@cloudflare/vite-plugin 0.0.0-5fc7fe6c7 → 0.0.0-5ffa20293

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
@@ -485,11 +485,12 @@ var require_mime = __commonJS({
485
485
  });
486
486
 
487
487
  // src/index.ts
488
- import assert9 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";
492
492
  import { createMiddleware } from "@hattip/adapter-node";
493
+ import replace from "@rollup/plugin-replace";
493
494
 
494
495
  // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
495
496
  var comma = ",".charCodeAt(0);
@@ -1557,6 +1558,7 @@ var MagicString = class _MagicString {
1557
1558
 
1558
1559
  // src/index.ts
1559
1560
  import { Miniflare } from "miniflare";
1561
+ import colors2 from "picocolors";
1560
1562
  import * as vite7 from "vite";
1561
1563
 
1562
1564
  // src/constants.ts
@@ -5782,7 +5784,8 @@ var z = /* @__PURE__ */ Object.freeze({
5782
5784
  // ../workers-shared/utils/types.ts
5783
5785
  var InternalConfigSchema = z.object({
5784
5786
  account_id: z.number().optional(),
5785
- script_id: z.number().optional()
5787
+ script_id: z.number().optional(),
5788
+ debug: z.boolean().optional()
5786
5789
  });
5787
5790
  var RouterConfigSchema = z.object({
5788
5791
  invoke_user_worker_ahead_of_assets: z.boolean().optional(),
@@ -5830,14 +5833,14 @@ var AssetConfigSchema = z.object({
5830
5833
  });
5831
5834
 
5832
5835
  // src/asset-config.ts
5833
- function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFile) {
5836
+ function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFilePath) {
5834
5837
  if (!resolvedPluginConfig.experimental?.headersAndRedirectsDevModeSupport) {
5835
5838
  return false;
5836
5839
  }
5837
5840
  return [
5838
5841
  getRedirectsConfigPath(resolvedViteConfig),
5839
5842
  getHeadersConfigPath(resolvedViteConfig)
5840
- ].includes(path.resolve(changedFile));
5843
+ ].includes(changedFilePath);
5841
5844
  }
5842
5845
  function getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedConfig) {
5843
5846
  const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
@@ -12878,6 +12881,15 @@ function isNodeCompat(workerConfig) {
12878
12881
  }
12879
12882
  return false;
12880
12883
  }
12884
+ function isNodeAls(workerConfig) {
12885
+ return workerConfig !== void 0 && getNodeCompat(
12886
+ workerConfig.compatibility_date,
12887
+ workerConfig.compatibility_flags ?? []
12888
+ ).mode === "als";
12889
+ }
12890
+ function isNodeAlsModule(path10) {
12891
+ return /^(node:)?async_hooks$/.test(path10);
12892
+ }
12881
12893
  function injectGlobalCode(id, code) {
12882
12894
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
12883
12895
  if (typeof globalInject === "string") {
@@ -12908,7 +12920,7 @@ globalThis.${globalName} = var_${globalName}.${exportName};
12908
12920
  }
12909
12921
  function resolveNodeJSImport(source) {
12910
12922
  const alias = env.alias[source];
12911
- if (alias) {
12923
+ if (alias && !nodeCompatExternals.has(alias)) {
12912
12924
  return {
12913
12925
  unresolved: alias,
12914
12926
  resolved: resolvePathSync(alias, { url: import.meta.url })
@@ -12939,8 +12951,9 @@ function getNodeCompatEntries() {
12939
12951
  return entries;
12940
12952
  }
12941
12953
  var NodeJsCompatWarnings = class {
12942
- constructor(environment) {
12943
- this.environment = environment;
12954
+ constructor(environmentName, resolvedViteConfig) {
12955
+ this.environmentName = environmentName;
12956
+ this.resolvedViteConfig = resolvedViteConfig;
12944
12957
  }
12945
12958
  sources = /* @__PURE__ */ new Map();
12946
12959
  timer;
@@ -12948,6 +12961,7 @@ var NodeJsCompatWarnings = class {
12948
12961
  const importers = this.sources.get(source) ?? /* @__PURE__ */ new Set();
12949
12962
  this.sources.set(source, importers);
12950
12963
  importers.add(importer);
12964
+ this.renderWarningsOnIdle();
12951
12965
  }
12952
12966
  renderWarningsOnIdle() {
12953
12967
  if (this.timer) {
@@ -12960,19 +12974,16 @@ var NodeJsCompatWarnings = class {
12960
12974
  }
12961
12975
  renderWarnings() {
12962
12976
  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.
12977
+ 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
12978
  `;
12968
12979
  this.sources.forEach((importers, source) => {
12969
12980
  importers.forEach((importer) => {
12970
- message += ` - "${source}" imported from "${path3.relative(this.environment.config.root, importer)}"
12981
+ message += ` - "${source}" imported from "${path3.relative(this.resolvedViteConfig.root, importer)}"
12971
12982
  `;
12972
12983
  });
12973
12984
  });
12974
- this.environment.logger.warn(message, {
12975
- environment: this.environment.name
12985
+ this.resolvedViteConfig.logger.warn(message, {
12986
+ timestamp: true
12976
12987
  });
12977
12988
  this.sources.clear();
12978
12989
  }
@@ -12992,6 +13003,7 @@ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
12992
13003
 
12993
13004
  // src/utils.ts
12994
13005
  import * as path4 from "node:path";
13006
+ import getPort, { portNumbers } from "get-port";
12995
13007
  import { Request as MiniflareRequest } from "miniflare";
12996
13008
  import "vite";
12997
13009
  function getOutputDirectory(userConfig, environmentName) {
@@ -13034,6 +13046,9 @@ var postfixRE = /[?#].*$/;
13034
13046
  function cleanUrl(url) {
13035
13047
  return url.replace(postfixRE, "");
13036
13048
  }
13049
+ function getFirstAvailablePort(start) {
13050
+ return getPort({ port: portNumbers(start, 65535) });
13051
+ }
13037
13052
 
13038
13053
  // src/cloudflare-environment.ts
13039
13054
  var webSocketUndefinedError = "The WebSocket is undefined";
@@ -13444,7 +13459,7 @@ function getEntryWorkerConfig(resolvedPluginConfig) {
13444
13459
  }
13445
13460
  return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
13446
13461
  }
13447
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13462
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspectorPort) {
13448
13463
  const resolvedViteConfig = viteDevServer.config;
13449
13464
  const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
13450
13465
  const assetsConfig = getAssetsConfig(
@@ -13536,7 +13551,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13536
13551
  worker: {
13537
13552
  ...workerOptions,
13538
13553
  name: workerOptions.name ?? workerConfig.name,
13539
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13554
+ unsafeInspectorProxy: inspectorPort !== false,
13540
13555
  modulesRoot: miniflareModulesRoot,
13541
13556
  unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
13542
13557
  serviceBindings: {
@@ -13578,8 +13593,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13578
13593
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13579
13594
  return {
13580
13595
  log: logger,
13581
- inspectorPort: resolvedPluginConfig.inspectorPort || void 0,
13582
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13596
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13597
+ unsafeInspectorProxy: inspectorPort !== false,
13583
13598
  handleRuntimeStdio(stdout, stderr) {
13584
13599
  const decoder = new TextDecoder();
13585
13600
  stdout.forEach((data2) => logger.info(decoder.decode(data2)));
@@ -13716,7 +13731,7 @@ function getPreviewModules(main, modulesRules) {
13716
13731
  ]
13717
13732
  };
13718
13733
  }
13719
- function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort = DEFAULT_INSPECTOR_PORT) {
13734
+ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort) {
13720
13735
  const resolvedViteConfig = vitePreviewServer.config;
13721
13736
  const workers = workerConfigs.flatMap((config) => {
13722
13737
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
@@ -13735,7 +13750,7 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13735
13750
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13736
13751
  return {
13737
13752
  log: logger,
13738
- inspectorPort: inspectorPort || void 0,
13753
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13739
13754
  unsafeInspectorProxy: inspectorPort !== false,
13740
13755
  handleRuntimeStdio(stdout, stderr) {
13741
13756
  const decoder = new TextDecoder();
@@ -13824,8 +13839,7 @@ var nonApplicableWorkerConfigs = {
13824
13839
  "preserve_file_names",
13825
13840
  "rules",
13826
13841
  "site",
13827
- "tsconfig",
13828
- "upload_source_maps"
13842
+ "tsconfig"
13829
13843
  ]
13830
13844
  };
13831
13845
  var nullableNonApplicable = [
@@ -13836,8 +13850,7 @@ var nullableNonApplicable = [
13836
13850
  "no_bundle",
13837
13851
  "preserve_file_names",
13838
13852
  "site",
13839
- "tsconfig",
13840
- "upload_source_maps"
13853
+ "tsconfig"
13841
13854
  ];
13842
13855
  function readWorkerConfig(configPath, env2) {
13843
13856
  const nonApplicable = {
@@ -14053,7 +14066,6 @@ function workerNameToEnvironmentName(workerName) {
14053
14066
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14054
14067
  const configPaths = /* @__PURE__ */ new Set();
14055
14068
  const persistState = pluginConfig.persistState ?? true;
14056
- const inspectorPort = pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT;
14057
14069
  const experimental = pluginConfig.experimental ?? {};
14058
14070
  const root = userConfig.root ? path8.resolve(userConfig.root) : process.cwd();
14059
14071
  const { CLOUDFLARE_ENV: cloudflareEnv } = vite6.loadEnv(
@@ -14079,7 +14091,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14079
14091
  type: "assets-only",
14080
14092
  config: entryWorkerResolvedConfig.config,
14081
14093
  configPaths,
14082
- inspectorPort,
14083
14094
  persistState,
14084
14095
  rawConfigs: {
14085
14096
  entryWorker: entryWorkerResolvedConfig
@@ -14125,7 +14136,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14125
14136
  type: "workers",
14126
14137
  configPaths,
14127
14138
  persistState,
14128
- inspectorPort,
14129
14139
  workers,
14130
14140
  entryWorkerEnvironmentName,
14131
14141
  rawConfigs: {
@@ -14173,6 +14183,57 @@ function handleWebSocket(httpServer, getFetcher) {
14173
14183
  );
14174
14184
  }
14175
14185
 
14186
+ // src/worker-environments-validation.ts
14187
+ import assert9 from "node:assert";
14188
+ function validateWorkerEnvironmentsResolvedConfigs(resolvedPluginConfig, resolvedViteConfig) {
14189
+ const workersEnvironmentNames = Object.keys(resolvedPluginConfig.workers);
14190
+ const disallowedEnvsConfigs = /* @__PURE__ */ new Map();
14191
+ for (const envName of workersEnvironmentNames) {
14192
+ const workerEnvConfig = resolvedViteConfig.environments[envName];
14193
+ assert9(workerEnvConfig, `Missing environment config for "${envName}"`);
14194
+ const { optimizeDeps, resolve: resolve7 } = workerEnvConfig;
14195
+ const disallowedConfig = {};
14196
+ const disallowedOptimizeDepsExcludeEntries = (optimizeDeps.exclude ?? []).filter((entry) => {
14197
+ if (cloudflareBuiltInModules.includes(entry)) {
14198
+ return false;
14199
+ }
14200
+ if (isNodeAlsModule(entry) && isNodeAls(resolvedPluginConfig.workers[envName])) {
14201
+ return false;
14202
+ }
14203
+ if (NODEJS_MODULES_RE.test(entry) && isNodeCompat(resolvedPluginConfig.workers[envName])) {
14204
+ return false;
14205
+ }
14206
+ return true;
14207
+ });
14208
+ if (disallowedOptimizeDepsExcludeEntries.length > 0) {
14209
+ disallowedConfig.optimizeDepsExclude = disallowedOptimizeDepsExcludeEntries;
14210
+ }
14211
+ if (resolve7.external === true || resolve7.external.length > 0) {
14212
+ disallowedConfig.resolveExternal = resolve7.external;
14213
+ }
14214
+ if (Object.keys(disallowedConfig).length > 0) {
14215
+ disallowedEnvsConfigs.set(envName, disallowedConfig);
14216
+ }
14217
+ }
14218
+ if (disallowedEnvsConfigs.size > 0) {
14219
+ const errorMessage = `The following environment configurations are incompatible with the Cloudflare Vite plugin:
14220
+ ${[
14221
+ ...disallowedEnvsConfigs
14222
+ ].map(
14223
+ ([envName, disallowedConfig]) => [
14224
+ disallowedConfig.optimizeDepsExclude ? ` - "${envName}" environment: \`optimizeDeps.exclude\`: ${JSON.stringify(disallowedConfig.optimizeDepsExclude)}
14225
+ ` : null,
14226
+ disallowedConfig.resolveExternal ? ` - "${envName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedConfig.resolveExternal)}
14227
+ ` : null
14228
+ ].join("")
14229
+ ).join(
14230
+ ""
14231
+ )}To resolve this issue, avoid setting \`optimizeDeps.exclude\` and \`resolve.external\` in your Cloudflare Worker environments.
14232
+ `;
14233
+ throw new Error(errorMessage);
14234
+ }
14235
+ }
14236
+
14176
14237
  // src/index.ts
14177
14238
  var workersConfigsWarningShown = false;
14178
14239
  var miniflare;
@@ -14243,7 +14304,7 @@ function cloudflare2(pluginConfig = {}) {
14243
14304
  resolvedPluginConfig.workers
14244
14305
  ).map((environmentName) => {
14245
14306
  const environment = builder.environments[environmentName];
14246
- assert9(
14307
+ assert10(
14247
14308
  environment,
14248
14309
  `${environmentName} environment not found`
14249
14310
  );
@@ -14264,6 +14325,12 @@ function cloudflare2(pluginConfig = {}) {
14264
14325
  },
14265
14326
  configResolved(config) {
14266
14327
  resolvedViteConfig = config;
14328
+ if (resolvedPluginConfig?.type === "workers") {
14329
+ validateWorkerEnvironmentsResolvedConfigs(
14330
+ resolvedPluginConfig,
14331
+ resolvedViteConfig
14332
+ );
14333
+ }
14267
14334
  },
14268
14335
  generateBundle(_, bundle) {
14269
14336
  let config;
@@ -14284,7 +14351,7 @@ function cloudflare2(pluginConfig = {}) {
14284
14351
  if (isEntryWorker && hasClientBuild) {
14285
14352
  const workerOutputDirectory = this.environment.config.build.outDir;
14286
14353
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
14287
- assert9(
14354
+ assert10(
14288
14355
  clientOutputDirectory,
14289
14356
  "Unexpected error: client output directory is undefined"
14290
14357
  );
@@ -14348,36 +14415,46 @@ function cloudflare2(pluginConfig = {}) {
14348
14415
  }
14349
14416
  },
14350
14417
  hotUpdate(options) {
14351
- if (
14352
- // Vite normalizes `options.file` so we use `path.resolve` for Windows compatibility
14353
- resolvedPluginConfig.configPaths.has(path9.resolve(options.file)) || hasAssetsConfigChanged(
14354
- resolvedPluginConfig,
14355
- resolvedViteConfig,
14356
- options.file
14357
- )
14358
- ) {
14418
+ const changedFilePath = path9.resolve(options.file);
14419
+ if (resolvedPluginConfig.configPaths.has(changedFilePath) || hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(
14420
+ resolvedPluginConfig,
14421
+ resolvedViteConfig,
14422
+ changedFilePath
14423
+ )) {
14359
14424
  options.server.restart();
14360
14425
  return [];
14361
14426
  }
14362
14427
  },
14363
14428
  async configureServer(viteDevServer) {
14364
- assert9(
14429
+ assert10(
14365
14430
  viteDevServer.httpServer,
14366
14431
  "Unexpected error: No Vite HTTP server"
14367
14432
  );
14368
- if (miniflare) {
14369
- await miniflare.setOptions(
14370
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14433
+ const inputInspectorPort = await getInputInspectorPortOption(
14434
+ pluginConfig,
14435
+ viteDevServer
14436
+ );
14437
+ if (!miniflare) {
14438
+ miniflare = new Miniflare(
14439
+ getDevMiniflareOptions(
14440
+ resolvedPluginConfig,
14441
+ viteDevServer,
14442
+ inputInspectorPort
14443
+ )
14371
14444
  );
14372
14445
  } else {
14373
- miniflare = new Miniflare(
14374
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14446
+ await miniflare.setOptions(
14447
+ getDevMiniflareOptions(
14448
+ resolvedPluginConfig,
14449
+ viteDevServer,
14450
+ inputInspectorPort
14451
+ )
14375
14452
  );
14376
14453
  }
14377
14454
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14378
14455
  const middleware = createMiddleware(
14379
14456
  async ({ request }) => {
14380
- assert9(miniflare, `Miniflare not defined`);
14457
+ assert10(miniflare, `Miniflare not defined`);
14381
14458
  const routerWorker = await getRouterWorker(miniflare);
14382
14459
  return routerWorker.fetch(toMiniflareRequest(request), {
14383
14460
  redirect: "manual"
@@ -14386,7 +14463,7 @@ function cloudflare2(pluginConfig = {}) {
14386
14463
  { alwaysCallNext: false }
14387
14464
  );
14388
14465
  handleWebSocket(viteDevServer.httpServer, async () => {
14389
- assert9(miniflare, `Miniflare not defined`);
14466
+ assert10(miniflare, `Miniflare not defined`);
14390
14467
  const routerWorker = await getRouterWorker(miniflare);
14391
14468
  return routerWorker.fetch;
14392
14469
  });
@@ -14396,14 +14473,18 @@ function cloudflare2(pluginConfig = {}) {
14396
14473
  });
14397
14474
  };
14398
14475
  },
14399
- configurePreviewServer(vitePreviewServer) {
14476
+ async configurePreviewServer(vitePreviewServer) {
14400
14477
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14478
+ const inputInspectorPort = await getInputInspectorPortOption(
14479
+ pluginConfig,
14480
+ vitePreviewServer
14481
+ );
14401
14482
  const miniflare2 = new Miniflare(
14402
14483
  getPreviewMiniflareOptions(
14403
14484
  vitePreviewServer,
14404
14485
  workerConfigs,
14405
14486
  pluginConfig.persistState ?? true,
14406
- pluginConfig.inspectorPort
14487
+ inputInspectorPort
14407
14488
  )
14408
14489
  );
14409
14490
  const middleware = createMiddleware(
@@ -14482,7 +14563,7 @@ function cloudflare2(pluginConfig = {}) {
14482
14563
  for (const match of matches) {
14483
14564
  magicString ??= new MagicString(code);
14484
14565
  const [full, _, modulePath] = match;
14485
- assert9(
14566
+ assert10(
14486
14567
  modulePath,
14487
14568
  `Unexpected error: module path not found in reference ${full}.`
14488
14569
  );
@@ -14528,17 +14609,22 @@ function cloudflare2(pluginConfig = {}) {
14528
14609
  configEnvironment(name) {
14529
14610
  if (isNodeCompat(getWorkerConfig2(name))) {
14530
14611
  return {
14612
+ build: {
14613
+ rollupOptions: {
14614
+ plugins: [
14615
+ replace({
14616
+ "process.env.NODE_ENV": JSON.stringify(
14617
+ process.env.NODE_ENV ?? "production"
14618
+ ),
14619
+ preventAssignment: true
14620
+ })
14621
+ ]
14622
+ }
14623
+ },
14531
14624
  resolve: {
14532
14625
  builtins: [...nodeCompatExternals]
14533
14626
  },
14534
14627
  optimizeDeps: {
14535
- // This is a list of dependency entry-points that should be pre-bundled.
14536
- // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
14537
- // ready ahead the first request to the dev server.
14538
- // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
14539
- // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
14540
- // TODO: work out how to re-enable pre-bundling of these
14541
- // include: [...getNodeCompatEntries()],
14542
14628
  // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
14543
14629
  // 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.
14544
14630
  // Obviously we don't want/need the optimizer to try to process modules that are built-in;
@@ -14562,7 +14648,7 @@ function cloudflare2(pluginConfig = {}) {
14562
14648
  return this.resolve(source, importer, options);
14563
14649
  }
14564
14650
  if (this.environment.mode === "dev") {
14565
- assert9(
14651
+ assert10(
14566
14652
  this.environment.depsOptimizer,
14567
14653
  "depsOptimizer is required in dev mode"
14568
14654
  );
@@ -14576,11 +14662,54 @@ function cloudflare2(pluginConfig = {}) {
14576
14662
  },
14577
14663
  async transform(code, id) {
14578
14664
  const workerConfig = getWorkerConfig2(this.environment.name);
14579
- assert9(workerConfig, "Expected a worker config");
14665
+ if (!workerConfig) {
14666
+ return;
14667
+ }
14580
14668
  const resolvedId = await this.resolve(workerConfig.main);
14581
14669
  if (id === resolvedId?.id) {
14582
14670
  return injectGlobalCode(id, code);
14583
14671
  }
14672
+ },
14673
+ async configureServer(viteDevServer) {
14674
+ await Promise.all(
14675
+ Object.values(viteDevServer.environments).flatMap(
14676
+ async (environment) => {
14677
+ const workerConfig = getWorkerConfig2(environment.name);
14678
+ if (isNodeCompat(workerConfig)) {
14679
+ await environment.depsOptimizer?.init();
14680
+ return Array.from(nodeCompatEntries).map((entry) => {
14681
+ const result = resolveNodeJSImport(entry);
14682
+ if (result) {
14683
+ const registration = environment.depsOptimizer?.registerMissingImport(
14684
+ result.unresolved,
14685
+ result.resolved
14686
+ );
14687
+ return registration?.processing;
14688
+ }
14689
+ });
14690
+ }
14691
+ }
14692
+ )
14693
+ );
14694
+ }
14695
+ },
14696
+ // Plugin that handles Node.js Async Local Storage (ALS) compatibility support for Vite Environments that are hosted in Cloudflare Workers.
14697
+ {
14698
+ name: "vite-plugin-cloudflare:nodejs-als",
14699
+ apply(_config, env2) {
14700
+ return !env2.isPreview;
14701
+ },
14702
+ configEnvironment(name, config) {
14703
+ if (isNodeAls(getWorkerConfig2(name))) {
14704
+ return {
14705
+ resolve: {
14706
+ builtins: ["async_hooks", "node:async_hooks"]
14707
+ },
14708
+ optimizeDeps: {
14709
+ exclude: ["async_hooks", "node:async_hooks"]
14710
+ }
14711
+ };
14712
+ }
14584
14713
  }
14585
14714
  },
14586
14715
  // Plugin that provides an __debug path for debugging the Cloudflare Workers.
@@ -14590,39 +14719,35 @@ function cloudflare2(pluginConfig = {}) {
14590
14719
  // the preview middleware here can take precedence
14591
14720
  enforce: "pre",
14592
14721
  configureServer(viteDevServer) {
14593
- if (resolvedPluginConfig.type === "workers" && resolvedPluginConfig.inspectorPort !== false) {
14722
+ if (resolvedPluginConfig.type === "workers" && pluginConfig.inspectorPort !== false) {
14594
14723
  addDebugToVitePrintUrls(viteDevServer);
14595
14724
  }
14596
14725
  const workerNames = resolvedPluginConfig.type === "assets-only" ? [] : Object.values(resolvedPluginConfig.workers).map(
14597
14726
  (worker) => worker.name
14598
14727
  );
14599
- viteDevServer.middlewares.use((req, res, next) => {
14600
- if (req.url === debuggingPath && resolvedPluginConfig.inspectorPort !== false) {
14601
- const html = getDebugPathHtml(
14602
- workerNames,
14603
- resolvedPluginConfig.inspectorPort
14604
- );
14728
+ viteDevServer.middlewares.use(async (req, res, next) => {
14729
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14730
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14731
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14605
14732
  res.setHeader("Content-Type", "text/html");
14606
14733
  return res.end(html);
14607
14734
  }
14608
14735
  next();
14609
14736
  });
14610
14737
  },
14611
- configurePreviewServer(vitePreviewServer) {
14738
+ async configurePreviewServer(vitePreviewServer) {
14612
14739
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14613
14740
  if (workerConfigs.length >= 1 && pluginConfig.inspectorPort !== false) {
14614
14741
  addDebugToVitePrintUrls(vitePreviewServer);
14615
14742
  }
14616
14743
  const workerNames = workerConfigs.map((worker) => {
14617
- assert9(worker.name, "Expected the Worker to have a name");
14744
+ assert10(worker.name, "Expected the Worker to have a name");
14618
14745
  return worker.name;
14619
14746
  });
14620
- vitePreviewServer.middlewares.use((req, res, next) => {
14621
- if (req.url === debuggingPath && pluginConfig.inspectorPort !== false) {
14622
- const html = getDebugPathHtml(
14623
- workerNames,
14624
- pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT
14625
- );
14747
+ vitePreviewServer.middlewares.use(async (req, res, next) => {
14748
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14749
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14750
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14626
14751
  res.setHeader("Content-Type", "text/html");
14627
14752
  return res.end(html);
14628
14753
  }
@@ -14636,6 +14761,9 @@ function cloudflare2(pluginConfig = {}) {
14636
14761
  apply(_config, env2) {
14637
14762
  return !env2.isPreview;
14638
14763
  },
14764
+ // We must ensure that the `resolveId` hook runs before the built-in ones.
14765
+ // Otherwise we never see the Node.js built-in imports since they get handled by default Vite behavior.
14766
+ enforce: "pre",
14639
14767
  configEnvironment(environmentName) {
14640
14768
  const workerConfig = getWorkerConfig2(environmentName);
14641
14769
  if (workerConfig && !isNodeCompat(workerConfig)) {
@@ -14649,21 +14777,14 @@ function cloudflare2(pluginConfig = {}) {
14649
14777
  build.onResolve(
14650
14778
  { filter: NODEJS_MODULES_RE },
14651
14779
  ({ path: path10, importer }) => {
14780
+ if (isNodeAls(workerConfig) && isNodeAlsModule(path10)) {
14781
+ return;
14782
+ }
14652
14783
  const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14653
- assert9(
14654
- nodeJsCompatWarnings,
14655
- `expected nodeJsCompatWarnings to be defined for Worker "${workerConfig.name}"`
14656
- );
14657
- nodeJsCompatWarnings.registerImport(path10, importer);
14784
+ nodeJsCompatWarnings?.registerImport(path10, importer);
14658
14785
  return { path: path10, external: true };
14659
14786
  }
14660
14787
  );
14661
- build.onEnd(() => {
14662
- const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14663
- if (nodeJsCompatWarnings) {
14664
- nodeJsCompatWarnings.renderWarnings();
14665
- }
14666
- });
14667
14788
  }
14668
14789
  }
14669
14790
  ]
@@ -14672,47 +14793,28 @@ function cloudflare2(pluginConfig = {}) {
14672
14793
  };
14673
14794
  }
14674
14795
  },
14675
- configureServer(viteDevServer) {
14676
- for (const environment of Object.values(viteDevServer.environments)) {
14677
- const workerConfig = getWorkerConfig2(environment.name);
14796
+ configResolved(resolvedViteConfig2) {
14797
+ for (const environmentName of Object.keys(
14798
+ resolvedViteConfig2.environments
14799
+ )) {
14800
+ const workerConfig = getWorkerConfig2(environmentName);
14678
14801
  if (workerConfig && !isNodeCompat(workerConfig)) {
14679
14802
  nodeJsCompatWarningsMap.set(
14680
14803
  workerConfig,
14681
- new NodeJsCompatWarnings(environment)
14804
+ new NodeJsCompatWarnings(environmentName, resolvedViteConfig2)
14682
14805
  );
14683
14806
  }
14684
14807
  }
14685
14808
  },
14686
- buildStart() {
14687
- const workerConfig = getWorkerConfig2(this.environment.name);
14688
- if (workerConfig && !isNodeCompat(workerConfig)) {
14689
- nodeJsCompatWarningsMap.set(
14690
- workerConfig,
14691
- new NodeJsCompatWarnings(this.environment)
14692
- );
14693
- }
14694
- },
14695
- buildEnd() {
14696
- const workerConfig = getWorkerConfig2(this.environment.name);
14697
- if (workerConfig && !isNodeCompat(workerConfig)) {
14698
- const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14699
- assert9(
14700
- nodeJsCompatWarnings,
14701
- `expected nodeJsCompatWarnings to be defined for Worker "${workerConfig.name}"`
14702
- );
14703
- nodeJsCompatWarnings.renderWarnings();
14704
- }
14705
- },
14706
- // We must ensure that the `resolveId` hook runs before the built-in ones otherwise we
14707
- // never see the Node.js built-in imports since they get handled by default Vite behavior.
14708
- enforce: "pre",
14709
14809
  async resolveId(source, importer) {
14710
14810
  const workerConfig = getWorkerConfig2(this.environment.name);
14711
14811
  if (workerConfig && !isNodeCompat(workerConfig)) {
14812
+ if (isNodeAls(workerConfig) && isNodeAlsModule(source)) {
14813
+ return;
14814
+ }
14712
14815
  const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14713
14816
  if (nodejsBuiltins.has(source)) {
14714
14817
  nodeJsCompatWarnings?.registerImport(source, importer);
14715
- nodeJsCompatWarnings?.renderWarningsOnIdle();
14716
14818
  return {
14717
14819
  id: source,
14718
14820
  external: true
@@ -14723,10 +14825,35 @@ function cloudflare2(pluginConfig = {}) {
14723
14825
  }
14724
14826
  ];
14725
14827
  function getWorkerConfig2(environmentName) {
14726
- assert9(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14828
+ assert10(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14727
14829
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
14728
14830
  }
14729
14831
  }
14832
+ async function getInputInspectorPortOption(pluginConfig, viteServer) {
14833
+ if (pluginConfig.inspectorPort === void 0 || pluginConfig.inspectorPort === 0) {
14834
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14835
+ if (resolvedInspectorPort !== null) {
14836
+ return resolvedInspectorPort;
14837
+ }
14838
+ }
14839
+ const inputInspectorPort = pluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
14840
+ if (pluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
14841
+ viteServer.config.logger.warn(
14842
+ colors2.dim(
14843
+ `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
14844
+ `
14845
+ )
14846
+ );
14847
+ }
14848
+ return inputInspectorPort;
14849
+ }
14850
+ async function getResolvedInspectorPort(pluginConfig) {
14851
+ if (miniflare && pluginConfig.inspectorPort !== false) {
14852
+ const miniflareInspectorUrl = await miniflare.getInspectorURL();
14853
+ return Number.parseInt(miniflareInspectorUrl.port);
14854
+ }
14855
+ return null;
14856
+ }
14730
14857
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14731
14858
  const configDir = path9.dirname(configPath);
14732
14859
  const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
@@ -14738,6 +14865,19 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14738
14865
  }
14739
14866
  return null;
14740
14867
  }
14868
+ function hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) {
14869
+ return [...resolvedPluginConfig.configPaths].some((configPath) => {
14870
+ const dotDevDotVars = path9.join(path9.dirname(configPath), ".dev.vars");
14871
+ if (dotDevDotVars === changedFilePath) {
14872
+ return true;
14873
+ }
14874
+ if (resolvedPluginConfig.cloudflareEnv) {
14875
+ const dotDevDotVarsForEnv = `${dotDevDotVars}.${resolvedPluginConfig.cloudflareEnv}`;
14876
+ return dotDevDotVarsForEnv === changedFilePath;
14877
+ }
14878
+ return false;
14879
+ });
14880
+ }
14741
14881
  export {
14742
14882
  cloudflare2 as cloudflare
14743
14883
  };