@cloudflare/vite-plugin 1.27.0 → 1.29.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.d.mts CHANGED
@@ -40,6 +40,10 @@ declare const nonApplicableWorkerConfigs: {
40
40
  * application they lose their purpose/meaning)
41
41
  */
42
42
  readonly notRelevant: readonly ["base_dir", "build", "find_additional_modules", "no_bundle", "preserve_file_names", "rules", "site", "tsconfig"];
43
+ /**
44
+ * Configs that are only supported on the entry worker and will be ignored on auxiliary workers
45
+ */
46
+ readonly notSupportedOnAuxiliary: readonly ["assets"];
43
47
  };
44
48
  //#endregion
45
49
  //#region src/plugin-config.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/utils.ts","../src/workers-configs.ts","../src/plugin-config.ts","../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;;ACgDK,KDOO,OCPP,CAAA,CAAA,CAAA,GDOoB,OCPpB,CDO4B,CCP5B,EAAA,SAA8B,CAAA;;;;AAA9B,KAjBO,YAAA,GAAe,IAiBtB,CAjB2B,eAiBG,EAAU,MAjBU,mBAiBV,CAA0B;KAAlE,8BAAA,UAAwC;KAExC,mBAAA,GACF,oCACA;KAEE,iCAAA,SACE;AC/BP,KDiCK,8BAAA,GACJ,8BClCuB,CAAA,aAAA,CAAA,CAAA,MAAA,CAAA;AAA8B;AAE5B;AAI0B;AAS1C,cDwBG,0BCtBJ,EAAA;EAGJ;AAEyB;AAMU;EAQnC,SAAA,cAAA,EAAsB;IAChB,SAAA,KAAA,EAAA;MAAR,SAAA,eAAA,EAAA,eAAA;MAES,SAAA,QAAA,EAAA,2DAAA;IACG,CAAA;IAED,SAAA,MAAA,EAAA;MACa,SAAA,eAAA,EAAA,QAAA;MAEX,SAAA,QAAA,EAAA,oDAAA;IAAR,CAAA;IAAO,SAAA,MAAA,EAAA;MAEE,SAAa,eAAA,EAAA,cAAA;MACV,SAAA,QAAA,EAAA,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ACJ,YADI;EACJ,aAAA,CAAA,EAAA,MAAA,GAAA,KAAA;EAGA,cAAA,CAAA,EAAA,OAAA;EALsB,YAAA,CAAA,EAKtB,YALsB;;AAQrB,UAAA,wBAAA,SAAiC,YAAR,CAAA;EACnB,YAAA,EAAR,OAAQ,CAAA,YAAA,CAAA,cAAA,CAAA,CAAA;EAAR,IAAA,EACR,OADQ,CACA,YADA,CAAA,MAAA,CAAA,CAAA;EACA,kBAAA,EACM,OADN,CACc,YADd,CAAA,oBAAA,CAAA,CAAA;;;;;AF1Bf;;;;ACxBA;;AAAuD,iBEevC,UAAA,CFfuC,YAAA,CAAA,EEed,YFfc,CAAA,EEeM,IAAA,CAAK,MFfX,EAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/utils.ts","../src/workers-configs.ts","../src/plugin-config.ts","../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;;ACsDK,KDCO,OCDP,CAAA,CAAA,CAAA,GDCoB,OCDpB,CDC4B,CCD5B,EAAA,SAA8B,CAAA;;;;AAA9B,KAvBO,YAAA,GAAe,IAuBtB,CAvB2B,eAuBG,EAAU,MAvBU,mBAuBV,CAA0B;KAAlE,8BAAA,UAAwC;KAExC,mBAAA,GACF,oCACA;AClCH,KDoCK,iCAAA,GCpCmB,MDqCjB,8BCrCiB,CAAA,gBAAA,CAAA;AAA8B,KDuCjD,8BAAA,GACJ,8BCtCyB,CAAA,aAAA,CAAA,CAAA,MAAA,CAAA;AAAA;AAI0B;AAKQ;AASvD,cDyBQ,0BCxBV,EAAA;EAGO;AAI8B;AAGH;EAM1B,SAAA,cAAA,EAAA;IAAR,SAAA,KAAA,EAAA;MAES,SAAA,eAAA,EAAA,eAAA;MACG,SAAA,QAAA,EAAA,2DAAA;IAED,CAAA;IACa,SAAA,MAAA,EAAA;MAEX,SAAA,eAAA,EAAA,QAAA;MAAR,SAAA,QAAA,EAAA,oDAAA;IAAO,CAAA;IAEE,SAAA,MAAa,EAAA;MACV,SAAA,eA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AA,CAAA;AAAO,UAEE,YAAA,SAAqB,iBAFvB,CAAA;EAEE,gBAAa,CAAA,EACV,qBADU,EAAA;EACV,YAAA,CAAA,EACJ,YADI;EACJ,aAAA,CAAA,EAAA,MAAA,GAAA,KAAA;EAGA,cAAA,CAAA,EAAA,OAAA;EALsB,YAAA,CAAA,EAKtB,YALsB;;AAQrB,UAAA,wBAAA,SAAiC,YAAR,CAAA;EACnB,YAAA,EAAR,OAAQ,CAAA,YAAA,CAAA,cAAA,CAAA,CAAA;EAAR,IAAA,EACR,OADQ,CACA,YADA,CAAA,MAAA,CAAA,CAAA;EACA,kBAAA,EACM,OADN,CACc,YADd,CAAA,oBAAA,CAAA,CAAA;;;;;AF1Bf;;;;ACxBA;;AAAuD,iBEevC,UAAA,CFfuC,YAAA,CAAA,EEed,YFfc,CAAA,EEeM,IAAA,CAAK,MFfX,EAAA"}
package/dist/index.mjs CHANGED
@@ -14332,7 +14332,8 @@ const nonApplicableWorkerConfigs = {
14332
14332
  "rules",
14333
14333
  "site",
14334
14334
  "tsconfig"
14335
- ]
14335
+ ],
14336
+ notSupportedOnAuxiliary: ["assets"]
14336
14337
  };
14337
14338
  /**
14338
14339
  * The non applicable configs that can be and default to `undefined`
@@ -14350,7 +14351,8 @@ const nullableNonApplicable = [
14350
14351
  function readWorkerConfig(configPath, env$1) {
14351
14352
  const nonApplicable = {
14352
14353
  replacedByVite: /* @__PURE__ */ new Set(),
14353
- notRelevant: /* @__PURE__ */ new Set()
14354
+ notRelevant: /* @__PURE__ */ new Set(),
14355
+ notSupportedOnAuxiliary: /* @__PURE__ */ new Set()
14354
14356
  };
14355
14357
  const config = wrangler.unstable_readConfig({
14356
14358
  config: configPath,
@@ -14386,7 +14388,7 @@ function getWarningForWorkersConfigs(configs) {
14386
14388
  }
14387
14389
  const lines = [];
14388
14390
  const processWorkerConfig = (workerConfig, isEntryWorker = false) => {
14389
- const nonApplicableLines = getWorkerNonApplicableWarnLines(workerConfig, ` - `);
14391
+ const nonApplicableLines = getWorkerNonApplicableWarnLines(workerConfig, ` - `, { isAuxiliary: !isEntryWorker });
14390
14392
  if (nonApplicableLines.length > 0) {
14391
14393
  lines.push(` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${nodePath.relative("", workerConfig.config.configPath)}\`)` : ""}`);
14392
14394
  nonApplicableLines.forEach((line) => lines.push(line));
@@ -14401,11 +14403,12 @@ function getWarningForWorkersConfigs(configs) {
14401
14403
  ""
14402
14404
  ].join("\n");
14403
14405
  }
14404
- function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
14406
+ function getWorkerNonApplicableWarnLines(workerConfig, linePrefix, options) {
14405
14407
  const lines = [];
14406
- const { replacedByVite, notRelevant } = workerConfig.nonApplicable;
14408
+ const { replacedByVite, notRelevant, notSupportedOnAuxiliary } = workerConfig.nonApplicable;
14407
14409
  for (const config of replacedByVite) lines.push(`${linePrefix}\`${config}\` which is replaced by Vite's \`${nonApplicableWorkerConfigs.replacedByVite[config].viteReplacement}\` (docs: ${nonApplicableWorkerConfigs.replacedByVite[config].viteDocs})`);
14408
14410
  if (notRelevant.size > 0) lines.push(`${linePrefix}${[...notRelevant].map((config) => `\`${config}\``).join(", ")} which ${notRelevant.size > 1 ? "are" : "is"} not relevant in the context of a Vite project`);
14411
+ if (options?.isAuxiliary && notSupportedOnAuxiliary.size > 0) lines.push(`${linePrefix}${[...notSupportedOnAuxiliary].map((config) => `\`${config}\``).join(", ")} which ${notSupportedOnAuxiliary.size > 1 ? "are" : "is"} not supported for auxiliary workers`);
14409
14412
  return lines;
14410
14413
  }
14411
14414
  function isReplacedByVite(configName) {
@@ -14550,7 +14553,8 @@ function resolveWorkerConfig(options) {
14550
14553
  raw = structuredClone(workerConfig);
14551
14554
  nonApplicable = {
14552
14555
  replacedByVite: /* @__PURE__ */ new Set(),
14553
- notRelevant: /* @__PURE__ */ new Set()
14556
+ notRelevant: /* @__PURE__ */ new Set(),
14557
+ notSupportedOnAuxiliary: /* @__PURE__ */ new Set()
14554
14558
  };
14555
14559
  }
14556
14560
  workerConfig = "entryWorkerConfig" in options ? customizeWorkerConfig({
@@ -14651,6 +14655,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14651
14655
  entryWorkerConfig: entryWorkerResolvedConfig.config,
14652
14656
  visitedConfigPaths: configPaths
14653
14657
  });
14658
+ if (workerResolvedConfig.config.assets) workerResolvedConfig.nonApplicable.notSupportedOnAuxiliary.add("assets");
14654
14659
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
14655
14660
  const workerEnvironmentName = auxiliaryWorker.viteEnvironment?.name ?? workerNameToEnvironmentName(workerResolvedConfig.config.topLevelName);
14656
14661
  validateAndAddEnvironmentName(workerEnvironmentName);
@@ -15792,6 +15797,34 @@ function createModuleReference(type, id) {
15792
15797
  return `__CLOUDFLARE_MODULE__${type}__${id}__CLOUDFLARE_MODULE__`;
15793
15798
  }
15794
15799
 
15800
+ //#endregion
15801
+ //#region src/plugins/cdn-cgi.ts
15802
+ /**
15803
+ * Plugin to forward `/cdn-cgi/` routes to Miniflare in development
15804
+ * We handle specified routes rather than using a catch all so that users can add their own routes using Vite's proxy functionality
15805
+ */
15806
+ const cdnCgiPlugin = createPlugin("cdn-cgi", (ctx) => {
15807
+ return {
15808
+ enforce: "pre",
15809
+ async configureServer(viteDevServer) {
15810
+ const entryWorkerConfig = ctx.entryWorkerConfig;
15811
+ if (!entryWorkerConfig) return;
15812
+ const entryWorkerName = entryWorkerConfig.name;
15813
+ const requestHandler = createRequestHandler((request$1) => {
15814
+ request$1.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
15815
+ return ctx.miniflare.dispatchFetch(request$1, { redirect: "manual" });
15816
+ });
15817
+ viteDevServer.middlewares.use(async (req, res, next) => {
15818
+ const url = req.originalUrl ?? "";
15819
+ const isLocalExplorer = url === "/cdn-cgi/explorer" || url.startsWith("/cdn-cgi/explorer/") || url.startsWith("/cdn-cgi/explorer?");
15820
+ const isTriggerHandler = url.startsWith("/cdn-cgi/handler/");
15821
+ if (isLocalExplorer || isTriggerHandler) await requestHandler(req, res, next);
15822
+ else next();
15823
+ });
15824
+ }
15825
+ };
15826
+ });
15827
+
15795
15828
  //#endregion
15796
15829
  //#region ../workers-shared/utils/configuration/constructConfiguration.ts
15797
15830
  function constructRedirects({ redirects, redirectsFile, logger }) {
@@ -21577,8 +21610,13 @@ function createHotChannel(webSocketContainer) {
21577
21610
  return {
21578
21611
  send(payload) {
21579
21612
  const webSocket = webSocketContainer.webSocket;
21580
- assert(webSocket, webSocketUndefinedError);
21581
- webSocket.send(JSON.stringify(payload));
21613
+ const message = JSON.stringify(payload);
21614
+ if (!webSocket) {
21615
+ webSocketContainer.messageBuffers ??= [];
21616
+ webSocketContainer.messageBuffers.push(message);
21617
+ return;
21618
+ }
21619
+ webSocket.send(message);
21582
21620
  },
21583
21621
  on(event, listener) {
21584
21622
  const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
@@ -21624,6 +21662,10 @@ var CloudflareDevEnvironment = class extends vite.DevEnvironment {
21624
21662
  assert(webSocket, "Failed to establish WebSocket");
21625
21663
  webSocket.accept();
21626
21664
  this.#webSocketContainer.webSocket = webSocket;
21665
+ if (this.#webSocketContainer.messageBuffers) {
21666
+ for (const bufferedMessage of this.#webSocketContainer.messageBuffers) webSocket.send(bufferedMessage);
21667
+ delete this.#webSocketContainer.messageBuffers;
21668
+ }
21627
21669
  }
21628
21670
  async fetchWorkerExportTypes(miniflare, workerConfig) {
21629
21671
  await this.depsOptimizer?.init();
@@ -22254,6 +22296,229 @@ const OpenAPI = {
22254
22296
  LOGGER: void 0
22255
22297
  };
22256
22298
 
22299
+ //#endregion
22300
+ //#region ../containers-shared/src/client/core/request.ts
22301
+ /* istanbul ignore file */
22302
+ const isDefined = (value) => {
22303
+ return value !== void 0 && value !== null;
22304
+ };
22305
+ const isString = (value) => {
22306
+ return typeof value === "string";
22307
+ };
22308
+ const isStringWithValue = (value) => {
22309
+ return isString(value) && value !== "";
22310
+ };
22311
+ const isBlob = (value) => {
22312
+ return typeof value === "object" && typeof value.type === "string" && typeof value.stream === "function" && typeof value.arrayBuffer === "function" && typeof value.constructor === "function" && typeof value.constructor.name === "string" && /^(Blob|File)$/.test(value.constructor.name) && /^(Blob|File)$/.test(value[Symbol.toStringTag]);
22313
+ };
22314
+ const base64 = (str) => {
22315
+ try {
22316
+ return btoa(str);
22317
+ } catch (err) {
22318
+ return Buffer.from(str).toString("base64");
22319
+ }
22320
+ };
22321
+ const getQueryString = (params) => {
22322
+ const qs = [];
22323
+ const append = (key, value) => {
22324
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
22325
+ };
22326
+ const process$2 = (key, value) => {
22327
+ if (isDefined(value)) if (Array.isArray(value)) value.forEach((v) => {
22328
+ process$2(key, v);
22329
+ });
22330
+ else if (typeof value === "object") Object.entries(value).forEach(([k, v]) => {
22331
+ process$2(`${key}[${k}]`, v);
22332
+ });
22333
+ else append(key, value);
22334
+ };
22335
+ Object.entries(params).forEach(([key, value]) => {
22336
+ process$2(key, value);
22337
+ });
22338
+ if (qs.length > 0) return `?${qs.join("&")}`;
22339
+ return "";
22340
+ };
22341
+ const getUrl = (config, options) => {
22342
+ const encoder = config.ENCODE_PATH || encodeURI;
22343
+ const path$1 = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring, group) => {
22344
+ if (options.path?.hasOwnProperty(group)) return encoder(String(options.path[group]));
22345
+ return substring;
22346
+ });
22347
+ const url = `${config.BASE}${path$1}`;
22348
+ if (options.query) return `${url}${getQueryString(options.query)}`;
22349
+ return url;
22350
+ };
22351
+ const getFormData = (options) => {
22352
+ if (options.formData) {
22353
+ const formData = new FormData();
22354
+ const process$2 = async (key, value) => {
22355
+ if (isString(value)) formData.append(key, value);
22356
+ else formData.append(key, JSON.stringify(value));
22357
+ };
22358
+ Object.entries(options.formData).filter(([_, value]) => isDefined(value)).forEach(([key, value]) => {
22359
+ if (Array.isArray(value)) value.forEach((v) => process$2(key, v));
22360
+ else process$2(key, value);
22361
+ });
22362
+ return formData;
22363
+ }
22364
+ };
22365
+ const resolve$1 = async (options, resolver) => {
22366
+ if (typeof resolver === "function") return resolver(options);
22367
+ return resolver;
22368
+ };
22369
+ const getHeaders = async (config, options) => {
22370
+ const token = await resolve$1(options, config.TOKEN);
22371
+ const username = await resolve$1(options, config.USERNAME);
22372
+ const password = await resolve$1(options, config.PASSWORD);
22373
+ const additionalHeaders = await resolve$1(options, config.HEADERS);
22374
+ const headers = Object.entries({
22375
+ Accept: "application/json",
22376
+ ...additionalHeaders,
22377
+ ...options.headers
22378
+ }).filter(([_, value]) => isDefined(value)).reduce((headers$1, [key, value]) => ({
22379
+ ...headers$1,
22380
+ [key]: String(value)
22381
+ }), {});
22382
+ if (isStringWithValue(token)) headers["Authorization"] = `Bearer ${token}`;
22383
+ if (isStringWithValue(username) && isStringWithValue(password)) headers["Authorization"] = `Basic ${base64(`${username}:${password}`)}`;
22384
+ if (options.body) if (options.mediaType) headers["Content-Type"] = options.mediaType;
22385
+ else if (isBlob(options.body)) headers["Content-Type"] = options.body.type || "application/octet-stream";
22386
+ else if (isString(options.body)) headers["Content-Type"] = "text/plain";
22387
+ else headers["Content-Type"] = "application/json";
22388
+ return new Headers(headers);
22389
+ };
22390
+ const getRequestBody = (options) => {
22391
+ if (options.body !== void 0) if (options.mediaType?.includes("/json")) return JSON.stringify(options.body);
22392
+ else if (isString(options.body) || isBlob(options.body)) return options.body;
22393
+ else return JSON.stringify(options.body);
22394
+ };
22395
+ const isResponseSchemaV4 = (config, _options) => {
22396
+ return config.BASE.endsWith("/containers");
22397
+ };
22398
+ const parseResponseSchemaV4 = (url, response, responseHeader, responseBody) => {
22399
+ const fetchResult = typeof responseBody === "object" ? responseBody : JSON.parse(responseBody);
22400
+ const ok = response.ok && fetchResult.success;
22401
+ let result;
22402
+ if (ok) if (fetchResult.result !== void 0) result = fetchResult.result;
22403
+ else result = {};
22404
+ else result = { error: fetchResult.errors?.[0]?.message };
22405
+ return {
22406
+ url,
22407
+ ok,
22408
+ status: response.status,
22409
+ statusText: response.statusText,
22410
+ body: responseHeader ?? result
22411
+ };
22412
+ };
22413
+ const sendRequest = async (config, options, url, body, formData, headers, onCancel) => {
22414
+ const controller = new AbortController();
22415
+ const request$1 = {
22416
+ headers,
22417
+ body: body ?? formData,
22418
+ method: options.method,
22419
+ signal: controller.signal
22420
+ };
22421
+ if (config.WITH_CREDENTIALS) request$1.credentials = config.CREDENTIALS;
22422
+ onCancel(() => controller.abort());
22423
+ return await fetch(url, request$1);
22424
+ };
22425
+ const getResponseHeader = (response, responseHeader) => {
22426
+ if (responseHeader) {
22427
+ const content = response.headers.get(responseHeader);
22428
+ if (isString(content)) return content;
22429
+ }
22430
+ };
22431
+ const getResponseBody = async (response) => {
22432
+ if (response.status !== 204) try {
22433
+ const contentType = response.headers.get("Content-Type");
22434
+ if (contentType) if (["application/json", "application/problem+json"].some((type) => contentType.toLowerCase().startsWith(type))) return await response.json();
22435
+ else return await response.text();
22436
+ } catch (error) {
22437
+ console.error(error);
22438
+ }
22439
+ };
22440
+ const catchErrorCodes = (options, result) => {
22441
+ const error = {
22442
+ 400: "Bad Request",
22443
+ 401: "Unauthorized",
22444
+ 403: "Forbidden",
22445
+ 404: "Not Found",
22446
+ 500: "Internal Server Error",
22447
+ 502: "Bad Gateway",
22448
+ 503: "Service Unavailable",
22449
+ ...options.errors
22450
+ }[result.status];
22451
+ if (error) throw new ApiError(options, result, error);
22452
+ if (!result.ok) throw new ApiError(options, result, "Generic Error");
22453
+ };
22454
+ /**
22455
+ * Shared HTTP execution: builds URL, headers, body, sends the request,
22456
+ * and returns the raw response components for further processing.
22457
+ * Returns null if the request was cancelled before sending.
22458
+ */
22459
+ const executeRequest = async (config, options, onCancel) => {
22460
+ const url = getUrl(config, options);
22461
+ const formData = getFormData(options);
22462
+ const body = getRequestBody(options);
22463
+ const headers = await getHeaders(config, options);
22464
+ debugLogRequest(config, url, headers, formData ?? body ?? {});
22465
+ if (onCancel.isCancelled) return null;
22466
+ const response = await sendRequest(config, options, url, body, formData, headers, onCancel);
22467
+ return {
22468
+ url,
22469
+ response,
22470
+ responseBody: await getResponseBody(response),
22471
+ responseHeader: getResponseHeader(response, options.responseHeader)
22472
+ };
22473
+ };
22474
+ /**
22475
+ * Build an ApiResult from the raw response, handling V4 schema parsing.
22476
+ */
22477
+ const buildApiResult = (config, options, req) => {
22478
+ if (isResponseSchemaV4(config, options)) return parseResponseSchemaV4(req.url, req.response, req.responseHeader, req.responseBody);
22479
+ return {
22480
+ url: req.url,
22481
+ ok: req.response.ok,
22482
+ status: req.response.status,
22483
+ statusText: req.response.statusText,
22484
+ body: req.responseHeader ?? req.responseBody
22485
+ };
22486
+ };
22487
+ /**
22488
+ * Request method
22489
+ * @param config The OpenAPI configuration object
22490
+ * @param options The request options from the service
22491
+ * @returns CancelablePromise<T>
22492
+ * @throws ApiError
22493
+ */
22494
+ const request = (config, options) => {
22495
+ return new CancelablePromise(async (resolve$2, reject, onCancel) => {
22496
+ try {
22497
+ const req = await executeRequest(config, options, onCancel);
22498
+ if (!req) return;
22499
+ const result = buildApiResult(config, options, req);
22500
+ debugLogResponse(config, result);
22501
+ catchErrorCodes(options, result);
22502
+ resolve$2(result.body);
22503
+ } catch (error) {
22504
+ reject(error);
22505
+ }
22506
+ });
22507
+ };
22508
+ const debugLogRequest = async (config, url, headers, body) => {
22509
+ config.LOGGER?.debug(`-- START CF API REQUEST: ${url}`);
22510
+ const logHeaders = new Headers(headers);
22511
+ logHeaders.delete("Authorization");
22512
+ config.LOGGER?.debugWithSanitization("HEADERS:", JSON.stringify(logHeaders, null, 2));
22513
+ config.LOGGER?.debugWithSanitization("BODY:", JSON.stringify(body instanceof FormData ? await new Response(body).text() : body, null, 2));
22514
+ config.LOGGER?.debug("-- END CF API REQUEST");
22515
+ };
22516
+ const debugLogResponse = (config, response) => {
22517
+ config.LOGGER?.debug("-- START CF API RESPONSE:", response.statusText, response.status);
22518
+ config.LOGGER?.debugWithSanitization("RESPONSE:", response.body);
22519
+ config.LOGGER?.debug("-- END CF API RESPONSE");
22520
+ };
22521
+
22257
22522
  //#endregion
22258
22523
  //#region ../containers-shared/src/client/models/ApplicationRollout.ts
22259
22524
  let ApplicationRollout;
@@ -22480,212 +22745,6 @@ let UpdateApplicationRolloutRequest;
22480
22745
  }({});
22481
22746
  })(UpdateApplicationRolloutRequest || (UpdateApplicationRolloutRequest = {}));
22482
22747
 
22483
- //#endregion
22484
- //#region ../containers-shared/src/client/core/request.ts
22485
- /* istanbul ignore file */
22486
- const isDefined = (value) => {
22487
- return value !== void 0 && value !== null;
22488
- };
22489
- const isString = (value) => {
22490
- return typeof value === "string";
22491
- };
22492
- const isStringWithValue = (value) => {
22493
- return isString(value) && value !== "";
22494
- };
22495
- const isBlob = (value) => {
22496
- return typeof value === "object" && typeof value.type === "string" && typeof value.stream === "function" && typeof value.arrayBuffer === "function" && typeof value.constructor === "function" && typeof value.constructor.name === "string" && /^(Blob|File)$/.test(value.constructor.name) && /^(Blob|File)$/.test(value[Symbol.toStringTag]);
22497
- };
22498
- const base64 = (str) => {
22499
- try {
22500
- return btoa(str);
22501
- } catch (err) {
22502
- return Buffer.from(str).toString("base64");
22503
- }
22504
- };
22505
- const getQueryString = (params) => {
22506
- const qs = [];
22507
- const append = (key, value) => {
22508
- qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
22509
- };
22510
- const process$2 = (key, value) => {
22511
- if (isDefined(value)) if (Array.isArray(value)) value.forEach((v) => {
22512
- process$2(key, v);
22513
- });
22514
- else if (typeof value === "object") Object.entries(value).forEach(([k, v]) => {
22515
- process$2(`${key}[${k}]`, v);
22516
- });
22517
- else append(key, value);
22518
- };
22519
- Object.entries(params).forEach(([key, value]) => {
22520
- process$2(key, value);
22521
- });
22522
- if (qs.length > 0) return `?${qs.join("&")}`;
22523
- return "";
22524
- };
22525
- const getUrl = (config, options) => {
22526
- const encoder = config.ENCODE_PATH || encodeURI;
22527
- const path$1 = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring, group) => {
22528
- if (options.path?.hasOwnProperty(group)) return encoder(String(options.path[group]));
22529
- return substring;
22530
- });
22531
- const url = `${config.BASE}${path$1}`;
22532
- if (options.query) return `${url}${getQueryString(options.query)}`;
22533
- return url;
22534
- };
22535
- const getFormData = (options) => {
22536
- if (options.formData) {
22537
- const formData = new FormData();
22538
- const process$2 = async (key, value) => {
22539
- if (isString(value)) formData.append(key, value);
22540
- else formData.append(key, JSON.stringify(value));
22541
- };
22542
- Object.entries(options.formData).filter(([_, value]) => isDefined(value)).forEach(([key, value]) => {
22543
- if (Array.isArray(value)) value.forEach((v) => process$2(key, v));
22544
- else process$2(key, value);
22545
- });
22546
- return formData;
22547
- }
22548
- };
22549
- const resolve$1 = async (options, resolver) => {
22550
- if (typeof resolver === "function") return resolver(options);
22551
- return resolver;
22552
- };
22553
- const getHeaders = async (config, options) => {
22554
- const token = await resolve$1(options, config.TOKEN);
22555
- const username = await resolve$1(options, config.USERNAME);
22556
- const password = await resolve$1(options, config.PASSWORD);
22557
- const additionalHeaders = await resolve$1(options, config.HEADERS);
22558
- const headers = Object.entries({
22559
- Accept: "application/json",
22560
- ...additionalHeaders,
22561
- ...options.headers
22562
- }).filter(([_, value]) => isDefined(value)).reduce((headers$1, [key, value]) => ({
22563
- ...headers$1,
22564
- [key]: String(value)
22565
- }), {});
22566
- if (isStringWithValue(token)) headers["Authorization"] = `Bearer ${token}`;
22567
- if (isStringWithValue(username) && isStringWithValue(password)) headers["Authorization"] = `Basic ${base64(`${username}:${password}`)}`;
22568
- if (options.body) if (options.mediaType) headers["Content-Type"] = options.mediaType;
22569
- else if (isBlob(options.body)) headers["Content-Type"] = options.body.type || "application/octet-stream";
22570
- else if (isString(options.body)) headers["Content-Type"] = "text/plain";
22571
- else headers["Content-Type"] = "application/json";
22572
- return new Headers(headers);
22573
- };
22574
- const getRequestBody = (options) => {
22575
- if (options.body !== void 0) if (options.mediaType?.includes("/json")) return JSON.stringify(options.body);
22576
- else if (isString(options.body) || isBlob(options.body)) return options.body;
22577
- else return JSON.stringify(options.body);
22578
- };
22579
- const isResponseSchemaV4 = (config, _options) => {
22580
- return config.BASE.endsWith("/containers");
22581
- };
22582
- const parseResponseSchemaV4 = (url, response, responseHeader, responseBody) => {
22583
- const fetchResult = typeof responseBody === "object" ? responseBody : JSON.parse(responseBody);
22584
- const ok = response.ok && fetchResult.success;
22585
- let result;
22586
- if (ok) if (fetchResult.result !== void 0) result = fetchResult.result;
22587
- else result = {};
22588
- else result = { error: fetchResult.errors?.[0]?.message };
22589
- return {
22590
- url,
22591
- ok,
22592
- status: response.status,
22593
- statusText: response.statusText,
22594
- body: responseHeader ?? result
22595
- };
22596
- };
22597
- const sendRequest = async (config, options, url, body, formData, headers, onCancel) => {
22598
- const controller = new AbortController();
22599
- const request$1 = {
22600
- headers,
22601
- body: body ?? formData,
22602
- method: options.method,
22603
- signal: controller.signal
22604
- };
22605
- if (config.WITH_CREDENTIALS) request$1.credentials = config.CREDENTIALS;
22606
- onCancel(() => controller.abort());
22607
- return await fetch(url, request$1);
22608
- };
22609
- const getResponseHeader = (response, responseHeader) => {
22610
- if (responseHeader) {
22611
- const content = response.headers.get(responseHeader);
22612
- if (isString(content)) return content;
22613
- }
22614
- };
22615
- const getResponseBody = async (response) => {
22616
- if (response.status !== 204) try {
22617
- const contentType = response.headers.get("Content-Type");
22618
- if (contentType) if (["application/json", "application/problem+json"].some((type) => contentType.toLowerCase().startsWith(type))) return await response.json();
22619
- else return await response.text();
22620
- } catch (error) {
22621
- console.error(error);
22622
- }
22623
- };
22624
- const catchErrorCodes = (options, result) => {
22625
- const error = {
22626
- 400: "Bad Request",
22627
- 401: "Unauthorized",
22628
- 403: "Forbidden",
22629
- 404: "Not Found",
22630
- 500: "Internal Server Error",
22631
- 502: "Bad Gateway",
22632
- 503: "Service Unavailable",
22633
- ...options.errors
22634
- }[result.status];
22635
- if (error) throw new ApiError(options, result, error);
22636
- if (!result.ok) throw new ApiError(options, result, "Generic Error");
22637
- };
22638
- /**
22639
- * Request method
22640
- * @param config The OpenAPI configuration object
22641
- * @param options The request options from the service
22642
- * @returns CancelablePromise<T>
22643
- * @throws ApiError
22644
- */
22645
- const request = (config, options) => {
22646
- return new CancelablePromise(async (resolve$2, reject, onCancel) => {
22647
- try {
22648
- const url = getUrl(config, options);
22649
- const formData = getFormData(options);
22650
- const body = getRequestBody(options);
22651
- const headers = await getHeaders(config, options);
22652
- debugLogRequest(config, url, headers, formData ?? body ?? {});
22653
- if (!onCancel.isCancelled) {
22654
- const response = await sendRequest(config, options, url, body, formData, headers, onCancel);
22655
- const responseBody = await getResponseBody(response);
22656
- const responseHeader = getResponseHeader(response, options.responseHeader);
22657
- let result;
22658
- if (isResponseSchemaV4(config, options)) result = parseResponseSchemaV4(url, response, responseHeader, responseBody);
22659
- else result = {
22660
- url,
22661
- ok: response.ok,
22662
- status: response.status,
22663
- statusText: response.statusText,
22664
- body: responseHeader ?? responseBody
22665
- };
22666
- debugLogResponse(config, result);
22667
- catchErrorCodes(options, result);
22668
- resolve$2(result.body);
22669
- }
22670
- } catch (error) {
22671
- reject(error);
22672
- }
22673
- });
22674
- };
22675
- const debugLogRequest = async (config, url, headers, body) => {
22676
- config.LOGGER?.debug(`-- START CF API REQUEST: ${url}`);
22677
- const logHeaders = new Headers(headers);
22678
- logHeaders.delete("Authorization");
22679
- config.LOGGER?.debugWithSanitization("HEADERS:", JSON.stringify(logHeaders, null, 2));
22680
- config.LOGGER?.debugWithSanitization("BODY:", JSON.stringify(body instanceof FormData ? await new Response(body).text() : body, null, 2));
22681
- config.LOGGER?.debug("-- END CF API REQUEST");
22682
- };
22683
- const debugLogResponse = (config, response) => {
22684
- config.LOGGER?.debug("-- START CF API RESPONSE:", response.statusText, response.status);
22685
- config.LOGGER?.debugWithSanitization("RESPONSE:", response.body);
22686
- config.LOGGER?.debug("-- END CF API RESPONSE");
22687
- };
22688
-
22689
22748
  //#endregion
22690
22749
  //#region ../containers-shared/src/client/services/ImageRegistriesService.ts
22691
22750
  /* istanbul ignore file */
@@ -23172,7 +23231,7 @@ async function cleanupDuplicateImageTags(dockerPath, imageTag) {
23172
23231
 
23173
23232
  //#endregion
23174
23233
  //#region ../containers-shared/src/images.ts
23175
- const DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE = "cloudflare/proxy-everything:3f5e832@sha256:816255f5b6ebdc2cdcddb578d803121e7ee9cfe178442da07725d75a66cdcf37";
23234
+ const DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE = "cloudflare/proxy-everything:233db0f@sha256:f159d9e1b0f28bc01bd106f38d62479c018d050e3f95b365c5f9b5f83f60df82";
23176
23235
  function getEgressInterceptorImage() {
23177
23236
  return process.env.MINIFLARE_CONTAINER_EGRESS_IMAGE ?? DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE;
23178
23237
  }
@@ -26260,8 +26319,12 @@ function handleWebSocket(httpServer, miniflare, entryWorkerName) {
26260
26319
  const nodeWebSocket = new WebSocketServer({ noServer: true });
26261
26320
  httpServer.on("upgrade", async (request$1, socket, head) => {
26262
26321
  socket.on("error", () => socket.destroy());
26263
- const url = new URL(request$1.url ?? "", UNKNOWN_HOST);
26264
- if (request$1.headers["sec-websocket-protocol"]?.startsWith("vite")) return;
26322
+ const rawHost = request$1.headers.host ?? UNKNOWN_HOST;
26323
+ const base = /^https?:\/\//i.test(rawHost) ? rawHost : `http://${rawHost}`;
26324
+ const url = new URL(request$1.url ?? "", base);
26325
+ const isViteRequest = request$1.headers["sec-websocket-protocol"]?.startsWith("vite");
26326
+ const isSandboxRequest = hasSandboxOrigin(url.origin);
26327
+ if (isViteRequest && !isSandboxRequest) return;
26265
26328
  const headers = createHeaders(request$1);
26266
26329
  if (entryWorkerName) headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
26267
26330
  const workerWebSocket = (await miniflare.dispatchFetch(url, {
@@ -26278,6 +26341,20 @@ function handleWebSocket(httpServer, miniflare, entryWorkerName) {
26278
26341
  });
26279
26342
  });
26280
26343
  }
26344
+ /**
26345
+ * Matches the origin of a Sandbox SDK preview URL.
26346
+ * See: https://developers.cloudflare.com/sandbox/concepts/preview-urls/
26347
+ *
26348
+ * Pattern: https?://<port(4+ digits)>-<id(no dots)>-<token>.localhost
26349
+ *
26350
+ * IMPORTANT: The token segment is [a-z0-9_]+ (no hyphens) to prevent ReDoS — two adjacent
26351
+ * [^.]+ groups separated by - cause quadratic backtracking on hyphen-heavy input. Tokens are
26352
+ * documented as letters/digits/underscores only.
26353
+ */
26354
+ const SANDBOX_ORIGIN_REGEXP = /^https?:\/\/\d{4,}-[^.]+-[a-z0-9_]+\.localhost(:\d+)?$/i;
26355
+ function hasSandboxOrigin(origin) {
26356
+ return SANDBOX_ORIGIN_REGEXP.test(origin);
26357
+ }
26281
26358
 
26282
26359
  //#endregion
26283
26360
  //#region src/plugins/dev.ts
@@ -26690,27 +26767,6 @@ function addBindingsShortcut(server, ctx) {
26690
26767
  server.bindCLIShortcuts({ customShortcuts: [printBindingsShortcut] });
26691
26768
  }
26692
26769
 
26693
- //#endregion
26694
- //#region src/plugins/trigger-handlers.ts
26695
- /**
26696
- * Plugin to forward `/cdn-cgi/handler/*` routes to trigger handlers in development
26697
- */
26698
- const triggerHandlersPlugin = createPlugin("trigger-handlers", (ctx) => {
26699
- return {
26700
- enforce: "pre",
26701
- async configureServer(viteDevServer) {
26702
- const entryWorkerConfig = ctx.entryWorkerConfig;
26703
- if (!entryWorkerConfig) return;
26704
- const entryWorkerName = entryWorkerConfig.name;
26705
- const requestHandler = createRequestHandler((request$1) => {
26706
- request$1.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
26707
- return ctx.miniflare.dispatchFetch(request$1, { redirect: "manual" });
26708
- });
26709
- viteDevServer.middlewares.use("/cdn-cgi/handler/", requestHandler);
26710
- }
26711
- };
26712
- });
26713
-
26714
26770
  //#endregion
26715
26771
  //#region src/plugins/wasm.ts
26716
26772
  const wasmInitRE = /\.wasm\?init$/;
@@ -26782,7 +26838,7 @@ function cloudflare(pluginConfig = {}) {
26782
26838
  previewPlugin(ctx),
26783
26839
  shortcutsPlugin(ctx),
26784
26840
  debugPlugin(ctx),
26785
- triggerHandlersPlugin(ctx),
26841
+ cdnCgiPlugin(ctx),
26786
26842
  virtualModulesPlugin(ctx),
26787
26843
  virtualClientFallbackPlugin(ctx),
26788
26844
  outputConfigPlugin(ctx),