@cloudflare/vite-plugin 0.0.0-cad99dc78 → 0.0.0-cc7fae4cb

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 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";
492
- import { createMiddleware } from "@hattip/adapter-node";
492
+ import { createRequest, sendResponse } from "@mjackson/node-fetch-server";
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 colors3 from "picocolors";
1560
1562
  import * as vite7 from "vite";
1561
1563
 
1562
1564
  // src/constants.ts
@@ -1587,7 +1589,7 @@ function matchAdditionalModule(source) {
1587
1589
  return null;
1588
1590
  }
1589
1591
  function createModuleReference(type, id) {
1590
- return `__CLOUDFLARE_MODULE__${type}__${id}__`;
1592
+ return `__CLOUDFLARE_MODULE__${type}__${id}__CLOUDFLARE_MODULE__`;
1591
1593
  }
1592
1594
 
1593
1595
  // src/asset-config.ts
@@ -5782,10 +5784,17 @@ 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()
5789
+ });
5790
+ var StaticRoutingSchema = z.object({
5791
+ version: z.literal(1),
5792
+ include: z.array(z.string()),
5793
+ exclude: z.array(z.string()).optional()
5786
5794
  });
5787
5795
  var RouterConfigSchema = z.object({
5788
5796
  invoke_user_worker_ahead_of_assets: z.boolean().optional(),
5797
+ static_routing: StaticRoutingSchema.optional(),
5789
5798
  has_user_worker: z.boolean().optional(),
5790
5799
  ...InternalConfigSchema.shape
5791
5800
  });
@@ -5826,18 +5835,19 @@ var AssetConfigSchema = z.object({
5826
5835
  not_found_handling: z.enum(["single-page-application", "404-page", "none"]).optional(),
5827
5836
  redirects: RedirectsSchema,
5828
5837
  headers: HeadersSchema,
5838
+ has_static_routing: z.boolean().optional(),
5829
5839
  ...InternalConfigSchema.shape
5830
5840
  });
5831
5841
 
5832
5842
  // src/asset-config.ts
5833
- function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFile) {
5843
+ function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFilePath) {
5834
5844
  if (!resolvedPluginConfig.experimental?.headersAndRedirectsDevModeSupport) {
5835
5845
  return false;
5836
5846
  }
5837
5847
  return [
5838
5848
  getRedirectsConfigPath(resolvedViteConfig),
5839
5849
  getHeadersConfigPath(resolvedViteConfig)
5840
- ].includes(path.resolve(changedFile));
5850
+ ].includes(changedFilePath);
5841
5851
  }
5842
5852
  function getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedConfig) {
5843
5853
  const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
@@ -12878,6 +12888,15 @@ function isNodeCompat(workerConfig) {
12878
12888
  }
12879
12889
  return false;
12880
12890
  }
12891
+ function isNodeAls(workerConfig) {
12892
+ return workerConfig !== void 0 && getNodeCompat(
12893
+ workerConfig.compatibility_date,
12894
+ workerConfig.compatibility_flags ?? []
12895
+ ).mode === "als";
12896
+ }
12897
+ function isNodeAlsModule(path10) {
12898
+ return /^(node:)?async_hooks$/.test(path10);
12899
+ }
12881
12900
  function injectGlobalCode(id, code) {
12882
12901
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
12883
12902
  if (typeof globalInject === "string") {
@@ -12908,7 +12927,7 @@ globalThis.${globalName} = var_${globalName}.${exportName};
12908
12927
  }
12909
12928
  function resolveNodeJSImport(source) {
12910
12929
  const alias = env.alias[source];
12911
- if (alias) {
12930
+ if (alias && !nodeCompatExternals.has(alias)) {
12912
12931
  return {
12913
12932
  unresolved: alias,
12914
12933
  resolved: resolvePathSync(alias, { url: import.meta.url })
@@ -12939,8 +12958,9 @@ function getNodeCompatEntries() {
12939
12958
  return entries;
12940
12959
  }
12941
12960
  var NodeJsCompatWarnings = class {
12942
- constructor(environment) {
12943
- this.environment = environment;
12961
+ constructor(environmentName, resolvedViteConfig) {
12962
+ this.environmentName = environmentName;
12963
+ this.resolvedViteConfig = resolvedViteConfig;
12944
12964
  }
12945
12965
  sources = /* @__PURE__ */ new Map();
12946
12966
  timer;
@@ -12948,6 +12968,7 @@ var NodeJsCompatWarnings = class {
12948
12968
  const importers = this.sources.get(source) ?? /* @__PURE__ */ new Set();
12949
12969
  this.sources.set(source, importers);
12950
12970
  importers.add(importer);
12971
+ this.renderWarningsOnIdle();
12951
12972
  }
12952
12973
  renderWarningsOnIdle() {
12953
12974
  if (this.timer) {
@@ -12960,19 +12981,16 @@ var NodeJsCompatWarnings = class {
12960
12981
  }
12961
12982
  renderWarnings() {
12962
12983
  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.
12984
+ 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
12985
  `;
12968
12986
  this.sources.forEach((importers, source) => {
12969
12987
  importers.forEach((importer) => {
12970
- message += ` - "${source}" imported from "${path3.relative(this.environment.config.root, importer)}"
12988
+ message += ` - "${source}" imported from "${path3.relative(this.resolvedViteConfig.root, importer)}"
12971
12989
  `;
12972
12990
  });
12973
12991
  });
12974
- this.environment.logger.warn(message, {
12975
- environment: this.environment.name
12992
+ this.resolvedViteConfig.logger.warn(message, {
12993
+ timestamp: true
12976
12994
  });
12977
12995
  this.sources.clear();
12978
12996
  }
@@ -12982,7 +13000,7 @@ Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more
12982
13000
  // src/shared.ts
12983
13001
  var UNKNOWN_HOST = "http://localhost";
12984
13002
  var INIT_PATH = "/__vite_plugin_cloudflare_init__";
12985
- var ADDITIONAL_MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${ADDITIONAL_MODULE_TYPES.join("|")})__(.*?)__`;
13003
+ var ADDITIONAL_MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${ADDITIONAL_MODULE_TYPES.join("|")})__(.*?)__CLOUDFLARE_MODULE__`;
12986
13004
  var additionalModuleRE = new RegExp(ADDITIONAL_MODULE_PATTERN);
12987
13005
  var additionalModuleGlobalRE = new RegExp(
12988
13006
  ADDITIONAL_MODULE_PATTERN,
@@ -12992,6 +13010,7 @@ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
12992
13010
 
12993
13011
  // src/utils.ts
12994
13012
  import * as path4 from "node:path";
13013
+ import getPort, { portNumbers } from "get-port";
12995
13014
  import { Request as MiniflareRequest } from "miniflare";
12996
13015
  import "vite";
12997
13016
  function getOutputDirectory(userConfig, environmentName) {
@@ -13002,6 +13021,10 @@ function getRouterWorker(miniflare2) {
13002
13021
  return miniflare2.getWorker(ROUTER_WORKER_NAME);
13003
13022
  }
13004
13023
  function toMiniflareRequest(request) {
13024
+ const host = request.headers.get("Host");
13025
+ if (host) {
13026
+ request.headers.set("X-Forwarded-Host", host);
13027
+ }
13005
13028
  const secFetchMode = request.headers.get("Sec-Fetch-Mode");
13006
13029
  if (secFetchMode) {
13007
13030
  request.headers.set("X-Mf-Sec-Fetch-Mode", secFetchMode);
@@ -13013,23 +13036,13 @@ function toMiniflareRequest(request) {
13013
13036
  duplex: "half"
13014
13037
  });
13015
13038
  }
13016
- function nodeHeadersToWebHeaders(nodeHeaders) {
13017
- const headers = new Headers();
13018
- for (const [key, value] of Object.entries(nodeHeaders)) {
13019
- if (typeof value === "string") {
13020
- headers.append(key, value);
13021
- } else if (Array.isArray(value)) {
13022
- for (const item of value) {
13023
- headers.append(key, item);
13024
- }
13025
- }
13026
- }
13027
- return headers;
13028
- }
13029
13039
  var postfixRE = /[?#].*$/;
13030
13040
  function cleanUrl(url) {
13031
13041
  return url.replace(postfixRE, "");
13032
13042
  }
13043
+ function getFirstAvailablePort(start) {
13044
+ return getPort({ port: portNumbers(start, 65535) });
13045
+ }
13033
13046
 
13034
13047
  // src/cloudflare-environment.ts
13035
13048
  var webSocketUndefinedError = "The WebSocket is undefined";
@@ -13336,6 +13349,7 @@ import {
13336
13349
  LogLevel,
13337
13350
  Response as MiniflareResponse
13338
13351
  } from "miniflare";
13352
+ import colors2 from "picocolors";
13339
13353
  import { globSync } from "tinyglobby";
13340
13354
  import "vite";
13341
13355
  import { unstable_getMiniflareWorkerOptions } from "wrangler";
@@ -13440,7 +13454,30 @@ function getEntryWorkerConfig(resolvedPluginConfig) {
13440
13454
  }
13441
13455
  return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
13442
13456
  }
13443
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13457
+ function filterTails(tails, userWorkers, log) {
13458
+ return tails?.filter((tailService) => {
13459
+ let name;
13460
+ if (typeof tailService === "string") {
13461
+ name = tailService;
13462
+ } else if (typeof tailService === "object" && "name" in tailService && typeof tailService.name === "string") {
13463
+ name = tailService.name;
13464
+ } else {
13465
+ return true;
13466
+ }
13467
+ const found = userWorkers.some((w) => w.name === name);
13468
+ if (!found) {
13469
+ log(
13470
+ colors2.dim(
13471
+ colors2.yellow(
13472
+ `Tail consumer "${name}" was not found in your config. Make sure you add it if you'd like to simulate receiving tail events locally.`
13473
+ )
13474
+ )
13475
+ );
13476
+ }
13477
+ return found;
13478
+ });
13479
+ }
13480
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspectorPort) {
13444
13481
  const resolvedViteConfig = viteDevServer.config;
13445
13482
  const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
13446
13483
  const assetsConfig = getAssetsConfig(
@@ -13532,7 +13569,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13532
13569
  worker: {
13533
13570
  ...workerOptions,
13534
13571
  name: workerOptions.name ?? workerConfig.name,
13535
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13572
+ unsafeInspectorProxy: inspectorPort !== false,
13536
13573
  modulesRoot: miniflareModulesRoot,
13537
13574
  unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
13538
13575
  serviceBindings: {
@@ -13574,8 +13611,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13574
13611
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13575
13612
  return {
13576
13613
  log: logger,
13577
- inspectorPort: resolvedPluginConfig.inspectorPort || void 0,
13578
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13614
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13615
+ unsafeInspectorProxy: inspectorPort !== false,
13579
13616
  handleRuntimeStdio(stdout, stderr) {
13580
13617
  const decoder = new TextDecoder();
13581
13618
  stdout.forEach((data2) => logger.info(decoder.decode(data2)));
@@ -13631,6 +13668,11 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13631
13668
  }
13632
13669
  return {
13633
13670
  ...workerOptions,
13671
+ tails: filterTails(
13672
+ workerOptions.tails,
13673
+ userWorkers,
13674
+ viteDevServer.config.logger.warn
13675
+ ),
13634
13676
  modules: [
13635
13677
  {
13636
13678
  type: "ESModule",
@@ -13712,7 +13754,7 @@ function getPreviewModules(main, modulesRules) {
13712
13754
  ]
13713
13755
  };
13714
13756
  }
13715
- function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort = DEFAULT_INSPECTOR_PORT) {
13757
+ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort) {
13716
13758
  const resolvedViteConfig = vitePreviewServer.config;
13717
13759
  const workers = workerConfigs.flatMap((config) => {
13718
13760
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
@@ -13721,6 +13763,11 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13721
13763
  return [
13722
13764
  {
13723
13765
  ...workerOptions,
13766
+ tails: filterTails(
13767
+ workerOptions.tails,
13768
+ workerConfigs,
13769
+ vitePreviewServer.config.logger.warn
13770
+ ),
13724
13771
  name: workerOptions.name ?? config.name,
13725
13772
  unsafeInspectorProxy: inspectorPort !== false,
13726
13773
  ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
@@ -13731,7 +13778,7 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13731
13778
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13732
13779
  return {
13733
13780
  log: logger,
13734
- inspectorPort: inspectorPort || void 0,
13781
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13735
13782
  unsafeInspectorProxy: inspectorPort !== false,
13736
13783
  handleRuntimeStdio(stdout, stderr) {
13737
13784
  const decoder = new TextDecoder();
@@ -13781,11 +13828,12 @@ function miniflareLogLevelFromViteLogLevel(level = "info") {
13781
13828
  }
13782
13829
 
13783
13830
  // src/plugin-config.ts
13784
- import assert7 from "node:assert";
13831
+ import assert8 from "node:assert";
13785
13832
  import * as path8 from "node:path";
13786
13833
  import * as vite6 from "vite";
13787
13834
 
13788
13835
  // src/workers-configs.ts
13836
+ import assert7 from "node:assert";
13789
13837
  import * as fs4 from "node:fs";
13790
13838
  import * as path7 from "node:path";
13791
13839
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
@@ -13819,8 +13867,7 @@ var nonApplicableWorkerConfigs = {
13819
13867
  "preserve_file_names",
13820
13868
  "rules",
13821
13869
  "site",
13822
- "tsconfig",
13823
- "upload_source_maps"
13870
+ "tsconfig"
13824
13871
  ]
13825
13872
  };
13826
13873
  var nullableNonApplicable = [
@@ -13831,8 +13878,7 @@ var nullableNonApplicable = [
13831
13878
  "no_bundle",
13832
13879
  "preserve_file_names",
13833
13880
  "site",
13834
- "tsconfig",
13835
- "upload_source_maps"
13881
+ "tsconfig"
13836
13882
  ];
13837
13883
  function readWorkerConfig(configPath, env2) {
13838
13884
  const nonApplicable = {
@@ -13994,14 +14040,52 @@ function getWorkerConfig(configPath, env2, opts) {
13994
14040
  nonApplicable
13995
14041
  };
13996
14042
  }
14043
+ function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
14044
+ if (requestedConfigPath) {
14045
+ const configPath2 = path7.resolve(root, requestedConfigPath);
14046
+ const forAuxiliaryWorkerErrorMessage = isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : "";
14047
+ const errorMessagePrefix = `The provided configPath (${configPath2})${forAuxiliaryWorkerErrorMessage}`;
14048
+ const fileExtension = path7.extname(configPath2).slice(1);
14049
+ if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
14050
+ const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
14051
+ throw new Error(
14052
+ `${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`
14053
+ );
14054
+ }
14055
+ const mainStat = fs4.statSync(configPath2, { throwIfNoEntry: false });
14056
+ if (!mainStat) {
14057
+ throw new Error(
14058
+ `${errorMessagePrefix} doesn't point to an existing file`
14059
+ );
14060
+ }
14061
+ if (mainStat.isDirectory()) {
14062
+ throw new Error(
14063
+ `${errorMessagePrefix} points to a directory. It should point to a file.`
14064
+ );
14065
+ }
14066
+ return configPath2;
14067
+ }
14068
+ assert7(
14069
+ isForAuxiliaryWorker === false,
14070
+ "Unexpected Error: trying to find the wrangler config for an auxiliary worker"
14071
+ );
14072
+ const configPath = findWranglerConfig(root);
14073
+ if (!configPath) {
14074
+ throw new Error(
14075
+ `No config file found in the ${root} directory. Please add a wrangler.(jsonc|json|toml) file.`
14076
+ );
14077
+ }
14078
+ return configPath;
14079
+ }
13997
14080
  function findWranglerConfig(root) {
13998
- for (const extension of ["json", "jsonc", "toml"]) {
14081
+ for (const extension of allowedWranglerConfigExtensions) {
13999
14082
  const configPath = path7.join(root, `wrangler.${extension}`);
14000
14083
  if (fs4.existsSync(configPath)) {
14001
14084
  return configPath;
14002
14085
  }
14003
14086
  }
14004
14087
  }
14088
+ var allowedWranglerConfigExtensions = ["jsonc", "json", "toml"];
14005
14089
 
14006
14090
  // src/plugin-config.ts
14007
14091
  function workerNameToEnvironmentName(workerName) {
@@ -14010,7 +14094,6 @@ function workerNameToEnvironmentName(workerName) {
14010
14094
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14011
14095
  const configPaths = /* @__PURE__ */ new Set();
14012
14096
  const persistState = pluginConfig.persistState ?? true;
14013
- const inspectorPort = pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT;
14014
14097
  const experimental = pluginConfig.experimental ?? {};
14015
14098
  const root = userConfig.root ? path8.resolve(userConfig.root) : process.cwd();
14016
14099
  const { CLOUDFLARE_ENV: cloudflareEnv } = vite6.loadEnv(
@@ -14019,22 +14102,23 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14019
14102
  /* prefixes */
14020
14103
  ""
14021
14104
  );
14022
- const configPath = pluginConfig.configPath ? path8.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
14023
- if (!configPath) {
14024
- throw new Error(
14025
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
14026
- );
14027
- }
14028
- const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
14029
- visitedConfigPaths: configPaths,
14030
- isEntryWorker: true
14031
- });
14105
+ const entryWorkerConfigPath = getValidatedWranglerConfigPath(
14106
+ root,
14107
+ pluginConfig.configPath
14108
+ );
14109
+ const entryWorkerResolvedConfig = getWorkerConfig(
14110
+ entryWorkerConfigPath,
14111
+ cloudflareEnv,
14112
+ {
14113
+ visitedConfigPaths: configPaths,
14114
+ isEntryWorker: true
14115
+ }
14116
+ );
14032
14117
  if (entryWorkerResolvedConfig.type === "assets-only") {
14033
14118
  return {
14034
14119
  type: "assets-only",
14035
14120
  config: entryWorkerResolvedConfig.config,
14036
14121
  configPaths,
14037
- inspectorPort,
14038
14122
  persistState,
14039
14123
  rawConfigs: {
14040
14124
  entryWorker: entryWorkerResolvedConfig
@@ -14050,15 +14134,20 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14050
14134
  };
14051
14135
  const auxiliaryWorkersResolvedConfigs = [];
14052
14136
  for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
14137
+ const workerConfigPath = getValidatedWranglerConfigPath(
14138
+ root,
14139
+ auxiliaryWorker.configPath,
14140
+ true
14141
+ );
14053
14142
  const workerResolvedConfig = getWorkerConfig(
14054
- path8.resolve(root, auxiliaryWorker.configPath),
14143
+ workerConfigPath,
14055
14144
  cloudflareEnv,
14056
14145
  {
14057
14146
  visitedConfigPaths: configPaths
14058
14147
  }
14059
14148
  );
14060
14149
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
14061
- assert7(
14150
+ assert8(
14062
14151
  workerResolvedConfig.type === "worker",
14063
14152
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
14064
14153
  );
@@ -14075,7 +14164,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14075
14164
  type: "workers",
14076
14165
  configPaths,
14077
14166
  persistState,
14078
- inspectorPort,
14079
14167
  workers,
14080
14168
  entryWorkerEnvironmentName,
14081
14169
  rawConfigs: {
@@ -14088,6 +14176,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14088
14176
  }
14089
14177
 
14090
14178
  // src/websockets.ts
14179
+ import { createHeaders } from "@mjackson/node-fetch-server";
14091
14180
  import { coupleWebSocket } from "miniflare";
14092
14181
  import { WebSocketServer } from "ws";
14093
14182
  function handleWebSocket(httpServer, getFetcher) {
@@ -14099,7 +14188,7 @@ function handleWebSocket(httpServer, getFetcher) {
14099
14188
  if (request.headers["sec-websocket-protocol"]?.startsWith("vite")) {
14100
14189
  return;
14101
14190
  }
14102
- const headers = nodeHeadersToWebHeaders(request.headers);
14191
+ const headers = createHeaders(request);
14103
14192
  const fetcher = await getFetcher();
14104
14193
  const response = await fetcher(url, {
14105
14194
  headers,
@@ -14123,6 +14212,57 @@ function handleWebSocket(httpServer, getFetcher) {
14123
14212
  );
14124
14213
  }
14125
14214
 
14215
+ // src/worker-environments-validation.ts
14216
+ import assert9 from "node:assert";
14217
+ function validateWorkerEnvironmentsResolvedConfigs(resolvedPluginConfig, resolvedViteConfig) {
14218
+ const workersEnvironmentNames = Object.keys(resolvedPluginConfig.workers);
14219
+ const disallowedEnvsConfigs = /* @__PURE__ */ new Map();
14220
+ for (const envName of workersEnvironmentNames) {
14221
+ const workerEnvConfig = resolvedViteConfig.environments[envName];
14222
+ assert9(workerEnvConfig, `Missing environment config for "${envName}"`);
14223
+ const { optimizeDeps, resolve: resolve7 } = workerEnvConfig;
14224
+ const disallowedConfig = {};
14225
+ const disallowedOptimizeDepsExcludeEntries = (optimizeDeps.exclude ?? []).filter((entry) => {
14226
+ if (cloudflareBuiltInModules.includes(entry)) {
14227
+ return false;
14228
+ }
14229
+ if (isNodeAlsModule(entry) && isNodeAls(resolvedPluginConfig.workers[envName])) {
14230
+ return false;
14231
+ }
14232
+ if (NODEJS_MODULES_RE.test(entry) && isNodeCompat(resolvedPluginConfig.workers[envName])) {
14233
+ return false;
14234
+ }
14235
+ return true;
14236
+ });
14237
+ if (disallowedOptimizeDepsExcludeEntries.length > 0) {
14238
+ disallowedConfig.optimizeDepsExclude = disallowedOptimizeDepsExcludeEntries;
14239
+ }
14240
+ if (resolve7.external === true || resolve7.external.length > 0) {
14241
+ disallowedConfig.resolveExternal = resolve7.external;
14242
+ }
14243
+ if (Object.keys(disallowedConfig).length > 0) {
14244
+ disallowedEnvsConfigs.set(envName, disallowedConfig);
14245
+ }
14246
+ }
14247
+ if (disallowedEnvsConfigs.size > 0) {
14248
+ const errorMessage = `The following environment configurations are incompatible with the Cloudflare Vite plugin:
14249
+ ${[
14250
+ ...disallowedEnvsConfigs
14251
+ ].map(
14252
+ ([envName, disallowedConfig]) => [
14253
+ disallowedConfig.optimizeDepsExclude ? ` - "${envName}" environment: \`optimizeDeps.exclude\`: ${JSON.stringify(disallowedConfig.optimizeDepsExclude)}
14254
+ ` : null,
14255
+ disallowedConfig.resolveExternal ? ` - "${envName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedConfig.resolveExternal)}
14256
+ ` : null
14257
+ ].join("")
14258
+ ).join(
14259
+ ""
14260
+ )}To resolve this issue, avoid setting \`optimizeDeps.exclude\` and \`resolve.external\` in your Cloudflare Worker environments.
14261
+ `;
14262
+ throw new Error(errorMessage);
14263
+ }
14264
+ }
14265
+
14126
14266
  // src/index.ts
14127
14267
  var workersConfigsWarningShown = false;
14128
14268
  var miniflare;
@@ -14193,7 +14333,7 @@ function cloudflare2(pluginConfig = {}) {
14193
14333
  resolvedPluginConfig.workers
14194
14334
  ).map((environmentName) => {
14195
14335
  const environment = builder.environments[environmentName];
14196
- assert8(
14336
+ assert10(
14197
14337
  environment,
14198
14338
  `${environmentName} environment not found`
14199
14339
  );
@@ -14214,6 +14354,12 @@ function cloudflare2(pluginConfig = {}) {
14214
14354
  },
14215
14355
  configResolved(config) {
14216
14356
  resolvedViteConfig = config;
14357
+ if (resolvedPluginConfig?.type === "workers") {
14358
+ validateWorkerEnvironmentsResolvedConfigs(
14359
+ resolvedPluginConfig,
14360
+ resolvedViteConfig
14361
+ );
14362
+ }
14217
14363
  },
14218
14364
  generateBundle(_, bundle) {
14219
14365
  let config;
@@ -14234,7 +14380,7 @@ function cloudflare2(pluginConfig = {}) {
14234
14380
  if (isEntryWorker && hasClientBuild) {
14235
14381
  const workerOutputDirectory = this.environment.config.build.outDir;
14236
14382
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
14237
- assert8(
14383
+ assert10(
14238
14384
  clientOutputDirectory,
14239
14385
  "Unexpected error: client output directory is undefined"
14240
14386
  );
@@ -14298,78 +14444,100 @@ function cloudflare2(pluginConfig = {}) {
14298
14444
  }
14299
14445
  },
14300
14446
  hotUpdate(options) {
14301
- if (
14302
- // Vite normalizes `options.file` so we use `path.resolve` for Windows compatibility
14303
- resolvedPluginConfig.configPaths.has(path9.resolve(options.file)) || hasAssetsConfigChanged(
14304
- resolvedPluginConfig,
14305
- resolvedViteConfig,
14306
- options.file
14307
- )
14308
- ) {
14447
+ const changedFilePath = path9.resolve(options.file);
14448
+ if (resolvedPluginConfig.configPaths.has(changedFilePath) || hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(
14449
+ resolvedPluginConfig,
14450
+ resolvedViteConfig,
14451
+ changedFilePath
14452
+ )) {
14309
14453
  options.server.restart();
14310
14454
  return [];
14311
14455
  }
14312
14456
  },
14313
14457
  async configureServer(viteDevServer) {
14314
- assert8(
14315
- viteDevServer.httpServer,
14316
- "Unexpected error: No Vite HTTP server"
14458
+ const inputInspectorPort = await getInputInspectorPortOption(
14459
+ pluginConfig,
14460
+ viteDevServer
14317
14461
  );
14318
- if (miniflare) {
14319
- await miniflare.setOptions(
14320
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14462
+ if (!miniflare) {
14463
+ miniflare = new Miniflare(
14464
+ getDevMiniflareOptions(
14465
+ resolvedPluginConfig,
14466
+ viteDevServer,
14467
+ inputInspectorPort
14468
+ )
14321
14469
  );
14322
14470
  } else {
14323
- miniflare = new Miniflare(
14324
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14471
+ await miniflare.setOptions(
14472
+ getDevMiniflareOptions(
14473
+ resolvedPluginConfig,
14474
+ viteDevServer,
14475
+ inputInspectorPort
14476
+ )
14325
14477
  );
14326
14478
  }
14327
14479
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14328
- const middleware = createMiddleware(
14329
- async ({ request }) => {
14330
- assert8(miniflare, `Miniflare not defined`);
14480
+ if (viteDevServer.httpServer) {
14481
+ handleWebSocket(viteDevServer.httpServer, async () => {
14482
+ assert10(miniflare, `Miniflare not defined`);
14331
14483
  const routerWorker = await getRouterWorker(miniflare);
14332
- return routerWorker.fetch(toMiniflareRequest(request), {
14333
- redirect: "manual"
14334
- });
14335
- },
14336
- { alwaysCallNext: false }
14337
- );
14338
- handleWebSocket(viteDevServer.httpServer, async () => {
14339
- assert8(miniflare, `Miniflare not defined`);
14340
- const routerWorker = await getRouterWorker(miniflare);
14341
- return routerWorker.fetch;
14342
- });
14484
+ return routerWorker.fetch;
14485
+ });
14486
+ }
14343
14487
  return () => {
14344
- viteDevServer.middlewares.use((req, res, next) => {
14345
- middleware(req, res, next);
14488
+ viteDevServer.middlewares.use(async (req, res, next) => {
14489
+ try {
14490
+ assert10(miniflare, `Miniflare not defined`);
14491
+ const routerWorker = await getRouterWorker(miniflare);
14492
+ const request = createRequest(req, res);
14493
+ const response = await routerWorker.fetch(
14494
+ toMiniflareRequest(request),
14495
+ {
14496
+ redirect: "manual"
14497
+ }
14498
+ );
14499
+ if (req.httpVersionMajor === 2) {
14500
+ response.headers.delete("transfer-encoding");
14501
+ }
14502
+ await sendResponse(res, response);
14503
+ } catch (error) {
14504
+ next(error);
14505
+ }
14346
14506
  });
14347
14507
  };
14348
14508
  },
14349
- configurePreviewServer(vitePreviewServer) {
14509
+ async configurePreviewServer(vitePreviewServer) {
14350
14510
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14511
+ const inputInspectorPort = await getInputInspectorPortOption(
14512
+ pluginConfig,
14513
+ vitePreviewServer
14514
+ );
14351
14515
  const miniflare2 = new Miniflare(
14352
14516
  getPreviewMiniflareOptions(
14353
14517
  vitePreviewServer,
14354
14518
  workerConfigs,
14355
14519
  pluginConfig.persistState ?? true,
14356
- pluginConfig.inspectorPort
14520
+ inputInspectorPort
14357
14521
  )
14358
14522
  );
14359
- const middleware = createMiddleware(
14360
- ({ request }) => {
14361
- return miniflare2.dispatchFetch(toMiniflareRequest(request), {
14362
- redirect: "manual"
14363
- });
14364
- },
14365
- { alwaysCallNext: false }
14366
- );
14367
14523
  handleWebSocket(
14368
14524
  vitePreviewServer.httpServer,
14369
14525
  () => miniflare2.dispatchFetch
14370
14526
  );
14371
- vitePreviewServer.middlewares.use((req, res, next) => {
14372
- middleware(req, res, next);
14527
+ vitePreviewServer.middlewares.use(async (req, res, next) => {
14528
+ try {
14529
+ const request = createRequest(req, res);
14530
+ const response = await miniflare2.dispatchFetch(
14531
+ toMiniflareRequest(request),
14532
+ { redirect: "manual" }
14533
+ );
14534
+ if (req.httpVersionMajor === 2) {
14535
+ response.headers.delete("transfer-encoding");
14536
+ }
14537
+ await sendResponse(res, response);
14538
+ } catch (error) {
14539
+ next(error);
14540
+ }
14373
14541
  });
14374
14542
  }
14375
14543
  },
@@ -14432,7 +14600,7 @@ function cloudflare2(pluginConfig = {}) {
14432
14600
  for (const match of matches) {
14433
14601
  magicString ??= new MagicString(code);
14434
14602
  const [full, _, modulePath] = match;
14435
- assert8(
14603
+ assert10(
14436
14604
  modulePath,
14437
14605
  `Unexpected error: module path not found in reference ${full}.`
14438
14606
  );
@@ -14478,17 +14646,22 @@ function cloudflare2(pluginConfig = {}) {
14478
14646
  configEnvironment(name) {
14479
14647
  if (isNodeCompat(getWorkerConfig2(name))) {
14480
14648
  return {
14649
+ build: {
14650
+ rollupOptions: {
14651
+ plugins: [
14652
+ replace({
14653
+ "process.env.NODE_ENV": JSON.stringify(
14654
+ process.env.NODE_ENV ?? "production"
14655
+ ),
14656
+ preventAssignment: true
14657
+ })
14658
+ ]
14659
+ }
14660
+ },
14481
14661
  resolve: {
14482
14662
  builtins: [...nodeCompatExternals]
14483
14663
  },
14484
14664
  optimizeDeps: {
14485
- // This is a list of dependency entry-points that should be pre-bundled.
14486
- // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
14487
- // ready ahead the first request to the dev server.
14488
- // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
14489
- // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
14490
- // TODO: work out how to re-enable pre-bundling of these
14491
- // include: [...getNodeCompatEntries()],
14492
14665
  // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
14493
14666
  // 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.
14494
14667
  // Obviously we don't want/need the optimizer to try to process modules that are built-in;
@@ -14512,7 +14685,7 @@ function cloudflare2(pluginConfig = {}) {
14512
14685
  return this.resolve(source, importer, options);
14513
14686
  }
14514
14687
  if (this.environment.mode === "dev") {
14515
- assert8(
14688
+ assert10(
14516
14689
  this.environment.depsOptimizer,
14517
14690
  "depsOptimizer is required in dev mode"
14518
14691
  );
@@ -14526,11 +14699,54 @@ function cloudflare2(pluginConfig = {}) {
14526
14699
  },
14527
14700
  async transform(code, id) {
14528
14701
  const workerConfig = getWorkerConfig2(this.environment.name);
14529
- assert8(workerConfig, "Expected a worker config");
14702
+ if (!workerConfig) {
14703
+ return;
14704
+ }
14530
14705
  const resolvedId = await this.resolve(workerConfig.main);
14531
14706
  if (id === resolvedId?.id) {
14532
14707
  return injectGlobalCode(id, code);
14533
14708
  }
14709
+ },
14710
+ async configureServer(viteDevServer) {
14711
+ await Promise.all(
14712
+ Object.values(viteDevServer.environments).flatMap(
14713
+ async (environment) => {
14714
+ const workerConfig = getWorkerConfig2(environment.name);
14715
+ if (isNodeCompat(workerConfig)) {
14716
+ await environment.depsOptimizer?.init();
14717
+ return Array.from(nodeCompatEntries).map((entry) => {
14718
+ const result = resolveNodeJSImport(entry);
14719
+ if (result) {
14720
+ const registration = environment.depsOptimizer?.registerMissingImport(
14721
+ result.unresolved,
14722
+ result.resolved
14723
+ );
14724
+ return registration?.processing;
14725
+ }
14726
+ });
14727
+ }
14728
+ }
14729
+ )
14730
+ );
14731
+ }
14732
+ },
14733
+ // Plugin that handles Node.js Async Local Storage (ALS) compatibility support for Vite Environments that are hosted in Cloudflare Workers.
14734
+ {
14735
+ name: "vite-plugin-cloudflare:nodejs-als",
14736
+ apply(_config, env2) {
14737
+ return !env2.isPreview;
14738
+ },
14739
+ configEnvironment(name, config) {
14740
+ if (isNodeAls(getWorkerConfig2(name))) {
14741
+ return {
14742
+ resolve: {
14743
+ builtins: ["async_hooks", "node:async_hooks"]
14744
+ },
14745
+ optimizeDeps: {
14746
+ exclude: ["async_hooks", "node:async_hooks"]
14747
+ }
14748
+ };
14749
+ }
14534
14750
  }
14535
14751
  },
14536
14752
  // Plugin that provides an __debug path for debugging the Cloudflare Workers.
@@ -14540,39 +14756,35 @@ function cloudflare2(pluginConfig = {}) {
14540
14756
  // the preview middleware here can take precedence
14541
14757
  enforce: "pre",
14542
14758
  configureServer(viteDevServer) {
14543
- if (resolvedPluginConfig.type === "workers" && resolvedPluginConfig.inspectorPort !== false) {
14759
+ if (resolvedPluginConfig.type === "workers" && pluginConfig.inspectorPort !== false) {
14544
14760
  addDebugToVitePrintUrls(viteDevServer);
14545
14761
  }
14546
14762
  const workerNames = resolvedPluginConfig.type === "assets-only" ? [] : Object.values(resolvedPluginConfig.workers).map(
14547
14763
  (worker) => worker.name
14548
14764
  );
14549
- viteDevServer.middlewares.use((req, res, next) => {
14550
- if (req.url === debuggingPath && resolvedPluginConfig.inspectorPort !== false) {
14551
- const html = getDebugPathHtml(
14552
- workerNames,
14553
- resolvedPluginConfig.inspectorPort
14554
- );
14765
+ viteDevServer.middlewares.use(async (req, res, next) => {
14766
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14767
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14768
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14555
14769
  res.setHeader("Content-Type", "text/html");
14556
14770
  return res.end(html);
14557
14771
  }
14558
14772
  next();
14559
14773
  });
14560
14774
  },
14561
- configurePreviewServer(vitePreviewServer) {
14775
+ async configurePreviewServer(vitePreviewServer) {
14562
14776
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14563
14777
  if (workerConfigs.length >= 1 && pluginConfig.inspectorPort !== false) {
14564
14778
  addDebugToVitePrintUrls(vitePreviewServer);
14565
14779
  }
14566
14780
  const workerNames = workerConfigs.map((worker) => {
14567
- assert8(worker.name, "Expected the Worker to have a name");
14781
+ assert10(worker.name, "Expected the Worker to have a name");
14568
14782
  return worker.name;
14569
14783
  });
14570
- vitePreviewServer.middlewares.use((req, res, next) => {
14571
- if (req.url === debuggingPath && pluginConfig.inspectorPort !== false) {
14572
- const html = getDebugPathHtml(
14573
- workerNames,
14574
- pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT
14575
- );
14784
+ vitePreviewServer.middlewares.use(async (req, res, next) => {
14785
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14786
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14787
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14576
14788
  res.setHeader("Content-Type", "text/html");
14577
14789
  return res.end(html);
14578
14790
  }
@@ -14586,6 +14798,9 @@ function cloudflare2(pluginConfig = {}) {
14586
14798
  apply(_config, env2) {
14587
14799
  return !env2.isPreview;
14588
14800
  },
14801
+ // We must ensure that the `resolveId` hook runs before the built-in ones.
14802
+ // Otherwise we never see the Node.js built-in imports since they get handled by default Vite behavior.
14803
+ enforce: "pre",
14589
14804
  configEnvironment(environmentName) {
14590
14805
  const workerConfig = getWorkerConfig2(environmentName);
14591
14806
  if (workerConfig && !isNodeCompat(workerConfig)) {
@@ -14599,21 +14814,14 @@ function cloudflare2(pluginConfig = {}) {
14599
14814
  build.onResolve(
14600
14815
  { filter: NODEJS_MODULES_RE },
14601
14816
  ({ path: path10, importer }) => {
14817
+ if (isNodeAls(workerConfig) && isNodeAlsModule(path10)) {
14818
+ return;
14819
+ }
14602
14820
  const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14603
- assert8(
14604
- nodeJsCompatWarnings,
14605
- `expected nodeJsCompatWarnings to be defined for Worker "${workerConfig.name}"`
14606
- );
14607
- nodeJsCompatWarnings.registerImport(path10, importer);
14821
+ nodeJsCompatWarnings?.registerImport(path10, importer);
14608
14822
  return { path: path10, external: true };
14609
14823
  }
14610
14824
  );
14611
- build.onEnd(() => {
14612
- const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14613
- if (nodeJsCompatWarnings) {
14614
- nodeJsCompatWarnings.renderWarnings();
14615
- }
14616
- });
14617
14825
  }
14618
14826
  }
14619
14827
  ]
@@ -14622,51 +14830,28 @@ function cloudflare2(pluginConfig = {}) {
14622
14830
  };
14623
14831
  }
14624
14832
  },
14625
- configureServer(viteDevServer) {
14626
- for (const environment of Object.values(viteDevServer.environments)) {
14627
- const workerConfig = getWorkerConfig2(environment.name);
14833
+ configResolved(resolvedViteConfig2) {
14834
+ for (const environmentName of Object.keys(
14835
+ resolvedViteConfig2.environments
14836
+ )) {
14837
+ const workerConfig = getWorkerConfig2(environmentName);
14628
14838
  if (workerConfig && !isNodeCompat(workerConfig)) {
14629
14839
  nodeJsCompatWarningsMap.set(
14630
14840
  workerConfig,
14631
- new NodeJsCompatWarnings(environment)
14841
+ new NodeJsCompatWarnings(environmentName, resolvedViteConfig2)
14632
14842
  );
14633
14843
  }
14634
14844
  }
14635
14845
  },
14636
- buildStart() {
14637
- const workerConfig = getWorkerConfig2(this.environment.name);
14638
- if (workerConfig && !isNodeCompat(workerConfig)) {
14639
- nodeJsCompatWarningsMap.set(
14640
- workerConfig,
14641
- new NodeJsCompatWarnings(this.environment)
14642
- );
14643
- }
14644
- },
14645
- buildEnd() {
14646
- const workerConfig = getWorkerConfig2(this.environment.name);
14647
- if (workerConfig && !isNodeCompat(workerConfig)) {
14648
- const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14649
- assert8(
14650
- nodeJsCompatWarnings,
14651
- `expected nodeJsCompatWarnings to be defined for Worker "${workerConfig.name}"`
14652
- );
14653
- nodeJsCompatWarnings.renderWarnings();
14654
- }
14655
- },
14656
- // We must ensure that the `resolveId` hook runs before the built-in ones otherwise we
14657
- // never see the Node.js built-in imports since they get handled by default Vite behavior.
14658
- enforce: "pre",
14659
14846
  async resolveId(source, importer) {
14660
14847
  const workerConfig = getWorkerConfig2(this.environment.name);
14661
14848
  if (workerConfig && !isNodeCompat(workerConfig)) {
14849
+ if (isNodeAls(workerConfig) && isNodeAlsModule(source)) {
14850
+ return;
14851
+ }
14662
14852
  const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14663
- assert8(
14664
- nodeJsCompatWarnings,
14665
- `expected nodeJsCompatWarnings to be defined for Worker "${workerConfig.name}"`
14666
- );
14667
14853
  if (nodejsBuiltins.has(source)) {
14668
- nodeJsCompatWarnings.registerImport(source, importer);
14669
- nodeJsCompatWarnings.renderWarningsOnIdle();
14854
+ nodeJsCompatWarnings?.registerImport(source, importer);
14670
14855
  return {
14671
14856
  id: source,
14672
14857
  external: true
@@ -14677,10 +14862,35 @@ function cloudflare2(pluginConfig = {}) {
14677
14862
  }
14678
14863
  ];
14679
14864
  function getWorkerConfig2(environmentName) {
14680
- assert8(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14865
+ assert10(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14681
14866
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
14682
14867
  }
14683
14868
  }
14869
+ async function getInputInspectorPortOption(pluginConfig, viteServer) {
14870
+ if (pluginConfig.inspectorPort === void 0 || pluginConfig.inspectorPort === 0) {
14871
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14872
+ if (resolvedInspectorPort !== null) {
14873
+ return resolvedInspectorPort;
14874
+ }
14875
+ }
14876
+ const inputInspectorPort = pluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
14877
+ if (pluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
14878
+ viteServer.config.logger.warn(
14879
+ colors3.dim(
14880
+ `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
14881
+ `
14882
+ )
14883
+ );
14884
+ }
14885
+ return inputInspectorPort;
14886
+ }
14887
+ async function getResolvedInspectorPort(pluginConfig) {
14888
+ if (miniflare && pluginConfig.inspectorPort !== false) {
14889
+ const miniflareInspectorUrl = await miniflare.getInspectorURL();
14890
+ return Number.parseInt(miniflareInspectorUrl.port);
14891
+ }
14892
+ return null;
14893
+ }
14684
14894
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14685
14895
  const configDir = path9.dirname(configPath);
14686
14896
  const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
@@ -14692,6 +14902,19 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14692
14902
  }
14693
14903
  return null;
14694
14904
  }
14905
+ function hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) {
14906
+ return [...resolvedPluginConfig.configPaths].some((configPath) => {
14907
+ const dotDevDotVars = path9.join(path9.dirname(configPath), ".dev.vars");
14908
+ if (dotDevDotVars === changedFilePath) {
14909
+ return true;
14910
+ }
14911
+ if (resolvedPluginConfig.cloudflareEnv) {
14912
+ const dotDevDotVarsForEnv = `${dotDevDotVars}.${resolvedPluginConfig.cloudflareEnv}`;
14913
+ return dotDevDotVarsForEnv === changedFilePath;
14914
+ }
14915
+ return false;
14916
+ });
14917
+ }
14695
14918
  export {
14696
14919
  cloudflare2 as cloudflare
14697
14920
  };