@cloudflare/vite-plugin 0.0.0-82f35b879 → 0.0.0-84ecfe9b4

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
@@ -248,17 +248,17 @@ var require_ignore = __commonJS({
248
248
  var throwError = (message, Ctor) => {
249
249
  throw new Ctor(message);
250
250
  };
251
- var checkPath = (path9, originalPath, doThrow) => {
252
- if (!isString(path9)) {
251
+ var checkPath = (path10, originalPath, doThrow) => {
252
+ if (!isString(path10)) {
253
253
  return doThrow(
254
254
  `path must be a string, but got \`${originalPath}\``,
255
255
  TypeError
256
256
  );
257
257
  }
258
- if (!path9) {
258
+ if (!path10) {
259
259
  return doThrow(`path must not be empty`, TypeError);
260
260
  }
261
- if (checkPath.isNotRelative(path9)) {
261
+ if (checkPath.isNotRelative(path10)) {
262
262
  const r2 = "`path.relative()`d";
263
263
  return doThrow(
264
264
  `path should be a ${r2} string, but got "${originalPath}"`,
@@ -267,7 +267,7 @@ var require_ignore = __commonJS({
267
267
  }
268
268
  return true;
269
269
  };
270
- var isNotRelative = (path9) => REGEX_TEST_INVALID_PATH.test(path9);
270
+ var isNotRelative = (path10) => REGEX_TEST_INVALID_PATH.test(path10);
271
271
  checkPath.isNotRelative = isNotRelative;
272
272
  checkPath.convert = (p) => p;
273
273
  var Ignore = class {
@@ -326,7 +326,7 @@ var require_ignore = __commonJS({
326
326
  // setting `checkUnignored` to `false` could reduce additional
327
327
  // path matching.
328
328
  // @returns {TestResult} true if a file is ignored
329
- _testOne(path9, checkUnignored) {
329
+ _testOne(path10, checkUnignored) {
330
330
  let ignored = false;
331
331
  let unignored = false;
332
332
  this._rules.forEach((rule) => {
@@ -334,7 +334,7 @@ var require_ignore = __commonJS({
334
334
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
335
335
  return;
336
336
  }
337
- const matched = rule.regex.test(path9);
337
+ const matched = rule.regex.test(path10);
338
338
  if (matched) {
339
339
  ignored = !negative;
340
340
  unignored = negative;
@@ -347,24 +347,24 @@ var require_ignore = __commonJS({
347
347
  }
348
348
  // @returns {TestResult}
349
349
  _test(originalPath, cache2, checkUnignored, slices) {
350
- const path9 = originalPath && checkPath.convert(originalPath);
350
+ const path10 = originalPath && checkPath.convert(originalPath);
351
351
  checkPath(
352
- path9,
352
+ path10,
353
353
  originalPath,
354
354
  this._allowRelativePaths ? RETURN_FALSE : throwError
355
355
  );
356
- return this._t(path9, cache2, checkUnignored, slices);
356
+ return this._t(path10, cache2, checkUnignored, slices);
357
357
  }
358
- _t(path9, cache2, checkUnignored, slices) {
359
- if (path9 in cache2) {
360
- return cache2[path9];
358
+ _t(path10, cache2, checkUnignored, slices) {
359
+ if (path10 in cache2) {
360
+ return cache2[path10];
361
361
  }
362
362
  if (!slices) {
363
- slices = path9.split(SLASH);
363
+ slices = path10.split(SLASH);
364
364
  }
365
365
  slices.pop();
366
366
  if (!slices.length) {
367
- return cache2[path9] = this._testOne(path9, checkUnignored);
367
+ return cache2[path10] = this._testOne(path10, checkUnignored);
368
368
  }
369
369
  const parent = this._t(
370
370
  slices.join(SLASH) + SLASH,
@@ -372,24 +372,24 @@ var require_ignore = __commonJS({
372
372
  checkUnignored,
373
373
  slices
374
374
  );
375
- return cache2[path9] = parent.ignored ? parent : this._testOne(path9, checkUnignored);
375
+ return cache2[path10] = parent.ignored ? parent : this._testOne(path10, checkUnignored);
376
376
  }
377
- ignores(path9) {
378
- return this._test(path9, this._ignoreCache, false).ignored;
377
+ ignores(path10) {
378
+ return this._test(path10, this._ignoreCache, false).ignored;
379
379
  }
380
380
  createFilter() {
381
- return (path9) => !this.ignores(path9);
381
+ return (path10) => !this.ignores(path10);
382
382
  }
383
383
  filter(paths) {
384
384
  return makeArray(paths).filter(this.createFilter());
385
385
  }
386
386
  // @returns {TestResult}
387
- test(path9) {
388
- return this._test(path9, this._testCache, true);
387
+ test(path10) {
388
+ return this._test(path10, this._testCache, true);
389
389
  }
390
390
  };
391
391
  var factory = (options) => new Ignore(options);
392
- var isPathValid = (path9) => checkPath(path9 && checkPath.convert(path9), path9, RETURN_FALSE);
392
+ var isPathValid = (path10) => checkPath(path10 && checkPath.convert(path10), path10, RETURN_FALSE);
393
393
  factory.isPathValid = isPathValid;
394
394
  factory.default = factory;
395
395
  module.exports = factory;
@@ -400,7 +400,7 @@ var require_ignore = __commonJS({
400
400
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
401
401
  checkPath.convert = makePosix;
402
402
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
403
- checkPath.isNotRelative = (path9) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path9) || isNotRelative(path9);
403
+ checkPath.isNotRelative = (path10) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path10) || isNotRelative(path10);
404
404
  }
405
405
  }
406
406
  });
@@ -443,11 +443,11 @@ var require_Mime = __commonJS({
443
443
  }
444
444
  }
445
445
  };
446
- Mime.prototype.getType = function(path9) {
447
- path9 = String(path9);
448
- let last = path9.replace(/^.*[/\\]/, "").toLowerCase();
446
+ Mime.prototype.getType = function(path10) {
447
+ path10 = String(path10);
448
+ let last = path10.replace(/^.*[/\\]/, "").toLowerCase();
449
449
  let ext = last.replace(/^.*\./, "").toLowerCase();
450
- let hasPath = last.length < path9.length;
450
+ let hasPath = last.length < path10.length;
451
451
  let hasDot = ext.length < last.length - 1;
452
452
  return (hasDot || !hasPath) && this._types[ext] || null;
453
453
  };
@@ -485,12 +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
- import { builtinModules as builtinModules2 } from "node:module";
492
- import * as path8 from "node:path";
491
+ import * as path9 from "node:path";
493
492
  import { createMiddleware } from "@hattip/adapter-node";
493
+ import replace from "@rollup/plugin-replace";
494
494
 
495
495
  // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
496
496
  var comma = ",".charCodeAt(0);
@@ -1558,7 +1558,8 @@ var MagicString = class _MagicString {
1558
1558
 
1559
1559
  // src/index.ts
1560
1560
  import { Miniflare } from "miniflare";
1561
- import * as vite6 from "vite";
1561
+ import colors2 from "picocolors";
1562
+ import * as vite7 from "vite";
1562
1563
 
1563
1564
  // src/constants.ts
1564
1565
  var ROUTER_WORKER_NAME = "__router-worker__";
@@ -1726,11 +1727,11 @@ ${invalidHeaderRulesList}`
1726
1727
  }
1727
1728
 
1728
1729
  // ../workers-shared/utils/configuration/validateURL.ts
1729
- var extractPathname = (path9 = "/", includeSearch, includeHash) => {
1730
- if (!path9.startsWith("/")) {
1731
- path9 = `/${path9}`;
1730
+ var extractPathname = (path10 = "/", includeSearch, includeHash) => {
1731
+ if (!path10.startsWith("/")) {
1732
+ path10 = `/${path10}`;
1732
1733
  }
1733
- const url = new URL(`//${path9}`, "relative://");
1734
+ const url = new URL(`//${path10}`, "relative://");
1734
1735
  return `${url.pathname}${includeSearch ? url.search : ""}${includeHash ? url.hash : ""}`;
1735
1736
  };
1736
1737
  var URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
@@ -1763,8 +1764,8 @@ var validateUrl = (token, onlyRelative = false, disallowPorts = false, includeSe
1763
1764
  if (!token.startsWith("/") && onlyRelative) {
1764
1765
  token = `/${token}`;
1765
1766
  }
1766
- const path9 = PATH_REGEX.exec(token);
1767
- if (path9) {
1767
+ const path10 = PATH_REGEX.exec(token);
1768
+ if (path10) {
1768
1769
  try {
1769
1770
  return [extractPathname(token, includeSearch, includeHash), void 0];
1770
1771
  } catch {
@@ -1825,7 +1826,7 @@ function parseHeaders(input, {
1825
1826
  });
1826
1827
  }
1827
1828
  }
1828
- const [path9, pathError] = validateUrl(line, false, true);
1829
+ const [path10, pathError] = validateUrl(line, false, true);
1829
1830
  if (pathError) {
1830
1831
  invalid.push({
1831
1832
  line,
@@ -1836,7 +1837,7 @@ function parseHeaders(input, {
1836
1837
  continue;
1837
1838
  }
1838
1839
  rule = {
1839
- path: path9,
1840
+ path: path10,
1840
1841
  line,
1841
1842
  headers: {},
1842
1843
  unsetHeaders: []
@@ -2411,8 +2412,8 @@ function getErrorMap() {
2411
2412
  return overrideErrorMap;
2412
2413
  }
2413
2414
  var makeIssue = (params) => {
2414
- const { data: data2, path: path9, errorMaps, issueData } = params;
2415
- const fullPath = [...path9, ...issueData.path || []];
2415
+ const { data: data2, path: path10, errorMaps, issueData } = params;
2416
+ const fullPath = [...path10, ...issueData.path || []];
2416
2417
  const fullIssue = {
2417
2418
  ...issueData,
2418
2419
  path: fullPath
@@ -2511,11 +2512,11 @@ var errorUtil;
2511
2512
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
2512
2513
  })(errorUtil || (errorUtil = {}));
2513
2514
  var ParseInputLazyPath = class {
2514
- constructor(parent, value, path9, key) {
2515
+ constructor(parent, value, path10, key) {
2515
2516
  this._cachedPath = [];
2516
2517
  this.parent = parent;
2517
2518
  this.data = value;
2518
- this._path = path9;
2519
+ this._path = path10;
2519
2520
  this._key = key;
2520
2521
  }
2521
2522
  get path() {
@@ -5831,14 +5832,14 @@ var AssetConfigSchema = z.object({
5831
5832
  });
5832
5833
 
5833
5834
  // src/asset-config.ts
5834
- function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFile) {
5835
+ function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFilePath) {
5835
5836
  if (!resolvedPluginConfig.experimental?.headersAndRedirectsDevModeSupport) {
5836
5837
  return false;
5837
5838
  }
5838
5839
  return [
5839
5840
  getRedirectsConfigPath(resolvedViteConfig),
5840
5841
  getHeadersConfigPath(resolvedViteConfig)
5841
- ].includes(path.resolve(changedFile));
5842
+ ].includes(changedFilePath);
5842
5843
  }
5843
5844
  function getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedConfig) {
5844
5845
  const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
@@ -5905,10 +5906,12 @@ function getHeadersConfigPath(config) {
5905
5906
 
5906
5907
  // src/cloudflare-environment.ts
5907
5908
  import assert3 from "node:assert";
5908
- import * as vite2 from "vite";
5909
+ import * as vite3 from "vite";
5909
5910
 
5910
5911
  // src/node-js-compat.ts
5911
5912
  import assert2 from "node:assert";
5913
+ import { builtinModules as builtinModules2 } from "node:module";
5914
+ import path3 from "node:path";
5912
5915
  import { cloudflare } from "@cloudflare/unenv-preset";
5913
5916
  import { getNodeCompat } from "miniflare";
5914
5917
 
@@ -11460,17 +11463,17 @@ function withTrailingSlash(input = "", respectQueryAndFragment) {
11460
11463
  if (hasTrailingSlash(input, true)) {
11461
11464
  return input || "/";
11462
11465
  }
11463
- let path9 = input;
11466
+ let path10 = input;
11464
11467
  let fragment = "";
11465
11468
  const fragmentIndex = input.indexOf("#");
11466
11469
  if (fragmentIndex >= 0) {
11467
- path9 = input.slice(0, fragmentIndex);
11470
+ path10 = input.slice(0, fragmentIndex);
11468
11471
  fragment = input.slice(fragmentIndex);
11469
- if (!path9) {
11472
+ if (!path10) {
11470
11473
  return fragment;
11471
11474
  }
11472
11475
  }
11473
- const [s0, ...s] = path9.split("?");
11476
+ const [s0, ...s] = path10.split("?");
11474
11477
  return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
11475
11478
  }
11476
11479
  function isNonEmptyURL(url) {
@@ -11504,8 +11507,8 @@ import path2, { dirname as dirname2 } from "node:path";
11504
11507
  import v8 from "node:v8";
11505
11508
  import { format as format2, inspect } from "node:util";
11506
11509
  var BUILTIN_MODULES = new Set(builtinModules);
11507
- function normalizeSlash(path9) {
11508
- return path9.replace(/\\/g, "/");
11510
+ function normalizeSlash(path10) {
11511
+ return path10.replace(/\\/g, "/");
11509
11512
  }
11510
11513
  var own$1 = {}.hasOwnProperty;
11511
11514
  var classRegExp = /^([A-Z][a-z\d]*)+$/;
@@ -11618,8 +11621,8 @@ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
11618
11621
  * @param {string} [base]
11619
11622
  * @param {string} [message]
11620
11623
  */
11621
- (path9, base, message) => {
11622
- return `Invalid package config ${path9}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11624
+ (path10, base, message) => {
11625
+ return `Invalid package config ${path10}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11623
11626
  },
11624
11627
  Error
11625
11628
  );
@@ -11651,8 +11654,8 @@ codes.ERR_MODULE_NOT_FOUND = createError(
11651
11654
  * @param {string} base
11652
11655
  * @param {boolean} [exactUrl]
11653
11656
  */
11654
- (path9, base, exactUrl = false) => {
11655
- return `Cannot find ${exactUrl ? "module" : "package"} '${path9}' imported from ${base}`;
11657
+ (path10, base, exactUrl = false) => {
11658
+ return `Cannot find ${exactUrl ? "module" : "package"} '${path10}' imported from ${base}`;
11656
11659
  },
11657
11660
  Error
11658
11661
  );
@@ -11703,8 +11706,8 @@ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
11703
11706
  * @param {string} extension
11704
11707
  * @param {string} path
11705
11708
  */
11706
- (extension, path9) => {
11707
- return `Unknown file extension "${extension}" for ${path9}`;
11709
+ (extension, path10) => {
11710
+ return `Unknown file extension "${extension}" for ${path10}`;
11708
11711
  },
11709
11712
  TypeError
11710
11713
  );
@@ -12076,9 +12079,9 @@ Default "index" lookups for the main are deprecated for ES modules.`,
12076
12079
  );
12077
12080
  }
12078
12081
  }
12079
- function tryStatSync(path9) {
12082
+ function tryStatSync(path10) {
12080
12083
  try {
12081
- return statSync(path9);
12084
+ return statSync(path10);
12082
12085
  } catch {
12083
12086
  }
12084
12087
  }
@@ -12845,12 +12848,20 @@ function resolvePathSync(id, options) {
12845
12848
 
12846
12849
  // src/node-js-compat.ts
12847
12850
  import { defineEnv } from "unenv";
12851
+ import "vite";
12848
12852
  var { env } = defineEnv({
12849
12853
  nodeCompat: true,
12850
12854
  presets: [cloudflare]
12851
12855
  });
12852
12856
  var nodeCompatExternals = new Set(env.external);
12853
12857
  var nodeCompatEntries = getNodeCompatEntries();
12858
+ var nodejsBuiltins = /* @__PURE__ */ new Set([
12859
+ ...builtinModules2,
12860
+ ...builtinModules2.map((m) => `node:${m}`)
12861
+ ]);
12862
+ var NODEJS_MODULES_RE = new RegExp(
12863
+ `^(node:)?(${builtinModules2.join("|")})$`
12864
+ );
12854
12865
  function isNodeCompat(workerConfig) {
12855
12866
  if (workerConfig === void 0) {
12856
12867
  return false;
@@ -12869,6 +12880,15 @@ function isNodeCompat(workerConfig) {
12869
12880
  }
12870
12881
  return false;
12871
12882
  }
12883
+ function isNodeAls(workerConfig) {
12884
+ return workerConfig !== void 0 && getNodeCompat(
12885
+ workerConfig.compatibility_date,
12886
+ workerConfig.compatibility_flags ?? []
12887
+ ).mode === "als";
12888
+ }
12889
+ function isNodeAlsModule(path10) {
12890
+ return /^(node:)?async_hooks$/.test(path10);
12891
+ }
12872
12892
  function injectGlobalCode(id, code) {
12873
12893
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
12874
12894
  if (typeof globalInject === "string") {
@@ -12899,7 +12919,7 @@ globalThis.${globalName} = var_${globalName}.${exportName};
12899
12919
  }
12900
12920
  function resolveNodeJSImport(source) {
12901
12921
  const alias = env.alias[source];
12902
- if (alias) {
12922
+ if (alias && !nodeCompatExternals.has(alias)) {
12903
12923
  return {
12904
12924
  unresolved: alias,
12905
12925
  resolved: resolvePathSync(alias, { url: import.meta.url })
@@ -12929,6 +12949,45 @@ function getNodeCompatEntries() {
12929
12949
  nodeCompatExternals.forEach((external) => entries.delete(external));
12930
12950
  return entries;
12931
12951
  }
12952
+ var NodeJsCompatWarnings = class {
12953
+ constructor(environmentName, resolvedViteConfig) {
12954
+ this.environmentName = environmentName;
12955
+ this.resolvedViteConfig = resolvedViteConfig;
12956
+ }
12957
+ sources = /* @__PURE__ */ new Map();
12958
+ timer;
12959
+ registerImport(source, importer = "<unknown>") {
12960
+ const importers = this.sources.get(source) ?? /* @__PURE__ */ new Set();
12961
+ this.sources.set(source, importers);
12962
+ importers.add(importer);
12963
+ this.renderWarningsOnIdle();
12964
+ }
12965
+ renderWarningsOnIdle() {
12966
+ if (this.timer) {
12967
+ clearTimeout(this.timer);
12968
+ }
12969
+ this.timer = setTimeout(() => {
12970
+ this.renderWarnings();
12971
+ this.timer = void 0;
12972
+ }, 500);
12973
+ }
12974
+ renderWarnings() {
12975
+ if (this.sources.size > 0) {
12976
+ 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.
12977
+ `;
12978
+ this.sources.forEach((importers, source) => {
12979
+ importers.forEach((importer) => {
12980
+ message += ` - "${source}" imported from "${path3.relative(this.resolvedViteConfig.root, importer)}"
12981
+ `;
12982
+ });
12983
+ });
12984
+ this.resolvedViteConfig.logger.warn(message, {
12985
+ timestamp: true
12986
+ });
12987
+ this.sources.clear();
12988
+ }
12989
+ }
12990
+ };
12932
12991
 
12933
12992
  // src/shared.ts
12934
12993
  var UNKNOWN_HOST = "http://localhost";
@@ -12942,17 +13001,22 @@ var additionalModuleGlobalRE = new RegExp(
12942
13001
  var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
12943
13002
 
12944
13003
  // src/utils.ts
12945
- import * as path3 from "node:path";
13004
+ import * as path4 from "node:path";
13005
+ import getPort, { portNumbers } from "get-port";
12946
13006
  import { Request as MiniflareRequest } from "miniflare";
12947
13007
  import "vite";
12948
13008
  function getOutputDirectory(userConfig, environmentName) {
12949
13009
  const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
12950
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path3.join(rootOutputDirectory, environmentName);
13010
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path4.join(rootOutputDirectory, environmentName);
12951
13011
  }
12952
- function getRouterWorker(miniflare) {
12953
- return miniflare.getWorker(ROUTER_WORKER_NAME);
13012
+ function getRouterWorker(miniflare2) {
13013
+ return miniflare2.getWorker(ROUTER_WORKER_NAME);
12954
13014
  }
12955
13015
  function toMiniflareRequest(request) {
13016
+ const host = request.headers.get("Host");
13017
+ if (host) {
13018
+ request.headers.set("X-Forwarded-Host", host);
13019
+ }
12956
13020
  const secFetchMode = request.headers.get("Sec-Fetch-Mode");
12957
13021
  if (secFetchMode) {
12958
13022
  request.headers.set("X-Mf-Sec-Fetch-Mode", secFetchMode);
@@ -12981,6 +13045,9 @@ var postfixRE = /[?#].*$/;
12981
13045
  function cleanUrl(url) {
12982
13046
  return url.replace(postfixRE, "");
12983
13047
  }
13048
+ function getFirstAvailablePort(start) {
13049
+ return getPort({ port: portNumbers(start, 65535) });
13050
+ }
12984
13051
 
12985
13052
  // src/cloudflare-environment.ts
12986
13053
  var webSocketUndefinedError = "The WebSocket is undefined";
@@ -13026,7 +13093,7 @@ function createHotChannel(webSocketContainer) {
13026
13093
  }
13027
13094
  };
13028
13095
  }
13029
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
13096
+ var CloudflareDevEnvironment = class extends vite3.DevEnvironment {
13030
13097
  #webSocketContainer;
13031
13098
  #worker;
13032
13099
  constructor(name, config) {
@@ -13087,7 +13154,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
13087
13154
  },
13088
13155
  build: {
13089
13156
  createEnvironment(name, config) {
13090
- return new vite2.BuildEnvironment(name, config);
13157
+ return new vite3.BuildEnvironment(name, config);
13091
13158
  },
13092
13159
  target,
13093
13160
  // We need to enable `emitAssets` in order to support additional modules defined by `rules`
@@ -13130,14 +13197,14 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
13130
13197
  keepProcessEnv: isNodeCompat(workerConfig)
13131
13198
  };
13132
13199
  }
13133
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
13200
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare2) {
13134
13201
  if (resolvedPluginConfig.type === "assets-only") {
13135
13202
  return;
13136
13203
  }
13137
13204
  return Promise.all(
13138
13205
  Object.entries(resolvedPluginConfig.workers).map(
13139
13206
  async ([environmentName, workerConfig]) => {
13140
- const worker = await miniflare.getWorker(workerConfig.name);
13207
+ const worker = await miniflare2.getWorker(workerConfig.name);
13141
13208
  return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
13142
13209
  }
13143
13210
  )
@@ -13196,11 +13263,11 @@ function getDebugPathHtml(workerNames, inspectorPort) {
13196
13263
  // src/deploy-config.ts
13197
13264
  import assert5 from "node:assert";
13198
13265
  import * as fs2 from "node:fs";
13199
- import * as path4 from "node:path";
13266
+ import * as path5 from "node:path";
13200
13267
  import "vite";
13201
13268
  import { unstable_readConfig } from "wrangler";
13202
13269
  function getDeployConfigPath(root) {
13203
- return path4.resolve(root, ".wrangler", "deploy", "config.json");
13270
+ return path5.resolve(root, ".wrangler", "deploy", "config.json");
13204
13271
  }
13205
13272
  function getWorkerConfigs(root) {
13206
13273
  const deployConfigPath = getDeployConfigPath(root);
@@ -13211,22 +13278,22 @@ function getWorkerConfigs(root) {
13211
13278
  { configPath: deployConfig.configPath },
13212
13279
  ...deployConfig.auxiliaryWorkers
13213
13280
  ].map(({ configPath }) => {
13214
- const resolvedConfigPath = path4.resolve(
13215
- path4.dirname(deployConfigPath),
13281
+ const resolvedConfigPath = path5.resolve(
13282
+ path5.dirname(deployConfigPath),
13216
13283
  configPath
13217
13284
  );
13218
13285
  return unstable_readConfig({ config: resolvedConfigPath });
13219
13286
  });
13220
13287
  }
13221
13288
  function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
13222
- return path4.relative(
13289
+ return path5.relative(
13223
13290
  deployConfigDirectory,
13224
- path4.resolve(root, outputDirectory, "wrangler.json")
13291
+ path5.resolve(root, outputDirectory, "wrangler.json")
13225
13292
  );
13226
13293
  }
13227
13294
  function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13228
13295
  const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
13229
- const deployConfigDirectory = path4.dirname(deployConfigPath);
13296
+ const deployConfigDirectory = path5.dirname(deployConfigPath);
13230
13297
  fs2.mkdirSync(deployConfigDirectory, { recursive: true });
13231
13298
  if (resolvedPluginConfig.type === "assets-only") {
13232
13299
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
@@ -13279,7 +13346,7 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13279
13346
  import assert6 from "node:assert";
13280
13347
  import * as fs3 from "node:fs";
13281
13348
  import * as fsp from "node:fs/promises";
13282
- import * as path5 from "node:path";
13349
+ import * as path6 from "node:path";
13283
13350
  import { fileURLToPath as fileURLToPath2 } from "node:url";
13284
13351
  import {
13285
13352
  kCurrentWorker,
@@ -13295,18 +13362,18 @@ function getPersistence(root, persistState) {
13295
13362
  return {};
13296
13363
  }
13297
13364
  const defaultPersistPath = ".wrangler/state";
13298
- const persistPath = path5.resolve(
13365
+ const persistPath = path6.resolve(
13299
13366
  root,
13300
13367
  typeof persistState === "object" ? persistState.path : defaultPersistPath,
13301
13368
  "v3"
13302
13369
  );
13303
13370
  return {
13304
- cachePersist: path5.join(persistPath, "cache"),
13305
- d1Persist: path5.join(persistPath, "d1"),
13306
- durableObjectsPersist: path5.join(persistPath, "do"),
13307
- kvPersist: path5.join(persistPath, "kv"),
13308
- r2Persist: path5.join(persistPath, "r2"),
13309
- workflowsPersist: path5.join(persistPath, "workflows")
13371
+ cachePersist: path6.join(persistPath, "cache"),
13372
+ d1Persist: path6.join(persistPath, "d1"),
13373
+ durableObjectsPersist: path6.join(persistPath, "do"),
13374
+ kvPersist: path6.join(persistPath, "kv"),
13375
+ r2Persist: path6.join(persistPath, "r2"),
13376
+ workflowsPersist: path6.join(persistPath, "workflows")
13310
13377
  };
13311
13378
  }
13312
13379
  function missingWorkerErrorMessage(workerName) {
@@ -13391,7 +13458,7 @@ function getEntryWorkerConfig(resolvedPluginConfig) {
13391
13458
  }
13392
13459
  return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
13393
13460
  }
13394
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13461
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspectorPort) {
13395
13462
  const resolvedViteConfig = viteDevServer.config;
13396
13463
  const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
13397
13464
  const assetsConfig = getAssetsConfig(
@@ -13407,7 +13474,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13407
13474
  modules: [
13408
13475
  {
13409
13476
  type: "ESModule",
13410
- path: path5.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13477
+ path: path6.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13411
13478
  contents: fs3.readFileSync(
13412
13479
  fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
13413
13480
  )
@@ -13430,7 +13497,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13430
13497
  modules: [
13431
13498
  {
13432
13499
  type: "ESModule",
13433
- path: path5.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13500
+ path: path6.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13434
13501
  contents: fs3.readFileSync(
13435
13502
  fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
13436
13503
  )
@@ -13442,7 +13509,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13442
13509
  serviceBindings: {
13443
13510
  __VITE_ASSET_EXISTS__: async (request) => {
13444
13511
  const { pathname } = new URL(request.url);
13445
- const filePath = path5.join(resolvedViteConfig.root, pathname);
13512
+ const filePath = path6.join(resolvedViteConfig.root, pathname);
13446
13513
  let exists;
13447
13514
  try {
13448
13515
  exists = fs3.statSync(filePath).isFile();
@@ -13453,7 +13520,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13453
13520
  },
13454
13521
  __VITE_FETCH_ASSET__: async (request) => {
13455
13522
  const { pathname } = new URL(request.url);
13456
- const filePath = path5.join(resolvedViteConfig.root, pathname);
13523
+ const filePath = path6.join(resolvedViteConfig.root, pathname);
13457
13524
  try {
13458
13525
  let html = await fsp.readFile(filePath, "utf-8");
13459
13526
  html = await viteDevServer.transformIndexHtml(pathname, html);
@@ -13483,7 +13550,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13483
13550
  worker: {
13484
13551
  ...workerOptions,
13485
13552
  name: workerOptions.name ?? workerConfig.name,
13486
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13553
+ unsafeInspectorProxy: inspectorPort !== false,
13487
13554
  modulesRoot: miniflareModulesRoot,
13488
13555
  unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
13489
13556
  serviceBindings: {
@@ -13525,8 +13592,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13525
13592
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13526
13593
  return {
13527
13594
  log: logger,
13528
- inspectorPort: resolvedPluginConfig.inspectorPort || void 0,
13529
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13595
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13596
+ unsafeInspectorProxy: inspectorPort !== false,
13530
13597
  handleRuntimeStdio(stdout, stderr) {
13531
13598
  const decoder = new TextDecoder();
13532
13599
  stdout.forEach((data2) => logger.info(decoder.decode(data2)));
@@ -13585,12 +13652,12 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13585
13652
  modules: [
13586
13653
  {
13587
13654
  type: "ESModule",
13588
- path: path5.join(miniflareModulesRoot, WRAPPER_PATH),
13655
+ path: path6.join(miniflareModulesRoot, WRAPPER_PATH),
13589
13656
  contents: wrappers.join("\n")
13590
13657
  },
13591
13658
  {
13592
13659
  type: "ESModule",
13593
- path: path5.join(miniflareModulesRoot, RUNNER_PATH),
13660
+ path: path6.join(miniflareModulesRoot, RUNNER_PATH),
13594
13661
  contents: fs3.readFileSync(
13595
13662
  fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
13596
13663
  )
@@ -13645,8 +13712,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13645
13712
  }
13646
13713
  function getPreviewModules(main, modulesRules) {
13647
13714
  assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
13648
- const rootPath = path5.dirname(main);
13649
- const entryPath = path5.basename(main);
13715
+ const rootPath = path6.dirname(main);
13716
+ const entryPath = path6.basename(main);
13650
13717
  return {
13651
13718
  rootPath,
13652
13719
  modules: [
@@ -13655,15 +13722,15 @@ function getPreviewModules(main, modulesRules) {
13655
13722
  path: entryPath
13656
13723
  },
13657
13724
  ...modulesRules.flatMap(
13658
- ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path9) => ({
13725
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path10) => ({
13659
13726
  type,
13660
- path: path9
13727
+ path: path10
13661
13728
  }))
13662
13729
  )
13663
13730
  ]
13664
13731
  };
13665
13732
  }
13666
- function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort = DEFAULT_INSPECTOR_PORT) {
13733
+ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort) {
13667
13734
  const resolvedViteConfig = vitePreviewServer.config;
13668
13735
  const workers = workerConfigs.flatMap((config) => {
13669
13736
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
@@ -13682,7 +13749,7 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13682
13749
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13683
13750
  return {
13684
13751
  log: logger,
13685
- inspectorPort: inspectorPort || void 0,
13752
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13686
13753
  unsafeInspectorProxy: inspectorPort !== false,
13687
13754
  handleRuntimeStdio(stdout, stderr) {
13688
13755
  const decoder = new TextDecoder();
@@ -13695,6 +13762,7 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13695
13762
  workers
13696
13763
  };
13697
13764
  }
13765
+ var removedMessages = [/^Ready on http/, /^Updated and ready on http/];
13698
13766
  var ViteMiniflareLogger = class extends Log {
13699
13767
  logger;
13700
13768
  constructor(config) {
@@ -13702,8 +13770,10 @@ var ViteMiniflareLogger = class extends Log {
13702
13770
  this.logger = config.logger;
13703
13771
  }
13704
13772
  logWithLevel(level, message) {
13705
- if (/^Ready on http/.test(message)) {
13706
- level = LogLevel.DEBUG;
13773
+ for (const removedMessage of removedMessages) {
13774
+ if (removedMessage.test(message)) {
13775
+ return;
13776
+ }
13707
13777
  }
13708
13778
  switch (level) {
13709
13779
  case LogLevel.ERROR:
@@ -13729,13 +13799,14 @@ function miniflareLogLevelFromViteLogLevel(level = "info") {
13729
13799
  }
13730
13800
 
13731
13801
  // src/plugin-config.ts
13732
- import assert7 from "node:assert";
13733
- import * as path7 from "node:path";
13734
- import * as vite5 from "vite";
13802
+ import assert8 from "node:assert";
13803
+ import * as path8 from "node:path";
13804
+ import * as vite6 from "vite";
13735
13805
 
13736
13806
  // src/workers-configs.ts
13807
+ import assert7 from "node:assert";
13737
13808
  import * as fs4 from "node:fs";
13738
- import * as path6 from "node:path";
13809
+ import * as path7 from "node:path";
13739
13810
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
13740
13811
  var nonApplicableWorkerConfigs = {
13741
13812
  /**
@@ -13767,8 +13838,7 @@ var nonApplicableWorkerConfigs = {
13767
13838
  "preserve_file_names",
13768
13839
  "rules",
13769
13840
  "site",
13770
- "tsconfig",
13771
- "upload_source_maps"
13841
+ "tsconfig"
13772
13842
  ]
13773
13843
  };
13774
13844
  var nullableNonApplicable = [
@@ -13779,8 +13849,7 @@ var nullableNonApplicable = [
13779
13849
  "no_bundle",
13780
13850
  "preserve_file_names",
13781
13851
  "site",
13782
- "tsconfig",
13783
- "upload_source_maps"
13852
+ "tsconfig"
13784
13853
  ];
13785
13854
  function readWorkerConfig(configPath, env2) {
13786
13855
  const nonApplicable = {
@@ -13829,7 +13898,7 @@ function getWarningForWorkersConfigs(configs) {
13829
13898
  const lines2 = [
13830
13899
  `
13831
13900
 
13832
- \x1B[43mWARNING\x1B[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path6.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`
13901
+ \x1B[43mWARNING\x1B[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path7.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`
13833
13902
  ];
13834
13903
  nonApplicableLines.forEach((line) => lines2.push(line));
13835
13904
  lines2.push("");
@@ -13843,7 +13912,7 @@ function getWarningForWorkersConfigs(configs) {
13843
13912
  );
13844
13913
  if (nonApplicableLines.length > 0) {
13845
13914
  lines.push(
13846
- ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path6.relative("", workerConfig.config.configPath)}\`)` : ""}`
13915
+ ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path7.relative("", workerConfig.config.configPath)}\`)` : ""}`
13847
13916
  );
13848
13917
  nonApplicableLines.forEach((line) => lines.push(line));
13849
13918
  }
@@ -13942,14 +14011,52 @@ function getWorkerConfig(configPath, env2, opts) {
13942
14011
  nonApplicable
13943
14012
  };
13944
14013
  }
14014
+ function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
14015
+ if (requestedConfigPath) {
14016
+ const configPath2 = path7.resolve(root, requestedConfigPath);
14017
+ const forAuxiliaryWorkerErrorMessage = isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : "";
14018
+ const errorMessagePrefix = `The provided configPath (${configPath2})${forAuxiliaryWorkerErrorMessage}`;
14019
+ const fileExtension = path7.extname(configPath2).slice(1);
14020
+ if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
14021
+ const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
14022
+ throw new Error(
14023
+ `${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`
14024
+ );
14025
+ }
14026
+ const mainStat = fs4.statSync(configPath2, { throwIfNoEntry: false });
14027
+ if (!mainStat) {
14028
+ throw new Error(
14029
+ `${errorMessagePrefix} doesn't point to an existing file`
14030
+ );
14031
+ }
14032
+ if (mainStat.isDirectory()) {
14033
+ throw new Error(
14034
+ `${errorMessagePrefix} points to a directory. It should point to a file.`
14035
+ );
14036
+ }
14037
+ return configPath2;
14038
+ }
14039
+ assert7(
14040
+ isForAuxiliaryWorker === false,
14041
+ "Unexpected Error: trying to find the wrangler config for an auxiliary worker"
14042
+ );
14043
+ const configPath = findWranglerConfig(root);
14044
+ if (!configPath) {
14045
+ throw new Error(
14046
+ `No config file found in the ${root} directory. Please add a wrangler.(jsonc|json|toml) file.`
14047
+ );
14048
+ }
14049
+ return configPath;
14050
+ }
13945
14051
  function findWranglerConfig(root) {
13946
- for (const extension of ["json", "jsonc", "toml"]) {
13947
- const configPath = path6.join(root, `wrangler.${extension}`);
14052
+ for (const extension of allowedWranglerConfigExtensions) {
14053
+ const configPath = path7.join(root, `wrangler.${extension}`);
13948
14054
  if (fs4.existsSync(configPath)) {
13949
14055
  return configPath;
13950
14056
  }
13951
14057
  }
13952
14058
  }
14059
+ var allowedWranglerConfigExtensions = ["jsonc", "json", "toml"];
13953
14060
 
13954
14061
  // src/plugin-config.ts
13955
14062
  function workerNameToEnvironmentName(workerName) {
@@ -13958,31 +14065,31 @@ function workerNameToEnvironmentName(workerName) {
13958
14065
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
13959
14066
  const configPaths = /* @__PURE__ */ new Set();
13960
14067
  const persistState = pluginConfig.persistState ?? true;
13961
- const inspectorPort = pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT;
13962
14068
  const experimental = pluginConfig.experimental ?? {};
13963
- const root = userConfig.root ? path7.resolve(userConfig.root) : process.cwd();
13964
- const { CLOUDFLARE_ENV: cloudflareEnv } = vite5.loadEnv(
14069
+ const root = userConfig.root ? path8.resolve(userConfig.root) : process.cwd();
14070
+ const { CLOUDFLARE_ENV: cloudflareEnv } = vite6.loadEnv(
13965
14071
  viteEnv.mode,
13966
14072
  root,
13967
14073
  /* prefixes */
13968
14074
  ""
13969
14075
  );
13970
- const configPath = pluginConfig.configPath ? path7.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
13971
- if (!configPath) {
13972
- throw new Error(
13973
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
13974
- );
13975
- }
13976
- const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
13977
- visitedConfigPaths: configPaths,
13978
- isEntryWorker: true
13979
- });
14076
+ const entryWorkerConfigPath = getValidatedWranglerConfigPath(
14077
+ root,
14078
+ pluginConfig.configPath
14079
+ );
14080
+ const entryWorkerResolvedConfig = getWorkerConfig(
14081
+ entryWorkerConfigPath,
14082
+ cloudflareEnv,
14083
+ {
14084
+ visitedConfigPaths: configPaths,
14085
+ isEntryWorker: true
14086
+ }
14087
+ );
13980
14088
  if (entryWorkerResolvedConfig.type === "assets-only") {
13981
14089
  return {
13982
14090
  type: "assets-only",
13983
14091
  config: entryWorkerResolvedConfig.config,
13984
14092
  configPaths,
13985
- inspectorPort,
13986
14093
  persistState,
13987
14094
  rawConfigs: {
13988
14095
  entryWorker: entryWorkerResolvedConfig
@@ -13998,15 +14105,20 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
13998
14105
  };
13999
14106
  const auxiliaryWorkersResolvedConfigs = [];
14000
14107
  for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
14108
+ const workerConfigPath = getValidatedWranglerConfigPath(
14109
+ root,
14110
+ auxiliaryWorker.configPath,
14111
+ true
14112
+ );
14001
14113
  const workerResolvedConfig = getWorkerConfig(
14002
- path7.resolve(root, auxiliaryWorker.configPath),
14114
+ workerConfigPath,
14003
14115
  cloudflareEnv,
14004
14116
  {
14005
14117
  visitedConfigPaths: configPaths
14006
14118
  }
14007
14119
  );
14008
14120
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
14009
- assert7(
14121
+ assert8(
14010
14122
  workerResolvedConfig.type === "worker",
14011
14123
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
14012
14124
  );
@@ -14023,7 +14135,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14023
14135
  type: "workers",
14024
14136
  configPaths,
14025
14137
  persistState,
14026
- inspectorPort,
14027
14138
  workers,
14028
14139
  entryWorkerEnvironmentName,
14029
14140
  rawConfigs: {
@@ -14038,7 +14149,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14038
14149
  // src/websockets.ts
14039
14150
  import { coupleWebSocket } from "miniflare";
14040
14151
  import { WebSocketServer } from "ws";
14041
- function handleWebSocket(httpServer, fetcher) {
14152
+ function handleWebSocket(httpServer, getFetcher) {
14042
14153
  const nodeWebSocket = new WebSocketServer({ noServer: true });
14043
14154
  httpServer.on(
14044
14155
  "upgrade",
@@ -14048,6 +14159,7 @@ function handleWebSocket(httpServer, fetcher) {
14048
14159
  return;
14049
14160
  }
14050
14161
  const headers = nodeHeadersToWebHeaders(request.headers);
14162
+ const fetcher = await getFetcher();
14051
14163
  const response = await fetcher(url, {
14052
14164
  headers,
14053
14165
  method: request.method
@@ -14070,13 +14182,65 @@ function handleWebSocket(httpServer, fetcher) {
14070
14182
  );
14071
14183
  }
14072
14184
 
14185
+ // src/worker-environments-validation.ts
14186
+ import assert9 from "node:assert";
14187
+ function validateWorkerEnvironmentsResolvedConfigs(resolvedPluginConfig, resolvedViteConfig) {
14188
+ const workersEnvironmentNames = Object.keys(resolvedPluginConfig.workers);
14189
+ const disallowedEnvsConfigs = /* @__PURE__ */ new Map();
14190
+ for (const envName of workersEnvironmentNames) {
14191
+ const workerEnvConfig = resolvedViteConfig.environments[envName];
14192
+ assert9(workerEnvConfig, `Missing environment config for "${envName}"`);
14193
+ const { optimizeDeps, resolve: resolve7 } = workerEnvConfig;
14194
+ const disallowedConfig = {};
14195
+ const disallowedOptimizeDepsExcludeEntries = (optimizeDeps.exclude ?? []).filter((entry) => {
14196
+ if (cloudflareBuiltInModules.includes(entry)) {
14197
+ return false;
14198
+ }
14199
+ if (isNodeAlsModule(entry) && isNodeAls(resolvedPluginConfig.workers[envName])) {
14200
+ return false;
14201
+ }
14202
+ if (NODEJS_MODULES_RE.test(entry) && isNodeCompat(resolvedPluginConfig.workers[envName])) {
14203
+ return false;
14204
+ }
14205
+ return true;
14206
+ });
14207
+ if (disallowedOptimizeDepsExcludeEntries.length > 0) {
14208
+ disallowedConfig.optimizeDepsExclude = disallowedOptimizeDepsExcludeEntries;
14209
+ }
14210
+ if (resolve7.external === true || resolve7.external.length > 0) {
14211
+ disallowedConfig.resolveExternal = resolve7.external;
14212
+ }
14213
+ if (Object.keys(disallowedConfig).length > 0) {
14214
+ disallowedEnvsConfigs.set(envName, disallowedConfig);
14215
+ }
14216
+ }
14217
+ if (disallowedEnvsConfigs.size > 0) {
14218
+ const errorMessage = `The following environment configurations are incompatible with the Cloudflare Vite plugin:
14219
+ ${[
14220
+ ...disallowedEnvsConfigs
14221
+ ].map(
14222
+ ([envName, disallowedConfig]) => [
14223
+ disallowedConfig.optimizeDepsExclude ? ` - "${envName}" environment: \`optimizeDeps.exclude\`: ${JSON.stringify(disallowedConfig.optimizeDepsExclude)}
14224
+ ` : null,
14225
+ disallowedConfig.resolveExternal ? ` - "${envName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedConfig.resolveExternal)}
14226
+ ` : null
14227
+ ].join("")
14228
+ ).join(
14229
+ ""
14230
+ )}To resolve this issue, avoid setting \`optimizeDeps.exclude\` and \`resolve.external\` in your Cloudflare Worker environments.
14231
+ `;
14232
+ throw new Error(errorMessage);
14233
+ }
14234
+ }
14235
+
14073
14236
  // src/index.ts
14074
14237
  var workersConfigsWarningShown = false;
14238
+ var miniflare;
14075
14239
  function cloudflare2(pluginConfig = {}) {
14076
14240
  let resolvedPluginConfig;
14077
14241
  let resolvedViteConfig;
14078
- let miniflare;
14079
14242
  const additionalModulePaths = /* @__PURE__ */ new Set();
14243
+ const nodeJsCompatWarningsMap = /* @__PURE__ */ new Map();
14080
14244
  let hasClientBuild = false;
14081
14245
  return [
14082
14246
  {
@@ -14127,7 +14291,7 @@ function cloudflare2(pluginConfig = {}) {
14127
14291
  builder: {
14128
14292
  buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
14129
14293
  const clientEnvironment = builder.environments.client;
14130
- const defaultHtmlPath = path8.resolve(
14294
+ const defaultHtmlPath = path9.resolve(
14131
14295
  builder.config.root,
14132
14296
  "index.html"
14133
14297
  );
@@ -14139,7 +14303,7 @@ function cloudflare2(pluginConfig = {}) {
14139
14303
  resolvedPluginConfig.workers
14140
14304
  ).map((environmentName) => {
14141
14305
  const environment = builder.environments[environmentName];
14142
- assert8(
14306
+ assert10(
14143
14307
  environment,
14144
14308
  `${environmentName} environment not found`
14145
14309
  );
@@ -14160,6 +14324,12 @@ function cloudflare2(pluginConfig = {}) {
14160
14324
  },
14161
14325
  configResolved(config) {
14162
14326
  resolvedViteConfig = config;
14327
+ if (resolvedPluginConfig?.type === "workers") {
14328
+ validateWorkerEnvironmentsResolvedConfigs(
14329
+ resolvedPluginConfig,
14330
+ resolvedViteConfig
14331
+ );
14332
+ }
14163
14333
  },
14164
14334
  generateBundle(_, bundle) {
14165
14335
  let config;
@@ -14180,15 +14350,15 @@ function cloudflare2(pluginConfig = {}) {
14180
14350
  if (isEntryWorker && hasClientBuild) {
14181
14351
  const workerOutputDirectory = this.environment.config.build.outDir;
14182
14352
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
14183
- assert8(
14353
+ assert10(
14184
14354
  clientOutputDirectory,
14185
14355
  "Unexpected error: client output directory is undefined"
14186
14356
  );
14187
14357
  workerConfig.assets = {
14188
14358
  ...workerConfig.assets,
14189
- directory: path8.relative(
14190
- path8.resolve(resolvedViteConfig.root, workerOutputDirectory),
14191
- path8.resolve(resolvedViteConfig.root, clientOutputDirectory)
14359
+ directory: path9.relative(
14360
+ path9.resolve(resolvedViteConfig.root, workerOutputDirectory),
14361
+ path9.resolve(resolvedViteConfig.root, clientOutputDirectory)
14192
14362
  )
14193
14363
  };
14194
14364
  } else {
@@ -14243,54 +14413,78 @@ function cloudflare2(pluginConfig = {}) {
14243
14413
  writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
14244
14414
  }
14245
14415
  },
14246
- handleHotUpdate(options) {
14247
- if (resolvedPluginConfig.configPaths.has(options.file) || hasAssetsConfigChanged(
14416
+ hotUpdate(options) {
14417
+ const changedFilePath = path9.resolve(options.file);
14418
+ if (resolvedPluginConfig.configPaths.has(changedFilePath) || hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(
14248
14419
  resolvedPluginConfig,
14249
14420
  resolvedViteConfig,
14250
- options.file
14421
+ changedFilePath
14251
14422
  )) {
14252
14423
  options.server.restart();
14253
- }
14254
- },
14255
- async buildEnd() {
14256
- if (miniflare) {
14257
- await miniflare.dispose();
14258
- miniflare = void 0;
14424
+ return [];
14259
14425
  }
14260
14426
  },
14261
14427
  async configureServer(viteDevServer) {
14262
- assert8(
14428
+ assert10(
14263
14429
  viteDevServer.httpServer,
14264
14430
  "Unexpected error: No Vite HTTP server"
14265
14431
  );
14266
- miniflare = new Miniflare(
14267
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14268
- );
14432
+ if (!miniflare) {
14433
+ const inputInspectorPort = await getInputInspectorPortOption(
14434
+ pluginConfig,
14435
+ viteDevServer
14436
+ );
14437
+ miniflare = new Miniflare(
14438
+ getDevMiniflareOptions(
14439
+ resolvedPluginConfig,
14440
+ viteDevServer,
14441
+ inputInspectorPort
14442
+ )
14443
+ );
14444
+ } else {
14445
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14446
+ await miniflare.setOptions(
14447
+ getDevMiniflareOptions(
14448
+ resolvedPluginConfig,
14449
+ viteDevServer,
14450
+ resolvedInspectorPort ?? false
14451
+ )
14452
+ );
14453
+ }
14269
14454
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14270
- const routerWorker = await getRouterWorker(miniflare);
14271
14455
  const middleware = createMiddleware(
14272
- ({ request }) => {
14456
+ async ({ request }) => {
14457
+ assert10(miniflare, `Miniflare not defined`);
14458
+ const routerWorker = await getRouterWorker(miniflare);
14273
14459
  return routerWorker.fetch(toMiniflareRequest(request), {
14274
14460
  redirect: "manual"
14275
14461
  });
14276
14462
  },
14277
14463
  { alwaysCallNext: false }
14278
14464
  );
14279
- handleWebSocket(viteDevServer.httpServer, routerWorker.fetch);
14465
+ handleWebSocket(viteDevServer.httpServer, async () => {
14466
+ assert10(miniflare, `Miniflare not defined`);
14467
+ const routerWorker = await getRouterWorker(miniflare);
14468
+ return routerWorker.fetch;
14469
+ });
14280
14470
  return () => {
14281
14471
  viteDevServer.middlewares.use((req, res, next) => {
14282
14472
  middleware(req, res, next);
14283
14473
  });
14284
14474
  };
14285
14475
  },
14286
- configurePreviewServer(vitePreviewServer) {
14476
+ async configurePreviewServer(vitePreviewServer) {
14287
14477
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14478
+ const inputInspectorPort = await getInputInspectorPortOption(
14479
+ pluginConfig,
14480
+ vitePreviewServer
14481
+ );
14288
14482
  const miniflare2 = new Miniflare(
14289
14483
  getPreviewMiniflareOptions(
14290
14484
  vitePreviewServer,
14291
14485
  workerConfigs,
14292
14486
  pluginConfig.persistState ?? true,
14293
- pluginConfig.inspectorPort
14487
+ inputInspectorPort
14294
14488
  )
14295
14489
  );
14296
14490
  const middleware = createMiddleware(
@@ -14301,7 +14495,10 @@ function cloudflare2(pluginConfig = {}) {
14301
14495
  },
14302
14496
  { alwaysCallNext: false }
14303
14497
  );
14304
- handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
14498
+ handleWebSocket(
14499
+ vitePreviewServer.httpServer,
14500
+ () => miniflare2.dispatchFetch
14501
+ );
14305
14502
  vitePreviewServer.middlewares.use((req, res, next) => {
14306
14503
  middleware(req, res, next);
14307
14504
  });
@@ -14357,6 +14554,7 @@ function cloudflare2(pluginConfig = {}) {
14357
14554
  hotUpdate(options) {
14358
14555
  if (additionalModulePaths.has(options.file)) {
14359
14556
  options.server.restart();
14557
+ return [];
14360
14558
  }
14361
14559
  },
14362
14560
  async renderChunk(code, chunk) {
@@ -14365,7 +14563,7 @@ function cloudflare2(pluginConfig = {}) {
14365
14563
  for (const match of matches) {
14366
14564
  magicString ??= new MagicString(code);
14367
14565
  const [full, _, modulePath] = match;
14368
- assert8(
14566
+ assert10(
14369
14567
  modulePath,
14370
14568
  `Unexpected error: module path not found in reference ${full}.`
14371
14569
  );
@@ -14379,13 +14577,13 @@ function cloudflare2(pluginConfig = {}) {
14379
14577
  }
14380
14578
  const referenceId = this.emitFile({
14381
14579
  type: "asset",
14382
- name: path8.basename(modulePath),
14580
+ name: path9.basename(modulePath),
14383
14581
  originalFileName: modulePath,
14384
14582
  source
14385
14583
  });
14386
14584
  const emittedFileName = this.getFileName(referenceId);
14387
- const relativePath = vite6.normalizePath(
14388
- path8.relative(path8.dirname(chunk.fileName), emittedFileName)
14585
+ const relativePath = vite7.normalizePath(
14586
+ path9.relative(path9.dirname(chunk.fileName), emittedFileName)
14389
14587
  );
14390
14588
  const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
14391
14589
  magicString.update(
@@ -14411,26 +14609,28 @@ function cloudflare2(pluginConfig = {}) {
14411
14609
  configEnvironment(name) {
14412
14610
  if (isNodeCompat(getWorkerConfig2(name))) {
14413
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
+ },
14414
14624
  resolve: {
14415
14625
  builtins: [...nodeCompatExternals]
14416
14626
  },
14417
14627
  optimizeDeps: {
14418
- // This is a list of dependency entry-points that should be pre-bundled.
14419
- // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
14420
- // ready ahead the first request to the dev server.
14421
- // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
14422
- // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
14423
- // TODO: work out how to re-enable pre-bundling of these
14424
- // include: [...getNodeCompatEntries()],
14425
14628
  // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
14426
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.
14427
14630
  // Obviously we don't want/need the optimizer to try to process modules that are built-in;
14428
14631
  // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
14429
14632
  // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
14430
- exclude: [
14431
- ...builtinModules2,
14432
- ...builtinModules2.map((m) => `node:${m}`)
14433
- ]
14633
+ exclude: [...nodejsBuiltins]
14434
14634
  }
14435
14635
  };
14436
14636
  }
@@ -14448,7 +14648,7 @@ function cloudflare2(pluginConfig = {}) {
14448
14648
  return this.resolve(source, importer, options);
14449
14649
  }
14450
14650
  if (this.environment.mode === "dev") {
14451
- assert8(
14651
+ assert10(
14452
14652
  this.environment.depsOptimizer,
14453
14653
  "depsOptimizer is required in dev mode"
14454
14654
  );
@@ -14462,11 +14662,54 @@ function cloudflare2(pluginConfig = {}) {
14462
14662
  },
14463
14663
  async transform(code, id) {
14464
14664
  const workerConfig = getWorkerConfig2(this.environment.name);
14465
- assert8(workerConfig, "Expected a worker config");
14665
+ if (!workerConfig) {
14666
+ return;
14667
+ }
14466
14668
  const resolvedId = await this.resolve(workerConfig.main);
14467
14669
  if (id === resolvedId?.id) {
14468
14670
  return injectGlobalCode(id, code);
14469
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
+ }
14470
14713
  }
14471
14714
  },
14472
14715
  // Plugin that provides an __debug path for debugging the Cloudflare Workers.
@@ -14476,54 +14719,137 @@ function cloudflare2(pluginConfig = {}) {
14476
14719
  // the preview middleware here can take precedence
14477
14720
  enforce: "pre",
14478
14721
  configureServer(viteDevServer) {
14479
- if (resolvedPluginConfig.type === "workers" && resolvedPluginConfig.inspectorPort !== false) {
14722
+ if (resolvedPluginConfig.type === "workers" && pluginConfig.inspectorPort !== false) {
14480
14723
  addDebugToVitePrintUrls(viteDevServer);
14481
14724
  }
14482
14725
  const workerNames = resolvedPluginConfig.type === "assets-only" ? [] : Object.values(resolvedPluginConfig.workers).map(
14483
14726
  (worker) => worker.name
14484
14727
  );
14485
- viteDevServer.middlewares.use((req, res, next) => {
14486
- if (req.url === debuggingPath && resolvedPluginConfig.inspectorPort !== false) {
14487
- const html = getDebugPathHtml(
14488
- workerNames,
14489
- resolvedPluginConfig.inspectorPort
14490
- );
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);
14491
14732
  res.setHeader("Content-Type", "text/html");
14492
14733
  return res.end(html);
14493
14734
  }
14494
14735
  next();
14495
14736
  });
14496
14737
  },
14497
- configurePreviewServer(vitePreviewServer) {
14738
+ async configurePreviewServer(vitePreviewServer) {
14498
14739
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14499
14740
  if (workerConfigs.length >= 1 && pluginConfig.inspectorPort !== false) {
14500
14741
  addDebugToVitePrintUrls(vitePreviewServer);
14501
14742
  }
14502
14743
  const workerNames = workerConfigs.map((worker) => {
14503
- assert8(worker.name);
14744
+ assert10(worker.name, "Expected the Worker to have a name");
14504
14745
  return worker.name;
14505
14746
  });
14506
- vitePreviewServer.middlewares.use((req, res, next) => {
14507
- if (req.url === debuggingPath && pluginConfig.inspectorPort !== false) {
14508
- const html = getDebugPathHtml(
14509
- workerNames,
14510
- pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT
14511
- );
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);
14512
14751
  res.setHeader("Content-Type", "text/html");
14513
14752
  return res.end(html);
14514
14753
  }
14515
14754
  next();
14516
14755
  });
14517
14756
  }
14757
+ },
14758
+ // Plugin to warn if Node.js APIs are being used without nodejs_compat turned on
14759
+ {
14760
+ name: "vite-plugin-cloudflare:nodejs-compat-warnings",
14761
+ apply(_config, env2) {
14762
+ return !env2.isPreview;
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",
14767
+ configEnvironment(environmentName) {
14768
+ const workerConfig = getWorkerConfig2(environmentName);
14769
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14770
+ return {
14771
+ optimizeDeps: {
14772
+ esbuildOptions: {
14773
+ plugins: [
14774
+ {
14775
+ name: "vite-plugin-cloudflare:nodejs-compat-warnings-resolver",
14776
+ setup(build) {
14777
+ build.onResolve(
14778
+ { filter: NODEJS_MODULES_RE },
14779
+ ({ path: path10, importer }) => {
14780
+ if (isNodeAls(workerConfig) && isNodeAlsModule(path10)) {
14781
+ return;
14782
+ }
14783
+ const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14784
+ nodeJsCompatWarnings?.registerImport(path10, importer);
14785
+ return { path: path10, external: true };
14786
+ }
14787
+ );
14788
+ }
14789
+ }
14790
+ ]
14791
+ }
14792
+ }
14793
+ };
14794
+ }
14795
+ },
14796
+ configResolved(resolvedViteConfig2) {
14797
+ for (const environmentName of Object.keys(
14798
+ resolvedViteConfig2.environments
14799
+ )) {
14800
+ const workerConfig = getWorkerConfig2(environmentName);
14801
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14802
+ nodeJsCompatWarningsMap.set(
14803
+ workerConfig,
14804
+ new NodeJsCompatWarnings(environmentName, resolvedViteConfig2)
14805
+ );
14806
+ }
14807
+ }
14808
+ },
14809
+ async resolveId(source, importer) {
14810
+ const workerConfig = getWorkerConfig2(this.environment.name);
14811
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14812
+ if (isNodeAls(workerConfig) && isNodeAlsModule(source)) {
14813
+ return;
14814
+ }
14815
+ const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14816
+ if (nodejsBuiltins.has(source)) {
14817
+ nodeJsCompatWarnings?.registerImport(source, importer);
14818
+ return {
14819
+ id: source,
14820
+ external: true
14821
+ };
14822
+ }
14823
+ }
14824
+ }
14518
14825
  }
14519
14826
  ];
14520
14827
  function getWorkerConfig2(environmentName) {
14521
- assert8(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14828
+ assert10(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14522
14829
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
14523
14830
  }
14524
14831
  }
14832
+ async function getInputInspectorPortOption(pluginConfig, viteServer) {
14833
+ const inputInspectorPort = pluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
14834
+ if (pluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
14835
+ viteServer.config.logger.warn(
14836
+ colors2.dim(
14837
+ `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
14838
+ `
14839
+ )
14840
+ );
14841
+ }
14842
+ return inputInspectorPort;
14843
+ }
14844
+ async function getResolvedInspectorPort(pluginConfig) {
14845
+ if (miniflare && pluginConfig.inspectorPort !== false) {
14846
+ const miniflareInspectorUrl = await miniflare.getInspectorURL();
14847
+ return Number.parseInt(miniflareInspectorUrl.port);
14848
+ }
14849
+ return null;
14850
+ }
14525
14851
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14526
- const configDir = path8.dirname(configPath);
14852
+ const configDir = path9.dirname(configPath);
14527
14853
  const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
14528
14854
  const inputDotDevDotVarsPath = `${defaultDotDevDotVarsPath}${cloudflareEnv ? `.${cloudflareEnv}` : ""}`;
14529
14855
  const targetPath = fs5.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs5.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
@@ -14533,6 +14859,19 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14533
14859
  }
14534
14860
  return null;
14535
14861
  }
14862
+ function hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) {
14863
+ return [...resolvedPluginConfig.configPaths].some((configPath) => {
14864
+ const dotDevDotVars = path9.join(path9.dirname(configPath), ".dev.vars");
14865
+ if (dotDevDotVars === changedFilePath) {
14866
+ return true;
14867
+ }
14868
+ if (resolvedPluginConfig.cloudflareEnv) {
14869
+ const dotDevDotVarsForEnv = `${dotDevDotVars}.${resolvedPluginConfig.cloudflareEnv}`;
14870
+ return dotDevDotVarsForEnv === changedFilePath;
14871
+ }
14872
+ return false;
14873
+ });
14874
+ }
14536
14875
  export {
14537
14876
  cloudflare2 as cloudflare
14538
14877
  };