env-runner 0.2.3 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +370 -20
  2. package/dist/_chunks/common-base-runner.d.mts +486 -15
  3. package/dist/_chunks/common-base-runner.mjs +712 -32
  4. package/dist/_chunks/common-process-data.mjs +13 -0
  5. package/dist/_chunks/common-worker-utils.mjs +47 -114
  6. package/dist/_chunks/deno-process-runner.d.mts +4 -1
  7. package/dist/_chunks/deno-process-runner.mjs +9 -6
  8. package/dist/_chunks/lexer.mjs +2 -0
  9. package/dist/_chunks/libs/cjs-module-lexer.mjs +6 -1
  10. package/dist/_chunks/miniflare-runner.d.mts +26 -14
  11. package/dist/_chunks/miniflare-runner.mjs +430 -134
  12. package/dist/_chunks/netlify-runner.d.mts +3 -1
  13. package/dist/_chunks/node-worker-runner.d.mts +3 -1
  14. package/dist/_chunks/node-worker-runner.mjs +8 -4
  15. package/dist/_chunks/plugin-hooks.mjs +1656 -0
  16. package/dist/_chunks/server.mjs +21 -5
  17. package/dist/_chunks/types.d.mts +37 -1
  18. package/dist/_chunks/vercel-runner.d.mts +3 -1
  19. package/dist/cli.mjs +0 -0
  20. package/dist/index.d.mts +21 -4
  21. package/dist/runners/bun-process/runner.d.mts +4 -1
  22. package/dist/runners/bun-process/runner.mjs +12 -9
  23. package/dist/runners/bun-process/worker.mjs +12 -11
  24. package/dist/runners/deno-process/worker.mjs +12 -11
  25. package/dist/runners/node-process/runner.d.mts +3 -1
  26. package/dist/runners/node-process/runner.mjs +2 -6
  27. package/dist/runners/node-process/worker.mjs +12 -11
  28. package/dist/runners/node-worker/worker.mjs +10 -10
  29. package/dist/runners/self/runner.d.mts +5 -2
  30. package/dist/runners/self/runner.mjs +12 -0
  31. package/package.json +26 -26
  32. package/dist/_chunks/common-host-env.mjs +0 -11
  33. package/dist/_chunks/virtual-loader.mjs +0 -71
@@ -1,25 +1,24 @@
1
- import { expandVirtualInvalidation, stripVirtualTypeScript, virtualModuleFormat } from "./virtual-loader.mjs";
1
+ import { encodeVirtualModules, expandVirtualInvalidation, jsonModuleCode, queryOf, restoreInternalQuery, stripInternalQuery, stripQuery, stripVirtualTypeScript, transformedFormat, unsupportedVirtualJSXError, virtualModuleCode, virtualModuleCodeSource, virtualModuleFormat } from "./plugin-hooks.mjs";
2
2
  import { BaseEnvRunner } from "./common-base-runner.mjs";
3
- import { isVirtualSpecifier } from "./common-worker-utils.mjs";
3
+ import { init, parse } from "./libs/es-module-lexer.mjs";
4
4
  import { resolveRuntimeDep } from "./common-runtime-deps.mjs";
5
- import { init, parse } from "./libs/cjs-module-lexer.mjs";
6
- import { init as init$1, parse as parse$1 } from "./libs/es-module-lexer.mjs";
5
+ import { init as init$1, parse as parse$1 } from "./libs/cjs-module-lexer.mjs";
7
6
  import { createRequire } from "node:module";
8
7
  import { proxyUpgrade } from "httpxy";
9
- import { fileURLToPath } from "node:url";
10
- import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
11
8
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
12
- import { resolveModulePath } from "exsolve";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
13
11
  import { tmpdir } from "node:os";
12
+ import { resolveModulePath } from "exsolve";
14
13
  import { parseEnv } from "node:util";
15
- const IPC_PATH = "/__env_runner_ipc";
14
+ const IPC_PATH$1 = "/__env_runner_ipc";
16
15
  const IPC_BINDING = "__ENV_RUNNER_IPC";
17
16
  const UNSAFE_EVAL_BINDING = "__ENV_RUNNER_UNSAFE_EVAL__";
18
17
  function generateWrapper(entryPath, opts) {
19
18
  const processShim = opts?.nodeCompat === false ? "" : `import __process from "node:process";
20
19
  if (!globalThis.process) { globalThis.process = __process; }`;
21
20
  const staticReExport = opts?.dynamicOnly ? "" : `export * from ${JSON.stringify(entryPath)};`;
22
- const explicitExports = opts?.dynamicOnly && opts.exports?.length ? opts.exports.map((name) => `export { ${name} } from ${JSON.stringify(entryPath)};`).join("\n") : "";
21
+ const explicitExports = typeof opts?.exports === "string" ? `export * from ${JSON.stringify(opts.exports)};` : opts?.dynamicOnly && opts.exports?.length ? opts.exports.map((name) => `export { ${name} } from ${JSON.stringify(entryPath)};`).join("\n") : "";
23
22
  const fetchBody = opts?.captureErrors ?? true ? `try {
24
23
  return await __server.fetch(request, env, ctx);
25
24
  } catch (e) {
@@ -38,7 +37,7 @@ if (!globalThis.process) { globalThis.process = __process; }`;
38
37
  ${staticReExport}
39
38
  ${explicitExports}
40
39
 
41
- const __IPC_PATH = "${IPC_PATH}";
40
+ const __IPC_PATH = "${IPC_PATH$1}";
42
41
  const __IPC_BINDING = "${IPC_BINDING}";
43
42
  const __UNSAFE_EVAL_BINDING = "${UNSAFE_EVAL_BINDING}";
44
43
  const __entryPath = ${JSON.stringify(entryPath)};
@@ -46,7 +45,10 @@ let __userEntry;
46
45
  let __server;
47
46
  let __ipcInitialized = false;
48
47
  let __serverWs;
49
- let __currentEnv;
48
+ // Raw env of the latest user request. Kept after the request ends: requests
49
+ // overlap and streamed bodies outlive fetch(), and unlike \`__serverWs\` the
50
+ // IPC binding works from any request context.
51
+ let __ipcEnv;
50
52
 
51
53
  const __userEnvs = new WeakMap();
52
54
 
@@ -132,9 +134,16 @@ async function __loadEntry(env, path) {
132
134
  return mod.default || mod;
133
135
  }
134
136
 
137
+ // Where an entry load error was thrown (first stack frame), so one thrown by a
138
+ // virtual module names its key (\`#config:2:7\`). workerd's messages don't.
139
+ function __errorLocation(e) {
140
+ const location = /\\n\\s+at (?:async )?(?:.* \\()?([^\\n()]+:\\d+:\\d+)\\)?/.exec(String(e?.stack))?.[1];
141
+ return location ? " (at " + location + ")" : "";
142
+ }
143
+
135
144
  function __sendMessage(message) {
136
145
  const payload = JSON.stringify(message);
137
- const env = __currentEnv;
146
+ const env = __ipcEnv;
138
147
  if (env && env[__IPC_BINDING]) {
139
148
  env[__IPC_BINDING].fetch("http://localhost/__ipc", {
140
149
  method: "POST",
@@ -161,7 +170,7 @@ async function __handleWsMessage(env, data) {
161
170
  if (msg.type === "reload" && env.__ENV_RUNNER_UNSAFE_EVAL__) {
162
171
  const version = msg.version || 0;
163
172
  try {
164
- const newEntry = await __loadEntry(env, __entryPath + "?t=" + version);
173
+ const newEntry = await __loadEntry(env, __entryPath + "?__envRunnerReload=" + version);
165
174
  const newServer = __createServer(newEntry);
166
175
  if (__userEntry?.ipc?.onClose) {
167
176
  await __userEntry.ipc.onClose();
@@ -206,8 +215,9 @@ export default {
206
215
  async fetch(request, env, ctx) {
207
216
  const url = new URL(request.url);
208
217
 
209
- // WebSocket IPC handshake
210
- if (url.pathname === __IPC_PATH && request.headers.get("upgrade") === "websocket") {
218
+ // IPC: a plain request loads the entry (204, or a 500 with the error), then
219
+ // the WebSocket upgrade opens the channel.
220
+ if (url.pathname === __IPC_PATH) {
211
221
  try {
212
222
  if (!__userEntry) {
213
223
  const entry = await __loadEntry(env, __entryPath);
@@ -215,7 +225,11 @@ export default {
215
225
  __userEntry = entry;
216
226
  }
217
227
  } catch (e) {
218
- return new Response("Failed to load entry: " + String(e), { status: 500 });
228
+ const message = "Failed to load entry: " + String(e) + __errorLocation(e);
229
+ return new Response(message, { status: 500 });
230
+ }
231
+ if (request.headers.get("upgrade") !== "websocket") {
232
+ return new Response(null, { status: 204 });
219
233
  }
220
234
 
221
235
  const pair = new WebSocketPair();
@@ -243,18 +257,15 @@ export default {
243
257
  return new Response("Worker not initialized", { status: 503 });
244
258
  }
245
259
 
260
+ __ipcEnv = env;
261
+
246
262
  // Handle WebSocket upgrade via crossws cloudflare adapter
247
263
  if (__userEntry.websocket && request.headers.get("upgrade") === "websocket") {
248
264
  const adapter = await __initCrossws(env, __userEntry.websocket);
249
265
  return adapter.handleUpgrade(request, __userEnv(env), ctx);
250
266
  }
251
267
 
252
- __currentEnv = env;
253
- try {
254
- ${fetchBody}
255
- } finally {
256
- __currentEnv = undefined;
257
- }
268
+ ${fetchBody}
258
269
  }
259
270
  };
260
271
  `;
@@ -895,6 +906,7 @@ function mapBindingArray(arr, keyField, value) {
895
906
  }
896
907
  return Object.keys(out).length > 0 ? out : void 0;
897
908
  }
909
+ const IPC_PATH = "/__env_runner_ipc";
898
910
  const _miniflareCache = /* @__PURE__ */ new Map();
899
911
  var MiniflareEnvRunner = class extends BaseEnvRunner {
900
912
  #miniflare;
@@ -902,7 +914,6 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
902
914
  #transformRequest;
903
915
  #reloadCounter = 0;
904
916
  #virtual;
905
- #virtualVersions = /* @__PURE__ */ new Map();
906
917
  #cacheEntry;
907
918
  #ws;
908
919
  #persistent;
@@ -959,8 +970,12 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
959
970
  for (let i = 0; i < 5 && !this._address && !this.closed; i++) await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i)));
960
971
  if (!this.#miniflare || this.closed) return new Response("miniflare env runner is unavailable", { status: 503 });
961
972
  const resolved = this._resolveFetchInput(input);
962
- const request = typeof resolved === "string" || resolved instanceof URL ? new Request(resolved, init) : new Request(new Request(resolved.url, resolved), {
973
+ const request = typeof resolved === "string" || resolved instanceof URL ? new Request(resolved, {
974
+ ...init,
975
+ redirect: "manual"
976
+ }) : new Request(new Request(resolved.url, resolved), {
963
977
  ...init,
978
+ redirect: "manual",
964
979
  referrer: init?.referrer ?? resolved.referrer,
965
980
  referrerPolicy: init?.referrerPolicy ?? resolved.referrerPolicy
966
981
  });
@@ -987,6 +1002,7 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
987
1002
  }));
988
1003
  }
989
1004
  async reloadModule(timeout = 5e3) {
1005
+ await this._virtualUpdates;
990
1006
  if (!this.#ws) throw new Error("Miniflare env runner should be initialized before reloading.");
991
1007
  if (!this._data?.entry) return;
992
1008
  this.#reloadCounter++;
@@ -1000,15 +1016,27 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1000
1016
  send: (message) => this.#ws.send(JSON.stringify(message))
1001
1017
  });
1002
1018
  }
1003
- async invalidateModule(specifier, _timeout) {
1019
+ async _applyVirtualUpdates(changes) {
1004
1020
  const virtual = this.#virtual;
1005
- if (!virtual || !Object.hasOwn(virtual, specifier)) {
1006
- const hasVirtual = Object.keys(this._data?.virtual ?? {}).length > 0;
1007
- throw !virtual && hasVirtual && !this.closed ? /* @__PURE__ */ new Error("Miniflare env runner should be initialized before invalidating modules.") : /* @__PURE__ */ new Error(`Cannot invalidate "${specifier}" (not a registered virtual module)`);
1021
+ if (!virtual) throw new Error("Miniflare env runner should be initialized before updating modules.");
1022
+ const prepared = {};
1023
+ for (const [key, module] of Object.entries(changes)) if (module !== null) prepared[key] = await this.#prepareVirtualModule(key, module);
1024
+ await init;
1025
+ const merged = {
1026
+ ...virtual.sources,
1027
+ ...prepared
1028
+ };
1029
+ const importers = virtualImporters(merged, createVirtualKeyResolver(Object.keys(merged)));
1030
+ const invalidated = expandVirtualInvalidation(merged, Object.keys(changes), importers);
1031
+ for (const key of Object.keys(changes)) if (Object.hasOwn(prepared, key)) {
1032
+ virtual.sources[key] = prepared[key];
1033
+ virtual.removed.delete(key);
1034
+ } else if (Object.hasOwn(virtual.sources, key)) {
1035
+ delete virtual.sources[key];
1036
+ virtual.removed.add(key);
1008
1037
  }
1009
- const source = await this._refreshVirtualSource(specifier);
1010
- if (source !== void 0) virtual[specifier] = await this.#prepareVirtualSource(specifier, source);
1011
- for (const key of expandVirtualInvalidation(virtual, specifier)) this.#virtualVersions.set(key, (this.#virtualVersions.get(key) ?? 0) + 1);
1038
+ for (const key of invalidated) virtual.versions.set(key, ++virtual.version);
1039
+ refreshVirtualKeyResolvers(virtual);
1012
1040
  if (this.#cacheKey && _miniflareCache.get(this.#cacheKey) === this.#cacheEntry) _miniflareCache.delete(this.#cacheKey);
1013
1041
  }
1014
1042
  _hasRuntime() {
@@ -1017,6 +1045,9 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1017
1045
  _runtimeType() {
1018
1046
  return "miniflare";
1019
1047
  }
1048
+ _resolveConditions() {
1049
+ return this.#exportConditions;
1050
+ }
1020
1051
  async _closeRuntime() {
1021
1052
  if (!this.#miniflare) return;
1022
1053
  if (this.#ws) {
@@ -1066,23 +1097,37 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1066
1097
  } catch {}
1067
1098
  }
1068
1099
  async #prepareVirtualModules() {
1069
- const virtual = this._data?.virtual;
1070
- if (!virtual || Object.keys(virtual).length === 0) return;
1100
+ const virtual = this._data?.virtual ?? {};
1071
1101
  const out = {};
1072
- for (const [specifier, source] of Object.entries(virtual)) out[specifier] = await this.#prepareVirtualSource(specifier, source);
1102
+ for (const [key, module] of Object.entries(virtual)) out[key] = await this.#prepareVirtualModule(key, module);
1073
1103
  return out;
1074
1104
  }
1075
- async #prepareVirtualSource(specifier, source) {
1076
- if (virtualModuleFormat(specifier) !== "module-typescript") return source;
1077
- return stripVirtualTypeScript(specifier, source, await _getStripTypeScriptTypes(), {
1078
- requirement: "on the host (workerd does not parse TypeScript)",
1079
- remedy: "upgrade Node.js"
1080
- });
1105
+ async #prepareVirtualModule(key, module) {
1106
+ const format = virtualModuleFormat(key, module);
1107
+ const source = typeof module === "string" ? module : module.source;
1108
+ switch (format) {
1109
+ case "module-typescript":
1110
+ case "commonjs-typescript": return {
1111
+ source: stripVirtualTypeScript(key, source, await _getStripTypeScriptTypes(), {
1112
+ requirement: "on the host (workerd does not parse TypeScript)",
1113
+ remedy: "upgrade Node.js"
1114
+ }),
1115
+ format: format === "module-typescript" ? "module" : "commonjs"
1116
+ };
1117
+ case "jsx":
1118
+ case "tsx": throw unsupportedVirtualJSXError(key, format, "workerd");
1119
+ }
1120
+ return {
1121
+ source,
1122
+ format
1123
+ };
1081
1124
  }
1082
1125
  async #initAsync() {
1083
- const { Miniflare, supportedCompatibilityDate } = await this.#resolveMiniflare();
1126
+ const miniflare = await this.#resolveMiniflare();
1127
+ const supportedCompatibilityDate = await resolveSupportedCompatibilityDate(miniflare);
1084
1128
  const entryPath = this._data?.entry;
1085
- const virtual = await this.#prepareVirtualModules();
1129
+ const initialVirtual = await this.#prepareVirtualModules();
1130
+ const virtual = createMiniflareVirtualModules({ ...initialVirtual });
1086
1131
  this.#virtual = virtual;
1087
1132
  const { options: wranglerOptions, configFile: wranglerConfigFile } = await loadWranglerConfig({
1088
1133
  wrangler: this.#wrangler,
@@ -1118,14 +1163,15 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1118
1163
  ...uValue
1119
1164
  };
1120
1165
  }
1166
+ const ipc = { runner: this };
1121
1167
  if (entryPath && !options.script && !options.scriptPath) {
1122
- const entryIsVirtual = isVirtualSpecifier(entryPath, virtual);
1123
- const resolvedEntry = entryIsVirtual ? entryPath : resolve(entryPath);
1168
+ const entryKey = virtual.keyOf(entryPath) ?? virtual.keyOf(resolve(entryPath));
1169
+ const entryIsVirtual = entryKey !== void 0;
1170
+ const resolvedEntry = entryIsVirtual ? virtualKeyPath(entryKey) ?? entryKey : resolve(entryPath);
1124
1171
  const entryBase = isAbsolute(resolvedEntry) ? resolvedEntry : resolve("__env_runner_virtual_entry__.mjs");
1125
1172
  const entryDir = dirname(entryBase);
1126
- const entrySource = entryIsVirtual ? virtual[entryPath] : _tryReadFile(resolvedEntry);
1127
- const detectedExports = this.#exports === false || this.#exports === void 0 ? [] : detectExportedClasses(entrySource, typeof this.#exports === "object" ? this.#exports : {});
1128
- if (entryIsVirtual && detectedExports.length > 0) throw new Error(`[env-runner] named exports (${detectedExports.join(", ")}) are not supported with a virtual entry on the miniflare runner; pass \`exports: false\` or use a real entry file.`);
1173
+ const entrySource = entryIsVirtual ? virtualModuleCodeSource(entryKey, virtual.sources[entryKey]) : _tryReadFile(resolvedEntry);
1174
+ const detectedExports = this.#exports === false || typeof this.#exports === "string" ? [] : detectExportedClasses(entrySource, typeof this.#exports === "object" ? this.#exports : {});
1129
1175
  if (detectedExports.length > 0) {
1130
1176
  const existingDOs = isPlainObject(options.durableObjects) ? options.durableObjects : {};
1131
1177
  const boundClasses = new Set(Object.values(existingDOs).map((b) => typeof b === "string" ? b : isPlainObject(b) && !b.scriptName ? b.className : void 0));
@@ -1136,13 +1182,23 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1136
1182
  }
1137
1183
  options.durableObjects = autoDOs;
1138
1184
  }
1139
- options.script = generateWrapper(resolvedEntry, {
1185
+ const script = generateWrapper(entryIsVirtual ? toWorkerdPath(resolvedEntry) : resolvedEntry, {
1140
1186
  dynamicOnly: true,
1141
1187
  captureErrors: this.#captureErrors,
1142
- exports: detectedExports,
1188
+ exports: typeof this.#exports === "string" ? this.#exports : detectedExports,
1143
1189
  nodeCompat: !options.compatibilityFlags.includes("no_nodejs_compat")
1144
1190
  });
1145
- options.scriptPath = entryDir + "/__env_runner_wrapper.mjs";
1191
+ const scriptPath = entryDir + "/__env_runner_wrapper.mjs";
1192
+ const skipLocator = typeof this.#exports === "string" || entryIsVirtual && detectedExports.length > 0;
1193
+ if (skipLocator) options.modules = [{
1194
+ type: "ESModule",
1195
+ path: scriptPath,
1196
+ contents: script
1197
+ }];
1198
+ else {
1199
+ options.script = script;
1200
+ options.scriptPath = scriptPath;
1201
+ }
1146
1202
  if (!options.modulesRoot) options.modulesRoot = "/";
1147
1203
  options.unsafeEvalBinding = UNSAFE_EVAL_BINDING;
1148
1204
  options.serviceBindings = {
@@ -1150,30 +1206,70 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1150
1206
  [IPC_BINDING]: async (request) => {
1151
1207
  try {
1152
1208
  const message = await request.json();
1153
- this._handleMessage(message);
1209
+ ipc.runner._handleMessage(message);
1154
1210
  } catch {}
1155
1211
  return new Response(null, { status: 204 });
1156
1212
  }
1157
1213
  };
1158
- if (this.#transformRequest && !options.modulesRules) options.modulesRules = [{
1214
+ if ((this.#transformRequest || this._plugins) && !options.modulesRules && !miniflare.convertV4MiniflareOptions && !skipLocator) options.modulesRules = [{
1159
1215
  type: "ESModule",
1160
1216
  include: [
1161
- "**/*.ts",
1162
- "**/*.tsx",
1163
- "**/*.jsx",
1164
- "**/*.mts"
1165
- ]
1217
+ ".ts",
1218
+ ".tsx",
1219
+ ".jsx",
1220
+ ".mts",
1221
+ ...this._plugins ? [".cts"] : []
1222
+ ].map((ext) => `**/*${ext}`)
1166
1223
  }];
1167
1224
  if (!options.unsafeModuleFallbackService) {
1168
1225
  const _require = createRequire(entryBase);
1169
1226
  const _virtual = virtual;
1170
- const _virtualVersions = this.#virtualVersions;
1171
1227
  const _transformRequest = this.#transformRequest;
1228
+ const _livePlugins = () => ipc.runner._plugins;
1229
+ const _cjsOutput = /* @__PURE__ */ new Map();
1172
1230
  const _exportConditions = this.#exportConditions;
1173
- const _applyVirtualVersions = (code) => applyVirtualVersions(code, _virtualVersions);
1231
+ const _applyVirtualVersions = (code, modulePath) => applyVirtualVersions(code, _virtual.versions, (specifier) => _virtual.versionedKeyOf(specifier, modulePath));
1232
+ const _serveVirtual = (module, modulePath) => {
1233
+ const { source } = module;
1234
+ switch (module.format) {
1235
+ case "module": return { esModule: _applyVirtualVersions(source, modulePath) };
1236
+ case "commonjs": return {
1237
+ commonJsModule: source,
1238
+ namedExports: commonJSExports(source).filter((e) => e !== "default")
1239
+ };
1240
+ case "json": return { json: source };
1241
+ case "text": return { text: source };
1242
+ case "bytes": return { esModule: virtualModuleCode("bytes", source) };
1243
+ case "wasm": return { wasm: Array.from(source) };
1244
+ }
1245
+ };
1246
+ const _pluginCode = async (id, result) => {
1247
+ if (result.moduleType !== "ts") return result.code;
1248
+ const strip = await _getStripTypeScriptTypes();
1249
+ if (typeof strip !== "function") throw new TypeError(`[env-runner] "${id}" is still TypeScript after its plugins, which needs \`module.stripTypeScriptTypes\` on the host: upgrade Node.js or compile it in a plugin.`);
1250
+ return strip(result.code);
1251
+ };
1252
+ const _servePluginModule = async (id, result) => {
1253
+ if (result.moduleType === "json") return { esModule: jsonModuleCode(id, result.code) };
1254
+ const code = await _pluginCode(id, result);
1255
+ if (transformedFormat(id, code) === "module") return { esModule: _applyVirtualVersions(code, void 0) };
1256
+ return {
1257
+ commonJsModule: code,
1258
+ namedExports: commonJSExports(code).filter((e) => e !== "default")
1259
+ };
1260
+ };
1261
+ const _pluginModuleIds = /* @__PURE__ */ new Map();
1262
+ const _pluginErrorModule = (name, error) => {
1263
+ const message = error?.message || String(error);
1264
+ console.error(message);
1265
+ return Response.json({
1266
+ name,
1267
+ esModule: `throw new Error(${JSON.stringify(message)});`
1268
+ });
1269
+ };
1174
1270
  options.unsafeUseModuleFallbackService = true;
1175
1271
  const modulePathMap = /* @__PURE__ */ new Map();
1176
- const _lexersReady = Promise.all([ensureCjsLexer(), init$1]);
1272
+ const _lexersReady = Promise.all([ensureCjsLexer(), init]);
1177
1273
  options.unsafeModuleFallbackService = async (request) => {
1178
1274
  await _lexersReady;
1179
1275
  const url = new URL(request.url);
@@ -1183,35 +1279,85 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1183
1279
  if (!specifier) return new Response(null, { status: 404 });
1184
1280
  const cleanSpecifier = specifier.split("?")[0] || specifier;
1185
1281
  const cleanRaw = rawSpecifier?.split("?")[0];
1186
- if (_virtual) {
1187
- const bareSpecifier = cleanSpecifier.startsWith("/") ? cleanSpecifier.slice(1) : cleanSpecifier;
1188
- const virtualKey = [
1189
- cleanRaw,
1190
- cleanSpecifier,
1191
- bareSpecifier
1192
- ].find((key) => key !== void 0 && Object.hasOwn(_virtual, key));
1193
- if (virtualKey !== void 0) {
1194
- const name = bareSpecifier + (specifier.includes("?") ? specifier.slice(specifier.indexOf("?")) : "");
1195
- const source = _virtual[virtualKey];
1196
- return virtualModuleFormat(virtualKey) === "json" ? Response.json({
1197
- name,
1198
- json: source
1199
- }) : Response.json({
1200
- name,
1201
- esModule: _applyVirtualVersions(source)
1282
+ const bareSpecifier = cleanSpecifier.startsWith("/") ? cleanSpecifier.slice(1) : cleanSpecifier;
1283
+ const referrerKey = referrer.startsWith("/") ? referrer.slice(1) : referrer;
1284
+ const referrerPath = modulePathMap.get(referrerKey);
1285
+ const virtualKey = [
1286
+ cleanRaw,
1287
+ cleanSpecifier,
1288
+ bareSpecifier
1289
+ ].find((key) => key !== void 0 && Object.hasOwn(_virtual.sources, key)) ?? (cleanRaw ? _virtual.keyOf(cleanRaw, referrerPath) : void 0) ?? _virtual.keyOf(cleanSpecifier);
1290
+ if (virtualKey !== void 0) {
1291
+ const query = specifier.includes("?") ? specifier.slice(specifier.indexOf("?")) : "";
1292
+ const keyPath = virtualKeyPath(virtualKey);
1293
+ if (keyPath && cleanRaw?.startsWith("file:") && cleanSpecifier !== keyPath && cleanSpecifier.includes("file:")) {
1294
+ const location = Buffer.from(toWorkerdPath(keyPath) + query, "utf8").toString("latin1");
1295
+ return new Response(null, {
1296
+ status: 301,
1297
+ headers: { location }
1202
1298
  });
1203
1299
  }
1300
+ const name = bareSpecifier + query;
1301
+ if (keyPath) modulePathMap.set(name, keyPath);
1302
+ return Response.json({
1303
+ name,
1304
+ ..._serveVirtual(_virtual.sources[virtualKey], keyPath)
1305
+ });
1204
1306
  }
1307
+ const rawQuery = specifier.includes("?") ? specifier.slice(specifier.indexOf("?")) : "";
1308
+ const name = (cleanSpecifier.startsWith("/") ? cleanSpecifier.slice(1) : cleanSpecifier) + rawQuery;
1309
+ const versionedKey = _virtual.versionedKeyOf(cleanRaw || cleanSpecifier, referrerPath);
1310
+ const version = versionedKey === void 0 ? void 0 : _virtual.versions.get(versionedKey);
1311
+ const query = queryOf(stripInternalQuery(specifier, version));
1205
1312
  let resolvedPath;
1313
+ let resolvedId;
1314
+ let pluginResolved = false;
1315
+ const _resolvePlugins = _livePlugins();
1316
+ const rawSource = rawSpecifier ? stripInternalQuery(rawSpecifier, version) : bareSpecifier + query;
1317
+ const _pluginResolve = async (fallback) => {
1318
+ if (!_resolvePlugins) return;
1319
+ try {
1320
+ const source = rawSource.startsWith("file:") ? fileURLToPath(stripQuery(rawSource)) + queryOf(rawSource) : rawSource;
1321
+ if (!_resolvePlugins.resolveFilter(source, fallback)) return;
1322
+ const resolved = await _resolvePlugins.resolveId(source, _pluginModuleIds.get(referrerKey) ?? referrerPath, { fallback });
1323
+ if (!resolved || resolved.external) return;
1324
+ const id = resolved.id;
1325
+ const idPath = stripQuery(id);
1326
+ const pathKey = isAbsolute(idPath) ? _virtual.keyOf(idPath) : void 0;
1327
+ const keyPath = pathKey === void 0 ? void 0 : virtualKeyPath(pathKey);
1328
+ if (keyPath) {
1329
+ const location = restoreInternalQuery(toWorkerdPath(keyPath) + queryOf(id), specifier);
1330
+ return new Response(null, {
1331
+ status: 301,
1332
+ headers: { location: Buffer.from(location, "utf8").toString("latin1") }
1333
+ });
1334
+ }
1335
+ if (isAbsolute(idPath)) {
1336
+ resolvedId = id;
1337
+ pluginResolved = true;
1338
+ return idPath;
1339
+ }
1340
+ const result = await _resolvePlugins.load(id);
1341
+ _pluginModuleIds.set(name, id);
1342
+ return Response.json({
1343
+ name,
1344
+ ...await _servePluginModule(id, result)
1345
+ });
1346
+ } catch (error) {
1347
+ return _pluginErrorModule(name, error);
1348
+ }
1349
+ };
1350
+ const pluginPath = await _pluginResolve(false);
1351
+ if (pluginPath instanceof Response) return pluginPath;
1352
+ resolvedPath = pluginPath;
1206
1353
  const fileUrlRaw = cleanRaw || cleanSpecifier;
1207
- if (fileUrlRaw.startsWith("file://")) try {
1354
+ if (resolvedPath !== void 0) {} else if (fileUrlRaw.startsWith("file://")) try {
1208
1355
  resolvedPath = fileURLToPath(fileUrlRaw);
1209
1356
  } catch {
1210
1357
  return new Response(null, { status: 404 });
1211
1358
  }
1212
- else if (cleanRaw && !cleanRaw.startsWith(".") && !cleanRaw.startsWith("/")) {
1213
- const referrerKey = referrer.startsWith("/") ? referrer.slice(1) : referrer;
1214
- const referrerReal = modulePathMap.get(referrerKey);
1359
+ else if (cleanRaw && !cleanRaw.startsWith(".") && !cleanRaw.startsWith("/") && !isAbsolute(cleanRaw)) {
1360
+ const referrerReal = referrerPath;
1215
1361
  const contextRequire = referrerReal ? createRequire(referrerReal) : _require;
1216
1362
  if (cleanRaw.startsWith("cloudflare:")) return new Response(null, { status: 404 });
1217
1363
  if (cleanRaw.startsWith("node:")) {
@@ -1228,57 +1374,107 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1228
1374
  try: true
1229
1375
  }) || contextRequire.resolve(cleanRaw);
1230
1376
  } catch {
1231
- const name = cleanSpecifier.startsWith("/") ? cleanSpecifier.slice(1) : cleanSpecifier;
1232
- return Response.json({
1233
- name,
1234
- esModule: "export default undefined;"
1235
- });
1377
+ const failed = await _pluginResolve(true);
1378
+ if (failed instanceof Response) return failed;
1379
+ if (failed === void 0) {
1380
+ const name = cleanSpecifier.startsWith("/") ? cleanSpecifier.slice(1) : cleanSpecifier;
1381
+ return Response.json({
1382
+ name,
1383
+ esModule: "export default undefined;"
1384
+ });
1385
+ }
1386
+ resolvedPath = failed;
1236
1387
  }
1237
1388
  } else {
1238
- const referrerKey = referrer.startsWith("/") ? referrer.slice(1) : referrer;
1239
- const referrerReal = modulePathMap.get(referrerKey) || (referrer.startsWith("/") ? referrer : "/" + referrer);
1389
+ const referrerReal = referrerPath || (referrer.startsWith("/") ? referrer : "/" + referrer);
1240
1390
  const referrerDir = dirname(referrerReal);
1241
1391
  const raw = cleanRaw || cleanSpecifier;
1242
1392
  if (raw.startsWith(".")) resolvedPath = resolve(referrerDir, raw);
1393
+ else if (cleanRaw && isAbsolute(cleanRaw) && !cleanRaw.startsWith("/")) resolvedPath = cleanRaw;
1243
1394
  else if (cleanSpecifier.startsWith("/")) resolvedPath = cleanSpecifier;
1244
1395
  else try {
1245
1396
  resolvedPath = _require.resolve(raw);
1246
1397
  } catch {
1247
- return new Response(null, { status: 404 });
1398
+ const failed = await _pluginResolve(true);
1399
+ if (failed === void 0) return new Response(null, { status: 404 });
1400
+ if (failed instanceof Response) return failed;
1401
+ resolvedPath = failed;
1248
1402
  }
1249
1403
  }
1250
- const rawQuery = specifier.includes("?") ? specifier.slice(specifier.indexOf("?")) : "";
1251
- const name = (cleanSpecifier.startsWith("/") ? cleanSpecifier.slice(1) : cleanSpecifier) + rawQuery;
1404
+ if (!pluginResolved && _resolvePlugins && !existsSync(resolvedPath)) {
1405
+ const failed = await _pluginResolve(true);
1406
+ if (failed instanceof Response) return failed;
1407
+ resolvedPath = failed ?? resolvedPath;
1408
+ }
1252
1409
  if (_transformRequest) try {
1253
1410
  const result = await _transformRequest(resolvedPath);
1254
1411
  if (result?.code) {
1255
1412
  modulePathMap.set(name, resolvedPath);
1256
1413
  return Response.json({
1257
1414
  name,
1258
- esModule: _applyVirtualVersions(result.code)
1415
+ esModule: _applyVirtualVersions(result.code, resolvedPath)
1259
1416
  });
1260
1417
  }
1261
1418
  } catch {}
1419
+ let contents;
1262
1420
  try {
1263
- const contents = readFileSync(resolvedPath, "utf8");
1264
- modulePathMap.set(name, resolvedPath);
1265
- if (resolvedPath.endsWith(".mjs") || !resolvedPath.endsWith(".cjs") && /\b(import\s|import\(|export\s|export\{|import\.meta\b)/.test(contents)) return Response.json({
1266
- name,
1267
- esModule: _applyVirtualVersions(contents)
1268
- });
1269
- const cjsSuffix = "?__cjs";
1270
- if (specifier.endsWith(cjsSuffix)) return Response.json({
1271
- name,
1272
- commonJsModule: contents
1273
- });
1274
- const esModule = createCjsEsmShim("./" + basename(resolvedPath) + cjsSuffix, contents);
1275
- return Response.json({
1276
- name,
1277
- esModule
1278
- });
1279
- } catch {
1280
- return new Response(null, { status: 404 });
1421
+ contents = readFileSync(resolvedPath, "utf8");
1422
+ } catch {}
1423
+ const _plugins = _livePlugins();
1424
+ const cjsRequest = /[?&]__cjs$/.test(specifier);
1425
+ const id = resolvedId ?? resolvedPath + query;
1426
+ const cachedCJS = cjsRequest && _cjsOutput.has(id);
1427
+ const pluginFile = !cachedCJS && _plugins?.filter(id, void 0, pluginResolved);
1428
+ if (contents === void 0 && !cachedCJS && !pluginFile) return new Response(null, { status: 404 });
1429
+ modulePathMap.set(name, resolvedPath);
1430
+ if (id !== resolvedPath) _pluginModuleIds.set(name, id);
1431
+ let transformed;
1432
+ if (cachedCJS) {
1433
+ transformed = _cjsOutput.get(id);
1434
+ _cjsOutput.delete(id);
1435
+ } else if (pluginFile) {
1436
+ try {
1437
+ const file = resolvedPath;
1438
+ const result = await _plugins.load(id, () => {
1439
+ if (contents === void 0) throw new Error(`Cannot find module "${file}"`);
1440
+ return contents;
1441
+ }, { resolved: pluginResolved });
1442
+ if (result?.moduleType === "json") return Response.json({
1443
+ name,
1444
+ esModule: jsonModuleCode(file, result.code)
1445
+ });
1446
+ transformed = result && await _pluginCode(id, result);
1447
+ } catch (error) {
1448
+ return _pluginErrorModule(name, error);
1449
+ }
1450
+ if (transformed === void 0 && contents === void 0) return new Response(null, { status: 404 });
1281
1451
  }
1452
+ if (transformed === void 0 && resolvedPath.endsWith(".wasm")) return Response.json({
1453
+ name,
1454
+ wasm: Array.from(readFileSync(resolvedPath))
1455
+ });
1456
+ let isESM;
1457
+ if (transformed === void 0) {
1458
+ contents = contents;
1459
+ isESM = resolvedPath.endsWith(".mjs") || !resolvedPath.endsWith(".cjs") && /\b(import\s|import\(|export\s|export\{|import\.meta\b)/.test(contents);
1460
+ } else {
1461
+ contents = transformed;
1462
+ isESM = transformedFormat(resolvedPath, contents) === "module";
1463
+ }
1464
+ if (isESM) return Response.json({
1465
+ name,
1466
+ esModule: _applyVirtualVersions(contents, resolvedPath)
1467
+ });
1468
+ if (cjsRequest) return Response.json({
1469
+ name,
1470
+ commonJsModule: contents
1471
+ });
1472
+ if (transformed !== void 0) _cjsOutput.set(id, transformed);
1473
+ const esModule = createCjsEsmShim("./" + basename(resolvedPath) + (query ? `${query}&` : "?") + "__cjs", contents);
1474
+ return Response.json({
1475
+ name,
1476
+ esModule
1477
+ });
1282
1478
  };
1283
1479
  }
1284
1480
  }
@@ -1286,31 +1482,36 @@ var MiniflareEnvRunner = class extends BaseEnvRunner {
1286
1482
  this.#cacheKey = computeCacheKey(entryPath, {
1287
1483
  ...this.#miniflareOptions,
1288
1484
  _exportConditions: this.#exportConditions,
1289
- _virtual: virtual
1485
+ _exports: this.#exports,
1486
+ _plugins: Boolean(this._plugins),
1487
+ _virtual: encodeVirtualModules(initialVirtual)
1290
1488
  });
1291
1489
  const cached = _miniflareCache.get(this.#cacheKey);
1292
1490
  if (cached) {
1293
1491
  this.#miniflare = cached.mf;
1294
1492
  cached.refCount++;
1295
1493
  this.#cacheEntry = cached;
1494
+ cached.ipc.runner = this;
1296
1495
  this.#virtual = cached.virtual;
1297
- this.#virtualVersions = cached.versions;
1298
1496
  }
1299
1497
  }
1300
1498
  if (!this.#miniflare) {
1301
- this.#miniflare = new Miniflare(options);
1499
+ this.#miniflare = new miniflare.Miniflare(toMiniflareOptions(miniflare, options));
1302
1500
  await this.#miniflare.ready;
1303
1501
  if (this.#persistent && this.#cacheKey) {
1304
1502
  this.#cacheEntry = {
1305
1503
  mf: this.#miniflare,
1306
1504
  refCount: 1,
1307
1505
  virtual,
1308
- versions: this.#virtualVersions
1506
+ ipc
1309
1507
  };
1310
1508
  _miniflareCache.set(this.#cacheKey, this.#cacheEntry);
1311
1509
  }
1312
1510
  }
1313
- const initRes = await this.#miniflare.dispatchFetch("http://localhost/__env_runner_ipc", { headers: { upgrade: "websocket" } });
1511
+ const loadRes = await this.#miniflare.dispatchFetch("http://localhost" + IPC_PATH);
1512
+ const loadBody = await loadRes.text().catch(() => "");
1513
+ if (!loadRes.ok) throw new Error(`Failed to establish WebSocket IPC channel (${loadRes.status}: ${loadBody})`);
1514
+ const initRes = await this.#miniflare.dispatchFetch("http://localhost" + IPC_PATH, { headers: { upgrade: "websocket" } });
1314
1515
  const ws = initRes.webSocket;
1315
1516
  if (!ws) {
1316
1517
  const body = await initRes.text().catch(() => "");
@@ -1339,6 +1540,31 @@ function detectExportedClasses(entrySource, explicit) {
1339
1540
  }
1340
1541
  return [...names];
1341
1542
  }
1543
+ function toMiniflareOptions(miniflare, options) {
1544
+ if (!miniflare.convertV4MiniflareOptions) return options;
1545
+ const { defaultPersistRoot, ...rest } = options;
1546
+ return miniflare.convertV4MiniflareOptions({
1547
+ resourcePersistencePath: defaultPersistRoot,
1548
+ ...rest
1549
+ });
1550
+ }
1551
+ async function resolveSupportedCompatibilityDate(miniflare) {
1552
+ if (typeof miniflare.supportedCompatibilityDate === "string") return miniflare.supportedCompatibilityDate;
1553
+ try {
1554
+ const from = [process.cwd() + "/", import.meta.url];
1555
+ const miniflarePath = resolveModulePath("miniflare", {
1556
+ from,
1557
+ try: true
1558
+ });
1559
+ const workerdPath = resolveModulePath("workerd", { from: miniflarePath || from });
1560
+ const { compatibilityDate } = await import(pathToFileURL(workerdPath).href);
1561
+ if (!_isDateString(compatibilityDate)) return;
1562
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1563
+ return compatibilityDate > today ? today : compatibilityDate;
1564
+ } catch {
1565
+ return;
1566
+ }
1567
+ }
1342
1568
  function resolveCompatibilityDate(candidates, supported) {
1343
1569
  const date = candidates.find((d) => typeof d === "string" && d) ?? supported;
1344
1570
  if (date && supported && _isDateString(date) && _isDateString(supported) && date > supported) {
@@ -1357,7 +1583,7 @@ function _isDateString(value) {
1357
1583
  return /^\d{4}-\d{2}-\d{2}$/.test(value);
1358
1584
  }
1359
1585
  function hasUserPersistOptions(options) {
1360
- return Object.keys(options).some((key) => key === "defaultPersistRoot" || key.endsWith("Persist"));
1586
+ return Object.keys(options).some((key) => key === "defaultPersistRoot" || key === "resourcePersistencePath" || key.endsWith("Persist"));
1361
1587
  }
1362
1588
  function wranglerPersistRoot(configFile, explicitPath) {
1363
1589
  const file = configFile ?? (explicitPath ? resolve(explicitPath) : void 0);
@@ -1378,26 +1604,93 @@ function computeCacheKey(entryPath, opts) {
1378
1604
  for (const [k, v] of Object.entries(opts)) if (typeof v !== "function") serializableOpts[k] = v;
1379
1605
  return `${resolve(entryPath)}::${JSON.stringify(serializableOpts)}`;
1380
1606
  }
1381
- function applyVirtualVersions(code, versions) {
1382
- if (versions.size === 0) return code;
1607
+ const _isWin = process.platform === "win32";
1608
+ function virtualKeyPath(key) {
1609
+ if (_isWin && /^\/[A-Za-z]:\//.test(key)) key = key.slice(1);
1610
+ if (key.startsWith("file:")) try {
1611
+ return fileURLToPath(key);
1612
+ } catch {
1613
+ return;
1614
+ }
1615
+ return isAbsolute(key) ? resolve(key) : void 0;
1616
+ }
1617
+ function toWorkerdPath(path) {
1618
+ return _isWin && /^[A-Za-z]:[\\/]/.test(path) ? "/" + path.replaceAll("\\", "/") : path;
1619
+ }
1620
+ function createMiniflareVirtualModules(sources) {
1621
+ return refreshVirtualKeyResolvers({
1622
+ sources,
1623
+ removed: /* @__PURE__ */ new Set(),
1624
+ versions: /* @__PURE__ */ new Map(),
1625
+ version: 0
1626
+ });
1627
+ }
1628
+ function refreshVirtualKeyResolvers(virtual) {
1629
+ const keys = Object.keys(virtual.sources);
1630
+ virtual.keyOf = createVirtualKeyResolver(keys);
1631
+ virtual.versionedKeyOf = virtual.removed.size > 0 ? createVirtualKeyResolver([...keys, ...virtual.removed]) : virtual.keyOf;
1632
+ return virtual;
1633
+ }
1634
+ function createVirtualKeyResolver(keys) {
1635
+ const verbatim = new Set(keys);
1636
+ const pathKeys = /* @__PURE__ */ new Map();
1637
+ for (const key of verbatim) {
1638
+ const path = virtualKeyPath(key);
1639
+ if (path !== void 0) pathKeys.set(path, key);
1640
+ }
1641
+ return (specifier, importerPath) => {
1642
+ const clean = specifier.split("?")[0];
1643
+ if (verbatim.has(clean)) return clean;
1644
+ if (pathKeys.size === 0) return;
1645
+ const path = /^\.\.?\//.test(clean) ? importerPath && resolve(dirname(importerPath), clean) : virtualKeyPath(clean);
1646
+ return path ? pathKeys.get(path) : void 0;
1647
+ };
1648
+ }
1649
+ function virtualImporters(virtual, keyOf) {
1650
+ const importers = /* @__PURE__ */ new Map();
1651
+ for (const [importer, { source, format }] of Object.entries(virtual)) {
1652
+ if (format !== "module") continue;
1653
+ const importerPath = virtualKeyPath(importer);
1654
+ for (const { specifier } of versionableImports(source) ?? []) {
1655
+ const key = keyOf(specifier, importerPath);
1656
+ if (key !== void 0 && key !== importer) {
1657
+ let set = importers.get(key);
1658
+ if (!set) importers.set(key, set = /* @__PURE__ */ new Set());
1659
+ set.add(importer);
1660
+ }
1661
+ }
1662
+ }
1663
+ return importers;
1664
+ }
1665
+ function versionableImports(code) {
1383
1666
  let imports;
1384
1667
  try {
1385
- [imports] = parse$1(code);
1668
+ [imports] = parse(code);
1386
1669
  } catch {
1387
- return code;
1670
+ return;
1388
1671
  }
1672
+ const result = [];
1673
+ for (const imp of imports) {
1674
+ if (typeof imp.specifier !== "string" || imp.type === "dynamic" && imp.glob) continue;
1675
+ result.push({
1676
+ specifier: imp.specifier,
1677
+ end: imp.type === "dynamic" ? imp.end - 1 : imp.end
1678
+ });
1679
+ }
1680
+ return result;
1681
+ }
1682
+ function applyVirtualVersions(code, versions, keyOf) {
1683
+ if (versions.size === 0) return code;
1684
+ const imports = versionableImports(code);
1685
+ if (!imports) return code;
1389
1686
  let out = "";
1390
1687
  let last = 0;
1391
- for (const imp of imports) {
1392
- if (imp.type === "import-meta") continue;
1393
- const dynamic = imp.type === "dynamic";
1394
- if (dynamic && imp.glob) continue;
1395
- const specifier = imp.specifier;
1396
- const version = specifier === void 0 ? void 0 : versions.get(specifier);
1688
+ for (const { specifier, end } of imports) {
1689
+ const key = keyOf(specifier);
1690
+ const version = key === void 0 ? void 0 : versions.get(key);
1397
1691
  if (!version) continue;
1398
- const versioned = `${specifier}?v=${version}`;
1399
- out += code.slice(last, imp.start) + (dynamic ? JSON.stringify(versioned) : versioned);
1400
- last = imp.end;
1692
+ out += code.slice(last, end) + (specifier.includes("?") ? "&" : "?") + `v=${version}`;
1693
+ last = end;
1401
1694
  }
1402
1695
  return out + code.slice(last);
1403
1696
  }
@@ -1408,15 +1701,18 @@ function _getStripTypeScriptTypes() {
1408
1701
  }
1409
1702
  let _cjsLexerReady;
1410
1703
  function ensureCjsLexer() {
1411
- if (!_cjsLexerReady) _cjsLexerReady = init();
1704
+ if (!_cjsLexerReady) _cjsLexerReady = init$1();
1412
1705
  return _cjsLexerReady;
1413
1706
  }
1414
- function createCjsEsmShim(cjsSpecifier, contents) {
1415
- let namedExports = [];
1707
+ function commonJSExports(contents) {
1416
1708
  try {
1417
- const { exports } = parse(contents);
1418
- namedExports = exports.filter((e) => e !== "default" && e !== "__esModule");
1419
- } catch {}
1709
+ return parse$1(contents).exports;
1710
+ } catch {
1711
+ return [];
1712
+ }
1713
+ }
1714
+ function createCjsEsmShim(cjsSpecifier, contents) {
1715
+ const namedExports = commonJSExports(contents).filter((e) => e !== "default" && e !== "__esModule");
1420
1716
  let shim = `import __cjs_mod__ from ${JSON.stringify(cjsSpecifier)};\nexport default __cjs_mod__;\n`;
1421
1717
  for (const name of namedExports) shim += `export var ${name} = __cjs_mod__["${name}"];\n`;
1422
1718
  return shim;