Skip to content

Commit

Permalink
fix: only apply some polyfills below node 18.11 (#10920)
Browse files Browse the repository at this point in the history
* fix: only apply some polyfills below node 18.11

related to #10918

* Update packages/kit/src/exports/node/polyfills.js

Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>

* be more defensive

* be more defensive

---------

Co-authored-by: Rich Harris <richard.a.harris@gmail.com>
Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>
  • Loading branch information
3 people authored Oct 25, 2023
1 parent 000c193 commit 060f47e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/mean-cheetahs-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: only apply some polyfills below node 18.11
28 changes: 22 additions & 6 deletions packages/kit/src/exports/node/polyfills.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,17 @@ import buffer from 'node:buffer';
import { webcrypto as crypto } from 'node:crypto';
import { fetch, Response, Request, Headers, FormData, File as UndiciFile } from 'undici';

/** @type {Record<string, any>} */
const globals_post_node_18_11 = {
crypto
};

// @ts-expect-error
const File = buffer.File ?? UndiciFile;

/** @type {Record<string, any>} */
const globals = {
// TODO: remove this once we only support Node 18.11+ (the version multipart/form-data was added)
const globals_pre_node_18_11 = {
crypto,
fetch,
Response,
Expand All @@ -21,16 +27,26 @@ const globals = {
};

// exported for dev/preview and node environments
// TODO: remove this once we only support Node 18.11+ (the version multipart/form-data was added)
/**
* Make various web APIs available as globals:
* - `crypto`
* - `fetch`
* - `Headers`
* - `Request`
* - `Response`
* - `fetch` (only in node < 18.11)
* - `Headers` (only in node < 18.11)
* - `Request` (only in node < 18.11)
* - `Response` (only in node < 18.11)
*/
export function installPolyfills() {
// Be defensive (we don't know in which environments this is called) and always apply if something goes wrong
let globals = globals_pre_node_18_11;
try {
const version = process.versions.node.split('.').map((n) => parseInt(n, 10));
if ((version[0] === 18 && version[1] >= 11) || version[0] > 18) {
globals = globals_post_node_18_11;
}
} catch (e) {
// ignore
}

for (const name in globals) {
Object.defineProperty(globalThis, name, {
enumerable: true,
Expand Down

0 comments on commit 060f47e

Please sign in to comment.