@cloudflare/vite-plugin 0.0.0-b391e0013 → 0.0.0-b48741547

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
@@ -1200,6 +1200,7 @@ var cloudflareBuiltInModules = [
1200
1200
  "cloudflare:workflows"
1201
1201
  ];
1202
1202
  var defaultConditions = ["workerd", "module", "browser"];
1203
+ var target = "es2022";
1203
1204
  function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1204
1205
  return {
1205
1206
  resolve: {
@@ -1220,7 +1221,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1220
1221
  createEnvironment(name2, config) {
1221
1222
  return new vite2.BuildEnvironment(name2, config);
1222
1223
  },
1223
- target: "es2022",
1224
+ target,
1224
1225
  // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1225
1226
  emitAssets: true,
1226
1227
  outDir: getOutputDirectory(userConfig, environmentName),
@@ -1241,6 +1242,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1241
1242
  exclude: [...cloudflareBuiltInModules],
1242
1243
  esbuildOptions: {
1243
1244
  platform: "neutral",
1245
+ target,
1244
1246
  conditions: [...defaultConditions, "development"],
1245
1247
  resolveExtensions: [
1246
1248
  ".mjs",
@@ -1370,6 +1372,7 @@ import {
1370
1372
  LogLevel,
1371
1373
  Response as MiniflareResponse
1372
1374
  } from "miniflare";
1375
+ import { globSync } from "tinyglobby";
1373
1376
  import "vite";
1374
1377
  import {
1375
1378
  unstable_getMiniflareWorkerOptions,
@@ -1551,7 +1554,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1551
1554
  }
1552
1555
  }
1553
1556
  ];
1554
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1557
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1555
1558
  ([environmentName, workerConfig]) => {
1556
1559
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1557
1560
  {
@@ -1560,51 +1563,58 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1560
1563
  },
1561
1564
  resolvedPluginConfig.cloudflareEnv
1562
1565
  );
1566
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1563
1567
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1564
1568
  return {
1565
- ...workerOptions,
1566
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1567
- name: workerConfig.name,
1568
- modulesRoot: miniflareModulesRoot,
1569
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1570
- bindings: {
1571
- ...workerOptions.bindings,
1572
- __VITE_ROOT__: resolvedViteConfig.root,
1573
- __VITE_ENTRY_PATH__: workerConfig.main
1574
- },
1575
- serviceBindings: {
1576
- ...workerOptions.serviceBindings,
1577
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1578
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1579
- } : {},
1580
- __VITE_INVOKE_MODULE__: async (request) => {
1581
- const payload = await request.json();
1582
- const invokePayloadData = payload.data;
1583
- assert4(
1584
- invokePayloadData.name === "fetchModule",
1585
- `Invalid invoke event: ${invokePayloadData.name}`
1586
- );
1587
- const [moduleId] = invokePayloadData.data;
1588
- const moduleRE = new RegExp(MODULE_PATTERN);
1589
- const shouldExternalize = (
1590
- // Worker modules (CompiledWasm, Text, Data)
1591
- moduleRE.test(moduleId)
1592
- );
1593
- if (shouldExternalize) {
1594
- const result2 = {
1595
- externalize: moduleId,
1596
- type: "module"
1597
- };
1598
- return MiniflareResponse.json({ result: result2 });
1569
+ externalWorkers: externalWorkers2,
1570
+ worker: {
1571
+ ...workerOptions,
1572
+ name: workerOptions.name ?? workerConfig.name,
1573
+ modulesRoot: miniflareModulesRoot,
1574
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1575
+ bindings: {
1576
+ ...workerOptions.bindings,
1577
+ __VITE_ROOT__: resolvedViteConfig.root,
1578
+ __VITE_ENTRY_PATH__: workerConfig.main
1579
+ },
1580
+ serviceBindings: {
1581
+ ...workerOptions.serviceBindings,
1582
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1583
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
1584
+ } : {},
1585
+ __VITE_INVOKE_MODULE__: async (request) => {
1586
+ const payload = await request.json();
1587
+ const invokePayloadData = payload.data;
1588
+ assert4(
1589
+ invokePayloadData.name === "fetchModule",
1590
+ `Invalid invoke event: ${invokePayloadData.name}`
1591
+ );
1592
+ const [moduleId] = invokePayloadData.data;
1593
+ const moduleRE = new RegExp(MODULE_PATTERN);
1594
+ const shouldExternalize = (
1595
+ // Worker modules (CompiledWasm, Text, Data)
1596
+ moduleRE.test(moduleId)
1597
+ );
1598
+ if (shouldExternalize) {
1599
+ const result2 = {
1600
+ externalize: moduleId,
1601
+ type: "module"
1602
+ };
1603
+ return MiniflareResponse.json({ result: result2 });
1604
+ }
1605
+ const devEnvironment = viteDevServer.environments[environmentName];
1606
+ const result = await devEnvironment.hot.handleInvoke(payload);
1607
+ return MiniflareResponse.json(result);
1599
1608
  }
1600
- const devEnvironment = viteDevServer.environments[environmentName];
1601
- const result = await devEnvironment.hot.handleInvoke(payload);
1602
- return MiniflareResponse.json(result);
1603
1609
  }
1604
1610
  }
1605
1611
  };
1606
1612
  }
1607
1613
  ) : [];
1614
+ const userWorkers = workersFromConfig.map((options) => options.worker);
1615
+ const externalWorkers = workersFromConfig.flatMap(
1616
+ (options) => options.externalWorkers
1617
+ );
1608
1618
  const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1609
1619
  const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1610
1620
  const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
@@ -1624,6 +1634,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1624
1634
  ),
1625
1635
  workers: [
1626
1636
  ...assetWorkers,
1637
+ ...externalWorkers,
1627
1638
  ...userWorkers.map((workerOptions) => {
1628
1639
  const wrappers = [
1629
1640
  `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
@@ -1656,7 +1667,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1656
1667
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1657
1668
  assert4(
1658
1669
  workflowEntrypointClassNames,
1659
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1670
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1660
1671
  );
1661
1672
  for (const className of [...workflowEntrypointClassNames].sort()) {
1662
1673
  wrappers.push(
@@ -1692,17 +1703,19 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1692
1703
  );
1693
1704
  const moduleRE = new RegExp(MODULE_PATTERN);
1694
1705
  const match = moduleRE.exec(rawSpecifier);
1695
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1706
+ assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1696
1707
  const [full, moduleType, modulePath] = match;
1697
1708
  assert4(
1698
1709
  modulePath,
1699
- `Unexpected error: module path not found in reference ${full}.`
1710
+ `Unexpected error: module path not found in reference: ${full}.`
1700
1711
  );
1701
1712
  let source;
1702
1713
  try {
1703
1714
  source = fs2.readFileSync(modulePath);
1704
1715
  } catch (error) {
1705
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1716
+ throw new Error(
1717
+ `Import "${modulePath}" not found. Does the file exist?`
1718
+ );
1706
1719
  }
1707
1720
  return MiniflareResponse.json({
1708
1721
  // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
@@ -1711,22 +1724,44 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1711
1724
  }
1712
1725
  };
1713
1726
  }
1727
+ function getPreviewModules(main, modulesRules) {
1728
+ assert4(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
1729
+ const rootPath = path3.dirname(main);
1730
+ const entryPath = path3.basename(main);
1731
+ return {
1732
+ rootPath,
1733
+ modules: [
1734
+ {
1735
+ type: "ESModule",
1736
+ path: entryPath
1737
+ },
1738
+ ...modulesRules.flatMap(
1739
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
1740
+ type,
1741
+ path: path8
1742
+ }))
1743
+ )
1744
+ ]
1745
+ };
1746
+ }
1714
1747
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1715
1748
  const resolvedViteConfig = vitePreviewServer.config;
1716
1749
  const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1717
1750
  const workerConfigs = configPaths.map(
1718
1751
  (configPath) => unstable_readConfig({ config: configPath })
1719
1752
  );
1720
- const workers = workerConfigs.map((config) => {
1753
+ const workers = workerConfigs.flatMap((config) => {
1721
1754
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1722
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1723
- return {
1724
- ...workerOptions,
1725
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1726
- name: config.name,
1727
- modules: true,
1728
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1729
- };
1755
+ const { externalWorkers } = miniflareWorkerOptions;
1756
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1757
+ return [
1758
+ {
1759
+ ...workerOptions,
1760
+ name: workerOptions.name ?? config.name,
1761
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
1762
+ },
1763
+ ...externalWorkers
1764
+ ];
1730
1765
  });
1731
1766
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
1732
1767
  return {
@@ -7368,7 +7403,7 @@ var isAbsolute = function(p) {
7368
7403
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7369
7404
  import assert5 from "node:assert";
7370
7405
  import process$1 from "node:process";
7371
- import path4, { dirname as dirname3 } from "node:path";
7406
+ import path4, { dirname as dirname4 } from "node:path";
7372
7407
  import v8 from "node:v8";
7373
7408
  import { format as format2, inspect } from "node:util";
7374
7409
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -7500,14 +7535,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7500
7535
  * @param {boolean} [isImport=false]
7501
7536
  * @param {string} [base]
7502
7537
  */
7503
- (packagePath, key, target, isImport = false, base = void 0) => {
7504
- const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
7538
+ (packagePath, key, target2, isImport = false, base = void 0) => {
7539
+ const relatedError = typeof target2 === "string" && !isImport && target2.length > 0 && !target2.startsWith("./");
7505
7540
  if (key === ".") {
7506
7541
  assert5(isImport === false);
7507
- return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7542
+ return `Invalid "exports" main target ${JSON.stringify(target2)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7508
7543
  }
7509
7544
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7510
- target
7545
+ target2
7511
7546
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7512
7547
  },
7513
7548
  Error
@@ -7903,14 +7938,14 @@ var patternRegEx = /\*/g;
7903
7938
  var encodedSeparatorRegEx = /%2f|%5c/i;
7904
7939
  var emittedPackageWarnings = /* @__PURE__ */ new Set();
7905
7940
  var doubleSlashRegEx = /[/\\]{2}/;
7906
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7941
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7907
7942
  if (process$1.noDeprecation) {
7908
7943
  return;
7909
7944
  }
7910
7945
  const pjsonPath = fileURLToPath$1(packageJsonUrl);
7911
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7946
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7912
7947
  process$1.emitWarning(
7913
- `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7948
+ `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target2}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7914
7949
  "DeprecationWarning",
7915
7950
  "DEP0166"
7916
7951
  );
@@ -8068,47 +8103,47 @@ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8068
8103
  base && fileURLToPath$1(base)
8069
8104
  );
8070
8105
  }
8071
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8072
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
8106
+ function invalidPackageTarget(subpath, target2, packageJsonUrl, internal, base) {
8107
+ target2 = typeof target2 === "object" && target2 !== null ? JSON.stringify(target2, null, "") : `${target2}`;
8073
8108
  return new ERR_INVALID_PACKAGE_TARGET(
8074
8109
  fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8075
8110
  subpath,
8076
- target,
8111
+ target2,
8077
8112
  internal,
8078
8113
  base && fileURLToPath$1(base)
8079
8114
  );
8080
8115
  }
8081
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8082
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8083
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8084
- if (!target.startsWith("./")) {
8085
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
8116
+ function resolvePackageTargetString(target2, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8117
+ if (subpath !== "" && !pattern && target2[target2.length - 1] !== "/")
8118
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8119
+ if (!target2.startsWith("./")) {
8120
+ if (internal && !target2.startsWith("../") && !target2.startsWith("/")) {
8086
8121
  let isURL = false;
8087
8122
  try {
8088
- new URL$1(target);
8123
+ new URL$1(target2);
8089
8124
  isURL = true;
8090
8125
  } catch {
8091
8126
  }
8092
8127
  if (!isURL) {
8093
8128
  const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8094
8129
  patternRegEx,
8095
- target,
8130
+ target2,
8096
8131
  () => subpath
8097
- ) : target + subpath;
8132
+ ) : target2 + subpath;
8098
8133
  return packageResolve(exportTarget, packageJsonUrl, conditions);
8099
8134
  }
8100
8135
  }
8101
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8136
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8102
8137
  }
8103
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8104
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8138
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
8139
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
8105
8140
  if (!isPathMap) {
8106
8141
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8107
8142
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8108
8143
  patternRegEx,
8109
- target,
8144
+ target2,
8110
8145
  () => subpath
8111
- ) : target;
8146
+ ) : target2;
8112
8147
  emitInvalidSegmentDeprecation(
8113
8148
  resolvedTarget,
8114
8149
  request,
@@ -8120,14 +8155,14 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8120
8155
  );
8121
8156
  }
8122
8157
  } else {
8123
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8158
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8124
8159
  }
8125
8160
  }
8126
- const resolved = new URL$1(target, packageJsonUrl);
8161
+ const resolved = new URL$1(target2, packageJsonUrl);
8127
8162
  const resolvedPath = resolved.pathname;
8128
8163
  const packagePath = new URL$1(".", packageJsonUrl).pathname;
8129
8164
  if (!resolvedPath.startsWith(packagePath))
8130
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8165
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8131
8166
  if (subpath === "") return resolved;
8132
8167
  if (invalidSegmentRegEx.exec(subpath) !== null) {
8133
8168
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
@@ -8135,9 +8170,9 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8135
8170
  if (!isPathMap) {
8136
8171
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8137
8172
  patternRegEx,
8138
- target,
8173
+ target2,
8139
8174
  () => subpath
8140
- ) : target;
8175
+ ) : target2;
8141
8176
  emitInvalidSegmentDeprecation(
8142
8177
  resolvedTarget,
8143
8178
  request,
@@ -8168,10 +8203,10 @@ function isArrayIndex(key) {
8168
8203
  if (`${keyNumber}` !== key) return false;
8169
8204
  return keyNumber >= 0 && keyNumber < 4294967295;
8170
8205
  }
8171
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8172
- if (typeof target === "string") {
8206
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8207
+ if (typeof target2 === "string") {
8173
8208
  return resolvePackageTargetString(
8174
- target,
8209
+ target2,
8175
8210
  subpath,
8176
8211
  packageSubpath,
8177
8212
  packageJsonUrl,
@@ -8182,8 +8217,8 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8182
8217
  conditions
8183
8218
  );
8184
8219
  }
8185
- if (Array.isArray(target)) {
8186
- const targetList = target;
8220
+ if (Array.isArray(target2)) {
8221
+ const targetList = target2;
8187
8222
  if (targetList.length === 0) return null;
8188
8223
  let lastException;
8189
8224
  let i = -1;
@@ -8223,8 +8258,8 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8223
8258
  }
8224
8259
  throw lastException;
8225
8260
  }
8226
- if (typeof target === "object" && target !== null) {
8227
- const keys = Object.getOwnPropertyNames(target);
8261
+ if (typeof target2 === "object" && target2 !== null) {
8262
+ const keys = Object.getOwnPropertyNames(target2);
8228
8263
  let i = -1;
8229
8264
  while (++i < keys.length) {
8230
8265
  const key = keys[i];
@@ -8242,7 +8277,7 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8242
8277
  if (key === "default" || conditions && conditions.has(key)) {
8243
8278
  const conditionalTarget = (
8244
8279
  /** @type {unknown} */
8245
- target[key]
8280
+ target2[key]
8246
8281
  );
8247
8282
  const resolveResult = resolvePackageTarget(
8248
8283
  packageJsonUrl,
@@ -8261,12 +8296,12 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8261
8296
  }
8262
8297
  return null;
8263
8298
  }
8264
- if (target === null) {
8299
+ if (target2 === null) {
8265
8300
  return null;
8266
8301
  }
8267
8302
  throw invalidPackageTarget(
8268
8303
  packageSubpath,
8269
- target,
8304
+ target2,
8270
8305
  packageJsonUrl,
8271
8306
  internal,
8272
8307
  base
@@ -8313,10 +8348,10 @@ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, ba
8313
8348
  exports = { ".": exports };
8314
8349
  }
8315
8350
  if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8316
- const target = exports[packageSubpath];
8351
+ const target2 = exports[packageSubpath];
8317
8352
  const resolveResult = resolvePackageTarget(
8318
8353
  packageJsonUrl,
8319
- target,
8354
+ target2,
8320
8355
  "",
8321
8356
  packageSubpath,
8322
8357
  base,
@@ -8356,13 +8391,13 @@ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, ba
8356
8391
  }
8357
8392
  }
8358
8393
  if (bestMatch) {
8359
- const target = (
8394
+ const target2 = (
8360
8395
  /** @type {unknown} */
8361
8396
  exports[bestMatch]
8362
8397
  );
8363
8398
  const resolveResult = resolvePackageTarget(
8364
8399
  packageJsonUrl,
8365
- target,
8400
+ target2,
8366
8401
  bestMatchSubpath,
8367
8402
  bestMatch,
8368
8403
  base,
@@ -8437,10 +8472,10 @@ function packageImportsResolve(name2, base, conditions) {
8437
8472
  }
8438
8473
  }
8439
8474
  if (bestMatch) {
8440
- const target = imports[bestMatch];
8475
+ const target2 = imports[bestMatch];
8441
8476
  const resolveResult = resolvePackageTarget(
8442
8477
  packageJsonUrl,
8443
- target,
8478
+ target2,
8444
8479
  bestMatchSubpath,
8445
8480
  bestMatch,
8446
8481
  base,
@@ -8730,11 +8765,6 @@ function isNodeCompat(workerConfig) {
8730
8765
  if (nodeCompatMode === "v2") {
8731
8766
  return true;
8732
8767
  }
8733
- if (nodeCompatMode === "legacy") {
8734
- throw new Error(
8735
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8736
- );
8737
- }
8738
8768
  if (nodeCompatMode === "v1") {
8739
8769
  throw new Error(
8740
8770
  `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`
@@ -8841,7 +8871,6 @@ var nonApplicableWorkerConfigs = {
8841
8871
  "build",
8842
8872
  "find_additional_modules",
8843
8873
  "no_bundle",
8844
- "node_compat",
8845
8874
  "preserve_file_names",
8846
8875
  "site",
8847
8876
  "tsconfig",
@@ -8858,7 +8887,6 @@ var nullableNonApplicable = [
8858
8887
  "find_additional_modules",
8859
8888
  "minify",
8860
8889
  "no_bundle",
8861
- "node_compat",
8862
8890
  "preserve_file_names",
8863
8891
  "site",
8864
8892
  "tsconfig",
@@ -9009,6 +9037,17 @@ function getWorkerConfig(configPath, env2, opts) {
9009
9037
  };
9010
9038
  }
9011
9039
  assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9040
+ const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9041
+ if (!mainStat) {
9042
+ throw new Error(
9043
+ `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
9044
+ );
9045
+ }
9046
+ if (mainStat.isDirectory()) {
9047
+ throw new Error(
9048
+ `The provided Wrangler config main field (${config.main}) points to a directory, it needs to point to a file instead`
9049
+ );
9050
+ }
9012
9051
  return {
9013
9052
  type: "worker",
9014
9053
  raw,
@@ -9109,8 +9148,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9148
  }
9110
9149
 
9111
9150
  // src/websockets.ts
9151
+ import { coupleWebSocket } from "miniflare";
9112
9152
  import { WebSocketServer } from "ws";
9113
- function handleWebSocket(httpServer, fetcher, logger) {
9153
+ function handleWebSocket(httpServer, fetcher) {
9114
9154
  const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9155
  httpServer.on(
9116
9156
  "upgrade",
@@ -9134,34 +9174,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9134
9174
  socket,
9135
9175
  head,
9136
9176
  async (clientWebSocket) => {
9137
- workerWebSocket.accept();
9138
- workerWebSocket.addEventListener("message", (event) => {
9139
- clientWebSocket.send(event.data);
9140
- });
9141
- workerWebSocket.addEventListener("error", (event) => {
9142
- logger.error(
9143
- `WebSocket error:
9144
- ${event.error?.stack || event.error?.message}`,
9145
- { error: event.error }
9146
- );
9147
- });
9148
- workerWebSocket.addEventListener("close", () => {
9149
- clientWebSocket.close();
9150
- });
9151
- clientWebSocket.on("message", (data2, isBinary) => {
9152
- workerWebSocket.send(
9153
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9154
- );
9155
- });
9156
- clientWebSocket.on("error", (error) => {
9157
- logger.error(`WebSocket error:
9158
- ${error.stack || error.message}`, {
9159
- error
9160
- });
9161
- });
9162
- clientWebSocket.on("close", () => {
9163
- workerWebSocket.close();
9164
- });
9177
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9165
9178
  nodeWebSocket.emit("connection", clientWebSocket, request);
9166
9179
  }
9167
9180
  );
@@ -9307,7 +9320,7 @@ function cloudflare2(pluginConfig = {}) {
9307
9320
  return;
9308
9321
  }
9309
9322
  config.no_bundle = true;
9310
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9323
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9311
9324
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9312
9325
  config.unsafe = void 0;
9313
9326
  }
@@ -9354,11 +9367,7 @@ function cloudflare2(pluginConfig = {}) {
9354
9367
  },
9355
9368
  { alwaysCallNext: false }
9356
9369
  );
9357
- handleWebSocket(
9358
- viteDevServer.httpServer,
9359
- entryWorker.fetch,
9360
- viteDevServer.config.logger
9361
- );
9370
+ handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9362
9371
  return () => {
9363
9372
  viteDevServer.middlewares.use((req, res, next) => {
9364
9373
  middleware(req, res, next);
@@ -9380,16 +9389,10 @@ function cloudflare2(pluginConfig = {}) {
9380
9389
  },
9381
9390
  { alwaysCallNext: false }
9382
9391
  );
9383
- handleWebSocket(
9384
- vitePreviewServer.httpServer,
9385
- miniflare2.dispatchFetch,
9386
- vitePreviewServer.config.logger
9387
- );
9388
- return () => {
9389
- vitePreviewServer.middlewares.use((req, res, next) => {
9390
- middleware(req, res, next);
9391
- });
9392
- };
9392
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9393
+ vitePreviewServer.middlewares.use((req, res, next) => {
9394
+ middleware(req, res, next);
9395
+ });
9393
9396
  }
9394
9397
  },
9395
9398
  // Plugin to support `CompiledWasm` modules
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/vite-plugin",
3
- "version": "0.0.0-b391e0013",
3
+ "version": "0.0.0-b48741547",
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
40
  "ws": "8.18.0",
40
- "miniflare": "0.0.0-b391e0013"
41
+ "miniflare": "0.0.0-b48741547",
42
+ "wrangler": "0.0.0-b48741547"
41
43
  },
42
44
  "devDependencies": {
43
- "@cloudflare/workers-types": "^4.20250214.0",
45
+ "@cloudflare/workers-types": "^4.20250317.0",
44
46
  "@types/node": "^22.10.1",
45
47
  "@types/ws": "^8.5.13",
46
48
  "magic-string": "^0.30.12",
@@ -51,13 +53,12 @@
51
53
  "vite": "^6.1.0",
52
54
  "vitest": "~3.0.5",
53
55
  "@cloudflare/mock-npm-registry": "0.0.0",
54
- "wrangler": "0.0.0-b391e0013",
55
56
  "@cloudflare/workers-tsconfig": "0.0.0",
56
- "@cloudflare/workers-shared": "0.0.0-b391e0013"
57
+ "@cloudflare/workers-shared": "0.0.0-b48741547"
57
58
  },
58
59
  "peerDependencies": {
59
60
  "vite": "^6.1.0",
60
- "wrangler": "^3.101.0"
61
+ "wrangler": "^3.101.0 || ^4.0.0"
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
  }