@cloudflare/vite-plugin 0.1.19 → 0.1.21

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/README.md CHANGED
@@ -376,7 +376,7 @@ It accepts an optional `PluginConfig` parameter.
376
376
 
377
377
  - `inspectorPort?: number | false`
378
378
 
379
- Optional inspector port to use for debugging your workers, for more details on debugging see the [devtools section](#devtools). Can be set to `false` to disable the debugging inspector altogether. Defaults to `9229`.
379
+ Optional inspector port to use for debugging your workers, for more details on debugging see the [devtools section](#devtools). By default the vite plugin will attempt to use the first available port it can find starting at `9229`.
380
380
 
381
381
  > [!NOTE]
382
382
  > When running `wrangler deploy`, only your main (entry) Worker will be deployed.
package/dist/index.js CHANGED
@@ -485,7 +485,7 @@ var require_mime = __commonJS({
485
485
  });
486
486
 
487
487
  // src/index.ts
488
- import assert8 from "node:assert";
488
+ import assert10 from "node:assert";
489
489
  import * as fs5 from "node:fs";
490
490
  import * as fsp2 from "node:fs/promises";
491
491
  import * as path9 from "node:path";
@@ -1557,6 +1557,7 @@ var MagicString = class _MagicString {
1557
1557
 
1558
1558
  // src/index.ts
1559
1559
  import { Miniflare } from "miniflare";
1560
+ import colors2 from "picocolors";
1560
1561
  import * as vite7 from "vite";
1561
1562
 
1562
1563
  // src/constants.ts
@@ -12939,8 +12940,9 @@ function getNodeCompatEntries() {
12939
12940
  return entries;
12940
12941
  }
12941
12942
  var NodeJsCompatWarnings = class {
12942
- constructor(environment) {
12943
- this.environment = environment;
12943
+ constructor(environmentName, resolvedViteConfig) {
12944
+ this.environmentName = environmentName;
12945
+ this.resolvedViteConfig = resolvedViteConfig;
12944
12946
  }
12945
12947
  sources = /* @__PURE__ */ new Map();
12946
12948
  timer;
@@ -12948,6 +12950,7 @@ var NodeJsCompatWarnings = class {
12948
12950
  const importers = this.sources.get(source) ?? /* @__PURE__ */ new Set();
12949
12951
  this.sources.set(source, importers);
12950
12952
  importers.add(importer);
12953
+ this.renderWarningsOnIdle();
12951
12954
  }
12952
12955
  renderWarningsOnIdle() {
12953
12956
  if (this.timer) {
@@ -12960,19 +12963,16 @@ var NodeJsCompatWarnings = class {
12960
12963
  }
12961
12964
  renderWarnings() {
12962
12965
  if (this.sources.size > 0) {
12963
- let message = `
12964
-
12965
- Unexpected Node.js imports for environment "${this.environment.name}". Do you need to enable the "nodejs_compat" compatibility flag?
12966
- Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.
12966
+ let message = `Unexpected Node.js imports for environment "${this.environmentName}". Do you need to enable the "nodejs_compat" compatibility flag? Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.
12967
12967
  `;
12968
12968
  this.sources.forEach((importers, source) => {
12969
12969
  importers.forEach((importer) => {
12970
- message += ` - "${source}" imported from "${path3.relative(this.environment.config.root, importer)}"
12970
+ message += ` - "${source}" imported from "${path3.relative(this.resolvedViteConfig.root, importer)}"
12971
12971
  `;
12972
12972
  });
12973
12973
  });
12974
- this.environment.logger.warn(message, {
12975
- environment: this.environment.name
12974
+ this.resolvedViteConfig.logger.warn(message, {
12975
+ timestamp: true
12976
12976
  });
12977
12977
  this.sources.clear();
12978
12978
  }
@@ -12992,6 +12992,7 @@ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
12992
12992
 
12993
12993
  // src/utils.ts
12994
12994
  import * as path4 from "node:path";
12995
+ import getPort, { portNumbers } from "get-port";
12995
12996
  import { Request as MiniflareRequest } from "miniflare";
12996
12997
  import "vite";
12997
12998
  function getOutputDirectory(userConfig, environmentName) {
@@ -13034,6 +13035,9 @@ var postfixRE = /[?#].*$/;
13034
13035
  function cleanUrl(url) {
13035
13036
  return url.replace(postfixRE, "");
13036
13037
  }
13038
+ function getFirstAvailablePort(start) {
13039
+ return getPort({ port: portNumbers(start, 65535) });
13040
+ }
13037
13041
 
13038
13042
  // src/cloudflare-environment.ts
13039
13043
  var webSocketUndefinedError = "The WebSocket is undefined";
@@ -13444,7 +13448,7 @@ function getEntryWorkerConfig(resolvedPluginConfig) {
13444
13448
  }
13445
13449
  return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
13446
13450
  }
13447
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13451
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspectorPort) {
13448
13452
  const resolvedViteConfig = viteDevServer.config;
13449
13453
  const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
13450
13454
  const assetsConfig = getAssetsConfig(
@@ -13536,7 +13540,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13536
13540
  worker: {
13537
13541
  ...workerOptions,
13538
13542
  name: workerOptions.name ?? workerConfig.name,
13539
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13543
+ unsafeInspectorProxy: inspectorPort !== false,
13540
13544
  modulesRoot: miniflareModulesRoot,
13541
13545
  unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
13542
13546
  serviceBindings: {
@@ -13578,8 +13582,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13578
13582
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13579
13583
  return {
13580
13584
  log: logger,
13581
- inspectorPort: resolvedPluginConfig.inspectorPort || void 0,
13582
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13585
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13586
+ unsafeInspectorProxy: inspectorPort !== false,
13583
13587
  handleRuntimeStdio(stdout, stderr) {
13584
13588
  const decoder = new TextDecoder();
13585
13589
  stdout.forEach((data2) => logger.info(decoder.decode(data2)));
@@ -13716,7 +13720,7 @@ function getPreviewModules(main, modulesRules) {
13716
13720
  ]
13717
13721
  };
13718
13722
  }
13719
- function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort = DEFAULT_INSPECTOR_PORT) {
13723
+ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort) {
13720
13724
  const resolvedViteConfig = vitePreviewServer.config;
13721
13725
  const workers = workerConfigs.flatMap((config) => {
13722
13726
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
@@ -13735,7 +13739,7 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13735
13739
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13736
13740
  return {
13737
13741
  log: logger,
13738
- inspectorPort: inspectorPort || void 0,
13742
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13739
13743
  unsafeInspectorProxy: inspectorPort !== false,
13740
13744
  handleRuntimeStdio(stdout, stderr) {
13741
13745
  const decoder = new TextDecoder();
@@ -13785,11 +13789,12 @@ function miniflareLogLevelFromViteLogLevel(level = "info") {
13785
13789
  }
13786
13790
 
13787
13791
  // src/plugin-config.ts
13788
- import assert7 from "node:assert";
13792
+ import assert8 from "node:assert";
13789
13793
  import * as path8 from "node:path";
13790
13794
  import * as vite6 from "vite";
13791
13795
 
13792
13796
  // src/workers-configs.ts
13797
+ import assert7 from "node:assert";
13793
13798
  import * as fs4 from "node:fs";
13794
13799
  import * as path7 from "node:path";
13795
13800
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
@@ -13823,8 +13828,7 @@ var nonApplicableWorkerConfigs = {
13823
13828
  "preserve_file_names",
13824
13829
  "rules",
13825
13830
  "site",
13826
- "tsconfig",
13827
- "upload_source_maps"
13831
+ "tsconfig"
13828
13832
  ]
13829
13833
  };
13830
13834
  var nullableNonApplicable = [
@@ -13835,8 +13839,7 @@ var nullableNonApplicable = [
13835
13839
  "no_bundle",
13836
13840
  "preserve_file_names",
13837
13841
  "site",
13838
- "tsconfig",
13839
- "upload_source_maps"
13842
+ "tsconfig"
13840
13843
  ];
13841
13844
  function readWorkerConfig(configPath, env2) {
13842
13845
  const nonApplicable = {
@@ -13998,14 +14001,52 @@ function getWorkerConfig(configPath, env2, opts) {
13998
14001
  nonApplicable
13999
14002
  };
14000
14003
  }
14004
+ function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
14005
+ if (requestedConfigPath) {
14006
+ const configPath2 = path7.resolve(root, requestedConfigPath);
14007
+ const forAuxiliaryWorkerErrorMessage = isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : "";
14008
+ const errorMessagePrefix = `The provided configPath (${configPath2})${forAuxiliaryWorkerErrorMessage}`;
14009
+ const fileExtension = path7.extname(configPath2).slice(1);
14010
+ if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
14011
+ const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
14012
+ throw new Error(
14013
+ `${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`
14014
+ );
14015
+ }
14016
+ const mainStat = fs4.statSync(configPath2, { throwIfNoEntry: false });
14017
+ if (!mainStat) {
14018
+ throw new Error(
14019
+ `${errorMessagePrefix} doesn't point to an existing file`
14020
+ );
14021
+ }
14022
+ if (mainStat.isDirectory()) {
14023
+ throw new Error(
14024
+ `${errorMessagePrefix} points to a directory. It should point to a file.`
14025
+ );
14026
+ }
14027
+ return configPath2;
14028
+ }
14029
+ assert7(
14030
+ isForAuxiliaryWorker === false,
14031
+ "Unexpected Error: trying to find the wrangler config for an auxiliary worker"
14032
+ );
14033
+ const configPath = findWranglerConfig(root);
14034
+ if (!configPath) {
14035
+ throw new Error(
14036
+ `No config file found in the ${root} directory. Please add a wrangler.(jsonc|json|toml) file.`
14037
+ );
14038
+ }
14039
+ return configPath;
14040
+ }
14001
14041
  function findWranglerConfig(root) {
14002
- for (const extension of ["json", "jsonc", "toml"]) {
14042
+ for (const extension of allowedWranglerConfigExtensions) {
14003
14043
  const configPath = path7.join(root, `wrangler.${extension}`);
14004
14044
  if (fs4.existsSync(configPath)) {
14005
14045
  return configPath;
14006
14046
  }
14007
14047
  }
14008
14048
  }
14049
+ var allowedWranglerConfigExtensions = ["jsonc", "json", "toml"];
14009
14050
 
14010
14051
  // src/plugin-config.ts
14011
14052
  function workerNameToEnvironmentName(workerName) {
@@ -14014,7 +14055,6 @@ function workerNameToEnvironmentName(workerName) {
14014
14055
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14015
14056
  const configPaths = /* @__PURE__ */ new Set();
14016
14057
  const persistState = pluginConfig.persistState ?? true;
14017
- const inspectorPort = pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT;
14018
14058
  const experimental = pluginConfig.experimental ?? {};
14019
14059
  const root = userConfig.root ? path8.resolve(userConfig.root) : process.cwd();
14020
14060
  const { CLOUDFLARE_ENV: cloudflareEnv } = vite6.loadEnv(
@@ -14023,22 +14063,23 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14023
14063
  /* prefixes */
14024
14064
  ""
14025
14065
  );
14026
- const configPath = pluginConfig.configPath ? path8.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
14027
- if (!configPath) {
14028
- throw new Error(
14029
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
14030
- );
14031
- }
14032
- const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
14033
- visitedConfigPaths: configPaths,
14034
- isEntryWorker: true
14035
- });
14066
+ const entryWorkerConfigPath = getValidatedWranglerConfigPath(
14067
+ root,
14068
+ pluginConfig.configPath
14069
+ );
14070
+ const entryWorkerResolvedConfig = getWorkerConfig(
14071
+ entryWorkerConfigPath,
14072
+ cloudflareEnv,
14073
+ {
14074
+ visitedConfigPaths: configPaths,
14075
+ isEntryWorker: true
14076
+ }
14077
+ );
14036
14078
  if (entryWorkerResolvedConfig.type === "assets-only") {
14037
14079
  return {
14038
14080
  type: "assets-only",
14039
14081
  config: entryWorkerResolvedConfig.config,
14040
14082
  configPaths,
14041
- inspectorPort,
14042
14083
  persistState,
14043
14084
  rawConfigs: {
14044
14085
  entryWorker: entryWorkerResolvedConfig
@@ -14054,15 +14095,20 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14054
14095
  };
14055
14096
  const auxiliaryWorkersResolvedConfigs = [];
14056
14097
  for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
14098
+ const workerConfigPath = getValidatedWranglerConfigPath(
14099
+ root,
14100
+ auxiliaryWorker.configPath,
14101
+ true
14102
+ );
14057
14103
  const workerResolvedConfig = getWorkerConfig(
14058
- path8.resolve(root, auxiliaryWorker.configPath),
14104
+ workerConfigPath,
14059
14105
  cloudflareEnv,
14060
14106
  {
14061
14107
  visitedConfigPaths: configPaths
14062
14108
  }
14063
14109
  );
14064
14110
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
14065
- assert7(
14111
+ assert8(
14066
14112
  workerResolvedConfig.type === "worker",
14067
14113
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
14068
14114
  );
@@ -14079,7 +14125,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14079
14125
  type: "workers",
14080
14126
  configPaths,
14081
14127
  persistState,
14082
- inspectorPort,
14083
14128
  workers,
14084
14129
  entryWorkerEnvironmentName,
14085
14130
  rawConfigs: {
@@ -14127,6 +14172,54 @@ function handleWebSocket(httpServer, getFetcher) {
14127
14172
  );
14128
14173
  }
14129
14174
 
14175
+ // src/worker-environments-validation.ts
14176
+ import assert9 from "node:assert";
14177
+ function validateWorkerEnvironmentsResolvedConfigs(resolvedPluginConfig, resolvedViteConfig) {
14178
+ const workersEnvironmentNames = Object.keys(resolvedPluginConfig.workers);
14179
+ const disallowedEnvsConfigs = /* @__PURE__ */ new Map();
14180
+ for (const envName of workersEnvironmentNames) {
14181
+ const workerEnvConfig = resolvedViteConfig.environments[envName];
14182
+ assert9(workerEnvConfig, `Missing environment config for "${envName}"`);
14183
+ const { optimizeDeps, resolve: resolve8 } = workerEnvConfig;
14184
+ const disallowedConfig = {};
14185
+ const disallowedOptimizeDepsExcludeEntries = (optimizeDeps.exclude ?? []).filter((entry) => {
14186
+ if (cloudflareBuiltInModules.includes(entry)) {
14187
+ return false;
14188
+ }
14189
+ if (NODEJS_MODULES_RE.test(entry) && isNodeCompat(resolvedPluginConfig.workers[envName])) {
14190
+ return false;
14191
+ }
14192
+ return true;
14193
+ });
14194
+ if (disallowedOptimizeDepsExcludeEntries.length > 0) {
14195
+ disallowedConfig.optimizeDepsExclude = disallowedOptimizeDepsExcludeEntries;
14196
+ }
14197
+ if (resolve8.external === true || resolve8.external.length > 0) {
14198
+ disallowedConfig.resolveExternal = resolve8.external;
14199
+ }
14200
+ if (Object.keys(disallowedConfig).length > 0) {
14201
+ disallowedEnvsConfigs.set(envName, disallowedConfig);
14202
+ }
14203
+ }
14204
+ if (disallowedEnvsConfigs.size > 0) {
14205
+ const errorMessage = `The following environment configurations are incompatible with the Cloudflare Vite plugin:
14206
+ ${[
14207
+ ...disallowedEnvsConfigs
14208
+ ].map(
14209
+ ([envName, disallowedConfig]) => [
14210
+ disallowedConfig.optimizeDepsExclude ? ` - "${envName}" environment: \`optimizeDeps.exclude\`: ${JSON.stringify(disallowedConfig.optimizeDepsExclude)}
14211
+ ` : null,
14212
+ disallowedConfig.resolveExternal ? ` - "${envName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedConfig.resolveExternal)}
14213
+ ` : null
14214
+ ].join("")
14215
+ ).join(
14216
+ ""
14217
+ )}To resolve this issue, avoid setting \`optimizeDeps.exclude\` and \`resolve.external\` in your Cloudflare Worker environments.
14218
+ `;
14219
+ throw new Error(errorMessage);
14220
+ }
14221
+ }
14222
+
14130
14223
  // src/index.ts
14131
14224
  var workersConfigsWarningShown = false;
14132
14225
  var miniflare;
@@ -14197,7 +14290,7 @@ function cloudflare2(pluginConfig = {}) {
14197
14290
  resolvedPluginConfig.workers
14198
14291
  ).map((environmentName) => {
14199
14292
  const environment = builder.environments[environmentName];
14200
- assert8(
14293
+ assert10(
14201
14294
  environment,
14202
14295
  `${environmentName} environment not found`
14203
14296
  );
@@ -14218,6 +14311,12 @@ function cloudflare2(pluginConfig = {}) {
14218
14311
  },
14219
14312
  configResolved(config) {
14220
14313
  resolvedViteConfig = config;
14314
+ if (resolvedPluginConfig?.type === "workers") {
14315
+ validateWorkerEnvironmentsResolvedConfigs(
14316
+ resolvedPluginConfig,
14317
+ resolvedViteConfig
14318
+ );
14319
+ }
14221
14320
  },
14222
14321
  generateBundle(_, bundle) {
14223
14322
  let config;
@@ -14238,7 +14337,7 @@ function cloudflare2(pluginConfig = {}) {
14238
14337
  if (isEntryWorker && hasClientBuild) {
14239
14338
  const workerOutputDirectory = this.environment.config.build.outDir;
14240
14339
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
14241
- assert8(
14340
+ assert10(
14242
14341
  clientOutputDirectory,
14243
14342
  "Unexpected error: client output directory is undefined"
14244
14343
  );
@@ -14315,23 +14414,36 @@ function cloudflare2(pluginConfig = {}) {
14315
14414
  }
14316
14415
  },
14317
14416
  async configureServer(viteDevServer) {
14318
- assert8(
14417
+ assert10(
14319
14418
  viteDevServer.httpServer,
14320
14419
  "Unexpected error: No Vite HTTP server"
14321
14420
  );
14322
- if (miniflare) {
14323
- await miniflare.setOptions(
14324
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14421
+ if (!miniflare) {
14422
+ const inputInspectorPort = await getInputInspectorPortOption(
14423
+ pluginConfig,
14424
+ viteDevServer
14325
14425
  );
14326
- } else {
14327
14426
  miniflare = new Miniflare(
14328
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14427
+ getDevMiniflareOptions(
14428
+ resolvedPluginConfig,
14429
+ viteDevServer,
14430
+ inputInspectorPort
14431
+ )
14432
+ );
14433
+ } else {
14434
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14435
+ await miniflare.setOptions(
14436
+ getDevMiniflareOptions(
14437
+ resolvedPluginConfig,
14438
+ viteDevServer,
14439
+ resolvedInspectorPort ?? false
14440
+ )
14329
14441
  );
14330
14442
  }
14331
14443
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14332
14444
  const middleware = createMiddleware(
14333
14445
  async ({ request }) => {
14334
- assert8(miniflare, `Miniflare not defined`);
14446
+ assert10(miniflare, `Miniflare not defined`);
14335
14447
  const routerWorker = await getRouterWorker(miniflare);
14336
14448
  return routerWorker.fetch(toMiniflareRequest(request), {
14337
14449
  redirect: "manual"
@@ -14340,7 +14452,7 @@ function cloudflare2(pluginConfig = {}) {
14340
14452
  { alwaysCallNext: false }
14341
14453
  );
14342
14454
  handleWebSocket(viteDevServer.httpServer, async () => {
14343
- assert8(miniflare, `Miniflare not defined`);
14455
+ assert10(miniflare, `Miniflare not defined`);
14344
14456
  const routerWorker = await getRouterWorker(miniflare);
14345
14457
  return routerWorker.fetch;
14346
14458
  });
@@ -14350,14 +14462,18 @@ function cloudflare2(pluginConfig = {}) {
14350
14462
  });
14351
14463
  };
14352
14464
  },
14353
- configurePreviewServer(vitePreviewServer) {
14465
+ async configurePreviewServer(vitePreviewServer) {
14354
14466
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14467
+ const inputInspectorPort = await getInputInspectorPortOption(
14468
+ pluginConfig,
14469
+ vitePreviewServer
14470
+ );
14355
14471
  const miniflare2 = new Miniflare(
14356
14472
  getPreviewMiniflareOptions(
14357
14473
  vitePreviewServer,
14358
14474
  workerConfigs,
14359
14475
  pluginConfig.persistState ?? true,
14360
- pluginConfig.inspectorPort
14476
+ inputInspectorPort
14361
14477
  )
14362
14478
  );
14363
14479
  const middleware = createMiddleware(
@@ -14436,7 +14552,7 @@ function cloudflare2(pluginConfig = {}) {
14436
14552
  for (const match of matches) {
14437
14553
  magicString ??= new MagicString(code);
14438
14554
  const [full, _, modulePath] = match;
14439
- assert8(
14555
+ assert10(
14440
14556
  modulePath,
14441
14557
  `Unexpected error: module path not found in reference ${full}.`
14442
14558
  );
@@ -14486,13 +14602,6 @@ function cloudflare2(pluginConfig = {}) {
14486
14602
  builtins: [...nodeCompatExternals]
14487
14603
  },
14488
14604
  optimizeDeps: {
14489
- // This is a list of dependency entry-points that should be pre-bundled.
14490
- // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
14491
- // ready ahead the first request to the dev server.
14492
- // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
14493
- // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
14494
- // TODO: work out how to re-enable pre-bundling of these
14495
- // include: [...getNodeCompatEntries()],
14496
14605
  // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
14497
14606
  // 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.
14498
14607
  // Obviously we don't want/need the optimizer to try to process modules that are built-in;
@@ -14516,7 +14625,7 @@ function cloudflare2(pluginConfig = {}) {
14516
14625
  return this.resolve(source, importer, options);
14517
14626
  }
14518
14627
  if (this.environment.mode === "dev") {
14519
- assert8(
14628
+ assert10(
14520
14629
  this.environment.depsOptimizer,
14521
14630
  "depsOptimizer is required in dev mode"
14522
14631
  );
@@ -14530,11 +14639,33 @@ function cloudflare2(pluginConfig = {}) {
14530
14639
  },
14531
14640
  async transform(code, id) {
14532
14641
  const workerConfig = getWorkerConfig2(this.environment.name);
14533
- assert8(workerConfig, "Expected a worker config");
14642
+ assert10(workerConfig, "Expected a worker config");
14534
14643
  const resolvedId = await this.resolve(workerConfig.main);
14535
14644
  if (id === resolvedId?.id) {
14536
14645
  return injectGlobalCode(id, code);
14537
14646
  }
14647
+ },
14648
+ async configureServer(viteDevServer) {
14649
+ await Promise.all(
14650
+ Object.values(viteDevServer.environments).flatMap(
14651
+ async (environment) => {
14652
+ const workerConfig = getWorkerConfig2(environment.name);
14653
+ if (isNodeCompat(workerConfig)) {
14654
+ await environment.depsOptimizer?.init();
14655
+ return Array.from(nodeCompatEntries).map((entry) => {
14656
+ const result = resolveNodeJSImport(entry);
14657
+ if (result) {
14658
+ const registration = environment.depsOptimizer?.registerMissingImport(
14659
+ result.unresolved,
14660
+ result.resolved
14661
+ );
14662
+ return registration?.processing;
14663
+ }
14664
+ });
14665
+ }
14666
+ }
14667
+ )
14668
+ );
14538
14669
  }
14539
14670
  },
14540
14671
  // Plugin that provides an __debug path for debugging the Cloudflare Workers.
@@ -14544,39 +14675,35 @@ function cloudflare2(pluginConfig = {}) {
14544
14675
  // the preview middleware here can take precedence
14545
14676
  enforce: "pre",
14546
14677
  configureServer(viteDevServer) {
14547
- if (resolvedPluginConfig.type === "workers" && resolvedPluginConfig.inspectorPort !== false) {
14678
+ if (resolvedPluginConfig.type === "workers" && pluginConfig.inspectorPort !== false) {
14548
14679
  addDebugToVitePrintUrls(viteDevServer);
14549
14680
  }
14550
14681
  const workerNames = resolvedPluginConfig.type === "assets-only" ? [] : Object.values(resolvedPluginConfig.workers).map(
14551
14682
  (worker) => worker.name
14552
14683
  );
14553
- viteDevServer.middlewares.use((req, res, next) => {
14554
- if (req.url === debuggingPath && resolvedPluginConfig.inspectorPort !== false) {
14555
- const html = getDebugPathHtml(
14556
- workerNames,
14557
- resolvedPluginConfig.inspectorPort
14558
- );
14684
+ viteDevServer.middlewares.use(async (req, res, next) => {
14685
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14686
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14687
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14559
14688
  res.setHeader("Content-Type", "text/html");
14560
14689
  return res.end(html);
14561
14690
  }
14562
14691
  next();
14563
14692
  });
14564
14693
  },
14565
- configurePreviewServer(vitePreviewServer) {
14694
+ async configurePreviewServer(vitePreviewServer) {
14566
14695
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14567
14696
  if (workerConfigs.length >= 1 && pluginConfig.inspectorPort !== false) {
14568
14697
  addDebugToVitePrintUrls(vitePreviewServer);
14569
14698
  }
14570
14699
  const workerNames = workerConfigs.map((worker) => {
14571
- assert8(worker.name, "Expected the Worker to have a name");
14700
+ assert10(worker.name, "Expected the Worker to have a name");
14572
14701
  return worker.name;
14573
14702
  });
14574
- vitePreviewServer.middlewares.use((req, res, next) => {
14575
- if (req.url === debuggingPath && pluginConfig.inspectorPort !== false) {
14576
- const html = getDebugPathHtml(
14577
- workerNames,
14578
- pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT
14579
- );
14703
+ vitePreviewServer.middlewares.use(async (req, res, next) => {
14704
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14705
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14706
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14580
14707
  res.setHeader("Content-Type", "text/html");
14581
14708
  return res.end(html);
14582
14709
  }
@@ -14590,6 +14717,9 @@ function cloudflare2(pluginConfig = {}) {
14590
14717
  apply(_config, env2) {
14591
14718
  return !env2.isPreview;
14592
14719
  },
14720
+ // We must ensure that the `resolveId` hook runs before the built-in ones.
14721
+ // Otherwise we never see the Node.js built-in imports since they get handled by default Vite behavior.
14722
+ enforce: "pre",
14593
14723
  configEnvironment(environmentName) {
14594
14724
  const workerConfig = getWorkerConfig2(environmentName);
14595
14725
  if (workerConfig && !isNodeCompat(workerConfig)) {
@@ -14604,20 +14734,10 @@ function cloudflare2(pluginConfig = {}) {
14604
14734
  { filter: NODEJS_MODULES_RE },
14605
14735
  ({ path: path10, importer }) => {
14606
14736
  const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14607
- assert8(
14608
- nodeJsCompatWarnings,
14609
- `expected nodeJsCompatWarnings to be defined for Worker "${workerConfig.name}"`
14610
- );
14611
- nodeJsCompatWarnings.registerImport(path10, importer);
14737
+ nodeJsCompatWarnings?.registerImport(path10, importer);
14612
14738
  return { path: path10, external: true };
14613
14739
  }
14614
14740
  );
14615
- build.onEnd(() => {
14616
- const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14617
- if (nodeJsCompatWarnings) {
14618
- nodeJsCompatWarnings.renderWarnings();
14619
- }
14620
- });
14621
14741
  }
14622
14742
  }
14623
14743
  ]
@@ -14626,47 +14746,25 @@ function cloudflare2(pluginConfig = {}) {
14626
14746
  };
14627
14747
  }
14628
14748
  },
14629
- configureServer(viteDevServer) {
14630
- for (const environment of Object.values(viteDevServer.environments)) {
14631
- const workerConfig = getWorkerConfig2(environment.name);
14749
+ configResolved(resolvedViteConfig2) {
14750
+ for (const environmentName of Object.keys(
14751
+ resolvedViteConfig2.environments
14752
+ )) {
14753
+ const workerConfig = getWorkerConfig2(environmentName);
14632
14754
  if (workerConfig && !isNodeCompat(workerConfig)) {
14633
14755
  nodeJsCompatWarningsMap.set(
14634
14756
  workerConfig,
14635
- new NodeJsCompatWarnings(environment)
14757
+ new NodeJsCompatWarnings(environmentName, resolvedViteConfig2)
14636
14758
  );
14637
14759
  }
14638
14760
  }
14639
14761
  },
14640
- buildStart() {
14641
- const workerConfig = getWorkerConfig2(this.environment.name);
14642
- if (workerConfig && !isNodeCompat(workerConfig)) {
14643
- nodeJsCompatWarningsMap.set(
14644
- workerConfig,
14645
- new NodeJsCompatWarnings(this.environment)
14646
- );
14647
- }
14648
- },
14649
- buildEnd() {
14650
- const workerConfig = getWorkerConfig2(this.environment.name);
14651
- if (workerConfig && !isNodeCompat(workerConfig)) {
14652
- const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14653
- assert8(
14654
- nodeJsCompatWarnings,
14655
- `expected nodeJsCompatWarnings to be defined for Worker "${workerConfig.name}"`
14656
- );
14657
- nodeJsCompatWarnings.renderWarnings();
14658
- }
14659
- },
14660
- // We must ensure that the `resolveId` hook runs before the built-in ones otherwise we
14661
- // never see the Node.js built-in imports since they get handled by default Vite behavior.
14662
- enforce: "pre",
14663
14762
  async resolveId(source, importer) {
14664
14763
  const workerConfig = getWorkerConfig2(this.environment.name);
14665
14764
  if (workerConfig && !isNodeCompat(workerConfig)) {
14666
14765
  const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14667
14766
  if (nodejsBuiltins.has(source)) {
14668
14767
  nodeJsCompatWarnings?.registerImport(source, importer);
14669
- nodeJsCompatWarnings?.renderWarningsOnIdle();
14670
14768
  return {
14671
14769
  id: source,
14672
14770
  external: true
@@ -14677,10 +14775,29 @@ function cloudflare2(pluginConfig = {}) {
14677
14775
  }
14678
14776
  ];
14679
14777
  function getWorkerConfig2(environmentName) {
14680
- assert8(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14778
+ assert10(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14681
14779
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
14682
14780
  }
14683
14781
  }
14782
+ async function getInputInspectorPortOption(pluginConfig, viteServer) {
14783
+ const inputInspectorPort = pluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
14784
+ if (pluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
14785
+ viteServer.config.logger.warn(
14786
+ colors2.dim(
14787
+ `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
14788
+ `
14789
+ )
14790
+ );
14791
+ }
14792
+ return inputInspectorPort;
14793
+ }
14794
+ async function getResolvedInspectorPort(pluginConfig) {
14795
+ if (miniflare && pluginConfig.inspectorPort !== false) {
14796
+ const miniflareInspectorUrl = await miniflare.getInspectorURL();
14797
+ return Number.parseInt(miniflareInspectorUrl.port);
14798
+ }
14799
+ return null;
14800
+ }
14684
14801
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14685
14802
  const configDir = path9.dirname(configPath);
14686
14803
  const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
@@ -1394,13 +1394,6 @@ async function createModuleRunner(env, webSocket, viteRoot) {
1394
1394
  },
1395
1395
  {
1396
1396
  async runInlinedModule(context, transformed, module) {
1397
- if (module.file.includes("/node_modules") && !module.file.includes("/node_modules/.vite")) {
1398
- throw new Error(
1399
- `[Error] Trying to import non-prebundled module (only prebundled modules are allowed): ${module.id}
1400
-
1401
- (have you excluded the module via \`optimizeDeps.exclude\`?)`
1402
- );
1403
- }
1404
1397
  const codeDefinition = `'use strict';async (${Object.keys(context).join(
1405
1398
  ","
1406
1399
  )})=>{{`;
@@ -1426,13 +1419,6 @@ async function createModuleRunner(env, webSocket, viteRoot) {
1426
1419
  )
1427
1420
  });
1428
1421
  }
1429
- if (!additionalModuleRE.test(filepath) && filepath.includes("/node_modules") && !filepath.includes("/node_modules/.vite")) {
1430
- throw new Error(
1431
- `[Error] Trying to import non-prebundled module (only prebundled modules are allowed): ${filepath}
1432
-
1433
- (have you externalized the module via \`resolve.external\`?)`
1434
- );
1435
- }
1436
1422
  filepath = filepath.replace(/^file:\/\//, "");
1437
1423
  return import(filepath);
1438
1424
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/vite-plugin",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
4
  "description": "Cloudflare plugin for Vite",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -34,12 +34,13 @@
34
34
  ],
35
35
  "dependencies": {
36
36
  "@hattip/adapter-node": "^0.0.49",
37
+ "get-port": "^7.1.0",
37
38
  "picocolors": "^1.1.1",
38
39
  "tinyglobby": "^0.2.12",
39
40
  "unenv": "2.0.0-rc.15",
40
41
  "ws": "8.18.0",
41
- "miniflare": "4.20250321.1",
42
- "wrangler": "4.6.0",
42
+ "wrangler": "4.7.1",
43
+ "miniflare": "4.20250321.2",
43
44
  "@cloudflare/unenv-preset": "2.3.1"
44
45
  },
45
46
  "devDependencies": {