@cloudflare/vite-plugin 0.0.0-ed5ebdc4c → 0.0.0-edf169d15

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
@@ -1364,7 +1364,13 @@ import * as fs2 from "node:fs";
1364
1364
  import * as fsp from "node:fs/promises";
1365
1365
  import * as path3 from "node:path";
1366
1366
  import { fileURLToPath } from "node:url";
1367
- 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";
1368
1374
  import "vite";
1369
1375
  import {
1370
1376
  unstable_getMiniflareWorkerOptions,
@@ -1398,11 +1404,10 @@ function getWorkerToWorkerEntrypointNamesMap(workers) {
1398
1404
  );
1399
1405
  for (const worker of workers) {
1400
1406
  for (const value of Object.values(worker.serviceBindings ?? {})) {
1401
- if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1402
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(
1403
- value.name
1404
- );
1405
- 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));
1406
1411
  entrypointNames.add(value.entrypoint);
1407
1412
  }
1408
1413
  }
@@ -1547,7 +1552,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1547
1552
  }
1548
1553
  }
1549
1554
  ];
1550
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1555
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1551
1556
  ([environmentName, workerConfig]) => {
1552
1557
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1553
1558
  {
@@ -1556,51 +1561,58 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1556
1561
  },
1557
1562
  resolvedPluginConfig.cloudflareEnv
1558
1563
  );
1564
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1559
1565
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1560
1566
  return {
1561
- ...workerOptions,
1562
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1563
- name: workerConfig.name,
1564
- modulesRoot: miniflareModulesRoot,
1565
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1566
- bindings: {
1567
- ...workerOptions.bindings,
1568
- __VITE_ROOT__: resolvedViteConfig.root,
1569
- __VITE_ENTRY_PATH__: workerConfig.main
1570
- },
1571
- serviceBindings: {
1572
- ...workerOptions.serviceBindings,
1573
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1574
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1575
- } : {},
1576
- __VITE_INVOKE_MODULE__: async (request) => {
1577
- const payload = await request.json();
1578
- const invokePayloadData = payload.data;
1579
- assert4(
1580
- invokePayloadData.name === "fetchModule",
1581
- `Invalid invoke event: ${invokePayloadData.name}`
1582
- );
1583
- const [moduleId] = invokePayloadData.data;
1584
- const moduleRE = new RegExp(MODULE_PATTERN);
1585
- const shouldExternalize = (
1586
- // Worker modules (CompiledWasm, Text, Data)
1587
- moduleRE.test(moduleId)
1588
- );
1589
- if (shouldExternalize) {
1590
- const result2 = {
1591
- externalize: moduleId,
1592
- type: "module"
1593
- };
1594
- 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);
1595
1606
  }
1596
- const devEnvironment = viteDevServer.environments[environmentName];
1597
- const result = await devEnvironment.hot.handleInvoke(payload);
1598
- return MiniflareResponse.json(result);
1599
1607
  }
1600
1608
  }
1601
1609
  };
1602
1610
  }
1603
1611
  ) : [];
1612
+ const userWorkers = workersFromConfig.map((options) => options.worker);
1613
+ const externalWorkers = workersFromConfig.flatMap(
1614
+ (options) => options.externalWorkers
1615
+ );
1604
1616
  const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1605
1617
  const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1606
1618
  const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
@@ -1620,6 +1632,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1620
1632
  ),
1621
1633
  workers: [
1622
1634
  ...assetWorkers,
1635
+ ...externalWorkers,
1623
1636
  ...userWorkers.map((workerOptions) => {
1624
1637
  const wrappers = [
1625
1638
  `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
@@ -1652,7 +1665,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1652
1665
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1653
1666
  assert4(
1654
1667
  workflowEntrypointClassNames,
1655
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1668
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1656
1669
  );
1657
1670
  for (const className of [...workflowEntrypointClassNames].sort()) {
1658
1671
  wrappers.push(
@@ -1688,17 +1701,19 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1688
1701
  );
1689
1702
  const moduleRE = new RegExp(MODULE_PATTERN);
1690
1703
  const match = moduleRE.exec(rawSpecifier);
1691
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1704
+ assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1692
1705
  const [full, moduleType, modulePath] = match;
1693
1706
  assert4(
1694
1707
  modulePath,
1695
- `Unexpected error: module path not found in reference ${full}.`
1708
+ `Unexpected error: module path not found in reference: ${full}.`
1696
1709
  );
1697
1710
  let source;
1698
1711
  try {
1699
1712
  source = fs2.readFileSync(modulePath);
1700
1713
  } catch (error) {
1701
- 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
+ );
1702
1717
  }
1703
1718
  return MiniflareResponse.json({
1704
1719
  // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
@@ -1707,22 +1722,44 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1707
1722
  }
1708
1723
  };
1709
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
+ }
1710
1745
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1711
1746
  const resolvedViteConfig = vitePreviewServer.config;
1712
1747
  const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1713
1748
  const workerConfigs = configPaths.map(
1714
1749
  (configPath) => unstable_readConfig({ config: configPath })
1715
1750
  );
1716
- const workers = workerConfigs.map((config) => {
1751
+ const workers = workerConfigs.flatMap((config) => {
1717
1752
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1718
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1719
- return {
1720
- ...workerOptions,
1721
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1722
- name: config.name,
1723
- modules: true,
1724
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1725
- };
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
+ ];
1726
1763
  });
1727
1764
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
1728
1765
  return {
@@ -7364,7 +7401,7 @@ var isAbsolute = function(p) {
7364
7401
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7365
7402
  import assert5 from "node:assert";
7366
7403
  import process$1 from "node:process";
7367
- import path4, { dirname as dirname3 } from "node:path";
7404
+ import path4, { dirname as dirname4 } from "node:path";
7368
7405
  import v8 from "node:v8";
7369
7406
  import { format as format2, inspect } from "node:util";
7370
7407
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -8713,6 +8750,8 @@ var { env } = defineEnv({
8713
8750
  nodeCompat: true,
8714
8751
  presets: [cloudflare]
8715
8752
  });
8753
+ var nodeCompatExternals = new Set(env.external);
8754
+ var nodeCompatEntries = getNodeCompatEntries();
8716
8755
  function isNodeCompat(workerConfig) {
8717
8756
  if (workerConfig === void 0) {
8718
8757
  return false;
@@ -8724,11 +8763,6 @@ function isNodeCompat(workerConfig) {
8724
8763
  if (nodeCompatMode === "v2") {
8725
8764
  return true;
8726
8765
  }
8727
- if (nodeCompatMode === "legacy") {
8728
- throw new Error(
8729
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8730
- );
8731
- }
8732
8766
  if (nodeCompatMode === "v1") {
8733
8767
  throw new Error(
8734
8768
  `Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`
@@ -8736,24 +8770,6 @@ function isNodeCompat(workerConfig) {
8736
8770
  }
8737
8771
  return false;
8738
8772
  }
8739
- function getNodeCompatEntries() {
8740
- const entries = new Set(Object.values(env.alias));
8741
- for (const globalInject of Object.values(env.inject)) {
8742
- if (typeof globalInject === "string") {
8743
- entries.add(globalInject);
8744
- } else {
8745
- assert6(
8746
- globalInject[0] !== void 0,
8747
- "Expected first element of globalInject to be defined"
8748
- );
8749
- entries.add(globalInject[0]);
8750
- }
8751
- }
8752
- for (const external of env.external) {
8753
- entries.delete(external);
8754
- }
8755
- return entries;
8756
- }
8757
8773
  function injectGlobalCode(id, code) {
8758
8774
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8759
8775
  if (typeof globalInject === "string") {
@@ -8779,9 +8795,6 @@ globalThis.${globalName} = var_${globalName}.${exportName};
8779
8795
  map: modified.generateMap({ hires: "boundary", source: id })
8780
8796
  };
8781
8797
  }
8782
- function getNodeCompatExternals() {
8783
- return env.external;
8784
- }
8785
8798
  function resolveNodeJSImport(source) {
8786
8799
  const alias = env.alias[source];
8787
8800
  if (alias) {
@@ -8790,6 +8803,28 @@ function resolveNodeJSImport(source) {
8790
8803
  resolved: resolvePathSync(alias, { url: import.meta.url })
8791
8804
  };
8792
8805
  }
8806
+ if (nodeCompatEntries.has(source)) {
8807
+ return {
8808
+ unresolved: source,
8809
+ resolved: resolvePathSync(source, { url: import.meta.url })
8810
+ };
8811
+ }
8812
+ }
8813
+ function getNodeCompatEntries() {
8814
+ const entries = new Set(Object.values(env.alias));
8815
+ for (const globalInject of Object.values(env.inject)) {
8816
+ if (typeof globalInject === "string") {
8817
+ entries.add(globalInject);
8818
+ } else {
8819
+ assert6(
8820
+ globalInject[0] !== void 0,
8821
+ "Expected first element of globalInject to be defined"
8822
+ );
8823
+ entries.add(globalInject[0]);
8824
+ }
8825
+ }
8826
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8827
+ return entries;
8793
8828
  }
8794
8829
 
8795
8830
  // src/plugin-config.ts
@@ -8834,7 +8869,6 @@ var nonApplicableWorkerConfigs = {
8834
8869
  "build",
8835
8870
  "find_additional_modules",
8836
8871
  "no_bundle",
8837
- "node_compat",
8838
8872
  "preserve_file_names",
8839
8873
  "site",
8840
8874
  "tsconfig",
@@ -8851,7 +8885,6 @@ var nullableNonApplicable = [
8851
8885
  "find_additional_modules",
8852
8886
  "minify",
8853
8887
  "no_bundle",
8854
- "node_compat",
8855
8888
  "preserve_file_names",
8856
8889
  "site",
8857
8890
  "tsconfig",
@@ -9102,9 +9135,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9102
9135
  }
9103
9136
 
9104
9137
  // src/websockets.ts
9105
- import ws from "ws";
9138
+ import { WebSocketServer } from "ws";
9106
9139
  function handleWebSocket(httpServer, fetcher, logger) {
9107
- const nodeWebSocket = new ws.Server({ noServer: true });
9140
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9108
9141
  httpServer.on(
9109
9142
  "upgrade",
9110
9143
  async (request, socket, head) => {
@@ -9213,7 +9246,7 @@ function cloudflare2(pluginConfig = {}) {
9213
9246
  }
9214
9247
  } : void 0,
9215
9248
  builder: {
9216
- async buildApp(builder) {
9249
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9217
9250
  const clientEnvironment = builder.environments.client;
9218
9251
  const defaultHtmlPath = path7.resolve(
9219
9252
  builder.config.root,
@@ -9239,7 +9272,7 @@ function cloudflare2(pluginConfig = {}) {
9239
9272
  )
9240
9273
  );
9241
9274
  }
9242
- }
9275
+ })
9243
9276
  }
9244
9277
  };
9245
9278
  },
@@ -9300,7 +9333,7 @@ function cloudflare2(pluginConfig = {}) {
9300
9333
  return;
9301
9334
  }
9302
9335
  config.no_bundle = true;
9303
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9336
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9304
9337
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9305
9338
  config.unsafe = void 0;
9306
9339
  }
@@ -9462,7 +9495,7 @@ function cloudflare2(pluginConfig = {}) {
9462
9495
  if (isNodeCompat(getWorkerConfig2(name2))) {
9463
9496
  return {
9464
9497
  resolve: {
9465
- builtins: getNodeCompatExternals()
9498
+ builtins: [...nodeCompatExternals]
9466
9499
  },
9467
9500
  optimizeDeps: {
9468
9501
  // This is a list of dependency entry-points that should be pre-bundled.
@@ -9470,7 +9503,8 @@ function cloudflare2(pluginConfig = {}) {
9470
9503
  // ready ahead the first request to the dev server.
9471
9504
  // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9472
9505
  // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9473
- include: [...getNodeCompatEntries()],
9506
+ // TODO: work out how to re-enable pre-bundling of these
9507
+ // include: [...getNodeCompatEntries()],
9474
9508
  // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9475
9509
  // 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.
9476
9510
  // Obviously we don't want/need the optimizer to try to process modules that are built-in;
@@ -9501,7 +9535,11 @@ function cloudflare2(pluginConfig = {}) {
9501
9535
  this.environment.depsOptimizer,
9502
9536
  "depsOptimizer is required in dev mode"
9503
9537
  );
9504
- return this.resolve(result.unresolved, importer, options);
9538
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9539
+ result.unresolved,
9540
+ result.resolved
9541
+ );
9542
+ return this.resolve(id, importer, options);
9505
9543
  }
9506
9544
  return this.resolve(result.resolved, importer, options);
9507
9545
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/vite-plugin",
3
- "version": "0.0.0-ed5ebdc4c",
3
+ "version": "0.0.0-edf169d15",
4
4
  "description": "Cloudflare plugin for Vite",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -35,12 +35,14 @@
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-ed5ebdc4c"
40
+ "ws": "8.18.0",
41
+ "miniflare": "0.0.0-edf169d15",
42
+ "wrangler": "0.0.0-edf169d15"
41
43
  },
42
44
  "devDependencies": {
43
- "@cloudflare/workers-types": "^4.20250214.0",
45
+ "@cloudflare/workers-types": "^4.20250310.0",
44
46
  "@types/node": "^22.10.1",
45
47
  "@types/ws": "^8.5.13",
46
48
  "magic-string": "^0.30.12",
@@ -50,10 +52,9 @@
50
52
  "undici": "^5.28.5",
51
53
  "vite": "^6.1.0",
52
54
  "vitest": "~3.0.5",
53
- "@cloudflare/mock-npm-registry": "0.0.0",
55
+ "@cloudflare/workers-shared": "0.0.0-edf169d15",
54
56
  "@cloudflare/workers-tsconfig": "0.0.0",
55
- "@cloudflare/workers-shared": "0.0.0-ed5ebdc4c",
56
- "wrangler": "0.0.0-ed5ebdc4c"
57
+ "@cloudflare/mock-npm-registry": "0.0.0"
57
58
  },
58
59
  "peerDependencies": {
59
60
  "vite": "^6.1.0",
@@ -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
  }