@cloudflare/worker-bundler 0.1.1 → 0.1.2

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.
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
- import { n as hasDependencies, r as installDependencies } from "./installer-CwkPhXvX.js";
1
+ import { n as hasDependencies, r as installDependencies } from "./installer-DM2snqBY.js";
2
2
  import * as esbuild from "esbuild-wasm/lib/browser.js";
3
- import esbuildWasm from "./esbuild.wasm";
4
3
  import { parse } from "es-module-lexer/js";
5
4
  import * as resolveExports from "resolve.exports";
6
5
  import { parse as parse$1 } from "smol-toml";
@@ -61,8 +60,9 @@ function resolvePackage(specifier, files, conditions, extensions) {
61
60
  let pkg;
62
61
  try {
63
62
  pkg = JSON.parse(packageJson);
64
- } catch {
65
- throw new Error(`Invalid package.json for ${packageName}`);
63
+ } catch (error) {
64
+ const detail = error instanceof Error ? error.message : String(error);
65
+ throw new Error(`Invalid package.json at ${packageJsonPath} (for "${packageName}"): ${detail}`);
66
66
  }
67
67
  const entrySubpath = subpath ? `./${subpath}` : ".";
68
68
  try {
@@ -208,81 +208,112 @@ function parseImportsRegex(code) {
208
208
  * esbuild-wasm bundling functionality.
209
209
  */
210
210
  /**
211
+ * Build a single warning string listing the bundler-only options the caller
212
+ * set together with `bundle: false`. Returns `null` if none were set.
213
+ *
214
+ * `transformAndResolve` is sucrase + naïve module resolution — it cannot apply
215
+ * `define` substitution, custom `loader` overrides, package-export `conditions`,
216
+ * or esbuild plugins. Silently ignoring these would produce subtly wrong output
217
+ * (e.g. `__DEV__` left as a free identifier in the emitted bundle).
218
+ */
219
+ function bundlerOnlyOptionsWarning(opts) {
220
+ const set = [];
221
+ if (opts.jsx !== void 0) set.push("jsx");
222
+ if (opts.jsxImportSource !== void 0) set.push("jsxImportSource");
223
+ if (opts.define !== void 0) set.push("define");
224
+ if (opts.loader !== void 0) set.push("loader");
225
+ if (opts.conditions !== void 0) set.push("conditions");
226
+ if (opts.plugins !== void 0) set.push("__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired");
227
+ if (set.length === 0) return null;
228
+ return `${set.join(", ")} ${set.length === 1 ? "is" : "are"} ignored when \`bundle: false\` (transform-only mode does not run esbuild). Set \`bundle: true\` (the default) to apply them.`;
229
+ }
230
+ /**
211
231
  * Bundle files using esbuild-wasm
212
232
  */
213
- async function bundleWithEsbuild(files, entryPoint, externals, target, minify, sourcemap, nodejsCompat) {
233
+ async function bundleWithEsbuild(options) {
234
+ const { files, entryPoint, externals, target, minify, sourcemap, nodejsCompat, jsx, jsxImportSource, define, loader: loaderOverrides, conditions, plugins: extraPlugins = [] } = options;
214
235
  await initializeEsbuild();
215
- const result = await esbuild.build({
216
- entryPoints: [entryPoint],
217
- bundle: true,
218
- write: false,
219
- format: "esm",
220
- platform: nodejsCompat ? "node" : "browser",
221
- target,
222
- minify,
223
- sourcemap: sourcemap ? "inline" : false,
224
- plugins: [{
225
- name: "virtual-fs",
226
- setup(build) {
227
- build.onResolve({ filter: /.*/ }, (args) => {
228
- if (args.kind === "entry-point") return {
229
- path: args.path,
236
+ const virtualFsPlugin = {
237
+ name: "virtual-fs",
238
+ setup(build) {
239
+ build.onResolve({ filter: /.*/ }, (args) => {
240
+ if (args.kind === "entry-point") return {
241
+ path: args.path,
242
+ namespace: "virtual"
243
+ };
244
+ if (args.path.startsWith(".")) {
245
+ const resolved = resolveRelativePath(args.resolveDir, args.path, files);
246
+ if (resolved) return {
247
+ path: resolved,
230
248
  namespace: "virtual"
231
249
  };
232
- if (args.path.startsWith(".")) {
233
- const resolved = resolveRelativePath(args.resolveDir, args.path, files);
234
- if (resolved) return {
235
- path: resolved,
250
+ }
251
+ if (!args.path.startsWith("/") && !args.path.startsWith(".")) {
252
+ if (externals.includes(args.path) || externals.some((e) => args.path.startsWith(`${e}/`) || args.path.startsWith(e))) return {
253
+ path: args.path,
254
+ external: true
255
+ };
256
+ try {
257
+ const result = resolveModule(args.path, { files });
258
+ if (!result.external) return {
259
+ path: result.path,
236
260
  namespace: "virtual"
237
261
  };
238
- }
239
- if (!args.path.startsWith("/") && !args.path.startsWith(".")) {
240
- if (externals.includes(args.path) || externals.some((e) => args.path.startsWith(`${e}/`) || args.path.startsWith(e))) return {
241
- path: args.path,
242
- external: true
243
- };
244
- try {
245
- const result = resolveModule(args.path, { files });
246
- if (!result.external) return {
247
- path: result.path,
248
- namespace: "virtual"
249
- };
250
- } catch {}
251
- return {
252
- path: args.path,
253
- external: true
254
- };
255
- }
256
- const normalizedPath = args.path.startsWith("/") ? args.path.slice(1) : args.path;
257
- if (files.read(normalizedPath) !== null) return {
258
- path: normalizedPath,
259
- namespace: "virtual"
260
- };
262
+ } catch {}
261
263
  return {
262
264
  path: args.path,
263
265
  external: true
264
266
  };
265
- });
266
- build.onLoad({
267
- filter: /.*/,
267
+ }
268
+ const normalizedPath = args.path.startsWith("/") ? args.path.slice(1) : args.path;
269
+ if (files.read(normalizedPath) !== null) return {
270
+ path: normalizedPath,
268
271
  namespace: "virtual"
269
- }, (args) => {
270
- const content = files.read(args.path);
271
- if (content === null) return { errors: [{ text: `File not found: ${args.path}` }] };
272
- const loader = getLoader(args.path);
273
- const lastSlash = args.path.lastIndexOf("/");
274
- return {
275
- contents: content,
276
- loader,
277
- resolveDir: lastSlash >= 0 ? args.path.slice(0, lastSlash) : ""
278
- };
279
- });
280
- }
281
- }],
282
- outfile: "bundle.js"
272
+ };
273
+ return {
274
+ path: args.path,
275
+ external: true
276
+ };
277
+ });
278
+ build.onLoad({
279
+ filter: /.*/,
280
+ namespace: "virtual"
281
+ }, (args) => {
282
+ const content = files.read(args.path);
283
+ if (content === null) return { errors: [{ text: `File not found: ${args.path}` }] };
284
+ const loader = getLoader(args.path, loaderOverrides);
285
+ const lastSlash = args.path.lastIndexOf("/");
286
+ return {
287
+ contents: content,
288
+ loader,
289
+ resolveDir: lastSlash >= 0 ? args.path.slice(0, lastSlash) : ""
290
+ };
291
+ });
292
+ }
293
+ };
294
+ for (let i = 0; i < extraPlugins.length; i++) {
295
+ const p = extraPlugins[i];
296
+ if (!p || typeof p !== "object" || typeof p.name !== "string" || typeof p.setup !== "function") throw new TypeError(`__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired[${i}] is not a valid esbuild plugin (expected an object with \`name: string\` and \`setup: (build) => void\`).`);
297
+ }
298
+ const userPlugins = extraPlugins;
299
+ const result = await esbuild.build({
300
+ entryPoints: [entryPoint],
301
+ bundle: true,
302
+ write: false,
303
+ format: "esm",
304
+ platform: nodejsCompat ? "node" : "browser",
305
+ target,
306
+ minify,
307
+ sourcemap: sourcemap ? "inline" : false,
308
+ plugins: [...userPlugins, virtualFsPlugin],
309
+ outfile: "bundle.js",
310
+ ...jsx !== void 0 ? { jsx } : {},
311
+ ...jsxImportSource !== void 0 ? { jsxImportSource } : {},
312
+ ...define !== void 0 ? { define } : {},
313
+ ...conditions !== void 0 ? { conditions } : {}
283
314
  });
284
315
  const output = result.outputFiles?.[0];
285
- if (!output) throw new Error("No output generated from esbuild");
316
+ if (!output) throw new Error(`esbuild produced no output for entry point "${entryPoint}". This usually means a custom plugin (\`__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\`) intercepted the entry without returning contents, or the entry resolved to an externalised module.`);
286
317
  const modules = { "bundle.js": output.text };
287
318
  const warnings = result.warnings.map((w) => w.text);
288
319
  if (warnings.length > 0) return {
@@ -320,7 +351,11 @@ function resolveRelativePath(resolveDir, relativePath, files) {
320
351
  if (files.read(indexPath) !== null) return indexPath;
321
352
  }
322
353
  }
323
- function getLoader(path) {
354
+ function getLoader(path, overrides) {
355
+ if (overrides) {
356
+ const matched = Object.keys(overrides).filter((ext) => path.endsWith(ext)).sort((a, b) => b.length - a.length)[0];
357
+ if (matched !== void 0) return overrides[matched];
358
+ }
324
359
  if (path.endsWith(".ts") || path.endsWith(".mts")) return "ts";
325
360
  if (path.endsWith(".tsx")) return "tsx";
326
361
  if (path.endsWith(".jsx")) return "jsx";
@@ -331,6 +366,44 @@ function getLoader(path) {
331
366
  let esbuildInitialized = false;
332
367
  let esbuildInitializePromise = null;
333
368
  /**
369
+ * Detect whether we are running inside the Cloudflare Workers runtime
370
+ * (workerd). Both production Workers and the local dev runtime expose
371
+ * `navigator.userAgent === "Cloudflare-Workers"`.
372
+ *
373
+ * Exported so tests can sanity-check the guard without standing up a
374
+ * separate Node-only test runner.
375
+ */
376
+ function isCloudflareWorkersRuntime() {
377
+ return typeof navigator !== "undefined" && typeof navigator.userAgent === "string" && navigator.userAgent === "Cloudflare-Workers";
378
+ }
379
+ /**
380
+ * Error message thrown when `createWorker` / `createApp` is called outside of
381
+ * the Workers runtime. Exported so tests can match against it without
382
+ * duplicating the wording.
383
+ */
384
+ const NOT_IN_WORKERS_ERROR = "@cloudflare/worker-bundler is only supported inside the Cloudflare Workers runtime (workerd). It cannot run in plain Node.js — including Vitest, Jest or other Node-based test runners — because it bundles via a `WebAssembly.Module` import that only the Workers module loader can resolve. To test code that uses this package, run your tests with @cloudflare/vitest-pool-workers so they execute inside workerd. See https://developers.cloudflare.com/workers/testing/vitest-integration/ for setup.";
385
+ /**
386
+ * Pre-started promise for the esbuild WASM module load.
387
+ *
388
+ * Pre-warmed at module evaluation time when (and only when) we're inside
389
+ * workerd, so the wasm `Compile` cost runs in parallel with everything else
390
+ * the test/handler is doing — matching the implicit behaviour of the static
391
+ * `import esbuildWasm from "./esbuild.wasm"` we used to have. Without this,
392
+ * the first `bundleWithEsbuild` call paid the full wasm-compile cost
393
+ * serially, which was enough to flake the first test of an `app-e2e`-style
394
+ * file under vitest's default 5s timeout on slower CI runners.
395
+ *
396
+ * Outside Workers, we *don't* start the import — Node's ESM-WASM loader
397
+ * would try to resolve esbuild's Go-runtime `gojs` import namespace as an
398
+ * npm package and crash. `initializeEsbuild()` throws `NOT_IN_WORKERS_ERROR`
399
+ * before ever touching the file in that case.
400
+ */
401
+ let pendingWasmImport = null;
402
+ if (isCloudflareWorkersRuntime()) {
403
+ pendingWasmImport = import("./esbuild.wasm");
404
+ pendingWasmImport.catch(() => {});
405
+ }
406
+ /**
334
407
  * Initialize the esbuild bundler.
335
408
  * This is called automatically when needed.
336
409
  */
@@ -338,9 +411,11 @@ async function initializeEsbuild() {
338
411
  if (esbuildInitialized) return;
339
412
  if (esbuildInitializePromise) return esbuildInitializePromise;
340
413
  esbuildInitializePromise = (async () => {
414
+ if (!isCloudflareWorkersRuntime() || pendingWasmImport === null) throw new Error(NOT_IN_WORKERS_ERROR);
341
415
  try {
416
+ const wasmModule = (await pendingWasmImport).default;
342
417
  await esbuild.initialize({
343
- wasmModule: esbuildWasm,
418
+ wasmModule,
344
419
  worker: false
345
420
  });
346
421
  esbuildInitialized = true;
@@ -670,6 +745,25 @@ function getDirectory(filePath) {
670
745
  //#endregion
671
746
  //#region src/utils.ts
672
747
  /**
748
+ * Default entry-point paths searched (in order) when no explicit entry has
749
+ * been provided and `wrangler.*` / `package.json` don't declare one.
750
+ *
751
+ * Exported so the "Could not determine entry point" error messages in
752
+ * `index.ts` (createWorker) and `app.ts` (createApp) can reference the same
753
+ * source of truth — otherwise the messages drift out of sync the first time
754
+ * someone adds a default and forgets to update both error strings.
755
+ */
756
+ const DEFAULT_ENTRY_POINTS = [
757
+ "src/index.ts",
758
+ "src/index.js",
759
+ "src/index.mts",
760
+ "src/index.mjs",
761
+ "index.ts",
762
+ "index.js",
763
+ "src/worker.ts",
764
+ "src/worker.js"
765
+ ];
766
+ /**
673
767
  * Detect entry point from wrangler config, package.json, or use defaults.
674
768
  * Priority: wrangler main > package.json exports/module/main > default paths
675
769
  */
@@ -693,21 +787,25 @@ function detectEntryPoint(files, wranglerConfig) {
693
787
  if (pkg.module) return normalizeEntryPath(pkg.module);
694
788
  if (pkg.main) return normalizeEntryPath(pkg.main);
695
789
  } catch {}
696
- for (const entry of [
697
- "src/index.ts",
698
- "src/index.js",
699
- "src/index.mts",
700
- "src/index.mjs",
701
- "index.ts",
702
- "index.js",
703
- "src/worker.ts",
704
- "src/worker.js"
705
- ]) if (files.read(entry) !== null) return entry;
790
+ for (const entry of DEFAULT_ENTRY_POINTS) if (files.read(entry) !== null) return entry;
706
791
  }
707
792
  function normalizeEntryPath(path) {
708
793
  if (path.startsWith("./")) return path.slice(2);
709
794
  return path;
710
795
  }
796
+ /**
797
+ * Render the user-provided source files as a short, readable list for use in
798
+ * "entry point not found" errors. Skips installed `node_modules/` files
799
+ * (which can be tens of thousands of paths and drown out the actually
800
+ * relevant signal — the files the user passed in) and truncates the tail.
801
+ */
802
+ function formatFileListForError(files, limit = 10) {
803
+ const all = files.list().filter((p) => !p.startsWith("node_modules/")).sort();
804
+ if (all.length === 0) return "(none — `files` is empty or only contains node_modules entries)";
805
+ const shown = all.slice(0, limit).join(", ");
806
+ if (all.length <= limit) return shown;
807
+ return `${shown}, … (+${all.length - limit} more)`;
808
+ }
711
809
  //#endregion
712
810
  //#region src/experimental.ts
713
811
  let warningShown = false;
@@ -1387,7 +1485,7 @@ async function handleAssetRequest(request, manifest, storage, config) {
1387
1485
  */
1388
1486
  async function createApp(options) {
1389
1487
  showExperimentalWarning("createApp");
1390
- const { files, bundle = true, externals: rawExternals = [], target = "es2022", minify = false, sourcemap = false, registry } = options;
1488
+ const { files, bundle = true, externals: rawExternals = [], target = "es2022", minify = false, sourcemap = false, registry, jsx, jsxImportSource, define, loader, conditions, __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins } = options;
1391
1489
  const fileSystem = isFileSystem(files) ? files : new InMemoryFileSystem(files);
1392
1490
  const externals = ["cloudflare:", ...rawExternals];
1393
1491
  const wranglerConfig = parseWranglerConfig(fileSystem);
@@ -1401,8 +1499,22 @@ async function createApp(options) {
1401
1499
  const clientOutputs = {};
1402
1500
  const clientBundles = [];
1403
1501
  for (const clientEntry of clientEntries) {
1404
- if (fileSystem.read(clientEntry) === null) throw new Error(`Client entry point "${clientEntry}" not found in files.`);
1405
- const bundleModule = (await bundleWithEsbuild(fileSystem, clientEntry, externals, "es2022", minify, sourcemap, false)).modules["bundle.js"];
1502
+ if (fileSystem.read(clientEntry) === null) throw new Error(`Client entry point "${clientEntry}" was not found in \`files\`. Available files: ${formatFileListForError(fileSystem)}.`);
1503
+ const bundleModule = (await bundleWithEsbuild({
1504
+ files: fileSystem,
1505
+ entryPoint: clientEntry,
1506
+ externals,
1507
+ target: "es2022",
1508
+ minify,
1509
+ sourcemap,
1510
+ nodejsCompat: false,
1511
+ jsx,
1512
+ jsxImportSource,
1513
+ define,
1514
+ loader,
1515
+ conditions,
1516
+ plugins
1517
+ })).modules["bundle.js"];
1406
1518
  if (typeof bundleModule === "string") {
1407
1519
  const outputPath = `/${clientEntry.replace(/^src\//, "").replace(/\.(tsx?|jsx?)$/, ".js")}`;
1408
1520
  clientOutputs[outputPath] = bundleModule;
@@ -1417,11 +1529,36 @@ async function createApp(options) {
1417
1529
  for (const [pathname, content] of Object.entries(clientOutputs)) allAssets[pathname] = content;
1418
1530
  const assetManifest = await buildAssetManifest(allAssets);
1419
1531
  const serverEntry = options.server ?? detectEntryPoint(fileSystem, wranglerConfig);
1420
- if (!serverEntry) throw new Error("Could not determine server entry point. Specify the 'server' option.");
1421
- if (fileSystem.read(serverEntry) === null) throw new Error(`Server entry point "${serverEntry}" not found in files.`);
1532
+ if (!serverEntry) throw new Error(`Could not determine server entry point for createApp. Tried (in order): the \`server\` option, \`main\` in wrangler config, \`exports\`/\`module\`/\`main\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(", ")}. Pass \`server\` explicitly or add one of those files.`);
1533
+ if (fileSystem.read(serverEntry) === null) throw new Error(`Server entry point "${serverEntry}" was not found in \`files\`. Available files: ${formatFileListForError(fileSystem)}.`);
1422
1534
  let serverResult;
1423
- if (bundle) serverResult = await bundleWithEsbuild(fileSystem, serverEntry, externals, target, minify, sourcemap, nodejsCompat);
1424
- else serverResult = await transformAndResolve(fileSystem, serverEntry, externals);
1535
+ if (bundle) serverResult = await bundleWithEsbuild({
1536
+ files: fileSystem,
1537
+ entryPoint: serverEntry,
1538
+ externals,
1539
+ target,
1540
+ minify,
1541
+ sourcemap,
1542
+ nodejsCompat,
1543
+ jsx,
1544
+ jsxImportSource,
1545
+ define,
1546
+ loader,
1547
+ conditions,
1548
+ plugins
1549
+ });
1550
+ else {
1551
+ serverResult = await transformAndResolve(fileSystem, serverEntry, externals);
1552
+ const bundlerOnly = bundlerOnlyOptionsWarning({
1553
+ jsx,
1554
+ jsxImportSource,
1555
+ define,
1556
+ loader,
1557
+ conditions,
1558
+ plugins
1559
+ });
1560
+ if (bundlerOnly) serverResult.warnings = [...serverResult.warnings ?? [], bundlerOnly];
1561
+ }
1425
1562
  const result = {
1426
1563
  mainModule: serverResult.mainModule,
1427
1564
  modules: serverResult.modules,
@@ -1457,7 +1594,7 @@ async function createApp(options) {
1457
1594
  */
1458
1595
  async function createWorker(options) {
1459
1596
  showExperimentalWarning("createWorker");
1460
- let { files, bundle = true, externals = [], target = "es2022", minify = false, sourcemap = false, registry } = options;
1597
+ let { files, bundle = true, externals = [], target = "es2022", minify = false, sourcemap = false, registry, jsx, jsxImportSource, define, loader, conditions, __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins } = options;
1461
1598
  let fileSystem;
1462
1599
  if (isFileSystem(files)) fileSystem = files;
1463
1600
  else fileSystem = new InMemoryFileSystem(files);
@@ -1470,17 +1607,40 @@ async function createWorker(options) {
1470
1607
  installWarnings.push(...installResult.warnings);
1471
1608
  }
1472
1609
  const entryPoint = options.entryPoint ?? detectEntryPoint(fileSystem, wranglerConfig);
1473
- if (!entryPoint) throw new Error("Could not determine entry point. Please specify entryPoint option.");
1474
- if (fileSystem.read(entryPoint) === null) throw new Error(`Entry point "${entryPoint}" not found in files.`);
1610
+ if (!entryPoint) throw new Error(`Could not determine entry point for createWorker. Tried (in order): the \`entryPoint\` option, \`main\` in wrangler config, \`exports\`/\`module\`/\`main\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(", ")}. Pass \`entryPoint\` explicitly or add one of those files.`);
1611
+ if (fileSystem.read(entryPoint) === null) throw new Error(`Entry point "${entryPoint}" was not found in \`files\`. Available files: ${formatFileListForError(fileSystem)}.`);
1475
1612
  if (bundle) {
1476
- const result = await bundleWithEsbuild(fileSystem, entryPoint, externals, target, minify, sourcemap, nodejsCompat);
1613
+ const result = await bundleWithEsbuild({
1614
+ files: fileSystem,
1615
+ entryPoint,
1616
+ externals,
1617
+ target,
1618
+ minify,
1619
+ sourcemap,
1620
+ nodejsCompat,
1621
+ jsx,
1622
+ jsxImportSource,
1623
+ define,
1624
+ loader,
1625
+ conditions,
1626
+ plugins
1627
+ });
1477
1628
  if (wranglerConfig !== void 0) result.wranglerConfig = wranglerConfig;
1478
1629
  if (installWarnings.length > 0) result.warnings = [...result.warnings ?? [], ...installWarnings];
1479
1630
  return result;
1480
1631
  } else {
1481
1632
  const result = await transformAndResolve(fileSystem, entryPoint, externals);
1633
+ const bundlerOnly = bundlerOnlyOptionsWarning({
1634
+ jsx,
1635
+ jsxImportSource,
1636
+ define,
1637
+ loader,
1638
+ conditions,
1639
+ plugins
1640
+ });
1482
1641
  if (wranglerConfig !== void 0) result.wranglerConfig = wranglerConfig;
1483
- if (installWarnings.length > 0) result.warnings = [...result.warnings ?? [], ...installWarnings];
1642
+ const extraWarnings = [...installWarnings, ...bundlerOnly ? [bundlerOnly] : []];
1643
+ if (extraWarnings.length > 0) result.warnings = [...result.warnings ?? [], ...extraWarnings];
1484
1644
  return result;
1485
1645
  }
1486
1646
  }