@cloudflare/vite-plugin 1.13.17 → 1.13.19

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
@@ -14,10 +14,10 @@ import * as path$2 from "node:path";
14
14
  import path$1, { relative } from "node:path";
15
15
  import * as fs$1 from "node:fs";
16
16
  import fs, { readFileSync as readFileSync$1, realpathSync, statSync as statSync$1 } from "node:fs";
17
+ import * as fsp from "node:fs/promises";
17
18
  import { createHeaders, createRequest, sendResponse } from "@remix-run/node-fetch-server";
18
19
  import getPort, { portNumbers } from "get-port";
19
20
  import { maybeStartOrUpdateRemoteProxySession, unstable_convertConfigBindingsToStartWorkerBindings, unstable_getMiniflareWorkerOptions, unstable_getVarsForDev, unstable_readConfig } from "wrangler";
20
- import * as fsp from "node:fs/promises";
21
21
  import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
22
22
  import { globSync } from "tinyglobby";
23
23
  import { getCloudflarePreset } from "@cloudflare/unenv-preset";
@@ -378,6 +378,7 @@ let UpdateApplicationRolloutRequest;
378
378
 
379
379
  //#endregion
380
380
  //#region ../containers-shared/src/client/core/request.ts
381
+ /* istanbul ignore file */
381
382
  const isDefined = (value) => {
382
383
  return value !== void 0 && value !== null;
383
384
  };
@@ -583,6 +584,7 @@ const debugLogResponse = (config, response) => {
583
584
 
584
585
  //#endregion
585
586
  //#region ../containers-shared/src/client/services/ImageRegistriesService.ts
587
+ /* istanbul ignore file */
586
588
  var ImageRegistriesService = class {
587
589
  /**
588
590
  * Create an image registry protocol that resolves to multiple domains.
@@ -6871,457 +6873,92 @@ function getImportedAssetPaths(viteManifest) {
6871
6873
  }
6872
6874
 
6873
6875
  //#endregion
6874
- //#region src/shared.ts
6875
- const UNKNOWN_HOST = "http://localhost";
6876
- const INIT_PATH = "/__vite_plugin_cloudflare_init__";
6877
- const WORKER_ENTRY_PATH_HEADER = "__VITE_WORKER_ENTRY_PATH__";
6878
- const IS_ENTRY_WORKER_HEADER = "__VITE_IS_ENTRY_WORKER__";
6879
-
6880
- //#endregion
6881
- //#region src/utils.ts
6882
- function getOutputDirectory(userConfig, environmentName) {
6883
- const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
6884
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path$2.join(rootOutputDirectory, environmentName);
6885
- }
6886
- const postfixRE = /[?#].*$/;
6887
- function cleanUrl(url) {
6888
- return url.replace(postfixRE, "");
6876
+ //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
6877
+ const comma = ",".charCodeAt(0);
6878
+ const semicolon = ";".charCodeAt(0);
6879
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
6880
+ const intToChar = new Uint8Array(64);
6881
+ const charToInt = new Uint8Array(128);
6882
+ for (let i$1 = 0; i$1 < 64; i$1++) {
6883
+ const c = chars.charCodeAt(i$1);
6884
+ intToChar[i$1] = c;
6885
+ charToInt[c] = i$1;
6889
6886
  }
6890
- function withTrailingSlash$1(path$3) {
6891
- return path$3.endsWith("/") ? path$3 : `${path$3}/`;
6887
+ function encodeInteger(builder, num, relative$1) {
6888
+ let delta = num - relative$1;
6889
+ delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
6890
+ do {
6891
+ let clamped = delta & 31;
6892
+ delta >>>= 5;
6893
+ if (delta > 0) clamped |= 32;
6894
+ builder.write(intToChar[clamped]);
6895
+ } while (delta > 0);
6896
+ return num;
6892
6897
  }
6893
- function createRequestHandler(handler) {
6894
- return async (req, res, next) => {
6895
- let request$1;
6896
- try {
6897
- if (req.originalUrl) req.url = req.originalUrl;
6898
- request$1 = createRequest(req, res);
6899
- let response = await handler(toMiniflareRequest(request$1), req);
6900
- if (req.httpVersionMajor === 2) {
6901
- response = new Response$1(response.body, response);
6902
- response.headers.delete("transfer-encoding");
6903
- }
6904
- await sendResponse(res, response);
6905
- } catch (error) {
6906
- if (request$1?.signal.aborted) return;
6907
- next(error);
6898
+ const bufLength = 1024 * 16;
6899
+ const td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
6900
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
6901
+ } } : { decode(buf) {
6902
+ let out = "";
6903
+ for (let i$1 = 0; i$1 < buf.length; i$1++) out += String.fromCharCode(buf[i$1]);
6904
+ return out;
6905
+ } };
6906
+ var StringWriter = class {
6907
+ constructor() {
6908
+ this.pos = 0;
6909
+ this.out = "";
6910
+ this.buffer = new Uint8Array(bufLength);
6911
+ }
6912
+ write(v) {
6913
+ const { buffer } = this;
6914
+ buffer[this.pos++] = v;
6915
+ if (this.pos === bufLength) {
6916
+ this.out += td.decode(buffer);
6917
+ this.pos = 0;
6908
6918
  }
6909
- };
6910
- }
6911
- function toMiniflareRequest(request$1) {
6912
- const host = request$1.headers.get("Host");
6913
- const xForwardedHost = request$1.headers.get("X-Forwarded-Host");
6914
- if (host && !xForwardedHost) request$1.headers.set("X-Forwarded-Host", host);
6915
- const secFetchMode = request$1.headers.get("Sec-Fetch-Mode");
6916
- if (secFetchMode) request$1.headers.set("X-Mf-Sec-Fetch-Mode", secFetchMode);
6917
- return new Request$1(request$1.url, {
6918
- method: request$1.method,
6919
- headers: [["accept-encoding", "identity"], ...request$1.headers],
6920
- body: request$1.body,
6921
- duplex: "half",
6922
- signal: request$1.signal
6923
- });
6919
+ }
6920
+ flush() {
6921
+ const { buffer, out, pos } = this;
6922
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
6923
+ }
6924
+ };
6925
+ function encode(decoded) {
6926
+ const writer = new StringWriter();
6927
+ let sourcesIndex = 0;
6928
+ let sourceLine = 0;
6929
+ let sourceColumn = 0;
6930
+ let namesIndex = 0;
6931
+ for (let i$1 = 0; i$1 < decoded.length; i$1++) {
6932
+ const line = decoded[i$1];
6933
+ if (i$1 > 0) writer.write(semicolon);
6934
+ if (line.length === 0) continue;
6935
+ let genColumn = 0;
6936
+ for (let j = 0; j < line.length; j++) {
6937
+ const segment = line[j];
6938
+ if (j > 0) writer.write(comma);
6939
+ genColumn = encodeInteger(writer, segment[0], genColumn);
6940
+ if (segment.length === 1) continue;
6941
+ sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
6942
+ sourceLine = encodeInteger(writer, segment[2], sourceLine);
6943
+ sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
6944
+ if (segment.length === 4) continue;
6945
+ namesIndex = encodeInteger(writer, segment[4], namesIndex);
6946
+ }
6947
+ }
6948
+ return writer.flush();
6924
6949
  }
6925
6950
 
6926
6951
  //#endregion
6927
- //#region src/cloudflare-environment.ts
6928
- const MAIN_ENTRY_NAME = "index";
6929
- const webSocketUndefinedError = "The WebSocket is undefined";
6930
- const debuglog$1 = util.debuglog("@cloudflare:vite-plugin");
6931
- function createHotChannel(webSocketContainer) {
6932
- const listenersMap = /* @__PURE__ */ new Map();
6933
- const client = { send(payload) {
6934
- const webSocket = webSocketContainer.webSocket;
6935
- assert(webSocket, webSocketUndefinedError);
6936
- webSocket.send(JSON.stringify(payload));
6937
- } };
6938
- function onMessage(event) {
6939
- const payload = JSON.parse(event.data.toString());
6940
- const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
6941
- for (const listener of listeners) listener(payload.data, client);
6952
+ //#region ../../node_modules/.pnpm/magic-string@0.30.17/node_modules/magic-string/dist/magic-string.es.mjs
6953
+ var BitSet = class BitSet {
6954
+ constructor(arg) {
6955
+ this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
6942
6956
  }
6943
- return {
6944
- send(payload) {
6945
- const webSocket = webSocketContainer.webSocket;
6946
- assert(webSocket, webSocketUndefinedError);
6947
- webSocket.send(JSON.stringify(payload));
6948
- },
6949
- on(event, listener) {
6950
- const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
6951
- listeners.add(listener);
6952
- listenersMap.set(event, listeners);
6953
- },
6954
- off(event, listener) {
6955
- listenersMap.get(event)?.delete(listener);
6956
- },
6957
- listen() {
6958
- const webSocket = webSocketContainer.webSocket;
6959
- assert(webSocket, webSocketUndefinedError);
6960
- webSocket.addEventListener("message", onMessage);
6961
- },
6962
- close() {
6963
- const webSocket = webSocketContainer.webSocket;
6964
- assert(webSocket, webSocketUndefinedError);
6965
- webSocket.removeEventListener("message", onMessage);
6966
- }
6967
- };
6968
- }
6969
- var CloudflareDevEnvironment = class extends vite.DevEnvironment {
6970
- #webSocketContainer;
6971
- #worker;
6972
- constructor(name, config) {
6973
- const webSocketContainer = {};
6974
- super(name, config, {
6975
- hot: true,
6976
- transport: createHotChannel(webSocketContainer)
6977
- });
6978
- this.#webSocketContainer = webSocketContainer;
6957
+ add(n$1) {
6958
+ this.bits[n$1 >> 5] |= 1 << (n$1 & 31);
6979
6959
  }
6980
- async initRunner(worker, workerConfig, isEntryWorker) {
6981
- this.#worker = worker;
6982
- const response = await this.#worker.fetch(new URL(INIT_PATH, UNKNOWN_HOST), { headers: {
6983
- [WORKER_ENTRY_PATH_HEADER]: encodeURIComponent(workerConfig.main),
6984
- [IS_ENTRY_WORKER_HEADER]: String(isEntryWorker),
6985
- upgrade: "websocket"
6986
- } });
6987
- assert(response.ok, `Failed to initialize module runner, error: ${await response.text()}`);
6988
- const webSocket = response.webSocket;
6989
- assert(webSocket, "Failed to establish WebSocket");
6990
- webSocket.accept();
6991
- this.#webSocketContainer.webSocket = webSocket;
6992
- }
6993
- };
6994
- const cloudflareBuiltInModules = [
6995
- "cloudflare:email",
6996
- "cloudflare:sockets",
6997
- "cloudflare:workers",
6998
- "cloudflare:workflows"
6999
- ];
7000
- const defaultConditions = [
7001
- "workerd",
7002
- "worker",
7003
- "module",
7004
- "browser"
7005
- ];
7006
- const target = "es2022";
7007
- function createCloudflareEnvironmentOptions({ workerConfig, userConfig, mode, environmentName, isEntryWorker, hasNodeJsCompat: hasNodeJsCompat$1 }) {
7008
- const define$1 = getProcessEnvReplacements(hasNodeJsCompat$1, mode);
7009
- return {
7010
- resolve: {
7011
- noExternal: true,
7012
- conditions: [...defaultConditions, "development|production"],
7013
- builtins: [...cloudflareBuiltInModules]
7014
- },
7015
- define: define$1,
7016
- dev: { createEnvironment(name, config) {
7017
- return new CloudflareDevEnvironment(name, config);
7018
- } },
7019
- build: {
7020
- createEnvironment(name, config) {
7021
- return new vite.BuildEnvironment(name, config);
7022
- },
7023
- target,
7024
- emitAssets: true,
7025
- manifest: isEntryWorker,
7026
- outDir: getOutputDirectory(userConfig, environmentName),
7027
- copyPublicDir: false,
7028
- ssr: true,
7029
- rollupOptions: {
7030
- input: { [MAIN_ENTRY_NAME]: VIRTUAL_WORKER_ENTRY },
7031
- preserveEntrySignatures: "strict",
7032
- ..."rolldownVersion" in vite ? { platform: "neutral" } : {}
7033
- }
7034
- },
7035
- optimizeDeps: {
7036
- noDiscovery: false,
7037
- entries: vite.normalizePath(workerConfig.main),
7038
- exclude: [...cloudflareBuiltInModules],
7039
- esbuildOptions: {
7040
- platform: "neutral",
7041
- target,
7042
- conditions: [...defaultConditions, "development"],
7043
- resolveExtensions: [
7044
- ".mjs",
7045
- ".js",
7046
- ".mts",
7047
- ".ts",
7048
- ".jsx",
7049
- ".tsx",
7050
- ".json",
7051
- ".cjs",
7052
- ".cts",
7053
- ".ctx"
7054
- ],
7055
- define: define$1
7056
- }
7057
- },
7058
- keepProcessEnv: true
7059
- };
7060
- }
7061
- /**
7062
- * Gets `process.env` replacement values.
7063
- * `process.env.NODE_ENV` is always replaced.
7064
- * `process.env` is replaced with an empty object if `nodejs_compat` is not enabled
7065
- * @param hasNodeJsCompat - whether `nodejs_compat` is enabled
7066
- * @param mode - the Vite mode
7067
- * @returns replacement values
7068
- */
7069
- function getProcessEnvReplacements(hasNodeJsCompat$1, mode) {
7070
- const nodeEnv = process.env.NODE_ENV || mode;
7071
- const nodeEnvReplacements = {
7072
- "process.env.NODE_ENV": JSON.stringify(nodeEnv),
7073
- "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
7074
- "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
7075
- };
7076
- return hasNodeJsCompat$1 ? nodeEnvReplacements : {
7077
- ...nodeEnvReplacements,
7078
- "process.env": "{}",
7079
- "global.process.env": "{}",
7080
- "globalThis.process.env": "{}"
7081
- };
7082
- }
7083
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare$1) {
7084
- return Promise.all(Object.entries(resolvedPluginConfig.workers).map(async ([environmentName, workerConfig]) => {
7085
- debuglog$1("Initializing worker:", workerConfig.name);
7086
- const worker = await miniflare$1.getWorker(workerConfig.name);
7087
- const isEntryWorker = environmentName === resolvedPluginConfig.entryWorkerEnvironmentName;
7088
- return viteDevServer.environments[environmentName].initRunner(worker, workerConfig, isEntryWorker);
7089
- }));
7090
- }
7091
-
7092
- //#endregion
7093
- //#region src/constants.ts
7094
- const ROUTER_WORKER_NAME = "__router-worker__";
7095
- const ASSET_WORKER_NAME = "__asset-worker__";
7096
- const VITE_PROXY_WORKER_NAME = "__vite_proxy_worker__";
7097
- const kRequestType = Symbol("kRequestType");
7098
-
7099
- //#endregion
7100
- //#region src/containers.ts
7101
- /**
7102
- * Returns the path to the Docker executable as defined by the
7103
- * `WRANGLER_DOCKER_BIN` environment variable, or the default value
7104
- * `"docker"`
7105
- */
7106
- function getDockerPath() {
7107
- return process.env["WRANGLER_DOCKER_BIN"] || "docker";
7108
- }
7109
- /**
7110
- * @returns Container options suitable for building or pulling images,
7111
- * with image tag set to well-known dev format, or undefined if
7112
- * containers are not enabled or not configured.
7113
- */
7114
- function getContainerOptions(options) {
7115
- const { containersConfig, containerBuildId, configPath } = options;
7116
- if (!containersConfig?.length) return;
7117
- return containersConfig.map((container) => {
7118
- if (isDockerfile(container.image, configPath)) return {
7119
- dockerfile: container.image,
7120
- image_build_context: container.image_build_context ?? path$1.dirname(container.image),
7121
- image_vars: container.image_vars,
7122
- class_name: container.class_name,
7123
- image_tag: getDevContainerImageName(container.class_name, containerBuildId)
7124
- };
7125
- else return {
7126
- image_uri: container.image,
7127
- class_name: container.class_name,
7128
- image_tag: getDevContainerImageName(container.class_name, containerBuildId)
7129
- };
7130
- });
7131
- }
7132
-
7133
- //#endregion
7134
- //#region src/debugging.ts
7135
- const DEBUG_PATH = "/__debug";
7136
- const DEFAULT_INSPECTOR_PORT = 9229;
7137
- /**
7138
- * Gets the inspector port option that should be passed to Miniflare based on the user's plugin config
7139
- */
7140
- async function getInputInspectorPortOption(resolvedPluginConfig, viteServer, miniflare$1) {
7141
- if (resolvedPluginConfig.inspectorPort === void 0 || resolvedPluginConfig.inspectorPort === 0) {
7142
- const resolvedInspectorPort = await getResolvedInspectorPort(resolvedPluginConfig, miniflare$1);
7143
- if (resolvedInspectorPort !== null) return resolvedInspectorPort;
7144
- }
7145
- const inputInspectorPort = resolvedPluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
7146
- if (resolvedPluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) viteServer.config.logger.warn(colors.dim(`Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead\n`));
7147
- return inputInspectorPort;
7148
- }
7149
- /**
7150
- * Gets the resolved inspector port provided by Miniflare
7151
- */
7152
- async function getResolvedInspectorPort(resolvedPluginConfig, miniflare$1) {
7153
- if (miniflare$1 && resolvedPluginConfig.inspectorPort !== false) {
7154
- const miniflareInspectorUrl = await miniflare$1.getInspectorURL();
7155
- return Number.parseInt(miniflareInspectorUrl.port);
7156
- }
7157
- return null;
7158
- }
7159
- function getFirstAvailablePort(start) {
7160
- return getPort({ port: portNumbers(start, 65535) });
7161
- }
7162
- /**
7163
- * Modifies the URL printing logic to also include a URL that developers can use to open DevTools to debug their Worker(s)
7164
- */
7165
- function addDebugToVitePrintUrls(server) {
7166
- const originalPrintUrls = server.printUrls;
7167
- server.printUrls = () => {
7168
- originalPrintUrls();
7169
- const localUrl = server.resolvedUrls?.local[0];
7170
- if (localUrl) {
7171
- const { protocol, hostname, port } = new URL(localUrl);
7172
- const colorDebugUrl = (url) => colors.dim(colors.yellow(url.replace(/:(\d+)\//, (_, port$1) => `:${colors.bold(port$1)}/`)));
7173
- server.config.logger.info(` ${colors.green("➜")} ${colors.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${DEBUG_PATH}`)}`);
7174
- }
7175
- };
7176
- }
7177
- /**
7178
- * Generate HTML that comprises a single script that:
7179
- * - redirects the page to the DevTools for debugging the first available Worker
7180
- * - opens tabs to the DevTools for all the remaining workers if any
7181
- *
7182
- * Note: this works based on the Miniflare inspector proxy logic (where Workers are available via
7183
- * their names)
7184
- */
7185
- function getDebugPathHtml(workerNames, inspectorPort) {
7186
- assert(workerNames.length >= 1, "no workers present to debug");
7187
- const workerDevtoolsUrls = workerNames.map((workerName) => {
7188
- const localhost = `localhost:${inspectorPort}/${workerName}`;
7189
- return `https://devtools.devprod.cloudflare.dev/js_app?${new URLSearchParams({
7190
- theme: "systemPreferred",
7191
- debugger: "true",
7192
- ws: localhost,
7193
- domain: workerName
7194
- })}`;
7195
- });
7196
- return `
7197
- <script>
7198
- const workerUrls = ${JSON.stringify(workerDevtoolsUrls)};
7199
- const [firstUrl, ...rest] = workerUrls;
7200
- for (const workerUrl of rest) {
7201
- // open new tabs for the devtools of the various workers
7202
- window.open(workerUrl);
7203
- }
7204
- // redirect the current tab to the devtools of the first worker
7205
- window.location.replace(firstUrl);
7206
- <\/script>
7207
- `;
7208
- }
7209
-
7210
- //#endregion
7211
- //#region src/dev-vars.ts
7212
- /**
7213
- * Gets any variables with which to augment the Worker config in preview mode.
7214
- *
7215
- * Calls `unstable_getVarsForDev` with the current Cloudflare environment to get local dev variables from the `.dev.vars` and `.env` files.
7216
- */
7217
- function getLocalDevVarsForPreview(configPath, cloudflareEnv) {
7218
- const dotDevDotVars = unstable_getVarsForDev(configPath, void 0, {}, cloudflareEnv);
7219
- const dotDevDotVarsEntries = Array.from(Object.entries(dotDevDotVars));
7220
- if (dotDevDotVarsEntries.length > 0) return dotDevDotVarsEntries.map(([key, value]) => {
7221
- return `${key} = "${value?.toString().replaceAll(`"`, `\\"`)}"\n`;
7222
- }).join("");
7223
- }
7224
- /**
7225
- * Returns `true` if the `changedFile` matches a `.dev.vars` or `.env` file.
7226
- */
7227
- function hasLocalDevVarsFileChanged({ configPaths, cloudflareEnv }, changedFilePath) {
7228
- return [...configPaths].some((configPath) => {
7229
- const configDir = path$2.dirname(configPath);
7230
- return [
7231
- ".dev.vars",
7232
- ".env",
7233
- ...cloudflareEnv ? [`.dev.vars.${cloudflareEnv}`, `.env.${cloudflareEnv}`] : []
7234
- ].some((localDevFile) => changedFilePath === path$2.join(configDir, localDevFile));
7235
- });
7236
- }
7237
-
7238
- //#endregion
7239
- //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
7240
- const comma = ",".charCodeAt(0);
7241
- const semicolon = ";".charCodeAt(0);
7242
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7243
- const intToChar = new Uint8Array(64);
7244
- const charToInt = new Uint8Array(128);
7245
- for (let i$1 = 0; i$1 < 64; i$1++) {
7246
- const c = chars.charCodeAt(i$1);
7247
- intToChar[i$1] = c;
7248
- charToInt[c] = i$1;
7249
- }
7250
- function encodeInteger(builder, num, relative$1) {
7251
- let delta = num - relative$1;
7252
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
7253
- do {
7254
- let clamped = delta & 31;
7255
- delta >>>= 5;
7256
- if (delta > 0) clamped |= 32;
7257
- builder.write(intToChar[clamped]);
7258
- } while (delta > 0);
7259
- return num;
7260
- }
7261
- const bufLength = 1024 * 16;
7262
- const td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
7263
- return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
7264
- } } : { decode(buf) {
7265
- let out = "";
7266
- for (let i$1 = 0; i$1 < buf.length; i$1++) out += String.fromCharCode(buf[i$1]);
7267
- return out;
7268
- } };
7269
- var StringWriter = class {
7270
- constructor() {
7271
- this.pos = 0;
7272
- this.out = "";
7273
- this.buffer = new Uint8Array(bufLength);
7274
- }
7275
- write(v) {
7276
- const { buffer } = this;
7277
- buffer[this.pos++] = v;
7278
- if (this.pos === bufLength) {
7279
- this.out += td.decode(buffer);
7280
- this.pos = 0;
7281
- }
7282
- }
7283
- flush() {
7284
- const { buffer, out, pos } = this;
7285
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
7286
- }
7287
- };
7288
- function encode(decoded) {
7289
- const writer = new StringWriter();
7290
- let sourcesIndex = 0;
7291
- let sourceLine = 0;
7292
- let sourceColumn = 0;
7293
- let namesIndex = 0;
7294
- for (let i$1 = 0; i$1 < decoded.length; i$1++) {
7295
- const line = decoded[i$1];
7296
- if (i$1 > 0) writer.write(semicolon);
7297
- if (line.length === 0) continue;
7298
- let genColumn = 0;
7299
- for (let j = 0; j < line.length; j++) {
7300
- const segment = line[j];
7301
- if (j > 0) writer.write(comma);
7302
- genColumn = encodeInteger(writer, segment[0], genColumn);
7303
- if (segment.length === 1) continue;
7304
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
7305
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
7306
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
7307
- if (segment.length === 4) continue;
7308
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
7309
- }
7310
- }
7311
- return writer.flush();
7312
- }
7313
-
7314
- //#endregion
7315
- //#region ../../node_modules/.pnpm/magic-string@0.30.17/node_modules/magic-string/dist/magic-string.es.mjs
7316
- var BitSet = class BitSet {
7317
- constructor(arg) {
7318
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
7319
- }
7320
- add(n$1) {
7321
- this.bits[n$1 >> 5] |= 1 << (n$1 & 31);
7322
- }
7323
- has(n$1) {
7324
- return !!(this.bits[n$1 >> 5] & 1 << (n$1 & 31));
6960
+ has(n$1) {
6961
+ return !!(this.bits[n$1 >> 5] & 1 << (n$1 & 31));
7325
6962
  }
7326
6963
  };
7327
6964
  var Chunk = class Chunk {
@@ -8181,148 +7818,518 @@ var MagicString = class MagicString {
8181
7818
  hasChanged() {
8182
7819
  return this.original !== this.toString();
8183
7820
  }
8184
- _replaceRegexp(searchValue, replacement) {
8185
- function getReplacement(match, str) {
8186
- if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i$1) => {
8187
- if (i$1 === "$") return "$";
8188
- if (i$1 === "&") return match[0];
8189
- if (+i$1 < match.length) return match[+i$1];
8190
- return `$${i$1}`;
8191
- });
8192
- else return replacement(...match, match.index, str, match.groups);
8193
- }
8194
- function matchAll(re, str) {
8195
- let match;
8196
- const matches = [];
8197
- while (match = re.exec(str)) matches.push(match);
8198
- return matches;
8199
- }
8200
- if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
8201
- if (match.index != null) {
8202
- const replacement$1 = getReplacement(match, this.original);
8203
- if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
7821
+ _replaceRegexp(searchValue, replacement) {
7822
+ function getReplacement(match, str) {
7823
+ if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i$1) => {
7824
+ if (i$1 === "$") return "$";
7825
+ if (i$1 === "&") return match[0];
7826
+ if (+i$1 < match.length) return match[+i$1];
7827
+ return `$${i$1}`;
7828
+ });
7829
+ else return replacement(...match, match.index, str, match.groups);
7830
+ }
7831
+ function matchAll(re, str) {
7832
+ let match;
7833
+ const matches = [];
7834
+ while (match = re.exec(str)) matches.push(match);
7835
+ return matches;
7836
+ }
7837
+ if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
7838
+ if (match.index != null) {
7839
+ const replacement$1 = getReplacement(match, this.original);
7840
+ if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
7841
+ }
7842
+ });
7843
+ else {
7844
+ const match = this.original.match(searchValue);
7845
+ if (match && match.index != null) {
7846
+ const replacement$1 = getReplacement(match, this.original);
7847
+ if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
7848
+ }
7849
+ }
7850
+ return this;
7851
+ }
7852
+ _replaceString(string, replacement) {
7853
+ const { original } = this;
7854
+ const index = original.indexOf(string);
7855
+ if (index !== -1) this.overwrite(index, index + string.length, replacement);
7856
+ return this;
7857
+ }
7858
+ replace(searchValue, replacement) {
7859
+ if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
7860
+ return this._replaceRegexp(searchValue, replacement);
7861
+ }
7862
+ _replaceAllString(string, replacement) {
7863
+ const { original } = this;
7864
+ const stringLength = string.length;
7865
+ for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) if (original.slice(index, index + stringLength) !== replacement) this.overwrite(index, index + stringLength, replacement);
7866
+ return this;
7867
+ }
7868
+ replaceAll(searchValue, replacement) {
7869
+ if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
7870
+ if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
7871
+ return this._replaceRegexp(searchValue, replacement);
7872
+ }
7873
+ };
7874
+
7875
+ //#endregion
7876
+ //#region src/utils.ts
7877
+ function getOutputDirectory(userConfig, environmentName) {
7878
+ const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
7879
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path$2.join(rootOutputDirectory, environmentName);
7880
+ }
7881
+ const postfixRE = /[?#].*$/;
7882
+ function cleanUrl(url) {
7883
+ return url.replace(postfixRE, "");
7884
+ }
7885
+ function withTrailingSlash$1(path$3) {
7886
+ return path$3.endsWith("/") ? path$3 : `${path$3}/`;
7887
+ }
7888
+ function createRequestHandler(handler) {
7889
+ return async (req, res, next) => {
7890
+ let request$1;
7891
+ try {
7892
+ if (req.originalUrl) req.url = req.originalUrl;
7893
+ request$1 = createRequest(req, res);
7894
+ let response = await handler(toMiniflareRequest(request$1), req);
7895
+ if (req.httpVersionMajor === 2) {
7896
+ response = new Response$1(response.body, response);
7897
+ response.headers.delete("transfer-encoding");
7898
+ }
7899
+ await sendResponse(res, response);
7900
+ } catch (error) {
7901
+ if (request$1?.signal.aborted) return;
7902
+ next(error);
7903
+ }
7904
+ };
7905
+ }
7906
+ function toMiniflareRequest(request$1) {
7907
+ const host = request$1.headers.get("Host");
7908
+ const xForwardedHost = request$1.headers.get("X-Forwarded-Host");
7909
+ if (host && !xForwardedHost) request$1.headers.set("X-Forwarded-Host", host);
7910
+ const secFetchMode = request$1.headers.get("Sec-Fetch-Mode");
7911
+ if (secFetchMode) request$1.headers.set(CoreHeaders.SEC_FETCH_MODE, secFetchMode);
7912
+ return new Request$1(request$1.url, {
7913
+ method: request$1.method,
7914
+ headers: [["accept-encoding", "identity"], ...request$1.headers],
7915
+ body: request$1.body,
7916
+ duplex: "half",
7917
+ signal: request$1.signal
7918
+ });
7919
+ }
7920
+
7921
+ //#endregion
7922
+ //#region src/plugins/additional-modules.ts
7923
+ const ADDITIONAL_MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${[
7924
+ "CompiledWasm",
7925
+ "Data",
7926
+ "Text"
7927
+ ].join("|")})__(.*?)__CLOUDFLARE_MODULE__`;
7928
+ const additionalModuleRE = new RegExp(ADDITIONAL_MODULE_PATTERN);
7929
+ const additionalModuleGlobalRE = new RegExp(ADDITIONAL_MODULE_PATTERN, "g");
7930
+ const moduleRules = [
7931
+ {
7932
+ type: "CompiledWasm",
7933
+ extensions: [".wasm", ".wasm?module"]
7934
+ },
7935
+ {
7936
+ type: "Data",
7937
+ extensions: [".bin"]
7938
+ },
7939
+ {
7940
+ type: "Text",
7941
+ extensions: [".txt", ".html"]
7942
+ }
7943
+ ];
7944
+ function matchAdditionalModule(source) {
7945
+ for (const rule of moduleRules) for (const extension of rule.extensions) if (source.endsWith(extension)) return rule.type;
7946
+ return null;
7947
+ }
7948
+ function createModuleReference(type, id) {
7949
+ return `__CLOUDFLARE_MODULE__${type}__${id}__CLOUDFLARE_MODULE__`;
7950
+ }
7951
+ /**
7952
+ * Plugin to support additional module types (`CompiledWasm`, `Data` and `Text`)
7953
+ */
7954
+ const additionalModulesPlugin = createPlugin("additional-modules", (ctx) => {
7955
+ const additionalModulePaths = /* @__PURE__ */ new Set();
7956
+ return {
7957
+ enforce: "pre",
7958
+ applyToEnvironment(environment) {
7959
+ return ctx.getWorkerConfig(environment.name) !== void 0;
7960
+ },
7961
+ async resolveId(source, importer, options) {
7962
+ const additionalModuleType = matchAdditionalModule(source);
7963
+ if (!additionalModuleType) return;
7964
+ const resolved = await this.resolve(cleanUrl(source), importer, options);
7965
+ if (!resolved) throw new Error(`Import "${source}" not found. Does the file exist?`);
7966
+ additionalModulePaths.add(resolved.id);
7967
+ return {
7968
+ external: true,
7969
+ id: createModuleReference(additionalModuleType, resolved.id)
7970
+ };
7971
+ },
7972
+ hotUpdate(options) {
7973
+ if (additionalModulePaths.has(options.file)) {
7974
+ options.server.restart();
7975
+ return [];
8204
7976
  }
8205
- });
8206
- else {
8207
- const match = this.original.match(searchValue);
8208
- if (match && match.index != null) {
8209
- const replacement$1 = getReplacement(match, this.original);
8210
- if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
7977
+ },
7978
+ async renderChunk(code, chunk) {
7979
+ const matches = code.matchAll(additionalModuleGlobalRE);
7980
+ let magicString;
7981
+ for (const match of matches) {
7982
+ magicString ??= new MagicString(code);
7983
+ const [full, _, modulePath] = match;
7984
+ assert(modulePath, `Unexpected error: module path not found in reference ${full}.`);
7985
+ let source;
7986
+ try {
7987
+ source = await fsp.readFile(modulePath);
7988
+ } catch (error) {
7989
+ throw new Error(`Import "${modulePath}" not found. Does the file exist?`);
7990
+ }
7991
+ const referenceId = this.emitFile({
7992
+ type: "asset",
7993
+ name: path$2.basename(modulePath),
7994
+ originalFileName: modulePath,
7995
+ source
7996
+ });
7997
+ const emittedFileName = this.getFileName(referenceId);
7998
+ const relativePath = vite.normalizePath(path$2.relative(path$2.dirname(chunk.fileName), emittedFileName));
7999
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
8000
+ magicString.update(match.index, match.index + full.length, importPath);
8211
8001
  }
8002
+ if (magicString) return {
8003
+ code: magicString.toString(),
8004
+ map: this.environment.config.build.sourcemap ? magicString.generateMap({ hires: "boundary" }) : null
8005
+ };
8212
8006
  }
8213
- return this;
8214
- }
8215
- _replaceString(string, replacement) {
8216
- const { original } = this;
8217
- const index = original.indexOf(string);
8218
- if (index !== -1) this.overwrite(index, index + string.length, replacement);
8219
- return this;
8007
+ };
8008
+ });
8009
+
8010
+ //#endregion
8011
+ //#region src/shared.ts
8012
+ const UNKNOWN_HOST = "http://localhost";
8013
+ const INIT_PATH = "/__vite_plugin_cloudflare_init__";
8014
+ const WORKER_ENTRY_PATH_HEADER = "__VITE_WORKER_ENTRY_PATH__";
8015
+ const IS_ENTRY_WORKER_HEADER = "__VITE_IS_ENTRY_WORKER__";
8016
+
8017
+ //#endregion
8018
+ //#region src/cloudflare-environment.ts
8019
+ const MAIN_ENTRY_NAME = "index";
8020
+ const webSocketUndefinedError = "The WebSocket is undefined";
8021
+ const debuglog$1 = util.debuglog("@cloudflare:vite-plugin");
8022
+ function createHotChannel(webSocketContainer) {
8023
+ const listenersMap = /* @__PURE__ */ new Map();
8024
+ const client = { send(payload) {
8025
+ const webSocket = webSocketContainer.webSocket;
8026
+ assert(webSocket, webSocketUndefinedError);
8027
+ webSocket.send(JSON.stringify(payload));
8028
+ } };
8029
+ function onMessage(event) {
8030
+ const payload = JSON.parse(event.data.toString());
8031
+ const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
8032
+ for (const listener of listeners) listener(payload.data, client);
8220
8033
  }
8221
- replace(searchValue, replacement) {
8222
- if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
8223
- return this._replaceRegexp(searchValue, replacement);
8034
+ return {
8035
+ send(payload) {
8036
+ const webSocket = webSocketContainer.webSocket;
8037
+ assert(webSocket, webSocketUndefinedError);
8038
+ webSocket.send(JSON.stringify(payload));
8039
+ },
8040
+ on(event, listener) {
8041
+ const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
8042
+ listeners.add(listener);
8043
+ listenersMap.set(event, listeners);
8044
+ },
8045
+ off(event, listener) {
8046
+ listenersMap.get(event)?.delete(listener);
8047
+ },
8048
+ listen() {
8049
+ const webSocket = webSocketContainer.webSocket;
8050
+ assert(webSocket, webSocketUndefinedError);
8051
+ webSocket.addEventListener("message", onMessage);
8052
+ },
8053
+ close() {
8054
+ const webSocket = webSocketContainer.webSocket;
8055
+ assert(webSocket, webSocketUndefinedError);
8056
+ webSocket.removeEventListener("message", onMessage);
8057
+ }
8058
+ };
8059
+ }
8060
+ var CloudflareDevEnvironment = class extends vite.DevEnvironment {
8061
+ #webSocketContainer;
8062
+ constructor(name, config) {
8063
+ const webSocketContainer = {};
8064
+ super(name, config, {
8065
+ hot: true,
8066
+ transport: createHotChannel(webSocketContainer)
8067
+ });
8068
+ this.#webSocketContainer = webSocketContainer;
8224
8069
  }
8225
- _replaceAllString(string, replacement) {
8226
- const { original } = this;
8227
- const stringLength = string.length;
8228
- for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) if (original.slice(index, index + stringLength) !== replacement) this.overwrite(index, index + stringLength, replacement);
8229
- return this;
8070
+ async initRunner(miniflare$1, workerConfig, isEntryWorker) {
8071
+ const response = await miniflare$1.dispatchFetch(new URL(INIT_PATH, UNKNOWN_HOST), { headers: {
8072
+ [CoreHeaders.ROUTE_OVERRIDE]: workerConfig.name,
8073
+ [WORKER_ENTRY_PATH_HEADER]: encodeURIComponent(workerConfig.main),
8074
+ [IS_ENTRY_WORKER_HEADER]: String(isEntryWorker),
8075
+ upgrade: "websocket"
8076
+ } });
8077
+ assert(response.ok, `Failed to initialize module runner, error: ${await response.text()}`);
8078
+ const webSocket = response.webSocket;
8079
+ assert(webSocket, "Failed to establish WebSocket");
8080
+ webSocket.accept();
8081
+ this.#webSocketContainer.webSocket = webSocket;
8230
8082
  }
8231
- replaceAll(searchValue, replacement) {
8232
- if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
8233
- if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
8234
- return this._replaceRegexp(searchValue, replacement);
8083
+ async fetchModule(id, importer, options) {
8084
+ if (additionalModuleRE.test(id)) return {
8085
+ externalize: id,
8086
+ type: "module"
8087
+ };
8088
+ return super.fetchModule(id, importer, options);
8235
8089
  }
8236
8090
  };
8091
+ const cloudflareBuiltInModules = [
8092
+ "cloudflare:email",
8093
+ "cloudflare:sockets",
8094
+ "cloudflare:workers",
8095
+ "cloudflare:workflows"
8096
+ ];
8097
+ const defaultConditions = [
8098
+ "workerd",
8099
+ "worker",
8100
+ "module",
8101
+ "browser"
8102
+ ];
8103
+ const target = "es2022";
8104
+ function createCloudflareEnvironmentOptions({ workerConfig, userConfig, mode, environmentName, isEntryWorker, hasNodeJsCompat: hasNodeJsCompat$1 }) {
8105
+ const define$1 = getProcessEnvReplacements(hasNodeJsCompat$1, mode);
8106
+ return {
8107
+ resolve: {
8108
+ noExternal: true,
8109
+ conditions: [...defaultConditions, "development|production"],
8110
+ builtins: [...cloudflareBuiltInModules]
8111
+ },
8112
+ define: define$1,
8113
+ dev: { createEnvironment(name, config) {
8114
+ return new CloudflareDevEnvironment(name, config);
8115
+ } },
8116
+ build: {
8117
+ createEnvironment(name, config) {
8118
+ return new vite.BuildEnvironment(name, config);
8119
+ },
8120
+ target,
8121
+ emitAssets: true,
8122
+ manifest: isEntryWorker,
8123
+ outDir: getOutputDirectory(userConfig, environmentName),
8124
+ copyPublicDir: false,
8125
+ ssr: true,
8126
+ rollupOptions: {
8127
+ input: { [MAIN_ENTRY_NAME]: VIRTUAL_WORKER_ENTRY },
8128
+ preserveEntrySignatures: "strict",
8129
+ ..."rolldownVersion" in vite ? { platform: "neutral" } : {}
8130
+ }
8131
+ },
8132
+ optimizeDeps: {
8133
+ noDiscovery: false,
8134
+ entries: vite.normalizePath(workerConfig.main),
8135
+ exclude: [...cloudflareBuiltInModules],
8136
+ esbuildOptions: {
8137
+ platform: "neutral",
8138
+ target,
8139
+ conditions: [...defaultConditions, "development"],
8140
+ resolveExtensions: [
8141
+ ".mjs",
8142
+ ".js",
8143
+ ".mts",
8144
+ ".ts",
8145
+ ".jsx",
8146
+ ".tsx",
8147
+ ".json",
8148
+ ".cjs",
8149
+ ".cts",
8150
+ ".ctx"
8151
+ ],
8152
+ define: define$1
8153
+ }
8154
+ },
8155
+ keepProcessEnv: true
8156
+ };
8157
+ }
8158
+ /**
8159
+ * Gets `process.env` replacement values.
8160
+ * `process.env.NODE_ENV` is always replaced.
8161
+ * `process.env` is replaced with an empty object if `nodejs_compat` is not enabled
8162
+ * @param hasNodeJsCompat - whether `nodejs_compat` is enabled
8163
+ * @param mode - the Vite mode
8164
+ * @returns replacement values
8165
+ */
8166
+ function getProcessEnvReplacements(hasNodeJsCompat$1, mode) {
8167
+ const nodeEnv = process.env.NODE_ENV || mode;
8168
+ const nodeEnvReplacements = {
8169
+ "process.env.NODE_ENV": JSON.stringify(nodeEnv),
8170
+ "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
8171
+ "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
8172
+ };
8173
+ return hasNodeJsCompat$1 ? nodeEnvReplacements : {
8174
+ ...nodeEnvReplacements,
8175
+ "process.env": "{}",
8176
+ "global.process.env": "{}",
8177
+ "globalThis.process.env": "{}"
8178
+ };
8179
+ }
8180
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare$1) {
8181
+ return Promise.all(Object.entries(resolvedPluginConfig.workers).map(async ([environmentName, workerConfig]) => {
8182
+ debuglog$1("Initializing worker:", workerConfig.name);
8183
+ const isEntryWorker = environmentName === resolvedPluginConfig.entryWorkerEnvironmentName;
8184
+ return viteDevServer.environments[environmentName].initRunner(miniflare$1, workerConfig, isEntryWorker);
8185
+ }));
8186
+ }
8237
8187
 
8238
8188
  //#endregion
8239
- //#region src/plugins/additional-modules.ts
8240
- const ADDITIONAL_MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${[
8241
- "CompiledWasm",
8242
- "Data",
8243
- "Text"
8244
- ].join("|")})__(.*?)__CLOUDFLARE_MODULE__`;
8245
- const additionalModuleRE = new RegExp(ADDITIONAL_MODULE_PATTERN);
8246
- const additionalModuleGlobalRE = new RegExp(ADDITIONAL_MODULE_PATTERN, "g");
8247
- const moduleRules = [
8248
- {
8249
- type: "CompiledWasm",
8250
- extensions: [".wasm", ".wasm?module"]
8251
- },
8252
- {
8253
- type: "Data",
8254
- extensions: [".bin"]
8255
- },
8256
- {
8257
- type: "Text",
8258
- extensions: [".txt", ".html"]
8189
+ //#region src/constants.ts
8190
+ const ROUTER_WORKER_NAME = "__router-worker__";
8191
+ const ASSET_WORKER_NAME = "__asset-worker__";
8192
+ const VITE_PROXY_WORKER_NAME = "__vite_proxy_worker__";
8193
+ const kRequestType = Symbol("kRequestType");
8194
+
8195
+ //#endregion
8196
+ //#region src/containers.ts
8197
+ /**
8198
+ * Returns the path to the Docker executable as defined by the
8199
+ * `WRANGLER_DOCKER_BIN` environment variable, or the default value
8200
+ * `"docker"`
8201
+ */
8202
+ function getDockerPath() {
8203
+ return process.env["WRANGLER_DOCKER_BIN"] || "docker";
8204
+ }
8205
+ /**
8206
+ * @returns Container options suitable for building or pulling images,
8207
+ * with image tag set to well-known dev format, or undefined if
8208
+ * containers are not enabled or not configured.
8209
+ */
8210
+ function getContainerOptions(options) {
8211
+ const { containersConfig, containerBuildId, configPath } = options;
8212
+ if (!containersConfig?.length) return;
8213
+ return containersConfig.map((container) => {
8214
+ if (isDockerfile(container.image, configPath)) return {
8215
+ dockerfile: container.image,
8216
+ image_build_context: container.image_build_context ?? path$1.dirname(container.image),
8217
+ image_vars: container.image_vars,
8218
+ class_name: container.class_name,
8219
+ image_tag: getDevContainerImageName(container.class_name, containerBuildId)
8220
+ };
8221
+ else return {
8222
+ image_uri: container.image,
8223
+ class_name: container.class_name,
8224
+ image_tag: getDevContainerImageName(container.class_name, containerBuildId)
8225
+ };
8226
+ });
8227
+ }
8228
+
8229
+ //#endregion
8230
+ //#region src/debugging.ts
8231
+ const DEBUG_PATH = "/__debug";
8232
+ const DEFAULT_INSPECTOR_PORT = 9229;
8233
+ /**
8234
+ * Gets the inspector port option that should be passed to Miniflare based on the user's plugin config
8235
+ */
8236
+ async function getInputInspectorPortOption(resolvedPluginConfig, viteServer, miniflare$1) {
8237
+ if (resolvedPluginConfig.inspectorPort === void 0 || resolvedPluginConfig.inspectorPort === 0) {
8238
+ const resolvedInspectorPort = await getResolvedInspectorPort(resolvedPluginConfig, miniflare$1);
8239
+ if (resolvedInspectorPort !== null) return resolvedInspectorPort;
8240
+ }
8241
+ const inputInspectorPort = resolvedPluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
8242
+ if (resolvedPluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) viteServer.config.logger.warn(colors.dim(`Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead\n`));
8243
+ return inputInspectorPort;
8244
+ }
8245
+ /**
8246
+ * Gets the resolved inspector port provided by Miniflare
8247
+ */
8248
+ async function getResolvedInspectorPort(resolvedPluginConfig, miniflare$1) {
8249
+ if (miniflare$1 && resolvedPluginConfig.inspectorPort !== false) {
8250
+ const miniflareInspectorUrl = await miniflare$1.getInspectorURL();
8251
+ return Number.parseInt(miniflareInspectorUrl.port);
8259
8252
  }
8260
- ];
8261
- function matchAdditionalModule(source) {
8262
- for (const rule of moduleRules) for (const extension of rule.extensions) if (source.endsWith(extension)) return rule.type;
8263
8253
  return null;
8264
8254
  }
8265
- function createModuleReference(type, id) {
8266
- return `__CLOUDFLARE_MODULE__${type}__${id}__CLOUDFLARE_MODULE__`;
8255
+ function getFirstAvailablePort(start) {
8256
+ return getPort({ port: portNumbers(start, 65535) });
8267
8257
  }
8268
8258
  /**
8269
- * Plugin to support additional module types (`CompiledWasm`, `Data` and `Text`)
8259
+ * Modifies the URL printing logic to also include a URL that developers can use to open DevTools to debug their Worker(s)
8270
8260
  */
8271
- const additionalModulesPlugin = createPlugin("additional-modules", (ctx) => {
8272
- const additionalModulePaths = /* @__PURE__ */ new Set();
8273
- return {
8274
- enforce: "pre",
8275
- applyToEnvironment(environment) {
8276
- return ctx.getWorkerConfig(environment.name) !== void 0;
8277
- },
8278
- async resolveId(source, importer, options) {
8279
- const additionalModuleType = matchAdditionalModule(source);
8280
- if (!additionalModuleType) return;
8281
- const resolved = await this.resolve(cleanUrl(source), importer, options);
8282
- if (!resolved) throw new Error(`Import "${source}" not found. Does the file exist?`);
8283
- additionalModulePaths.add(resolved.id);
8284
- return {
8285
- external: true,
8286
- id: createModuleReference(additionalModuleType, resolved.id)
8287
- };
8288
- },
8289
- hotUpdate(options) {
8290
- if (additionalModulePaths.has(options.file)) {
8291
- options.server.restart();
8292
- return [];
8293
- }
8294
- },
8295
- async renderChunk(code, chunk) {
8296
- const matches = code.matchAll(additionalModuleGlobalRE);
8297
- let magicString;
8298
- for (const match of matches) {
8299
- magicString ??= new MagicString(code);
8300
- const [full, _, modulePath] = match;
8301
- assert(modulePath, `Unexpected error: module path not found in reference ${full}.`);
8302
- let source;
8303
- try {
8304
- source = await fsp.readFile(modulePath);
8305
- } catch (error) {
8306
- throw new Error(`Import "${modulePath}" not found. Does the file exist?`);
8307
- }
8308
- const referenceId = this.emitFile({
8309
- type: "asset",
8310
- name: path$2.basename(modulePath),
8311
- originalFileName: modulePath,
8312
- source
8313
- });
8314
- const emittedFileName = this.getFileName(referenceId);
8315
- const relativePath = vite.normalizePath(path$2.relative(path$2.dirname(chunk.fileName), emittedFileName));
8316
- const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
8317
- magicString.update(match.index, match.index + full.length, importPath);
8318
- }
8319
- if (magicString) return {
8320
- code: magicString.toString(),
8321
- map: this.environment.config.build.sourcemap ? magicString.generateMap({ hires: "boundary" }) : null
8322
- };
8261
+ function addDebugToVitePrintUrls(server) {
8262
+ const originalPrintUrls = server.printUrls;
8263
+ server.printUrls = () => {
8264
+ originalPrintUrls();
8265
+ const localUrl = server.resolvedUrls?.local[0];
8266
+ if (localUrl) {
8267
+ const { protocol, hostname, port } = new URL(localUrl);
8268
+ const colorDebugUrl = (url) => colors.dim(colors.yellow(url.replace(/:(\d+)\//, (_, port$1) => `:${colors.bold(port$1)}/`)));
8269
+ server.config.logger.info(` ${colors.green("➜")} ${colors.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${DEBUG_PATH}`)}`);
8323
8270
  }
8324
8271
  };
8325
- });
8272
+ }
8273
+ /**
8274
+ * Generate HTML that comprises a single script that:
8275
+ * - redirects the page to the DevTools for debugging the first available Worker
8276
+ * - opens tabs to the DevTools for all the remaining workers if any
8277
+ *
8278
+ * Note: this works based on the Miniflare inspector proxy logic (where Workers are available via
8279
+ * their names)
8280
+ */
8281
+ function getDebugPathHtml(workerNames, inspectorPort) {
8282
+ assert(workerNames.length >= 1, "no workers present to debug");
8283
+ const workerDevtoolsUrls = workerNames.map((workerName) => {
8284
+ const localhost = `localhost:${inspectorPort}/${workerName}`;
8285
+ return `https://devtools.devprod.cloudflare.dev/js_app?${new URLSearchParams({
8286
+ theme: "systemPreferred",
8287
+ debugger: "true",
8288
+ ws: localhost,
8289
+ domain: workerName
8290
+ })}`;
8291
+ });
8292
+ return `
8293
+ <script>
8294
+ const workerUrls = ${JSON.stringify(workerDevtoolsUrls)};
8295
+ const [firstUrl, ...rest] = workerUrls;
8296
+ for (const workerUrl of rest) {
8297
+ // open new tabs for the devtools of the various workers
8298
+ window.open(workerUrl);
8299
+ }
8300
+ // redirect the current tab to the devtools of the first worker
8301
+ window.location.replace(firstUrl);
8302
+ <\/script>
8303
+ `;
8304
+ }
8305
+
8306
+ //#endregion
8307
+ //#region src/dev-vars.ts
8308
+ /**
8309
+ * Gets any variables with which to augment the Worker config in preview mode.
8310
+ *
8311
+ * Calls `unstable_getVarsForDev` with the current Cloudflare environment to get local dev variables from the `.dev.vars` and `.env` files.
8312
+ */
8313
+ function getLocalDevVarsForPreview(configPath, cloudflareEnv) {
8314
+ const dotDevDotVars = unstable_getVarsForDev(configPath, void 0, {}, cloudflareEnv);
8315
+ const dotDevDotVarsEntries = Array.from(Object.entries(dotDevDotVars));
8316
+ if (dotDevDotVarsEntries.length > 0) return dotDevDotVarsEntries.map(([key, value]) => {
8317
+ return `${key} = "${value?.toString().replaceAll(`"`, `\\"`)}"\n`;
8318
+ }).join("");
8319
+ }
8320
+ /**
8321
+ * Returns `true` if the `changedFile` matches a `.dev.vars` or `.env` file.
8322
+ */
8323
+ function hasLocalDevVarsFileChanged({ configPaths, cloudflareEnv }, changedFilePath) {
8324
+ return [...configPaths].some((configPath) => {
8325
+ const configDir = path$2.dirname(configPath);
8326
+ return [
8327
+ ".dev.vars",
8328
+ ".env",
8329
+ ...cloudflareEnv ? [`.dev.vars.${cloudflareEnv}`, `.env.${cloudflareEnv}`] : []
8330
+ ].some((localDevFile) => changedFilePath === path$2.join(configDir, localDevFile));
8331
+ });
8332
+ }
8326
8333
 
8327
8334
  //#endregion
8328
8335
  //#region src/miniflare-options.ts
@@ -8526,16 +8533,6 @@ async function getDevMiniflareOptions(config) {
8526
8533
  } } } : {},
8527
8534
  __VITE_INVOKE_MODULE__: async (request$1) => {
8528
8535
  const payload = await request$1.json();
8529
- const invokePayloadData = payload.data;
8530
- assert(invokePayloadData.name === "fetchModule", `Invalid invoke event: ${invokePayloadData.name}`);
8531
- const [moduleId] = invokePayloadData.data;
8532
- if (additionalModuleRE.test(moduleId)) {
8533
- const result$1 = {
8534
- externalize: moduleId,
8535
- type: "module"
8536
- };
8537
- return Response$1.json({ result: result$1 });
8538
- }
8539
8536
  const result = await viteDevServer.environments[environmentName].hot.handleInvoke(payload);
8540
8537
  return Response$1.json(result);
8541
8538
  }
@@ -15696,15 +15693,16 @@ function validateWorkerEnvironmentOptions(resolvedPluginConfig, resolvedViteConf
15696
15693
  //#endregion
15697
15694
  //#region src/websockets.ts
15698
15695
  /**
15699
- * This function handles 'upgrade' requests to the Vite HTTP server and forwards WebSocket events between the client and Worker environments.
15696
+ * Handles 'upgrade' requests to the Vite HTTP server and forwards WebSocket events between the client and Worker environments.
15700
15697
  */
15701
- function handleWebSocket(httpServer, getFetcher) {
15698
+ function handleWebSocket(httpServer, miniflare$1, entryWorkerName) {
15702
15699
  const nodeWebSocket = new WebSocketServer({ noServer: true });
15703
15700
  httpServer.on("upgrade", async (request$1, socket, head) => {
15704
15701
  const url = new URL(request$1.url ?? "", UNKNOWN_HOST);
15705
15702
  if (request$1.headers["sec-websocket-protocol"]?.startsWith("vite")) return;
15706
15703
  const headers = createHeaders(request$1);
15707
- const workerWebSocket = (await (await getFetcher())(url, {
15704
+ if (entryWorkerName) headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
15705
+ const workerWebSocket = (await miniflare$1.dispatchFetch(url, {
15708
15706
  headers,
15709
15707
  method: request$1.method
15710
15708
  })).webSocket;
@@ -15832,17 +15830,15 @@ function cloudflare(pluginConfig = {}) {
15832
15830
  debuglog("Initializing the Vite module runners");
15833
15831
  await initRunners(ctx.resolvedPluginConfig, viteDevServer, miniflare);
15834
15832
  const entryWorkerName = entryWorkerConfig.name;
15835
- if (viteDevServer.httpServer) handleWebSocket(viteDevServer.httpServer, async () => {
15836
- assert(miniflare, `Miniflare not defined`);
15837
- return (await miniflare.getWorker(entryWorkerName)).fetch;
15838
- });
15833
+ if (viteDevServer.httpServer) handleWebSocket(viteDevServer.httpServer, miniflare, entryWorkerName);
15839
15834
  const staticRouting = entryWorkerConfig.assets?.run_worker_first === true ? { user_worker: ["/*"] } : ctx.resolvedPluginConfig.staticRouting;
15840
15835
  if (staticRouting) {
15841
15836
  const excludeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.asset_worker ?? []);
15842
15837
  const includeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.user_worker);
15843
15838
  const userWorkerHandler = createRequestHandler(async (request$1) => {
15844
15839
  assert(miniflare, `Miniflare not defined`);
15845
- return (await miniflare.getWorker(entryWorkerName)).fetch(request$1, { redirect: "manual" });
15840
+ request$1.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
15841
+ return miniflare.dispatchFetch(request$1, { redirect: "manual" });
15846
15842
  });
15847
15843
  preMiddleware = async (req, res, next) => {
15848
15844
  assert(req.url, `req.url not defined`);
@@ -15882,8 +15878,13 @@ function cloudflare(pluginConfig = {}) {
15882
15878
  }
15883
15879
  viteDevServer.middlewares.use(createRequestHandler(async (request$1, req) => {
15884
15880
  assert(miniflare, `Miniflare not defined`);
15885
- if (req[kRequestType] === "asset") return (await miniflare.getWorker(ASSET_WORKER_NAME)).fetch(request$1, { redirect: "manual" });
15886
- else return (await miniflare.getWorker(ROUTER_WORKER_NAME)).fetch(request$1, { redirect: "manual" });
15881
+ if (req[kRequestType] === "asset") {
15882
+ request$1.headers.set(CoreHeaders.ROUTE_OVERRIDE, ASSET_WORKER_NAME);
15883
+ return miniflare.dispatchFetch(request$1, { redirect: "manual" });
15884
+ } else {
15885
+ request$1.headers.set(CoreHeaders.ROUTE_OVERRIDE, ROUTER_WORKER_NAME);
15886
+ return miniflare.dispatchFetch(request$1, { redirect: "manual" });
15887
+ }
15887
15888
  }));
15888
15889
  };
15889
15890
  },
@@ -15911,10 +15912,7 @@ function cloudflare(pluginConfig = {}) {
15911
15912
  if (containerImageTagsSeen.size) cleanupContainers(dockerPath, containerImageTagsSeen);
15912
15913
  });
15913
15914
  }
15914
- handleWebSocket(vitePreviewServer.httpServer, () => {
15915
- assert(miniflare, `Miniflare not defined`);
15916
- return miniflare.dispatchFetch;
15917
- });
15915
+ handleWebSocket(vitePreviewServer.httpServer, miniflare);
15918
15916
  vitePreviewServer.middlewares.use(createRequestHandler((request$1) => {
15919
15917
  assert(miniflare, `Miniflare not defined`);
15920
15918
  return miniflare.dispatchFetch(request$1, { redirect: "manual" });