@cloudflare/vite-plugin 1.55.0 → 1.57.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
@@ -16,7 +16,7 @@ import net from "node:net";
16
16
  import http from "node:http";
17
17
  import events, { EventEmitter } from "node:events";
18
18
  import { Buffer as Buffer$1 } from "node:buffer";
19
- import crypto$1, { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID, webcrypto } from "node:crypto";
19
+ import crypto2, { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID, webcrypto } from "node:crypto";
20
20
  import { AsyncLocalStorage } from "node:async_hooks";
21
21
  import * as fsp from "node:fs/promises";
22
22
  import fs, { constants as constants$1 } from "node:fs/promises";
@@ -136,7 +136,7 @@ function createFatalError$1(message, isJson, options) {
136
136
  __name$6(createFatalError$1, "createFatalError");
137
137
 
138
138
  //#endregion
139
- //#region ../workers-utils/dist/chunk-JGKSDUFK.mjs
139
+ //#region ../workers-utils/dist/chunk-JTB7VJSC.mjs
140
140
  function hasKnownExportType(entry) {
141
141
  const type = entry?.type;
142
142
  return type === "durable-object" || type === "worker";
@@ -163,7 +163,6 @@ function hasDurableObjectExports(exports$1) {
163
163
  return Object.keys(getDurableObjectExports(exports$1)).length > 0;
164
164
  }
165
165
  __name$6(hasDurableObjectExports, "hasDurableObjectExports");
166
- var CONTAINER_IMAGES_BINDING = "EXPERIMENTAL_CLOUDFLARE_CONTAINER_IMAGES";
167
166
  function isDurableObjectContainerApp(container) {
168
167
  return container.scheduling_policy === "durable_object";
169
168
  }
@@ -2614,8 +2613,8 @@ function formatConfigSnippet(snippet, configPath, formatted = true) {
2614
2613
  __name$6(formatConfigSnippet, "formatConfigSnippet");
2615
2614
 
2616
2615
  //#endregion
2617
- //#region ../workers-utils/dist/chunk-2OPNWQJ5.mjs
2618
- var DEFAULT_COMPAT_DATE = "2026-09-17";
2616
+ //#region ../workers-utils/dist/chunk-4PNP2TCS.mjs
2617
+ var DEFAULT_COMPAT_DATE = "2026-09-21";
2619
2618
  function assertNever(_value) {}
2620
2619
  __name$6(assertNever, "assertNever");
2621
2620
  function mapWorkerMetadataBindings(bindings) {
@@ -15573,7 +15572,7 @@ var require_snapshot_utils = /* @__PURE__ */ __commonJS$2({ "../../node_modules/
15573
15572
  match: new Set(matchHeaders$1.map((header) => caseSensitive ? header : header.toLowerCase()))
15574
15573
  };
15575
15574
  }
15576
- const crypto$4 = runtimeFeatures$5.has("crypto") ? __require$2("node:crypto") : null;
15575
+ const crypto$3 = runtimeFeatures$5.has("crypto") ? __require$2("node:crypto") : null;
15577
15576
  /**
15578
15577
  * @callback HashIdFunction
15579
15578
  * @param {string} value - The value to hash
@@ -15583,7 +15582,7 @@ var require_snapshot_utils = /* @__PURE__ */ __commonJS$2({ "../../node_modules/
15583
15582
  * Generates a hash for a given value
15584
15583
  * @type {HashIdFunction}
15585
15584
  */
15586
- const hashId$1 = crypto$4?.hash ? (value) => crypto$4.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
15585
+ const hashId$1 = crypto$3?.hash ? (value) => crypto$3.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
15587
15586
  /**
15588
15587
  * @typedef {(url: string) => boolean} IsUrlExcluded Checks if a URL matches any of the exclude patterns
15589
15588
  */
@@ -21153,10 +21152,10 @@ var require_subresource_integrity = /* @__PURE__ */ __commonJS$2({ "../../node_m
21153
21152
  ["sha512", 2]
21154
21153
  ]);
21155
21154
  /** @type {import('node:crypto')} */
21156
- let crypto$3;
21155
+ let crypto$2;
21157
21156
  if (runtimeFeatures$3.has("crypto")) {
21158
- crypto$3 = __require$2("node:crypto");
21159
- const cryptoHashes = crypto$3.getHashes();
21157
+ crypto$2 = __require$2("node:crypto");
21158
+ const cryptoHashes = crypto$2.getHashes();
21160
21159
  if (cryptoHashes.length === 0) validSRIHashAlgorithmTokenSet.clear();
21161
21160
  for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) if (cryptoHashes.includes(algorithm) === false) validSRIHashAlgorithmTokenSet.delete(algorithm);
21162
21161
  } else validSRIHashAlgorithmTokenSet.clear();
@@ -21254,7 +21253,7 @@ var require_subresource_integrity = /* @__PURE__ */ __commonJS$2({ "../../node_m
21254
21253
  * @returns {string}
21255
21254
  */
21256
21255
  const applyAlgorithmToBytes = (algorithm, bytes) => {
21257
- return crypto$3.hash(algorithm, bytes, "base64");
21256
+ return crypto$2.hash(algorithm, bytes, "base64");
21258
21257
  };
21259
21258
  /**
21260
21259
  * Compares two base64 strings, allowing for base64url
@@ -23838,7 +23837,7 @@ var require_connection = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnp
23838
23837
  const { WebsocketFrameSend: WebsocketFrameSend$4 } = require_frame();
23839
23838
  const assert$3 = __require$2("node:assert");
23840
23839
  const { runtimeFeatures } = require_runtime_features();
23841
- const crypto$2 = runtimeFeatures.has("crypto") ? __require$2("node:crypto") : null;
23840
+ const crypto$1 = runtimeFeatures.has("crypto") ? __require$2("node:crypto") : null;
23842
23841
  let warningEmitted = false;
23843
23842
  /**
23844
23843
  * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
@@ -23862,7 +23861,7 @@ var require_connection = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnp
23862
23861
  useURLCredentials: true
23863
23862
  });
23864
23863
  if (options.headers) request$2.headersList = getHeadersList(new Headers$2(options.headers));
23865
- const keyValue = crypto$2.randomBytes(16).toString("base64");
23864
+ const keyValue = crypto$1.randomBytes(16).toString("base64");
23866
23865
  request$2.headersList.append("sec-websocket-key", keyValue, true);
23867
23866
  request$2.headersList.append("sec-websocket-version", "13", true);
23868
23867
  for (const protocol of protocols) request$2.headersList.append("sec-websocket-protocol", protocol, true);
@@ -23898,7 +23897,7 @@ var require_connection = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnp
23898
23897
  failWebsocketConnection$3(handler, 1002, "Server did not set Connection header to \"upgrade\".");
23899
23898
  return;
23900
23899
  }
23901
- if (response.headersList.get("Sec-WebSocket-Accept") !== crypto$2.hash("sha1", keyValue + uid, "base64")) {
23900
+ if (response.headersList.get("Sec-WebSocket-Accept") !== crypto$1.hash("sha1", keyValue + uid, "base64")) {
23902
23901
  failWebsocketConnection$3(handler, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
23903
23902
  return;
23904
23903
  }
@@ -26328,11 +26327,11 @@ var require_ci_info$1 = __commonJS$1({ "../../node_modules/.pnpm/ci-info@4.4.0/n
26328
26327
  var require_command_exists$2 = __commonJS$1({ "../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/lib/command-exists.js"(exports$1, module$1) {
26329
26328
  var exec$3 = __require$1("child_process").exec;
26330
26329
  var execSync$2 = __require$1("child_process").execSync;
26331
- var fs3 = __require$1("fs");
26332
- var path5 = __require$1("path");
26333
- var access$1 = fs3.access;
26334
- var accessSync2 = fs3.accessSync;
26335
- var constants2 = fs3.constants || fs3;
26330
+ var fs4 = __require$1("fs");
26331
+ var path6 = __require$1("path");
26332
+ var access$1 = fs4.access;
26333
+ var accessSync2 = fs4.accessSync;
26334
+ var constants2 = fs4.constants || fs4;
26336
26335
  var isUsingWindows$1 = process.platform == "win32";
26337
26336
  var fileNotExists$1 = /* @__PURE__ */ __name$6(function(commandName, callback$1) {
26338
26337
  access$1(commandName, constants2.F_OK, function(err) {
@@ -26406,8 +26405,8 @@ var require_command_exists$2 = __commonJS$1({ "../../node_modules/.pnpm/command-
26406
26405
  }, "cleanInput");
26407
26406
  if (isUsingWindows$1) cleanInput$1 = /* @__PURE__ */ __name$6(function(s) {
26408
26407
  if (/[\\]/.test(s)) {
26409
- var dirname4 = "\"" + path5.dirname(s) + "\"";
26410
- var basename2 = "\"" + path5.basename(s) + "\"";
26408
+ var dirname4 = "\"" + path6.dirname(s) + "\"";
26409
+ var basename2 = "\"" + path6.basename(s) + "\"";
26411
26410
  return dirname4 + ":" + basename2;
26412
26411
  }
26413
26412
  return "\"" + s + "\"";
@@ -26628,9 +26627,9 @@ var require_strip_json_comments = __commonJS$1({ "../../node_modules/.pnpm/strip
26628
26627
  };
26629
26628
  } });
26630
26629
  var require_utils$1 = __commonJS$1({ "../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/lib/utils.js"(exports$1) {
26631
- var fs3 = __require$1("fs");
26630
+ var fs4 = __require$1("fs");
26632
26631
  var ini = require_ini();
26633
- var path5 = __require$1("path");
26632
+ var path6 = __require$1("path");
26634
26633
  var stripJsonComments = require_strip_json_comments();
26635
26634
  var parse3$1 = exports$1.parse = function(content) {
26636
26635
  if (/^\s*{/.test(content)) return JSON.parse(stripJsonComments(content));
@@ -26641,9 +26640,9 @@ var require_utils$1 = __commonJS$1({ "../../node_modules/.pnpm/rc@1.2.8/node_mod
26641
26640
  return arg != null;
26642
26641
  });
26643
26642
  for (var i$1 in args) if ("string" !== typeof args[i$1]) return;
26644
- var file3 = path5.join.apply(null, args);
26643
+ var file3 = path6.join.apply(null, args);
26645
26644
  try {
26646
- return fs3.readFileSync(file3, "utf-8");
26645
+ return fs4.readFileSync(file3, "utf-8");
26647
26646
  } catch (err) {
26648
26647
  return;
26649
26648
  }
@@ -26671,14 +26670,14 @@ var require_utils$1 = __commonJS$1({ "../../node_modules/.pnpm/rc@1.2.8/node_mod
26671
26670
  return obj;
26672
26671
  };
26673
26672
  exports$1.find = function() {
26674
- var rel = path5.join.apply(null, [].slice.call(arguments));
26673
+ var rel = path6.join.apply(null, [].slice.call(arguments));
26675
26674
  function find2(start, rel2) {
26676
- var file3 = path5.join(start, rel2);
26675
+ var file3 = path6.join(start, rel2);
26677
26676
  try {
26678
- fs3.statSync(file3);
26677
+ fs4.statSync(file3);
26679
26678
  return file3;
26680
26679
  } catch (err) {
26681
- if (path5.dirname(start) !== start) return find2(path5.dirname(start), rel2);
26680
+ if (path6.dirname(start) !== start) return find2(path6.dirname(start), rel2);
26682
26681
  }
26683
26682
  }
26684
26683
  __name$6(find2, "find");
@@ -27068,8 +27067,8 @@ var require_registry_auth_token = __commonJS$1({ "../../node_modules/.pnpm/regis
27068
27067
  };
27069
27068
  }
27070
27069
  __name$6(getLegacyAuthInfo, "getLegacyAuthInfo");
27071
- function normalizePath$3(path5) {
27072
- return path5[path5.length - 1] === "/" ? path5 : path5 + "/";
27070
+ function normalizePath$3(path6) {
27071
+ return path6[path6.length - 1] === "/" ? path6 : path6 + "/";
27073
27072
  }
27074
27073
  __name$6(normalizePath$3, "normalizePath");
27075
27074
  function getAuthInfoForUrl(regUrl, npmrc) {
@@ -27106,24 +27105,24 @@ var require_registry_auth_token = __commonJS$1({ "../../node_modules/.pnpm/regis
27106
27105
  var require_update_check = __commonJS$1({ "../../node_modules/.pnpm/update-check@1.5.4/node_modules/update-check/index.js"(exports$1, module$1) {
27107
27106
  var { URL: URL2 } = __require$1("url");
27108
27107
  var { join: join3 } = __require$1("path");
27109
- var fs3 = __require$1("fs");
27108
+ var fs4 = __require$1("fs");
27110
27109
  var { promisify: promisify$3 } = __require$1("util");
27111
27110
  var { tmpdir } = __require$1("os");
27112
27111
  var registryUrl = require_registry_url();
27113
- var writeFile$1 = promisify$3(fs3.writeFile);
27114
- var mkdir$1 = promisify$3(fs3.mkdir);
27115
- var readFile$1 = promisify$3(fs3.readFile);
27112
+ var writeFile$1 = promisify$3(fs4.writeFile);
27113
+ var mkdir$1 = promisify$3(fs4.mkdir);
27114
+ var readFile$1 = promisify$3(fs4.readFile);
27116
27115
  var compareVersions = /* @__PURE__ */ __name$6((a, b) => a.localeCompare(b, "en-US", { numeric: true }), "compareVersions");
27117
27116
  var encode3 = /* @__PURE__ */ __name$6((value) => encodeURIComponent(value).replace(/^%40/, "@"), "encode");
27118
27117
  var getFile = /* @__PURE__ */ __name$6(async (details, distTag) => {
27119
27118
  const subDir = join3(tmpdir(), "update-check");
27120
- if (!fs3.existsSync(subDir)) await mkdir$1(subDir);
27119
+ if (!fs4.existsSync(subDir)) await mkdir$1(subDir);
27121
27120
  let name = `${details.name}-${distTag}.json`;
27122
27121
  if (details.scope) name = `${details.scope}-${name}`;
27123
27122
  return join3(subDir, name);
27124
27123
  }, "getFile");
27125
27124
  var evaluateCache = /* @__PURE__ */ __name$6(async (file2, time3, interval) => {
27126
- if (fs3.existsSync(file2)) {
27125
+ if (fs4.existsSync(file2)) {
27127
27126
  const content = await readFile$1(file2, "utf8");
27128
27127
  const { lastUpdate, latest } = JSON.parse(content);
27129
27128
  if (lastUpdate + interval > time3) return {
@@ -27225,6 +27224,700 @@ var require_update_check = __commonJS$1({ "../../node_modules/.pnpm/update-check
27225
27224
  return null;
27226
27225
  };
27227
27226
  } });
27227
+ var require_path = __commonJS$1({ "../../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js"(exports$1, module$1) {
27228
+ module$1.exports = typeof process === "object" && process && process.platform === "win32" ? { sep: "\\" } : { sep: "/" };
27229
+ } });
27230
+ var require_balanced_match = __commonJS$1({ "../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports$1, module$1) {
27231
+ module$1.exports = balanced;
27232
+ function balanced(a, b, str) {
27233
+ if (a instanceof RegExp) a = maybeMatch(a, str);
27234
+ if (b instanceof RegExp) b = maybeMatch(b, str);
27235
+ var r2 = range(a, b, str);
27236
+ return r2 && {
27237
+ start: r2[0],
27238
+ end: r2[1],
27239
+ pre: str.slice(0, r2[0]),
27240
+ body: str.slice(r2[0] + a.length, r2[1]),
27241
+ post: str.slice(r2[1] + b.length)
27242
+ };
27243
+ }
27244
+ __name$6(balanced, "balanced");
27245
+ function maybeMatch(reg, str) {
27246
+ var m = str.match(reg);
27247
+ return m ? m[0] : null;
27248
+ }
27249
+ __name$6(maybeMatch, "maybeMatch");
27250
+ balanced.range = range;
27251
+ function range(a, b, str) {
27252
+ var begs, beg, left, right, result;
27253
+ var ai = str.indexOf(a);
27254
+ var bi = str.indexOf(b, ai + 1);
27255
+ var i$1 = ai;
27256
+ if (ai >= 0 && bi > 0) {
27257
+ if (a === b) return [ai, bi];
27258
+ begs = [];
27259
+ left = str.length;
27260
+ while (i$1 >= 0 && !result) {
27261
+ if (i$1 == ai) {
27262
+ begs.push(i$1);
27263
+ ai = str.indexOf(a, i$1 + 1);
27264
+ } else if (begs.length == 1) result = [begs.pop(), bi];
27265
+ else {
27266
+ beg = begs.pop();
27267
+ if (beg < left) {
27268
+ left = beg;
27269
+ right = bi;
27270
+ }
27271
+ bi = str.indexOf(b, i$1 + 1);
27272
+ }
27273
+ i$1 = ai < bi && ai >= 0 ? ai : bi;
27274
+ }
27275
+ if (begs.length) result = [left, right];
27276
+ }
27277
+ return result;
27278
+ }
27279
+ __name$6(range, "range");
27280
+ } });
27281
+ var require_brace_expansion = __commonJS$1({ "../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports$1, module$1) {
27282
+ var balanced = require_balanced_match();
27283
+ module$1.exports = expandTop;
27284
+ var escSlash = "\0SLASH" + Math.random() + "\0";
27285
+ var escOpen = "\0OPEN" + Math.random() + "\0";
27286
+ var escClose = "\0CLOSE" + Math.random() + "\0";
27287
+ var escComma = "\0COMMA" + Math.random() + "\0";
27288
+ var escPeriod = "\0PERIOD" + Math.random() + "\0";
27289
+ function numeric$1(str) {
27290
+ return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
27291
+ }
27292
+ __name$6(numeric$1, "numeric");
27293
+ function escapeBraces(str) {
27294
+ return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
27295
+ }
27296
+ __name$6(escapeBraces, "escapeBraces");
27297
+ function unescapeBraces(str) {
27298
+ return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
27299
+ }
27300
+ __name$6(unescapeBraces, "unescapeBraces");
27301
+ function parseCommaParts(str) {
27302
+ if (!str) return [""];
27303
+ var parts = [];
27304
+ var m = balanced("{", "}", str);
27305
+ if (!m) return str.split(",");
27306
+ var pre = m.pre;
27307
+ var body = m.body;
27308
+ var post = m.post;
27309
+ var p$2 = pre.split(",");
27310
+ p$2[p$2.length - 1] += "{" + body + "}";
27311
+ var postParts = parseCommaParts(post);
27312
+ if (post.length) {
27313
+ p$2[p$2.length - 1] += postParts.shift();
27314
+ p$2.push.apply(p$2, postParts);
27315
+ }
27316
+ parts.push.apply(parts, p$2);
27317
+ return parts;
27318
+ }
27319
+ __name$6(parseCommaParts, "parseCommaParts");
27320
+ function expandTop(str) {
27321
+ if (!str) return [];
27322
+ if (str.substr(0, 2) === "{}") str = "\\{\\}" + str.substr(2);
27323
+ return expand(escapeBraces(str), true).map(unescapeBraces);
27324
+ }
27325
+ __name$6(expandTop, "expandTop");
27326
+ function embrace(str) {
27327
+ return "{" + str + "}";
27328
+ }
27329
+ __name$6(embrace, "embrace");
27330
+ function isPadded(el) {
27331
+ return /^-?0\d/.test(el);
27332
+ }
27333
+ __name$6(isPadded, "isPadded");
27334
+ function lte$4(i$1, y) {
27335
+ return i$1 <= y;
27336
+ }
27337
+ __name$6(lte$4, "lte");
27338
+ function gte$4(i$1, y) {
27339
+ return i$1 >= y;
27340
+ }
27341
+ __name$6(gte$4, "gte");
27342
+ function expand(str, isTop) {
27343
+ var expansions = [];
27344
+ var m = balanced("{", "}", str);
27345
+ if (!m) return [str];
27346
+ var pre = m.pre;
27347
+ var post = m.post.length ? expand(m.post, false) : [""];
27348
+ if (/\$$/.test(m.pre)) for (var k = 0; k < post.length; k++) {
27349
+ var expansion = pre + "{" + m.body + "}" + post[k];
27350
+ expansions.push(expansion);
27351
+ }
27352
+ else {
27353
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
27354
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
27355
+ var isSequence = isNumericSequence || isAlphaSequence;
27356
+ var isOptions = m.body.indexOf(",") >= 0;
27357
+ if (!isSequence && !isOptions) {
27358
+ if (m.post.match(/,.*\}/)) {
27359
+ str = m.pre + "{" + m.body + escClose + m.post;
27360
+ return expand(str);
27361
+ }
27362
+ return [str];
27363
+ }
27364
+ var n2;
27365
+ if (isSequence) n2 = m.body.split(/\.\./);
27366
+ else {
27367
+ n2 = parseCommaParts(m.body);
27368
+ if (n2.length === 1) {
27369
+ n2 = expand(n2[0], false).map(embrace);
27370
+ if (n2.length === 1) return post.map(function(p$2) {
27371
+ return m.pre + n2[0] + p$2;
27372
+ });
27373
+ }
27374
+ }
27375
+ var N;
27376
+ if (isSequence) {
27377
+ var x = numeric$1(n2[0]);
27378
+ var y = numeric$1(n2[1]);
27379
+ var width = Math.max(n2[0].length, n2[1].length);
27380
+ var incr = n2.length == 3 ? Math.abs(numeric$1(n2[2])) : 1;
27381
+ var test = lte$4;
27382
+ if (y < x) {
27383
+ incr *= -1;
27384
+ test = gte$4;
27385
+ }
27386
+ var pad = n2.some(isPadded);
27387
+ N = [];
27388
+ for (var i$1 = x; test(i$1, y); i$1 += incr) {
27389
+ var c$1;
27390
+ if (isAlphaSequence) {
27391
+ c$1 = String.fromCharCode(i$1);
27392
+ if (c$1 === "\\") c$1 = "";
27393
+ } else {
27394
+ c$1 = String(i$1);
27395
+ if (pad) {
27396
+ var need = width - c$1.length;
27397
+ if (need > 0) {
27398
+ var z2 = new Array(need + 1).join("0");
27399
+ if (i$1 < 0) c$1 = "-" + z2 + c$1.slice(1);
27400
+ else c$1 = z2 + c$1;
27401
+ }
27402
+ }
27403
+ }
27404
+ N.push(c$1);
27405
+ }
27406
+ } else {
27407
+ N = [];
27408
+ for (var j$1 = 0; j$1 < n2.length; j$1++) N.push.apply(N, expand(n2[j$1], false));
27409
+ }
27410
+ for (var j$1 = 0; j$1 < N.length; j$1++) for (var k = 0; k < post.length; k++) {
27411
+ var expansion = pre + N[j$1] + post[k];
27412
+ if (!isTop || isSequence || expansion) expansions.push(expansion);
27413
+ }
27414
+ }
27415
+ return expansions;
27416
+ }
27417
+ __name$6(expand, "expand");
27418
+ } });
27419
+ var require_minimatch = __commonJS$1({ "../../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js"(exports$1, module$1) {
27420
+ var minimatch = module$1.exports = (p$2, pattern, options = {}) => {
27421
+ assertValidPattern(pattern);
27422
+ if (!options.nocomment && pattern.charAt(0) === "#") return false;
27423
+ return new Minimatch2(pattern, options).match(p$2);
27424
+ };
27425
+ module$1.exports = minimatch;
27426
+ var path6 = require_path();
27427
+ minimatch.sep = path6.sep;
27428
+ var GLOBSTAR = Symbol("globstar **");
27429
+ minimatch.GLOBSTAR = GLOBSTAR;
27430
+ var expand = require_brace_expansion();
27431
+ var plTypes = {
27432
+ "!": {
27433
+ open: "(?:(?!(?:",
27434
+ close: "))[^/]*?)"
27435
+ },
27436
+ "?": {
27437
+ open: "(?:",
27438
+ close: ")?"
27439
+ },
27440
+ "+": {
27441
+ open: "(?:",
27442
+ close: ")+"
27443
+ },
27444
+ "*": {
27445
+ open: "(?:",
27446
+ close: ")*"
27447
+ },
27448
+ "@": {
27449
+ open: "(?:",
27450
+ close: ")"
27451
+ }
27452
+ };
27453
+ var qmark = "[^/]";
27454
+ var star = qmark + "*?";
27455
+ var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
27456
+ var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
27457
+ var charSet = /* @__PURE__ */ __name$6((s) => s.split("").reduce((set2, c$1) => {
27458
+ set2[c$1] = true;
27459
+ return set2;
27460
+ }, {}), "charSet");
27461
+ var reSpecials = charSet("().*{}+?[]^$\\!");
27462
+ var addPatternStartSet = charSet("[.(");
27463
+ var slashSplit = /\/+/;
27464
+ minimatch.filter = (pattern, options = {}) => (p$2, i$1, list$1) => minimatch(p$2, pattern, options);
27465
+ var ext = /* @__PURE__ */ __name$6((a, b = {}) => {
27466
+ const t2 = {};
27467
+ Object.keys(a).forEach((k) => t2[k] = a[k]);
27468
+ Object.keys(b).forEach((k) => t2[k] = b[k]);
27469
+ return t2;
27470
+ }, "ext");
27471
+ minimatch.defaults = (def) => {
27472
+ if (!def || typeof def !== "object" || !Object.keys(def).length) return minimatch;
27473
+ const orig = minimatch;
27474
+ const m = /* @__PURE__ */ __name$6((p$2, pattern, options) => orig(p$2, pattern, ext(def, options)), "m");
27475
+ m.Minimatch = class Minimatch extends orig.Minimatch {
27476
+ static {
27477
+ __name$6(this, "Minimatch");
27478
+ }
27479
+ constructor(pattern, options) {
27480
+ super(pattern, ext(def, options));
27481
+ }
27482
+ };
27483
+ m.Minimatch.defaults = (options) => orig.defaults(ext(def, options)).Minimatch;
27484
+ m.filter = (pattern, options) => orig.filter(pattern, ext(def, options));
27485
+ m.defaults = (options) => orig.defaults(ext(def, options));
27486
+ m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options));
27487
+ m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options));
27488
+ m.match = (list$1, pattern, options) => orig.match(list$1, pattern, ext(def, options));
27489
+ return m;
27490
+ };
27491
+ minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options);
27492
+ var braceExpand = /* @__PURE__ */ __name$6((pattern, options = {}) => {
27493
+ assertValidPattern(pattern);
27494
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) return [pattern];
27495
+ return expand(pattern);
27496
+ }, "braceExpand");
27497
+ var MAX_PATTERN_LENGTH = 1024 * 64;
27498
+ var assertValidPattern = /* @__PURE__ */ __name$6((pattern) => {
27499
+ if (typeof pattern !== "string") throw new TypeError("invalid pattern");
27500
+ if (pattern.length > MAX_PATTERN_LENGTH) throw new TypeError("pattern is too long");
27501
+ }, "assertValidPattern");
27502
+ var SUBPARSE = Symbol("subparse");
27503
+ minimatch.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
27504
+ minimatch.match = (list$1, pattern, options = {}) => {
27505
+ const mm = new Minimatch2(pattern, options);
27506
+ list$1 = list$1.filter((f) => mm.match(f));
27507
+ if (mm.options.nonull && !list$1.length) list$1.push(pattern);
27508
+ return list$1;
27509
+ };
27510
+ var globUnescape = /* @__PURE__ */ __name$6((s) => s.replace(/\\(.)/g, "$1"), "globUnescape");
27511
+ var charUnescape = /* @__PURE__ */ __name$6((s) => s.replace(/\\([^-\]])/g, "$1"), "charUnescape");
27512
+ var regExpEscape = /* @__PURE__ */ __name$6((s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "regExpEscape");
27513
+ var braExpEscape = /* @__PURE__ */ __name$6((s) => s.replace(/[[\]\\]/g, "\\$&"), "braExpEscape");
27514
+ var Minimatch2 = class {
27515
+ static {
27516
+ __name$6(this, "Minimatch");
27517
+ }
27518
+ constructor(pattern, options) {
27519
+ assertValidPattern(pattern);
27520
+ if (!options) options = {};
27521
+ this.options = options;
27522
+ this.set = [];
27523
+ this.pattern = pattern;
27524
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
27525
+ if (this.windowsPathsNoEscape) this.pattern = this.pattern.replace(/\\/g, "/");
27526
+ this.regexp = null;
27527
+ this.negate = false;
27528
+ this.comment = false;
27529
+ this.empty = false;
27530
+ this.partial = !!options.partial;
27531
+ this.make();
27532
+ }
27533
+ debug() {}
27534
+ make() {
27535
+ const pattern = this.pattern;
27536
+ const options = this.options;
27537
+ if (!options.nocomment && pattern.charAt(0) === "#") {
27538
+ this.comment = true;
27539
+ return;
27540
+ }
27541
+ if (!pattern) {
27542
+ this.empty = true;
27543
+ return;
27544
+ }
27545
+ this.parseNegate();
27546
+ let set2 = this.globSet = this.braceExpand();
27547
+ if (options.debug) this.debug = (...args) => console.error(...args);
27548
+ this.debug(this.pattern, set2);
27549
+ set2 = this.globParts = set2.map((s) => s.split(slashSplit));
27550
+ this.debug(this.pattern, set2);
27551
+ set2 = set2.map((s, si, set3) => s.map(this.parse, this));
27552
+ this.debug(this.pattern, set2);
27553
+ set2 = set2.filter((s) => s.indexOf(false) === -1);
27554
+ this.debug(this.pattern, set2);
27555
+ this.set = set2;
27556
+ }
27557
+ parseNegate() {
27558
+ if (this.options.nonegate) return;
27559
+ const pattern = this.pattern;
27560
+ let negate = false;
27561
+ let negateOffset = 0;
27562
+ for (let i$1 = 0; i$1 < pattern.length && pattern.charAt(i$1) === "!"; i$1++) {
27563
+ negate = !negate;
27564
+ negateOffset++;
27565
+ }
27566
+ if (negateOffset) this.pattern = pattern.slice(negateOffset);
27567
+ this.negate = negate;
27568
+ }
27569
+ matchOne(file2, pattern, partial2) {
27570
+ var options = this.options;
27571
+ this.debug("matchOne", {
27572
+ "this": this,
27573
+ file: file2,
27574
+ pattern
27575
+ });
27576
+ this.debug("matchOne", file2.length, pattern.length);
27577
+ for (var fi = 0, pi = 0, fl = file2.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
27578
+ this.debug("matchOne loop");
27579
+ var p$2 = pattern[pi];
27580
+ var f = file2[fi];
27581
+ this.debug(pattern, p$2, f);
27582
+ if (p$2 === false) return false;
27583
+ if (p$2 === GLOBSTAR) {
27584
+ this.debug("GLOBSTAR", [
27585
+ pattern,
27586
+ p$2,
27587
+ f
27588
+ ]);
27589
+ var fr = fi;
27590
+ var pr = pi + 1;
27591
+ if (pr === pl) {
27592
+ this.debug("** at the end");
27593
+ for (; fi < fl; fi++) if (file2[fi] === "." || file2[fi] === ".." || !options.dot && file2[fi].charAt(0) === ".") return false;
27594
+ return true;
27595
+ }
27596
+ while (fr < fl) {
27597
+ var swallowee = file2[fr];
27598
+ this.debug("\nglobstar while", file2, fr, pattern, pr, swallowee);
27599
+ if (this.matchOne(file2.slice(fr), pattern.slice(pr), partial2)) {
27600
+ this.debug("globstar found match!", fr, fl, swallowee);
27601
+ return true;
27602
+ } else {
27603
+ if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
27604
+ this.debug("dot detected!", file2, fr, pattern, pr);
27605
+ break;
27606
+ }
27607
+ this.debug("globstar swallow a segment, and continue");
27608
+ fr++;
27609
+ }
27610
+ }
27611
+ if (partial2) {
27612
+ this.debug("\n>>> no match, partial?", file2, fr, pattern, pr);
27613
+ if (fr === fl) return true;
27614
+ }
27615
+ return false;
27616
+ }
27617
+ var hit;
27618
+ if (typeof p$2 === "string") {
27619
+ hit = f === p$2;
27620
+ this.debug("string match", p$2, f, hit);
27621
+ } else {
27622
+ hit = f.match(p$2);
27623
+ this.debug("pattern match", p$2, f, hit);
27624
+ }
27625
+ if (!hit) return false;
27626
+ }
27627
+ if (fi === fl && pi === pl) return true;
27628
+ else if (fi === fl) return partial2;
27629
+ else if (pi === pl) return fi === fl - 1 && file2[fi] === "";
27630
+ throw new Error("wtf?");
27631
+ }
27632
+ braceExpand() {
27633
+ return braceExpand(this.pattern, this.options);
27634
+ }
27635
+ parse(pattern, isSub) {
27636
+ assertValidPattern(pattern);
27637
+ const options = this.options;
27638
+ if (pattern === "**") if (!options.noglobstar) return GLOBSTAR;
27639
+ else pattern = "*";
27640
+ if (pattern === "") return "";
27641
+ let re$5 = "";
27642
+ let hasMagic = false;
27643
+ let escaping = false;
27644
+ const patternListStack = [];
27645
+ const negativeLists = [];
27646
+ let stateChar;
27647
+ let inClass = false;
27648
+ let reClassStart = -1;
27649
+ let classStart = -1;
27650
+ let cs;
27651
+ let pl;
27652
+ let sp;
27653
+ let dotTravAllowed = pattern.charAt(0) === ".";
27654
+ let dotFileAllowed = options.dot || dotTravAllowed;
27655
+ const patternStart = /* @__PURE__ */ __name$6(() => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)", "patternStart");
27656
+ const subPatternStart = /* @__PURE__ */ __name$6((p$2) => p$2.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)", "subPatternStart");
27657
+ const clearStateChar = /* @__PURE__ */ __name$6(() => {
27658
+ if (stateChar) {
27659
+ switch (stateChar) {
27660
+ case "*":
27661
+ re$5 += star;
27662
+ hasMagic = true;
27663
+ break;
27664
+ case "?":
27665
+ re$5 += qmark;
27666
+ hasMagic = true;
27667
+ break;
27668
+ default:
27669
+ re$5 += "\\" + stateChar;
27670
+ break;
27671
+ }
27672
+ this.debug("clearStateChar %j %j", stateChar, re$5);
27673
+ stateChar = false;
27674
+ }
27675
+ }, "clearStateChar");
27676
+ for (let i$1 = 0, c$1; i$1 < pattern.length && (c$1 = pattern.charAt(i$1)); i$1++) {
27677
+ this.debug("%s %s %s %j", pattern, i$1, re$5, c$1);
27678
+ if (escaping) {
27679
+ if (c$1 === "/") return false;
27680
+ if (reSpecials[c$1]) re$5 += "\\";
27681
+ re$5 += c$1;
27682
+ escaping = false;
27683
+ continue;
27684
+ }
27685
+ switch (c$1) {
27686
+ case "/": return false;
27687
+ case "\\":
27688
+ if (inClass && pattern.charAt(i$1 + 1) === "-") {
27689
+ re$5 += c$1;
27690
+ continue;
27691
+ }
27692
+ clearStateChar();
27693
+ escaping = true;
27694
+ continue;
27695
+ case "?":
27696
+ case "*":
27697
+ case "+":
27698
+ case "@":
27699
+ case "!":
27700
+ this.debug("%s %s %s %j <-- stateChar", pattern, i$1, re$5, c$1);
27701
+ if (inClass) {
27702
+ this.debug(" in class");
27703
+ if (c$1 === "!" && i$1 === classStart + 1) c$1 = "^";
27704
+ re$5 += c$1;
27705
+ continue;
27706
+ }
27707
+ this.debug("call clearStateChar %j", stateChar);
27708
+ clearStateChar();
27709
+ stateChar = c$1;
27710
+ if (options.noext) clearStateChar();
27711
+ continue;
27712
+ case "(": {
27713
+ if (inClass) {
27714
+ re$5 += "(";
27715
+ continue;
27716
+ }
27717
+ if (!stateChar) {
27718
+ re$5 += "\\(";
27719
+ continue;
27720
+ }
27721
+ const plEntry = {
27722
+ type: stateChar,
27723
+ start: i$1 - 1,
27724
+ reStart: re$5.length,
27725
+ open: plTypes[stateChar].open,
27726
+ close: plTypes[stateChar].close
27727
+ };
27728
+ this.debug(this.pattern, " ", plEntry);
27729
+ patternListStack.push(plEntry);
27730
+ re$5 += plEntry.open;
27731
+ if (plEntry.start === 0 && plEntry.type !== "!") {
27732
+ dotTravAllowed = true;
27733
+ re$5 += subPatternStart(pattern.slice(i$1 + 1));
27734
+ }
27735
+ this.debug("plType %j %j", stateChar, re$5);
27736
+ stateChar = false;
27737
+ continue;
27738
+ }
27739
+ case ")": {
27740
+ const plEntry = patternListStack[patternListStack.length - 1];
27741
+ if (inClass || !plEntry) {
27742
+ re$5 += "\\)";
27743
+ continue;
27744
+ }
27745
+ patternListStack.pop();
27746
+ clearStateChar();
27747
+ hasMagic = true;
27748
+ pl = plEntry;
27749
+ re$5 += pl.close;
27750
+ if (pl.type === "!") negativeLists.push(Object.assign(pl, { reEnd: re$5.length }));
27751
+ continue;
27752
+ }
27753
+ case "|": {
27754
+ const plEntry = patternListStack[patternListStack.length - 1];
27755
+ if (inClass || !plEntry) {
27756
+ re$5 += "\\|";
27757
+ continue;
27758
+ }
27759
+ clearStateChar();
27760
+ re$5 += "|";
27761
+ if (plEntry.start === 0 && plEntry.type !== "!") {
27762
+ dotTravAllowed = true;
27763
+ re$5 += subPatternStart(pattern.slice(i$1 + 1));
27764
+ }
27765
+ continue;
27766
+ }
27767
+ case "[":
27768
+ clearStateChar();
27769
+ if (inClass) {
27770
+ re$5 += "\\" + c$1;
27771
+ continue;
27772
+ }
27773
+ inClass = true;
27774
+ classStart = i$1;
27775
+ reClassStart = re$5.length;
27776
+ re$5 += c$1;
27777
+ continue;
27778
+ case "]":
27779
+ if (i$1 === classStart + 1 || !inClass) {
27780
+ re$5 += "\\" + c$1;
27781
+ continue;
27782
+ }
27783
+ cs = pattern.substring(classStart + 1, i$1);
27784
+ try {
27785
+ RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
27786
+ re$5 += c$1;
27787
+ } catch (er) {
27788
+ re$5 = re$5.substring(0, reClassStart) + "(?:$.)";
27789
+ }
27790
+ hasMagic = true;
27791
+ inClass = false;
27792
+ continue;
27793
+ default:
27794
+ clearStateChar();
27795
+ if (reSpecials[c$1] && !(c$1 === "^" && inClass)) re$5 += "\\";
27796
+ re$5 += c$1;
27797
+ break;
27798
+ }
27799
+ }
27800
+ if (inClass) {
27801
+ cs = pattern.slice(classStart + 1);
27802
+ sp = this.parse(cs, SUBPARSE);
27803
+ re$5 = re$5.substring(0, reClassStart) + "\\[" + sp[0];
27804
+ hasMagic = hasMagic || sp[1];
27805
+ }
27806
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
27807
+ let tail$1;
27808
+ tail$1 = re$5.slice(pl.reStart + pl.open.length);
27809
+ this.debug("setting tail", re$5, pl);
27810
+ tail$1 = tail$1.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
27811
+ if (!$2) $2 = "\\";
27812
+ return $1 + $1 + $2 + "|";
27813
+ });
27814
+ this.debug("tail=%j\n %s", tail$1, tail$1, pl, re$5);
27815
+ const t2 = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
27816
+ hasMagic = true;
27817
+ re$5 = re$5.slice(0, pl.reStart) + t2 + "\\(" + tail$1;
27818
+ }
27819
+ clearStateChar();
27820
+ if (escaping) re$5 += "\\\\";
27821
+ const addPatternStart = addPatternStartSet[re$5.charAt(0)];
27822
+ for (let n2 = negativeLists.length - 1; n2 > -1; n2--) {
27823
+ const nl = negativeLists[n2];
27824
+ const nlBefore = re$5.slice(0, nl.reStart);
27825
+ const nlFirst = re$5.slice(nl.reStart, nl.reEnd - 8);
27826
+ let nlAfter = re$5.slice(nl.reEnd);
27827
+ const nlLast = re$5.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
27828
+ const closeParensBefore = nlBefore.split(")").length;
27829
+ const openParensBefore = nlBefore.split("(").length - closeParensBefore;
27830
+ let cleanAfter = nlAfter;
27831
+ for (let i$1 = 0; i$1 < openParensBefore; i$1++) cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
27832
+ nlAfter = cleanAfter;
27833
+ const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
27834
+ re$5 = nlBefore + nlFirst + nlAfter + dollar + nlLast;
27835
+ }
27836
+ if (re$5 !== "" && hasMagic) re$5 = "(?=.)" + re$5;
27837
+ if (addPatternStart) re$5 = patternStart() + re$5;
27838
+ if (isSub === SUBPARSE) return [re$5, hasMagic];
27839
+ if (options.nocase && !hasMagic) hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
27840
+ if (!hasMagic) return globUnescape(pattern);
27841
+ const flags = options.nocase ? "i" : "";
27842
+ try {
27843
+ return Object.assign(new RegExp("^" + re$5 + "$", flags), {
27844
+ _glob: pattern,
27845
+ _src: re$5
27846
+ });
27847
+ } catch (er) {
27848
+ return /* @__PURE__ */ new RegExp("$.");
27849
+ }
27850
+ }
27851
+ makeRe() {
27852
+ if (this.regexp || this.regexp === false) return this.regexp;
27853
+ const set2 = this.set;
27854
+ if (!set2.length) {
27855
+ this.regexp = false;
27856
+ return this.regexp;
27857
+ }
27858
+ const options = this.options;
27859
+ const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
27860
+ const flags = options.nocase ? "i" : "";
27861
+ let re$5 = set2.map((pattern) => {
27862
+ pattern = pattern.map((p$2) => typeof p$2 === "string" ? regExpEscape(p$2) : p$2 === GLOBSTAR ? GLOBSTAR : p$2._src).reduce((set3, p$2) => {
27863
+ if (!(set3[set3.length - 1] === GLOBSTAR && p$2 === GLOBSTAR)) set3.push(p$2);
27864
+ return set3;
27865
+ }, []);
27866
+ pattern.forEach((p$2, i$1) => {
27867
+ if (p$2 !== GLOBSTAR || pattern[i$1 - 1] === GLOBSTAR) return;
27868
+ if (i$1 === 0) if (pattern.length > 1) pattern[i$1 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i$1 + 1];
27869
+ else pattern[i$1] = twoStar;
27870
+ else if (i$1 === pattern.length - 1) pattern[i$1 - 1] += "(?:\\/|" + twoStar + ")?";
27871
+ else {
27872
+ pattern[i$1 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i$1 + 1];
27873
+ pattern[i$1 + 1] = GLOBSTAR;
27874
+ }
27875
+ });
27876
+ return pattern.filter((p$2) => p$2 !== GLOBSTAR).join("/");
27877
+ }).join("|");
27878
+ re$5 = "^(?:" + re$5 + ")$";
27879
+ if (this.negate) re$5 = "^(?!" + re$5 + ").*$";
27880
+ try {
27881
+ this.regexp = new RegExp(re$5, flags);
27882
+ } catch (ex) {
27883
+ this.regexp = false;
27884
+ }
27885
+ return this.regexp;
27886
+ }
27887
+ match(f, partial2 = this.partial) {
27888
+ this.debug("match", f, this.pattern);
27889
+ if (this.comment) return false;
27890
+ if (this.empty) return f === "";
27891
+ if (f === "/" && partial2) return true;
27892
+ const options = this.options;
27893
+ if (path6.sep !== "/") f = f.split(path6.sep).join("/");
27894
+ f = f.split(slashSplit);
27895
+ this.debug(this.pattern, "split", f);
27896
+ const set2 = this.set;
27897
+ this.debug(this.pattern, "set", set2);
27898
+ let filename;
27899
+ for (let i$1 = f.length - 1; i$1 >= 0; i$1--) {
27900
+ filename = f[i$1];
27901
+ if (filename) break;
27902
+ }
27903
+ for (let i$1 = 0; i$1 < set2.length; i$1++) {
27904
+ const pattern = set2[i$1];
27905
+ let file2 = f;
27906
+ if (options.matchBase && pattern.length === 1) file2 = [filename];
27907
+ if (this.matchOne(file2, pattern, partial2)) {
27908
+ if (options.flipNegate) return true;
27909
+ return !this.negate;
27910
+ }
27911
+ }
27912
+ if (options.flipNegate) return false;
27913
+ return this.negate;
27914
+ }
27915
+ static defaults(def) {
27916
+ return minimatch.defaults(def).Minimatch;
27917
+ }
27918
+ };
27919
+ minimatch.Minimatch = Minimatch2;
27920
+ } });
27228
27921
  var ARTIFACTS_EVENT_TYPES = [
27229
27922
  "cf.artifacts.repo.created",
27230
27923
  "cf.artifacts.repo.deleted",
@@ -28113,9 +28806,9 @@ function cloneDef(schema) {
28113
28806
  return mergeDefs$1(schema._zod.def);
28114
28807
  }
28115
28808
  __name$6(cloneDef, "cloneDef");
28116
- function getElementAtPath(obj, path5) {
28117
- if (!path5) return obj;
28118
- return path5.reduce((acc, key) => acc?.[key], obj);
28809
+ function getElementAtPath(obj, path6) {
28810
+ if (!path6) return obj;
28811
+ return path6.reduce((acc, key) => acc?.[key], obj);
28119
28812
  }
28120
28813
  __name$6(getElementAtPath, "getElementAtPath");
28121
28814
  function promiseAllObject(promisesObj) {
@@ -28445,11 +29138,11 @@ function explicitlyAborted$1(x, startIndex = 0) {
28445
29138
  return false;
28446
29139
  }
28447
29140
  __name$6(explicitlyAborted$1, "explicitlyAborted");
28448
- function prefixIssues$2(path5, issues) {
29141
+ function prefixIssues$2(path6, issues) {
28449
29142
  return issues.map((iss) => {
28450
29143
  var _a3;
28451
29144
  (_a3 = iss).path ?? (_a3.path = []);
28452
- iss.path.unshift(path5);
29145
+ iss.path.unshift(path6);
28453
29146
  return iss;
28454
29147
  });
28455
29148
  }
@@ -28584,12 +29277,12 @@ function flattenError$1(error51, mapper = (issue2) => issue2.message) {
28584
29277
  __name$6(flattenError$1, "flattenError");
28585
29278
  function formatError$2(error51, mapper = (issue2) => issue2.message) {
28586
29279
  const fieldErrors = { _errors: [] };
28587
- const processError = /* @__PURE__ */ __name$6((error52, path5 = []) => {
28588
- for (const issue2 of error52.issues) if (issue2.code === "invalid_union" && issue2.errors.length) issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
28589
- else if (issue2.code === "invalid_key") processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
28590
- else if (issue2.code === "invalid_element") processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
29280
+ const processError = /* @__PURE__ */ __name$6((error52, path6 = []) => {
29281
+ for (const issue2 of error52.issues) if (issue2.code === "invalid_union" && issue2.errors.length) issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
29282
+ else if (issue2.code === "invalid_key") processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
29283
+ else if (issue2.code === "invalid_element") processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
28591
29284
  else {
28592
- const fullpath = [...path5, ...issue2.path];
29285
+ const fullpath = [...path6, ...issue2.path];
28593
29286
  if (fullpath.length === 0) fieldErrors._errors.push(mapper(issue2));
28594
29287
  else {
28595
29288
  let curr = fieldErrors;
@@ -28613,13 +29306,13 @@ function formatError$2(error51, mapper = (issue2) => issue2.message) {
28613
29306
  __name$6(formatError$2, "formatError");
28614
29307
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
28615
29308
  const result = { errors: [] };
28616
- const processError = /* @__PURE__ */ __name$6((error52, path5 = []) => {
29309
+ const processError = /* @__PURE__ */ __name$6((error52, path6 = []) => {
28617
29310
  var _a3, _b;
28618
- for (const issue2 of error52.issues) if (issue2.code === "invalid_union" && issue2.errors.length) issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
28619
- else if (issue2.code === "invalid_key") processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
28620
- else if (issue2.code === "invalid_element") processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
29311
+ for (const issue2 of error52.issues) if (issue2.code === "invalid_union" && issue2.errors.length) issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
29312
+ else if (issue2.code === "invalid_key") processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
29313
+ else if (issue2.code === "invalid_element") processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
28621
29314
  else {
28622
- const fullpath = [...path5, ...issue2.path];
29315
+ const fullpath = [...path6, ...issue2.path];
28623
29316
  if (fullpath.length === 0) {
28624
29317
  result.errors.push(mapper(issue2));
28625
29318
  continue;
@@ -28649,8 +29342,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
28649
29342
  __name$6(treeifyError, "treeifyError");
28650
29343
  function toDotPath(_path) {
28651
29344
  const segs = [];
28652
- const path5 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
28653
- for (const seg of path5) if (typeof seg === "number") segs.push(`[${seg}]`);
29345
+ const path6 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
29346
+ for (const seg of path6) if (typeof seg === "number") segs.push(`[${seg}]`);
28654
29347
  else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`);
28655
29348
  else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`);
28656
29349
  else {
@@ -40782,11 +41475,11 @@ function detectVersion(schema, defaultTarget) {
40782
41475
  __name$6(detectVersion, "detectVersion");
40783
41476
  function resolveRef(ref$1, ctx) {
40784
41477
  if (!ref$1.startsWith("#")) throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
40785
- const path5 = ref$1.slice(1).split("/").filter(Boolean);
40786
- if (path5.length === 0) return ctx.rootSchema;
41478
+ const path6 = ref$1.slice(1).split("/").filter(Boolean);
41479
+ if (path6.length === 0) return ctx.rootSchema;
40787
41480
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
40788
- if (path5[0] === defsKey) {
40789
- const key = path5[1];
41481
+ if (path6[0] === defsKey) {
41482
+ const key = path6[1];
40790
41483
  if (!key || !ctx.defs[key]) throw new Error(`Reference not found: ${ref$1}`);
40791
41484
  return ctx.defs[key];
40792
41485
  }
@@ -41175,9 +41868,9 @@ Please add "${field}" to "env.${envName}".`);
41175
41868
  return rawEnv[field] ?? defaultValue;
41176
41869
  }
41177
41870
  __name$6(notInheritable, "notInheritable");
41178
- function unwindPropertyPath(root, path5) {
41871
+ function unwindPropertyPath(root, path6) {
41179
41872
  let container = root;
41180
- const parts = path5.split(".");
41873
+ const parts = path6.split(".");
41181
41874
  for (let i$1 = 0; i$1 < parts.length - 1; i$1++) {
41182
41875
  if (!hasProperty(container, parts[i$1])) return;
41183
41876
  container = container[parts[i$1]];
@@ -41963,7 +42656,7 @@ function normalizeAndValidateEnvironment(diagnostics, configPath, rawEnv, isDisp
41963
42656
  warnIfDurableObjectsHaveNoLifecycleConfig(diagnostics, environment.durable_objects, environment.migrations, environment.exports, configPath);
41964
42657
  errorIfMigrationsAndExportsBothSet(diagnostics, environment.migrations, environment.exports);
41965
42658
  const containersDeclaredElsewhere = rawConfig !== void 0 ? rawConfig.containers !== void 0 : Object.values("env" in rawEnv ? rawEnv.env ?? {} : {}).some((rawNamedEnv) => rawNamedEnv?.containers !== void 0);
41966
- validateContainerExportLinks$1(diagnostics, environment.containers, environment.exports, containersDeclaredElsewhere);
42659
+ validateContainerExportLinks(diagnostics, environment.containers, environment.exports, containersDeclaredElsewhere);
41967
42660
  if (envName !== "top level") validateAdditionalProperties(diagnostics, "env." + envName, Object.keys(rawEnv), Object.keys(environment));
41968
42661
  return environment;
41969
42662
  }
@@ -43255,7 +43948,6 @@ var validateBindingsHaveUniqueNames = /* @__PURE__ */ __name$6((diagnostics, con
43255
43948
  const bindingNamesArray = Object.entries(friendlyBindingNames);
43256
43949
  const bindingsGroupedByType = Object.fromEntries(bindingNamesArray.map(([bindingType, binding]) => [binding, getBindingNames(bindingType === "queues" ? config2[bindingType]?.producers : config2[bindingType])]));
43257
43950
  bindingsGroupedByType["Secret"] = config2.secrets?.required ?? [];
43258
- bindingsGroupedByType["Container images"] = [CONTAINER_IMAGES_BINDING];
43259
43951
  const bindingsGroupedByName = {};
43260
43952
  for (const bindingType in bindingsGroupedByType) {
43261
43953
  const bindingNames = bindingsGroupedByType[bindingType];
@@ -44226,7 +44918,7 @@ function errorIfMigrationsAndExportsBothSet(diagnostics, migrations, exports$1)
44226
44918
  if (migrations.length > 0 && exports$1 !== void 0 && Object.values(exports$1).some((entry) => entry.type === "durable-object")) diagnostics.errors.push(`\`migrations\` and \`exports\` are mutually exclusive. Choose one or the other to declare your Durable Object lifecycle, but not both.`);
44227
44919
  }
44228
44920
  __name$6(errorIfMigrationsAndExportsBothSet, "errorIfMigrationsAndExportsBothSet");
44229
- function validateContainerExportLinks$1(diagnostics, containers, exports$1, containersDeclaredElsewhere) {
44921
+ function validateContainerExportLinks(diagnostics, containers, exports$1, containersDeclaredElsewhere) {
44230
44922
  if (containers !== void 0 && !Array.isArray(containers)) return;
44231
44923
  if (containers === void 0 && containersDeclaredElsewhere) return;
44232
44924
  const containersByName = /* @__PURE__ */ new Map();
@@ -44286,7 +44978,7 @@ function validateContainerExportLinks$1(diagnostics, containers, exports$1, cont
44286
44978
  if (referencedContainerName === void 0 && exportEntry !== void 0 && "storage" in exportEntry && exportEntry.storage === "legacy-kv") diagnostics.errors.push(`The container "${container.name}" sets "class_name" to "${container.class_name}", but "exports.${container.class_name}.storage" is "legacy-kv". Containers are not supported on Durable Objects using the "legacy-kv" storage backend.`);
44287
44979
  }
44288
44980
  }
44289
- __name$6(validateContainerExportLinks$1, "validateContainerExportLinks");
44981
+ __name$6(validateContainerExportLinks, "validateContainerExportLinks");
44290
44982
  var validatePythonModules = /* @__PURE__ */ __name$6((diagnostics, field, value, topLevelEnv) => {
44291
44983
  if (value === void 0) return true;
44292
44984
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -44357,6 +45049,7 @@ var BINDING_LOCAL_SUPPORT = {
44357
45049
  pipeline: "local-and-remote",
44358
45050
  service: "local-and-remote",
44359
45051
  queue: "local-and-remote",
45052
+ flagship: "local-and-remote",
44360
45053
  vectorize: "remote",
44361
45054
  mtls_certificate: "remote",
44362
45055
  dispatch_namespace: "remote",
@@ -44365,7 +45058,6 @@ var BINDING_LOCAL_SUPPORT = {
44365
45058
  ai_search_namespace: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
44366
45059
  media: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
44367
45060
  artifacts: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
44368
- flagship: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
44369
45061
  vpc_service: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
44370
45062
  vpc_network: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
44371
45063
  agent_memory: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator"
@@ -45080,12 +45772,12 @@ function printBindings(bindings, options) {
45080
45772
  mode: getMode({ isSimulatedLocally: true })
45081
45773
  };
45082
45774
  }));
45083
- if (flagship.length > 0) output.push(...flagship.map(({ binding, app_id }) => {
45775
+ if (flagship.length > 0) output.push(...flagship.map(({ binding, app_id, remote }) => {
45084
45776
  return {
45085
45777
  name: binding,
45086
45778
  type: getBindingTypeFriendlyName("flagship"),
45087
45779
  value: app_id,
45088
- mode: getMode({ isSimulatedLocally: !context.remoteBindingsDisabled ? false : void 0 })
45780
+ mode: getMode({ isSimulatedLocally: context.remoteBindingsDisabled || !remote })
45089
45781
  };
45090
45782
  }));
45091
45783
  if (services.length > 0) output.push(...services.map(({ binding, service, entrypoint, remote, dev }) => {
@@ -46718,6 +47410,91 @@ function toUrlPath(filePath) {
46718
47410
  return filePath.replace(/\\/g, "/");
46719
47411
  }
46720
47412
  __name$6(toUrlPath, "toUrlPath");
47413
+ var import_minimatch = __toESM(require_minimatch());
47414
+ var DEFAULT_MIGRATIONS_DIR = "./migrations";
47415
+ function getD1MigrationFiles(options) {
47416
+ const migrationsDir = normalizeRelativePath(options.migrationsDir ?? DEFAULT_MIGRATIONS_DIR);
47417
+ const dirRelativePattern = stripDirPrefix(normalizeRelativePath(options.migrationsPattern ?? `${migrationsDir}/*.sql`), migrationsDir);
47418
+ const walkRoot = path__default.resolve(options.projectPath, migrationsDir);
47419
+ return listFilesRelative(walkRoot, new import_minimatch.Minimatch(dirRelativePattern, { dot: false })).map((name) => ({
47420
+ name,
47421
+ filePath: path__default.join(walkRoot, ...name.split("/"))
47422
+ }));
47423
+ }
47424
+ __name$6(getD1MigrationFiles, "getD1MigrationFiles");
47425
+ function normalizeRelativePath(p$2) {
47426
+ const forwardSlashed = p$2.replace(/\\/g, "/");
47427
+ const normalized = path__default.posix.normalize(forwardSlashed);
47428
+ if (normalized.endsWith("/")) return normalized.slice(0, -1);
47429
+ return normalized;
47430
+ }
47431
+ __name$6(normalizeRelativePath, "normalizeRelativePath");
47432
+ function stripDirPrefix(pattern, dir2) {
47433
+ if (dir2 === ".") return pattern;
47434
+ const prefix = `${dir2}/`;
47435
+ if (!pattern.startsWith(prefix)) throw new Error(`Expected migrations pattern ${JSON.stringify(pattern)} to start with ${JSON.stringify(prefix)}`);
47436
+ return pattern.slice(prefix.length);
47437
+ }
47438
+ __name$6(stripDirPrefix, "stripDirPrefix");
47439
+ function listFilesRelative(dir2, matcher) {
47440
+ const out = [];
47441
+ const stack = [{
47442
+ abs: dir2,
47443
+ rel: ""
47444
+ }];
47445
+ while (stack.length > 0) {
47446
+ const { abs, rel } = stack.pop();
47447
+ let entries;
47448
+ try {
47449
+ entries = fs2.readdirSync(abs, { withFileTypes: true });
47450
+ } catch {
47451
+ continue;
47452
+ }
47453
+ for (const entry of entries) {
47454
+ const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
47455
+ if (entry.isDirectory()) {
47456
+ if (matcher.match(childRel, true)) stack.push({
47457
+ abs: path__default.join(abs, entry.name),
47458
+ rel: childRel
47459
+ });
47460
+ } else if (entry.isFile() && matcher.match(childRel)) out.push(childRel);
47461
+ }
47462
+ }
47463
+ return out.sort(compareMigrationPaths);
47464
+ }
47465
+ __name$6(listFilesRelative, "listFilesRelative");
47466
+ function compareMigrationPaths(a, b) {
47467
+ const aSegments = a.split("/");
47468
+ const bSegments = b.split("/");
47469
+ const shared = Math.min(aSegments.length, bSegments.length);
47470
+ for (let i$1 = 0; i$1 < shared; i$1++) {
47471
+ const aSegment = aSegments[i$1];
47472
+ const bSegment = bSegments[i$1];
47473
+ if (aSegment === void 0 || bSegment === void 0) break;
47474
+ const cmp$3 = compareSegments(aSegment, bSegment);
47475
+ if (cmp$3 !== 0) return cmp$3;
47476
+ }
47477
+ return aSegments.length - bSegments.length;
47478
+ }
47479
+ __name$6(compareMigrationPaths, "compareMigrationPaths");
47480
+ function compareSegments(a, b) {
47481
+ const aNum = leadingMigrationNumber(a);
47482
+ const bNum = leadingMigrationNumber(b);
47483
+ if (aNum !== bNum) {
47484
+ if (Number.isFinite(aNum) && Number.isFinite(bNum)) return aNum - bNum;
47485
+ if (Number.isFinite(aNum)) return -1;
47486
+ if (Number.isFinite(bNum)) return 1;
47487
+ }
47488
+ if (a < b) return -1;
47489
+ if (a > b) return 1;
47490
+ return 0;
47491
+ }
47492
+ __name$6(compareSegments, "compareSegments");
47493
+ function leadingMigrationNumber(relativePath) {
47494
+ const firstSegment = relativePath.split("/")[0];
47495
+ return parseInt(firstSegment.split("_")[0], 10);
47496
+ }
47497
+ __name$6(leadingMigrationNumber, "leadingMigrationNumber");
46721
47498
 
46722
47499
  //#endregion
46723
47500
  //#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/constants.js
@@ -48168,10 +48945,14 @@ async function assertWranglerVersion() {
48168
48945
  * delegate uses to force the experimental Build Output Specification on by default.
48169
48946
  */
48170
48947
  const FORCE_BUILD_OUTPUT_ENV_VAR = "CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT";
48948
+ const PREVIEW_BUILD_ENV_VAR = "CLOUDFLARE_VITE_PREVIEW_BUILD";
48171
48949
  /** Whether `cf-vite build` has forced the Build Output Specification on. */
48172
48950
  function isForcedBuildOutput() {
48173
48951
  return process.env[FORCE_BUILD_OUTPUT_ENV_VAR] === "true";
48174
48952
  }
48953
+ function isPreviewBuild() {
48954
+ return process.env[PREVIEW_BUILD_ENV_VAR] === "true";
48955
+ }
48175
48956
 
48176
48957
  //#endregion
48177
48958
  //#region ../../node_modules/.pnpm/@remix-run+node-fetch-server@0.8.0/node_modules/@remix-run/node-fetch-server/dist/node-fetch-server.js
@@ -55624,14 +56405,13 @@ const ContainerObservabilityBaseSchema = strictObject({
55624
56405
  enabled: boolean().optional(),
55625
56406
  logs: strictObject({ enabled: boolean().optional() }).optional()
55626
56407
  });
55627
- const ContainerObservabilitySchema = union([ContainerObservabilityBaseSchema.extend({ targetInstancePercentage: number().min(0).max(100).optional() }), ContainerObservabilityBaseSchema.extend({ targetInstanceCount: number().int().nonnegative().optional() })]);
56408
+ const StandardContainerObservabilitySchema = union([ContainerObservabilityBaseSchema.extend({ targetInstancePercentage: number().min(0).max(100).optional() }), ContainerObservabilityBaseSchema.extend({ targetInstanceCount: number().int().nonnegative().optional() })]);
55628
56409
  const BaseContainerSchema = strictObject({
55629
- type: literal$1("container"),
55630
56410
  name: string().min(1),
55631
- observability: ContainerObservabilitySchema.optional(),
55632
56411
  unsafe: record(string(), unknown()).optional()
55633
56412
  });
55634
56413
  const StandardContainerBaseSchema = BaseContainerSchema.extend({
56414
+ observability: StandardContainerObservabilitySchema.optional(),
55635
56415
  maxInstances: number().int().nonnegative().default(20),
55636
56416
  instanceType: union([_enum([
55637
56417
  "basic",
@@ -55678,16 +56458,18 @@ const StandardContainerBaseSchema = BaseContainerSchema.extend({
55678
56458
  activeGracePeriod: number().nonnegative().optional()
55679
56459
  }).optional()
55680
56460
  });
55681
- const DurableObjectContainerBaseSchema = BaseContainerSchema.extend({ schedulingPolicy: literal$1("durable-object") });
56461
+ const DurableObjectContainerBaseSchema = BaseContainerSchema.extend({
56462
+ schedulingPolicy: literal$1("durable-object"),
56463
+ observability: ContainerObservabilityBaseSchema.optional()
56464
+ });
55682
56465
  /**
55683
- * Input Container schema — validates user-authored `cloudflare.config.ts`
55684
- * Container exports. Dockerfiles are built by the consuming build tool.
56466
+ * Input Container schema — parses user-authored `cloudflare.config.ts`
56467
+ * Container objects. Dockerfiles are built by the consuming build tool.
55685
56468
  */
55686
56469
  const InputContainerSchema = union([StandardContainerBaseSchema.extend({ image: InputContainerImageSchema }).superRefine(validateContainerRelationships), DurableObjectContainerBaseSchema.extend({ images: record(string(), InputContainerImageSchema).optional() })]);
55687
56470
  /**
55688
- * Output Container schema — validates Container configs in the Build Output
55689
- * Specification, after any Dockerfile has been built into a local or remote
55690
- * image reference.
56471
+ * Output Container schema — parses `container.config.json` files in the Build
56472
+ * Output Specification, after any Dockerfile has been built into a local image reference.
55691
56473
  */
55692
56474
  const OutputContainerSchema = union([StandardContainerBaseSchema.extend({ image: OutputContainerImageSchema }).superRefine(validateContainerRelationships), DurableObjectContainerBaseSchema.extend({ images: record(string(), OutputContainerImageSchema).optional() })]);
55693
56475
  const DurableObjectCreatedExportSchema = strictObject({
@@ -55829,7 +56611,6 @@ const UnsafeSchema = strictObject({
55829
56611
  * (user-authored) and output (on-disk) Worker configs.
55830
56612
  */
55831
56613
  const BaseWorkerSchema = strictObject({
55832
- type: literal$1("worker"),
55833
56614
  name: string(),
55834
56615
  compatibilityDate: string(),
55835
56616
  compatibilityFlags: array(string()).optional(),
@@ -55850,72 +56631,37 @@ const BaseWorkerSchema = strictObject({
55850
56631
  exports: record(string(), ExportSchema).optional()
55851
56632
  });
55852
56633
  /**
55853
- * Input Worker schema — the shape that user-authored `cloudflare.config.ts`
55854
- * files are validated against. Adds an optional `entrypoint` field to the
55855
- * base schema.
56634
+ * Input Worker schema — parses Worker definitions from user-authored
56635
+ * `cloudflare.config.ts` files. Adds an optional `entrypoint` field to the base
56636
+ * schema.
55856
56637
  */
55857
56638
  const InputWorkerSchema = BaseWorkerSchema.extend({ entrypoint: union([string(), strictObject({ default: string() })]).transform((value) => typeof value === "string" ? value : value.default).optional() });
55858
56639
  /**
55859
- * Input settings schema — validates the named `settings` export of a
55860
- * `cloudflare.config.ts`. Holds account/deployment settings shared by the other exports.
56640
+ * Input settings schema — parses the account settings at the top level of
56641
+ * `cloudflare.config.ts`.
55861
56642
  */
55862
- const InputSettingsSchema = strictObject({
55863
- type: literal$1("settings"),
56643
+ const InputSettingsSchema = object({
55864
56644
  accountId: string().optional(),
55865
56645
  complianceRegion: _enum(["public", "fedramp-high"]).optional()
55866
56646
  });
56647
+ /** The resolved, user-authored project configuration. */
56648
+ const InputConfigSchema = strictObject({
56649
+ ...InputSettingsSchema.shape,
56650
+ worker: InputWorkerSchema.optional(),
56651
+ containers: array(InputContainerSchema).default([])
56652
+ });
56653
+ const BuildContextSchema = strictObject({
56654
+ isPreview: boolean(),
56655
+ mode: string().optional()
56656
+ });
55867
56657
  /**
55868
- * Output settings schema — the shape of the top-level `config.json` in the
55869
- * Build Output Specification. Adds the `mode` the build was produced in.
56658
+ * The shape of the root `config.json` in the Build Output Specification.
56659
+ * Account settings remain at the top level while build context is grouped
56660
+ * under `buildContext`.
55870
56661
  */
55871
- const OutputSettingsSchema = InputSettingsSchema.extend({ mode: string().optional() });
55872
- const DEFAULT_EXPORT_NAME = "default";
55873
- const SETTINGS_EXPORT_NAME = "settings";
55874
- const SUPPORTED_EXPORT_TYPES = new Set([
55875
- "container",
55876
- "worker",
55877
- "settings"
55878
- ]);
55879
- function invalidConfigExportMessage(exportName) {
55880
- return `The \`${exportName}\` export is not a supported export type. Move constants, helper functions, and other unsupported exports to a separate module.`;
55881
- }
55882
- const ConfigExportsTypeSchema = record(string(), unknown()).check((ctx) => {
55883
- for (const [key, value] of Object.entries(ctx.value)) {
55884
- const isObject$5 = typeof value === "object" && value !== null;
55885
- const type = isObject$5 && "type" in value ? value.type : void 0;
55886
- if (typeof type !== "string" || !SUPPORTED_EXPORT_TYPES.has(type)) {
55887
- ctx.issues.push({
55888
- code: "custom",
55889
- input: value,
55890
- path: isObject$5 ? [key, "type"] : [key],
55891
- message: invalidConfigExportMessage(key)
55892
- });
55893
- continue;
55894
- }
55895
- if (key === DEFAULT_EXPORT_NAME && type !== "worker") {
55896
- ctx.issues.push({
55897
- code: "custom",
55898
- input: value,
55899
- path: [key],
55900
- message: `The \`${DEFAULT_EXPORT_NAME}\` export is reserved for a \`worker\` config; found a \`${type}\` config.`
55901
- });
55902
- continue;
55903
- }
55904
- const isSettingsName = key === SETTINGS_EXPORT_NAME;
55905
- const isSettingsType = type === "settings";
55906
- if (isSettingsType && !isSettingsName) ctx.issues.push({
55907
- code: "custom",
55908
- input: value,
55909
- path: [key],
55910
- message: `A \`settings\` config is only allowed on the \`${SETTINGS_EXPORT_NAME}\` export; found one on the \`${key}\` export.`
55911
- });
55912
- else if (isSettingsName && !isSettingsType) ctx.issues.push({
55913
- code: "custom",
55914
- input: value,
55915
- path: [key],
55916
- message: `The \`${SETTINGS_EXPORT_NAME}\` export is reserved for a \`settings\` config; found a \`${type}\` config.`
55917
- });
55918
- }
56662
+ const OutputRootConfigSchema = strictObject({
56663
+ ...InputSettingsSchema.shape,
56664
+ buildContext: BuildContextSchema
55919
56665
  });
55920
56666
  const ModuleTypeSchema = _enum([
55921
56667
  "esm",
@@ -55947,9 +56693,9 @@ const ManifestSchema = strictObject({
55947
56693
  });
55948
56694
  });
55949
56695
  /**
55950
- * Output Worker schema — the shape of the Worker's `config.json` in the
55951
- * Build Output Specification. Adds an optional `manifest` field to the
55952
- * base schema.
56696
+ * Output Worker schema — the shape of the Worker's `worker.config.json` in the
56697
+ * Build Output Specification. Adds an optional `manifest` field to the base
56698
+ * schema.
55953
56699
  */
55954
56700
  const OutputWorkerSchema = BaseWorkerSchema.extend({ manifest: ManifestSchema.optional() });
55955
56701
  var import_dist = (/* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/dist/index.js": ((exports$1) => {
@@ -56008,7 +56754,8 @@ function generateTypes({ configPath, packageName = "@cloudflare/config" }) {
56008
56754
  return import_dist.dedent`
56009
56755
  /* eslint-disable */
56010
56756
  // Generated by @cloudflare/config
56011
- type __WorkerConfig = import("${packageName}").UnwrapConfig<typeof import("${configPath.replace(/\.(ts|js|mts|mjs)$/, "")}").default>;
56757
+ type __Config = import("${packageName}").UnwrapConfig<typeof import("${configPath.replace(/\.(ts|js|mts|mjs)$/, "")}").default>;
56758
+ type __WorkerConfig = import("${packageName}").UnwrapConfig<__Config["worker"]>;
56012
56759
  type __Env = import("${packageName}").InferEnv<__WorkerConfig>;
56013
56760
 
56014
56761
  declare namespace Cloudflare {
@@ -56090,34 +56837,36 @@ const ROLLOUT_KIND_MAP = {
56090
56837
  /**
56091
56838
  * Convert a parsed `@cloudflare/config` config into a Wrangler `RawConfig`.
56092
56839
  *
56093
- * The caller is responsible for unwrapping any function/promise wrappers and
56094
- * validating the configs against their corresponding input schemas before
56095
- * passing them in.
56840
+ * The caller is responsible for resolving any function/promise wrappers and
56841
+ * parsing the configuration before passing it in.
56096
56842
  *
56097
- * @param workerConfig The parsed (post-validation) Worker config.
56098
- * @param settingsConfig The optional parsed settings config, whose fields
56099
- * are merged onto the result.
56100
- * @param containerExports The parsed Container exports to include in the
56101
- * result.
56843
+ * @param config The parsed configuration.
56102
56844
  * @returns The corresponding Wrangler `RawConfig`.
56103
56845
  */
56104
- function convertToWranglerConfig(workerConfig, settingsConfig, containerExports = []) {
56846
+ function convertToWranglerConfig(config$2) {
56105
56847
  const result = {};
56106
- convertTopLevel(workerConfig, result);
56107
- convertBindingsAndAssets(workerConfig, result);
56108
- convertExports(workerConfig, result);
56109
- convertDomains(workerConfig, result);
56110
- convertTriggers(workerConfig, result);
56111
- convertTailConsumers(workerConfig, result);
56112
- if (settingsConfig !== void 0) convertSettings(settingsConfig, result);
56113
- if (containerExports.length > 0) result.containers = containerExports.map((container) => convertContainer(container));
56848
+ const { worker, containers } = config$2;
56849
+ if (worker !== void 0) {
56850
+ convertTopLevel(worker, result);
56851
+ convertBindingsAndAssets(worker, result);
56852
+ convertExports(worker, result);
56853
+ convertDomains(worker, result);
56854
+ convertTriggers(worker, result);
56855
+ convertTailConsumers(worker, result);
56856
+ }
56857
+ convertSettings(config$2, result);
56858
+ if (containers.length > 0) result.containers = containers.map((container) => convertContainer(container));
56114
56859
  return result;
56115
56860
  }
56116
56861
  function convertContainer(container) {
56117
- if (container.schedulingPolicy === "durable-object") throw new UserError$1("Durable Object-managed Containers are not currently supported by `convertToWranglerConfig()`.", { telemetryMessage: false });
56118
56862
  const converted = { name: container.name };
56119
56863
  if (container.observability !== void 0) converted.observability = convertContainerObservability(container.observability);
56120
56864
  if (container.unsafe !== void 0) converted.unsafe = container.unsafe;
56865
+ if (container.schedulingPolicy === "durable-object") {
56866
+ converted.scheduling_policy = "durable_object";
56867
+ if (container.images !== void 0) converted.images = Object.fromEntries(Object.entries(container.images).map(([name, image]) => [name, convertDurableObjectContainerImage(image)]));
56868
+ return converted;
56869
+ }
56121
56870
  converted.image = "dockerfile" in container.image ? container.image.dockerfile : container.image.reference;
56122
56871
  converted.max_instances = container.maxInstances;
56123
56872
  if ("dockerfile" in container.image) {
@@ -56146,6 +56895,13 @@ function convertContainer(container) {
56146
56895
  }
56147
56896
  return converted;
56148
56897
  }
56898
+ function convertDurableObjectContainerImage(image) {
56899
+ if ("reference" in image) return { image: image.reference };
56900
+ const converted = { dockerfile: image.dockerfile };
56901
+ if (image.buildContext !== void 0) converted.build_context = image.buildContext;
56902
+ if (image.buildVars !== void 0) converted.build_vars = image.buildVars;
56903
+ return converted;
56904
+ }
56149
56905
  function convertContainerObservability(observability) {
56150
56906
  const converted = {};
56151
56907
  if (observability.enabled !== void 0) converted.enabled = observability.enabled;
@@ -56697,31 +57453,22 @@ const CF_NO_CACHE_QUERY_KEY = "cf-no-cache";
56697
57453
  const RE_NODE_MODULES = /[/\\]node_modules[/\\]/;
56698
57454
  const depsStore = new AsyncLocalStorage();
56699
57455
  /**
56700
- * Dynamically import a worker config file from disk.
57456
+ * Dynamically import a Cloudflare config file from disk.
56701
57457
  *
56702
- * Returns all of the module's exports (keyed by export name, including
56703
- * `default`), plus the set of file paths imported during resolution. Callers
56704
- * are responsible for unwrapping function/promise/definition wrappers around
56705
- * each export and validating them.
57458
+ * Returns the module's default export plus the set of file paths imported
57459
+ * during resolution.
56706
57460
  *
56707
57461
  * @param configPath Filesystem path to the config file. Relative paths are
56708
57462
  * resolved against `process.cwd()`.
56709
- * @param options.include When provided, only exports whose names are listed
56710
- * survive into the returned `exports` map. Filtering happens before any
56711
- * resolution or validation.
56712
57463
  */
56713
- async function loadConfig(configPath, options) {
57464
+ async function loadConfig(configPath) {
56714
57465
  registerConfigHooks();
56715
57466
  const url$2 = pathToFileURL(configPath).href;
56716
57467
  const dependencies = /* @__PURE__ */ new Set();
56717
57468
  const mod$1 = await depsStore.run(dependencies, () => import(url$2, { with: { [CF_ATTR]: CF_NO_CACHE_VALUE } }));
56718
- const exports$2 = {};
56719
- for (const [name, value] of Object.entries(mod$1)) {
56720
- if (options?.include && !options.include.includes(name)) continue;
56721
- exports$2[name] = value;
56722
- }
57469
+ if (!("default" in mod$1)) throw new Error(`The config file "${configPath}" does not have a default export. Export your configuration with \`export default defineConfig({ ... })\`.`);
56723
57470
  return {
56724
- exports: exports$2,
57471
+ config: mod$1.default,
56725
57472
  dependencies
56726
57473
  };
56727
57474
  }
@@ -56813,11 +57560,8 @@ const CROSS_WORKER_BINDING_TYPES = new Set([
56813
57560
  function isRecord(value) {
56814
57561
  return typeof value === "object" && value !== null;
56815
57562
  }
56816
- function isConfigReference(value) {
56817
- return typeof value === "function" || isRecord(value);
56818
- }
56819
- function normalizeConfigReference(reference, resolved, expectedType) {
56820
- return isRecord(resolved) && resolved.type === expectedType && typeof resolved.name === "string" ? resolved.name : reference;
57563
+ function normalizeConfigReference(reference, resolved) {
57564
+ return isRecord(resolved) && typeof resolved.name === "string" ? resolved.name : reference;
56821
57565
  }
56822
57566
  function createDefinitionResolver(ctx) {
56823
57567
  const resolvedDefinitions = /* @__PURE__ */ new Map();
@@ -56835,11 +57579,11 @@ async function normalizeWorkerReferences(resolved, resolveDefinition) {
56835
57579
  if (!isRecord(resolved) || !isRecord(resolved.env)) return resolved;
56836
57580
  const env$3 = { ...resolved.env };
56837
57581
  for (const [bindingName, binding] of Object.entries(env$3)) {
56838
- if (!isRecord(binding) || typeof binding.type !== "string" || !CROSS_WORKER_BINDING_TYPES.has(binding.type) || !isConfigReference(binding.worker)) continue;
57582
+ if (!isRecord(binding) || typeof binding.type !== "string" || !CROSS_WORKER_BINDING_TYPES.has(binding.type) || typeof binding.worker === "string") continue;
56839
57583
  const target$1 = await resolveDefinition(binding.worker);
56840
57584
  env$3[bindingName] = {
56841
57585
  ...binding,
56842
- worker: normalizeConfigReference(binding.worker, target$1, "worker")
57586
+ worker: normalizeConfigReference(binding.worker, target$1)
56843
57587
  };
56844
57588
  }
56845
57589
  return {
@@ -56847,7 +57591,7 @@ async function normalizeWorkerReferences(resolved, resolveDefinition) {
56847
57591
  env: env$3
56848
57592
  };
56849
57593
  }
56850
- async function normalizeContainerReferences(resolved, resolveDefinition, resolvedExports) {
57594
+ async function normalizeContainerReferences(resolved, resolveDefinition, containers) {
56851
57595
  const issues = [];
56852
57596
  if (!isRecord(resolved) || !isRecord(resolved.exports)) return {
56853
57597
  value: resolved,
@@ -56866,7 +57610,7 @@ async function normalizeContainerReferences(resolved, resolveDefinition, resolve
56866
57610
  exportName,
56867
57611
  "container"
56868
57612
  ],
56869
- message: "Container provided as a string. Reference an exported Container definition instead."
57613
+ message: "Container provided as a string. Reference a Container definition instead, for example `container: myContainer`."
56870
57614
  });
56871
57615
  workerExports[exportName] = {
56872
57616
  ...workerExport,
@@ -56875,7 +57619,7 @@ async function normalizeContainerReferences(resolved, resolveDefinition, resolve
56875
57619
  continue;
56876
57620
  }
56877
57621
  const target$1 = await resolveDefinition(reference);
56878
- if (isRecord(target$1) && target$1.type === "container" && typeof target$1.name === "string" && !Object.values(resolvedExports).includes(target$1)) {
57622
+ if (isRecord(target$1) && typeof target$1.name === "string" && !containers.includes(target$1)) {
56879
57623
  issues.push({
56880
57624
  code: "custom",
56881
57625
  input: reference,
@@ -56884,7 +57628,7 @@ async function normalizeContainerReferences(resolved, resolveDefinition, resolve
56884
57628
  exportName,
56885
57629
  "container"
56886
57630
  ],
56887
- message: `The referenced Container "${target$1.name}" is not exported.`
57631
+ message: `The referenced Container "${target$1.name}" is not included in the \`containers\` array.`
56888
57632
  });
56889
57633
  workerExports[exportName] = {
56890
57634
  ...workerExport,
@@ -56894,7 +57638,7 @@ async function normalizeContainerReferences(resolved, resolveDefinition, resolve
56894
57638
  }
56895
57639
  workerExports[exportName] = {
56896
57640
  ...workerExport,
56897
- container: normalizeConfigReference(reference, target$1, "container")
57641
+ container: normalizeConfigReference(reference, target$1)
56898
57642
  };
56899
57643
  }
56900
57644
  return {
@@ -56905,8 +57649,8 @@ async function normalizeContainerReferences(resolved, resolveDefinition, resolve
56905
57649
  issues
56906
57650
  };
56907
57651
  }
56908
- async function normalizeConfigReferences(resolved, resolveDefinition, resolvedExports) {
56909
- return normalizeContainerReferences(await normalizeWorkerReferences(resolved, resolveDefinition), resolveDefinition, resolvedExports);
57652
+ async function normalizeWorkerConfig(resolved, resolveDefinition, containers) {
57653
+ return normalizeContainerReferences(await normalizeWorkerReferences(resolved, resolveDefinition), resolveDefinition, containers);
56910
57654
  }
56911
57655
  function prefixIssues(issues, prefix) {
56912
57656
  return issues.map((issue$2) => ({
@@ -56914,126 +57658,83 @@ function prefixIssues(issues, prefix) {
56914
57658
  path: [prefix, ...issue$2.path]
56915
57659
  }));
56916
57660
  }
56917
- function validateUniqueResourceNames(configExports) {
57661
+ function validateUniqueContainerNames(config$2) {
56918
57662
  const issues = [];
56919
- const exportNameByResourceName = {
56920
- container: /* @__PURE__ */ new Map(),
56921
- worker: /* @__PURE__ */ new Map()
56922
- };
56923
- for (const [exportName, config$2] of Object.entries(configExports)) {
56924
- if (config$2.type !== "container" && config$2.type !== "worker") continue;
56925
- const resourceType = config$2.type === "container" ? "Container" : "Worker";
56926
- const exportNames = exportNameByResourceName[config$2.type];
56927
- const previousExportName = exportNames.get(config$2.name);
56928
- if (previousExportName !== void 0) {
57663
+ const firstIndexByName = /* @__PURE__ */ new Map();
57664
+ for (const [index, container] of config$2.containers.entries()) {
57665
+ const firstIndex = firstIndexByName.get(container.name);
57666
+ if (firstIndex !== void 0) {
56929
57667
  issues.push({
56930
57668
  code: "custom",
56931
- input: config$2.name,
56932
- path: [exportName, "name"],
56933
- message: `The ${resourceType} name "${config$2.name}" is also used by the "${previousExportName}" export. ${resourceType} names must be unique.`
57669
+ input: container.name,
57670
+ path: [
57671
+ "containers",
57672
+ index,
57673
+ "name"
57674
+ ],
57675
+ message: `The Container name "${container.name}" is also used by \`containers[${firstIndex}]\`. Container names must be unique.`
56934
57676
  });
56935
57677
  continue;
56936
57678
  }
56937
- exportNames.set(config$2.name, exportName);
57679
+ firstIndexByName.set(container.name, index);
56938
57680
  }
56939
57681
  return issues;
56940
57682
  }
56941
- function validateContainerExportLinks(configExports) {
57683
+ function validateContainerLinks(config$2) {
56942
57684
  const issues = [];
56943
- const containerNames = /* @__PURE__ */ new Set();
56944
- for (const config$2 of Object.values(configExports)) if (config$2.type === "container") containerNames.add(config$2.name);
56945
- const firstReferenceByContainerName = /* @__PURE__ */ new Map();
56946
- for (const [workerExportName, config$2] of Object.entries(configExports)) {
56947
- if (config$2.type !== "worker") continue;
56948
- for (const [durableObjectExportName, workerExport] of Object.entries(config$2.exports ?? {})) {
56949
- if (workerExport.type !== "durable-object" || !("container" in workerExport) || workerExport.container === void 0) continue;
56950
- const containerName = workerExport.container;
56951
- const path$2 = [
56952
- workerExportName,
56953
- "exports",
56954
- durableObjectExportName,
56955
- "container"
56956
- ];
56957
- if (!containerNames.has(containerName)) {
56958
- issues.push({
56959
- code: "custom",
56960
- input: containerName,
56961
- path: path$2,
56962
- message: `The Container "${containerName}" is not exported from this configuration.`
56963
- });
56964
- continue;
56965
- }
56966
- const firstReference = firstReferenceByContainerName.get(containerName);
56967
- if (firstReference !== void 0) {
56968
- issues.push({
56969
- code: "custom",
56970
- input: containerName,
56971
- path: path$2,
56972
- message: `The Container "${containerName}" is already referenced by "${firstReference.workerExportName}.exports.${firstReference.durableObjectExportName}". A Container can only be linked to one Durable Object.`
56973
- });
56974
- continue;
56975
- }
56976
- firstReferenceByContainerName.set(containerName, {
56977
- workerExportName,
56978
- durableObjectExportName
57685
+ const firstExportByContainerName = /* @__PURE__ */ new Map();
57686
+ for (const [exportName, workerExport] of Object.entries(config$2.worker?.exports ?? {})) {
57687
+ if (workerExport.type !== "durable-object" || !("container" in workerExport) || workerExport.container === void 0) continue;
57688
+ const containerName = workerExport.container;
57689
+ const firstExportName = firstExportByContainerName.get(containerName);
57690
+ if (firstExportName !== void 0) {
57691
+ issues.push({
57692
+ code: "custom",
57693
+ input: containerName,
57694
+ path: [
57695
+ "worker",
57696
+ "exports",
57697
+ exportName,
57698
+ "container"
57699
+ ],
57700
+ message: `The Container "${containerName}" is already referenced by \`worker.exports.${firstExportName}\`. A Container can only be linked to one Durable Object.`
56979
57701
  });
57702
+ continue;
56980
57703
  }
57704
+ firstExportByContainerName.set(containerName, exportName);
56981
57705
  }
56982
57706
  return issues;
56983
57707
  }
56984
- /**
56985
- * Resolve and validate loaded `cloudflare.config.ts` exports.
56986
- *
56987
- * Config inputs are resolved once by identity. Top-level Worker and Container
56988
- * exports are also parsed once by identity. References are resolved only far
56989
- * enough to replace them with resource names, then Container links are
56990
- * validated across the exported resources.
56991
- */
56992
- async function resolveAndValidateConfigExports(exports$2, ctx) {
57708
+ /** Resolve and parse the default configuration export. */
57709
+ async function resolveAndParseConfig(input, ctx) {
56993
57710
  const resolveDefinition = createDefinitionResolver(ctx);
56994
- const parsedResources = /* @__PURE__ */ new Map();
56995
- const resolvedExports = {};
56996
- for (const [name, input] of Object.entries(exports$2)) resolvedExports[name] = await resolveDefinition(input);
56997
- const typeResult = ConfigExportsTypeSchema.safeParse(resolvedExports);
56998
- if (!typeResult.success) return typeResult;
56999
- const issues = [];
57000
- const data$1 = {};
57001
- const resolvedSettings = resolvedExports.settings;
57002
- const settingsResult = resolvedSettings ? InputSettingsSchema.safeParse(resolvedSettings) : void 0;
57003
- if (settingsResult) if (settingsResult.success) data$1.settings = settingsResult.data;
57004
- else issues.push(...prefixIssues(settingsResult.error.issues, "settings"));
57005
- for (const [name, input] of Object.entries(exports$2)) {
57006
- const resolved = resolvedExports[name];
57007
- if (!isRecord(resolved)) continue;
57008
- if (resolved.type !== "worker" && resolved.type !== "container") continue;
57009
- let result = parsedResources.get(input);
57010
- if (!result) {
57011
- if (resolved.type === "worker") {
57012
- const normalized = await normalizeConfigReferences(resolved, resolveDefinition, resolvedExports);
57013
- issues.push(...prefixIssues(normalized.issues, name));
57014
- result = InputWorkerSchema.safeParse(normalized.value);
57015
- } else result = InputContainerSchema.safeParse(resolved);
57016
- parsedResources.set(input, result);
57017
- if (!result.success) issues.push(...prefixIssues(result.error.issues, name));
57018
- }
57019
- if (result.success) data$1[name] = result.data;
57020
- }
57021
- issues.push(...validateUniqueResourceNames(data$1), ...validateContainerExportLinks(data$1));
57711
+ const resolved = await resolveDefinition(input);
57712
+ if (!isRecord(resolved)) return InputConfigSchema.safeParse(resolved);
57713
+ const containerInputs = Array.isArray(resolved.containers) ? resolved.containers : [];
57714
+ const containers = await Promise.all(containerInputs.map((container) => resolveDefinition(container)));
57715
+ const normalizedWorker = resolved.worker === void 0 ? {
57716
+ value: void 0,
57717
+ issues: []
57718
+ } : await normalizeWorkerConfig(await resolveDefinition(resolved.worker), resolveDefinition, containers);
57719
+ const candidate = {
57720
+ ...resolved,
57721
+ ...resolved.worker === void 0 ? {} : { worker: normalizedWorker.value },
57722
+ ...Array.isArray(resolved.containers) ? { containers } : {}
57723
+ };
57724
+ const result = InputConfigSchema.safeParse(candidate);
57725
+ const issues = [...prefixIssues(normalizedWorker.issues, "worker")];
57726
+ if (!result.success) issues.push(...result.error.issues);
57727
+ else issues.push(...validateUniqueContainerNames(result.data), ...validateContainerLinks(result.data));
57022
57728
  return issues.length > 0 ? {
57023
57729
  success: false,
57024
57730
  error: new ZodError(issues)
57025
- } : {
57026
- success: true,
57027
- data: data$1
57028
- };
57731
+ } : result;
57029
57732
  }
57030
- /**
57031
- * Load a `cloudflare.config.ts`, resolve all exports, and validate them.
57032
- */
57033
- async function loadAndValidateConfig(configPath, ctx, options) {
57034
- const { exports: exports$2, dependencies } = await loadConfig(configPath, options);
57733
+ /** Load and parse `cloudflare.config.ts`'s default export. */
57734
+ async function loadAndParseConfig(configPath, ctx) {
57735
+ const { config: config$2, dependencies } = await loadConfig(configPath);
57035
57736
  return {
57036
- result: await resolveAndValidateConfigExports(exports$2, ctx),
57737
+ result: await resolveAndParseConfig(config$2, ctx),
57037
57738
  dependencies
57038
57739
  };
57039
57740
  }
@@ -57306,35 +58007,31 @@ const defuArrayFn = createDefu((object$2, key, currentValue) => {
57306
58007
  * Will move to `v1` when the spec stabilises.
57307
58008
  */
57308
58009
  const BUILD_OUTPUT_VERSION = "v0";
57309
- /**
57310
- * Project-relative root.
57311
- */
58010
+ /** Build output directory relative to the project root. */
57312
58011
  const BUILD_OUTPUT_ROOT = ".cloudflare/output";
57313
- /**
57314
- * Filename shared by every config in the Build Output Specification.
57315
- *
57316
- * Configs are discriminated by their `type` field.
57317
- */
57318
- const CONFIG_FILENAME = "config.json";
57319
- /**
57320
- * Name of the sub-directory under `workers/` holding the default Worker.
57321
- */
58012
+ /** Filename of the root config in the Build Output Specification. */
58013
+ const ROOT_CONFIG_FILENAME = "config.json";
58014
+ /** Filename of each Worker config in the Build Output Specification. */
58015
+ const WORKER_CONFIG_FILENAME = "worker.config.json";
58016
+ /** Filename of each Container config in the Build Output Specification. */
58017
+ const CONTAINER_CONFIG_FILENAME = "container.config.json";
58018
+ /** Name of the directory containing the default Worker. */
57322
58019
  const DEFAULT_WORKER_DIRECTORY_NAME = "default";
57323
- /**
57324
- * Absolute path to the Build Output Specification root for the current project.
57325
- */
58020
+ const INVALID_DIRECTORY_NAME_CHARACTERS = /[\s<>:"/\\|?*\u0000-\u001f]+|\.+$/g;
58021
+ const WINDOWS_RESERVED_NAME = /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/;
58022
+ const MAX_DIRECTORY_NAME_BYTES = 254;
58023
+ /** Absolute path to the Build Output Specification directory. */
57326
58024
  function getBuildOutputDir(root) {
57327
58025
  return path.resolve(root, BUILD_OUTPUT_ROOT);
57328
58026
  }
57329
58027
  /**
57330
- * Absolute path to the top-level `config.json` for the current project.
58028
+ * Absolute path to the root `config.json`.
57331
58029
  *
57332
- * Holds the project-level settings shared by every Worker: those declared by
57333
- * the `settings` export of the input `cloudflare.config.ts`, including the
57334
- * mode the build was produced in.
58030
+ * Holds the settings declared at the top level of `cloudflare.config.ts` and
58031
+ * build context.
57335
58032
  */
57336
- function getSettingsConfigPath(root) {
57337
- return path.join(getBuildOutputDir(root), BUILD_OUTPUT_VERSION, CONFIG_FILENAME);
58033
+ function getRootConfigPath(root) {
58034
+ return path.join(getBuildOutputDir(root), BUILD_OUTPUT_VERSION, ROOT_CONFIG_FILENAME);
57338
58035
  }
57339
58036
  /**
57340
58037
  * Absolute path to the Workers output directory.
@@ -57348,47 +58045,68 @@ function getWorkersDir(root) {
57348
58045
  function getContainersDir(root) {
57349
58046
  return path.join(getBuildOutputDir(root), BUILD_OUTPUT_VERSION, "containers");
57350
58047
  }
57351
- function validateDirectoryName(name, resourceName) {
57352
- if (name.length === 0 || name === "." || name === ".." || name.includes("/") || name.includes("\\") || name.includes("\0")) throw new Error(`${resourceName} directory names must be non-empty, single path segments. Received ${JSON.stringify(name)}.`);
58048
+ /**
58049
+ * Convert a Cloudflare resource name into a portable, case-insensitive
58050
+ * directory name.
58051
+ *
58052
+ * The original resource name remains in its config file. Callers must reject
58053
+ * collisions when multiple resource names normalise to the same directory.
58054
+ */
58055
+ function normalizeDirectoryName(name) {
58056
+ const directoryName = truncateUtf8(name.toLowerCase(), MAX_DIRECTORY_NAME_BYTES).replace(INVALID_DIRECTORY_NAME_CHARACTERS, "-");
58057
+ return WINDOWS_RESERVED_NAME.test(directoryName) ? `_${directoryName}` : directoryName;
58058
+ }
58059
+ function truncateUtf8(value, maxBytes) {
58060
+ let result = "";
58061
+ let byteLength = 0;
58062
+ for (const character of value) {
58063
+ const characterByteLength = Buffer.byteLength(character);
58064
+ if (byteLength + characterByteLength > maxBytes) break;
58065
+ result += character;
58066
+ byteLength += characterByteLength;
58067
+ }
58068
+ return result;
58069
+ }
58070
+ function validateDirectoryName(name, resourceType) {
58071
+ if (name.length === 0 || name === "." || name === ".." || name.includes("/") || name.includes("\\") || name.includes("\0")) throw new Error(`${resourceType} directory names must be non-empty, single path segments. Received ${JSON.stringify(name)}.`);
57353
58072
  }
57354
58073
  /**
57355
- * Absolute path to a Worker's directory (`workers/<worker-directory-name>`).
58074
+ * Absolute path to a Worker's directory (`workers/<directory-name>`).
57356
58075
  */
57357
- function getWorkerDir(root, workerDirectoryName = DEFAULT_WORKER_DIRECTORY_NAME) {
57358
- validateDirectoryName(workerDirectoryName, "Worker");
57359
- return path.join(getWorkersDir(root), workerDirectoryName);
58076
+ function getWorkerDir(root, directoryName = DEFAULT_WORKER_DIRECTORY_NAME) {
58077
+ validateDirectoryName(directoryName, "Worker");
58078
+ return path.join(getWorkersDir(root), directoryName);
57360
58079
  }
57361
58080
  /**
57362
- * Absolute path to a Container's directory
57363
- * (`containers/<container-directory-name>`).
58081
+ * Absolute path to a Container's directory (`containers/<directory-name>`).
57364
58082
  */
57365
- function getContainerDir(root, containerDirectoryName) {
57366
- validateDirectoryName(containerDirectoryName, "Container");
57367
- return path.join(getContainersDir(root), containerDirectoryName);
58083
+ function getContainerDir(root, directoryName) {
58084
+ validateDirectoryName(directoryName, "Container");
58085
+ return path.join(getContainersDir(root), directoryName);
57368
58086
  }
57369
58087
  /**
57370
58088
  * Absolute path to the Container's config file.
57371
58089
  */
57372
- function getContainerConfigPath(root, containerDirectoryName) {
57373
- return path.join(getContainerDir(root, containerDirectoryName), CONFIG_FILENAME);
58090
+ function getContainerConfigPath(root, directoryName) {
58091
+ return path.join(getContainerDir(root, directoryName), CONTAINER_CONFIG_FILENAME);
57374
58092
  }
57375
58093
  /**
57376
58094
  * Absolute path to the Worker's config file.
57377
58095
  */
57378
- function getWorkerConfigPath(root, workerDirectoryName = DEFAULT_WORKER_DIRECTORY_NAME) {
57379
- return path.join(getWorkerDir(root, workerDirectoryName), CONFIG_FILENAME);
58096
+ function getWorkerConfigPath(root, directoryName = DEFAULT_WORKER_DIRECTORY_NAME) {
58097
+ return path.join(getWorkerDir(root, directoryName), WORKER_CONFIG_FILENAME);
57380
58098
  }
57381
58099
  /**
57382
58100
  * Absolute path to the Worker's bundle directory.
57383
58101
  */
57384
- function getWorkerBundleDir(root, workerDirectoryName = DEFAULT_WORKER_DIRECTORY_NAME) {
57385
- return path.join(getWorkerDir(root, workerDirectoryName), "bundle");
58102
+ function getWorkerBundleDir(root, directoryName = DEFAULT_WORKER_DIRECTORY_NAME) {
58103
+ return path.join(getWorkerDir(root, directoryName), "bundle");
57386
58104
  }
57387
58105
  /**
57388
58106
  * Absolute path to the Worker's assets directory.
57389
58107
  */
57390
- function getWorkerAssetsDir(root, workerDirectoryName = DEFAULT_WORKER_DIRECTORY_NAME) {
57391
- return path.join(getWorkerDir(root, workerDirectoryName), "assets");
58108
+ function getWorkerAssetsDir(root, directoryName = DEFAULT_WORKER_DIRECTORY_NAME) {
58109
+ return path.join(getWorkerDir(root, directoryName), "assets");
57392
58110
  }
57393
58111
  var __defProp$3 = Object.defineProperty;
57394
58112
  var __name$3 = (target$1, value) => __defProp$3(target$1, "name", {
@@ -57426,7 +58144,8 @@ async function cleanBuildOutputDir(root) {
57426
58144
  await removeDir(getBuildOutputDir(root));
57427
58145
  }
57428
58146
  /**
57429
- * Write an output Worker `config.json` to the Build Output Specification tree.
58147
+ * Write an output Worker `worker.config.json` to the Build Output Specification
58148
+ * tree.
57430
58149
  *
57431
58150
  * - Workers mode: `manifest` is provided (bundle/ present on disk).
57432
58151
  * - Assets-only mode: `manifest` is omitted (no bundle/ directory).
@@ -57441,30 +58160,35 @@ async function writeWorkerConfig({ root, config: config$2, manifest, directoryNa
57441
58160
  await fsp.writeFile(getWorkerConfigPath(root, directoryName), JSON.stringify(outputConfig));
57442
58161
  }
57443
58162
  /**
57444
- * Write the top-level `config.json` to the Build Output Specification tree.
58163
+ * Write an output Container `container.config.json` to the Build Output
58164
+ * Specification tree.
57445
58165
  *
57446
- * Holds the project-level settings shared by every Worker: those declared by
57447
- * the `settings` export, including the `mode`, which is supplied at build time
57448
- * rather than declared. Always written, even when there are no declared
57449
- * settings and no mode: the result then degrades to `{ "type": "settings" }`.
58166
+ * Local Dockerfiles must already have been built and represented by a
58167
+ * `localReference` in the output config.
58168
+ */
58169
+ async function writeContainerConfig({ root, config: config$2, directoryName }) {
58170
+ await fsp.mkdir(getContainerDir(root, directoryName), { recursive: true });
58171
+ await fsp.writeFile(getContainerConfigPath(root, directoryName), JSON.stringify(config$2));
58172
+ }
58173
+ /**
58174
+ * Write the root `config.json` to the Build Output Specification tree.
57450
58175
  *
57451
- * `mode` is omitted when undefined, which is the case for Wrangler builds that
57452
- * selected no mode (Vite always resolves one).
58176
+ * Holds the settings declared at the top level of `cloudflare.config.ts` and
58177
+ * build context supplied at build time.
57453
58178
  */
57454
- async function writeSettingsConfig(root, settings, mode) {
58179
+ async function writeRootConfig(root, settings, buildContext) {
57455
58180
  const outputConfig = {
57456
58181
  ...settings,
57457
- type: "settings",
57458
- ...mode !== void 0 ? { mode } : {}
58182
+ buildContext
57459
58183
  };
57460
- const configPath = getSettingsConfigPath(root);
58184
+ const configPath = getRootConfigPath(root);
57461
58185
  await fsp.mkdir(path.dirname(configPath), { recursive: true });
57462
58186
  await fsp.writeFile(configPath, JSON.stringify(outputConfig));
57463
58187
  }
57464
58188
  const BUILD_OUTPUT_ERROR_PREFIX = "Build Output Specification: ";
57465
58189
  /**
57466
58190
  * Thrown when the Build Output Specification tree is missing, malformed, or
57467
- * fails schema validation while being read.
58191
+ * internally inconsistent.
57468
58192
  */
57469
58193
  var BuildOutputError = class extends Error {
57470
58194
  constructor(message) {
@@ -57473,43 +58197,51 @@ var BuildOutputError = class extends Error {
57473
58197
  }
57474
58198
  };
57475
58199
  /**
57476
- * Read and validate the Build Output Specification tree at
58200
+ * Read and parse the Build Output Specification tree at
57477
58201
  * `<root>/.cloudflare/output/v0/`.
57478
58202
  *
57479
- * Reads the optional top-level settings `config.json`, then reads and
57480
- * schema-validates each Worker and Container `config.json`, and resolves each
57481
- * Worker's `bundle/` / `assets/` directories. Partial manifests are resolved
57482
- * into complete manifests using the files in `bundle/`.
58203
+ * Reads the root `config.json`, then reads and parses each
58204
+ * `worker.config.json` and `container.config.json`, and resolves each Worker's
58205
+ * `bundle/` / `assets/` directories. Partial manifests are resolved into
58206
+ * complete manifests using the files in `bundle/`.
57483
58207
  *
57484
- * @throws {BuildOutputError} if the top-level `config.json` is invalid, or if
57485
- * a Worker or Container config is missing, is not valid JSON, or fails schema
57486
- * validation.
58208
+ * @throws {BuildOutputError} if the root `config.json` is missing or
58209
+ * invalid, or if a Worker or Container config is missing, is not valid JSON,
58210
+ * or does not match its schema.
57487
58211
  */
57488
58212
  async function readBuildOutput(root) {
57489
- const settings = await readSettings(root);
57490
- const defaultWorker = await readWorker(root, DEFAULT_WORKER_DIRECTORY_NAME);
57491
- const additionalWorkerDirectoryNames = (await fsp.readdir(getWorkersDir(root), { withFileTypes: true })).filter((entry) => entry.isDirectory() && entry.name !== DEFAULT_WORKER_DIRECTORY_NAME).map((entry) => entry.name).sort();
57492
- const additionalWorkers = await Promise.all(additionalWorkerDirectoryNames.map(async (workerDirectoryName) => [workerDirectoryName, await readWorker(root, workerDirectoryName)]));
58213
+ const absoluteRoot = path.resolve(root);
58214
+ const rootConfig = await readRootConfig(absoluteRoot);
58215
+ const [workers, containers] = await Promise.all([readWorkers(absoluteRoot), readContainers(absoluteRoot)]);
57493
58216
  return {
57494
- root,
58217
+ root: absoluteRoot,
57495
58218
  version: BUILD_OUTPUT_VERSION,
57496
- settings,
57497
- workers: {
57498
- default: defaultWorker,
57499
- ...Object.fromEntries(additionalWorkers)
57500
- },
57501
- containers: await readContainers(root)
58219
+ rootConfig,
58220
+ workers,
58221
+ containers
57502
58222
  };
57503
58223
  }
57504
- /** Read and schema-validate all Container configs, if any. */
58224
+ /** Read and parse the default Worker and any additional Worker configs. */
58225
+ async function readWorkers(root) {
58226
+ const workersDir = getWorkersDir(root);
58227
+ const defaultWorker = await readWorker(root, DEFAULT_WORKER_DIRECTORY_NAME);
58228
+ const additionalWorkerDirectoryNames = (await fsp.readdir(workersDir, { withFileTypes: true })).filter((entry) => entry.isDirectory() && entry.name !== DEFAULT_WORKER_DIRECTORY_NAME).map((entry) => entry.name);
58229
+ const additionalWorkers = await Promise.all(additionalWorkerDirectoryNames.map(async (workerDirectoryName) => {
58230
+ return [workerDirectoryName, await readWorker(root, workerDirectoryName)];
58231
+ }));
58232
+ return {
58233
+ default: defaultWorker,
58234
+ ...Object.fromEntries(additionalWorkers)
58235
+ };
58236
+ }
58237
+ /** Read and parse all Container configs, if any. */
57505
58238
  async function readContainers(root) {
57506
58239
  const containersDir = getContainersDir(root);
57507
- if (!fs$1.existsSync(containersDir)) return {};
57508
- const containerDirectoryNames = (await fsp.readdir(containersDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
57509
- const containers = await Promise.all(containerDirectoryNames.map(async (containerDirectoryName) => [containerDirectoryName, await readContainer(root, containerDirectoryName)]));
57510
- return Object.fromEntries(containers);
58240
+ if (!fs$1.existsSync(containersDir)) return [];
58241
+ const containerDirectoryNames = (await fsp.readdir(containersDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
58242
+ return Promise.all(containerDirectoryNames.map((containerDirectoryName) => readContainer(root, containerDirectoryName)));
57511
58243
  }
57512
- /** Read and schema-validate one Container config. */
58244
+ /** Read and parse one Container config. */
57513
58245
  async function readContainer(root, containerDirectoryName) {
57514
58246
  const configPath = getContainerConfigPath(root, containerDirectoryName);
57515
58247
  if (!fs$1.existsSync(configPath)) throw new BuildOutputError(`no Container config found at ${configPath}.`);
@@ -57522,12 +58254,12 @@ async function readContainer(root, containerDirectoryName) {
57522
58254
  };
57523
58255
  }
57524
58256
  /**
57525
- * Read and schema-validate the Worker's `config.json` and resolve its
58257
+ * Read and parse the Worker's `worker.config.json` and resolve its
57526
58258
  * `bundle/` / `assets/` directories.
57527
58259
  *
57528
58260
  * @returns the Worker, with whichever of its directories exist resolved.
57529
58261
  * @throws {BuildOutputError} if the config is missing, is not valid JSON, or
57530
- * fails schema validation.
58262
+ * does not match its schema.
57531
58263
  */
57532
58264
  async function readWorker(root, workerDirectoryName) {
57533
58265
  const configPath = getWorkerConfigPath(root, workerDirectoryName);
@@ -57608,23 +58340,18 @@ function inferModuleType(modulePath) {
57608
58340
  }
57609
58341
  }
57610
58342
  /**
57611
- * Read and schema-validate the optional top-level `config.json` holding the
57612
- * project-level settings shared by every Worker, including the mode the build
57613
- * was produced in.
57614
- *
57615
- * Returned whole: consumers that need only the settings the user declared
57616
- * narrow it themselves.
58343
+ * Read and parse the root `config.json`.
57617
58344
  *
57618
- * @returns the parsed settings, or `undefined` when the file is absent.
57619
- * @throws {BuildOutputError} if the file is not valid JSON or fails schema
57620
- * validation.
58345
+ * @returns the parsed root config.
58346
+ * @throws {BuildOutputError} if the file is missing, is not valid JSON, or
58347
+ * does not match its schema.
57621
58348
  */
57622
- async function readSettings(root) {
57623
- const configPath = getSettingsConfigPath(root);
57624
- if (!fs$1.existsSync(configPath)) return;
58349
+ async function readRootConfig(root) {
58350
+ const configPath = getRootConfigPath(root);
58351
+ if (!fs$1.existsSync(configPath)) throw new BuildOutputError(`no root config found at ${configPath}.`);
57625
58352
  const contents = await fsp.readFile(configPath, "utf-8");
57626
- const result = OutputSettingsSchema.safeParse(parseJson(contents, configPath));
57627
- if (!result.success) throw new BuildOutputError(`invalid settings config at ${configPath}.\n${result.error.message}`);
58353
+ const result = OutputRootConfigSchema.safeParse(parseJson(contents, configPath));
58354
+ if (!result.success) throw new BuildOutputError(`invalid root config at ${configPath}.\n${result.error.message}`);
57628
58355
  return result.data;
57629
58356
  }
57630
58357
  function parseJson(contents, configPath) {
@@ -57646,10 +58373,15 @@ function parseJson(contents, configPath) {
57646
58373
  * single-element array.
57647
58374
  */
57648
58375
  async function readBuildOutputWorkers(root) {
57649
- const { workers, settings } = await readBuildOutput(root);
58376
+ const { workers, rootConfig, containers } = await readBuildOutput(root);
57650
58377
  const worker = workers[DEFAULT_WORKER_DIRECTORY_NAME];
57651
58378
  const { manifest,...inputShape } = worker.config;
57652
- const { config: config$2, diagnostics } = normalizeAndValidateConfig(convertToWranglerConfig(inputShape, settings), void 0, void 0, {}, true);
58379
+ const { buildContext: _buildContext,...settings } = rootConfig;
58380
+ const { config: config$2, diagnostics } = normalizeAndValidateConfig(convertToWranglerConfig({
58381
+ ...settings,
58382
+ worker: inputShape,
58383
+ containers: containers.map(({ config: config$3 }) => convertOutputContainerToInput(config$3))
58384
+ }), void 0, void 0, { enableContainers: false }, true);
57653
58385
  if (diagnostics.hasWarnings()) console.warn(diagnostics.renderWarnings());
57654
58386
  if (diagnostics.hasErrors()) throw new Error(diagnostics.renderErrors());
57655
58387
  if (worker.assetsDir) config$2.assets = {
@@ -57671,6 +58403,19 @@ async function readBuildOutputWorkers(root) {
57671
58403
  bundle
57672
58404
  }];
57673
58405
  }
58406
+ function convertOutputContainerToInput(config$2) {
58407
+ if (config$2.schedulingPolicy === "durable-object") {
58408
+ const { images: _images,...container } = config$2;
58409
+ return container;
58410
+ }
58411
+ return {
58412
+ ...config$2,
58413
+ image: convertOutputContainerImage(config$2.image)
58414
+ };
58415
+ }
58416
+ function convertOutputContainerImage(image) {
58417
+ return { reference: "reference" in image ? image.reference : image.localReference };
58418
+ }
57674
58419
 
57675
58420
  //#endregion
57676
58421
  //#region src/deploy-config.ts
@@ -64398,8 +65143,8 @@ function readWorkerConfig(configPath, env$3) {
64398
65143
  * validation pipeline as on-disk Wrangler config files, then apply the
64399
65144
  * Vite-specific sanitization.
64400
65145
  */
64401
- function readWorkerConfigFromRaw(rawConfig) {
64402
- const { config: config$2, diagnostics } = normalizeAndValidateConfig(rawConfig, void 0, void 0, {}, true);
65146
+ function readWorkerConfigFromRaw(rawConfig, configPath) {
65147
+ const { config: config$2, diagnostics } = normalizeAndValidateConfig(rawConfig, configPath, configPath, {}, true);
64403
65148
  if (diagnostics.hasWarnings()) console.warn(diagnostics.renderWarnings());
64404
65149
  if (diagnostics.hasErrors()) throw new Error(diagnostics.renderErrors());
64405
65150
  return processNormalizedWorkerConfig(config$2);
@@ -64598,7 +65343,7 @@ function resolveWorkerConfig(options) {
64598
65343
  let workerConfig;
64599
65344
  let raw;
64600
65345
  let nonApplicable;
64601
- if (options.rawConfigOverride) ({raw, config: workerConfig, nonApplicable} = readWorkerConfigFromRaw(options.rawConfigOverride));
65346
+ if (options.rawConfigOverride) ({raw, config: workerConfig, nonApplicable} = readWorkerConfigFromRaw(options.rawConfigOverride, options.rawConfigPath));
64602
65347
  else if (options.configPath) ({raw, config: workerConfig, nonApplicable} = readWorkerConfigFromFile(options.configPath, options.env, { visitedConfigPaths: options.visitedConfigPaths }));
64603
65348
  else {
64604
65349
  workerConfig = { ...wrangler.unstable_defaultWranglerConfig };
@@ -64687,7 +65432,8 @@ async function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
64687
65432
  env: cloudflareEnv,
64688
65433
  configCustomizer: resolvedNewConfig ? void 0 : pluginConfig.config,
64689
65434
  visitedConfigPaths: configPaths,
64690
- rawConfigOverride
65435
+ rawConfigOverride,
65436
+ rawConfigPath: resolvedNewConfig ? configPath : void 0
64691
65437
  });
64692
65438
  const environmentNameToWorkerMap = /* @__PURE__ */ new Map();
64693
65439
  const environmentNameToChildEnvironmentNamesMap = /* @__PURE__ */ new Map();
@@ -64728,7 +65474,7 @@ async function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
64728
65474
  if (Array.isArray(entryWorkerResolvedConfig.config.assets?.run_worker_first)) staticRouting = parseStaticRouting(entryWorkerResolvedConfig.config.assets.run_worker_first);
64729
65475
  const entryWorkerEnvironmentName = pluginConfig.viteEnvironment?.name ?? workerNameToEnvironmentName(entryWorkerResolvedConfig.config.topLevelName);
64730
65476
  validateAndAddEnvironmentName(entryWorkerEnvironmentName);
64731
- const entryWorkerNewConfig = parsedNewConfig?.default?.type === "worker" ? parsedNewConfig.default : void 0;
65477
+ const entryWorkerNewConfig = parsedNewConfig?.worker;
64732
65478
  environmentNameToWorkerMap.set(entryWorkerEnvironmentName, resolveWorker(entryWorkerResolvedConfig.config, pluginConfig.assetsOnly, entryWorkerNewConfig));
64733
65479
  const entryWorkerChildEnvironments = pluginConfig.viteEnvironment?.childEnvironments;
64734
65480
  if (entryWorkerChildEnvironments) {
@@ -64818,11 +65564,14 @@ const EXPERIMENTAL_CONFIG_PKG = "@cloudflare/vite-plugin/experimental-config";
64818
65564
  async function loadNewConfig(options) {
64819
65565
  const configPath = path.resolve(options.root, NEW_CONFIG_FILENAME);
64820
65566
  if (!fs$1.existsSync(configPath)) throw new Error(`\`experimental.newConfig\` is enabled but no \`${NEW_CONFIG_FILENAME}\` was found at ${configPath}.`);
64821
- const { result, dependencies } = await loadAndValidateConfig(configPath, { mode: options.mode });
65567
+ const { result, dependencies } = await loadAndParseConfig(configPath, {
65568
+ isPreview: isPreviewBuild(),
65569
+ mode: options.mode
65570
+ });
64822
65571
  if (!result.success) throw new Error(`Invalid \`${NEW_CONFIG_FILENAME}\`:\n${result.error.message}`);
64823
- const worker = result.data.default?.type === "worker" ? result.data.default : void 0;
64824
- if (worker === void 0) throw new Error(`\`${NEW_CONFIG_FILENAME}\` must have a default worker export.`);
64825
- const rawConfig = convertToWranglerConfig(worker, result.data.settings?.type === "settings" ? result.data.settings : void 0);
65572
+ const worker = result.data.worker;
65573
+ if (worker === void 0) throw new Error(`\`${NEW_CONFIG_FILENAME}\` must define a Worker using the \`worker\` property.`);
65574
+ const rawConfig = convertToWranglerConfig(result.data);
64826
65575
  if (options.command === "serve" && options.types.generate) await writeWorkerConfigurationDts({
64827
65576
  root: options.root,
64828
65577
  configPath,
@@ -66691,14 +67440,13 @@ const buildOutputPlugin = createPlugin("build-output", (ctx) => {
66691
67440
  return { async writeBundle(_, bundle) {
66692
67441
  if (ctx.isChildEnvironment(this.environment.name)) return;
66693
67442
  if (ctx.resolvedPluginConfig.type === "assets-only" && this.environment.name === "client") {
66694
- const defaultExport = ctx.resolvedPluginConfig.parsedNewConfig?.default;
66695
- const workerNewConfig$1 = defaultExport?.type === "worker" ? defaultExport : void 0;
66696
- assert2(workerNewConfig$1, "Expected a default worker export on assets-only resolved config");
67443
+ const workerNewConfig$1 = ctx.resolvedPluginConfig.parsedNewConfig?.worker;
67444
+ assert2(workerNewConfig$1, "Expected a Worker on assets-only resolved config");
66697
67445
  await writeWorkerConfig({
66698
67446
  root: ctx.resolvedViteConfig.root,
66699
67447
  config: workerNewConfig$1
66700
67448
  });
66701
- await writeSettings();
67449
+ await writeRoot();
66702
67450
  return;
66703
67451
  }
66704
67452
  if (ctx.resolvedPluginConfig.type === "workers" && this.environment.name !== ctx.resolvedPluginConfig.entryWorkerEnvironmentName) return;
@@ -66723,20 +67471,26 @@ const buildOutputPlugin = createPlugin("build-output", (ctx) => {
66723
67471
  modules
66724
67472
  }
66725
67473
  });
66726
- await writeSettings();
67474
+ await writeRoot();
66727
67475
  } };
66728
67476
  /**
66729
- * Write the top-level `config.json`, recording the settings shared by every
67477
+ * Write the root `config.json`, recording the settings shared by every
66730
67478
  * Worker, including the Vite mode the build ran in.
66731
67479
  *
66732
- * Written even when there is no `settings` export, so the mode is always
66733
- * captured.
67480
+ * Written even when there are no account settings, so the build context is
67481
+ * always captured.
66734
67482
  */
66735
- async function writeSettings() {
67483
+ async function writeRoot() {
66736
67484
  if (ctx.resolvedPluginConfig.type === "preview") return;
66737
- const settingsExport = ctx.resolvedPluginConfig.parsedNewConfig?.settings;
66738
- const settings = settingsExport?.type === "settings" ? settingsExport : void 0;
66739
- await writeSettingsConfig(ctx.resolvedViteConfig.root, settings, ctx.resolvedViteConfig.mode);
67485
+ const config$2 = ctx.resolvedPluginConfig.parsedNewConfig;
67486
+ const settings = config$2 && {
67487
+ accountId: config$2.accountId,
67488
+ complianceRegion: config$2.complianceRegion
67489
+ };
67490
+ await writeRootConfig(ctx.resolvedViteConfig.root, settings, {
67491
+ isPreview: isPreviewBuild(),
67492
+ mode: ctx.resolvedViteConfig.mode
67493
+ });
66740
67494
  }
66741
67495
  });
66742
67496
  /**
@@ -68935,392 +69689,6 @@ function removeAssetsField(entryWorkerBuildDirectory) {
68935
69689
  fs$1.writeFileSync(entryWorkerConfigPath, JSON.stringify(workerConfig));
68936
69690
  }
68937
69691
 
68938
- //#endregion
68939
- //#region src/dev-vars.ts
68940
- /**
68941
- * Gets any variables with which to augment the Worker config in preview mode.
68942
- *
68943
- * Calls `unstable_getVarsForDev` with the current Cloudflare environment to get local dev variables from the .dev.vars/.env/process.env.
68944
- * When `secrets` is defined in the Worker config, only declared secrets are loaded.
68945
- */
68946
- function getLocalDevVarsForPreview(config$2, cloudflareEnv) {
68947
- const dotDevDotVars = wrangler.unstable_getVarsForDev(config$2.configPath, void 0, {}, cloudflareEnv, false, config$2.secrets);
68948
- const dotDevDotVarsEntries = Array.from(Object.entries(dotDevDotVars));
68949
- if (dotDevDotVarsEntries.length > 0) return dotDevDotVarsEntries.map(([key, { value }]) => {
68950
- return `${key}=${quoteForDotenv(value?.toString() ?? "")}\n`;
68951
- }).join("");
68952
- }
68953
- /**
68954
- * Quote a value so that wrangler reads it back unchanged when it parses
68955
- * `dist/<env>/.dev.vars` at preview time.
68956
- *
68957
- * Strategy: To quote the string pick the first quote character that does not
68958
- * appear in the value (single → backtick → double). Throw if a value cannot
68959
- * be losslessly serialized rather than silently corrupting it.
68960
- *
68961
- * @internal exported for tests
68962
- */
68963
- function quoteForDotenv(value) {
68964
- if (!value.includes("'")) return `'${value}'`;
68965
- if (!value.includes("`")) return `\`${value}\``;
68966
- if (!value.includes("\"") && !/[\\\n\r]/.test(value)) return `"${value}"`;
68967
- throw new Error("Unable to serialize value to .dev.vars: contains every supported quote character or unsafe escape sequence.");
68968
- }
68969
- /**
68970
- * Returns `true` if the `changedFile` matches a `.dev.vars` or `.env` file.
68971
- */
68972
- function hasLocalDevVarsFileChanged({ configPaths, cloudflareEnv }, changedFilePath) {
68973
- return [...configPaths].some((configPath) => {
68974
- const configDir = path.dirname(configPath);
68975
- return [
68976
- ".dev.vars",
68977
- ".env",
68978
- ...cloudflareEnv ? [`.dev.vars.${cloudflareEnv}`, `.env.${cloudflareEnv}`] : []
68979
- ].some((localDevFile) => changedFilePath === path.join(configDir, localDevFile));
68980
- });
68981
- }
68982
-
68983
- //#endregion
68984
- //#region src/vite-config.ts
68985
- const NODE_BUILTIN_SET = new Set([...builtinModules, ...builtinModules.filter((m) => !m.startsWith("node:")).map((m) => `node:${m}`)]);
68986
- function isOnlyNodeBuiltins(external) {
68987
- if (!Array.isArray(external)) return false;
68988
- return external.every((entry) => typeof entry === "string" && NODE_BUILTIN_SET.has(entry));
68989
- }
68990
- /**
68991
- * Throws an error if Worker environments include configuration options that are incompatible with the plugin.
68992
- */
68993
- function validateWorkerEnvironmentOptions(resolvedPluginConfig, resolvedViteConfig) {
68994
- const disallowedEnvironmentOptionsMap = /* @__PURE__ */ new Map();
68995
- for (const environmentName of resolvedPluginConfig.environmentNameToWorkerMap.keys()) {
68996
- const environmentOptions = resolvedViteConfig.environments[environmentName];
68997
- assert2(environmentOptions, `Missing environment config for "${environmentName}"`);
68998
- const { resolve: resolve$4 } = environmentOptions;
68999
- const disallowedEnvironmentOptions = {};
69000
- if ((resolve$4.external === true || Array.isArray(resolve$4.external) && resolve$4.external.length > 0) && !isOnlyNodeBuiltins(resolve$4.external)) disallowedEnvironmentOptions.resolveExternal = resolve$4.external;
69001
- if (Object.keys(disallowedEnvironmentOptions).length) disallowedEnvironmentOptionsMap.set(environmentName, disallowedEnvironmentOptions);
69002
- }
69003
- if (disallowedEnvironmentOptionsMap.size) {
69004
- const errorMessage = `The following environment options are incompatible with the Cloudflare Vite plugin:\n${[...disallowedEnvironmentOptionsMap].map(([environmentName, disallowedEnvironmentOptions]) => disallowedEnvironmentOptions.resolveExternal && ` - "${environmentName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedEnvironmentOptions.resolveExternal)}\n`).join("")}To resolve this issue, avoid setting \`resolve.external\` in your Cloudflare Worker environments.\n`;
69005
- throw new Error(errorMessage);
69006
- }
69007
- }
69008
-
69009
- //#endregion
69010
- //#region src/plugins/wrangler-watch-ignore.ts
69011
- const WRANGLER_STATE_WATCH_IGNORE = "**/.wrangler/**";
69012
- /**
69013
- * Keep Miniflare persistence writes out of Vite's file watcher without
69014
- * replacing any ignore patterns the user already configured.
69015
- *
69016
- * @param userIgnored - Existing `server.watch.ignored` patterns, if any
69017
- * @returns Ignore patterns that always include `.wrangler` directories
69018
- */
69019
- function withWranglerStateIgnored(userIgnored) {
69020
- if (userIgnored == null) return WRANGLER_STATE_WATCH_IGNORE;
69021
- if (Array.isArray(userIgnored)) return [...userIgnored, WRANGLER_STATE_WATCH_IGNORE];
69022
- return [userIgnored, WRANGLER_STATE_WATCH_IGNORE];
69023
- }
69024
- /**
69025
- * Merge `.wrangler` into Vite's `server.watch` config.
69026
- *
69027
- * Returns `null` when the user disabled watching with `server.watch: null`,
69028
- * so this plugin does not turn the watcher back on.
69029
- *
69030
- * @param userWatch - The user's `server.watch` value from Vite config
69031
- * @returns `null` when watching is disabled, otherwise a watch object whose
69032
- * `ignored` list includes `.wrangler` directories
69033
- */
69034
- function getServerWatchConfig(userWatch) {
69035
- if (userWatch === null) return null;
69036
- return {
69037
- ...userWatch,
69038
- ignored: withWranglerStateIgnored(userWatch?.ignored)
69039
- };
69040
- }
69041
-
69042
- //#endregion
69043
- //#region src/plugins/config.ts
69044
- /**
69045
- * Plugin to handle configuration and config file watching
69046
- */
69047
- const configPlugin = createPlugin("config", (ctx) => {
69048
- return {
69049
- config(userConfig, env$3) {
69050
- if (ctx.resolvedPluginConfig.type === "preview") return { appType: "custom" };
69051
- if (!ctx.hasShownWorkerConfigWarnings) {
69052
- ctx.setHasShownWorkerConfigWarnings(true);
69053
- const workerConfigWarnings = getWarningForWorkersConfigs(ctx.resolvedPluginConfig.rawConfigs);
69054
- if (workerConfigWarnings) console.warn(workerConfigWarnings);
69055
- }
69056
- return {
69057
- appType: "custom",
69058
- server: {
69059
- allowedHosts: getAllowedHosts(ctx.getTunnelHostnames(), userConfig.server?.allowedHosts),
69060
- watch: getServerWatchConfig(userConfig.server?.watch),
69061
- fs: { deny: [...[
69062
- ".env",
69063
- ".env.*",
69064
- ".npmrc",
69065
- ".yarnrc",
69066
- ".yarnrc.yml",
69067
- "*.{crt,pem,key,pfx,p12,p8,jks}",
69068
- "**/.git/**",
69069
- ".dev.vars",
69070
- ".dev.vars.*",
69071
- "**/.wrangler/**"
69072
- ], ...Array.from(ctx.resolvedPluginConfig.configPaths, (configPath) => normalizePath(configPath))] }
69073
- },
69074
- environments: getEnvironmentsConfig(ctx, userConfig, env$3.mode),
69075
- builder: { buildApp: userConfig.builder?.buildApp ?? createBuildApp(ctx.resolvedPluginConfig) }
69076
- };
69077
- },
69078
- async configResolved(resolvedViteConfig) {
69079
- ctx.setResolvedViteConfig(resolvedViteConfig);
69080
- if (ctx.resolvedPluginConfig.type === "preview") return;
69081
- validateWorkerEnvironmentOptions(ctx.resolvedPluginConfig, ctx.resolvedViteConfig);
69082
- if (ctx.resolvedPluginConfig.experimental.newConfig?.cfBuildOutput) {
69083
- forceBuildOutputDirs(ctx.resolvedPluginConfig, ctx.resolvedViteConfig);
69084
- if (ctx.resolvedViteConfig.command === "build") await cleanBuildOutputDir(ctx.resolvedViteConfig.root);
69085
- }
69086
- },
69087
- buildStart() {
69088
- ctx.setHasShownWorkerConfigWarnings(false);
69089
- },
69090
- configureServer(viteDevServer) {
69091
- let restartInFlight = false;
69092
- const configChangedHandler = async (changedFilePath) => {
69093
- assertIsNotPreview(ctx);
69094
- if (restartInFlight) return;
69095
- if (ctx.resolvedPluginConfig.configPaths.has(changedFilePath) || hasLocalDevVarsFileChanged(ctx.resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(ctx.resolvedPluginConfig, ctx.resolvedViteConfig, changedFilePath)) {
69096
- debuglog("Config changed: " + changedFilePath);
69097
- restartInFlight = true;
69098
- debuglog("Restarting dev server and aborting previous setup");
69099
- try {
69100
- await viteDevServer.restart();
69101
- } finally {
69102
- restartInFlight = false;
69103
- }
69104
- }
69105
- };
69106
- viteDevServer.watcher.on("change", configChangedHandler);
69107
- },
69108
- buildApp: {
69109
- order: "post",
69110
- async handler(builder) {
69111
- if (ctx.resolvedPluginConfig.type !== "workers") return;
69112
- const workerEnvironments = [...ctx.resolvedPluginConfig.environmentNameToWorkerMap.entries()].filter(([_, worker]) => !resolveDevOnly(worker.devOnly)).map(([environmentName]) => {
69113
- const environment = builder.environments[environmentName];
69114
- assert2(environment, `"${environmentName}" environment not found`);
69115
- return environment;
69116
- });
69117
- await Promise.all(workerEnvironments.filter((environment) => !environment.isBuilt).map((environment) => builder.build(environment)));
69118
- const { entryWorkerEnvironmentName } = ctx.resolvedPluginConfig;
69119
- const entryWorkerEnvironment = builder.environments[entryWorkerEnvironmentName];
69120
- assert2(entryWorkerEnvironment, `No "${entryWorkerEnvironmentName}" environment`);
69121
- const cfBuildOutput = ctx.resolvedPluginConfig.experimental.newConfig?.cfBuildOutput === true;
69122
- if (entryWorkerEnvironment.isBuilt) {
69123
- if (!builder.environments.client?.isBuilt && !cfBuildOutput) removeAssetsField(path.resolve(builder.config.root, entryWorkerEnvironment.config.build.outDir));
69124
- } else {
69125
- const clientEnvironment = builder.environments.client;
69126
- assert2(clientEnvironment, "No \"client\" environment");
69127
- if (!clientEnvironment.isBuilt) throw new Error("If `assetsOnly` is set to `true`, the client environment must be built");
69128
- if (cfBuildOutput) {
69129
- const entryWorkerNewConfig = ctx.getWorkerNewConfig(entryWorkerEnvironmentName);
69130
- assert2(entryWorkerNewConfig, `No config found for "${entryWorkerEnvironmentName}" environment`);
69131
- await writeWorkerConfig({
69132
- root: builder.config.root,
69133
- config: entryWorkerNewConfig
69134
- });
69135
- } else {
69136
- const entryWorkerConfig = ctx.getWorkerConfig(entryWorkerEnvironmentName);
69137
- assert2(entryWorkerConfig, `No config found for "${entryWorkerEnvironmentName}" environment`);
69138
- const outputConfig = {
69139
- ...entryWorkerConfig,
69140
- main: void 0,
69141
- assets: {
69142
- ...entryWorkerConfig.assets,
69143
- directory: ".",
69144
- binding: void 0
69145
- }
69146
- };
69147
- if (outputConfig.unsafe && Object.keys(outputConfig.unsafe).length === 0) outputConfig.unsafe = void 0;
69148
- fs$1.writeFileSync(path.resolve(builder.config.root, clientEnvironment.config.build.outDir, "wrangler.json"), JSON.stringify(outputConfig));
69149
- writeDeployConfig(ctx.resolvedPluginConfig, ctx.resolvedViteConfig, true);
69150
- }
69151
- }
69152
- }
69153
- }
69154
- };
69155
- });
69156
- /**
69157
- * Generates the environment configuration for all Worker environments.
69158
- */
69159
- function getEnvironmentsConfig(ctx, userConfig, mode) {
69160
- assertIsNotPreview(ctx);
69161
- if (!ctx.resolvedPluginConfig.environmentNameToWorkerMap.size) return;
69162
- return {
69163
- ...Object.fromEntries([...ctx.resolvedPluginConfig.environmentNameToWorkerMap].flatMap(([environmentName, worker]) => {
69164
- const childEnvironmentNames = ctx.resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap.get(environmentName) ?? [];
69165
- const sharedOptions = {
69166
- workerConfig: worker.config,
69167
- userConfig,
69168
- mode,
69169
- hasNodeJsCompat: ctx.getNodeJsCompat(environmentName) !== void 0
69170
- };
69171
- const isEntryWorker = environmentName === ctx.resolvedPluginConfig.prerenderWorkerEnvironmentName || ctx.resolvedPluginConfig.type === "workers" && environmentName === ctx.resolvedPluginConfig.entryWorkerEnvironmentName;
69172
- return [[environmentName, createCloudflareEnvironmentOptions({
69173
- ...sharedOptions,
69174
- environmentName,
69175
- isEntryWorker,
69176
- isParentEnvironment: true
69177
- })], ...childEnvironmentNames.map((childEnvironmentName) => [childEnvironmentName, createCloudflareEnvironmentOptions({
69178
- ...sharedOptions,
69179
- environmentName: childEnvironmentName,
69180
- isEntryWorker: false,
69181
- isParentEnvironment: false
69182
- })])];
69183
- })),
69184
- client: {
69185
- build: { outDir: getOutputDirectory(userConfig, "client") },
69186
- optimizeDeps: { exclude: [...cloudflareBuiltInModules] }
69187
- }
69188
- };
69189
- }
69190
- /**
69191
- * When the Build Output Specification is enabled,
69192
- * force every Worker environment's and the client environment's `build.outDir`
69193
- * to the spec-mandated location.
69194
- *
69195
- * Runs after Vite's merge in `configResolved`, so it overrides any
69196
- * user-supplied `build.outDir`
69197
- */
69198
- function forceBuildOutputDirs(resolvedPluginConfig, resolvedViteConfig) {
69199
- if (!resolvedPluginConfig.experimental.newConfig?.cfBuildOutput) return;
69200
- const { root } = resolvedViteConfig;
69201
- if (resolvedPluginConfig.type === "workers") {
69202
- const entryName = resolvedPluginConfig.entryWorkerEnvironmentName;
69203
- const entryEnvironment = resolvedViteConfig.environments[entryName];
69204
- if (entryEnvironment) entryEnvironment.build.outDir = getWorkerBundleDir(root);
69205
- }
69206
- const clientEnvironment = resolvedViteConfig.environments.client;
69207
- if (clientEnvironment) clientEnvironment.build.outDir = getWorkerAssetsDir(root);
69208
- }
69209
- function getAllowedHosts(tunnelHostnames, userAllowedHosts) {
69210
- if (tunnelHostnames.length === 0 || userAllowedHosts === true) return userAllowedHosts;
69211
- return Array.from(new Set([...userAllowedHosts ?? [], ...tunnelHostnames]));
69212
- }
69213
-
69214
- //#endregion
69215
- //#region src/debug.ts
69216
- var import_picocolors$3 = /* @__PURE__ */ __toESM$1(require_picocolors(), 1);
69217
- const DEBUG_PATH = "/__debug";
69218
- const DEFAULT_INSPECTOR_PORT = 9229;
69219
- /**
69220
- * Gets the inspector port option that should be passed to Miniflare based on the user's plugin config
69221
- */
69222
- async function getInputInspectorPort(ctx, viteServer) {
69223
- if (ctx.resolvedPluginConfig.inspectorPort === void 0 || ctx.resolvedPluginConfig.inspectorPort === 0) {
69224
- const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
69225
- if (resolvedInspectorPort !== null) return resolvedInspectorPort;
69226
- }
69227
- const inputInspectorPort = ctx.resolvedPluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
69228
- if (ctx.resolvedPluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) viteServer.config.logger.warn(import_picocolors$3.default.dim(`Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead\n`));
69229
- return inputInspectorPort;
69230
- }
69231
- function getFirstAvailablePort(start) {
69232
- return getPorts({ port: portNumbers(start, 65535) });
69233
- }
69234
- /**
69235
- * Modifies the URL printing logic to also include a URL that developers can use to open DevTools to debug their Worker(s)
69236
- */
69237
- function addDebugToVitePrintUrls(server) {
69238
- const originalPrintUrls = server.printUrls;
69239
- server.printUrls = () => {
69240
- originalPrintUrls();
69241
- const localUrl = server.resolvedUrls?.local[0];
69242
- if (localUrl) {
69243
- const { protocol, hostname: hostname$1, port } = new URL(localUrl);
69244
- const colorDebugUrl = (url$2) => import_picocolors$3.default.dim(import_picocolors$3.default.yellow(url$2.replace(/:(\d+)\//, (_, portNumber) => `:${import_picocolors$3.default.bold(portNumber)}/`)));
69245
- server.config.logger.info(` ${import_picocolors$3.default.green("➜")} ${import_picocolors$3.default.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname$1}:${port}${DEBUG_PATH}`)}`);
69246
- }
69247
- };
69248
- }
69249
- /**
69250
- * Generate HTML that comprises a single script that:
69251
- * - redirects the page to the DevTools for debugging the first available Worker
69252
- * - opens tabs to the DevTools for all the remaining workers if any
69253
- *
69254
- * Note: this works based on the Miniflare inspector proxy logic (where Workers are available via
69255
- * their names)
69256
- */
69257
- function getDebugPathHtml(workerNames, inspectorPort) {
69258
- assert2(workerNames.length >= 1, "no workers present to debug");
69259
- const workerDevtoolsUrls = workerNames.map((workerName) => {
69260
- const localhost = `localhost:${inspectorPort}/${workerName}`;
69261
- return `https://devtools.devprod.cloudflare.dev/js_app?${new URLSearchParams({
69262
- theme: "systemPreferred",
69263
- debugger: "true",
69264
- ws: localhost,
69265
- domain: workerName
69266
- })}`;
69267
- });
69268
- return `
69269
- <script>
69270
- const workerUrls = ${JSON.stringify(workerDevtoolsUrls)};
69271
- const [firstUrl, ...rest] = workerUrls;
69272
- for (const workerUrl of rest) {
69273
- // open new tabs for the devtools of the various workers
69274
- window.open(workerUrl);
69275
- }
69276
- // redirect the current tab to the devtools of the first worker
69277
- window.location.replace(firstUrl);
69278
- <\/script>
69279
- `;
69280
- }
69281
-
69282
- //#endregion
69283
- //#region src/plugins/debug.ts
69284
- /**
69285
- * Plugin to provide a `/__debug` path for debugging Workers
69286
- */
69287
- const debugPlugin = createPlugin("debug", (ctx) => {
69288
- return {
69289
- enforce: "pre",
69290
- configureServer(viteDevServer) {
69291
- assertIsNotPreview(ctx);
69292
- if (!!process.env.VSCODE_INSPECTOR_OPTIONS) return;
69293
- if (ctx.resolvedPluginConfig.type === "workers" && ctx.resolvedPluginConfig.inspectorPort !== false) addDebugToVitePrintUrls(viteDevServer);
69294
- const workerNames = ctx.resolvedPluginConfig.type === "workers" ? [...ctx.resolvedPluginConfig.environmentNameToWorkerMap.values()].map((worker) => worker.config.name) : [];
69295
- viteDevServer.middlewares.use(DEBUG_PATH, async (_, res, next) => {
69296
- const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
69297
- if (resolvedInspectorPort) {
69298
- const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
69299
- res.setHeader("Content-Type", "text/html");
69300
- res.end(html);
69301
- } else next();
69302
- });
69303
- },
69304
- async configurePreviewServer(vitePreviewServer) {
69305
- assertIsPreview(ctx);
69306
- if (!!process.env.VSCODE_INSPECTOR_OPTIONS) return;
69307
- if (ctx.resolvedPluginConfig.workers.length >= 1 && ctx.resolvedPluginConfig.inspectorPort !== false) addDebugToVitePrintUrls(vitePreviewServer);
69308
- const workerNames = ctx.resolvedPluginConfig.workers.map((worker) => {
69309
- assert2(worker.config.name, "Expected the Worker to have a name");
69310
- return worker.config.name;
69311
- });
69312
- vitePreviewServer.middlewares.use(DEBUG_PATH, async (_, res, next) => {
69313
- const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
69314
- if (resolvedInspectorPort) {
69315
- const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
69316
- res.setHeader("Content-Type", "text/html");
69317
- res.end(html);
69318
- } else next();
69319
- });
69320
- }
69321
- };
69322
- });
69323
-
69324
69692
  //#endregion
69325
69693
  //#region ../cli/dist/colors.mjs
69326
69694
  const { white, gray, dim, hidden, bold, cyanBright, bgCyan } = source_default;
@@ -72024,11 +72392,11 @@ var getQueryString = /* @__PURE__ */ __name$2((params) => {
72024
72392
  }, "getQueryString");
72025
72393
  var getUrl = /* @__PURE__ */ __name$2((config$2, options) => {
72026
72394
  const encoder$1 = config$2.ENCODE_PATH || encodeURI;
72027
- const path2 = options.url.replace("{api-version}", config$2.VERSION).replace(/{(.*?)}/g, (substring, group) => {
72395
+ const path3 = options.url.replace("{api-version}", config$2.VERSION).replace(/{(.*?)}/g, (substring, group) => {
72028
72396
  if (options.path?.hasOwnProperty(group)) return encoder$1(String(options.path[group]));
72029
72397
  return substring;
72030
72398
  });
72031
- const url$2 = `${config$2.BASE}${path2}`;
72399
+ const url$2 = `${config$2.BASE}${path3}`;
72032
72400
  if (options.query) return `${url$2}${getQueryString(options.query)}`;
72033
72401
  return url$2;
72034
72402
  }, "getUrl");
@@ -73826,31 +74194,6 @@ async function dockerLoginImageRegistry(pathToDocker, domain$1) {
73826
74194
  });
73827
74195
  }
73828
74196
  __name$2(dockerLoginImageRegistry, "dockerLoginImageRegistry");
73829
- async function dockerImageInspect(dockerPath, options) {
73830
- return new Promise((resolve2, reject) => {
73831
- const proc = spawn(dockerPath, [
73832
- "image",
73833
- "inspect",
73834
- options.imageTag,
73835
- "--format",
73836
- options.formatString
73837
- ], { stdio: [
73838
- "ignore",
73839
- "pipe",
73840
- "pipe"
73841
- ] });
73842
- let stdout$2 = "";
73843
- let stderr$1 = "";
73844
- proc.stdout.on("data", (chunk) => stdout$2 += chunk);
73845
- proc.stderr.on("data", (chunk) => stderr$1 += chunk);
73846
- proc.on("close", (code) => {
73847
- if (code !== 0) return reject(new UserError(`failed inspecting image locally: ${stderr$1.trim()}`, { telemetryMessage: false }));
73848
- resolve2(stdout$2.trim());
73849
- });
73850
- proc.on("error", (err) => reject(err));
73851
- });
73852
- }
73853
- __name$2(dockerImageInspect, "dockerImageInspect");
73854
74197
  var runDockerCmd = /* @__PURE__ */ __name$2((dockerPath, args, stdio) => {
73855
74198
  let aborted$2 = false;
73856
74199
  let resolve2;
@@ -74008,15 +74351,6 @@ var getContainerIdsFromImage = /* @__PURE__ */ __name$2((dockerPath, ancestorIma
74008
74351
  "{{.ID}}"
74009
74352
  ]).split("\n").filter((line) => line.trim());
74010
74353
  }, "getContainerIdsFromImage");
74011
- async function checkExposedPorts(dockerPath, options) {
74012
- if (await dockerImageInspect(dockerPath, {
74013
- imageTag: options.image_tag,
74014
- formatString: "{{ len .Config.ExposedPorts }}"
74015
- }) === "0") throw new UserError(`The container "${options.image_name === void 0 ? options.class_name : `${options.class_name}.${options.image_name}`}" does not expose any ports. In your Dockerfile, please expose any ports you intend to connect to.
74016
- For additional information please see: https://developers.cloudflare.com/containers/local-dev/#exposing-ports.
74017
- `, { telemetryMessage: false });
74018
- }
74019
- __name$2(checkExposedPorts, "checkExposedPorts");
74020
74354
  function generateContainerBuildId() {
74021
74355
  return randomUUID().slice(0, 8);
74022
74356
  }
@@ -74136,7 +74470,6 @@ async function prepareContainerImagesForDev(args) {
74136
74470
  onContainerImagePreparationEnd({ containerOptions: options });
74137
74471
  }
74138
74472
  if (aborted$2) break;
74139
- await checkExposedPorts(dockerPath, options);
74140
74473
  }
74141
74474
  if (!aborted$2) await pullEgressInterceptorImage(dockerPath);
74142
74475
  return { aborted: aborted$2 };
@@ -74223,6 +74556,31 @@ function validateAndEncodeGarKey(rawKey, expectedEmail) {
74223
74556
  return base64Key;
74224
74557
  }
74225
74558
  __name$2(validateAndEncodeGarKey, "validateAndEncodeGarKey");
74559
+ async function dockerImageInspect(dockerPath, options) {
74560
+ return new Promise((resolve2, reject) => {
74561
+ const proc = spawn(dockerPath, [
74562
+ "image",
74563
+ "inspect",
74564
+ options.imageTag,
74565
+ "--format",
74566
+ options.formatString
74567
+ ], { stdio: [
74568
+ "ignore",
74569
+ "pipe",
74570
+ "pipe"
74571
+ ] });
74572
+ let stdout$2 = "";
74573
+ let stderr$1 = "";
74574
+ proc.stdout.on("data", (chunk) => stdout$2 += chunk);
74575
+ proc.stderr.on("data", (chunk) => stderr$1 += chunk);
74576
+ proc.on("close", (code) => {
74577
+ if (code !== 0) return reject(new UserError(`failed inspecting image locally: ${stderr$1.trim()}`, { telemetryMessage: false }));
74578
+ resolve2(stdout$2.trim());
74579
+ });
74580
+ proc.on("error", (err) => reject(err));
74581
+ });
74582
+ }
74583
+ __name$2(dockerImageInspect, "dockerImageInspect");
74226
74584
  var MB = 1e3 * 1e3;
74227
74585
  var MiB = 1024 * 1024;
74228
74586
  var instanceTypes = {
@@ -74349,6 +74707,11 @@ async function getContainerAccount(accountId, complianceConfig) {
74349
74707
  return await fetchResult$1(complianceConfig ?? {}, `/accounts/${accountId}/containers/me`);
74350
74708
  }
74351
74709
  __name$2(getContainerAccount, "getContainerAccount");
74710
+ var MAX_DOCKER_REPOSITORY_NAME_LENGTH = 255;
74711
+ function normalizeContainerImageRepositoryName(value) {
74712
+ return value.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/[._-]+/g, (separators) => separators === "." || separators === "_" || separators === "__" || /^-+$/.test(separators) ? separators : "-").replace(/^[._-]+|[._-]+$/g, "").slice(0, MAX_DOCKER_REPOSITORY_NAME_LENGTH).replace(/[._-]+$/g, "") || "container";
74713
+ }
74714
+ __name$2(normalizeContainerImageRepositoryName, "normalizeContainerImageRepositoryName");
74352
74715
  function isDockerfileContainerConfig(container) {
74353
74716
  return "dockerfile" in container;
74354
74717
  }
@@ -74591,7 +74954,7 @@ async function buildAndMaybePush(args, pathToDocker, push, containerConfig, veri
74591
74954
  }
74592
74955
  __name$2(buildAndMaybePush, "buildAndMaybePush");
74593
74956
  async function buildContainerImage(containerConfig, pathToDocker, verifyDockerIsRunning) {
74594
- const localTag = `${getContainerImageRepositoryName(containerConfig)}:wrangler-${crypto$1.randomUUID()}`;
74957
+ const localTag = `${getContainerImageRepositoryName(containerConfig)}:wrangler-${crypto2.randomUUID()}`;
74595
74958
  logger$1.log("Building image", localTag);
74596
74959
  try {
74597
74960
  await (await startContainerBuild({
@@ -74729,6 +75092,171 @@ async function dockerBuild(dockerPath, options) {
74729
75092
  };
74730
75093
  }
74731
75094
  __name$2(dockerBuild, "dockerBuild");
75095
+ var BUILD_OUTPUT_IMAGE_NAMESPACE = "cloudflare-build";
75096
+ var DOCKER_REPOSITORY_NAME_LENGTH = 255;
75097
+ async function buildAndWriteContainerOutput(options) {
75098
+ const localTags = /* @__PURE__ */ new Set();
75099
+ try {
75100
+ const containers = resolveContainerDirectories(options.containers);
75101
+ await cleanupPreviousBuildOutputImageTags({
75102
+ root: options.root,
75103
+ pathToDocker: options.pathToDocker
75104
+ });
75105
+ const buildId = createBuildId();
75106
+ const dockerfileCount = countDockerfiles(options.containers);
75107
+ if (dockerfileCount > 0) await verifyDockerInstalled({
75108
+ dockerPath: options.pathToDocker,
75109
+ operation: "building the project",
75110
+ imageNoun: dockerfileCount === 1 ? "the configured image" : "the configured images"
75111
+ });
75112
+ const outputConfigs = [];
75113
+ try {
75114
+ for (const { config: config$2, directoryName } of containers) outputConfigs.push({
75115
+ root: options.root,
75116
+ directoryName,
75117
+ config: await buildContainerOutputConfig({
75118
+ config: config$2,
75119
+ root: options.root,
75120
+ pathToDocker: options.pathToDocker,
75121
+ buildId,
75122
+ localTags
75123
+ })
75124
+ });
75125
+ } catch (error$2) {
75126
+ throwBuildError(error$2);
75127
+ }
75128
+ for (const outputConfig of outputConfigs) await writeContainerConfig(outputConfig);
75129
+ } catch (error$2) {
75130
+ await Promise.allSettled([cleanBuildOutputDir(options.root), cleanupBuiltImages(Array.from(localTags, (localTag) => ({ localTag })), options.pathToDocker)]);
75131
+ throw error$2;
75132
+ }
75133
+ }
75134
+ __name$2(buildAndWriteContainerOutput, "buildAndWriteContainerOutput");
75135
+ function resolveContainerDirectories(containers) {
75136
+ const containerNameByDirectory = /* @__PURE__ */ new Map();
75137
+ return containers.map((config$2) => {
75138
+ const directoryName = normalizeDirectoryName(config$2.name);
75139
+ const conflictingName = containerNameByDirectory.get(directoryName);
75140
+ if (conflictingName !== void 0) throw new UserError(`Container names ${JSON.stringify(conflictingName)} and ${JSON.stringify(config$2.name)} resolve to the same Build Output directory ${JSON.stringify(directoryName)}. Rename one of the Containers.`, { telemetryMessage: "container build output directory name conflict" });
75141
+ containerNameByDirectory.set(directoryName, config$2.name);
75142
+ return {
75143
+ config: config$2,
75144
+ directoryName
75145
+ };
75146
+ });
75147
+ }
75148
+ __name$2(resolveContainerDirectories, "resolveContainerDirectories");
75149
+ async function buildContainerOutputConfig(options) {
75150
+ if (options.config.schedulingPolicy === "durable-object") {
75151
+ if (options.config.images === void 0) return {
75152
+ ...options.config,
75153
+ images: void 0
75154
+ };
75155
+ const images = {};
75156
+ for (const [imageName, image2] of Object.entries(options.config.images)) images[imageName] = await buildContainerImage2({
75157
+ image: image2,
75158
+ repositoryName: `${options.config.name}-${imageName}`,
75159
+ root: options.root,
75160
+ pathToDocker: options.pathToDocker,
75161
+ buildId: options.buildId,
75162
+ localTags: options.localTags
75163
+ });
75164
+ return {
75165
+ ...options.config,
75166
+ images
75167
+ };
75168
+ }
75169
+ const image = await buildContainerImage2({
75170
+ image: options.config.image,
75171
+ repositoryName: options.config.name,
75172
+ root: options.root,
75173
+ pathToDocker: options.pathToDocker,
75174
+ buildId: options.buildId,
75175
+ localTags: options.localTags
75176
+ });
75177
+ return {
75178
+ ...options.config,
75179
+ image
75180
+ };
75181
+ }
75182
+ __name$2(buildContainerOutputConfig, "buildContainerOutputConfig");
75183
+ async function buildContainerImage2(options) {
75184
+ if ("reference" in options.image) return { reference: options.image.reference };
75185
+ const pathToDockerfile = path__default.resolve(options.root, options.image.dockerfile);
75186
+ const localTag = createBuildOutputImageTag({
75187
+ root: options.root,
75188
+ repositoryName: options.repositoryName,
75189
+ buildId: options.buildId
75190
+ });
75191
+ if (options.localTags.has(localTag)) throw new UserError(`Container image name ${JSON.stringify(options.repositoryName)} conflicts with another image after Docker name normalization.`, { telemetryMessage: "container build output image name conflict" });
75192
+ await (await startContainerBuild({
75193
+ build: {
75194
+ tag: localTag,
75195
+ pathToDockerfile,
75196
+ buildContext: options.image.buildContext === void 0 ? path__default.dirname(pathToDockerfile) : path__default.resolve(options.root, options.image.buildContext),
75197
+ args: options.image.buildVars,
75198
+ platform: "linux/amd64"
75199
+ },
75200
+ pathToDocker: options.pathToDocker,
75201
+ verifyDockerIsRunning: false
75202
+ })).ready;
75203
+ options.localTags.add(localTag);
75204
+ return { localReference: localTag };
75205
+ }
75206
+ __name$2(buildContainerImage2, "buildContainerImage");
75207
+ function createBuildOutputImageTag(options) {
75208
+ const repositoryPrefix = getBuildOutputImageRepositoryPrefix(options.root);
75209
+ const maxNameLength = DOCKER_REPOSITORY_NAME_LENGTH - repositoryPrefix.length;
75210
+ return `${repositoryPrefix}${normalizeContainerImageRepositoryName(options.repositoryName).slice(0, maxNameLength).replace(/[._-]+$/g, "")}:${options.buildId}`;
75211
+ }
75212
+ __name$2(createBuildOutputImageTag, "createBuildOutputImageTag");
75213
+ async function cleanupPreviousBuildOutputImageTags(options) {
75214
+ const repositoryPrefix = getBuildOutputImageRepositoryPrefix(options.root);
75215
+ let existingTags;
75216
+ try {
75217
+ const output = runDockerCmdWithOutput(options.pathToDocker, [
75218
+ "image",
75219
+ "ls",
75220
+ "--filter",
75221
+ `reference=${repositoryPrefix}*`,
75222
+ "--format",
75223
+ "{{.Repository}}:{{.Tag}}"
75224
+ ]);
75225
+ existingTags = output === "" ? [] : output.split(/\r?\n/);
75226
+ } catch {
75227
+ return;
75228
+ }
75229
+ if (existingTags.length > 0) await cleanupBuiltImages(existingTags.map((localTag) => ({ localTag })), options.pathToDocker);
75230
+ }
75231
+ __name$2(cleanupPreviousBuildOutputImageTags, "cleanupPreviousBuildOutputImageTags");
75232
+ function getBuildOutputImageRepositoryPrefix(root) {
75233
+ return `${BUILD_OUTPUT_IMAGE_NAMESPACE}/${shortHash(path__default.resolve(root))}/`;
75234
+ }
75235
+ __name$2(getBuildOutputImageRepositoryPrefix, "getBuildOutputImageRepositoryPrefix");
75236
+ function shortHash(value) {
75237
+ return crypto2.createHash("sha256").update(value).digest("hex").slice(0, 12);
75238
+ }
75239
+ __name$2(shortHash, "shortHash");
75240
+ function createBuildId() {
75241
+ return crypto2.randomUUID().replaceAll("-", "").slice(0, 12);
75242
+ }
75243
+ __name$2(createBuildId, "createBuildId");
75244
+ function countDockerfiles(containers) {
75245
+ let count = 0;
75246
+ for (const config$2 of containers) if (config$2.schedulingPolicy === "durable-object") count += Object.values(config$2.images ?? {}).filter((image) => "dockerfile" in image).length;
75247
+ else if ("dockerfile" in config$2.image) count++;
75248
+ return count;
75249
+ }
75250
+ __name$2(countDockerfiles, "countDockerfiles");
75251
+ function throwBuildError(error$2) {
75252
+ if (error$2 instanceof UserError) throw error$2;
75253
+ if (error$2 instanceof Error) throw new UserError(error$2.message, {
75254
+ cause: error$2,
75255
+ telemetryMessage: "container build image operation failed"
75256
+ });
75257
+ throw new UserError("An unknown error occurred", { telemetryMessage: "container build unknown error" });
75258
+ }
75259
+ __name$2(throwBuildError, "throwBuildError");
74732
75260
  var Diff = class {
74733
75261
  static {
74734
75262
  __name$2(this, "Diff");
@@ -74893,10 +75421,10 @@ var Diff = class {
74893
75421
  print(options = { contextLines: 3 }) {
74894
75422
  log$1(this.toString(options));
74895
75423
  }
74896
- #addToPath(path2, added, removed, oldPosInc) {
74897
- const last = path2.lastComponent;
75424
+ #addToPath(path3, added, removed, oldPosInc) {
75425
+ const last = path3.lastComponent;
74898
75426
  if (last && last.added === added && last.removed === removed) return {
74899
- oldPos: path2.oldPos + oldPosInc,
75427
+ oldPos: path3.oldPos + oldPosInc,
74900
75428
  lastComponent: {
74901
75429
  count: last.count + 1,
74902
75430
  added,
@@ -74905,7 +75433,7 @@ var Diff = class {
74905
75433
  }
74906
75434
  };
74907
75435
  return {
74908
- oldPos: path2.oldPos + oldPosInc,
75436
+ oldPos: path3.oldPos + oldPosInc,
74909
75437
  lastComponent: {
74910
75438
  count: 1,
74911
75439
  added,
@@ -75509,6 +76037,412 @@ function createContainerDevPlan(options) {
75509
76037
  }
75510
76038
  __name$2(createContainerDevPlan, "createContainerDevPlan");
75511
76039
 
76040
+ //#endregion
76041
+ //#region src/build-output-containers.ts
76042
+ /**
76043
+ * Build and write the Container portion of the Build Output Specification.
76044
+ *
76045
+ * @param resolvedPluginConfig - The resolved Cloudflare Vite plugin config.
76046
+ * @param root - The Vite project root and Build Output root.
76047
+ */
76048
+ async function buildOutputContainers(resolvedPluginConfig, root) {
76049
+ if (resolvedPluginConfig.type === "preview" || resolvedPluginConfig.experimental.newConfig?.cfBuildOutput !== true) return;
76050
+ const config$2 = resolvedPluginConfig.parsedNewConfig;
76051
+ if (config$2 === void 0) return;
76052
+ await buildAndWriteContainerOutput({
76053
+ containers: config$2.containers,
76054
+ root,
76055
+ pathToDocker: getDockerPath$1()
76056
+ });
76057
+ }
76058
+
76059
+ //#endregion
76060
+ //#region src/dev-vars.ts
76061
+ /**
76062
+ * Gets any variables with which to augment the Worker config in preview mode.
76063
+ *
76064
+ * Calls `unstable_getVarsForDev` with the current Cloudflare environment to get local dev variables from the .dev.vars/.env/process.env.
76065
+ * When `secrets` is defined in the Worker config, only declared secrets are loaded.
76066
+ */
76067
+ function getLocalDevVarsForPreview(config$2, cloudflareEnv) {
76068
+ const dotDevDotVars = wrangler.unstable_getVarsForDev(config$2.configPath, void 0, {}, cloudflareEnv, false, config$2.secrets);
76069
+ const dotDevDotVarsEntries = Array.from(Object.entries(dotDevDotVars));
76070
+ if (dotDevDotVarsEntries.length > 0) return dotDevDotVarsEntries.map(([key, { value }]) => {
76071
+ return `${key}=${quoteForDotenv(value?.toString() ?? "")}\n`;
76072
+ }).join("");
76073
+ }
76074
+ /**
76075
+ * Quote a value so that wrangler reads it back unchanged when it parses
76076
+ * `dist/<env>/.dev.vars` at preview time.
76077
+ *
76078
+ * Strategy: To quote the string pick the first quote character that does not
76079
+ * appear in the value (single → backtick → double). Throw if a value cannot
76080
+ * be losslessly serialized rather than silently corrupting it.
76081
+ *
76082
+ * @internal exported for tests
76083
+ */
76084
+ function quoteForDotenv(value) {
76085
+ if (!value.includes("'")) return `'${value}'`;
76086
+ if (!value.includes("`")) return `\`${value}\``;
76087
+ if (!value.includes("\"") && !/[\\\n\r]/.test(value)) return `"${value}"`;
76088
+ throw new Error("Unable to serialize value to .dev.vars: contains every supported quote character or unsafe escape sequence.");
76089
+ }
76090
+ /**
76091
+ * Returns `true` if the `changedFile` matches a `.dev.vars` or `.env` file.
76092
+ */
76093
+ function hasLocalDevVarsFileChanged({ configPaths, cloudflareEnv }, changedFilePath) {
76094
+ return [...configPaths].some((configPath) => {
76095
+ const configDir = path.dirname(configPath);
76096
+ return [
76097
+ ".dev.vars",
76098
+ ".env",
76099
+ ...cloudflareEnv ? [`.dev.vars.${cloudflareEnv}`, `.env.${cloudflareEnv}`] : []
76100
+ ].some((localDevFile) => changedFilePath === path.join(configDir, localDevFile));
76101
+ });
76102
+ }
76103
+
76104
+ //#endregion
76105
+ //#region src/vite-config.ts
76106
+ const NODE_BUILTIN_SET = new Set([...builtinModules, ...builtinModules.filter((m) => !m.startsWith("node:")).map((m) => `node:${m}`)]);
76107
+ function isOnlyNodeBuiltins(external) {
76108
+ if (!Array.isArray(external)) return false;
76109
+ return external.every((entry) => typeof entry === "string" && NODE_BUILTIN_SET.has(entry));
76110
+ }
76111
+ /**
76112
+ * Throws an error if Worker environments include configuration options that are incompatible with the plugin.
76113
+ */
76114
+ function validateWorkerEnvironmentOptions(resolvedPluginConfig, resolvedViteConfig) {
76115
+ const disallowedEnvironmentOptionsMap = /* @__PURE__ */ new Map();
76116
+ for (const environmentName of resolvedPluginConfig.environmentNameToWorkerMap.keys()) {
76117
+ const environmentOptions = resolvedViteConfig.environments[environmentName];
76118
+ assert2(environmentOptions, `Missing environment config for "${environmentName}"`);
76119
+ const { resolve: resolve$4 } = environmentOptions;
76120
+ const disallowedEnvironmentOptions = {};
76121
+ if ((resolve$4.external === true || Array.isArray(resolve$4.external) && resolve$4.external.length > 0) && !isOnlyNodeBuiltins(resolve$4.external)) disallowedEnvironmentOptions.resolveExternal = resolve$4.external;
76122
+ if (Object.keys(disallowedEnvironmentOptions).length) disallowedEnvironmentOptionsMap.set(environmentName, disallowedEnvironmentOptions);
76123
+ }
76124
+ if (disallowedEnvironmentOptionsMap.size) {
76125
+ const errorMessage = `The following environment options are incompatible with the Cloudflare Vite plugin:\n${[...disallowedEnvironmentOptionsMap].map(([environmentName, disallowedEnvironmentOptions]) => disallowedEnvironmentOptions.resolveExternal && ` - "${environmentName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedEnvironmentOptions.resolveExternal)}\n`).join("")}To resolve this issue, avoid setting \`resolve.external\` in your Cloudflare Worker environments.\n`;
76126
+ throw new Error(errorMessage);
76127
+ }
76128
+ }
76129
+
76130
+ //#endregion
76131
+ //#region src/plugins/wrangler-watch-ignore.ts
76132
+ const WRANGLER_STATE_WATCH_IGNORE = "**/.wrangler/**";
76133
+ /**
76134
+ * Keep Miniflare persistence writes out of Vite's file watcher without
76135
+ * replacing any ignore patterns the user already configured.
76136
+ *
76137
+ * @param userIgnored - Existing `server.watch.ignored` patterns, if any
76138
+ * @returns Ignore patterns that always include `.wrangler` directories
76139
+ */
76140
+ function withWranglerStateIgnored(userIgnored) {
76141
+ if (userIgnored == null) return WRANGLER_STATE_WATCH_IGNORE;
76142
+ if (Array.isArray(userIgnored)) return [...userIgnored, WRANGLER_STATE_WATCH_IGNORE];
76143
+ return [userIgnored, WRANGLER_STATE_WATCH_IGNORE];
76144
+ }
76145
+ /**
76146
+ * Merge `.wrangler` into Vite's `server.watch` config.
76147
+ *
76148
+ * Returns `null` when the user disabled watching with `server.watch: null`,
76149
+ * so this plugin does not turn the watcher back on.
76150
+ *
76151
+ * @param userWatch - The user's `server.watch` value from Vite config
76152
+ * @returns `null` when watching is disabled, otherwise a watch object whose
76153
+ * `ignored` list includes `.wrangler` directories
76154
+ */
76155
+ function getServerWatchConfig(userWatch) {
76156
+ if (userWatch === null) return null;
76157
+ return {
76158
+ ...userWatch,
76159
+ ignored: withWranglerStateIgnored(userWatch?.ignored)
76160
+ };
76161
+ }
76162
+
76163
+ //#endregion
76164
+ //#region src/plugins/config.ts
76165
+ /**
76166
+ * Plugin to handle configuration and config file watching
76167
+ */
76168
+ const configPlugin = createPlugin("config", (ctx) => {
76169
+ return {
76170
+ config(userConfig, env$3) {
76171
+ if (ctx.resolvedPluginConfig.type === "preview") return { appType: "custom" };
76172
+ if (!ctx.hasShownWorkerConfigWarnings) {
76173
+ ctx.setHasShownWorkerConfigWarnings(true);
76174
+ const workerConfigWarnings = getWarningForWorkersConfigs(ctx.resolvedPluginConfig.rawConfigs);
76175
+ if (workerConfigWarnings) console.warn(workerConfigWarnings);
76176
+ }
76177
+ return {
76178
+ appType: "custom",
76179
+ server: {
76180
+ allowedHosts: getAllowedHosts(ctx.getTunnelHostnames(), userConfig.server?.allowedHosts),
76181
+ watch: getServerWatchConfig(userConfig.server?.watch),
76182
+ fs: { deny: [...[
76183
+ ".env",
76184
+ ".env.*",
76185
+ ".npmrc",
76186
+ ".yarnrc",
76187
+ ".yarnrc.yml",
76188
+ "*.{crt,pem,key,pfx,p12,p8,jks}",
76189
+ "**/.git/**",
76190
+ ".dev.vars",
76191
+ ".dev.vars.*",
76192
+ "**/.wrangler/**"
76193
+ ], ...Array.from(ctx.resolvedPluginConfig.configPaths, (configPath) => normalizePath(configPath))] }
76194
+ },
76195
+ environments: getEnvironmentsConfig(ctx, userConfig, env$3.mode),
76196
+ builder: { buildApp: userConfig.builder?.buildApp ?? createBuildApp(ctx.resolvedPluginConfig) }
76197
+ };
76198
+ },
76199
+ async configResolved(resolvedViteConfig) {
76200
+ ctx.setResolvedViteConfig(resolvedViteConfig);
76201
+ if (ctx.resolvedPluginConfig.type === "preview") return;
76202
+ validateWorkerEnvironmentOptions(ctx.resolvedPluginConfig, ctx.resolvedViteConfig);
76203
+ if (ctx.resolvedPluginConfig.experimental.newConfig?.cfBuildOutput) {
76204
+ forceBuildOutputDirs(ctx.resolvedPluginConfig, ctx.resolvedViteConfig);
76205
+ if (ctx.resolvedViteConfig.command === "build") await cleanBuildOutputDir(ctx.resolvedViteConfig.root);
76206
+ }
76207
+ },
76208
+ buildStart() {
76209
+ ctx.setHasShownWorkerConfigWarnings(false);
76210
+ },
76211
+ configureServer(viteDevServer) {
76212
+ let restartInFlight = false;
76213
+ const configChangedHandler = async (changedFilePath) => {
76214
+ assertIsNotPreview(ctx);
76215
+ if (restartInFlight) return;
76216
+ if (ctx.resolvedPluginConfig.configPaths.has(changedFilePath) || hasLocalDevVarsFileChanged(ctx.resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(ctx.resolvedPluginConfig, ctx.resolvedViteConfig, changedFilePath)) {
76217
+ debuglog("Config changed: " + changedFilePath);
76218
+ restartInFlight = true;
76219
+ debuglog("Restarting dev server and aborting previous setup");
76220
+ try {
76221
+ await viteDevServer.restart();
76222
+ } finally {
76223
+ restartInFlight = false;
76224
+ }
76225
+ }
76226
+ };
76227
+ viteDevServer.watcher.on("change", configChangedHandler);
76228
+ },
76229
+ buildApp: {
76230
+ order: "post",
76231
+ async handler(builder) {
76232
+ if (ctx.resolvedPluginConfig.type !== "workers") return;
76233
+ const workerEnvironments = [...ctx.resolvedPluginConfig.environmentNameToWorkerMap.entries()].filter(([_, worker]) => !resolveDevOnly(worker.devOnly)).map(([environmentName]) => {
76234
+ const environment = builder.environments[environmentName];
76235
+ assert2(environment, `"${environmentName}" environment not found`);
76236
+ return environment;
76237
+ });
76238
+ await Promise.all(workerEnvironments.filter((environment) => !environment.isBuilt).map((environment) => builder.build(environment)));
76239
+ const { entryWorkerEnvironmentName } = ctx.resolvedPluginConfig;
76240
+ const entryWorkerEnvironment = builder.environments[entryWorkerEnvironmentName];
76241
+ assert2(entryWorkerEnvironment, `No "${entryWorkerEnvironmentName}" environment`);
76242
+ const cfBuildOutput = ctx.resolvedPluginConfig.experimental.newConfig?.cfBuildOutput === true;
76243
+ if (entryWorkerEnvironment.isBuilt) {
76244
+ if (!builder.environments.client?.isBuilt && !cfBuildOutput) removeAssetsField(path.resolve(builder.config.root, entryWorkerEnvironment.config.build.outDir));
76245
+ } else {
76246
+ const clientEnvironment = builder.environments.client;
76247
+ assert2(clientEnvironment, "No \"client\" environment");
76248
+ if (!clientEnvironment.isBuilt) throw new Error("If `assetsOnly` is set to `true`, the client environment must be built");
76249
+ if (cfBuildOutput) {
76250
+ const entryWorkerNewConfig = ctx.getWorkerNewConfig(entryWorkerEnvironmentName);
76251
+ assert2(entryWorkerNewConfig, `No config found for "${entryWorkerEnvironmentName}" environment`);
76252
+ await writeWorkerConfig({
76253
+ root: builder.config.root,
76254
+ config: entryWorkerNewConfig
76255
+ });
76256
+ } else {
76257
+ const entryWorkerConfig = ctx.getWorkerConfig(entryWorkerEnvironmentName);
76258
+ assert2(entryWorkerConfig, `No config found for "${entryWorkerEnvironmentName}" environment`);
76259
+ const outputConfig = {
76260
+ ...entryWorkerConfig,
76261
+ main: void 0,
76262
+ assets: {
76263
+ ...entryWorkerConfig.assets,
76264
+ directory: ".",
76265
+ binding: void 0
76266
+ }
76267
+ };
76268
+ if (outputConfig.unsafe && Object.keys(outputConfig.unsafe).length === 0) outputConfig.unsafe = void 0;
76269
+ fs$1.writeFileSync(path.resolve(builder.config.root, clientEnvironment.config.build.outDir, "wrangler.json"), JSON.stringify(outputConfig));
76270
+ writeDeployConfig(ctx.resolvedPluginConfig, ctx.resolvedViteConfig, true);
76271
+ }
76272
+ }
76273
+ await buildOutputContainers(ctx.resolvedPluginConfig, builder.config.root);
76274
+ }
76275
+ }
76276
+ };
76277
+ });
76278
+ /**
76279
+ * Generates the environment configuration for all Worker environments.
76280
+ */
76281
+ function getEnvironmentsConfig(ctx, userConfig, mode) {
76282
+ assertIsNotPreview(ctx);
76283
+ if (!ctx.resolvedPluginConfig.environmentNameToWorkerMap.size) return;
76284
+ return {
76285
+ ...Object.fromEntries([...ctx.resolvedPluginConfig.environmentNameToWorkerMap].flatMap(([environmentName, worker]) => {
76286
+ const childEnvironmentNames = ctx.resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap.get(environmentName) ?? [];
76287
+ const sharedOptions = {
76288
+ workerConfig: worker.config,
76289
+ userConfig,
76290
+ mode,
76291
+ hasNodeJsCompat: ctx.getNodeJsCompat(environmentName) !== void 0
76292
+ };
76293
+ const isEntryWorker = environmentName === ctx.resolvedPluginConfig.prerenderWorkerEnvironmentName || ctx.resolvedPluginConfig.type === "workers" && environmentName === ctx.resolvedPluginConfig.entryWorkerEnvironmentName;
76294
+ return [[environmentName, createCloudflareEnvironmentOptions({
76295
+ ...sharedOptions,
76296
+ environmentName,
76297
+ isEntryWorker,
76298
+ isParentEnvironment: true
76299
+ })], ...childEnvironmentNames.map((childEnvironmentName) => [childEnvironmentName, createCloudflareEnvironmentOptions({
76300
+ ...sharedOptions,
76301
+ environmentName: childEnvironmentName,
76302
+ isEntryWorker: false,
76303
+ isParentEnvironment: false
76304
+ })])];
76305
+ })),
76306
+ client: {
76307
+ build: { outDir: getOutputDirectory(userConfig, "client") },
76308
+ optimizeDeps: { exclude: [...cloudflareBuiltInModules] }
76309
+ }
76310
+ };
76311
+ }
76312
+ /**
76313
+ * When the Build Output Specification is enabled,
76314
+ * force every Worker environment's and the client environment's `build.outDir`
76315
+ * to the spec-mandated location.
76316
+ *
76317
+ * Runs after Vite's merge in `configResolved`, so it overrides any
76318
+ * user-supplied `build.outDir`
76319
+ */
76320
+ function forceBuildOutputDirs(resolvedPluginConfig, resolvedViteConfig) {
76321
+ if (!resolvedPluginConfig.experimental.newConfig?.cfBuildOutput) return;
76322
+ const { root } = resolvedViteConfig;
76323
+ if (resolvedPluginConfig.type === "workers") {
76324
+ const entryName = resolvedPluginConfig.entryWorkerEnvironmentName;
76325
+ const entryEnvironment = resolvedViteConfig.environments[entryName];
76326
+ if (entryEnvironment) entryEnvironment.build.outDir = getWorkerBundleDir(root);
76327
+ }
76328
+ const clientEnvironment = resolvedViteConfig.environments.client;
76329
+ if (clientEnvironment) clientEnvironment.build.outDir = getWorkerAssetsDir(root);
76330
+ }
76331
+ function getAllowedHosts(tunnelHostnames, userAllowedHosts) {
76332
+ if (tunnelHostnames.length === 0 || userAllowedHosts === true) return userAllowedHosts;
76333
+ return Array.from(new Set([...userAllowedHosts ?? [], ...tunnelHostnames]));
76334
+ }
76335
+
76336
+ //#endregion
76337
+ //#region src/debug.ts
76338
+ var import_picocolors$3 = /* @__PURE__ */ __toESM$1(require_picocolors(), 1);
76339
+ const DEBUG_PATH = "/__debug";
76340
+ const DEFAULT_INSPECTOR_PORT = 9229;
76341
+ /**
76342
+ * Gets the inspector port option that should be passed to Miniflare based on the user's plugin config
76343
+ */
76344
+ async function getInputInspectorPort(ctx, viteServer) {
76345
+ if (ctx.resolvedPluginConfig.inspectorPort === void 0 || ctx.resolvedPluginConfig.inspectorPort === 0) {
76346
+ const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
76347
+ if (resolvedInspectorPort !== null) return resolvedInspectorPort;
76348
+ }
76349
+ const inputInspectorPort = ctx.resolvedPluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
76350
+ if (ctx.resolvedPluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) viteServer.config.logger.warn(import_picocolors$3.default.dim(`Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead\n`));
76351
+ return inputInspectorPort;
76352
+ }
76353
+ function getFirstAvailablePort(start) {
76354
+ return getPorts({ port: portNumbers(start, 65535) });
76355
+ }
76356
+ /**
76357
+ * Modifies the URL printing logic to also include a URL that developers can use to open DevTools to debug their Worker(s)
76358
+ */
76359
+ function addDebugToVitePrintUrls(server) {
76360
+ const originalPrintUrls = server.printUrls;
76361
+ server.printUrls = () => {
76362
+ originalPrintUrls();
76363
+ const localUrl = server.resolvedUrls?.local[0];
76364
+ if (localUrl) {
76365
+ const { protocol, hostname: hostname$1, port } = new URL(localUrl);
76366
+ const colorDebugUrl = (url$2) => import_picocolors$3.default.dim(import_picocolors$3.default.yellow(url$2.replace(/:(\d+)\//, (_, portNumber) => `:${import_picocolors$3.default.bold(portNumber)}/`)));
76367
+ server.config.logger.info(` ${import_picocolors$3.default.green("➜")} ${import_picocolors$3.default.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname$1}:${port}${DEBUG_PATH}`)}`);
76368
+ }
76369
+ };
76370
+ }
76371
+ /**
76372
+ * Generate HTML that comprises a single script that:
76373
+ * - redirects the page to the DevTools for debugging the first available Worker
76374
+ * - opens tabs to the DevTools for all the remaining workers if any
76375
+ *
76376
+ * Note: this works based on the Miniflare inspector proxy logic (where Workers are available via
76377
+ * their names)
76378
+ */
76379
+ function getDebugPathHtml(workerNames, inspectorPort) {
76380
+ assert2(workerNames.length >= 1, "no workers present to debug");
76381
+ const workerDevtoolsUrls = workerNames.map((workerName) => {
76382
+ const localhost = `localhost:${inspectorPort}/${workerName}`;
76383
+ return `https://devtools.devprod.cloudflare.dev/js_app?${new URLSearchParams({
76384
+ theme: "systemPreferred",
76385
+ debugger: "true",
76386
+ ws: localhost,
76387
+ domain: workerName
76388
+ })}`;
76389
+ });
76390
+ return `
76391
+ <script>
76392
+ const workerUrls = ${JSON.stringify(workerDevtoolsUrls)};
76393
+ const [firstUrl, ...rest] = workerUrls;
76394
+ for (const workerUrl of rest) {
76395
+ // open new tabs for the devtools of the various workers
76396
+ window.open(workerUrl);
76397
+ }
76398
+ // redirect the current tab to the devtools of the first worker
76399
+ window.location.replace(firstUrl);
76400
+ <\/script>
76401
+ `;
76402
+ }
76403
+
76404
+ //#endregion
76405
+ //#region src/plugins/debug.ts
76406
+ /**
76407
+ * Plugin to provide a `/__debug` path for debugging Workers
76408
+ */
76409
+ const debugPlugin = createPlugin("debug", (ctx) => {
76410
+ return {
76411
+ enforce: "pre",
76412
+ configureServer(viteDevServer) {
76413
+ assertIsNotPreview(ctx);
76414
+ if (!!process.env.VSCODE_INSPECTOR_OPTIONS) return;
76415
+ if (ctx.resolvedPluginConfig.type === "workers" && ctx.resolvedPluginConfig.inspectorPort !== false) addDebugToVitePrintUrls(viteDevServer);
76416
+ const workerNames = ctx.resolvedPluginConfig.type === "workers" ? [...ctx.resolvedPluginConfig.environmentNameToWorkerMap.values()].map((worker) => worker.config.name) : [];
76417
+ viteDevServer.middlewares.use(DEBUG_PATH, async (_, res, next) => {
76418
+ const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
76419
+ if (resolvedInspectorPort) {
76420
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
76421
+ res.setHeader("Content-Type", "text/html");
76422
+ res.end(html);
76423
+ } else next();
76424
+ });
76425
+ },
76426
+ async configurePreviewServer(vitePreviewServer) {
76427
+ assertIsPreview(ctx);
76428
+ if (!!process.env.VSCODE_INSPECTOR_OPTIONS) return;
76429
+ if (ctx.resolvedPluginConfig.workers.length >= 1 && ctx.resolvedPluginConfig.inspectorPort !== false) addDebugToVitePrintUrls(vitePreviewServer);
76430
+ const workerNames = ctx.resolvedPluginConfig.workers.map((worker) => {
76431
+ assert2(worker.config.name, "Expected the Worker to have a name");
76432
+ return worker.config.name;
76433
+ });
76434
+ vitePreviewServer.middlewares.use(DEBUG_PATH, async (_, res, next) => {
76435
+ const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
76436
+ if (resolvedInspectorPort) {
76437
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
76438
+ res.setHeader("Content-Type", "text/html");
76439
+ res.end(html);
76440
+ } else next();
76441
+ });
76442
+ }
76443
+ };
76444
+ });
76445
+
75512
76446
  //#endregion
75513
76447
  //#region ../workers-shared/asset-worker/src/utils/rules-engine.ts
75514
76448
  const ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g;
@@ -81158,7 +82092,7 @@ __name(createWorkerUploadForm, "createWorkerUploadForm");
81158
82092
  //#endregion
81159
82093
  //#region ../remote-bindings/dist/index.mjs
81160
82094
  var import_undici = require_undici();
81161
- var version$2 = "0.0.27";
82095
+ var version$2 = "0.0.29";
81162
82096
  var NoDefaultValueProvided = class extends UserError {
81163
82097
  constructor() {
81164
82098
  super("This command cannot be run in a non-interactive context", { telemetryMessage: "remote bindings prompt default missing" });
@@ -81442,7 +82376,7 @@ async function getOrRegisterWorkersDevSubdomain(complianceConfig, account, abort
81442
82376
  } catch (error$2) {
81443
82377
  if (!(error$2 instanceof APIError) || error$2.code !== 10007) throw error$2;
81444
82378
  }
81445
- const subdomain = crypto$1.randomBytes(4).toString("hex");
82379
+ const subdomain = crypto2.randomBytes(4).toString("hex");
81446
82380
  return (await fetchResult(complianceConfig, account, resource, {
81447
82381
  method: "PUT",
81448
82382
  body: JSON.stringify({ subdomain })