@cloudflare/vite-plugin 1.15.2 → 1.16.0

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.mjs CHANGED
@@ -2,14 +2,15 @@ import { builtinModules } from "node:module";
2
2
  import * as vite from "vite";
3
3
  import assert from "node:assert";
4
4
  import { CoreHeaders, Log, LogLevel, Miniflare, Request as Request$1, Response as Response$1, coupleWebSocket, getDefaultDevRegistryPath, getNodeCompat, kUnsafeEphemeralUniqueKey } from "miniflare";
5
- import { maybeStartOrUpdateRemoteProxySession, unstable_convertConfigBindingsToStartWorkerBindings, unstable_getDurableObjectClassNameToUseSQLiteMap, unstable_getMiniflareWorkerOptions, unstable_getVarsForDev, unstable_readConfig } from "wrangler";
6
- import * as path$2 from "node:path";
5
+ import { maybeStartOrUpdateRemoteProxySession, unstable_convertConfigBindingsToStartWorkerBindings, unstable_defaultWranglerConfig, unstable_getDevCompatibilityDate, unstable_getDurableObjectClassNameToUseSQLiteMap, unstable_getMiniflareWorkerOptions, unstable_getVarsForDev, unstable_getWorkerNameFromProject, unstable_readConfig } from "wrangler";
6
+ import * as path$1 from "node:path";
7
7
  import path, { relative } from "node:path";
8
8
  import * as util$1 from "node:util";
9
9
  import { format, inspect } from "node:util";
10
10
  import { createHeaders, createRequest, sendResponse } from "@remix-run/node-fetch-server";
11
+ import { defu } from "defu";
11
12
  import * as fs$1 from "node:fs";
12
- import fs, { readFileSync, realpathSync, statSync } from "node:fs";
13
+ import fs, { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
13
14
  import { getCloudflarePreset } from "@cloudflare/unenv-preset";
14
15
  import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
15
16
  import process$1 from "node:process";
@@ -18,11 +19,8 @@ import { defineEnv } from "unenv";
18
19
  import * as fsp from "node:fs/promises";
19
20
  import colors from "picocolors";
20
21
  import getPort, { portNumbers } from "get-port";
21
- import { execFileSync, spawn } from "child_process";
22
- import { existsSync, readFileSync as readFileSync$1, statSync as statSync$1 } from "fs";
23
- import { spawn as spawn$1 } from "node:child_process";
24
- import { randomUUID } from "crypto";
25
- import path$1 from "path";
22
+ import { execFileSync, spawn } from "node:child_process";
23
+ import { randomUUID } from "node:crypto";
26
24
  import { globSync } from "tinyglobby";
27
25
  import { WebSocketServer } from "ws";
28
26
 
@@ -69,14 +67,14 @@ function createPlugin(name, pluginFactory) {
69
67
  }
70
68
  function getOutputDirectory(userConfig, environmentName) {
71
69
  const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
72
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path$2.join(rootOutputDirectory, environmentName);
70
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path$1.join(rootOutputDirectory, environmentName);
73
71
  }
74
72
  const postfixRE = /[?#].*$/;
75
73
  function cleanUrl(url) {
76
74
  return url.replace(postfixRE, "");
77
75
  }
78
- function withTrailingSlash(path$3) {
79
- return path$3.endsWith("/") ? path$3 : `${path$3}/`;
76
+ function withTrailingSlash(path$2) {
77
+ return path$2.endsWith("/") ? path$2 : `${path$2}/`;
80
78
  }
81
79
  function createRequestHandler(handler) {
82
80
  return async (req, res, next) => {
@@ -156,6 +154,7 @@ function getInitialWorkerNameToExportTypesMap(resolvedPluginConfig) {
156
154
  * Fetches the export types for all Workers and returns them in a Map
157
155
  */
158
156
  async function getCurrentWorkerNameToExportTypesMap(resolvedPluginConfig, viteDevServer, miniflare) {
157
+ await viteDevServer.environments.client.pluginContainer.buildStart();
159
158
  const results = await Promise.all([...resolvedPluginConfig.environmentNameToWorkerMap].map(async ([environmentName, worker]) => {
160
159
  debuglog(`Fetching export types for worker "${worker.config.name}"`);
161
160
  const exportTypes = await viteDevServer.environments[environmentName].fetchWorkerExportTypes(miniflare, worker.config);
@@ -357,21 +356,21 @@ const formatInvalidRoutes = (invalidRules) => {
357
356
  //#endregion
358
357
  //#region src/deploy-config.ts
359
358
  function getDeployConfigPath(root) {
360
- return path$2.resolve(root, ".wrangler", "deploy", "config.json");
359
+ return path$1.resolve(root, ".wrangler", "deploy", "config.json");
361
360
  }
362
361
  function getWorkerConfigs(root) {
363
362
  const deployConfigPath = getDeployConfigPath(root);
364
363
  const deployConfig = JSON.parse(fs$1.readFileSync(deployConfigPath, "utf-8"));
365
364
  return [{ configPath: deployConfig.configPath }, ...deployConfig.auxiliaryWorkers].map(({ configPath }) => {
366
- return unstable_readConfig({ config: path$2.resolve(path$2.dirname(deployConfigPath), configPath) });
365
+ return unstable_readConfig({ config: path$1.resolve(path$1.dirname(deployConfigPath), configPath) });
367
366
  });
368
367
  }
369
368
  function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
370
- return path$2.relative(deployConfigDirectory, path$2.resolve(root, outputDirectory, "wrangler.json"));
369
+ return path$1.relative(deployConfigDirectory, path$1.resolve(root, outputDirectory, "wrangler.json"));
371
370
  }
372
371
  function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
373
372
  const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
374
- const deployConfigDirectory = path$2.dirname(deployConfigPath);
373
+ const deployConfigDirectory = path$1.dirname(deployConfigPath);
375
374
  fs$1.mkdirSync(deployConfigDirectory, { recursive: true });
376
375
  if (resolvedPluginConfig.type === "assets-only") {
377
376
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
@@ -5387,15 +5386,15 @@ function hasTrailingSlash(input = "", respectQueryAndFragment) {
5387
5386
  function withTrailingSlash$1(input = "", respectQueryAndFragment) {
5388
5387
  if (!respectQueryAndFragment) return input.endsWith("/") ? input : input + "/";
5389
5388
  if (hasTrailingSlash(input, true)) return input || "/";
5390
- let path$3 = input;
5389
+ let path$2 = input;
5391
5390
  let fragment = "";
5392
5391
  const fragmentIndex = input.indexOf("#");
5393
5392
  if (fragmentIndex >= 0) {
5394
- path$3 = input.slice(0, fragmentIndex);
5393
+ path$2 = input.slice(0, fragmentIndex);
5395
5394
  fragment = input.slice(fragmentIndex);
5396
- if (!path$3) return fragment;
5395
+ if (!path$2) return fragment;
5397
5396
  }
5398
- const [s0, ...s] = path$3.split("?");
5397
+ const [s0, ...s] = path$2.split("?");
5399
5398
  return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
5400
5399
  }
5401
5400
  function isNonEmptyURL(url) {
@@ -5421,8 +5420,8 @@ const isAbsolute = function(p) {
5421
5420
  //#endregion
5422
5421
  //#region ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
5423
5422
  const BUILTIN_MODULES = new Set(builtinModules);
5424
- function normalizeSlash(path$3) {
5425
- return path$3.replace(/\\/g, "/");
5423
+ function normalizeSlash(path$2) {
5424
+ return path$2.replace(/\\/g, "/");
5426
5425
  }
5427
5426
  /**
5428
5427
  * @typedef ErrnoExceptionFields
@@ -5542,8 +5541,8 @@ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
5542
5541
  * @param {string} [base]
5543
5542
  * @param {string} [message]
5544
5543
  */
5545
- (path$3, base, message) => {
5546
- return `Invalid package config ${path$3}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
5544
+ (path$2, base, message) => {
5545
+ return `Invalid package config ${path$2}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
5547
5546
  },
5548
5547
  Error
5549
5548
  );
@@ -5573,8 +5572,8 @@ codes.ERR_MODULE_NOT_FOUND = createError(
5573
5572
  * @param {string} base
5574
5573
  * @param {boolean} [exactUrl]
5575
5574
  */
5576
- (path$3, base, exactUrl = false) => {
5577
- return `Cannot find ${exactUrl ? "module" : "package"} '${path$3}' imported from ${base}`;
5575
+ (path$2, base, exactUrl = false) => {
5576
+ return `Cannot find ${exactUrl ? "module" : "package"} '${path$2}' imported from ${base}`;
5578
5577
  },
5579
5578
  Error
5580
5579
  );
@@ -5612,8 +5611,8 @@ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
5612
5611
  * @param {string} extension
5613
5612
  * @param {string} path
5614
5613
  */
5615
- (extension, path$3) => {
5616
- return `Unknown file extension "${extension}" for ${path$3}`;
5614
+ (extension, path$2) => {
5615
+ return `Unknown file extension "${extension}" for ${path$2}`;
5617
5616
  },
5618
5617
  TypeError
5619
5618
  );
@@ -5982,9 +5981,9 @@ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
5982
5981
  * @param {string} path
5983
5982
  * @returns {Stats | undefined}
5984
5983
  */
5985
- function tryStatSync(path$3) {
5984
+ function tryStatSync(path$2) {
5986
5985
  try {
5987
- return statSync(path$3);
5986
+ return statSync(path$2);
5988
5987
  } catch {}
5989
5988
  }
5990
5989
  /**
@@ -6715,8 +6714,8 @@ function hasNodeJsAls(workerConfig) {
6715
6714
  */
6716
6715
  const nodeJsBuiltins = new Set([...builtinModules, ...builtinModules.map((m) => `node:${m}`)]);
6717
6716
  const NODEJS_MODULES_RE = /* @__PURE__ */ new RegExp(`^(node:)?(${builtinModules.join("|")})$`);
6718
- function isNodeAlsModule(path$3) {
6719
- return /^(node:)?async_hooks$/.test(path$3);
6717
+ function isNodeAlsModule(path$2) {
6718
+ return /^(node:)?async_hooks$/.test(path$2);
6720
6719
  }
6721
6720
  function assertHasNodeJsCompat(nodeJsCompat) {
6722
6721
  assert(nodeJsCompat, `expected nodeJsCompat to be defined`);
@@ -6747,7 +6746,7 @@ var NodeJsCompatWarnings = class {
6747
6746
  `;
6748
6747
  this.sources.forEach((importers, source) => {
6749
6748
  importers.forEach((importer) => {
6750
- message += ` - "${source}" imported from "${path$2.relative(this.resolvedViteConfig.root, importer)}"\n`;
6749
+ message += ` - "${source}" imported from "${path$1.relative(this.resolvedViteConfig.root, importer)}"\n`;
6751
6750
  });
6752
6751
  });
6753
6752
  this.resolvedViteConfig.logger.warn(message, { timestamp: true });
@@ -6832,7 +6831,7 @@ function getWarningForWorkersConfigs(configs) {
6832
6831
  if (!("auxiliaryWorkers" in configs) || configs.auxiliaryWorkers.length === 0) {
6833
6832
  const nonApplicableLines = getWorkerNonApplicableWarnLines(configs.entryWorker, ` - `);
6834
6833
  if (nonApplicableLines.length === 0) return;
6835
- const lines$1 = [`\n\n\x1b[43mWARNING\x1b[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path$2.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`];
6834
+ const lines$1 = [`\n\n\x1b[43mWARNING\x1b[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path$1.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`];
6836
6835
  nonApplicableLines.forEach((line) => lines$1.push(line));
6837
6836
  lines$1.push("");
6838
6837
  return lines$1.join("\n");
@@ -6841,7 +6840,7 @@ function getWarningForWorkersConfigs(configs) {
6841
6840
  const processWorkerConfig = (workerConfig, isEntryWorker = false) => {
6842
6841
  const nonApplicableLines = getWorkerNonApplicableWarnLines(workerConfig, ` - `);
6843
6842
  if (nonApplicableLines.length > 0) {
6844
- lines.push(` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path$2.relative("", workerConfig.config.configPath)}\`)` : ""}`);
6843
+ lines.push(` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path$1.relative("", workerConfig.config.configPath)}\`)` : ""}`);
6845
6844
  nonApplicableLines.forEach((line) => lines.push(line));
6846
6845
  }
6847
6846
  };
@@ -6868,15 +6867,30 @@ function isNotRelevant(configName) {
6868
6867
  return nonApplicableWorkerConfigs.notRelevant.includes(configName);
6869
6868
  }
6870
6869
  function missingFieldErrorMessage(field, configPath, env) {
6871
- return `No ${field} field provided in '${configPath}'${env ? ` for '${env}' environment` : ""}`;
6870
+ return `No '${field}' field provided${configPath ? ` in '${configPath}'` : ""}${env ? ` for '${env}' environment` : ""}`;
6872
6871
  }
6873
- function getWorkerConfig(configPath, env, opts) {
6872
+ /**
6873
+ * Reads and sanitizes a worker config from a wrangler config file.
6874
+ */
6875
+ function readWorkerConfigFromFile(configPath, env, opts) {
6874
6876
  if (opts?.visitedConfigPaths?.has(configPath)) throw new Error(`Duplicate Wrangler config path found: ${configPath}`);
6875
- const { raw, config, nonApplicable } = readWorkerConfig(configPath, env);
6877
+ const result = readWorkerConfig(configPath, env);
6876
6878
  opts?.visitedConfigPaths?.add(configPath);
6877
- if (!config.name) throw new Error(missingFieldErrorMessage(`'name'`, configPath, env));
6878
- if (!config.topLevelName) throw new Error(missingFieldErrorMessage(`top-level 'name'`, configPath, env));
6879
- if (!config.compatibility_date) throw new Error(missingFieldErrorMessage(`'compatibility_date`, configPath, env));
6879
+ return result;
6880
+ }
6881
+ /**
6882
+ * Validates required fields and determines whether the config represents
6883
+ * an assets-only worker or a worker with server logic.
6884
+ *
6885
+ * @param config The sanitized worker config (after merging defaults, file config, and config())
6886
+ * @param raw The raw config (before sanitization)
6887
+ * @param nonApplicable The non-applicable config map
6888
+ * @param opts Options for validation
6889
+ */
6890
+ function resolveWorkerType(config, raw, nonApplicable, opts) {
6891
+ if (!config.name) throw new Error(missingFieldErrorMessage("name", opts?.configPath, opts?.env));
6892
+ if (!config.topLevelName) throw new Error(missingFieldErrorMessage("top-level name", opts?.configPath, opts?.env));
6893
+ if (!config.compatibility_date) throw new Error(missingFieldErrorMessage("compatibility_date", opts?.configPath, opts?.env));
6880
6894
  const requiredFields = {
6881
6895
  topLevelName: config.topLevelName,
6882
6896
  name: config.name,
@@ -6891,14 +6905,15 @@ function getWorkerConfig(configPath, env, opts) {
6891
6905
  },
6892
6906
  nonApplicable
6893
6907
  };
6894
- if (!config.main) throw new Error(missingFieldErrorMessage(`'main'`, configPath, env));
6908
+ if (!config.main) throw new Error(missingFieldErrorMessage("main", opts?.configPath, opts?.env));
6909
+ const resolvedMain = maybeResolveMain(config.main, opts?.configPath, opts?.root);
6895
6910
  return {
6896
6911
  type: "worker",
6897
6912
  raw,
6898
6913
  config: {
6899
6914
  ...config,
6900
6915
  ...requiredFields,
6901
- main: maybeResolveMain(config.main, configPath)
6916
+ main: resolvedMain
6902
6917
  },
6903
6918
  nonApplicable
6904
6919
  };
@@ -6916,9 +6931,11 @@ const ENTRY_MODULE_EXTENSIONS = [
6916
6931
  * Else `main` is returned as is so that it can be resolved by Vite.
6917
6932
  * This enables resolving entry modules relative to the Worker config while also supporting virtual modules and package exports.
6918
6933
  */
6919
- function maybeResolveMain(main, configPath) {
6934
+ function maybeResolveMain(main, configPath, root) {
6920
6935
  if (!ENTRY_MODULE_EXTENSIONS.some((extension) => main.endsWith(extension))) return main;
6921
- const resolvedMain = path$2.resolve(path$2.dirname(configPath), main);
6936
+ const baseDir = configPath ? path$1.dirname(configPath) : root;
6937
+ if (!baseDir) return main;
6938
+ const resolvedMain = path$1.resolve(baseDir, main);
6922
6939
  if (!fs$1.existsSync(resolvedMain)) throw new Error(`The provided Wrangler config main field (${resolvedMain}) doesn't point to an existing file`);
6923
6940
  return resolvedMain;
6924
6941
  }
@@ -6929,30 +6946,28 @@ function maybeResolveMain(main, configPath) {
6929
6946
  * @param root the root of the vite project
6930
6947
  * @param requestedConfigPath the requested config path, if any
6931
6948
  * @param isForAuxiliaryWorker whether the config path is being requested for an auxiliary worker
6932
- * @returns a valid path to a config file
6949
+ * @returns a valid path to a config file, or undefined for entry workers when no config is found
6933
6950
  */
6934
6951
  function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
6935
6952
  if (requestedConfigPath) {
6936
- const configPath$1 = path$2.resolve(root, requestedConfigPath);
6937
- const errorMessagePrefix = `The provided configPath (${configPath$1})${isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : ""}`;
6938
- const fileExtension = path$2.extname(configPath$1).slice(1);
6953
+ const configPath = path$1.resolve(root, requestedConfigPath);
6954
+ const errorMessagePrefix = `The provided configPath (${configPath})${isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : ""}`;
6955
+ const fileExtension = path$1.extname(configPath).slice(1);
6939
6956
  if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
6940
6957
  const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
6941
6958
  throw new Error(`${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`);
6942
6959
  }
6943
- const mainStat = fs$1.statSync(configPath$1, { throwIfNoEntry: false });
6960
+ const mainStat = fs$1.statSync(configPath, { throwIfNoEntry: false });
6944
6961
  if (!mainStat) throw new Error(`${errorMessagePrefix} doesn't point to an existing file`);
6945
6962
  if (mainStat.isDirectory()) throw new Error(`${errorMessagePrefix} points to a directory. It should point to a file.`);
6946
- return configPath$1;
6963
+ return configPath;
6947
6964
  }
6948
- assert(isForAuxiliaryWorker === false, "Unexpected Error: trying to find the wrangler config for an auxiliary worker");
6949
- const configPath = findWranglerConfig(root);
6950
- if (!configPath) throw new Error(`No config file found in the ${root} directory. Please add a wrangler.(jsonc|json|toml) file.`);
6951
- return configPath;
6965
+ if (isForAuxiliaryWorker) return;
6966
+ return findWranglerConfig(root);
6952
6967
  }
6953
6968
  function findWranglerConfig(root) {
6954
6969
  for (const extension of allowedWranglerConfigExtensions) {
6955
- const configPath = path$2.join(root, `wrangler.${extension}`);
6970
+ const configPath = path$1.join(root, `wrangler.${extension}`);
6956
6971
  if (fs$1.existsSync(configPath)) return configPath;
6957
6972
  }
6958
6973
  }
@@ -6964,13 +6979,45 @@ const allowedWranglerConfigExtensions = [
6964
6979
 
6965
6980
  //#endregion
6966
6981
  //#region src/plugin-config.ts
6982
+ function customizeWorkerConfig(resolvedConfig, config) {
6983
+ const configResult = typeof config === "function" ? config(resolvedConfig) : config;
6984
+ if (configResult) return defu(configResult, resolvedConfig);
6985
+ return resolvedConfig;
6986
+ }
6987
+ /**
6988
+ * Resolves the config for a single worker, applying defaults, file config, and config().
6989
+ */
6990
+ function resolveWorkerConfig({ configPath, env, config, visitedConfigPaths, isEntryWorker, root }) {
6991
+ let workerConfig;
6992
+ let raw;
6993
+ let nonApplicable;
6994
+ if (configPath) ({raw, config: workerConfig, nonApplicable} = readWorkerConfigFromFile(configPath, env, { visitedConfigPaths }));
6995
+ else {
6996
+ workerConfig = { ...unstable_defaultWranglerConfig };
6997
+ raw = structuredClone(workerConfig);
6998
+ nonApplicable = {
6999
+ replacedByVite: /* @__PURE__ */ new Set(),
7000
+ notRelevant: /* @__PURE__ */ new Set()
7001
+ };
7002
+ }
7003
+ workerConfig = customizeWorkerConfig(workerConfig, config);
7004
+ workerConfig.compatibility_date ??= unstable_getDevCompatibilityDate(void 0);
7005
+ if (isEntryWorker) workerConfig.name ??= unstable_getWorkerNameFromProject(root);
7006
+ workerConfig.topLevelName ??= workerConfig.name;
7007
+ return resolveWorkerType(workerConfig, raw, nonApplicable, {
7008
+ isEntryWorker,
7009
+ configPath,
7010
+ root,
7011
+ env
7012
+ });
7013
+ }
6967
7014
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
6968
7015
  const shared = {
6969
7016
  persistState: pluginConfig.persistState ?? true,
6970
7017
  inspectorPort: pluginConfig.inspectorPort,
6971
7018
  experimental: pluginConfig.experimental ?? {}
6972
7019
  };
6973
- const root = userConfig.root ? path$2.resolve(userConfig.root) : process.cwd();
7020
+ const root = userConfig.root ? path$1.resolve(userConfig.root) : process.cwd();
6974
7021
  const prefixedEnv = vite.loadEnv(viteEnv.mode, root, ["CLOUDFLARE_", "WRANGLER_HYPERDRIVE_LOCAL_CONNECTION_STRING_"]);
6975
7022
  Object.assign(process.env, prefixedEnv);
6976
7023
  if (viteEnv.isPreview) return {
@@ -6981,7 +7028,11 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
6981
7028
  };
6982
7029
  const configPaths = /* @__PURE__ */ new Set();
6983
7030
  const cloudflareEnv = prefixedEnv.CLOUDFLARE_ENV;
6984
- const entryWorkerResolvedConfig = getWorkerConfig(getValidatedWranglerConfigPath(root, pluginConfig.configPath), cloudflareEnv, {
7031
+ const entryWorkerResolvedConfig = resolveWorkerConfig({
7032
+ root,
7033
+ configPath: getValidatedWranglerConfigPath(root, pluginConfig.configPath),
7034
+ env: prefixedEnv.CLOUDFLARE_ENV,
7035
+ config: pluginConfig.config,
6985
7036
  visitedConfigPaths: configPaths,
6986
7037
  isEntryWorker: true
6987
7038
  });
@@ -7001,13 +7052,18 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
7001
7052
  const environmentNameToWorkerMap = new Map([[entryWorkerEnvironmentName, resolveWorker(entryWorkerConfig)]]);
7002
7053
  const auxiliaryWorkersResolvedConfigs = [];
7003
7054
  for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
7004
- const workerResolvedConfig = getWorkerConfig(getValidatedWranglerConfigPath(root, auxiliaryWorker.configPath, true), cloudflareEnv, { visitedConfigPaths: configPaths });
7055
+ const workerResolvedConfig = resolveWorkerConfig({
7056
+ root,
7057
+ configPath: getValidatedWranglerConfigPath(root, auxiliaryWorker.configPath, true),
7058
+ env: cloudflareEnv,
7059
+ config: "config" in auxiliaryWorker ? auxiliaryWorker.config : void 0,
7060
+ visitedConfigPaths: configPaths,
7061
+ isEntryWorker: false
7062
+ });
7005
7063
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
7006
- assert(workerResolvedConfig.type === "worker", "Unexpected error: received AssetsOnlyResult with auxiliary workers.");
7007
- const workerConfig = workerResolvedConfig.config;
7008
- const workerEnvironmentName = auxiliaryWorker.viteEnvironment?.name ?? workerNameToEnvironmentName(workerConfig.topLevelName);
7064
+ const workerEnvironmentName = auxiliaryWorker.viteEnvironment?.name ?? workerNameToEnvironmentName(workerResolvedConfig.config.topLevelName);
7009
7065
  if (environmentNameToWorkerMap.has(workerEnvironmentName)) throw new Error(`Duplicate Vite environment name found: ${workerEnvironmentName}`);
7010
- environmentNameToWorkerMap.set(workerEnvironmentName, resolveWorker(workerConfig));
7066
+ environmentNameToWorkerMap.set(workerEnvironmentName, resolveWorker(workerResolvedConfig.config));
7011
7067
  }
7012
7068
  return {
7013
7069
  ...shared,
@@ -8078,12 +8134,12 @@ const additionalModulesPlugin = createPlugin("additional-modules", (ctx) => {
8078
8134
  }
8079
8135
  const referenceId = this.emitFile({
8080
8136
  type: "asset",
8081
- name: path$2.basename(modulePath),
8137
+ name: path$1.basename(modulePath),
8082
8138
  originalFileName: modulePath,
8083
8139
  source
8084
8140
  });
8085
8141
  const emittedFileName = this.getFileName(referenceId);
8086
- const relativePath = vite.normalizePath(path$2.relative(path$2.dirname(chunk.fileName), emittedFileName));
8142
+ const relativePath = vite.normalizePath(path$1.relative(path$1.dirname(chunk.fileName), emittedFileName));
8087
8143
  const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
8088
8144
  magicString.update(match.index, match.index + full.length, importPath);
8089
8145
  }
@@ -8194,9 +8250,9 @@ function constructHeaders({ headers, headersFile, logger }) {
8194
8250
 
8195
8251
  //#endregion
8196
8252
  //#region ../workers-shared/utils/configuration/validateURL.ts
8197
- const extractPathname = (path$3 = "/", includeSearch, includeHash) => {
8198
- if (!path$3.startsWith("/")) path$3 = `/${path$3}`;
8199
- const url = new URL(`//${path$3}`, "relative://");
8253
+ const extractPathname = (path$2 = "/", includeSearch, includeHash) => {
8254
+ if (!path$2.startsWith("/")) path$2 = `/${path$2}`;
8255
+ const url = new URL(`//${path$2}`, "relative://");
8200
8256
  return `${url.pathname}${includeSearch ? url.search : ""}${includeHash ? url.hash : ""}`;
8201
8257
  };
8202
8258
  const URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
@@ -8253,7 +8309,7 @@ function parseHeaders(input, { maxRules = MAX_HEADER_RULES, maxLineLength = MAX_
8253
8309
  lineNumber: i$1 + 1,
8254
8310
  message: "No headers specified"
8255
8311
  });
8256
- const [path$3, pathError] = validateUrl(line, false, true);
8312
+ const [path$2, pathError] = validateUrl(line, false, true);
8257
8313
  if (pathError) {
8258
8314
  invalid.push({
8259
8315
  line,
@@ -8264,7 +8320,7 @@ function parseHeaders(input, { maxRules = MAX_HEADER_RULES, maxLineLength = MAX_
8264
8320
  continue;
8265
8321
  }
8266
8322
  rule = {
8267
- path: path$3,
8323
+ path: path$2,
8268
8324
  line,
8269
8325
  headers: {},
8270
8326
  unsetHeaders: []
@@ -8552,13 +8608,13 @@ var require_ignore = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/igno
8552
8608
  const throwError = (message, Ctor) => {
8553
8609
  throw new Ctor(message);
8554
8610
  };
8555
- const checkPath = (path$3, originalPath, doThrow) => {
8556
- if (!isString$1(path$3)) return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
8557
- if (!path$3) return doThrow(`path must not be empty`, TypeError);
8558
- if (checkPath.isNotRelative(path$3)) return doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`, RangeError);
8611
+ const checkPath = (path$2, originalPath, doThrow) => {
8612
+ if (!isString$1(path$2)) return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
8613
+ if (!path$2) return doThrow(`path must not be empty`, TypeError);
8614
+ if (checkPath.isNotRelative(path$2)) return doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`, RangeError);
8559
8615
  return true;
8560
8616
  };
8561
- const isNotRelative = (path$3) => REGEX_TEST_INVALID_PATH.test(path$3);
8617
+ const isNotRelative = (path$2) => REGEX_TEST_INVALID_PATH.test(path$2);
8562
8618
  checkPath.isNotRelative = isNotRelative;
8563
8619
  checkPath.convert = (p) => p;
8564
8620
  var Ignore = class {
@@ -8594,13 +8650,13 @@ var require_ignore = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/igno
8594
8650
  addPattern(pattern) {
8595
8651
  return this.add(pattern);
8596
8652
  }
8597
- _testOne(path$3, checkUnignored) {
8653
+ _testOne(path$2, checkUnignored) {
8598
8654
  let ignored = false;
8599
8655
  let unignored = false;
8600
8656
  this._rules.forEach((rule) => {
8601
8657
  const { negative } = rule;
8602
8658
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) return;
8603
- if (rule.regex.test(path$3)) {
8659
+ if (rule.regex.test(path$2)) {
8604
8660
  ignored = !negative;
8605
8661
  unignored = negative;
8606
8662
  }
@@ -8611,33 +8667,33 @@ var require_ignore = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/igno
8611
8667
  };
8612
8668
  }
8613
8669
  _test(originalPath, cache$1, checkUnignored, slices) {
8614
- const path$3 = originalPath && checkPath.convert(originalPath);
8615
- checkPath(path$3, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
8616
- return this._t(path$3, cache$1, checkUnignored, slices);
8670
+ const path$2 = originalPath && checkPath.convert(originalPath);
8671
+ checkPath(path$2, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
8672
+ return this._t(path$2, cache$1, checkUnignored, slices);
8617
8673
  }
8618
- _t(path$3, cache$1, checkUnignored, slices) {
8619
- if (path$3 in cache$1) return cache$1[path$3];
8620
- if (!slices) slices = path$3.split(SLASH);
8674
+ _t(path$2, cache$1, checkUnignored, slices) {
8675
+ if (path$2 in cache$1) return cache$1[path$2];
8676
+ if (!slices) slices = path$2.split(SLASH);
8621
8677
  slices.pop();
8622
- if (!slices.length) return cache$1[path$3] = this._testOne(path$3, checkUnignored);
8678
+ if (!slices.length) return cache$1[path$2] = this._testOne(path$2, checkUnignored);
8623
8679
  const parent = this._t(slices.join(SLASH) + SLASH, cache$1, checkUnignored, slices);
8624
- return cache$1[path$3] = parent.ignored ? parent : this._testOne(path$3, checkUnignored);
8680
+ return cache$1[path$2] = parent.ignored ? parent : this._testOne(path$2, checkUnignored);
8625
8681
  }
8626
- ignores(path$3) {
8627
- return this._test(path$3, this._ignoreCache, false).ignored;
8682
+ ignores(path$2) {
8683
+ return this._test(path$2, this._ignoreCache, false).ignored;
8628
8684
  }
8629
8685
  createFilter() {
8630
- return (path$3) => !this.ignores(path$3);
8686
+ return (path$2) => !this.ignores(path$2);
8631
8687
  }
8632
8688
  filter(paths) {
8633
8689
  return makeArray(paths).filter(this.createFilter());
8634
8690
  }
8635
- test(path$3) {
8636
- return this._test(path$3, this._testCache, true);
8691
+ test(path$2) {
8692
+ return this._test(path$2, this._testCache, true);
8637
8693
  }
8638
8694
  };
8639
8695
  const factory = (options) => new Ignore(options);
8640
- const isPathValid = (path$3) => checkPath(path$3 && checkPath.convert(path$3), path$3, RETURN_FALSE);
8696
+ const isPathValid = (path$2) => checkPath(path$2 && checkPath.convert(path$2), path$2, RETURN_FALSE);
8641
8697
  factory.isPathValid = isPathValid;
8642
8698
  factory.default = factory;
8643
8699
  module.exports = factory;
@@ -8646,7 +8702,7 @@ var require_ignore = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/igno
8646
8702
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
8647
8703
  checkPath.convert = makePosix;
8648
8704
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
8649
- checkPath.isNotRelative = (path$3) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path$3) || isNotRelative(path$3);
8705
+ checkPath.isNotRelative = (path$2) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path$2) || isNotRelative(path$2);
8650
8706
  }
8651
8707
  }) });
8652
8708
 
@@ -10001,11 +10057,11 @@ var Mime = class {
10001
10057
  }
10002
10058
  return this;
10003
10059
  }
10004
- getType(path$3) {
10005
- if (typeof path$3 !== "string") return null;
10006
- const last = path$3.replace(/^.*[/\\]/s, "").toLowerCase();
10060
+ getType(path$2) {
10061
+ if (typeof path$2 !== "string") return null;
10062
+ const last = path$2.replace(/^.*[/\\]/s, "").toLowerCase();
10007
10063
  const ext = last.replace(/^.*\./s, "").toLowerCase();
10008
- const hasPath = last.length < path$3.length;
10064
+ const hasPath = last.length < path$2.length;
10009
10065
  if (!(ext.length < last.length - 1) && hasPath) return null;
10010
10066
  return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
10011
10067
  }
@@ -10327,8 +10383,8 @@ function getErrorMap() {
10327
10383
  return overrideErrorMap;
10328
10384
  }
10329
10385
  const makeIssue = (params) => {
10330
- const { data: data$1, path: path$3, errorMaps, issueData } = params;
10331
- const fullPath = [...path$3, ...issueData.path || []];
10386
+ const { data: data$1, path: path$2, errorMaps, issueData } = params;
10387
+ const fullPath = [...path$2, ...issueData.path || []];
10332
10388
  const fullIssue = {
10333
10389
  ...issueData,
10334
10390
  path: fullPath
@@ -10425,11 +10481,11 @@ var errorUtil;
10425
10481
  errorUtil$1.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
10426
10482
  })(errorUtil || (errorUtil = {}));
10427
10483
  var ParseInputLazyPath = class {
10428
- constructor(parent, value, path$3, key) {
10484
+ constructor(parent, value, path$2, key) {
10429
10485
  this._cachedPath = [];
10430
10486
  this.parent = parent;
10431
10487
  this.data = value;
10432
- this._path = path$3;
10488
+ this._path = path$2;
10433
10489
  this._key = key;
10434
10490
  }
10435
10491
  get path() {
@@ -13591,10 +13647,10 @@ function getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedConfig
13591
13647
  };
13592
13648
  }
13593
13649
  function getRedirectsConfigPath(config) {
13594
- return path$2.join(config.publicDir, REDIRECTS_FILENAME);
13650
+ return path$1.join(config.publicDir, REDIRECTS_FILENAME);
13595
13651
  }
13596
13652
  function getHeadersConfigPath(config) {
13597
- return path$2.join(config.publicDir, HEADERS_FILENAME);
13653
+ return path$1.join(config.publicDir, HEADERS_FILENAME);
13598
13654
  }
13599
13655
 
13600
13656
  //#endregion
@@ -13711,7 +13767,7 @@ function createBuildApp(resolvedPluginConfig) {
13711
13767
  return async (builder) => {
13712
13768
  const clientEnvironment = builder.environments.client;
13713
13769
  assert(clientEnvironment, `No "client" environment`);
13714
- const defaultHtmlPath = path$2.resolve(builder.config.root, "index.html");
13770
+ const defaultHtmlPath = path$1.resolve(builder.config.root, "index.html");
13715
13771
  const hasClientEntry = clientEnvironment.config.build.rollupOptions.input || fs$1.existsSync(defaultHtmlPath);
13716
13772
  if (resolvedPluginConfig.type === "assets-only") {
13717
13773
  if (hasClientEntry) await builder.build(clientEnvironment);
@@ -13727,32 +13783,32 @@ function createBuildApp(resolvedPluginConfig) {
13727
13783
  const { entryWorkerEnvironmentName } = resolvedPluginConfig;
13728
13784
  const entryWorkerEnvironment = builder.environments[entryWorkerEnvironmentName];
13729
13785
  assert(entryWorkerEnvironment, `No "${entryWorkerEnvironmentName}" environment`);
13730
- const entryWorkerBuildDirectory = path$2.resolve(builder.config.root, entryWorkerEnvironment.config.build.outDir);
13786
+ const entryWorkerBuildDirectory = path$1.resolve(builder.config.root, entryWorkerEnvironment.config.build.outDir);
13731
13787
  const importedAssetPaths = getImportedAssetPaths(loadViteManifest(entryWorkerBuildDirectory));
13732
13788
  if (hasClientEntry) await builder.build(clientEnvironment);
13733
13789
  else if (importedAssetPaths.size || getHasPublicAssets(builder.config)) await fallbackBuild(builder, clientEnvironment);
13734
13790
  else {
13735
- const entryWorkerConfigPath = path$2.join(entryWorkerBuildDirectory, "wrangler.json");
13791
+ const entryWorkerConfigPath = path$1.join(entryWorkerBuildDirectory, "wrangler.json");
13736
13792
  const workerConfig = JSON.parse(fs$1.readFileSync(entryWorkerConfigPath, "utf-8"));
13737
13793
  workerConfig.assets = void 0;
13738
13794
  fs$1.writeFileSync(entryWorkerConfigPath, JSON.stringify(workerConfig));
13739
13795
  return;
13740
13796
  }
13741
- const clientBuildDirectory = path$2.resolve(builder.config.root, clientEnvironment.config.build.outDir);
13797
+ const clientBuildDirectory = path$1.resolve(builder.config.root, clientEnvironment.config.build.outDir);
13742
13798
  const movedAssetPaths = [];
13743
13799
  for (const assetPath of importedAssetPaths) {
13744
- const src = path$2.join(entryWorkerBuildDirectory, assetPath);
13745
- const dest = path$2.join(clientBuildDirectory, assetPath);
13800
+ const src = path$1.join(entryWorkerBuildDirectory, assetPath);
13801
+ const dest = path$1.join(clientBuildDirectory, assetPath);
13746
13802
  if (!fs$1.existsSync(src)) continue;
13747
13803
  if (fs$1.existsSync(dest)) fs$1.unlinkSync(src);
13748
13804
  else {
13749
- const destDir = path$2.dirname(dest);
13805
+ const destDir = path$1.dirname(dest);
13750
13806
  fs$1.mkdirSync(destDir, { recursive: true });
13751
13807
  fs$1.renameSync(src, dest);
13752
13808
  movedAssetPaths.push(dest);
13753
13809
  }
13754
13810
  }
13755
- if (movedAssetPaths.length) builder.config.logger.info([`${colors.green("✓")} ${movedAssetPaths.length} asset${movedAssetPaths.length > 1 ? "s" : ""} moved from "${entryWorkerEnvironmentName}" to "client" build output.`, ...movedAssetPaths.map((assetPath) => colors.dim(path$2.relative(builder.config.root, assetPath)))].join("\n"));
13811
+ if (movedAssetPaths.length) builder.config.logger.info([`${colors.green("✓")} ${movedAssetPaths.length} asset${movedAssetPaths.length > 1 ? "s" : ""} moved from "${entryWorkerEnvironmentName}" to "client" build output.`, ...movedAssetPaths.map((assetPath) => colors.dim(path$1.relative(builder.config.root, assetPath)))].join("\n"));
13756
13812
  };
13757
13813
  }
13758
13814
  function getHasPublicAssets({ publicDir }) {
@@ -13769,11 +13825,11 @@ async function fallbackBuild(builder, environment) {
13769
13825
  output: { entryFileNames: CLIENT_FALLBACK_ENTRY_NAME }
13770
13826
  };
13771
13827
  await builder.build(environment);
13772
- const fallbackEntryPath = path$2.resolve(builder.config.root, environment.config.build.outDir, CLIENT_FALLBACK_ENTRY_NAME);
13828
+ const fallbackEntryPath = path$1.resolve(builder.config.root, environment.config.build.outDir, CLIENT_FALLBACK_ENTRY_NAME);
13773
13829
  fs$1.unlinkSync(fallbackEntryPath);
13774
13830
  }
13775
13831
  function loadViteManifest(directory) {
13776
- const contents = fs$1.readFileSync(path$2.resolve(directory, ".vite", "manifest.json"), "utf-8");
13832
+ const contents = fs$1.readFileSync(path$1.resolve(directory, ".vite", "manifest.json"), "utf-8");
13777
13833
  return JSON.parse(contents);
13778
13834
  }
13779
13835
  function getImportedAssetPaths(viteManifest) {
@@ -13975,12 +14031,12 @@ function getLocalDevVarsForPreview(configPath, cloudflareEnv) {
13975
14031
  */
13976
14032
  function hasLocalDevVarsFileChanged({ configPaths, cloudflareEnv }, changedFilePath) {
13977
14033
  return [...configPaths].some((configPath) => {
13978
- const configDir = path$2.dirname(configPath);
14034
+ const configDir = path$1.dirname(configPath);
13979
14035
  return [
13980
14036
  ".dev.vars",
13981
14037
  ".env",
13982
14038
  ...cloudflareEnv ? [`.dev.vars.${cloudflareEnv}`, `.env.${cloudflareEnv}`] : []
13983
- ].some((localDevFile) => changedFilePath === path$2.join(configDir, localDevFile));
14039
+ ].some((localDevFile) => changedFilePath === path$1.join(configDir, localDevFile));
13984
14040
  });
13985
14041
  }
13986
14042
 
@@ -14550,11 +14606,11 @@ const getQueryString = (params) => {
14550
14606
  };
14551
14607
  const getUrl = (config, options) => {
14552
14608
  const encoder = config.ENCODE_PATH || encodeURI;
14553
- const path$3 = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring, group) => {
14609
+ const path$2 = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring, group) => {
14554
14610
  if (options.path?.hasOwnProperty(group)) return encoder(String(options.path[group]));
14555
14611
  return substring;
14556
14612
  });
14557
- const url = `${config.BASE}${path$3}`;
14613
+ const url = `${config.BASE}${path$2}`;
14558
14614
  if (options.query) return `${url}${getQueryString(options.query)}`;
14559
14615
  return url;
14560
14616
  };
@@ -14895,7 +14951,7 @@ async function constructBuildCommand(options, logger) {
14895
14951
  ];
14896
14952
  if (options.args) for (const arg in options.args) buildCmd.push("--build-arg", `${arg}=${options.args[arg]}`);
14897
14953
  if (options.setNetworkToHost) buildCmd.push("--network", "host");
14898
- const dockerfile = readFileSync$1(options.pathToDockerfile, "utf-8");
14954
+ const dockerfile = readFileSync(options.pathToDockerfile, "utf-8");
14899
14955
  buildCmd.push("-f", "-");
14900
14956
  buildCmd.push(options.buildContext);
14901
14957
  logger?.debug(`Building image with command: ${buildCmd.join(" ")}`);
@@ -14971,7 +15027,7 @@ async function dockerLoginImageRegistry(pathToDocker, domain) {
14971
15027
  expiration_minutes: 15,
14972
15028
  permissions: [ImageRegistryPermissions.PUSH, ImageRegistryPermissions.PULL]
14973
15029
  });
14974
- const child = spawn$1(pathToDocker, [
15030
+ const child = spawn(pathToDocker, [
14975
15031
  "login",
14976
15032
  "--password-stdin",
14977
15033
  "--username",
@@ -15000,6 +15056,9 @@ const MF_DEV_CONTAINER_PREFIX = "cloudflare-dev";
15000
15056
 
15001
15057
  //#endregion
15002
15058
  //#region ../containers-shared/src/knobs.ts
15059
+ const getCloudflareContainerRegistry = () => {
15060
+ return process.env.CLOUDFLARE_CONTAINER_REGISTRY ?? (process.env.WRANGLER_API_ENVIRONMENT === "staging" ? "staging.registry.cloudflare.com" : "registry.cloudflare.com");
15061
+ };
15003
15062
  /** Prefixes with the cloudflare-dev namespace. The name should be the container's DO classname, and the tag a build uuid. */
15004
15063
  const getDevContainerImageName = (name, tag) => {
15005
15064
  return `${MF_DEV_CONTAINER_PREFIX}/${name.toLowerCase()}:${tag}`;
@@ -15097,12 +15156,12 @@ const verifyDockerInstalled = async (dockerPath, isDev = true) => {
15097
15156
  Other container tooling that is compatible with the Docker CLI and engine may work, but is not yet guaranteed to do so. You can specify an executable with the environment variable WRANGLER_DOCKER_BIN and a socket with DOCKER_HOST.${isDev ? "\nTo suppress this error if you do not intend on triggering any container instances, set dev.enable_containers to false in your Wrangler config or passing in --enable-containers=false." : ""}`);
15098
15157
  };
15099
15158
  function isDir(inputPath) {
15100
- return statSync$1(inputPath).isDirectory();
15159
+ return statSync(inputPath).isDirectory();
15101
15160
  }
15102
15161
  /** returns true if it is a dockerfile, false if it is a registry link, throws if neither */
15103
15162
  const isDockerfile = (image, configPath) => {
15104
- const baseDir = configPath ? path$1.dirname(configPath) : process.cwd();
15105
- const maybeDockerfile = path$1.resolve(baseDir, image);
15163
+ const baseDir = configPath ? path.dirname(configPath) : process.cwd();
15164
+ const maybeDockerfile = path.resolve(baseDir, image);
15106
15165
  if (existsSync(maybeDockerfile)) {
15107
15166
  if (isDir(maybeDockerfile)) throw new UserError(`${image} is a directory, you should specify a path to the Dockerfile`);
15108
15167
  return true;
@@ -15233,11 +15292,33 @@ async function cleanupDuplicateImageTags(dockerPath, imageTag) {
15233
15292
  } catch {}
15234
15293
  }
15235
15294
 
15295
+ //#endregion
15296
+ //#region ../containers-shared/src/client/models/ExternalRegistryKind.ts
15297
+ /* istanbul ignore file */
15298
+ /**
15299
+ * The type of external registry that is being configured.
15300
+ */
15301
+ let ExternalRegistryKind = /* @__PURE__ */ function(ExternalRegistryKind$1) {
15302
+ ExternalRegistryKind$1["ECR"] = "ECR";
15303
+ return ExternalRegistryKind$1;
15304
+ }({});
15305
+
15236
15306
  //#endregion
15237
15307
  //#region ../containers-shared/src/images.ts
15238
- async function pullImage(dockerPath, options) {
15308
+ async function pullImage(dockerPath, options, logger, isVite) {
15239
15309
  const domain = new URL(`http://${options.image_uri}`).hostname;
15240
- await dockerLoginImageRegistry(dockerPath, domain);
15310
+ const isExternalRegistry = domain !== getCloudflareContainerRegistry();
15311
+ try {
15312
+ await dockerLoginImageRegistry(dockerPath, domain);
15313
+ } catch (e) {
15314
+ if (!isExternalRegistry) {
15315
+ if (isVite) throw new UserError(`Using images from the Cloudflare-managed registry is not currently supported with the Vite plugin.
15316
+ You should use a Dockerfile or a supported external registry and authenticate to that registry separately using \`docker login\` or similar.
15317
+ Supported external registries are currently: ${Object.values(ExternalRegistryKind).join(", ")}.`);
15318
+ throw e;
15319
+ }
15320
+ logger?.warn("Unable to retrieve configured registry credentials from Cloudflare.\nUnless this is a public image, you will need to run `wrangler containers registries configure` before deploying.\nAttempting to pull image anyway...");
15321
+ }
15241
15322
  const pull = runDockerCmd(dockerPath, [
15242
15323
  "pull",
15243
15324
  options.image_uri,
@@ -15285,7 +15366,7 @@ async function prepareContainerImagesForDev(args) {
15285
15366
  await build.ready;
15286
15367
  onContainerImagePreparationEnd({ containerOptions: options });
15287
15368
  } else {
15288
- const pull = await pullImage(dockerPath, options);
15369
+ const pull = await pullImage(dockerPath, options, args.logger, args.isVite);
15289
15370
  onContainerImagePreparationStart({
15290
15371
  containerOptions: options,
15291
15372
  abort: () => {
@@ -15369,7 +15450,7 @@ const INTERNAL_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
15369
15450
  const PUBLIC_DIR_PREFIX = "/__vite_public_dir__";
15370
15451
  function getPersistenceRoot(root, persistState) {
15371
15452
  if (persistState === false) return;
15372
- return path$2.resolve(root, typeof persistState === "object" ? persistState.path : ".wrangler/state", "v3");
15453
+ return path$1.resolve(root, typeof persistState === "object" ? persistState.path : ".wrangler/state", "v3");
15373
15454
  }
15374
15455
  const miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
15375
15456
  const ROUTER_WORKER_PATH = "./workers/router-worker.js";
@@ -15377,15 +15458,6 @@ const ASSET_WORKER_PATH = "./workers/asset-worker.js";
15377
15458
  const VITE_PROXY_WORKER_PATH = "./workers/vite-proxy-worker.js";
15378
15459
  const RUNNER_PATH = "./workers/runner-worker.js";
15379
15460
  const WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
15380
- function logUnknownTails(tails, userWorkers, log) {
15381
- for (const tailService of tails ?? []) {
15382
- let name;
15383
- if (typeof tailService === "string") name = tailService;
15384
- else if (typeof tailService === "object" && "name" in tailService && typeof tailService.name === "string") name = tailService.name;
15385
- else continue;
15386
- if (!userWorkers.some((w) => w.name === name)) log(colors.dim(colors.yellow(`Tail consumer "${name}" was not found in your config. Make sure you add it to the config or run it in another dev session if you'd like to simulate receiving tail events locally.`)));
15387
- }
15388
- }
15389
15461
  /** Map that maps worker configPaths to their existing remote proxy session data (if any) */
15390
15462
  const remoteProxySessionsDataMap = /* @__PURE__ */ new Map();
15391
15463
  async function getDevMiniflareOptions(ctx, viteDevServer) {
@@ -15399,7 +15471,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15399
15471
  modulesRoot: miniflareModulesRoot,
15400
15472
  modules: [{
15401
15473
  type: "ESModule",
15402
- path: path$2.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
15474
+ path: path$1.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
15403
15475
  contents: fs$1.readFileSync(fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url)))
15404
15476
  }],
15405
15477
  bindings: { CONFIG: { has_user_worker: resolvedPluginConfig.type === "workers" } },
@@ -15414,7 +15486,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15414
15486
  modulesRoot: miniflareModulesRoot,
15415
15487
  modules: [{
15416
15488
  type: "ESModule",
15417
- path: path$2.join(miniflareModulesRoot, ASSET_WORKER_PATH),
15489
+ path: path$1.join(miniflareModulesRoot, ASSET_WORKER_PATH),
15418
15490
  contents: fs$1.readFileSync(fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url)))
15419
15491
  }],
15420
15492
  bindings: {
@@ -15429,8 +15501,8 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15429
15501
  const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
15430
15502
  const publicPath = withTrailingSlash(publicDir.slice(root.length));
15431
15503
  if (publicDirInRoot && pathname.startsWith(publicPath)) return Response$1.json(null);
15432
- const publicDirFilePath = path$2.join(publicDir, pathname);
15433
- const rootDirFilePath = path$2.join(root, pathname);
15504
+ const publicDirFilePath = path$1.join(publicDir, pathname);
15505
+ const rootDirFilePath = path$1.join(root, pathname);
15434
15506
  for (const resolvedPath of [publicDirFilePath, rootDirFilePath]) try {
15435
15507
  if ((await fsp.stat(resolvedPath)).isFile()) return Response$1.json(resolvedPath === publicDirFilePath ? `${PUBLIC_DIR_PREFIX}${pathname}` : pathname);
15436
15508
  } catch (error) {}
@@ -15441,7 +15513,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15441
15513
  const { pathname } = new URL(request$1.url);
15442
15514
  const { root, publicDir } = resolvedViteConfig;
15443
15515
  const isInPublicDir = pathname.startsWith(PUBLIC_DIR_PREFIX);
15444
- const resolvedPath = isInPublicDir ? path$2.join(publicDir, pathname.slice(20)) : path$2.join(root, pathname);
15516
+ const resolvedPath = isInPublicDir ? path$1.join(publicDir, pathname.slice(20)) : path$1.join(root, pathname);
15445
15517
  try {
15446
15518
  let html = await fsp.readFile(resolvedPath, "utf-8");
15447
15519
  if (!isInPublicDir) html = await viteDevServer.transformIndexHtml(resolvedPath, html);
@@ -15458,7 +15530,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15458
15530
  modulesRoot: miniflareModulesRoot,
15459
15531
  modules: [{
15460
15532
  type: "ESModule",
15461
- path: path$2.join(miniflareModulesRoot, VITE_PROXY_WORKER_PATH),
15533
+ path: path$1.join(miniflareModulesRoot, VITE_PROXY_WORKER_PATH),
15462
15534
  contents: fs$1.readFileSync(fileURLToPath(new URL(VITE_PROXY_WORKER_PATH, import.meta.url)))
15463
15535
  }],
15464
15536
  serviceBindings: {
@@ -15473,7 +15545,8 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15473
15545
  const preExistingRemoteProxySession = worker.config.configPath ? remoteProxySessionsDataMap.get(worker.config.configPath) : void 0;
15474
15546
  const remoteProxySessionData = !resolvedPluginConfig.remoteBindings ? null : await maybeStartOrUpdateRemoteProxySession({
15475
15547
  name: worker.config.name,
15476
- bindings: bindings ?? {}
15548
+ bindings: bindings ?? {},
15549
+ account_id: worker.config.account_id
15477
15550
  }, preExistingRemoteProxySession ?? null);
15478
15551
  if (worker.config.configPath && remoteProxySessionData) remoteProxySessionsDataMap.set(worker.config.configPath, remoteProxySessionData);
15479
15552
  let containerBuildId;
@@ -15488,27 +15561,45 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15488
15561
  });
15489
15562
  for (const option of options ?? []) containerTagToOptionsMap.set(option.image_tag, option);
15490
15563
  }
15491
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions({
15564
+ const { externalWorkers: externalWorkers$1, workerOptions } = unstable_getMiniflareWorkerOptions({
15492
15565
  ...worker.config,
15493
15566
  assets: void 0
15494
15567
  }, resolvedPluginConfig.cloudflareEnv, {
15495
15568
  remoteProxyConnectionString: remoteProxySessionData?.session?.remoteProxyConnectionString,
15496
15569
  containerBuildId
15497
15570
  });
15498
- const { externalWorkers: externalWorkers$1 } = miniflareWorkerOptions;
15499
- const workerOptions = miniflareWorkerOptions.workerOptions;
15571
+ const wrappers = [
15572
+ `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from "${RUNNER_PATH}";`,
15573
+ `export { __VITE_RUNNER_OBJECT__ } from "${RUNNER_PATH}";`,
15574
+ `export default createWorkerEntrypointWrapper("default");`
15575
+ ];
15576
+ const exportTypes = ctx.workerNameToExportTypesMap.get(worker.config.name);
15577
+ assert(exportTypes, `Expected exportTypes to be defined`);
15578
+ for (const [name, type] of Object.entries(exportTypes)) wrappers.push(`export const ${name} = create${type}Wrapper("${name}");`);
15500
15579
  return {
15501
15580
  externalWorkers: externalWorkers$1,
15502
15581
  worker: {
15503
15582
  ...workerOptions,
15504
- name: workerOptions.name ?? worker.config.name,
15583
+ name: worker.config.name,
15584
+ modulesRoot: miniflareModulesRoot,
15585
+ modules: [{
15586
+ type: "ESModule",
15587
+ path: path$1.join(miniflareModulesRoot, WRAPPER_PATH),
15588
+ contents: wrappers.join("\n")
15589
+ }, {
15590
+ type: "ESModule",
15591
+ path: path$1.join(miniflareModulesRoot, RUNNER_PATH),
15592
+ contents: fs$1.readFileSync(fileURLToPath(new URL(RUNNER_PATH, import.meta.url)))
15593
+ }],
15594
+ unsafeUseModuleFallbackService: true,
15505
15595
  unsafeInspectorProxy: inputInspectorPort !== false,
15506
15596
  unsafeDirectSockets: environmentName === resolvedPluginConfig.entryWorkerEnvironmentName ? [{
15507
15597
  serviceName: VITE_PROXY_WORKER_NAME,
15508
- entrypoint: void 0,
15509
15598
  proxy: true
15510
- }] : [],
15511
- modulesRoot: miniflareModulesRoot,
15599
+ }, ...Object.entries(exportTypes).filter(([_, type]) => type === "WorkerEntrypoint").map(([entrypoint]) => ({
15600
+ entrypoint,
15601
+ proxy: true
15602
+ }))] : [],
15512
15603
  unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
15513
15604
  serviceBindings: {
15514
15605
  ...workerOptions.serviceBindings,
@@ -15521,6 +15612,14 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15521
15612
  const result = await viteDevServer.environments[environmentName].hot.handleInvoke(payload);
15522
15613
  return Response$1.json(result);
15523
15614
  }
15615
+ },
15616
+ durableObjects: {
15617
+ ...workerOptions.durableObjects,
15618
+ __VITE_RUNNER_OBJECT__: {
15619
+ className: "__VITE_RUNNER_OBJECT__",
15620
+ unsafeUniqueKey: kUnsafeEphemeralUniqueKey,
15621
+ unsafePreventEviction: true
15622
+ }
15524
15623
  }
15525
15624
  }
15526
15625
  };
@@ -15540,38 +15639,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15540
15639
  workers: [
15541
15640
  ...assetWorkers,
15542
15641
  ...externalWorkers,
15543
- ...userWorkers.map((workerOptions) => {
15544
- const wrappers = [
15545
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from "${RUNNER_PATH}";`,
15546
- `export { __VITE_RUNNER_OBJECT__ } from "${RUNNER_PATH}";`,
15547
- `export default createWorkerEntrypointWrapper("default");`
15548
- ];
15549
- const exportTypes = ctx.workerNameToExportTypesMap.get(workerOptions.name);
15550
- assert(exportTypes, `Expected exportTypes to be defined`);
15551
- for (const [name, type] of Object.entries(exportTypes)) wrappers.push(`export const ${name} = create${type}Wrapper("${name}");`);
15552
- logUnknownTails(workerOptions.tails, userWorkers, viteDevServer.config.logger.warn);
15553
- return {
15554
- ...workerOptions,
15555
- durableObjects: {
15556
- ...workerOptions.durableObjects,
15557
- __VITE_RUNNER_OBJECT__: {
15558
- className: "__VITE_RUNNER_OBJECT__",
15559
- unsafeUniqueKey: kUnsafeEphemeralUniqueKey,
15560
- unsafePreventEviction: true
15561
- }
15562
- },
15563
- modules: [{
15564
- type: "ESModule",
15565
- path: path$2.join(miniflareModulesRoot, WRAPPER_PATH),
15566
- contents: wrappers.join("\n")
15567
- }, {
15568
- type: "ESModule",
15569
- path: path$2.join(miniflareModulesRoot, RUNNER_PATH),
15570
- contents: fs$1.readFileSync(fileURLToPath(new URL(RUNNER_PATH, import.meta.url)))
15571
- }],
15572
- unsafeUseModuleFallbackService: true
15573
- };
15574
- })
15642
+ ...userWorkers
15575
15643
  ],
15576
15644
  async unsafeModuleFallbackService(request$1) {
15577
15645
  const rawSpecifier = new URL(request$1.url).searchParams.get("rawSpecifier");
@@ -15600,8 +15668,8 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
15600
15668
  }
15601
15669
  function getPreviewModules(main, modulesRules) {
15602
15670
  assert(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
15603
- const rootPath = path$2.dirname(main);
15604
- const entryPath = path$2.basename(main);
15671
+ const rootPath = path$1.dirname(main);
15672
+ const entryPath = path$1.basename(main);
15605
15673
  return {
15606
15674
  rootPath,
15607
15675
  modules: [{
@@ -15610,9 +15678,9 @@ function getPreviewModules(main, modulesRules) {
15610
15678
  }, ...modulesRules.flatMap(({ type, include }) => globSync(include, {
15611
15679
  cwd: rootPath,
15612
15680
  ignore: entryPath
15613
- }).map((path$3) => ({
15681
+ }).map((path$2) => ({
15614
15682
  type,
15615
- path: path$3
15683
+ path: path$2
15616
15684
  })))]
15617
15685
  };
15618
15686
  }
@@ -15625,7 +15693,8 @@ async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
15625
15693
  const preExistingRemoteProxySessionData = workerConfig.configPath ? remoteProxySessionsDataMap.get(workerConfig.configPath) : void 0;
15626
15694
  const remoteProxySessionData = !resolvedPluginConfig.remoteBindings ? null : await maybeStartOrUpdateRemoteProxySession({
15627
15695
  name: workerConfig.name,
15628
- bindings: bindings ?? {}
15696
+ bindings: bindings ?? {},
15697
+ account_id: workerConfig.account_id
15629
15698
  }, preExistingRemoteProxySessionData ?? null);
15630
15699
  if (workerConfig.configPath && remoteProxySessionData) remoteProxySessionsDataMap.set(workerConfig.configPath, remoteProxySessionData);
15631
15700
  let containerBuildId;
@@ -15646,7 +15715,6 @@ async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
15646
15715
  });
15647
15716
  const { externalWorkers } = miniflareWorkerOptions;
15648
15717
  const { modulesRules,...workerOptions } = miniflareWorkerOptions.workerOptions;
15649
- logUnknownTails(workerOptions.tails, resolvedPluginConfig.workers, vitePreviewServer.config.logger.warn);
15650
15718
  return [{
15651
15719
  ...workerOptions,
15652
15720
  name: workerOptions.name ?? workerConfig.name,
@@ -15823,7 +15891,9 @@ const devPlugin = createPlugin("dev", (ctx) => {
15823
15891
  dockerPath: getDockerPath(),
15824
15892
  containerOptions: [...containerTagToOptionsMap.values()],
15825
15893
  onContainerImagePreparationStart: () => {},
15826
- onContainerImagePreparationEnd: () => {}
15894
+ onContainerImagePreparationEnd: () => {},
15895
+ logger: viteDevServer.config.logger,
15896
+ isVite: true
15827
15897
  });
15828
15898
  containerImageTags = new Set(containerTagToOptionsMap.keys());
15829
15899
  viteDevServer.config.logger.info(colors.dim(colors.yellow("\n⚡️ Containers successfully built. To rebuild your containers during development, restart the Vite dev server (r + enter).")));
@@ -15937,11 +16007,11 @@ const nodeJsCompatWarningsPlugin = createPlugin("nodejs-compat-warnings", (ctx)
15937
16007
  if (workerConfig && !nodeJsCompat) return { optimizeDeps: { esbuildOptions: { plugins: [{
15938
16008
  name: "vite-plugin-cloudflare:nodejs-compat-warnings-resolver",
15939
16009
  setup(build) {
15940
- build.onResolve({ filter: NODEJS_MODULES_RE }, ({ path: path$3, importer }) => {
15941
- if (hasNodeJsAls(workerConfig) && isNodeAlsModule(path$3)) return;
15942
- nodeJsCompatWarningsMap.get(workerConfig)?.registerImport(path$3, importer);
16010
+ build.onResolve({ filter: NODEJS_MODULES_RE }, ({ path: path$2, importer }) => {
16011
+ if (hasNodeJsAls(workerConfig) && isNodeAlsModule(path$2)) return;
16012
+ nodeJsCompatWarningsMap.get(workerConfig)?.registerImport(path$2, importer);
15943
16013
  return {
15944
- path: path$3,
16014
+ path: path$2,
15945
16015
  external: true
15946
16016
  };
15947
16017
  });
@@ -16042,7 +16112,7 @@ const outputConfigPlugin = createPlugin("output-config", (ctx) => {
16042
16112
  function getAssetsDirectory(workerOutputDirectory, resolvedViteConfig) {
16043
16113
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
16044
16114
  assert(clientOutputDirectory, "Unexpected error: client output directory is undefined");
16045
- return path$2.relative(path$2.resolve(resolvedViteConfig.root, workerOutputDirectory), path$2.resolve(resolvedViteConfig.root, clientOutputDirectory));
16115
+ return path$1.relative(path$1.resolve(resolvedViteConfig.root, workerOutputDirectory), path$1.resolve(resolvedViteConfig.root, clientOutputDirectory));
16046
16116
  }
16047
16117
 
16048
16118
  //#endregion
@@ -16070,7 +16140,9 @@ const previewPlugin = createPlugin("preview", (ctx) => {
16070
16140
  dockerPath: getDockerPath(),
16071
16141
  containerOptions: [...containerTagToOptionsMap.values()],
16072
16142
  onContainerImagePreparationStart: () => {},
16073
- onContainerImagePreparationEnd: () => {}
16143
+ onContainerImagePreparationEnd: () => {},
16144
+ logger: vitePreviewServer.config.logger,
16145
+ isVite: true
16074
16146
  });
16075
16147
  const containerImageTags = new Set(containerTagToOptionsMap.keys());
16076
16148
  vitePreviewServer.config.logger.info(colors.dim(colors.yellow("\n⚡️ Containers successfully built.\n")));