@cloudflare/vite-plugin 0.0.0-07613d3b2 → 0.0.0-08b8c4687

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,7 @@
1
1
  // src/index.ts
2
2
  import assert9 from "node:assert";
3
3
  import * as fs5 from "node:fs";
4
+ import { builtinModules as builtinModules2 } from "node:module";
4
5
  import * as path7 from "node:path";
5
6
  import { createMiddleware } from "@hattip/adapter-node";
6
7
 
@@ -1074,7 +1075,6 @@ import * as vite6 from "vite";
1074
1075
 
1075
1076
  // src/cloudflare-environment.ts
1076
1077
  import assert from "node:assert";
1077
- import { builtinModules } from "node:module";
1078
1078
  import * as vite2 from "vite";
1079
1079
 
1080
1080
  // src/constants.ts
@@ -1207,7 +1207,9 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1207
1207
  // dependencies as not external
1208
1208
  noExternal: true,
1209
1209
  // We want to use `workerd` package exports if available (e.g. for postgres).
1210
- conditions: [...defaultConditions, "development|production"]
1210
+ conditions: [...defaultConditions, "development|production"],
1211
+ // The Cloudflare ones are proper builtins in the environment
1212
+ builtins: [...cloudflareBuiltInModules]
1211
1213
  },
1212
1214
  dev: {
1213
1215
  createEnvironment(name2, config) {
@@ -1229,19 +1231,14 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1229
1231
  // so the input value here serves both as the build input as well as the starting point for
1230
1232
  // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
1231
1233
  // optimizeDeps.entries in the dev config)
1232
- input: workerConfig.main,
1233
- external: [...cloudflareBuiltInModules]
1234
+ input: workerConfig.main
1234
1235
  }
1235
1236
  },
1236
1237
  optimizeDeps: {
1237
1238
  // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1238
1239
  noDiscovery: false,
1239
1240
  entries: workerConfig.main,
1240
- exclude: [
1241
- ...cloudflareBuiltInModules,
1242
- // we have to exclude all node modules to work in dev-mode not just the unenv externals...
1243
- ...builtinModules.concat(builtinModules.map((m) => `node:${m}`))
1244
- ],
1241
+ exclude: [...cloudflareBuiltInModules],
1245
1242
  esbuildOptions: {
1246
1243
  platform: "neutral",
1247
1244
  conditions: [...defaultConditions, "development"],
@@ -1367,7 +1364,13 @@ import * as fs2 from "node:fs";
1367
1364
  import * as fsp from "node:fs/promises";
1368
1365
  import * as path3 from "node:path";
1369
1366
  import { fileURLToPath } from "node:url";
1370
- import { Log, LogLevel, Response as MiniflareResponse } from "miniflare";
1367
+ import {
1368
+ kCurrentWorker,
1369
+ Log,
1370
+ LogLevel,
1371
+ Response as MiniflareResponse
1372
+ } from "miniflare";
1373
+ import { globSync } from "tinyglobby";
1371
1374
  import "vite";
1372
1375
  import {
1373
1376
  unstable_getMiniflareWorkerOptions,
@@ -1401,11 +1404,10 @@ function getWorkerToWorkerEntrypointNamesMap(workers) {
1401
1404
  );
1402
1405
  for (const worker of workers) {
1403
1406
  for (const value of Object.values(worker.serviceBindings ?? {})) {
1404
- if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1405
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(
1406
- value.name
1407
- );
1408
- assert4(entrypointNames, missingWorkerErrorMessage(value.name));
1407
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1408
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
1409
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
1410
+ assert4(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
1409
1411
  entrypointNames.add(value.entrypoint);
1410
1412
  }
1411
1413
  }
@@ -1550,7 +1552,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1550
1552
  }
1551
1553
  }
1552
1554
  ];
1553
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1555
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1554
1556
  ([environmentName, workerConfig]) => {
1555
1557
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1556
1558
  {
@@ -1559,54 +1561,58 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1559
1561
  },
1560
1562
  resolvedPluginConfig.cloudflareEnv
1561
1563
  );
1564
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1562
1565
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1563
1566
  return {
1564
- ...workerOptions,
1565
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1566
- name: workerConfig.name,
1567
- modulesRoot: miniflareModulesRoot,
1568
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1569
- bindings: {
1570
- ...workerOptions.bindings,
1571
- __VITE_ROOT__: resolvedViteConfig.root,
1572
- __VITE_ENTRY_PATH__: workerConfig.main
1573
- },
1574
- serviceBindings: {
1575
- ...workerOptions.serviceBindings,
1576
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1577
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1578
- } : {},
1579
- __VITE_INVOKE_MODULE__: async (request) => {
1580
- const payload = await request.json();
1581
- const invokePayloadData = payload.data;
1582
- assert4(
1583
- invokePayloadData.name === "fetchModule",
1584
- `Invalid invoke event: ${invokePayloadData.name}`
1585
- );
1586
- const [moduleId] = invokePayloadData.data;
1587
- const moduleRE = new RegExp(MODULE_PATTERN);
1588
- if (moduleRE.test(moduleId)) {
1589
- const result2 = {
1590
- externalize: moduleId,
1591
- type: "module"
1592
- };
1593
- return MiniflareResponse.json({ result: result2 });
1594
- }
1595
- if (moduleId.startsWith("cloudflare:")) {
1596
- const result2 = {
1597
- externalize: moduleId,
1598
- type: "builtin"
1599
- };
1600
- return MiniflareResponse.json({ result: result2 });
1567
+ externalWorkers: externalWorkers2,
1568
+ worker: {
1569
+ ...workerOptions,
1570
+ name: workerOptions.name ?? workerConfig.name,
1571
+ modulesRoot: miniflareModulesRoot,
1572
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1573
+ bindings: {
1574
+ ...workerOptions.bindings,
1575
+ __VITE_ROOT__: resolvedViteConfig.root,
1576
+ __VITE_ENTRY_PATH__: workerConfig.main
1577
+ },
1578
+ serviceBindings: {
1579
+ ...workerOptions.serviceBindings,
1580
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1581
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
1582
+ } : {},
1583
+ __VITE_INVOKE_MODULE__: async (request) => {
1584
+ const payload = await request.json();
1585
+ const invokePayloadData = payload.data;
1586
+ assert4(
1587
+ invokePayloadData.name === "fetchModule",
1588
+ `Invalid invoke event: ${invokePayloadData.name}`
1589
+ );
1590
+ const [moduleId] = invokePayloadData.data;
1591
+ const moduleRE = new RegExp(MODULE_PATTERN);
1592
+ const shouldExternalize = (
1593
+ // Worker modules (CompiledWasm, Text, Data)
1594
+ moduleRE.test(moduleId)
1595
+ );
1596
+ if (shouldExternalize) {
1597
+ const result2 = {
1598
+ externalize: moduleId,
1599
+ type: "module"
1600
+ };
1601
+ return MiniflareResponse.json({ result: result2 });
1602
+ }
1603
+ const devEnvironment = viteDevServer.environments[environmentName];
1604
+ const result = await devEnvironment.hot.handleInvoke(payload);
1605
+ return MiniflareResponse.json(result);
1601
1606
  }
1602
- const devEnvironment = viteDevServer.environments[environmentName];
1603
- const result = await devEnvironment.hot.handleInvoke(payload);
1604
- return MiniflareResponse.json(result);
1605
1607
  }
1606
1608
  }
1607
1609
  };
1608
1610
  }
1609
1611
  ) : [];
1612
+ const userWorkers = workersFromConfig.map((options) => options.worker);
1613
+ const externalWorkers = workersFromConfig.flatMap(
1614
+ (options) => options.externalWorkers
1615
+ );
1610
1616
  const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1611
1617
  const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1612
1618
  const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
@@ -1626,6 +1632,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1626
1632
  ),
1627
1633
  workers: [
1628
1634
  ...assetWorkers,
1635
+ ...externalWorkers,
1629
1636
  ...userWorkers.map((workerOptions) => {
1630
1637
  const wrappers = [
1631
1638
  `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
@@ -1658,7 +1665,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1658
1665
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1659
1666
  assert4(
1660
1667
  workflowEntrypointClassNames,
1661
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1668
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1662
1669
  );
1663
1670
  for (const className of [...workflowEntrypointClassNames].sort()) {
1664
1671
  wrappers.push(
@@ -1694,17 +1701,19 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1694
1701
  );
1695
1702
  const moduleRE = new RegExp(MODULE_PATTERN);
1696
1703
  const match = moduleRE.exec(rawSpecifier);
1697
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1704
+ assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1698
1705
  const [full, moduleType, modulePath] = match;
1699
1706
  assert4(
1700
1707
  modulePath,
1701
- `Unexpected error: module path not found in reference ${full}.`
1708
+ `Unexpected error: module path not found in reference: ${full}.`
1702
1709
  );
1703
1710
  let source;
1704
1711
  try {
1705
1712
  source = fs2.readFileSync(modulePath);
1706
1713
  } catch (error) {
1707
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1714
+ throw new Error(
1715
+ `Import "${modulePath}" not found. Does the file exist?`
1716
+ );
1708
1717
  }
1709
1718
  return MiniflareResponse.json({
1710
1719
  // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
@@ -1713,22 +1722,44 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1713
1722
  }
1714
1723
  };
1715
1724
  }
1725
+ function getPreviewModules(main, modulesRules) {
1726
+ assert4(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
1727
+ const rootPath = path3.dirname(main);
1728
+ const entryPath = path3.basename(main);
1729
+ return {
1730
+ rootPath,
1731
+ modules: [
1732
+ {
1733
+ type: "ESModule",
1734
+ path: entryPath
1735
+ },
1736
+ ...modulesRules.flatMap(
1737
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
1738
+ type,
1739
+ path: path8
1740
+ }))
1741
+ )
1742
+ ]
1743
+ };
1744
+ }
1716
1745
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1717
1746
  const resolvedViteConfig = vitePreviewServer.config;
1718
1747
  const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1719
1748
  const workerConfigs = configPaths.map(
1720
1749
  (configPath) => unstable_readConfig({ config: configPath })
1721
1750
  );
1722
- const workers = workerConfigs.map((config) => {
1751
+ const workers = workerConfigs.flatMap((config) => {
1723
1752
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1724
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1725
- return {
1726
- ...workerOptions,
1727
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1728
- name: config.name,
1729
- modules: true,
1730
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1731
- };
1753
+ const { externalWorkers } = miniflareWorkerOptions;
1754
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1755
+ return [
1756
+ {
1757
+ ...workerOptions,
1758
+ name: workerOptions.name ?? config.name,
1759
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
1760
+ },
1761
+ ...externalWorkers
1762
+ ];
1732
1763
  });
1733
1764
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
1734
1765
  return {
@@ -7310,7 +7341,7 @@ Parser.acorn = {
7310
7341
  };
7311
7342
 
7312
7343
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7313
- import { builtinModules as builtinModules2, createRequire } from "node:module";
7344
+ import { builtinModules, createRequire } from "node:module";
7314
7345
  import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
7315
7346
 
7316
7347
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
@@ -7370,10 +7401,10 @@ var isAbsolute = function(p) {
7370
7401
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7371
7402
  import assert5 from "node:assert";
7372
7403
  import process$1 from "node:process";
7373
- import path4, { dirname as dirname3 } from "node:path";
7404
+ import path4, { dirname as dirname4 } from "node:path";
7374
7405
  import v8 from "node:v8";
7375
7406
  import { format as format2, inspect } from "node:util";
7376
- var BUILTIN_MODULES = new Set(builtinModules2);
7407
+ var BUILTIN_MODULES = new Set(builtinModules);
7377
7408
  function normalizeSlash(path8) {
7378
7409
  return path8.replace(/\\/g, "/");
7379
7410
  }
@@ -8487,7 +8518,7 @@ function parsePackageName(specifier, base) {
8487
8518
  return { packageName, packageSubpath, isScoped };
8488
8519
  }
8489
8520
  function packageResolve(specifier, base, conditions) {
8490
- if (builtinModules2.includes(specifier)) {
8521
+ if (builtinModules.includes(specifier)) {
8491
8522
  return new URL$1("node:" + specifier);
8492
8523
  }
8493
8524
  const { packageName, packageSubpath, isScoped } = parsePackageName(
@@ -8574,7 +8605,7 @@ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8574
8605
  try {
8575
8606
  resolved = new URL$1(specifier);
8576
8607
  } catch (error_) {
8577
- if (isRemote && !builtinModules2.includes(specifier)) {
8608
+ if (isRemote && !builtinModules.includes(specifier)) {
8578
8609
  const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8579
8610
  error.cause = error_;
8580
8611
  throw error;
@@ -8719,7 +8750,8 @@ var { env } = defineEnv({
8719
8750
  nodeCompat: true,
8720
8751
  presets: [cloudflare]
8721
8752
  });
8722
- var CLOUDFLARE_VIRTUAL_PREFIX = "\0__CLOUDFLARE_NODEJS_COMPAT__";
8753
+ var nodeCompatExternals = new Set(env.external);
8754
+ var nodeCompatEntries = getNodeCompatEntries();
8723
8755
  function isNodeCompat(workerConfig) {
8724
8756
  if (workerConfig === void 0) {
8725
8757
  return false;
@@ -8747,12 +8779,17 @@ function injectGlobalCode(id, code) {
8747
8779
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8748
8780
  if (typeof globalInject === "string") {
8749
8781
  const moduleSpecifier2 = globalInject;
8750
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier2}";
8782
+ return `import var_${globalName} from "${moduleSpecifier2}";
8751
8783
  globalThis.${globalName} = var_${globalName};
8752
8784
  `;
8753
8785
  }
8754
8786
  const [moduleSpecifier, exportName] = globalInject;
8755
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier}";
8787
+ assert6(
8788
+ moduleSpecifier !== void 0,
8789
+ "Expected moduleSpecifier to be defined"
8790
+ );
8791
+ assert6(exportName !== void 0, "Expected exportName to be defined");
8792
+ return `import var_${globalName} from "${moduleSpecifier}";
8756
8793
  globalThis.${globalName} = var_${globalName}.${exportName};
8757
8794
  `;
8758
8795
  }).join("\n");
@@ -8763,37 +8800,36 @@ globalThis.${globalName} = var_${globalName}.${exportName};
8763
8800
  map: modified.generateMap({ hires: "boundary", source: id })
8764
8801
  };
8765
8802
  }
8766
- function getNodeCompatAliases() {
8767
- const aliases = {};
8768
- Object.keys(env.alias).forEach((key) => {
8769
- if (!env.external.includes(key)) {
8770
- aliases[key] = CLOUDFLARE_VIRTUAL_PREFIX + key;
8771
- }
8772
- });
8773
- return aliases;
8774
- }
8775
- function getNodeCompatExternals() {
8776
- return env.external;
8777
- }
8778
- function maybeStripNodeJsVirtualPrefix(source) {
8779
- return source.startsWith(CLOUDFLARE_VIRTUAL_PREFIX) ? source.slice(CLOUDFLARE_VIRTUAL_PREFIX.length) : void 0;
8780
- }
8781
8803
  function resolveNodeJSImport(source) {
8782
8804
  const alias = env.alias[source];
8783
8805
  if (alias) {
8784
- assert6(
8785
- !env.external.includes(alias),
8786
- `Unexpected unenv alias to external module: ${source} -> ${alias}`
8787
- );
8788
- source = alias;
8806
+ return {
8807
+ unresolved: alias,
8808
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8809
+ };
8789
8810
  }
8790
- const resolved = resolvePathSync(source, {
8791
- url: import.meta.url
8792
- });
8793
- return {
8794
- unresolved: source,
8795
- resolved
8796
- };
8811
+ if (nodeCompatEntries.has(source)) {
8812
+ return {
8813
+ unresolved: source,
8814
+ resolved: resolvePathSync(source, { url: import.meta.url })
8815
+ };
8816
+ }
8817
+ }
8818
+ function getNodeCompatEntries() {
8819
+ const entries = new Set(Object.values(env.alias));
8820
+ for (const globalInject of Object.values(env.inject)) {
8821
+ if (typeof globalInject === "string") {
8822
+ entries.add(globalInject);
8823
+ } else {
8824
+ assert6(
8825
+ globalInject[0] !== void 0,
8826
+ "Expected first element of globalInject to be defined"
8827
+ );
8828
+ entries.add(globalInject[0]);
8829
+ }
8830
+ }
8831
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8832
+ return entries;
8797
8833
  }
8798
8834
 
8799
8835
  // src/plugin-config.ts
@@ -9106,9 +9142,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9106
9142
  }
9107
9143
 
9108
9144
  // src/websockets.ts
9109
- import ws from "ws";
9145
+ import { WebSocketServer } from "ws";
9110
9146
  function handleWebSocket(httpServer, fetcher, logger) {
9111
- const nodeWebSocket = new ws.Server({ noServer: true });
9147
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9112
9148
  httpServer.on(
9113
9149
  "upgrade",
9114
9150
  async (request, socket, head) => {
@@ -9217,7 +9253,7 @@ function cloudflare2(pluginConfig = {}) {
9217
9253
  }
9218
9254
  } : void 0,
9219
9255
  builder: {
9220
- async buildApp(builder) {
9256
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9221
9257
  const clientEnvironment = builder.environments.client;
9222
9258
  const defaultHtmlPath = path7.resolve(
9223
9259
  builder.config.root,
@@ -9243,7 +9279,7 @@ function cloudflare2(pluginConfig = {}) {
9243
9279
  )
9244
9280
  );
9245
9281
  }
9246
- }
9282
+ })
9247
9283
  }
9248
9284
  };
9249
9285
  },
@@ -9304,7 +9340,7 @@ function cloudflare2(pluginConfig = {}) {
9304
9340
  return;
9305
9341
  }
9306
9342
  config.no_bundle = true;
9307
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9343
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9308
9344
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9309
9345
  config.unsafe = void 0;
9310
9346
  }
@@ -9462,49 +9498,61 @@ function cloudflare2(pluginConfig = {}) {
9462
9498
  apply(_config, env2) {
9463
9499
  return !env2.isPreview;
9464
9500
  },
9465
- config() {
9466
- return {
9467
- resolve: {
9468
- alias: getNodeCompatAliases()
9469
- }
9470
- };
9471
- },
9472
- configEnvironment(environmentName) {
9473
- const workerConfig = getWorkerConfig2(environmentName);
9474
- if (isNodeCompat(workerConfig)) {
9501
+ configEnvironment(name2) {
9502
+ if (isNodeCompat(getWorkerConfig2(name2))) {
9475
9503
  return {
9476
- build: {
9477
- rollupOptions: {
9478
- external: getNodeCompatExternals()
9479
- }
9504
+ resolve: {
9505
+ builtins: [...nodeCompatExternals]
9506
+ },
9507
+ optimizeDeps: {
9508
+ // This is a list of dependency entry-points that should be pre-bundled.
9509
+ // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
9510
+ // ready ahead the first request to the dev server.
9511
+ // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9512
+ // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9513
+ // TODO: work out how to re-enable pre-bundling of these
9514
+ // include: [...getNodeCompatEntries()],
9515
+ // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9516
+ // In this case we provide a list of all the Node.js modules, both those built-in to workerd and those that will be polyfilled.
9517
+ // Obviously we don't want/need the optimizer to try to process modules that are built-in;
9518
+ // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
9519
+ // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
9520
+ exclude: [
9521
+ ...builtinModules2,
9522
+ ...builtinModules2.map((m) => `node:${m}`)
9523
+ ]
9480
9524
  }
9481
9525
  };
9482
9526
  }
9483
9527
  },
9528
+ applyToEnvironment(environment) {
9529
+ return isNodeCompat(getWorkerConfig2(environment.name));
9530
+ },
9531
+ // We need the resolver from this plugin to run before built-in ones, otherwise Vite's built-in
9532
+ // resolver will try to externalize the Node.js module imports (e.g. `perf_hooks` and `node:tty`)
9533
+ // rather than allowing the resolve hook here to alias then to polyfills.
9534
+ enforce: "pre",
9484
9535
  async resolveId(source, importer, options) {
9485
- const strippedSource = maybeStripNodeJsVirtualPrefix(source);
9486
- if (!strippedSource) {
9487
- return;
9488
- }
9489
- const workerConfig = getWorkerConfig2(this.environment.name);
9490
- if (!isNodeCompat(workerConfig)) {
9491
- return this.resolve(strippedSource, importer, options);
9536
+ const result = resolveNodeJSImport(source);
9537
+ if (!result) {
9538
+ return this.resolve(source, importer, options);
9492
9539
  }
9493
- const { unresolved, resolved } = resolveNodeJSImport(strippedSource);
9494
- if (this.environment.mode === "dev" && this.environment.depsOptimizer) {
9495
- const optimized = this.environment.depsOptimizer.registerMissingImport(
9496
- unresolved,
9497
- resolved
9498
- ).id;
9499
- return this.resolve(optimized, importer, options);
9540
+ if (this.environment.mode === "dev") {
9541
+ assert9(
9542
+ this.environment.depsOptimizer,
9543
+ "depsOptimizer is required in dev mode"
9544
+ );
9545
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9546
+ result.unresolved,
9547
+ result.resolved
9548
+ );
9549
+ return this.resolve(id, importer, options);
9500
9550
  }
9501
- return this.resolve(resolved, importer, options);
9551
+ return this.resolve(result.resolved, importer, options);
9502
9552
  },
9503
9553
  async transform(code, id) {
9504
9554
  const workerConfig = getWorkerConfig2(this.environment.name);
9505
- if (!isNodeCompat(workerConfig)) {
9506
- return;
9507
- }
9555
+ assert9(workerConfig, "Expected a worker config");
9508
9556
  const resolvedId = await this.resolve(workerConfig.main);
9509
9557
  if (id === resolvedId?.id) {
9510
9558
  return injectGlobalCode(id, code);
@@ -25,7 +25,7 @@ function stripInternalEnv(internalEnv) {
25
25
  return userEnv;
26
26
  }
27
27
 
28
- // ../../node_modules/.pnpm/vite@6.1.0_@types+node@18.19.74_jiti@2.4.2/node_modules/vite/dist/node/module-runner.js
28
+ // ../../node_modules/.pnpm/vite@6.1.0_@types+node@18.19.76_jiti@2.4.2/node_modules/vite/dist/node/module-runner.js
29
29
  var VALID_ID_PREFIX = "/@id/";
30
30
  var NULL_BYTE_PLACEHOLDER = "__x00__";
31
31
  var SOURCEMAPPING_URL = "sourceMa";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/vite-plugin",
3
- "version": "0.0.0-07613d3b2",
3
+ "version": "0.0.0-08b8c4687",
4
4
  "description": "Cloudflare plugin for Vite",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -35,29 +35,30 @@
35
35
  "dependencies": {
36
36
  "@cloudflare/unenv-preset": "1.1.1",
37
37
  "@hattip/adapter-node": "^0.0.49",
38
+ "tinyglobby": "^0.2.12",
38
39
  "unenv": "2.0.0-rc.1",
39
- "ws": "^8.18.0",
40
- "miniflare": "0.0.0-07613d3b2"
40
+ "ws": "8.18.0",
41
+ "miniflare": "0.0.0-08b8c4687",
42
+ "wrangler": "0.0.0-08b8c4687"
41
43
  },
42
44
  "devDependencies": {
43
- "@cloudflare/workers-types": "^4.20250204.0",
45
+ "@cloudflare/workers-types": "^4.20250224.0",
44
46
  "@types/node": "^22.10.1",
45
47
  "@types/ws": "^8.5.13",
46
48
  "magic-string": "^0.30.12",
47
49
  "mlly": "^1.7.4",
48
50
  "tsup": "8.3.0",
49
51
  "typescript": "^5.7.2",
50
- "undici": "^5.28.4",
52
+ "undici": "^5.28.5",
51
53
  "vite": "^6.1.0",
52
- "vitest": "~2.1.9",
54
+ "vitest": "~3.0.5",
53
55
  "@cloudflare/mock-npm-registry": "0.0.0",
54
56
  "@cloudflare/workers-tsconfig": "0.0.0",
55
- "wrangler": "0.0.0-07613d3b2",
56
- "@cloudflare/workers-shared": "0.0.0-07613d3b2"
57
+ "@cloudflare/workers-shared": "0.0.0-08b8c4687"
57
58
  },
58
59
  "peerDependencies": {
59
60
  "vite": "^6.1.0",
60
- "wrangler": "^3.101.0"
61
+ "wrangler": "0.0.0-08b8c4687"
61
62
  },
62
63
  "publishConfig": {
63
64
  "access": "public"
@@ -70,7 +71,7 @@
70
71
  "check:type": "tsc --build",
71
72
  "dev": "tsup --watch",
72
73
  "test": "vitest run",
73
- "test:ci": "pnpm test && pnpm test:e2e",
74
+ "test:ci": "pnpm test",
74
75
  "test:e2e": "vitest run -c e2e/vitest.config.ts",
75
76
  "test:watch": "vitest"
76
77
  }