@cloudflare/workers-utils 0.22.1 → 0.23.1

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
@@ -1,8 +1,7 @@
1
- export { assertNever, constructWranglerConfig, getTodaysCompatDate, isCompatDate, mapWorkerMetadataBindings } from './chunk-UFU4JGIG.mjs';
1
+ export { assertNever, constructWranglerConfig, getTodaysCompatDate, isCompatDate, mapWorkerMetadataBindings } from './chunk-J6D57QVQ.mjs';
2
2
  export { MetricsRegistry } from './chunk-O4YGOZSW.mjs';
3
- import { isDirectory, UserError, isRedirectedRawConfig, dedent, configFileName, formatConfigSnippet, FatalError, removeDirSync, ParseError, parseJSON, APIError, readFileSync as readFileSync$1, parseTOML, modify, applyEdits, format, dist_default, parseJSONC } from './chunk-GMTGAG26.mjs';
4
- export { APIError, CommandLineArgsError, DeprecationError, FatalError, JsonFriendlyFatalError, MissingConfigError, ParseError, UserError, configFileName, configFormat, createFatalError, experimental_readRawConfig, findWranglerConfig, formatConfigSnippet, indexLocation, isDirectory, isRedirectedConfig, parseByteSize, parseHumanDuration, parseJSON, parseJSONC, parseNonHyphenedUuid, parsePackageJSON, parseTOML, readFileSync, readFileSyncToBuffer, removeDir, removeDirSync, resolveWranglerConfigPath, searchLocation } from './chunk-GMTGAG26.mjs';
5
- export { ENVIRONMENT_TAG_PREFIX, INHERIT_SYMBOL, JSON_CONFIG_FORMATS, PATH_TO_DEPLOY_CONFIG, SERVICE_TAG_PREFIX } from './chunk-OZQVB3L3.mjs';
3
+ import { isDirectory, UserError, isRedirectedRawConfig, dedent, configFileName, formatConfigSnippet, FatalError, removeDirSync, ParseError, parseJSON, APIError, readFileSync as readFileSync$1, parseTOML, modify, applyEdits, format, dist_default, parseJSONC } from './chunk-ULVYGN52.mjs';
4
+ export { APIError, CommandLineArgsError, DeprecationError, ENVIRONMENT_TAG_PREFIX, FatalError, INHERIT_SYMBOL, JSON_CONFIG_FORMATS, JsonFriendlyFatalError, MissingConfigError, PATH_TO_DEPLOY_CONFIG, ParseError, SERVICE_TAG_PREFIX, UserError, configFileName, configFormat, createFatalError, experimental_readRawConfig, findWranglerConfig, formatConfigSnippet, indexLocation, isDirectory, isRedirectedConfig, parseByteSize, parseHumanDuration, parseJSON, parseJSONC, parseNonHyphenedUuid, parsePackageJSON, parseTOML, readFileSync, readFileSyncToBuffer, removeDir, removeDirSync, resolveWranglerConfigPath, searchLocation } from './chunk-ULVYGN52.mjs';
6
5
  import { __commonJS, __name, __require, __export, __toESM, __reExport } from './chunk-DCOBXSFB.mjs';
7
6
  import fs2, { accessSync, constants, writeFileSync, renameSync, existsSync, unlinkSync, mkdirSync, chmodSync, readFileSync } from 'node:fs';
8
7
  import assert from 'node:assert';
@@ -13,6 +12,7 @@ import { createHash } from 'node:crypto';
13
12
  import { fetch, Headers, FormData, Response } from 'undici';
14
13
  import { URLSearchParams } from 'node:url';
15
14
  import * as timersPromises from 'node:timers/promises';
15
+ import { setTimeout as setTimeout$1 } from 'node:timers/promises';
16
16
 
17
17
  // ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js
18
18
  var require_XDGAppPaths = __commonJS({
@@ -1911,7 +1911,7 @@ var defaultWranglerConfig = {
1911
1911
  vectorize: [],
1912
1912
  ai_search_namespaces: [],
1913
1913
  ai_search: [],
1914
- web_search: void 0,
1914
+ websearch: void 0,
1915
1915
  agent_memory: [],
1916
1916
  hyperdrive: [],
1917
1917
  workflows: [],
@@ -5930,14 +5930,24 @@ __reExport(mod_esm_exports, __toESM(require_mod_cjs3(), 1));
5930
5930
  var mod_esm_default = import_mod_cjs.default;
5931
5931
 
5932
5932
  // src/global-wrangler-config-path.ts
5933
+ function getGlobalConfigPath({
5934
+ appName = "wrangler",
5935
+ leadingDot = true,
5936
+ useLegacyHomeDir = true
5937
+ } = {}) {
5938
+ const dirName = `${leadingDot ? "." : ""}${appName}`;
5939
+ const configDir = mod_esm_default(dirName).config();
5940
+ if (useLegacyHomeDir) {
5941
+ const legacyConfigDir = path3.join(os.homedir(), dirName);
5942
+ if (isDirectory(legacyConfigDir)) {
5943
+ return legacyConfigDir;
5944
+ }
5945
+ }
5946
+ return configDir;
5947
+ }
5948
+ __name(getGlobalConfigPath, "getGlobalConfigPath");
5933
5949
  function getGlobalWranglerConfigPath() {
5934
- const configDir = mod_esm_default(".wrangler").config();
5935
- const legacyConfigDir = path3.join(os.homedir(), ".wrangler");
5936
- if (isDirectory(legacyConfigDir)) {
5937
- return legacyConfigDir;
5938
- } else {
5939
- return configDir;
5940
- }
5950
+ return getGlobalConfigPath();
5941
5951
  }
5942
5952
  __name(getGlobalWranglerConfigPath, "getGlobalWranglerConfigPath");
5943
5953
 
@@ -6588,7 +6598,7 @@ var friendlyBindingNames = {
6588
6598
  vectorize: "Vectorize Index",
6589
6599
  ai_search_namespaces: "AI Search Namespace",
6590
6600
  ai_search: "AI Search Instance",
6591
- web_search: "Web Search",
6601
+ websearch: "Web Search",
6592
6602
  agent_memory: "Agent Memory",
6593
6603
  hyperdrive: "Hyperdrive Config",
6594
6604
  r2_buckets: "R2 Bucket",
@@ -6642,7 +6652,7 @@ var bindingTypeFriendlyNames = {
6642
6652
  vectorize: "Vectorize Index",
6643
6653
  ai_search_namespace: "AI Search Namespace",
6644
6654
  ai_search: "AI Search Instance",
6645
- web_search: "Web Search",
6655
+ websearch: "Web Search",
6646
6656
  agent_memory: "Agent Memory",
6647
6657
  hyperdrive: "Hyperdrive Config",
6648
6658
  service: "Worker",
@@ -7314,8 +7324,8 @@ function normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv) {
7314
7324
  );
7315
7325
  }
7316
7326
  __name(normalizeAndValidateRoute, "normalizeAndValidateRoute");
7317
- function validateRoutes(diagnostics, topLevelEnv, rawEnv) {
7318
- return inheritable(
7327
+ function validateRoutes(diagnostics, topLevelEnv, rawEnv, envName) {
7328
+ const result = inheritable(
7319
7329
  diagnostics,
7320
7330
  topLevelEnv,
7321
7331
  rawEnv,
@@ -7323,6 +7333,18 @@ function validateRoutes(diagnostics, topLevelEnv, rawEnv) {
7323
7333
  all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
7324
7334
  void 0
7325
7335
  );
7336
+ if (topLevelEnv !== void 0 && envName !== void 0 && rawEnv.routes === void 0) {
7337
+ const customDomainRoutes = topLevelEnv.routes?.filter(
7338
+ (r2) => typeof r2 === "object" && r2 !== null && r2.custom_domain === true
7339
+ );
7340
+ if (customDomainRoutes && customDomainRoutes.length > 0) {
7341
+ const customDomains = customDomainRoutes.map((r2) => r2.pattern).join(", ");
7342
+ diagnostics.warnings.push(
7343
+ `The "env.${envName}" environment inherits the top-level \`routes\` configuration, which includes the custom domain(s): ${customDomains}. Deploying this environment will reassign these custom domains away from the top-level Worker. Add \`"routes": []\` to "env.${envName}" to prevent inheritance, or copy the route configuration from the top level to hide this warning.`
7344
+ );
7345
+ }
7346
+ }
7347
+ return result;
7326
7348
  }
7327
7349
  __name(validateRoutes, "validateRoutes");
7328
7350
  function normalizeAndValidatePlacement(diagnostics, topLevelEnv, rawEnv) {
@@ -7538,7 +7560,12 @@ function normalizeAndValidateEnvironment(diagnostics, configPath, rawEnv, isDisp
7538
7560
  void 0,
7539
7561
  void 0
7540
7562
  );
7541
- const routes = validateRoutes(diagnostics, topLevelEnv, rawEnv);
7563
+ const routes = validateRoutes(
7564
+ diagnostics,
7565
+ topLevelEnv,
7566
+ rawEnv,
7567
+ topLevelEnv === void 0 ? void 0 : envName
7568
+ );
7542
7569
  const workers_dev = inheritable(
7543
7570
  diagnostics,
7544
7571
  topLevelEnv,
@@ -7838,13 +7865,13 @@ function normalizeAndValidateEnvironment(diagnostics, configPath, rawEnv, isDisp
7838
7865
  validateBindingArray(envName, validateAISearchBinding),
7839
7866
  []
7840
7867
  ),
7841
- web_search: notInheritable(
7868
+ websearch: notInheritable(
7842
7869
  diagnostics,
7843
7870
  topLevelEnv,
7844
7871
  rawConfig,
7845
7872
  rawEnv,
7846
7873
  envName,
7847
- "web_search",
7874
+ "websearch",
7848
7875
  validateNamedSimpleBinding(envName),
7849
7876
  void 0
7850
7877
  ),
@@ -8941,7 +8968,7 @@ var validateUnsafeBinding = /* @__PURE__ */ __name((diagnostics, field, value) =
8941
8968
  "ai",
8942
8969
  "ai_search_namespace",
8943
8970
  "ai_search",
8944
- "web_search",
8971
+ "websearch",
8945
8972
  "agent_memory",
8946
8973
  "kv_namespace",
8947
8974
  "durable_object_namespace",
@@ -9752,12 +9779,21 @@ var validateD1Binding = /* @__PURE__ */ __name((diagnostics, field, value) => {
9752
9779
  if (!isRemoteValid(value, field, diagnostics)) {
9753
9780
  isValid2 = false;
9754
9781
  }
9782
+ if (!isOptionalProperty(value, "migrations_pattern", "string")) {
9783
+ diagnostics.errors.push(
9784
+ `"${field}" bindings should, optionally, have a string "migrations_pattern" field but got ${JSON.stringify(
9785
+ value
9786
+ )}.`
9787
+ );
9788
+ isValid2 = false;
9789
+ }
9755
9790
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
9756
9791
  "binding",
9757
9792
  "database_id",
9758
9793
  "database_internal_env",
9759
9794
  "database_name",
9760
9795
  "migrations_dir",
9796
+ "migrations_pattern",
9761
9797
  "migrations_table",
9762
9798
  "preview_database_id",
9763
9799
  "remote"
@@ -11350,7 +11386,7 @@ var BINDING_LOCAL_SUPPORT = {
11350
11386
  flagship: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
11351
11387
  vpc_service: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
11352
11388
  vpc_network: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
11353
- web_search: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
11389
+ websearch: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
11354
11390
  agent_memory: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator"
11355
11391
  };
11356
11392
  function getBindingLocalSupport(type) {
@@ -12331,7 +12367,7 @@ __name(maybeThrowFriendlyError, "maybeThrowFriendlyError");
12331
12367
  function logHeaders(headers, logger) {
12332
12368
  const clone = cloneHeaders(headers);
12333
12369
  clone.delete("Authorization");
12334
- logger.debugWithSanitization(
12370
+ logger.debugWithSanitization?.(
12335
12371
  "HEADERS:",
12336
12372
  JSON.stringify(Object.fromEntries(clone), null, 2)
12337
12373
  );
@@ -12352,11 +12388,11 @@ async function performApiFetchBase(complianceConfig, resource, init = {}, userAg
12352
12388
  logger.debug(
12353
12389
  `-- START CF API REQUEST: ${method} ${getCloudflareApiBaseUrl(complianceConfig)}${resource}`
12354
12390
  );
12355
- logger.debugWithSanitization("QUERY STRING:", queryString);
12391
+ logger.debugWithSanitization?.("QUERY STRING:", queryString);
12356
12392
  logHeaders(headers, logger);
12357
- logger.debugWithSanitization("INIT:", JSON.stringify({ ...init }, null, 2));
12393
+ logger.debugWithSanitization?.("INIT:", JSON.stringify({ ...init }, null, 2));
12358
12394
  if (init.body instanceof FormData) {
12359
- logger.debugWithSanitization(
12395
+ logger.debugWithSanitization?.(
12360
12396
  "BODY:",
12361
12397
  await new Response(init.body).text(),
12362
12398
  null,
@@ -12394,7 +12430,7 @@ async function fetchInternalBase(complianceConfig, resource, init = {}, userAgen
12394
12430
  response.status
12395
12431
  );
12396
12432
  logHeaders(response.headers, logger);
12397
- logger.debugWithSanitization("RESPONSE:", jsonText);
12433
+ logger.debugWithSanitization?.("RESPONSE:", jsonText);
12398
12434
  logger.debug("-- END CF API RESPONSE");
12399
12435
  if (!jsonText && (response.status === 204 || response.status === 205)) {
12400
12436
  return {
@@ -12633,6 +12669,27 @@ function throwWAFBlockError(headers, method, resource, status, statusText) {
12633
12669
  });
12634
12670
  }
12635
12671
  __name(throwWAFBlockError, "throwWAFBlockError");
12672
+ async function fetchKVGetValueBase(complianceConfig, accountId, namespaceId, key, userAgent, logger, credentials) {
12673
+ const headers = new Headers();
12674
+ addAuthorizationHeader(headers, credentials);
12675
+ headers.set("User-Agent", userAgent);
12676
+ maybeAddTraceHeader(headers);
12677
+ const resource = `${getCloudflareApiBaseUrl(complianceConfig)}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
12678
+ logger.debug(`-- START CF API REQUEST: GET ${resource}`);
12679
+ logger.debug("-- END CF API REQUEST");
12680
+ const response = await fetch(resource, {
12681
+ method: "GET",
12682
+ headers
12683
+ });
12684
+ if (response.ok) {
12685
+ return await response.arrayBuffer();
12686
+ } else {
12687
+ throw new Error(
12688
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText}`
12689
+ );
12690
+ }
12691
+ }
12692
+ __name(fetchKVGetValueBase, "fetchKVGetValueBase");
12636
12693
  function hasCursor(result_info) {
12637
12694
  const cursor = result_info?.cursor;
12638
12695
  return cursor !== void 0 && cursor !== null && cursor !== "";
@@ -12680,6 +12737,87 @@ async function fetchLatestNpmVersion(name, version) {
12680
12737
  return { status: "update-available", latest: result.latest };
12681
12738
  }
12682
12739
  __name(fetchLatestNpmVersion, "fetchLatestNpmVersion");
12740
+
12741
+ // src/logger.ts
12742
+ var LOGGER_LEVELS = {
12743
+ none: -1,
12744
+ error: 0,
12745
+ warn: 1,
12746
+ info: 2,
12747
+ log: 3,
12748
+ debug: 4
12749
+ };
12750
+ var MAX_ATTEMPTS = 3;
12751
+ async function retryOnAPIFailure(action, logger, backoff = 0, attempts = MAX_ATTEMPTS, abortSignal) {
12752
+ try {
12753
+ return await action();
12754
+ } catch (err) {
12755
+ if (err instanceof APIError) {
12756
+ if (!err.isRetryable()) {
12757
+ throw err;
12758
+ }
12759
+ } else if (err instanceof DOMException && err.name === "TimeoutError") ; else if (!(err instanceof TypeError)) {
12760
+ throw err;
12761
+ }
12762
+ logger.debug(`Retrying API call after error...`);
12763
+ logger.debug(err);
12764
+ if (attempts <= 1) {
12765
+ throw err;
12766
+ }
12767
+ await setTimeout$1(backoff, void 0, { signal: abortSignal });
12768
+ return retryOnAPIFailure(
12769
+ action,
12770
+ logger,
12771
+ backoff + 1e3,
12772
+ attempts - 1,
12773
+ abortSignal
12774
+ );
12775
+ }
12776
+ }
12777
+ __name(retryOnAPIFailure, "retryOnAPIFailure");
12778
+
12779
+ // src/format-time.ts
12780
+ function formatTime(duration) {
12781
+ return `(${(duration / 1e3).toFixed(2)} sec)`;
12782
+ }
12783
+ __name(formatTime, "formatTime");
12784
+
12785
+ // src/route-utils.ts
12786
+ function getHostFromRoute(route) {
12787
+ let host;
12788
+ if (typeof route === "string") {
12789
+ host = getHostFromUrl(route);
12790
+ } else if (typeof route === "object") {
12791
+ host = getHostFromUrl(route.pattern);
12792
+ if (host === void 0 && "zone_name" in route) {
12793
+ host = getHostFromUrl(route.zone_name);
12794
+ }
12795
+ }
12796
+ return host;
12797
+ }
12798
+ __name(getHostFromRoute, "getHostFromRoute");
12799
+ function getZoneFromRoute(route) {
12800
+ if (typeof route === "object" && "zone_name" in route && route.zone_name) {
12801
+ return route.zone_name;
12802
+ }
12803
+ return getHostFromRoute(route);
12804
+ }
12805
+ __name(getZoneFromRoute, "getZoneFromRoute");
12806
+ function getHostFromUrl(urlLike) {
12807
+ if (urlLike.startsWith("*/") || urlLike.startsWith("http://*/") || urlLike.startsWith("https://*/")) {
12808
+ return void 0;
12809
+ }
12810
+ urlLike = urlLike.replace(/\*(\.)?/g, "");
12811
+ if (!(urlLike.startsWith("http://") || urlLike.startsWith("https://"))) {
12812
+ urlLike = "http://" + urlLike;
12813
+ }
12814
+ try {
12815
+ return new URL(urlLike).host;
12816
+ } catch {
12817
+ return void 0;
12818
+ }
12819
+ }
12820
+ __name(getHostFromUrl, "getHostFromUrl");
12683
12821
  /*! Bundled license information:
12684
12822
 
12685
12823
  deep-extend/lib/deep-extend.js:
@@ -12714,4 +12852,4 @@ safe-buffer/index.js:
12714
12852
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
12715
12853
  */
12716
12854
 
12717
- export { COMPLIANCE_REGION_CONFIG_PUBLIC, COMPLIANCE_REGION_CONFIG_UNKNOWN, Diagnostics, PatchConfigError, addAuthorizationHeader, bucketFormatMessage, defaultWranglerConfig, experimental_patchConfig, extractAccountTag, extractWAFBlockRayId, fetchInternalBase, fetchLatestNpmVersion, fetchListResultBase, fetchResultBase, friendlyBindingNames, getBindingLocalSupport, getBindingTypeFriendlyName, getBooleanEnvironmentVariableFactory, getBrowserRenderingHeadfulFromEnv, getBuildConditionsFromEnv, getBuildPlatformFromEnv, getC3CommandFromEnv, getCIGeneratePreviewAlias, getCIMatchTag, getCIOverrideName, getCIOverrideNetworkModeHost, getCfFetchEnabledFromEnv, getCfFetchPathFromEnv, getCloudflareApiBaseUrl, getCloudflareApiEnvironmentFromEnv, getCloudflareComplianceRegion, getCloudflareEnv, getCloudflareIncludeProcessEnvFromEnv, getCloudflareLoadDevVarsFromDotEnv, getCloudflaredPathFromEnv, getComplianceRegionSubdomain, getD1ExtraLocationChoices, getDisableConfigWatching, getDockerPath, getEnvironmentVariableFactory, getGlobalWranglerConfigPath, getLocalExplorerEnabledFromEnv, getOpenNextDeployFromEnv, getOutputFileDirectoryFromEnv, getOutputFilePathFromEnv, getRegistryPath, getSanitizeLogs, getSubdomainMixedStateCheckDisabled, getTraceHeader, getWorkersCIBranchName, getWranglerCacheDirFromEnv, getWranglerHiddenDirPath, getWranglerHideBanner, getWranglerSendErrorReportsFromEnv, getWranglerSendMetricsFromEnv, getWranglerTmpDir, hasCursor, hasMorePages, hasProperty, isDockerfile, isOptionalProperty, isPagesConfig, isRequiredProperty, isValidR2BucketName, isWAFBlockResponse, maybeAddTraceHeader, normalizeAndValidateConfig, performApiFetchBase, renderError, spawnCloudflared, startTunnel, sweepStaleWranglerTmpDirs, throwFetchError, truncate, validatePagesConfig };
12855
+ export { COMPLIANCE_REGION_CONFIG_PUBLIC, COMPLIANCE_REGION_CONFIG_UNKNOWN, Diagnostics, LOGGER_LEVELS, PatchConfigError, addAuthorizationHeader, bucketFormatMessage, defaultWranglerConfig, experimental_patchConfig, extractAccountTag, extractWAFBlockRayId, fetchInternalBase, fetchKVGetValueBase, fetchLatestNpmVersion, fetchListResultBase, fetchResultBase, formatTime, friendlyBindingNames, getBindingLocalSupport, getBindingTypeFriendlyName, getBooleanEnvironmentVariableFactory, getBrowserRenderingHeadfulFromEnv, getBuildConditionsFromEnv, getBuildPlatformFromEnv, getC3CommandFromEnv, getCIGeneratePreviewAlias, getCIMatchTag, getCIOverrideName, getCIOverrideNetworkModeHost, getCfFetchEnabledFromEnv, getCfFetchPathFromEnv, getCloudflareApiBaseUrl, getCloudflareApiEnvironmentFromEnv, getCloudflareComplianceRegion, getCloudflareEnv, getCloudflareIncludeProcessEnvFromEnv, getCloudflareLoadDevVarsFromDotEnv, getCloudflaredPathFromEnv, getComplianceRegionSubdomain, getD1ExtraLocationChoices, getDisableConfigWatching, getDockerPath, getEnvironmentVariableFactory, getGlobalConfigPath, getGlobalWranglerConfigPath, getHostFromRoute, getHostFromUrl, getLocalExplorerEnabledFromEnv, getOpenNextDeployFromEnv, getOutputFileDirectoryFromEnv, getOutputFilePathFromEnv, getRegistryPath, getSanitizeLogs, getSubdomainMixedStateCheckDisabled, getTraceHeader, getWorkersCIBranchName, getWranglerCacheDirFromEnv, getWranglerHiddenDirPath, getWranglerHideBanner, getWranglerSendErrorReportsFromEnv, getWranglerSendMetricsFromEnv, getWranglerTmpDir, getZoneFromRoute, hasCursor, hasMorePages, hasProperty, isDockerfile, isOptionalProperty, isPagesConfig, isRequiredProperty, isValidR2BucketName, isWAFBlockResponse, maybeAddTraceHeader, normalizeAndValidateConfig, performApiFetchBase, renderError, retryOnAPIFailure, spawnCloudflared, startTunnel, sweepStaleWranglerTmpDirs, throwFetchError, truncate, validatePagesConfig };