-
Notifications
You must be signed in to change notification settings - Fork 776
/
Copy pathhybrid-nodejs-compat.ts
250 lines (232 loc) · 7.46 KB
/
hybrid-nodejs-compat.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { builtinModules } from "node:module";
import nodePath from "node:path";
import dedent from "ts-dedent";
import { cloudflare, env, nodeless } from "unenv";
import { getBasePath } from "../../paths";
import type { Plugin, PluginBuild } from "esbuild";
const REQUIRED_NODE_BUILT_IN_NAMESPACE = "node-built-in-modules";
const REQUIRED_UNENV_ALIAS_NAMESPACE = "required-unenv-alias";
export const nodejsHybridPlugin: () => Plugin = () => {
const { alias, inject, external } = env(nodeless, cloudflare);
return {
name: "hybrid-nodejs_compat",
setup(build) {
errorOnServiceWorkerFormat(build);
handleRequireCallsToNodeJSBuiltins(build);
handleUnenvAliasedPackages(build, alias, external);
handleNodeJSGlobals(build, inject);
},
};
};
const NODEJS_MODULES_RE = new RegExp(`^(node:)?(${builtinModules.join("|")})$`);
/**
* If we are bundling a "Service Worker" formatted Worker, imports of external modules,
* which won't be inlined/bundled by esbuild, are invalid.
*
* This `onResolve()` handler will error if it identifies node.js external imports.
*/
function errorOnServiceWorkerFormat(build: PluginBuild) {
const paths = new Set();
build.onStart(() => paths.clear());
build.onResolve({ filter: NODEJS_MODULES_RE }, (args) => {
paths.add(args.path);
return null;
});
build.onEnd(() => {
if (build.initialOptions.format === "iife" && paths.size > 0) {
const pathList = new Intl.ListFormat("en-US").format(
Array.from(paths.keys())
.map((p) => `"${p}"`)
.sort()
);
return {
errors: [
{
text: dedent`
Unexpected external import of ${pathList}.
Your worker has no default export, which means it is assumed to be a Service Worker format Worker.
Did you mean to create a ES Module format Worker?
If so, try adding \`export default { ... }\` in your entry-point.
See https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/.
`,
},
],
};
}
});
}
/**
* We must convert `require()` calls for Node.js modules to a virtual ES Module that can be imported avoiding the require calls.
* We do this by creating a special virtual ES module that re-exports the library in an onLoad handler.
* The onLoad handler is triggered by matching the "namespace" added to the resolve.
*/
function handleRequireCallsToNodeJSBuiltins(build: PluginBuild) {
build.onResolve({ filter: NODEJS_MODULES_RE }, (args) => {
if (args.kind === "require-call") {
return {
path: args.path,
namespace: REQUIRED_NODE_BUILT_IN_NAMESPACE,
};
}
});
build.onLoad(
{ filter: /.*/, namespace: REQUIRED_NODE_BUILT_IN_NAMESPACE },
({ path }) => {
return {
contents: dedent`
import libDefault from '${path}';
module.exports = libDefault;`,
loader: "js",
};
}
);
}
function handleUnenvAliasedPackages(
build: PluginBuild,
alias: Record<string, string>,
external: string[]
) {
// esbuild expects alias paths to be absolute
const aliasAbsolute: Record<string, string> = {};
for (const [module, unresolvedAlias] of Object.entries(alias)) {
try {
aliasAbsolute[module] = require
.resolve(unresolvedAlias)
.replace(/\.cjs$/, ".mjs");
} catch (e) {
// this is an alias for package that is not installed in the current app => ignore
}
}
const UNENV_ALIAS_RE = new RegExp(
`^(${Object.keys(aliasAbsolute).join("|")})$`
);
build.onResolve({ filter: UNENV_ALIAS_RE }, (args) => {
const unresolvedAlias = alias[args.path];
// Convert `require()` calls for NPM packages to a virtual ES Module that can be imported avoiding the require calls.
// Note: Does not apply to Node.js packages that are handled in `handleRequireCallsToNodeJSBuiltins`
if (
args.kind === "require-call" &&
(unresolvedAlias.startsWith("unenv/runtime/npm/") ||
unresolvedAlias.startsWith("unenv/runtime/mock/"))
) {
return {
path: args.path,
namespace: REQUIRED_UNENV_ALIAS_NAMESPACE,
};
}
// Resolve the alias to its absolute path and potentially mark it as external
return {
path: aliasAbsolute[args.path],
external: external.includes(unresolvedAlias),
};
});
build.initialOptions.banner = { js: "", ...build.initialOptions.banner };
build.initialOptions.banner.js += dedent`
function __cf_cjs(esm) {
const cjs = 'default' in esm ? esm.default : {};
for (const [k, v] of Object.entries(esm)) {
if (k !== 'default') {
Object.defineProperty(cjs, k, {
enumerable: true,
value: v,
});
}
}
return cjs;
}
`;
build.onLoad(
{ filter: /.*/, namespace: REQUIRED_UNENV_ALIAS_NAMESPACE },
({ path }) => {
return {
contents: dedent`
import * as esm from '${path}';
module.exports = __cf_cjs(esm);
`,
loader: "js",
};
}
);
}
/**
* Inject node globals defined in unenv's `inject` config via virtual modules
*/
function handleNodeJSGlobals(
build: PluginBuild,
inject: Record<string, string | string[]>
) {
const UNENV_GLOBALS_RE = /_virtual_unenv_global_polyfill-([^.]+)\.js$/;
const prefix = nodePath.resolve(
getBasePath(),
"_virtual_unenv_global_polyfill-"
);
build.initialOptions.inject = [
...(build.initialOptions.inject ?? []),
//convert unenv's inject keys to absolute specifiers of custom virtual modules that will be provided via a custom onLoad
...Object.keys(inject).map(
(globalName) => `${prefix}${encodeToLowerCase(globalName)}.js`
),
];
build.onResolve({ filter: UNENV_GLOBALS_RE }, ({ path }) => ({ path }));
build.onLoad({ filter: UNENV_GLOBALS_RE }, ({ path }) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const globalName = decodeFromLowerCase(path.match(UNENV_GLOBALS_RE)![1]);
const { importStatement, exportName } = getGlobalInject(inject[globalName]);
return {
contents: `${importStatement}\nglobalThis.${globalName} = ${exportName};`,
};
});
}
/**
* Get the import statement and export name to be used for the given global inject setting.
*/
function getGlobalInject(globalInject: string | string[]) {
if (typeof globalInject === "string") {
// the mapping is a simple string, indicating a default export, so the string is just the module specifier.
return {
importStatement: `import globalVar from "${globalInject}";`,
exportName: "globalVar",
};
}
// the mapping is a 2 item tuple, indicating a named export, made up of a module specifier and an export name.
const [moduleSpecifier, exportName] = globalInject;
return {
importStatement: `import { ${exportName} } from "${moduleSpecifier}";`,
exportName,
};
}
/**
* Encodes a case sensitive string to lowercase string by prefixing all uppercase letters
* with $ and turning them into lowercase letters.
*
* This function exists because ESBuild requires that all resolved paths are case insensitive.
* Without this transformation, ESBuild will clobber /foo/bar.js with /foo/Bar.js
*
* This is important to support `inject` config for `performance` and `Performance` introduced
* in https://github.com/unjs/unenv/pull/257
*/
export function encodeToLowerCase(str: string): string {
return str
.replaceAll(/\$/g, () => "$$")
.replaceAll(/[A-Z]/g, (letter) => `$${letter.toLowerCase()}`);
}
/**
* Decodes a string lowercased using `encodeToLowerCase` to the original strings
*/
export function decodeFromLowerCase(str: string): string {
let out = "";
let i = 0;
while (i < str.length - 1) {
if (str[i] === "$") {
i++;
out += str[i].toUpperCase();
} else {
out += str[i];
}
i++;
}
if (i < str.length) {
out += str[i];
}
return out;
}