wrangler 4.146.0 → 4.148.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.
@@ -3593,12 +3593,23 @@ function findRedirectedWranglerConfig(cwd2, userConfigPath) {
3593
3593
  );
3594
3594
  }
3595
3595
  if (userConfigPath) {
3596
- if (path28__namespace.default.join(path28__namespace.default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) {
3596
+ const expectedDeployConfigPath = path28__namespace.default.join(
3597
+ path28__namespace.default.dirname(userConfigPath),
3598
+ PATH_TO_DEPLOY_CONFIG
3599
+ );
3600
+ if (expectedDeployConfigPath !== deployConfigPath) {
3597
3601
  throw new UserError(
3598
3602
  esm_default`
3599
3603
  Found both a user configuration file at "${path28__namespace.default.relative(".", userConfigPath)}"
3600
3604
  and a deploy configuration file at "${path28__namespace.default.relative(".", deployConfigPath)}".
3601
3605
  But these do not share the same base path so it is not clear which should be used.
3606
+
3607
+ A deploy configuration file is generated by a build tool to redirect Wrangler to the configuration it generated.
3608
+ It is only applied when it sits alongside the user configuration file, which here would be "${path28__namespace.default.relative(".", expectedDeployConfigPath)}".
3609
+
3610
+ Please either delete "${path28__namespace.default.relative(".", deployConfigPath)}" if it is left over from a previous build,
3611
+ or try running this command from the directory containing the configuration you want to use.
3612
+ See https://developers.cloudflare.com/workers/wrangler/configuration/#generated-wrangler-configuration
3602
3613
  `,
3603
3614
  { telemetryMessage: false }
3604
3615
  );
@@ -22586,9 +22597,9 @@ function validateContainerApp(envName, topLevelName, configPath, options = {}) {
22586
22597
  constraints.jurisdiction,
22587
22598
  "string"
22588
22599
  );
22589
- if (constraints.jurisdiction && !["eu", "fedramp"].includes(constraints.jurisdiction)) {
22600
+ if (constraints.jurisdiction && !["eu", "fedramp", "us"].includes(constraints.jurisdiction)) {
22590
22601
  diagnostics.errors.push(
22591
- `${field}.constraints.jurisdiction must be one of: "eu", "fedramp"`
22602
+ `${field}.constraints.jurisdiction must be one of: "eu", "fedramp", "us"`
22592
22603
  );
22593
22604
  }
22594
22605
  if (validateOptionalTypedArray(
@@ -24213,6 +24224,13 @@ Please add a binding for each to "${fieldPath}.bindings":
24213
24224
  "string",
24214
24225
  ["single-page-application", "404-page", "none"]
24215
24226
  ) && isValid;
24227
+ isValid = validateOptionalProperty(
24228
+ diagnostics,
24229
+ field,
24230
+ "base_path",
24231
+ value.base_path,
24232
+ "string"
24233
+ ) && isValid;
24216
24234
  if (value.run_worker_first !== void 0) {
24217
24235
  if (typeof value.run_worker_first === "boolean") {
24218
24236
  isValid = validateOptionalProperty(
@@ -24243,6 +24261,7 @@ Please add a binding for each to "${fieldPath}.bindings":
24243
24261
  "binding",
24244
24262
  "html_handling",
24245
24263
  "not_found_handling",
24264
+ "base_path",
24246
24265
  "run_worker_first"
24247
24266
  ]) && isValid;
24248
24267
  return isValid;
@@ -27412,7 +27431,7 @@ var DEFAULT_COMPAT_DATE;
27412
27431
  var init_default_compat_date = __esm({
27413
27432
  "../workers-utils/src/default-compat-date.ts"() {
27414
27433
  init_import_meta_url();
27415
- DEFAULT_COMPAT_DATE = "2026-10-01";
27434
+ DEFAULT_COMPAT_DATE = "2026-10-06";
27416
27435
  }
27417
27436
  });
27418
27437
 
@@ -58006,10 +58025,25 @@ function startTunnel(options) {
58006
58025
  const reminderIntervalMs = options.reminderIntervalMs ?? DEFAULT_TUNNEL_REMINDER_INTERVAL_MS;
58007
58026
  const defaultExpiryMs = options.expiryMs ?? DEFAULT_TUNNEL_EXPIRY_MS;
58008
58027
  const isNamedTunnel = options.token !== void 0;
58028
+ if (isNamedTunnel && (options.allowedMail?.length ?? 0) > 0) {
58029
+ throw new UserError(
58030
+ "The `allowedMail` option is only supported for Quick Tunnels.",
58031
+ { telemetryMessage: "tunnel allowed mail named tunnel conflict" }
58032
+ );
58033
+ }
58009
58034
  const timeFormatter = new Intl.DateTimeFormat(void 0, {
58010
58035
  timeStyle: "short"
58011
58036
  });
58012
- const cloudflaredArgs = isNamedTunnel ? ["tunnel", "--no-autoupdate", "run"] : ["tunnel", "--no-autoupdate", "--url", options.origin.href];
58037
+ const cloudflaredArgs = isNamedTunnel ? ["tunnel", "--no-autoupdate", "run"] : [
58038
+ "tunnel",
58039
+ "--no-autoupdate",
58040
+ "--url",
58041
+ options.origin.href,
58042
+ ...(options.allowedMail ?? []).flatMap((allowedMail) => [
58043
+ "--allowed-mail",
58044
+ allowedMail
58045
+ ])
58046
+ ];
58013
58047
  const cloudflaredPromise = spawnCloudflared(cloudflaredArgs, {
58014
58048
  stdio: "pipe",
58015
58049
  env: options.token ? { TUNNEL_TOKEN: options.token } : void 0,
@@ -63071,7 +63105,7 @@ var name, version2;
63071
63105
  var init_package = __esm({
63072
63106
  "package.json"() {
63073
63107
  name = "wrangler";
63074
- version2 = "4.146.0";
63108
+ version2 = "4.148.0";
63075
63109
  }
63076
63110
  });
63077
63111
 
@@ -125271,7 +125305,7 @@ function getCachedTemporaryPreviewAccount(storage) {
125271
125305
  }
125272
125306
  return temporaryPreviewAccount;
125273
125307
  }
125274
- async function requestPowSolution(logger7) {
125308
+ async function requestPowSolution(temporaryAccountLogger) {
125275
125309
  const response = await (0, import_undici3.fetch)(getTemporaryPreviewChallengeUrl(), {
125276
125310
  method: "POST",
125277
125311
  headers: { "Content-Type": "application/json" },
@@ -125309,11 +125343,11 @@ async function requestPowSolution(logger7) {
125309
125343
  }
125310
125344
  );
125311
125345
  }
125312
- logger7.log("Solving proof-of-work challenge\u2026");
125346
+ temporaryAccountLogger.log("Solving proof-of-work challenge\u2026");
125313
125347
  return solveChallenge({ challengeToken, seed, k: k7, g: g7 });
125314
125348
  }
125315
- async function createTemporaryPreviewAccount(logger7, request4) {
125316
- const pow = await requestPowSolution(logger7);
125349
+ async function createTemporaryPreviewAccount(temporaryAccountLogger, request4) {
125350
+ const pow = await requestPowSolution(temporaryAccountLogger);
125317
125351
  const response = await (0, import_undici3.fetch)(getTemporaryPreviewUrl(), {
125318
125352
  method: "POST",
125319
125353
  headers: { "Content-Type": "application/json" },
@@ -125407,7 +125441,7 @@ async function getOrCreateTemporaryPreviewAccount(options) {
125407
125441
  });
125408
125442
  }
125409
125443
  const temporaryPreviewAccount = await createTemporaryPreviewAccount(
125410
- options.logger,
125444
+ options.temporaryAccountLogger,
125411
125445
  options.request
125412
125446
  );
125413
125447
  options.storage.write(temporaryPreviewAccount);
@@ -126509,7 +126543,6 @@ function createOAuthFlow(ctx) {
126509
126543
  }
126510
126544
  const result = await getOrCreateTemporaryPreviewAccount({
126511
126545
  ...ctx.temporary,
126512
- logger: ctx.logger,
126513
126546
  ...temporaryRequest ? { request: temporaryRequest } : {}
126514
126547
  });
126515
126548
  activeTemporaryAccount = result.account;
@@ -127420,8 +127453,8 @@ function scrubEncryptedCredentials(options) {
127420
127453
  return { backendAvailable: false, encryptedFileExisted };
127421
127454
  }
127422
127455
  var import_undici3, hasWarnedAboutDeprecatedV1ApiToken, getCloudflareAPITokenFromEnv, getCloudflareGlobalAuthKeyFromEnv, getCloudflareGlobalAuthEmailFromEnv, ACCOUNT_ID_PATTERN, getAuthDomainFromEnv, getAuthUrlFromEnv, getTokenUrlFromEnv, getRevokeUrlFromEnv, readCloudflareAccountIdFromEnv, DEVICE_AUTH_PATH, getAccessClientIdFromEnv, getAccessClientSecretFromEnv, getCfAuthorizationTokenFromEnv, getCloudflareAuthUseKeyringFromEnv, headersCache, usesAccessCache, RECOMMENDED_CODE_VERIFIER_LENGTH, RECOMMENDED_STATE_LENGTH, PKCE_CHARSET, generateVerificationUrl, generateAuthUrl, POW_MAX_ITERATIONS, TEMPORARY_TERMS_URLS, TEMPORARY_TERMS_PROMPT, TEMPORARY_TERMS_NOTICE, TEMPORARY_TERMS_ERROR, EVENT_ACCOUNT_ERRORS, esm_default3, ErrorOAuth2, ErrorUnknown, ErrorAuthServerUnreachable, ErrorNoAuthCode, ErrorInvalidReturnedStateParam, ErrorInvalidJson, ErrorInvalidScope, ErrorInvalidRequest, ErrorInvalidToken, ErrorAuthenticationGrant, ErrorUnauthorizedClient, ErrorAccessDenied, ErrorUnsupportedResponseType, ErrorServerError, ErrorTemporarilyUnavailable, ErrorAccessTokenResponse, ErrorInvalidClient, ErrorInvalidGrant, ErrorUnsupportedGrantType, DEVICE_FLOW_MAX_DURATION_SECONDS, DEVICE_FLOW_MIN_POLL_INTERVAL_SECONDS, RESERVED_PROFILE_NAMES, BARE_KEY2, HAS_WELLFORMED2, FILE_FORMATS, USER_AUTH_CONFIG_PATH, FileCredentialStore, KEY_LENGTH_BYTES, IV_LENGTH_BYTES, TAG_LENGTH_BYTES, ALGORITHM_LABEL, CIPHER_NAME, EncryptedFileCredentialStore, PINNED_KEYRING_VERSION, npmRunner, cachedBindingPathByDir, entryFactoryOverride, runner, cachedProbeResult, LinuxSecretToolKeyProvider, SECURITY_EXIT_ITEM_NOT_FOUND, runner2, MacSecurityKeyProvider, NapiKeyringKeyProvider, testProviderFactory, sessionFlags;
127423
- var init_chunk_FT2NMTJB = __esm({
127424
- "../workers-auth/dist/chunk-FT2NMTJB.mjs"() {
127456
+ var init_chunk_NDZDTP46 = __esm({
127457
+ "../workers-auth/dist/chunk-NDZDTP46.mjs"() {
127425
127458
  init_import_meta_url();
127426
127459
  init_chunk_VAZEJK55();
127427
127460
  init_src();
@@ -128413,7 +128446,7 @@ var init_chunk_FT2NMTJB = __esm({
128413
128446
  var init_dist2 = __esm({
128414
128447
  "../workers-auth/dist/index.mjs"() {
128415
128448
  init_import_meta_url();
128416
- init_chunk_FT2NMTJB();
128449
+ init_chunk_NDZDTP46();
128417
128450
  nodeModule.createRequire(import_meta_url || (typeof __filename === "string" ? __filename : "/"));
128418
128451
  }
128419
128452
  });
@@ -128674,10 +128707,10 @@ function createFileStorage(format9, getPath) {
128674
128707
  };
128675
128708
  }
128676
128709
  function createTemporaryTermsPrompt(deps) {
128677
- const { logger: logger7, prompt: prompt3 } = deps;
128710
+ const { temporaryAccountLogger, prompt: prompt3 } = deps;
128678
128711
  return /* @__PURE__ */ __name2(/* @__PURE__ */ __name(async function ensureTemporaryTermsAccepted(question, notice) {
128679
128712
  if (isNonInteractiveOrCI()) {
128680
- logger7.log(notice);
128713
+ temporaryAccountLogger.log(notice);
128681
128714
  return true;
128682
128715
  }
128683
128716
  const answer = await prompt3(question);
@@ -128700,9 +128733,9 @@ function notLoggedInErrorBodies(loginCommand2) {
128700
128733
  "token-refresh-unreachable": `Your auth token has expired and could not be refreshed because the Cloudflare auth server could not be reached. This is usually a network problem (connectivity, proxy, or IPv6), not an invalid login: your stored credentials were left unchanged. Check your connection and try again.`
128701
128734
  };
128702
128735
  }
128703
- function logTemporaryPreviewAccount(logger7, temporaryPreviewAccount, cached2) {
128736
+ function logTemporaryPreviewAccount(temporaryAccountLogger, temporaryPreviewAccount, cached2) {
128704
128737
  const claimExpiresAt = new Date(temporaryPreviewAccount.claim.expiresAt);
128705
- logger7.log(
128738
+ temporaryAccountLogger.log(
128706
128739
  dedent2`
128707
128740
  Temporary account ready:
128708
128741
  Account: ${temporaryPreviewAccount.account.name} (${cached2 ? "reused" : "created"})
@@ -128713,6 +128746,7 @@ function logTemporaryPreviewAccount(logger7, temporaryPreviewAccount, cached2) {
128713
128746
  }
128714
128747
  function createCloudflareAuth(descriptor, ctx) {
128715
128748
  const { logger: logger7 } = ctx;
128749
+ const temporaryAccountLogger = ctx.temporaryAccountLogger ?? logger7;
128716
128750
  const cliName = descriptor.cliName;
128717
128751
  const NOT_LOGGED_IN_ERROR_BODIES = notLoggedInErrorBodies(
128718
128752
  descriptor.commands.login
@@ -128755,7 +128789,11 @@ Run \`${descriptor.commands.whoami}\` to check your current authentication statu
128755
128789
  descriptor.fileFormat,
128756
128790
  descriptor.getTemporaryAccountConfigPath
128757
128791
  ),
128758
- prompt: createTemporaryTermsPrompt({ logger: logger7, prompt: ctx.prompt })
128792
+ prompt: createTemporaryTermsPrompt({
128793
+ temporaryAccountLogger,
128794
+ prompt: ctx.prompt
128795
+ }),
128796
+ temporaryAccountLogger
128759
128797
  }
128760
128798
  });
128761
128799
  function setProfile2(profile) {
@@ -129044,7 +129082,11 @@ ${accounts.map(
129044
129082
  );
129045
129083
  }
129046
129084
  const { account: temporaryPreviewAccount, cached: cached2 } = await oauthFlow.activateTemporaryAccount();
129047
- logTemporaryPreviewAccount(logger7, temporaryPreviewAccount, cached2);
129085
+ logTemporaryPreviewAccount(
129086
+ temporaryAccountLogger,
129087
+ temporaryPreviewAccount,
129088
+ cached2
129089
+ );
129048
129090
  return temporaryPreviewAccount.account.id;
129049
129091
  }
129050
129092
  const result = await loginOrRefreshIfRequired2(config2);
@@ -129327,10 +129369,10 @@ function createAuthConfigFileHelpers(deps) {
129327
129369
  };
129328
129370
  }
129329
129371
  var millisecondsInMinute, minutesInYear, minutesInMonth, minutesInDay, constructFromSymbol, defaultOptions2, formatDistanceLocale, formatDistance, dateFormats, timeFormats, dateTimeFormats, formatLong, formatRelativeLocale, formatRelative, eraValues, quarterValues, monthValues, dayValues, dayPeriodValues, formattingDayPeriodValues, ordinalNumber, localize, matchOrdinalNumberPattern, parseOrdinalNumberPattern, matchEraPatterns, parseEraPatterns, matchQuarterPatterns, parseQuarterPatterns, matchMonthPatterns, parseMonthPatterns, matchDayPatterns, parseDayPatterns, matchDayPeriodPatterns, parseDayPeriodPatterns, match, enUS, MEMBERSHIPS_INACCESSIBLE_CODES, DIRECTORY_BINDINGS_FILE, ENCRYPTED_PROFILE_CONFIG_EXTENSION;
129330
- var init_chunk_VVLCNASF = __esm({
129331
- "../workers-auth/dist/chunk-VVLCNASF.mjs"() {
129372
+ var init_chunk_PGZZHNWG = __esm({
129373
+ "../workers-auth/dist/chunk-PGZZHNWG.mjs"() {
129332
129374
  init_import_meta_url();
129333
- init_chunk_FT2NMTJB();
129375
+ init_chunk_NDZDTP46();
129334
129376
  init_chunk_VAZEJK55();
129335
129377
  init_src();
129336
129378
  nodeModule.createRequire(import_meta_url || (typeof __filename === "string" ? __filename : "/"));
@@ -129845,7 +129887,7 @@ var DefaultScopes, DefaultScopeKeys, WRANGLER_KEYRING_SERVICE_NAME, WRANGLER_CLI
129845
129887
  var init_wrangler = __esm({
129846
129888
  "../workers-auth/dist/wrangler/index.mjs"() {
129847
129889
  init_import_meta_url();
129848
- init_chunk_VVLCNASF();
129890
+ init_chunk_PGZZHNWG();
129849
129891
  init_chunk_VAZEJK55();
129850
129892
  init_src();
129851
129893
  nodeModule.createRequire(import_meta_url || (typeof __filename === "string" ? __filename : "/"));
@@ -135195,6 +135237,12 @@ var init_user2 = __esm({
135195
135237
  init_logger2();
135196
135238
  auth = createWranglerAuth({
135197
135239
  logger: logger2,
135240
+ // Temporary-account notices go to stderr so they never corrupt command
135241
+ // output on stdout (JSON, piped values), and stay visible when `--json`
135242
+ // commands lower the log level to "error".
135243
+ temporaryAccountLogger: {
135244
+ log: /* @__PURE__ */ __name((...args) => logger2.console("error", ...args), "log")
135245
+ },
135198
135246
  userAgent: `wrangler/${version2}`,
135199
135247
  prompt: prompt2,
135200
135248
  select: select2,
@@ -136151,6 +136199,7 @@ function convertBindingsAndAssets(config2, result) {
136151
136199
  if (assetsBindingName !== void 0) assets.binding = assetsBindingName;
136152
136200
  if (config2.assets?.htmlHandling !== void 0) assets.html_handling = config2.assets.htmlHandling;
136153
136201
  if (config2.assets?.notFoundHandling !== void 0) assets.not_found_handling = config2.assets.notFoundHandling;
136202
+ if (config2.assets?.basePath !== void 0) assets.base_path = config2.assets.basePath;
136154
136203
  if (config2.assets?.runWorkerFirst !== void 0) assets.run_worker_first = config2.assets.runWorkerFirst;
136155
136204
  result.assets = assets;
136156
136205
  }
@@ -136587,6 +136636,7 @@ var init_dist3 = __esm({
136587
136636
  "404-page",
136588
136637
  "none"
136589
136638
  ]).optional(),
136639
+ basePath: string2().optional(),
136590
136640
  runWorkerFirst: union([array(string2()), boolean2()]).optional()
136591
136641
  });
136592
136642
  BrowserBindingSchema = strictObject({
@@ -136917,7 +136967,11 @@ var init_dist3 = __esm({
136917
136967
  "OC",
136918
136968
  "AFR"
136919
136969
  ])).optional(),
136920
- jurisdiction: _enum2(["eu", "fedramp"]).optional()
136970
+ jurisdiction: _enum2([
136971
+ "eu",
136972
+ "fedramp",
136973
+ "us"
136974
+ ]).optional()
136921
136975
  }).optional(),
136922
136976
  rollout: strictObject({
136923
136977
  kind: _enum2([
@@ -150894,7 +150948,7 @@ var init_bundle_type = __esm({
150894
150948
  function isJavaScriptModuleRule(rule) {
150895
150949
  return rule.type === "ESModule" || rule.type === "CommonJS";
150896
150950
  }
150897
- function parseRules(userRules = []) {
150951
+ function parseRules(userRules = [], logWarnings = true) {
150898
150952
  const rules = [...userRules, ...DEFAULT_MODULE_RULES];
150899
150953
  const completedRuleLocations = {};
150900
150954
  const redundantRules = {};
@@ -150923,7 +150977,7 @@ function parseRules(userRules = []) {
150923
150977
  }
150924
150978
  for (const completedRuleType in completedRuleLocations) {
150925
150979
  const r10 = redundantRules[completedRuleType];
150926
- if (r10) {
150980
+ if (r10 && logWarnings) {
150927
150981
  const completedRuleIndex = completedRuleLocations[completedRuleType];
150928
150982
  let warning = `The ${completedRuleIndex >= userRules.length ? "default " : ""}module rule ${JSON.stringify(
150929
150983
  rules[completedRuleIndex]
@@ -162804,6 +162858,7 @@ function resolveAssetOptions({ assetsDir, main: main2 }, config2) {
162804
162858
  const assetConfig = {
162805
162859
  html_handling: config2.assets?.html_handling,
162806
162860
  not_found_handling: config2.assets?.not_found_handling,
162861
+ base_path: config2.assets?.base_path,
162807
162862
  // The _redirects and _headers files are parsed in Miniflare in dev and parsing is not required for deploy
162808
162863
  compatibility_date: config2.compatibility_date,
162809
162864
  compatibility_flags: config2.compatibility_flags
@@ -163542,6 +163597,7 @@ function createWorkerUploadForm(worker, bindings, options) {
163542
163597
  const assetConfig = {
163543
163598
  html_handling: assets?.assetConfig?.html_handling,
163544
163599
  not_found_handling: assets?.assetConfig?.not_found_handling,
163600
+ base_path: assets?.assetConfig?.base_path,
163545
163601
  run_worker_first: assets?.run_worker_first,
163546
163602
  _redirects: assets?._redirects,
163547
163603
  _headers: assets?._headers
@@ -175334,13 +175390,92 @@ var init_match_tag = __esm({
175334
175390
  __name(verifyWorkerMatchesCITag, "verifyWorkerMatchesCITag");
175335
175391
  }
175336
175392
  });
175393
+
175394
+ // ../workers-shared/utils/base-path.ts
175395
+ function normalizeBasePath(value) {
175396
+ if (value === "/") {
175397
+ return { valid: true, value: "/" };
175398
+ }
175399
+ if (typeof value !== "string") {
175400
+ return {
175401
+ valid: false,
175402
+ error: `Expected a string but got ${typeof value}.`
175403
+ };
175404
+ }
175405
+ if (value.length === 0) {
175406
+ return { valid: false, error: `The value must not be empty.` };
175407
+ }
175408
+ if (value.startsWith("//") || /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(value)) {
175409
+ return {
175410
+ valid: false,
175411
+ error: `The value must be a pathname, not a URL.`
175412
+ };
175413
+ }
175414
+ if (value.includes("\\")) {
175415
+ return { valid: false, error: `The value must not contain backslashes.` };
175416
+ }
175417
+ if (CONTROL_CHARACTER.test(value)) {
175418
+ return {
175419
+ valid: false,
175420
+ error: `The value must not contain control characters.`
175421
+ };
175422
+ }
175423
+ if (value.includes("?") || value.includes("#")) {
175424
+ return {
175425
+ valid: false,
175426
+ error: `The value must not contain query strings or fragments.`
175427
+ };
175428
+ }
175429
+ if (value.includes("%")) {
175430
+ return {
175431
+ valid: false,
175432
+ error: `The value must not contain percent-encoded sequences.`
175433
+ };
175434
+ }
175435
+ const normalizedSegments = [];
175436
+ for (const segment of value.split("/")) {
175437
+ if (segment === "" || segment === ".") {
175438
+ continue;
175439
+ }
175440
+ if (segment === "..") {
175441
+ normalizedSegments.pop();
175442
+ continue;
175443
+ }
175444
+ normalizedSegments.push(segment);
175445
+ }
175446
+ const canonical = normalizedSegments.length === 0 ? "/" : `/${normalizedSegments.join("/")}/`;
175447
+ return { valid: true, value: canonical };
175448
+ }
175449
+ var CONTROL_CHARACTER;
175450
+ var init_base_path = __esm({
175451
+ "../workers-shared/utils/base-path.ts"() {
175452
+ init_import_meta_url();
175453
+ CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
175454
+ __name(normalizeBasePath, "normalizeBasePath");
175455
+ }
175456
+ });
175457
+ function routeMatchesPath(route, pathname) {
175458
+ if (typeof route !== "string" && route.custom_domain) {
175459
+ return !("enabled" in route) || route.enabled !== false;
175460
+ }
175461
+ const pattern = typeof route === "string" ? route : route.pattern;
175462
+ const patternWithoutScheme = pattern.replace(/^https?:\/\//, "");
175463
+ const pathStart = patternWithoutScheme.indexOf("/");
175464
+ if (pathStart === -1) {
175465
+ return false;
175466
+ }
175467
+ const pathPattern = patternWithoutScheme.slice(pathStart);
175468
+ const regexpPattern = pathPattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*");
175469
+ return new RegExp(`^${regexpPattern}$`).test(pathname);
175470
+ }
175337
175471
  var validateRoutes2;
175338
175472
  var init_validate_routes = __esm({
175339
175473
  "../deploy-helpers/src/deploy/helpers/validate-routes.ts"() {
175340
175474
  init_import_meta_url();
175475
+ init_base_path();
175341
175476
  init_src();
175342
175477
  init_context();
175343
- validateRoutes2 = /* @__PURE__ */ __name((routes, assets) => {
175478
+ validateRoutes2 = /* @__PURE__ */ __name((routes, assets, workersDevEnabled) => {
175344
175479
  const invalidRoutes = {};
175345
175480
  const mountedAssetRoutes = [];
175346
175481
  for (const route of routes) {
@@ -175378,6 +175513,12 @@ var init_validate_routes = __esm({
175378
175513
  { telemetryMessage: "deploy invalid routes" }
175379
175514
  );
175380
175515
  }
175516
+ const basePath = normalizeBasePath(assets?.assetConfig.base_path);
175517
+ if (workersDevEnabled === false && basePath.valid && basePath.value !== "/" && !routes.some((route) => routeMatchesPath(route, basePath.value))) {
175518
+ logger.warn(
175519
+ `The configured assets base path "${basePath.value}" is not reachable through any configured route. Add a route that matches "${basePath.value}" or enable \`workers_dev\`.`
175520
+ );
175521
+ }
175381
175522
  if (mountedAssetRoutes.length > 0 && assets?.directory !== void 0) {
175382
175523
  const relativeAssetsDir = path28__namespace.default.relative(process.cwd(), assets.directory);
175383
175524
  const warnFn = logger.once?.warn ?? logger.warn;
@@ -175394,6 +175535,7 @@ ${mountedAssetRoutes.map((route) => {
175394
175535
  );
175395
175536
  }
175396
175537
  }, "validateRoutes");
175538
+ __name(routeMatchesPath, "routeMatchesPath");
175397
175539
  }
175398
175540
  });
175399
175541
  function validateWorkerProps(props, config2) {
@@ -175442,7 +175584,12 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m
175442
175584
  validateOwnedWorkflowDeclarations(config2, name2);
175443
175585
  if (props.command === "deploy") {
175444
175586
  validateEventTriggerTargets(config2, name2);
175445
- validateRoutes2(props.routes, props.assetsOptions);
175587
+ const workersDevEnabled = getSubdomainValues(
175588
+ config2.workers_dev,
175589
+ config2.preview_urls,
175590
+ props.routes
175591
+ ).workers_dev;
175592
+ validateRoutes2(props.routes, props.assetsOptions, workersDevEnabled);
175446
175593
  assert38__default.default(
175447
175594
  !config2.site || config2.site.bucket,
175448
175595
  "A [site] definition requires a `bucket` field with a path to the site's assets directory."
@@ -176620,6 +176767,42 @@ var init_versions_upload = __esm({
176620
176767
  __name(uploadWorkerVersion, "uploadWorkerVersion");
176621
176768
  }
176622
176769
  });
176770
+ function gitCommandText(stdout2) {
176771
+ if (typeof stdout2 === "string") {
176772
+ return stdout2;
176773
+ }
176774
+ if (stdout2 instanceof Uint8Array) {
176775
+ return new TextDecoder().decode(stdout2);
176776
+ }
176777
+ return "";
176778
+ }
176779
+ function resolveGitBranchName() {
176780
+ try {
176781
+ childProcess.execSync(`git rev-parse --is-inside-work-tree`, {
176782
+ stdio: ["ignore", "ignore", "ignore"]
176783
+ });
176784
+ } catch {
176785
+ return void 0;
176786
+ }
176787
+ try {
176788
+ const branch = gitCommandText(
176789
+ childProcess.execSync(`git branch --show-current`, {
176790
+ encoding: "utf8",
176791
+ stdio: ["ignore", "pipe", "ignore"]
176792
+ })
176793
+ ).trim();
176794
+ return branch || void 0;
176795
+ } catch {
176796
+ return void 0;
176797
+ }
176798
+ }
176799
+ var init_git_branch = __esm({
176800
+ "../deploy-helpers/src/shared/git-branch.ts"() {
176801
+ init_import_meta_url();
176802
+ __name(gitCommandText, "gitCommandText");
176803
+ __name(resolveGitBranchName, "resolveGitBranchName");
176804
+ }
176805
+ });
176623
176806
  function truncateWithSuffix(body, suffix, maxLength) {
176624
176807
  const maxBodyLength = Math.max(0, maxLength - suffix.length);
176625
176808
  return `${body.slice(0, maxBodyLength)}${suffix}`;
@@ -176644,12 +176827,7 @@ function getBranchName() {
176644
176827
  if (ciBranchName) {
176645
176828
  return ciBranchName;
176646
176829
  }
176647
- try {
176648
- childProcess.execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore" });
176649
- return childProcess.execSync(`git rev-parse --abbrev-ref HEAD`).toString().trim();
176650
- } catch {
176651
- return void 0;
176652
- }
176830
+ return resolveGitBranchName();
176653
176831
  }
176654
176832
  function createTruncatedAlias(branchName, sanitizedAlias, availableSpace) {
176655
176833
  const hash2 = crypto2.createHash("sha256").update(branchName).digest("hex").slice(0, HASH_LENGTH);
@@ -176691,6 +176869,7 @@ var init_preview_alias = __esm({
176691
176869
  init_import_meta_url();
176692
176870
  init_src();
176693
176871
  init_context();
176872
+ init_git_branch();
176694
176873
  init_names();
176695
176874
  MAX_DNS_LABEL_LENGTH = 63;
176696
176875
  HASH_LENGTH = 4;
@@ -176910,6 +177089,14 @@ var init_api2 = __esm({
176910
177089
  __name(patchPreviewBaseConfig, "patchPreviewBaseConfig");
176911
177090
  }
176912
177091
  });
177092
+ function readGitStdout(command2) {
177093
+ return gitCommandText(
177094
+ childProcess.execSync(command2, {
177095
+ encoding: "utf8",
177096
+ stdio: ["ignore", "pipe", "ignore"]
177097
+ })
177098
+ ).trim();
177099
+ }
176913
177100
  function getBranchName2() {
176914
177101
  const workersCIBranch = getWorkersCIBranchName();
176915
177102
  if (workersCIBranch) {
@@ -176923,12 +177110,7 @@ function getBranchName2() {
176923
177110
  if (gitlabBranch) {
176924
177111
  return gitlabBranch;
176925
177112
  }
176926
- try {
176927
- childProcess.execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore" });
176928
- return childProcess.execSync(`git rev-parse --abbrev-ref HEAD`).toString().trim();
176929
- } catch {
176930
- return void 0;
176931
- }
177113
+ return resolveGitBranchName();
176932
177114
  }
176933
177115
  function shouldUseCIMetadataFallback() {
176934
177116
  return process.env.CI === "1" || process.env.CI === "true";
@@ -176936,7 +177118,7 @@ function shouldUseCIMetadataFallback() {
176936
177118
  function getHeadCommitRef() {
176937
177119
  try {
176938
177120
  childProcess.execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore" });
176939
- return childProcess.execSync(`git rev-parse --short HEAD`).toString().trim();
177121
+ return readGitStdout(`git rev-parse --short HEAD`);
176940
177122
  } catch {
176941
177123
  return void 0;
176942
177124
  }
@@ -176944,7 +177126,7 @@ function getHeadCommitRef() {
176944
177126
  function getHeadCommitMessage() {
176945
177127
  try {
176946
177128
  childProcess.execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore" });
176947
- return childProcess.execSync(`git log -1 --format=%B`).toString().trim();
177129
+ return readGitStdout(`git log -1 --format=%B`);
176948
177130
  } catch {
176949
177131
  return void 0;
176950
177132
  }
@@ -176997,7 +177179,7 @@ function getRepositoryUrl() {
176997
177179
  try {
176998
177180
  childProcess.execSync(`git rev-parse --is-inside-work-tree`, { stdio: "ignore" });
176999
177181
  return normalizeRepositoryUrl(
177000
- childProcess.execSync(`git config --get remote.origin.url`).toString()
177182
+ readGitStdout(`git config --get remote.origin.url`)
177001
177183
  );
177002
177184
  } catch {
177003
177185
  return void 0;
@@ -177434,8 +177616,10 @@ var init_shared2 = __esm({
177434
177616
  "../deploy-helpers/src/preview/shared.ts"() {
177435
177617
  init_import_meta_url();
177436
177618
  init_src();
177619
+ init_git_branch();
177437
177620
  init_names();
177438
177621
  MAX_CONTAINER_APP_NAME_LENGTH = 253;
177622
+ __name(readGitStdout, "readGitStdout");
177439
177623
  __name(getBranchName2, "getBranchName");
177440
177624
  __name(shouldUseCIMetadataFallback, "shouldUseCIMetadataFallback");
177441
177625
  __name(getHeadCommitRef, "getHeadCommitRef");
@@ -177748,6 +177932,7 @@ async function assemblePreviewDeploymentSettings(config2, buildResult, accountId
177748
177932
  config: {
177749
177933
  html_handling: options.assetsOptions.assetConfig.html_handling,
177750
177934
  not_found_handling: options.assetsOptions.assetConfig.not_found_handling,
177935
+ base_path: options.assetsOptions.assetConfig.base_path,
177751
177936
  run_worker_first: options.assetsOptions.run_worker_first
177752
177937
  }
177753
177938
  };
@@ -179589,7 +179774,7 @@ var CF_KEYRING_SERVICE_NAME, CF_CLI_NAME, CF_DISPLAY_NAME, CF_OAUTH_CALLBACK_URL
179589
179774
  var init_cf = __esm({
179590
179775
  "../workers-auth/dist/cf/index.mjs"() {
179591
179776
  init_import_meta_url();
179592
- init_chunk_VVLCNASF();
179777
+ init_chunk_PGZZHNWG();
179593
179778
  init_chunk_VAZEJK55();
179594
179779
  init_src();
179595
179780
  nodeModule.createRequire(import_meta_url || (typeof __filename === "string" ? __filename : "/"));
@@ -180080,6 +180265,8 @@ var init_cf = __esm({
180080
180265
  "zone-disable-esc.write",
180081
180266
  "zone-dns-settings.read",
180082
180267
  "zone-dns-settings.write",
180268
+ "zone-observability.read",
180269
+ "zone-observability.write",
180083
180270
  "zone-security-center-insights.read",
180084
180271
  "zone-security-center-insights.write",
180085
180272
  "zone-settings.read",
@@ -180600,7 +180787,7 @@ var init_dist14 = __esm({
180600
180787
  init_wrapper();
180601
180788
  init_create_worker_upload_form();
180602
180789
  import_undici13 = __toESM(require_undici(), 1);
180603
- version3 = "0.0.42";
180790
+ version3 = "0.0.44";
180604
180791
  NoDefaultValueProvided2 = class extends UserError {
180605
180792
  static {
180606
180793
  __name(this, "NoDefaultValueProvided");
@@ -186581,6 +186768,12 @@ var init_dev = __esm({
186581
186768
  "tunnel-name": {
186582
186769
  describe: "Use an existing named Cloudflare Tunnel when `--tunnel` is enabled.",
186583
186770
  type: "string"
186771
+ },
186772
+ "tunnel-allowed-mail": {
186773
+ describe: "Require email authentication for a Quick Tunnel. Accepts an exact address or domain wildcard such as user@example.com or *@example.org. May be repeated or comma-separated.",
186774
+ type: "string",
186775
+ array: true,
186776
+ nargs: 1
186584
186777
  }
186585
186778
  },
186586
186779
  async validateArgs(args) {
@@ -186596,6 +186789,14 @@ var init_dev = __esm({
186596
186789
  { telemetryMessage: "dev command live reload remote conflict" }
186597
186790
  );
186598
186791
  }
186792
+ if (args.tunnelName && (args.tunnelAllowedMail?.length ?? 0) > 0) {
186793
+ throw new UserError(
186794
+ "--tunnel-allowed-mail is only supported for Quick Tunnels and cannot be used with --tunnel-name.",
186795
+ {
186796
+ telemetryMessage: "dev command tunnel allowed mail named conflict"
186797
+ }
186798
+ );
186799
+ }
186599
186800
  if (args.tunnel && args.remote) {
186600
186801
  throw new UserError(
186601
186802
  "--tunnel cannot be used with --remote. Tunnels expose your local dev server to the internet, which is only applicable in local mode. Remove --remote to use --tunnel, or remove --tunnel to use --remote.",
@@ -188776,7 +188977,7 @@ function renderContainerTable(apps2) {
188776
188977
  ID: app.id,
188777
188978
  NAME: app.name,
188778
188979
  STATE: colorState(state3),
188779
- "LIVE INSTANCES": String(app.instances),
188980
+ "LIVE INSTANCES": String(app.health.instances.active),
188780
188981
  "LAST MODIFIED": app.updated_at
188781
188982
  };
188782
188983
  })
@@ -196390,10 +196591,22 @@ var require_dist4 = __commonJS({
196390
196591
  }
196391
196592
  });
196392
196593
 
196594
+ // src/containers/application-id.ts
196595
+ function isValidApplicationId(id) {
196596
+ return APPLICATION_ID_REGEX.test(id);
196597
+ }
196598
+ var APPLICATION_ID_REGEX;
196599
+ var init_application_id = __esm({
196600
+ "src/containers/application-id.ts"() {
196601
+ init_import_meta_url();
196602
+ APPLICATION_ID_REGEX = /^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
196603
+ __name(isValidApplicationId, "isValidApplicationId");
196604
+ }
196605
+ });
196606
+
196393
196607
  // src/containers/containers.ts
196394
196608
  async function deleteCommand(deleteArgs, _config) {
196395
- const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
196396
- if (!uuidRegex.test(deleteArgs.ID)) {
196609
+ if (!isValidApplicationId(deleteArgs.ID)) {
196397
196610
  throw new UserError(
196398
196611
  `Expected a container ID but got ${deleteArgs.ID}. Use \`wrangler containers list\` to view your containers and corresponding IDs.`,
196399
196612
  { telemetryMessage: "containers delete invalid container id" }
@@ -196484,6 +196697,7 @@ var init_containers2 = __esm({
196484
196697
  init_wrap();
196485
196698
  init_create_command();
196486
196699
  init_logger2();
196700
+ init_application_id();
196487
196701
  init_containers3();
196488
196702
  __name(deleteCommand, "deleteCommand");
196489
196703
  __name(infoCommand, "infoCommand");
@@ -196725,8 +196939,7 @@ function renderTable(rows) {
196725
196939
  }
196726
196940
  }
196727
196941
  async function instancesCommand(args) {
196728
- const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
196729
- if (!uuidRegex.test(args.ID)) {
196942
+ if (!isValidApplicationId(args.ID)) {
196730
196943
  throw new UserError(
196731
196944
  `Expected an application ID but got ${args.ID}. Use \`wrangler containers list\` to view your containers and corresponding IDs.`,
196732
196945
  { telemetryMessage: "containers instances invalid application id" }
@@ -196873,6 +197086,7 @@ var init_instances2 = __esm({
196873
197086
  init_create_command();
196874
197087
  init_logger2();
196875
197088
  init_onKeyPress();
197089
+ init_application_id();
196876
197090
  init_containers3();
196877
197091
  DEFAULT_PER_PAGE = 25;
196878
197092
  __name(deriveInstanceState, "deriveInstanceState");
@@ -203557,14 +203771,267 @@ function constructTypeKey(key) {
203557
203771
  }
203558
203772
  return `"${escapeTypeScriptString(key)}"`;
203559
203773
  }
203560
- function constructTSModuleGlob(glob) {
203774
+ function getTSModuleGlob(glob) {
203561
203775
  if (!glob.includes("*")) {
203562
- return glob;
203563
- } else if (glob.includes(".")) {
203564
- return `*.${glob.split(".").at(-1)}`;
203565
- } else {
203566
- return glob.replace("**/*", "*").replace("**/", "*/").replace("/**", "/*");
203776
+ return {
203777
+ moduleGlob: glob,
203778
+ fallbackModuleGlob: getFallbackModuleGlob(glob),
203779
+ preservesScope: true,
203780
+ isRecursiveFallback: false,
203781
+ emitsFallback: false
203782
+ };
203783
+ }
203784
+ const moduleGlob = glob.replaceAll("**/*", "*").replaceAll("**/", "*/").replaceAll("/**", "/*");
203785
+ const fallbackModuleGlob = getFallbackModuleGlob(glob);
203786
+ const preservesScope = moduleGlob.indexOf("*") === moduleGlob.lastIndexOf("*");
203787
+ return {
203788
+ moduleGlob: preservesScope ? moduleGlob : fallbackModuleGlob ?? "*",
203789
+ fallbackModuleGlob,
203790
+ preservesScope,
203791
+ isRecursiveFallback: preservesScope && moduleGlob === fallbackModuleGlob && glob.startsWith("**/"),
203792
+ emitsFallback: true
203793
+ };
203794
+ }
203795
+ function getFallbackModuleGlob(glob) {
203796
+ const lastAsteriskIndex = glob.lastIndexOf("*");
203797
+ if (lastAsteriskIndex !== -1) {
203798
+ const suffix = glob.slice(lastAsteriskIndex + 1);
203799
+ return suffix ? `*${suffix}` : void 0;
203800
+ }
203801
+ const lastSlashIndex = Math.max(
203802
+ glob.lastIndexOf("/"),
203803
+ glob.lastIndexOf("\\")
203804
+ );
203805
+ const lastDotIndex = glob.lastIndexOf(".");
203806
+ return lastDotIndex > lastSlashIndex ? `*${glob.slice(lastDotIndex)}` : void 0;
203807
+ }
203808
+ function isAdditionalModuleDiscoveryEnabled(config2) {
203809
+ return config2.find_additional_modules ?? config2.no_bundle === true;
203810
+ }
203811
+ function generateModuleTypeDeclarations(rules = [], resolveOverlappingGlobs = false, findAdditionalModules2 = false) {
203812
+ const moduleTypeMap = {
203813
+ CompiledWasm: "WebAssembly.Module",
203814
+ Data: "ArrayBuffer",
203815
+ Text: "string"
203816
+ };
203817
+ const declarations = new Array();
203818
+ if (!resolveOverlappingGlobs) {
203819
+ for (const rule of rules) {
203820
+ const typeScriptType = moduleTypeMap[rule.type];
203821
+ if (typeScriptType === void 0) {
203822
+ continue;
203823
+ }
203824
+ for (const glob of rule.globs) {
203825
+ declarations.push(
203826
+ generateModuleTypeDeclaration(getTSModuleGlob(glob).moduleGlob, [
203827
+ typeScriptType
203828
+ ])
203829
+ );
203830
+ }
203831
+ }
203832
+ return declarations;
203833
+ }
203834
+ return generateCombinedModuleTypeDeclarations([
203835
+ { findAdditionalModules: findAdditionalModules2, rules }
203836
+ ]);
203837
+ }
203838
+ function resolveModuleTypeDeclarations(ruleSet5) {
203839
+ const { findAdditionalModules: findAdditionalModules2, rules } = ruleSet5;
203840
+ const moduleTypeMap = {
203841
+ CompiledWasm: "WebAssembly.Module",
203842
+ Data: "ArrayBuffer",
203843
+ Text: "string"
203844
+ };
203845
+ const seenRuleGlobs = /* @__PURE__ */ new Set();
203846
+ const scopedDeclarations = /* @__PURE__ */ new Map();
203847
+ const fallbackDeclarations = /* @__PURE__ */ new Map();
203848
+ const matchingRules = new Array();
203849
+ for (const rule of rules) {
203850
+ const typeScriptType = moduleTypeMap[rule.type];
203851
+ if (typeScriptType === void 0) {
203852
+ continue;
203853
+ }
203854
+ for (const glob of rule.globs) {
203855
+ const {
203856
+ moduleGlob,
203857
+ fallbackModuleGlob,
203858
+ preservesScope,
203859
+ isRecursiveFallback,
203860
+ emitsFallback
203861
+ } = getTSModuleGlob(glob);
203862
+ if (seenRuleGlobs.has(glob)) {
203863
+ continue;
203864
+ }
203865
+ seenRuleGlobs.add(glob);
203866
+ matchingRules.push({
203867
+ deploymentGlob: glob,
203868
+ isConservativeFallback: !preservesScope,
203869
+ moduleGlob,
203870
+ type: typeScriptType
203871
+ });
203872
+ if (fallbackModuleGlob === void 0) {
203873
+ const types14 = scopedDeclarations.get(moduleGlob) ?? /* @__PURE__ */ new Set();
203874
+ types14.add(typeScriptType);
203875
+ scopedDeclarations.set(moduleGlob, types14);
203876
+ continue;
203877
+ }
203878
+ const fallbackDeclaration = fallbackDeclarations.get(
203879
+ fallbackModuleGlob
203880
+ ) ?? {
203881
+ types: /* @__PURE__ */ new Set(),
203882
+ recursiveRuleSeen: false,
203883
+ shouldEmit: false
203884
+ };
203885
+ if (fallbackDeclaration.recursiveRuleSeen) {
203886
+ continue;
203887
+ }
203888
+ if (preservesScope && moduleGlob !== fallbackModuleGlob) {
203889
+ const types14 = scopedDeclarations.get(moduleGlob) ?? /* @__PURE__ */ new Set();
203890
+ types14.add(typeScriptType);
203891
+ scopedDeclarations.set(moduleGlob, types14);
203892
+ }
203893
+ fallbackDeclaration.types.add(typeScriptType);
203894
+ fallbackDeclaration.recursiveRuleSeen = isRecursiveFallback;
203895
+ fallbackDeclaration.shouldEmit ||= emitsFallback;
203896
+ fallbackDeclarations.set(fallbackModuleGlob, fallbackDeclaration);
203897
+ }
203898
+ }
203899
+ return {
203900
+ findAdditionalModules: findAdditionalModules2,
203901
+ scoped: scopedDeclarations,
203902
+ fallbacks: fallbackDeclarations,
203903
+ matchingRules
203904
+ };
203905
+ }
203906
+ function intersectModuleGlobs(left2, right2) {
203907
+ const leftAsteriskIndex = left2.indexOf("*");
203908
+ const rightAsteriskIndex = right2.indexOf("*");
203909
+ if (leftAsteriskIndex === -1) {
203910
+ return moduleGlobMatches(right2, left2) ? left2 : void 0;
203911
+ }
203912
+ if (rightAsteriskIndex === -1) {
203913
+ return moduleGlobMatches(left2, right2) ? right2 : void 0;
203914
+ }
203915
+ const leftPrefix = left2.slice(0, leftAsteriskIndex);
203916
+ const rightPrefix = right2.slice(0, rightAsteriskIndex);
203917
+ if (!leftPrefix.startsWith(rightPrefix) && !rightPrefix.startsWith(leftPrefix)) {
203918
+ return void 0;
203919
+ }
203920
+ const leftSuffix = left2.slice(leftAsteriskIndex + 1);
203921
+ const rightSuffix = right2.slice(rightAsteriskIndex + 1);
203922
+ if (!leftSuffix.endsWith(rightSuffix) && !rightSuffix.endsWith(leftSuffix)) {
203923
+ return void 0;
203924
+ }
203925
+ const prefix = leftPrefix.length >= rightPrefix.length ? leftPrefix : rightPrefix;
203926
+ const suffix = leftSuffix.length >= rightSuffix.length ? leftSuffix : rightSuffix;
203927
+ return `${prefix}*${suffix}`;
203928
+ }
203929
+ function moduleGlobMatches(moduleGlob, moduleName) {
203930
+ const asteriskIndex = moduleGlob.indexOf("*");
203931
+ if (asteriskIndex === -1) {
203932
+ return moduleGlob === moduleName;
203933
+ }
203934
+ const prefix = moduleGlob.slice(0, asteriskIndex);
203935
+ const suffix = moduleGlob.slice(asteriskIndex + 1);
203936
+ return moduleName.length >= prefix.length + suffix.length && moduleName.startsWith(prefix) && moduleName.endsWith(suffix);
203937
+ }
203938
+ function moduleGlobContains(container, contained) {
203939
+ const containedAsteriskIndex = contained.indexOf("*");
203940
+ if (containedAsteriskIndex === -1) {
203941
+ return moduleGlobMatches(container, contained);
203942
+ }
203943
+ const containerAsteriskIndex = container.indexOf("*");
203944
+ if (containerAsteriskIndex === -1) {
203945
+ return false;
203946
+ }
203947
+ const containerPrefix = container.slice(0, containerAsteriskIndex);
203948
+ const containedPrefix = contained.slice(0, containedAsteriskIndex);
203949
+ const containerSuffix = container.slice(containerAsteriskIndex + 1);
203950
+ const containedSuffix = contained.slice(containedAsteriskIndex + 1);
203951
+ return containedPrefix.startsWith(containerPrefix) && containedSuffix.endsWith(containerSuffix);
203952
+ }
203953
+ function resolveMatchingModuleTypes(moduleGlob, matchingRules, findAdditionalModules2) {
203954
+ const types14 = /* @__PURE__ */ new Set();
203955
+ const coveredPatterns = new Array();
203956
+ const exactModuleName = moduleGlob.includes("*") ? void 0 : moduleGlob;
203957
+ for (const rule of matchingRules) {
203958
+ const deploymentRegExp = findAdditionalModules2 ? (0, import_glob_to_regexp3.default)(rule.deploymentGlob, { globstar: true }) : (0, import_glob_to_regexp3.default)(rule.deploymentGlob);
203959
+ const conservativeFallbackMatchesExact = exactModuleName !== void 0 && rule.isConservativeFallback && deploymentRegExp.test(exactModuleName);
203960
+ if (exactModuleName !== void 0 && rule.isConservativeFallback && !conservativeFallbackMatchesExact) {
203961
+ continue;
203962
+ }
203963
+ const overlap = intersectModuleGlobs(moduleGlob, rule.moduleGlob);
203964
+ if (overlap === void 0 || coveredPatterns.some((pattern) => moduleGlobContains(pattern, overlap))) {
203965
+ continue;
203966
+ }
203967
+ types14.add(rule.type);
203968
+ if (!rule.isConservativeFallback || conservativeFallbackMatchesExact) {
203969
+ coveredPatterns.push(overlap);
203970
+ if (moduleGlobContains(rule.moduleGlob, moduleGlob)) {
203971
+ break;
203972
+ }
203973
+ }
203974
+ }
203975
+ return types14;
203976
+ }
203977
+ function generateCombinedModuleTypeDeclarations(ruleSets) {
203978
+ const combinedDeclarations = /* @__PURE__ */ new Map();
203979
+ const combinedFallbacks = /* @__PURE__ */ new Map();
203980
+ const resolvedRuleSets = ruleSets.map(resolveModuleTypeDeclarations);
203981
+ for (const { scoped, fallbacks } of resolvedRuleSets) {
203982
+ for (const moduleGlob of scoped.keys()) {
203983
+ combinedDeclarations.set(
203984
+ moduleGlob,
203985
+ combinedDeclarations.get(moduleGlob) ?? /* @__PURE__ */ new Set()
203986
+ );
203987
+ }
203988
+ for (const [moduleGlob, { types: types14, shouldEmit }] of fallbacks) {
203989
+ const combinedFallback = combinedFallbacks.get(moduleGlob) ?? {
203990
+ types: /* @__PURE__ */ new Set(),
203991
+ shouldEmit: false
203992
+ };
203993
+ for (const type of types14) {
203994
+ combinedFallback.types.add(type);
203995
+ }
203996
+ combinedFallback.shouldEmit ||= shouldEmit;
203997
+ combinedFallbacks.set(moduleGlob, combinedFallback);
203998
+ }
203999
+ }
204000
+ for (const [moduleGlob, { types: types14, shouldEmit }] of combinedFallbacks) {
204001
+ if (!shouldEmit && types14.size === 1) {
204002
+ continue;
204003
+ }
204004
+ combinedDeclarations.set(
204005
+ moduleGlob,
204006
+ combinedDeclarations.get(moduleGlob) ?? /* @__PURE__ */ new Set()
204007
+ );
203567
204008
  }
204009
+ for (const [moduleGlob, combinedTypes] of combinedDeclarations) {
204010
+ for (const { findAdditionalModules: findAdditionalModules2, matchingRules } of resolvedRuleSets) {
204011
+ for (const type of resolveMatchingModuleTypes(
204012
+ moduleGlob,
204013
+ matchingRules,
204014
+ findAdditionalModules2
204015
+ )) {
204016
+ combinedTypes.add(type);
204017
+ }
204018
+ }
204019
+ }
204020
+ return [...combinedDeclarations].map(
204021
+ ([moduleGlob, types14]) => generateModuleTypeDeclaration(moduleGlob, types14)
204022
+ );
204023
+ }
204024
+ function generateModuleTypeDeclaration(moduleGlob, types14) {
204025
+ return `declare module "${moduleGlob}" {
204026
+ const value: ${[...types14].join(" | ")};
204027
+ export default value;
204028
+ }`;
204029
+ }
204030
+ function generateServiceWorkerTypes(typeDefinitions, envTypeStructure) {
204031
+ return [
204032
+ ...typeDefinitions,
204033
+ ...envTypeStructure.map((value) => `declare const ${value}`)
204034
+ ].join("\n");
203568
204035
  }
203569
204036
  function generateImportSpecifier(from, to) {
203570
204037
  const relativePath = path28.relative(path28.dirname(from), path28.dirname(to)).replace(/\\/g, "/");
@@ -203824,33 +204291,22 @@ async function generateSimpleEnvTypes(config2, collectionArgs, envInterface, out
203824
204291
  });
203825
204292
  }
203826
204293
  }
203827
- const modulesTypeStructure = new Array();
203828
- if (config2.rules) {
203829
- const moduleTypeMap = {
203830
- CompiledWasm: "WebAssembly.Module",
203831
- Data: "ArrayBuffer",
203832
- Text: "string"
203833
- };
203834
- for (const ruleObject of config2.rules) {
203835
- const typeScriptType = moduleTypeMap[ruleObject.type];
203836
- if (typeScriptType === void 0) {
203837
- continue;
203838
- }
203839
- for (const glob of ruleObject.globs) {
203840
- modulesTypeStructure.push(`declare module "${constructTSModuleGlob(glob)}" {
203841
- const value: ${typeScriptType};
203842
- export default value;
203843
- }`);
203844
- }
203845
- }
203846
- }
203847
- const typesHaveBeenFound = envTypeStructure.length > 0 || modulesTypeStructure.length > 0;
204294
+ const configuredModulesTypeStructure = generateModuleTypeDeclarations(
204295
+ config2.rules
204296
+ );
204297
+ const effectiveModulesTypeStructure = generateModuleTypeDeclarations(
204298
+ parseRules(config2.rules, log2).rules,
204299
+ true,
204300
+ isAdditionalModuleDiscoveryEnabled(config2)
204301
+ );
204302
+ const typesHaveBeenFound = envTypeStructure.length > 0 || effectiveModulesTypeStructure.length > 0;
203848
204303
  if (entrypointFormat === "modules" || typesHaveBeenFound) {
203849
204304
  const { consoleOutput, fileContent } = generateTypeStrings(
203850
204305
  entrypointFormat,
203851
204306
  envInterface,
203852
204307
  envTypeStructure.map(({ key, type }) => `${key}: ${type};`),
203853
- modulesTypeStructure,
204308
+ configuredModulesTypeStructure,
204309
+ effectiveModulesTypeStructure,
203854
204310
  stringKeys,
203855
204311
  config2.compatibility_date,
203856
204312
  config2.compatibility_flags,
@@ -203863,7 +204319,7 @@ async function generateSimpleEnvTypes(config2, collectionArgs, envInterface, out
203863
204319
  ],
203864
204320
  typeDefinitions
203865
204321
  );
203866
- const hash2 = crypto2.createHash("sha256").update(consoleOutput).digest("hex").slice(0, 32);
204322
+ const hash2 = crypto2.createHash("sha256").update(fileContent).digest("hex").slice(0, 32);
203867
204323
  if (log2) {
203868
204324
  logger2.log(source_default.dim(consoleOutput));
203869
204325
  }
@@ -204130,31 +204586,41 @@ ${bindingLines}
204130
204586
  });
204131
204587
  }
204132
204588
  }
204133
- const modulesTypeStructure = new Array();
204134
- if (config2.rules) {
204135
- const moduleTypeMap = {
204136
- CompiledWasm: "WebAssembly.Module",
204137
- Data: "ArrayBuffer",
204138
- Text: "string"
204139
- };
204140
- for (const ruleObject of config2.rules) {
204141
- const typeScriptType = moduleTypeMap[ruleObject.type];
204142
- if (typeScriptType !== void 0) {
204143
- for (const glob of ruleObject.globs) {
204144
- modulesTypeStructure.push(`declare module "${constructTSModuleGlob(glob)}" {
204145
- const value: ${typeScriptType};
204146
- export default value;
204147
- }`);
204148
- }
204149
- }
204150
- }
204151
- }
204589
+ const environmentRuleSets = [
204590
+ {
204591
+ findAdditionalModules: isAdditionalModuleDiscoveryEnabled(config2),
204592
+ rules: config2.rules
204593
+ },
204594
+ ...envNames.map((envName) => {
204595
+ const environmentConfig = readConfig(
204596
+ { ...collectionArgs, env: envName },
204597
+ { hideWarnings: true }
204598
+ );
204599
+ return {
204600
+ findAdditionalModules: isAdditionalModuleDiscoveryEnabled(environmentConfig),
204601
+ rules: environmentConfig.rules
204602
+ };
204603
+ })
204604
+ ];
204605
+ const uniqueRuleSets = [
204606
+ ...new Map(
204607
+ environmentRuleSets.map((ruleSet5) => [JSON.stringify(ruleSet5), ruleSet5])
204608
+ ).values()
204609
+ ];
204610
+ const configuredModulesTypeStructure = generateCombinedModuleTypeDeclarations(uniqueRuleSets);
204611
+ const effectiveModulesTypeStructure = generateCombinedModuleTypeDeclarations(
204612
+ uniqueRuleSets.map(({ findAdditionalModules: findAdditionalModules2, rules }) => ({
204613
+ findAdditionalModules: findAdditionalModules2,
204614
+ rules: parseRules(rules, log2).rules
204615
+ }))
204616
+ );
204152
204617
  const { consoleOutput, fileContent } = generatePerEnvTypeStrings(
204153
204618
  entrypointFormat,
204154
204619
  envInterface,
204155
204620
  perEnvInterfaces,
204156
204621
  aggregatedEnvBindings,
204157
- modulesTypeStructure,
204622
+ configuredModulesTypeStructure,
204623
+ effectiveModulesTypeStructure,
204158
204624
  stringKeys,
204159
204625
  config2.compatibility_date,
204160
204626
  config2.compatibility_flags,
@@ -204167,7 +204633,7 @@ ${bindingLines}
204167
204633
  ],
204168
204634
  [...typeDefinitions]
204169
204635
  );
204170
- const hash2 = crypto2.createHash("sha256").update(consoleOutput).digest("hex").slice(0, 32);
204636
+ const hash2 = crypto2.createHash("sha256").update(fileContent).digest("hex").slice(0, 32);
204171
204637
  if (log2) {
204172
204638
  logger2.log(source_default.dim(consoleOutput));
204173
204639
  }
@@ -204179,8 +204645,9 @@ ${bindingLines}
204179
204645
  function prefixEnvInterface(envInterface) {
204180
204646
  return `__BaseEnv_${envInterface}`;
204181
204647
  }
204182
- function generatePerEnvTypeStrings(formatType, envInterface, perEnvInterfaces, aggregatedEnvBindings, modulesTypeStructure, stringKeys, compatibilityDate, compatibilityFlags, entrypointModule, configuredDurableObjects, typeDefinitions = []) {
204648
+ function generatePerEnvTypeStrings(formatType, envInterface, perEnvInterfaces, aggregatedEnvBindings, consoleModulesTypeStructure, fileModulesTypeStructure, stringKeys, compatibilityDate, compatibilityFlags, entrypointModule, configuredDurableObjects, typeDefinitions = []) {
204183
204649
  let baseContent = "";
204650
+ let fileBaseContent;
204184
204651
  let processEnv = "";
204185
204652
  const typeDefsContent = typeDefinitions.length > 0 ? typeDefinitions.map((def) => ` ${def}`).join("\n") : "";
204186
204653
  if (formatType === "modules") {
@@ -204217,17 +204684,22 @@ interface ${envInterface} extends ${internalEnvInterface} {}${processEnv}`;
204217
204684
  declare global {
204218
204685
  ${envBindingLines}
204219
204686
  }`;
204687
+ fileBaseContent = generateServiceWorkerTypes(
204688
+ typeDefinitions,
204689
+ aggregatedEnvBindings.map(({ key, type }) => `${key}: ${type};`)
204690
+ );
204220
204691
  }
204221
- const modulesContent = modulesTypeStructure.join("\n");
204692
+ const consoleModulesContent = consoleModulesTypeStructure.join("\n");
204693
+ const fileModulesContent = fileModulesTypeStructure.join("\n");
204222
204694
  return {
204223
204695
  consoleOutput: `${baseContent}
204224
- ${modulesContent}`,
204225
- fileContent: `${baseContent}
204226
- ${modulesContent}`
204696
+ ${consoleModulesContent}`,
204697
+ fileContent: [fileBaseContent ?? baseContent, fileModulesContent].filter((content) => content.length > 0).join("\n")
204227
204698
  };
204228
204699
  }
204229
- function generateTypeStrings(formatType, envInterface, envTypeStructure, modulesTypeStructure, stringKeys, compatibilityDate, compatibilityFlags, entrypointModule, configuredDurableObjects, typeDefinitions = []) {
204700
+ function generateTypeStrings(formatType, envInterface, envTypeStructure, consoleModulesTypeStructure, fileModulesTypeStructure, stringKeys, compatibilityDate, compatibilityFlags, entrypointModule, configuredDurableObjects, typeDefinitions = []) {
204230
204701
  let baseContent = "";
204702
+ let fileBaseContent;
204231
204703
  let processEnv = "";
204232
204704
  const typeDefsContent = typeDefinitions.length > 0 ? typeDefinitions.map((def) => ` ${def}`).join("\n") : "";
204233
204705
  if (formatType === "modules") {
@@ -204259,13 +204731,17 @@ interface ${envInterface} extends ${internalEnvInterface} {}${processEnv}`;
204259
204731
  declare global {
204260
204732
  ${envTypeStructure.map((value) => ` const ${value}`).join("\n")}
204261
204733
  }`;
204734
+ fileBaseContent = generateServiceWorkerTypes(
204735
+ typeDefinitions,
204736
+ envTypeStructure
204737
+ );
204262
204738
  }
204263
- const modulesContent = modulesTypeStructure.join("\n");
204739
+ const consoleModulesContent = consoleModulesTypeStructure.join("\n");
204740
+ const fileModulesContent = fileModulesTypeStructure.join("\n");
204264
204741
  return {
204265
- fileContent: `${baseContent}
204266
- ${modulesContent}`,
204742
+ fileContent: [fileBaseContent ?? baseContent, fileModulesContent].filter((content) => content.length > 0).join("\n"),
204267
204743
  consoleOutput: `${baseContent}
204268
- ${modulesContent}`
204744
+ ${consoleModulesContent}`
204269
204745
  };
204270
204746
  }
204271
204747
  function readTsconfigTypes(tsconfigPath) {
@@ -205834,7 +206310,7 @@ function collectPipelinesPerEnvironment(args) {
205834
206310
  }
205835
206311
  return result;
205836
206312
  }
205837
- var typesCommand, validateTypesFile, logHorizontalRule, INHERITABLE_BINDINGS;
206313
+ var import_glob_to_regexp3, typesCommand, validateTypesFile, logHorizontalRule, INHERITABLE_BINDINGS;
205838
206314
  var init_type_generation = __esm({
205839
206315
  "src/type-generation/index.ts"() {
205840
206316
  init_import_meta_url();
@@ -205842,10 +206318,12 @@ var init_type_generation = __esm({
205842
206318
  init_src();
205843
206319
  init_source();
205844
206320
  init_find();
206321
+ import_glob_to_regexp3 = __toESM(require_glob_to_regexp());
205845
206322
  init_yargs();
205846
206323
  init_config6();
205847
206324
  init_create_command();
205848
206325
  init_entry();
206326
+ init_rules13();
205849
206327
  init_class_names_sqlite();
205850
206328
  init_dev_vars();
205851
206329
  init_logger2();
@@ -206022,7 +206500,18 @@ var init_type_generation = __esm({
206022
206500
  __name(isValidIdentifier2, "isValidIdentifier");
206023
206501
  __name(escapeTypeScriptString, "escapeTypeScriptString");
206024
206502
  __name(constructTypeKey, "constructTypeKey");
206025
- __name(constructTSModuleGlob, "constructTSModuleGlob");
206503
+ __name(getTSModuleGlob, "getTSModuleGlob");
206504
+ __name(getFallbackModuleGlob, "getFallbackModuleGlob");
206505
+ __name(isAdditionalModuleDiscoveryEnabled, "isAdditionalModuleDiscoveryEnabled");
206506
+ __name(generateModuleTypeDeclarations, "generateModuleTypeDeclarations");
206507
+ __name(resolveModuleTypeDeclarations, "resolveModuleTypeDeclarations");
206508
+ __name(intersectModuleGlobs, "intersectModuleGlobs");
206509
+ __name(moduleGlobMatches, "moduleGlobMatches");
206510
+ __name(moduleGlobContains, "moduleGlobContains");
206511
+ __name(resolveMatchingModuleTypes, "resolveMatchingModuleTypes");
206512
+ __name(generateCombinedModuleTypeDeclarations, "generateCombinedModuleTypeDeclarations");
206513
+ __name(generateModuleTypeDeclaration, "generateModuleTypeDeclaration");
206514
+ __name(generateServiceWorkerTypes, "generateServiceWorkerTypes");
206026
206515
  __name(generateImportSpecifier, "generateImportSpecifier");
206027
206516
  __name(hasConfigSecrets, "hasConfigSecrets");
206028
206517
  __name(generateEnvTypes, "generateEnvTypes");
@@ -232116,7 +232605,7 @@ async function executeSql({
232116
232605
  preview: preview2
232117
232606
  }) {
232118
232607
  const existingLogLevel = logger2.loggerLevel;
232119
- if (json2) {
232608
+ if (json2 && existingLogLevel !== "none") {
232120
232609
  logger2.loggerLevel = "error";
232121
232610
  }
232122
232611
  try {
@@ -232575,7 +233064,7 @@ var init_execute = __esm({
232575
233064
  preview: preview2
232576
233065
  } = args;
232577
233066
  const existingLogLevel = logger2.loggerLevel;
232578
- if (json2) {
233067
+ if (json2 && existingLogLevel !== "none") {
232579
233068
  logger2.loggerLevel = "error";
232580
233069
  }
232581
233070
  if (file3 && command2) {
@@ -295631,7 +296120,7 @@ var init_split = __esm({
295631
296120
  conditions: [],
295632
296121
  serve_variation: variation,
295633
296122
  rollout: {
295634
- percentage: Math.min(100, Number(cumulative.toFixed(6))),
296123
+ percentage: Math.min(100, Number(cumulative.toFixed(2))),
295635
296124
  attribute: args.by
295636
296125
  }
295637
296126
  });
@@ -297814,6 +298303,14 @@ var init_kv2 = __esm({
297814
298303
  describe: 'The jurisdiction where the new namespace will be created (e.g. "us", "eu", "fedramp")',
297815
298304
  requiresArg: true
297816
298305
  },
298306
+ "experimental-mode": {
298307
+ alias: "x-mode",
298308
+ type: "string",
298309
+ describe: "The storage mode for the new namespace. Instant mode offers lower-latency reads and faster global updates [private beta].\nCannot be combined with --jurisdiction.",
298310
+ choices: ["instant"],
298311
+ requiresArg: true,
298312
+ conflicts: "jurisdiction"
298313
+ },
297817
298314
  ...sharedResourceCreationArgs
297818
298315
  },
297819
298316
  positionalArgs: ["namespace"],
@@ -297822,18 +298319,19 @@ var init_kv2 = __esm({
297822
298319
  const environment = args.env ? `${args.env}-` : "";
297823
298320
  const preview2 = args.preview ? "_preview" : "";
297824
298321
  const title = `${environment}${args.namespace}${preview2}`;
297825
- const { jurisdiction } = args;
298322
+ const { jurisdiction, experimentalMode: mode } = args;
297826
298323
  const accountId = await requireAuth(config2);
297827
298324
  printResourceLocation("remote");
297828
298325
  logger2.log(
297829
- `\u{1F300} Creating namespace with title "${title}"${jurisdiction ? ` (jurisdiction: ${jurisdiction})` : ""}`
298326
+ `\u{1F300} Creating namespace with title "${title}"${jurisdiction ? ` (jurisdiction: ${jurisdiction})` : ""}${mode ? ` (mode: ${mode})` : ""}`
297830
298327
  );
297831
298328
  let namespaceId;
297832
298329
  try {
297833
298330
  const createParams = {
297834
298331
  account_id: accountId,
297835
298332
  title,
297836
- jurisdiction
298333
+ jurisdiction,
298334
+ mode
297837
298335
  };
297838
298336
  const result = await sdk.kv.namespaces.create(createParams);
297839
298337
  namespaceId = result.id;
@@ -304823,6 +305321,7 @@ ${JSON.stringify(defaultRoutesJSONSpec, null, 2)}`
304823
305321
  tsconfig: void 0,
304824
305322
  minify: void 0,
304825
305323
  tunnelName: void 0,
305324
+ tunnelAllowedMail: void 0,
304826
305325
  env: void 0,
304827
305326
  envFile: void 0,
304828
305327
  ip,
@@ -305238,6 +305737,19 @@ var init_getLegacyScriptName = __esm({
305238
305737
  });
305239
305738
 
305240
305739
  // src/secret/index.ts
305740
+ function throwIfLatestVersionNotDeployed(e11, versionsCommand, telemetryMessage) {
305741
+ if (e11 instanceof APIError && e11.code !== void 0 && VERSION_NOT_DEPLOYED_ERR_CODES.includes(e11.code)) {
305742
+ throw new UserError(
305743
+ `Secret edit failed. You attempted to modify a secret, but the latest version of your Worker isn't currently deployed.
305744
+ This limitation exists to prevent accidental deployment when using Worker versions and secrets together.
305745
+ To resolve this, you have two options:
305746
+ (1) use the \`${versionsCommand}\` instead, which allows you to update secrets without deploying; or
305747
+ (2) deploy the latest version first, then modify secrets.
305748
+ Alternatively, you can use the Cloudflare dashboard to modify secrets and deploy the version.`,
305749
+ { telemetryMessage }
305750
+ );
305751
+ }
305752
+ }
305241
305753
  async function createDraftWorker({
305242
305754
  config: config2,
305243
305755
  accountId,
@@ -305306,14 +305818,23 @@ async function putBulkSecrets(config2, accountId, scriptName, content) {
305306
305818
  secrets[key] = null;
305307
305819
  }
305308
305820
  }
305309
- const resp = await fetchResult2(config2, url4, {
305310
- method: "PATCH",
305311
- headers: { "Content-Type": "application/merge-patch+json" },
305312
- body: JSON.stringify({ secrets })
305313
- });
305314
- return [resp, toCreate, toDelete];
305821
+ try {
305822
+ const resp = await fetchResult2(config2, url4, {
305823
+ method: "PATCH",
305824
+ headers: { "Content-Type": "application/merge-patch+json" },
305825
+ body: JSON.stringify({ secrets })
305826
+ });
305827
+ return [resp, toCreate, toDelete];
305828
+ } catch (e11) {
305829
+ throwIfLatestVersionNotDeployed(
305830
+ e11,
305831
+ "wrangler versions secret bulk",
305832
+ "secret bulk version not deployed"
305833
+ );
305834
+ throw e11;
305835
+ }
305315
305836
  }
305316
- var VERSION_NOT_DEPLOYED_ERR_CODE, secretNamespace, secretPutCommand, secretDeleteCommand, secretListCommand, secretBulkCommand;
305837
+ var VERSION_NOT_DEPLOYED_ERR_CODE, VERSION_SETTINGS_NOT_DEPLOYED_ERR_CODE, VERSION_NOT_DEPLOYED_ERR_CODES, secretNamespace, secretPutCommand, secretDeleteCommand, secretListCommand, secretBulkCommand;
305317
305838
  var init_secret = __esm({
305318
305839
  "src/secret/index.ts"() {
305319
305840
  init_import_meta_url();
@@ -305330,6 +305851,12 @@ var init_secret = __esm({
305330
305851
  init_std();
305331
305852
  init_src3();
305332
305853
  VERSION_NOT_DEPLOYED_ERR_CODE = 10215;
305854
+ VERSION_SETTINGS_NOT_DEPLOYED_ERR_CODE = 10214;
305855
+ VERSION_NOT_DEPLOYED_ERR_CODES = [
305856
+ VERSION_NOT_DEPLOYED_ERR_CODE,
305857
+ VERSION_SETTINGS_NOT_DEPLOYED_ERR_CODE
305858
+ ];
305859
+ __name(throwIfLatestVersionNotDeployed, "throwIfLatestVersionNotDeployed");
305333
305860
  __name(createDraftWorker, "createDraftWorker");
305334
305861
  secretNamespace = createNamespace({
305335
305862
  metadata: {
@@ -305396,14 +305923,12 @@ var init_secret = __esm({
305396
305923
  })
305397
305924
  });
305398
305925
  } catch (e11) {
305399
- if (e11 instanceof APIError && e11.code === VERSION_NOT_DEPLOYED_ERR_CODE) {
305400
- throw new UserError(
305401
- "Secret edit failed. You attempted to modify a secret, but the latest version of your Worker isn't currently deployed.\nThis limitation exists to prevent accidental deployment when using Worker versions and secrets together.\nTo resolve this, you have two options:\n(1) use the `wrangler versions secret put` instead, which allows you to update secrets without deploying; or\n(2) deploy the latest version first, then modify secrets.\nAlternatively, you can use the Cloudflare dashboard to modify secrets and deploy the version.",
305402
- { telemetryMessage: "secret put version not deployed" }
305403
- );
305404
- } else {
305405
- throw e11;
305406
- }
305926
+ throwIfLatestVersionNotDeployed(
305927
+ e11,
305928
+ "wrangler versions secret put",
305929
+ "secret put version not deployed"
305930
+ );
305931
+ throw e11;
305407
305932
  }
305408
305933
  }
305409
305934
  __name(submitSecret, "submitSecret");
@@ -344962,7 +345487,23 @@ function parseSourceArgument(source, args) {
344962
345487
  case "artifacts" /* ARTIFACTS */:
344963
345488
  return { type: "artifacts" /* ARTIFACTS */ };
344964
345489
  case "artifacts.repo" /* ARTIFACTS_REPO */:
344965
- return { type: "artifacts.repo" /* ARTIFACTS_REPO */ };
345490
+ if (!args.sourceNamespace) {
345491
+ throw new UserError(
345492
+ `--source-namespace is required when using source '${"artifacts.repo" /* ARTIFACTS_REPO */}'`,
345493
+ { telemetryMessage: "queues subscription create missing namespace" }
345494
+ );
345495
+ }
345496
+ if (!args.sourceRepoName) {
345497
+ throw new UserError(
345498
+ `--source-repo-name is required when using source '${"artifacts.repo" /* ARTIFACTS_REPO */}'`,
345499
+ { telemetryMessage: "queues subscription create missing repo name" }
345500
+ );
345501
+ }
345502
+ return {
345503
+ type: "artifacts.repo" /* ARTIFACTS_REPO */,
345504
+ namespace: args.sourceNamespace,
345505
+ repo_name: args.sourceRepoName
345506
+ };
344966
345507
  case "browserRun" /* BROWSER_RUN */:
344967
345508
  return { type: "browserRun" /* BROWSER_RUN */ };
344968
345509
  case "email.sending" /* EMAIL_SENDING */:
@@ -345066,7 +345607,7 @@ var init_create18 = __esm({
345066
345607
  choices: EVENT_SOURCE_TYPES
345067
345608
  },
345068
345609
  events: {
345069
- describe: "Comma-separated list of event types to subscribe to",
345610
+ describe: "Comma-separated list of event types to subscribe to (for artifacts.repo, use pushed, not cf.artifacts.repo.pushed)",
345070
345611
  type: "string",
345071
345612
  demandOption: true
345072
345613
  },
@@ -345098,6 +345639,14 @@ var init_create18 = __esm({
345098
345639
  domain: {
345099
345640
  describe: "Sending domain \u2014 zone apex or verified subdomain (required for email.sending source)",
345100
345641
  type: "string"
345642
+ },
345643
+ "source-namespace": {
345644
+ describe: "Artifacts namespace (required for artifacts.repo source)",
345645
+ type: "string"
345646
+ },
345647
+ "source-repo-name": {
345648
+ describe: "Artifacts repository name (required for artifacts.repo source)",
345649
+ type: "string"
345101
345650
  }
345102
345651
  },
345103
345652
  async handler(args, { config: config2 }) {
@@ -345106,7 +345655,9 @@ var init_create18 = __esm({
345106
345655
  workerName: args.workerName,
345107
345656
  workflowName: args.workflowName,
345108
345657
  zoneId: args.zoneId,
345109
- domain: args.domain
345658
+ domain: args.domain,
345659
+ sourceNamespace: args.sourceNamespace,
345660
+ sourceRepoName: args.sourceRepoName
345110
345661
  });
345111
345662
  const events7 = args.events.split(",").map((event) => event.trim()).filter(Boolean);
345112
345663
  if (events7.length === 0) {
@@ -345204,6 +345755,8 @@ function getSourceType(source) {
345204
345755
  }
345205
345756
  function getSourceResource(source) {
345206
345757
  switch (source.type) {
345758
+ case "artifacts.repo" /* ARTIFACTS_REPO */:
345759
+ return `${source.namespace}/${source.repo_name}`;
345207
345760
  case "email.sending" /* EMAIL_SENDING */:
345208
345761
  return source.domain;
345209
345762
  case "workersAi.model" /* WORKERS_AI_MODEL */:
@@ -348038,7 +348591,7 @@ async function usingLocalBucket(persistTo, config2, bucketName, closure) {
348038
348591
  try {
348039
348592
  if (request.method !== "PUT") return new Response(null, { status: 405 });
348040
348593
  const url = new URL(request.url);
348041
- const key = url.pathname.substring(1);
348594
+ const key = decodeURIComponent(url.pathname.substring(1));
348042
348595
  const optsHeader = request.headers.get("Wrangler-R2-Put-Options");
348043
348596
  const opts = JSON.parse(optsHeader);
348044
348597
  await env.BUCKET.put(key, request.body, opts);
@@ -348437,15 +348990,18 @@ var init_object3 = __esm({
348437
348990
  cacheExpiry: yArgs.expires === void 0 ? void 0 : parseInt(yArgs.expires)
348438
348991
  }
348439
348992
  };
348440
- await mf.dispatchFetch(`http://localhost/${key}`, {
348441
- method: "PUT",
348442
- body: objectStream,
348443
- duplex: "half",
348444
- headers: {
348445
- "Content-Length": String(sizeBytes),
348446
- "Wrangler-R2-Put-Options": JSON.stringify(putOptions)
348993
+ await mf.dispatchFetch(
348994
+ `http://localhost/${encodeURIComponent(key)}`,
348995
+ {
348996
+ method: "PUT",
348997
+ body: objectStream,
348998
+ duplex: "half",
348999
+ headers: {
349000
+ "Content-Length": String(sizeBytes),
349001
+ "Wrangler-R2-Put-Options": JSON.stringify(putOptions)
349002
+ }
348447
349003
  }
348448
- });
349004
+ );
348449
349005
  }
348450
349006
  );
348451
349007
  } else {
@@ -348690,15 +349246,18 @@ var init_object3 = __esm({
348690
349246
  if ((index + 1) % 100 === 0 || index + 1 === entries2.length) {
348691
349247
  logBulkProgress2("Uploaded", index + 1, entries2.length);
348692
349248
  }
348693
- await mf.dispatchFetch(`http://localhost/${entry.key}`, {
348694
- method: "PUT",
348695
- body: Stream__namespace.Readable.toWeb(fs14__namespace.createReadStream(entry.file)),
348696
- duplex: "half",
348697
- headers: {
348698
- "Content-Length": String(entry.size),
348699
- "Wrangler-R2-Put-Options": jsonPutOptions
349249
+ await mf.dispatchFetch(
349250
+ `http://localhost/${encodeURIComponent(entry.key)}`,
349251
+ {
349252
+ method: "PUT",
349253
+ body: Stream__namespace.Readable.toWeb(fs14__namespace.createReadStream(entry.file)),
349254
+ duplex: "half",
349255
+ headers: {
349256
+ "Content-Length": String(entry.size),
349257
+ "Wrangler-R2-Put-Options": jsonPutOptions
349258
+ }
348700
349259
  }
348701
- });
349260
+ );
348702
349261
  })
348703
349262
  );
348704
349263
  try {
@@ -354987,7 +355546,7 @@ var init_bulk5 = __esm({
354987
355546
  init_secrets6();
354988
355547
  versionsSecretBulkCommand = createCommand({
354989
355548
  metadata: {
354990
- description: "Create or update a secret variable for a Worker",
355549
+ description: "Create, update, or delete multiple secret variables for a Worker",
354991
355550
  owner: "Workers: Authoring and Testing",
354992
355551
  status: "stable"
354993
355552
  },
@@ -354999,7 +355558,7 @@ var init_bulk5 = __esm({
354999
355558
  },
355000
355559
  args: {
355001
355560
  file: {
355002
- describe: `The file of key-value pairs to upload, as JSON in form {"key": value, ...} or .dev.vars file in the form KEY=VALUE`,
355561
+ describe: `The file of key-value pairs to create, update, or delete, as JSON in form {"key": "value", ...} or .env file in the form KEY=VALUE. Set a key to null in the JSON file to delete it. Deletion is not supported with .env files. If omitted, Wrangler expects to receive input from stdin rather than a file.`,
355003
355562
  type: "string"
355004
355563
  },
355005
355564
  name: {
@@ -355029,9 +355588,9 @@ var init_bulk5 = __esm({
355029
355588
  }
355030
355589
  const accountId = await requireAuth(config2);
355031
355590
  logger2.log(
355032
- `\u{1F300} Creating the secrets for the Worker "${scriptName}" ${args.env ? `(${args.env})` : ""}`
355591
+ `\u{1F300} Processing the secrets for the Worker "${scriptName}" ${args.env ? `(${args.env})` : ""}`
355033
355592
  );
355034
- const result = await parseBulkInputToObject(args.file);
355593
+ const result = await parseBulkInputToObject(args.file, true);
355035
355594
  if (!result) {
355036
355595
  return logger2.error(`No content found in file or piped input.`);
355037
355596
  }
@@ -355047,8 +355606,16 @@ var init_bulk5 = __esm({
355047
355606
  sendMetrics: config2.send_metrics,
355048
355607
  noVersionsTelemetryMessage: "versions secrets bulk no uploaded versions"
355049
355608
  });
355050
- for (const [name2] of secretEntries) {
355051
- logger2.log(`\u2728 Successfully created secret for key: ${name2}`);
355609
+ let created = 0;
355610
+ let deleted = 0;
355611
+ for (const [name2, value] of secretEntries) {
355612
+ if (value === null) {
355613
+ deleted++;
355614
+ logger2.log(`\u{1F4A5} Successfully deleted secret for key: ${name2}`);
355615
+ } else {
355616
+ created++;
355617
+ logger2.log(`\u2728 Successfully created secret for key: ${name2}`);
355618
+ }
355052
355619
  }
355053
355620
  sendMetricsEvent(
355054
355621
  "create encrypted variable",
@@ -355063,7 +355630,7 @@ var init_bulk5 = __esm({
355063
355630
  }
355064
355631
  );
355065
355632
  logger2.log(
355066
- `\u2728 Success! Created version ${newVersion.id} with ${secretEntries.length} secrets.
355633
+ `\u2728 Success! Created version ${newVersion.id} with ${created} secret${created === 1 ? "" : "s"} created and ${deleted} secret${deleted === 1 ? "" : "s"} deleted.
355067
355634
  \u27A1\uFE0F To deploy this version to production traffic use the command "wrangler versions deploy".`
355068
355635
  );
355069
355636
  }, "versionsSecretPutBulkHandler")
@@ -356331,6 +356898,18 @@ var init_local = __esm({
356331
356898
  });
356332
356899
 
356333
356900
  // src/workflows/utils.ts
356901
+ function getJsonAwareRetryLogger(json2) {
356902
+ if (!json2) {
356903
+ return logger2;
356904
+ }
356905
+ return {
356906
+ debug: logger2.debug,
356907
+ log: logger2.warn,
356908
+ info: logger2.warn,
356909
+ warn: logger2.warn,
356910
+ error: /* @__PURE__ */ __name((...args) => logger2.error(...args), "error")
356911
+ };
356912
+ }
356334
356913
  function withUtcDesignator(value) {
356335
356914
  const timeIndex = value.indexOf("T");
356336
356915
  if (timeIndex === -1 || UTC_DESIGNATOR_REG_EXP.test(value.slice(timeIndex + 1))) {
@@ -356368,9 +356947,12 @@ function validateInstanceDate(value, flag, bound) {
356368
356947
  async function getInstanceIdFromArgs(accountId, args, config2) {
356369
356948
  let id = args.id;
356370
356949
  if (id == "latest") {
356371
- const instances = (await fetchResult2(
356372
- config2,
356373
- `/accounts/${accountId}/workflows/${args.name}/instances/`
356950
+ const instances = (await retryOnAPIFailure(
356951
+ () => fetchResult2(
356952
+ config2,
356953
+ `/accounts/${accountId}/workflows/${args.name}/instances/`
356954
+ ),
356955
+ getJsonAwareRetryLogger(args.json)
356374
356956
  )).sort((a8, b11) => b11.created_on.localeCompare(a8.created_on));
356375
356957
  if (instances.length == 0) {
356376
356958
  throw new UserError(
@@ -356406,6 +356988,8 @@ var init_utils21 = __esm({
356406
356988
  init_import_meta_url();
356407
356989
  init_src();
356408
356990
  init_cfetch2();
356991
+ init_logger2();
356992
+ __name(getJsonAwareRetryLogger, "getJsonAwareRetryLogger");
356409
356993
  jsonWorkflowArgs = {
356410
356994
  json: {
356411
356995
  describe: "Output the raw API response as JSON",
@@ -356768,7 +357352,7 @@ var init_delete27 = __esm({
356768
357352
  if (ids.includes("latest")) {
356769
357353
  const latestId = await getInstanceIdFromArgs(
356770
357354
  accountId,
356771
- { id: "latest", name: args.name },
357355
+ { id: "latest", name: args.name, json: args.json },
356772
357356
  config2
356773
357357
  );
356774
357358
  ids = ids.map((id) => id === "latest" ? latestId : id);
@@ -359742,6 +360326,7 @@ var init_describe2 = __esm({
359742
360326
  init_import_meta_url();
359743
360327
  init_dist5();
359744
360328
  init_colors();
360329
+ init_src();
359745
360330
  init_date_fns();
359746
360331
  init_itty_time2();
359747
360332
  init_cfetch2();
@@ -359800,9 +360385,12 @@ var init_describe2 = __esm({
359800
360385
  } else {
359801
360386
  const accountId = await requireAuth(config2);
359802
360387
  id = await getInstanceIdFromArgs(accountId, args, config2);
359803
- instance = await fetchResult2(
359804
- config2,
359805
- `/accounts/${accountId}/workflows/${args.name}/instances/${id}`
360388
+ instance = await retryOnAPIFailure(
360389
+ () => fetchResult2(
360390
+ config2,
360391
+ `/accounts/${accountId}/workflows/${args.name}/instances/${id}`
360392
+ ),
360393
+ getJsonAwareRetryLogger(args.json)
359806
360394
  );
359807
360395
  }
359808
360396
  if (args.json) {
@@ -359961,11 +360549,15 @@ var init_list35 = __esm({
359961
360549
  URLParams.set("per_page", args.perPage.toString());
359962
360550
  }
359963
360551
  URLParams.set("page", args.page.toString());
359964
- const instances = await fetchCursorPage(
359965
- config2,
359966
- `/accounts/${accountId}/workflows/${args.name}/instances`,
359967
- void 0,
359968
- URLParams
360552
+ const instances = await retryOnAPIFailure(
360553
+ () => fetchCursorPage(
360554
+ config2,
360555
+ `/accounts/${accountId}/workflows/${args.name}/instances`,
360556
+ void 0,
360557
+ // fetchCursorPage deletes `page` from the params it is given, so each attempt needs its own copy
360558
+ new URLSearchParams(URLParams)
360559
+ ),
360560
+ getJsonAwareRetryLogger(args.json)
359969
360561
  );
359970
360562
  const sortedInstances = instances.sort(
359971
360563
  (a8, b11) => args.reverse ? a8.created_on.localeCompare(b11.created_on) : b11.created_on.localeCompare(a8.created_on)
@@ -366857,7 +367449,7 @@ var init_dev3 = __esm({
366857
367449
  const tunnelConfig = this.getCurrentTunnelConfig();
366858
367450
  const isQuickTunnel = tunnelConfig?.name === void 0;
366859
367451
  logger2.warn(
366860
- (isQuickTunnel ? source_default.dim("Once connected, this tunnel will be ") + "publicly accessible" : source_default.dim(
367452
+ (isQuickTunnel ? source_default.dim("Once connected, this tunnel may be ") + "publicly accessible" : source_default.dim(
366861
367453
  "Once connected, this tunnel may be reachable from the Internet"
366862
367454
  )) + source_default.dim(". Anyone who can reach it can:\n") + source_default.dim(
366863
367455
  "- Call ungated endpoints\n- Trigger logic that uses remote bindings\n- Reach internal services if your Worker proxies requests\n\n" + (isQuickTunnel ? "Consider using a named tunnel with Cloudflare Access to restrict access.\n" : "Consider using Cloudflare Access to restrict access.\n")
@@ -366870,6 +367462,7 @@ var init_dev3 = __esm({
366870
367462
  const nextTunnel = startTunnel({
366871
367463
  origin,
366872
367464
  token: namedTunnel?.token,
367465
+ allowedMail: tunnelConfig?.allowedMail,
366873
367466
  extendHint: "Press [a] to extend by 1 hour.",
366874
367467
  logger: logger2
366875
367468
  });
@@ -368150,7 +368743,7 @@ var init_compatibility_flags = __esm({
368150
368743
  });
368151
368744
 
368152
368745
  // ../workers-shared/asset-worker/src/utils/base-path.ts
368153
- var init_base_path = __esm({
368746
+ var init_base_path2 = __esm({
368154
368747
  "../workers-shared/asset-worker/src/utils/base-path.ts"() {
368155
368748
  init_import_meta_url();
368156
368749
  }
@@ -368182,7 +368775,7 @@ var init_handler2 = __esm({
368182
368775
  init_responses2();
368183
368776
  init_tracing2();
368184
368777
  init_compatibility_flags();
368185
- init_base_path();
368778
+ init_base_path2();
368186
368779
  init_headers();
368187
368780
  init_rules_engine();
368188
368781
  }
@@ -369457,7 +370050,8 @@ async function setupDevEnv(devEnv, configPath, auth2, args) {
369457
370050
  experimentalNewConfig: args.experimentalNewConfig,
369458
370051
  tunnel: {
369459
370052
  enabled: args.tunnel ?? false,
369460
- name: args.tunnelName
370053
+ name: args.tunnelName,
370054
+ allowedMail: args.tunnelAllowedMail?.length ? args.tunnelAllowedMail : void 0
369461
370055
  }
369462
370056
  },
369463
370057
  legacy: {
@@ -369680,6 +370274,7 @@ unstable_dev()'s behaviour will likely change in future releases`
369680
370274
  types: false,
369681
370275
  tunnel: void 0,
369682
370276
  tunnelName: void 0,
370277
+ tunnelAllowedMail: void 0,
369683
370278
  experimentalNewConfig: false
369684
370279
  };
369685
370280
  const devServer = await run(