@cloudflare/deploy-helpers 0.2.5 → 0.3.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,8 @@
1
1
  import { __commonJS, __name, __require, __toESM, fetchResult, fetchListResult, logger, confirm, fetchPagedListResult, prompt, isNonInteractiveOrCI, select } from './chunk-N72KNDFF.mjs';
2
2
  export { initDeployHelpersContext } from './chunk-N72KNDFF.mjs';
3
- import * as path3 from 'node:path';
4
- import path3__default, { resolve, isAbsolute, dirname, join, extname, sep } from 'node:path';
5
- import fs2, { readFileSync, statSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
+ import * as path2 from 'node:path';
4
+ import path2__default, { resolve, isAbsolute, dirname, join, extname, sep } from 'node:path';
5
+ import fs2, { readFileSync, statSync, existsSync, mkdirSync, writeFileSync, createReadStream } from 'node:fs';
6
6
  import { AsyncLocalStorage } from 'node:async_hooks';
7
7
  import * as z from 'zod';
8
8
  import { z as z$1 } from 'zod';
@@ -10,7 +10,7 @@ import assert4 from 'node:assert';
10
10
  import url, { URLSearchParams as URLSearchParams$1 } from 'node:url';
11
11
  import * as cli from '@cloudflare/cli-shared-helpers';
12
12
  import { cancel } from '@cloudflare/cli-shared-helpers';
13
- import { INHERIT_SYMBOL, APIError, UserError as UserError$1, getEnvironmentVariableFactory, getHostFromRoute, retryOnAPIFailure, ParseError as ParseError$1, getComplianceRegionSubdomain, configFileName as configFileName$1, formatTime, getSubdomainMixedStateCheckDisabled, LOGGER_LEVELS, SERVICE_TAG_PREFIX, ENVIRONMENT_TAG_PREFIX, getWranglerTmpDir, FatalError as FatalError$1, readFileSync as readFileSync$2, parseJSON as parseJSON$1, getBindingTypeFriendlyName, getBindingLocalSupport, assertNever as assertNever$1, experimental_readRawConfig, experimental_patchConfig, PatchConfigError, COMPLIANCE_REGION_CONFIG_UNKNOWN, constructWranglerConfig, getCIMatchTag, formatConfigSnippet as formatConfigSnippet$1, getTodaysCompatDate, getDockerPath, parseNonHyphenedUuid as parseNonHyphenedUuid$1, getWorkersCIBranchName } from '@cloudflare/workers-utils';
13
+ import { INHERIT_SYMBOL, APIError, UserError as UserError$1, getEnvironmentVariableFactory, getHostFromRoute, retryOnAPIFailure, ParseError as ParseError$1, getComplianceRegionSubdomain, configFileName as configFileName$1, formatTime, getSubdomainMixedStateCheckDisabled, LOGGER_LEVELS, SERVICE_TAG_PREFIX, ENVIRONMENT_TAG_PREFIX, getDurableObjectExports, partitionExports as partitionExports$1, getWranglerTmpDir, FatalError as FatalError$1, readFileSync as readFileSync$2, parseJSON as parseJSON$1, getBindingTypeFriendlyName, getBindingLocalSupport, assertNever as assertNever$1, experimental_readRawConfig, experimental_patchConfig, PatchConfigError, COMPLIANCE_REGION_CONFIG_UNKNOWN, constructWranglerConfig, getCIMatchTag, formatConfigSnippet as formatConfigSnippet$1, getTodaysCompatDate, hasDurableObjectExports, getDockerPath, parseNonHyphenedUuid as parseNonHyphenedUuid$1, getWorkersCIBranchName } from '@cloudflare/workers-utils';
14
14
  import { spawnSync, execSync, spawn } from 'node:child_process';
15
15
  import { FormData, Response } from 'undici';
16
16
  import chalk5 from 'chalk';
@@ -20,7 +20,7 @@ import prettyBytes from 'pretty-bytes';
20
20
  import { hash } from 'blake3-wasm';
21
21
  import { Blob } from 'node:buffer';
22
22
  import { gzipSync } from 'node:zlib';
23
- import { brandColor, white, gray, dim, blue } from '@cloudflare/cli-shared-helpers/colors';
23
+ import { brandColor, white, gray, bold, yellow, dim, red, blue } from '@cloudflare/cli-shared-helpers/colors';
24
24
  import { inputPrompt, leftT } from '@cloudflare/cli-shared-helpers/interactive';
25
25
  import { sync } from 'command-exists';
26
26
  import readline from 'node:readline';
@@ -2753,6 +2753,45 @@ var __name2 = /* @__PURE__ */ __name((target, value) => __defProp(target, "name"
2753
2753
  value,
2754
2754
  configurable: true
2755
2755
  }), "__name");
2756
+ function isDirectory(path$1) {
2757
+ return fs2.statSync(path$1, { throwIfNoEntry: false })?.isDirectory() ?? false;
2758
+ }
2759
+ __name(isDirectory, "isDirectory");
2760
+ __name2(isDirectory, "isDirectory");
2761
+ function removeDir(dirPath, { fireAndForget = false } = {}) {
2762
+ const result = fs2.promises.rm(dirPath, {
2763
+ recursive: true,
2764
+ force: true,
2765
+ maxRetries: 5,
2766
+ retryDelay: 100
2767
+ });
2768
+ if (fireAndForget) result.catch(() => {
2769
+ });
2770
+ else return result;
2771
+ }
2772
+ __name(removeDir, "removeDir");
2773
+ __name2(removeDir, "removeDir");
2774
+ function removeDirSync(dirPath) {
2775
+ fs2.rmSync(dirPath, {
2776
+ recursive: true,
2777
+ force: true,
2778
+ maxRetries: 5,
2779
+ retryDelay: 100
2780
+ });
2781
+ }
2782
+ __name(removeDirSync, "removeDirSync");
2783
+ __name2(removeDirSync, "removeDirSync");
2784
+ function partitionExports(exports$2) {
2785
+ const partitioned = {
2786
+ "durable-object": {},
2787
+ worker: {}
2788
+ };
2789
+ if (exports$2 === void 0) return partitioned;
2790
+ for (const [name, entry] of Object.entries(exports$2)) partitioned[entry.type][name] = entry;
2791
+ return partitioned;
2792
+ }
2793
+ __name(partitionExports, "partitionExports");
2794
+ __name2(partitionExports, "partitionExports");
2756
2795
  var UserError = class extends Error {
2757
2796
  static {
2758
2797
  __name(this, "UserError");
@@ -3553,10 +3592,10 @@ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
3553
3592
  }
3554
3593
  __name(parseTree, "parseTree");
3555
3594
  __name2(parseTree, "parseTree");
3556
- function findNodeAtLocation(root, path22) {
3595
+ function findNodeAtLocation(root, path2$1) {
3557
3596
  if (!root) return;
3558
3597
  let node = root;
3559
- for (let segment of path22) if (typeof segment === "string") {
3598
+ for (let segment of path2$1) if (typeof segment === "string") {
3560
3599
  if (node.type !== "object" || !Array.isArray(node.children)) return;
3561
3600
  let found = false;
3562
3601
  for (const propertyNode of node.children) if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
@@ -3809,13 +3848,13 @@ function getNodeType(value) {
3809
3848
  __name(getNodeType, "getNodeType");
3810
3849
  __name2(getNodeType, "getNodeType");
3811
3850
  function setProperty(text, originalPath, value, options) {
3812
- const path22 = originalPath.slice();
3851
+ const path2$1 = originalPath.slice();
3813
3852
  const root = parseTree(text, []);
3814
3853
  let parent = void 0;
3815
3854
  let lastSegment = void 0;
3816
- while (path22.length > 0) {
3817
- lastSegment = path22.pop();
3818
- parent = findNodeAtLocation(root, path22);
3855
+ while (path2$1.length > 0) {
3856
+ lastSegment = path2$1.pop();
3857
+ parent = findNodeAtLocation(root, path2$1);
3819
3858
  if (parent === void 0 && value !== void 0) if (typeof lastSegment === "string") value = { [lastSegment]: value };
3820
3859
  else value = [value];
3821
3860
  else break;
@@ -4078,8 +4117,8 @@ function format2(documentText, range, options) {
4078
4117
  }
4079
4118
  __name(format2, "format2");
4080
4119
  __name2(format2, "format");
4081
- function modify(text, path22, value, options) {
4082
- return setProperty(text, path22, value, options);
4120
+ function modify(text, path2$1, value, options) {
4121
+ return setProperty(text, path2$1, value, options);
4083
4122
  }
4084
4123
  __name(modify, "modify");
4085
4124
  __name2(modify, "modify");
@@ -4881,6 +4920,12 @@ var ParseError = class extends UserError {
4881
4920
  #status;
4882
4921
  code;
4883
4922
  accountTag;
4923
+ /**
4924
+ * Optional structured metadata hoisted from the first `FetchError.meta`
4925
+ * on the v4 response envelope. Consumers can inspect this to render
4926
+ * endpoint-specific structured error payloads.
4927
+ */
4928
+ meta;
4884
4929
  constructor({ status, ...rest }) {
4885
4930
  super(rest);
4886
4931
  this.name = this.constructor.name;
@@ -5238,7 +5283,7 @@ function resolveWranglerConfigPath({ config, script }, options) {
5238
5283
  deployConfigPath: void 0,
5239
5284
  redirected: false
5240
5285
  };
5241
- return findWranglerConfig(script !== void 0 ? path3__default.dirname(script) : process.cwd(), options);
5286
+ return findWranglerConfig(script !== void 0 ? path2__default.dirname(script) : process.cwd(), options);
5242
5287
  }
5243
5288
  __name(resolveWranglerConfigPath, "resolveWranglerConfigPath");
5244
5289
  __name2(resolveWranglerConfigPath, "resolveWranglerConfigPath");
@@ -5271,15 +5316,15 @@ function findRedirectedWranglerConfig(cwd, userConfigPath) {
5271
5316
  const deployConfigFile = readFileSync$1(deployConfigPath);
5272
5317
  try {
5273
5318
  const deployConfig = parseJSONC(deployConfigFile, deployConfigPath);
5274
- redirectedConfigPath = deployConfig.configPath && path3__default.resolve(path3__default.dirname(deployConfigPath), deployConfig.configPath);
5319
+ redirectedConfigPath = deployConfig.configPath && path2__default.resolve(path2__default.dirname(deployConfigPath), deployConfig.configPath);
5275
5320
  } catch (e) {
5276
- throw new UserError(`Failed to parse the deploy configuration file at ${path3__default.relative(".", deployConfigPath)}`, {
5321
+ throw new UserError(`Failed to parse the deploy configuration file at ${path2__default.relative(".", deployConfigPath)}`, {
5277
5322
  cause: e,
5278
5323
  telemetryMessage: false
5279
5324
  });
5280
5325
  }
5281
5326
  if (!redirectedConfigPath) throw new UserError(esm_default`
5282
- A deploy configuration file was found at "${path3__default.relative(".", deployConfigPath)}".
5327
+ A deploy configuration file was found at "${path2__default.relative(".", deployConfigPath)}".
5283
5328
  But this is not valid - the required "configPath" property was not found.
5284
5329
  Instead this file contains:
5285
5330
  \`\`\`
@@ -5287,13 +5332,13 @@ function findRedirectedWranglerConfig(cwd, userConfigPath) {
5287
5332
  \`\`\`
5288
5333
  `, { telemetryMessage: false });
5289
5334
  if (!existsSync(redirectedConfigPath)) throw new UserError(esm_default`
5290
- There is a deploy configuration at "${path3__default.relative(".", deployConfigPath)}".
5291
- But the redirected configuration path it points to, "${path3__default.relative(".", redirectedConfigPath)}", does not exist.
5335
+ There is a deploy configuration at "${path2__default.relative(".", deployConfigPath)}".
5336
+ But the redirected configuration path it points to, "${path2__default.relative(".", redirectedConfigPath)}", does not exist.
5292
5337
  `, { telemetryMessage: false });
5293
5338
  if (userConfigPath) {
5294
- if (path3__default.join(path3__default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) throw new UserError(esm_default`
5295
- Found both a user configuration file at "${path3__default.relative(".", userConfigPath)}"
5296
- and a deploy configuration file at "${path3__default.relative(".", deployConfigPath)}".
5339
+ if (path2__default.join(path2__default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) throw new UserError(esm_default`
5340
+ Found both a user configuration file at "${path2__default.relative(".", userConfigPath)}"
5341
+ and a deploy configuration file at "${path2__default.relative(".", deployConfigPath)}".
5297
5342
  But these do not share the same base path so it is not clear which should be used.
5298
5343
  `, { telemetryMessage: false });
5299
5344
  }
@@ -5346,34 +5391,6 @@ function formatConfigSnippet(snippet, configPath, formatted = true) {
5346
5391
  }
5347
5392
  __name(formatConfigSnippet, "formatConfigSnippet");
5348
5393
  __name2(formatConfigSnippet, "formatConfigSnippet");
5349
- function isDirectory(path22) {
5350
- return fs2.statSync(path22, { throwIfNoEntry: false })?.isDirectory() ?? false;
5351
- }
5352
- __name(isDirectory, "isDirectory");
5353
- __name2(isDirectory, "isDirectory");
5354
- function removeDir(dirPath, { fireAndForget = false } = {}) {
5355
- const result = fs2.promises.rm(dirPath, {
5356
- recursive: true,
5357
- force: true,
5358
- maxRetries: 5,
5359
- retryDelay: 100
5360
- });
5361
- if (fireAndForget) result.catch(() => {
5362
- });
5363
- else return result;
5364
- }
5365
- __name(removeDir, "removeDir");
5366
- __name2(removeDir, "removeDir");
5367
- function removeDirSync(dirPath) {
5368
- fs2.rmSync(dirPath, {
5369
- recursive: true,
5370
- force: true,
5371
- maxRetries: 5,
5372
- retryDelay: 100
5373
- });
5374
- }
5375
- __name(removeDirSync, "removeDirSync");
5376
- __name2(removeDirSync, "removeDirSync");
5377
5394
  var AssetsSchema = z.strictObject({
5378
5395
  htmlHandling: z.enum([
5379
5396
  "auto-trailing-slash",
@@ -5582,7 +5599,10 @@ function isParsedUnsafeBinding(binding) {
5582
5599
  return binding.type.startsWith("unsafe:");
5583
5600
  }
5584
5601
  __name(isParsedUnsafeBinding, "isParsedUnsafeBinding");
5585
- var CacheSchema = z.strictObject({ enabled: z.boolean() });
5602
+ var CacheSchema = z.strictObject({
5603
+ enabled: z.boolean(),
5604
+ crossVersionCache: z.boolean().optional()
5605
+ });
5586
5606
  var SINGLETON_BINDING_TYPES = /* @__PURE__ */ new Set([
5587
5607
  "ai",
5588
5608
  "assets",
@@ -5609,10 +5629,37 @@ var EnvSchema = z.record(z.string(), BindingSchema).superRefine((env, ctx) => {
5609
5629
  message: `${listFormatter.format([...duplicates].sort())} bindings can only be defined once`
5610
5630
  });
5611
5631
  }).optional();
5612
- var ExportSchema = z.discriminatedUnion("type", [z.strictObject({
5613
- type: z.literal("durable-object"),
5614
- storage: z.enum(["sqlite", "legacy-kv"])
5615
- })]);
5632
+ var ExportSchema = z.union([
5633
+ z.strictObject({
5634
+ type: z.literal("durable-object"),
5635
+ state: z.literal("created").optional(),
5636
+ storage: z.enum(["sqlite", "legacy-kv"])
5637
+ }),
5638
+ z.strictObject({
5639
+ type: z.literal("durable-object"),
5640
+ state: z.literal("deleted")
5641
+ }),
5642
+ z.strictObject({
5643
+ type: z.literal("durable-object"),
5644
+ state: z.literal("renamed"),
5645
+ renamedTo: z.string()
5646
+ }),
5647
+ z.strictObject({
5648
+ type: z.literal("durable-object"),
5649
+ state: z.literal("transferred"),
5650
+ transferredTo: z.string()
5651
+ }),
5652
+ z.strictObject({
5653
+ type: z.literal("durable-object"),
5654
+ state: z.literal("expecting-transfer"),
5655
+ storage: z.enum(["sqlite", "legacy-kv"]),
5656
+ transferFrom: z.string()
5657
+ }),
5658
+ z.strictObject({
5659
+ type: z.literal("worker"),
5660
+ cache: z.strictObject({ enabled: z.boolean() }).optional()
5661
+ })
5662
+ ]);
5616
5663
  var LimitsSchema = z.strictObject({
5617
5664
  cpuMs: z.number().optional(),
5618
5665
  subrequests: z.number().optional()
@@ -5772,7 +5819,7 @@ function convertToWranglerConfig(config) {
5772
5819
  const result = {};
5773
5820
  convertTopLevel(config, result);
5774
5821
  convertBindingsAndAssets(config, result);
5775
- convertExports(config);
5822
+ convertExports(config, result);
5776
5823
  convertDomains(config, result);
5777
5824
  convertTriggers(config, result);
5778
5825
  convertTailConsumers(config, result);
@@ -5798,7 +5845,11 @@ function convertTopLevel(config, result) {
5798
5845
  result.limits = limits;
5799
5846
  }
5800
5847
  if (config.observability !== void 0) result.observability = convertObservability(config.observability);
5801
- if (config.cache !== void 0) result.cache = { enabled: config.cache.enabled };
5848
+ if (config.cache !== void 0) {
5849
+ const cache = { enabled: config.cache.enabled };
5850
+ if (config.cache.crossVersionCache !== void 0) cache.cross_version_cache = config.cache.crossVersionCache;
5851
+ result.cache = cache;
5852
+ }
5802
5853
  if (config.unsafe !== void 0) result.unsafe = convertUnsafeTopLevel(config.unsafe);
5803
5854
  }
5804
5855
  __name(convertTopLevel, "convertTopLevel");
@@ -6159,10 +6210,60 @@ function convertBindingsAndAssets(config, result) {
6159
6210
  }
6160
6211
  }
6161
6212
  __name(convertBindingsAndAssets, "convertBindingsAndAssets");
6162
- function convertExports(config, _result) {
6213
+ function convertExports(config, result) {
6163
6214
  const exports$2 = config.exports;
6164
6215
  if (!exports$2) return;
6165
- for (const value of Object.values(exports$2)) if (value.type === "durable-object") throw new Error("Durable Object exports are not currently supported.");
6216
+ const converted = {};
6217
+ const unknownExports = {};
6218
+ for (const [exportName, value] of Object.entries(exports$2)) {
6219
+ if (value.type === "worker") {
6220
+ converted[exportName] = value;
6221
+ continue;
6222
+ }
6223
+ if (value.type !== "durable-object") {
6224
+ unknownExports[exportName] = value;
6225
+ continue;
6226
+ }
6227
+ switch (value.state) {
6228
+ case void 0:
6229
+ case "created":
6230
+ converted[exportName] = {
6231
+ type: "durable-object",
6232
+ storage: value.storage
6233
+ };
6234
+ break;
6235
+ case "deleted":
6236
+ converted[exportName] = {
6237
+ type: "durable-object",
6238
+ state: "deleted"
6239
+ };
6240
+ break;
6241
+ case "renamed":
6242
+ converted[exportName] = {
6243
+ type: "durable-object",
6244
+ state: "renamed",
6245
+ renamed_to: value.renamedTo
6246
+ };
6247
+ break;
6248
+ case "transferred":
6249
+ converted[exportName] = {
6250
+ type: "durable-object",
6251
+ state: "transferred",
6252
+ transferred_to: value.transferredTo
6253
+ };
6254
+ break;
6255
+ case "expecting-transfer":
6256
+ converted[exportName] = {
6257
+ type: "durable-object",
6258
+ state: "expecting-transfer",
6259
+ storage: value.storage,
6260
+ transfer_from: value.transferFrom
6261
+ };
6262
+ break;
6263
+ }
6264
+ }
6265
+ if (Object.keys(unknownExports).length > 0) throw new UserError("Unknown export types found: " + Object.entries(unknownExports).map(([exportName, { type }]) => `- ${exportName} : ${type}`).join("\n"), { telemetryMessage: "Unknown export types found" });
6266
+ if (Object.keys(converted).length > 0) result.exports = converted;
6166
6267
  }
6167
6268
  __name(convertExports, "convertExports");
6168
6269
  function convertTriggers(config, result) {
@@ -8987,14 +9088,15 @@ var hashFile = /* @__PURE__ */ __name((filepath) => {
8987
9088
  }, "hashFile");
8988
9089
 
8989
9090
  // src/deploy/helpers/jwt.ts
9091
+ var decodeJwtPayload = /* @__PURE__ */ __name((token) => {
9092
+ return JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
9093
+ }, "decodeJwtPayload");
8990
9094
  var isJwtExpired = /* @__PURE__ */ __name((token) => {
8991
9095
  if ("vitest" in globalThis && (token === "<<funfetti-auth-jwt>>" || token === "<<funfetti-auth-jwt2>>" || token === "<<aus-completion-token>>")) {
8992
9096
  return false;
8993
9097
  }
8994
9098
  try {
8995
- const decodedJwt = JSON.parse(
8996
- Buffer.from(token.split(".")[1], "base64").toString()
8997
- );
9099
+ const decodedJwt = decodeJwtPayload(token);
8998
9100
  const dateNow = (/* @__PURE__ */ new Date()).getTime() / 1e3;
8999
9101
  return decodedJwt.exp <= dateNow;
9000
9102
  } catch (e) {
@@ -9006,6 +9108,7 @@ var isJwtExpired = /* @__PURE__ */ __name((token) => {
9006
9108
 
9007
9109
  // src/deploy/helpers/assets.ts
9008
9110
  var BULK_UPLOAD_CONCURRENCY = 3;
9111
+ var EDGE_KV_UPLOAD_CONCURRENCY = 50;
9009
9112
  var MAX_UPLOAD_ATTEMPTS = 5;
9010
9113
  var MAX_UPLOAD_GATEWAY_ERRORS = 5;
9011
9114
  var MAX_DIFF_LINES = 100;
@@ -9026,7 +9129,11 @@ var syncAssets = /* @__PURE__ */ __name(async (complianceConfig, accountId, asse
9026
9129
  { code: 1, telemetryMessage: "assets upload unexpected api response" }
9027
9130
  );
9028
9131
  }
9029
- if (initializeAssetsResponse.buckets.flat().length === 0) {
9132
+ const filesToUpload = initializeAssetsResponse.buckets.flat();
9133
+ const useSingleAssetUpload = isSingleAssetUploadMode(
9134
+ initializeAssetsResponse.jwt
9135
+ );
9136
+ if (filesToUpload.length === 0) {
9030
9137
  if (!initializeAssetsResponse.jwt) {
9031
9138
  throw new FatalError$1(
9032
9139
  "Could not find assets information to attach to deployment. Please try again.",
@@ -9036,9 +9143,17 @@ var syncAssets = /* @__PURE__ */ __name(async (complianceConfig, accountId, asse
9036
9143
  logger.info(
9037
9144
  `No updated asset files to upload. Proceeding with deployment...`
9038
9145
  );
9039
- return initializeAssetsResponse.jwt;
9146
+ return {
9147
+ jwt: initializeAssetsResponse.jwt,
9148
+ assetUploadStats: {
9149
+ assetUploadDurationMs: 0,
9150
+ assetUploadIsBulk: !useSingleAssetUpload,
9151
+ assetUploadFileCount: 0,
9152
+ assetUploadTotalBytes: 0
9153
+ }
9154
+ };
9040
9155
  }
9041
- const numberFilesToUpload = initializeAssetsResponse.buckets.flat().length;
9156
+ const numberFilesToUpload = filesToUpload.length;
9042
9157
  logger.info(
9043
9158
  `\u{1F300} Found ${numberFilesToUpload} new or modified static asset${numberFilesToUpload > 1 ? "s" : ""} to upload. Proceeding with upload...`
9044
9159
  );
@@ -9062,50 +9177,81 @@ var syncAssets = /* @__PURE__ */ __name(async (complianceConfig, accountId, asse
9062
9177
  return manifestEntry;
9063
9178
  });
9064
9179
  });
9065
- const queue = new PQueue({ concurrency: BULK_UPLOAD_CONCURRENCY });
9180
+ const uploadBuckets = useSingleAssetUpload ? assetBuckets.flat().map((entry) => [entry]) : assetBuckets;
9181
+ const concurrency = useSingleAssetUpload ? getEdgeKvUploadConcurrency(initializeAssetsResponse.jwt) : BULK_UPLOAD_CONCURRENCY;
9182
+ if (useSingleAssetUpload) {
9183
+ logger.debug(`Edge KV asset upload concurrency: ${concurrency}`);
9184
+ }
9185
+ const queue = new PQueue({ concurrency });
9066
9186
  const queuePromises = [];
9067
- let attempts = 0;
9068
9187
  const start = Date.now();
9069
9188
  let completionJwt = "";
9070
9189
  let uploadedAssetsCount = 0;
9071
- for (const [bucketIndex, bucket] of assetBuckets.entries()) {
9072
- attempts = 0;
9190
+ let uploadedBytes = 0;
9191
+ for (const [bucketIndex, bucket] of uploadBuckets.entries()) {
9192
+ let attempts = 0;
9073
9193
  let gatewayErrors = 0;
9074
9194
  const doUpload = /* @__PURE__ */ __name(async () => {
9075
- const payload = new FormData();
9076
9195
  const uploadedFiles = [];
9077
9196
  for (const manifestEntry of bucket) {
9078
- const absFilePath = path3.join(assetDirectory, manifestEntry[0]);
9079
9197
  uploadedFiles.push(manifestEntry[0]);
9080
- payload.append(
9081
- manifestEntry[1].hash,
9082
- new File(
9083
- [(await readFile(absFilePath)).toString("base64")],
9084
- manifestEntry[1].hash,
9085
- {
9086
- // Most formdata body encoders (incl. undici's) will override with "application/octet-stream" if you use a falsy value here
9087
- // Additionally, it appears that undici doesn't support non-standard main types (e.g. "null")
9088
- // So, to make it easier for any other clients, we'll just parse "application/null" on the API
9089
- // to mean actually null (signal to not send a Content-Type header with the response)
9090
- type: getContentType(absFilePath) ?? "application/null"
9091
- }
9092
- ),
9093
- manifestEntry[1].hash
9094
- );
9095
9198
  }
9096
9199
  try {
9097
- const res = await fetchResult(
9098
- complianceConfig,
9099
- `/accounts/${accountId}/workers/assets/upload?base64=true`,
9100
- {
9101
- method: "POST",
9102
- headers: {
9103
- Authorization: `Bearer ${initializeAssetsResponse.jwt}`
9104
- },
9105
- body: payload
9200
+ let res;
9201
+ if (useSingleAssetUpload) {
9202
+ const manifestEntry = bucket[0];
9203
+ const absFilePath = path2.join(assetDirectory, manifestEntry[0]);
9204
+ const contentType = getContentType(absFilePath);
9205
+ res = await fetchResult(
9206
+ complianceConfig,
9207
+ `/accounts/${accountId}/workers/assets/upload/${manifestEntry[1].hash}`,
9208
+ {
9209
+ method: "POST",
9210
+ headers: {
9211
+ Authorization: `Bearer ${initializeAssetsResponse.jwt}`,
9212
+ "Content-Type": contentType ?? "application/null"
9213
+ },
9214
+ body: createReadStream(absFilePath),
9215
+ duplex: "half"
9216
+ }
9217
+ );
9218
+ } else {
9219
+ const payload = new FormData();
9220
+ for (const manifestEntry of bucket) {
9221
+ const absFilePath = path2.join(assetDirectory, manifestEntry[0]);
9222
+ payload.append(
9223
+ manifestEntry[1].hash,
9224
+ new File(
9225
+ [(await readFile(absFilePath)).toString("base64")],
9226
+ manifestEntry[1].hash,
9227
+ {
9228
+ // Most formdata body encoders (incl. undici's) will override with "application/octet-stream" if you use a falsy value here
9229
+ // Additionally, it appears that undici doesn't support non-standard main types (e.g. "null")
9230
+ // So, to make it easier for any other clients, we'll just parse "application/null" on the API
9231
+ // to mean actually null (signal to not send a Content-Type header with the response)
9232
+ type: getContentType(absFilePath) ?? "application/null"
9233
+ }
9234
+ ),
9235
+ manifestEntry[1].hash
9236
+ );
9106
9237
  }
9107
- );
9238
+ res = await fetchResult(
9239
+ complianceConfig,
9240
+ `/accounts/${accountId}/workers/assets/upload?base64=true`,
9241
+ {
9242
+ method: "POST",
9243
+ headers: {
9244
+ Authorization: `Bearer ${initializeAssetsResponse.jwt}`
9245
+ },
9246
+ body: payload
9247
+ }
9248
+ );
9249
+ }
9108
9250
  uploadedAssetsCount += bucket.length;
9251
+ uploadedBytes += bucket.reduce(
9252
+ (total, manifestEntry) => total + manifestEntry[1].size,
9253
+ 0
9254
+ );
9109
9255
  logAssetsUploadStatus(
9110
9256
  numberFilesToUpload,
9111
9257
  uploadedAssetsCount,
@@ -9140,7 +9286,7 @@ var syncAssets = /* @__PURE__ */ __name(async (complianceConfig, accountId, asse
9140
9286
  } else if (isJwtExpired(initializeAssetsResponse.jwt)) {
9141
9287
  throw new FatalError$1(
9142
9288
  `Upload took too long.
9143
- Asset upload took too long on bucket ${bucketIndex + 1}/${initializeAssetsResponse.buckets.length}. Please try again.
9289
+ Asset upload took too long on bucket ${bucketIndex + 1}/${uploadBuckets.length}. Please try again.
9144
9290
  Assets already uploaded have been saved, so the next attempt will automatically resume from this point.`,
9145
9291
  { telemetryMessage: "Asset upload took too long" }
9146
9292
  );
@@ -9175,8 +9321,33 @@ Assets already uploaded have been saved, so the next attempt will automatically
9175
9321
  `\u2728 Success! Uploaded ${numberFilesToUpload} file${numberFilesToUpload > 1 ? "s" : ""} ${skippedMessage}${formatTime(uploadMs)}
9176
9322
  `
9177
9323
  );
9178
- return completionJwt;
9324
+ return {
9325
+ jwt: completionJwt,
9326
+ assetUploadStats: {
9327
+ assetUploadDurationMs: uploadMs,
9328
+ assetUploadIsBulk: !useSingleAssetUpload,
9329
+ assetUploadFileCount: uploadedAssetsCount,
9330
+ assetUploadTotalBytes: uploadedBytes
9331
+ }
9332
+ };
9179
9333
  }, "syncAssets");
9334
+ function isSingleAssetUploadMode(jwt) {
9335
+ try {
9336
+ return decodeJwtPayload(jwt).wrangler_single_asset_uploads === true;
9337
+ } catch {
9338
+ return false;
9339
+ }
9340
+ }
9341
+ __name(isSingleAssetUploadMode, "isSingleAssetUploadMode");
9342
+ function getEdgeKvUploadConcurrency(jwt) {
9343
+ try {
9344
+ const value = Number(decodeJwtPayload(jwt).edge_kv_upload_concurrency);
9345
+ return value > 0 ? Math.floor(value) : EDGE_KV_UPLOAD_CONCURRENCY;
9346
+ } catch {
9347
+ return EDGE_KV_UPLOAD_CONCURRENCY;
9348
+ }
9349
+ }
9350
+ __name(getEdgeKvUploadConcurrency, "getEdgeKvUploadConcurrency");
9180
9351
  var buildAssetManifest = /* @__PURE__ */ __name(async (dir) => {
9181
9352
  const files = await readdir(dir, { recursive: true });
9182
9353
  logReadFilesFromDirectory(dir, files);
@@ -9188,7 +9359,7 @@ var buildAssetManifest = /* @__PURE__ */ __name(async (dir) => {
9188
9359
  logger.debug("Ignoring asset:", relativeFilepath);
9189
9360
  return;
9190
9361
  }
9191
- const filepath = path3.join(dir, relativeFilepath);
9362
+ const filepath = path2.join(dir, relativeFilepath);
9192
9363
  const filestat = await stat(filepath);
9193
9364
  if (filestat.isSymbolicLink() || filestat.isDirectory()) {
9194
9365
  return;
@@ -9295,8 +9466,8 @@ function resolveAssetOptions({ assetsDir, main }, config) {
9295
9466
  { telemetryMessage: "assets router missing worker script" }
9296
9467
  );
9297
9468
  }
9298
- const _redirects = directoryExists ? maybeGetFile(path3.join(directory, REDIRECTS_FILENAME)) : void 0;
9299
- const _headers = directoryExists ? maybeGetFile(path3.join(directory, HEADERS_FILENAME)) : void 0;
9469
+ const _redirects = directoryExists ? maybeGetFile(path2.join(directory, REDIRECTS_FILENAME)) : void 0;
9470
+ const _headers = directoryExists ? maybeGetFile(path2.join(directory, HEADERS_FILENAME)) : void 0;
9300
9471
  const assetConfig = {
9301
9472
  html_handling: config.assets?.html_handling,
9302
9473
  not_found_handling: config.assets?.not_found_handling,
@@ -9927,6 +10098,7 @@ function createWorkerUploadForm(worker, bindings, options) {
9927
10098
  main,
9928
10099
  sourceMaps,
9929
10100
  migrations,
10101
+ exports: configuredExports,
9930
10102
  compatibility_date,
9931
10103
  compatibility_flags,
9932
10104
  keepVars,
@@ -10478,14 +10650,14 @@ function createWorkerUploadForm(worker, bindings, options) {
10478
10650
  if (hasManifest && main.type === "esm") {
10479
10651
  assert4(modules !== void 0);
10480
10652
  const subDirs = new Set(
10481
- modules.map((module) => path3__default.posix.dirname(module.name))
10653
+ modules.map((module) => path2__default.posix.dirname(module.name))
10482
10654
  );
10483
10655
  for (const subDir of subDirs) {
10484
10656
  if (subDir === ".") {
10485
10657
  continue;
10486
10658
  }
10487
- const relativePath = path3__default.posix.relative(subDir, manifestModuleName);
10488
- const filePath = path3__default.posix.join(subDir, manifestModuleName);
10659
+ const relativePath = path2__default.posix.relative(subDir, manifestModuleName);
10660
+ const filePath = path2__default.posix.join(subDir, manifestModuleName);
10489
10661
  modules.push({
10490
10662
  name: filePath,
10491
10663
  filePath,
@@ -10554,6 +10726,9 @@ function createWorkerUploadForm(worker, bindings, options) {
10554
10726
  compatibility_flags
10555
10727
  },
10556
10728
  ...migrations && { migrations },
10729
+ ...configuredExports && Object.keys(configuredExports).length > 0 && {
10730
+ exports: configuredExports
10731
+ },
10557
10732
  capnp_schema: capnpSchemaOutputFile,
10558
10733
  ...keep_bindings && { keep_bindings },
10559
10734
  ...logpush !== void 0 && { logpush },
@@ -10609,6 +10784,57 @@ function deployWfpUserWorker(dispatchNamespace, versionId) {
10609
10784
  logger.log("Current Version ID:", versionId);
10610
10785
  }
10611
10786
  __name(deployWfpUserWorker, "deployWfpUserWorker");
10787
+
10788
+ // src/deploy/helpers/use-service-environments.ts
10789
+ function useServiceEnvironments(config) {
10790
+ return "legacy_env" in config ? !config.legacy_env : Boolean(config.legacy.useServiceEnvironments);
10791
+ }
10792
+ __name(useServiceEnvironments, "useServiceEnvironments");
10793
+
10794
+ // src/deploy/helpers/environments.ts
10795
+ function hasDefinedEnvironments(config) {
10796
+ return !useServiceEnvironments(config) && Boolean(config.definedEnvironments?.length);
10797
+ }
10798
+ __name(hasDefinedEnvironments, "hasDefinedEnvironments");
10799
+ function applyServiceAndEnvironmentTags(config, tags) {
10800
+ const env = config.targetEnvironment;
10801
+ const serviceName = config.topLevelName;
10802
+ const shouldApplyTags = hasDefinedEnvironments(config);
10803
+ if (shouldApplyTags && !serviceName) {
10804
+ logger.warn(
10805
+ "No top-level `name` has been defined in Wrangler configuration. Add a top-level `name` to group this Worker together with its sibling environments in the Cloudflare dashboard."
10806
+ );
10807
+ }
10808
+ const serviceTag = shouldApplyTags && serviceName ? `${SERVICE_TAG_PREFIX}${serviceName}` : null;
10809
+ const environmentTag = serviceTag && env ? `${ENVIRONMENT_TAG_PREFIX}${env}` : null;
10810
+ tags = tags.filter(
10811
+ (tag) => !tag.startsWith(SERVICE_TAG_PREFIX) && !tag.startsWith(ENVIRONMENT_TAG_PREFIX)
10812
+ );
10813
+ if (serviceTag) {
10814
+ tags.push(serviceTag);
10815
+ }
10816
+ if (environmentTag) {
10817
+ tags.push(environmentTag);
10818
+ }
10819
+ return tags;
10820
+ }
10821
+ __name(applyServiceAndEnvironmentTags, "applyServiceAndEnvironmentTags");
10822
+ function warnOnErrorUpdatingServiceAndEnvironmentTags() {
10823
+ logger.warn(
10824
+ "Could not apply service and environment tags. This Worker will not appear grouped together with its sibling environments in the Cloudflare dashboard."
10825
+ );
10826
+ }
10827
+ __name(warnOnErrorUpdatingServiceAndEnvironmentTags, "warnOnErrorUpdatingServiceAndEnvironmentTags");
10828
+ function tagsAreEqual(a, b) {
10829
+ return a.length === b.length && a.every((el, i) => b[i] === el);
10830
+ }
10831
+ __name(tagsAreEqual, "tagsAreEqual");
10832
+
10833
+ // src/deploy/helpers/error-codes.ts
10834
+ var INVALID_INHERIT_BINDING_CODE = 10057;
10835
+ var EXPORTS_RECONCILIATION_ERROR_CODE = 100402;
10836
+ var INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE = 100405;
10837
+ var ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE = 100406;
10612
10838
  async function getMigrationsToUpload(scriptName, props) {
10613
10839
  const { config, accountId } = props;
10614
10840
  assert4(accountId, "Missing accountId");
@@ -10687,51 +10913,128 @@ var suppressNotFoundError = /* @__PURE__ */ __name((err) => {
10687
10913
  throw err;
10688
10914
  }
10689
10915
  }, "suppressNotFoundError");
10690
-
10691
- // src/deploy/helpers/use-service-environments.ts
10692
- function useServiceEnvironments(config) {
10693
- return "legacy_env" in config ? !config.legacy_env : Boolean(config.legacy.useServiceEnvironments);
10916
+ async function resolveDoLifecyclePayload(props) {
10917
+ const durableObjectExports = getDurableObjectExports(props.config.exports);
10918
+ const hasDurableObjectExports2 = Object.keys(durableObjectExports).length > 0;
10919
+ if (hasDurableObjectExports2) {
10920
+ return {
10921
+ migrations: void 0,
10922
+ exports: durableObjectExports
10923
+ };
10924
+ }
10925
+ const migrations = !props.isDryRun ? await getMigrationsToUpload(props.scriptName, {
10926
+ accountId: props.accountId,
10927
+ config: props.config,
10928
+ useServiceEnvironments: props.useServiceEnvironments,
10929
+ env: props.env,
10930
+ dispatchNamespace: props.dispatchNamespace
10931
+ }) : void 0;
10932
+ return {
10933
+ migrations,
10934
+ exports: void 0
10935
+ };
10694
10936
  }
10695
- __name(useServiceEnvironments, "useServiceEnvironments");
10937
+ __name(resolveDoLifecyclePayload, "resolveDoLifecyclePayload");
10696
10938
 
10697
- // src/deploy/helpers/environments.ts
10698
- function hasDefinedEnvironments(config) {
10699
- return !useServiceEnvironments(config) && Boolean(config.definedEnvironments?.length);
10939
+ // src/deploy/helpers/exports.ts
10940
+ async function resolveExportsUploadPayload(props) {
10941
+ const partitionedExports = partitionExports$1(props.config.exports);
10942
+ const { migrations, exports: durableObjectExports } = await resolveDoLifecyclePayload(props);
10943
+ const exports = {
10944
+ ...partitionedExports.worker,
10945
+ ...durableObjectExports ?? {}
10946
+ };
10947
+ return {
10948
+ migrations,
10949
+ exports: Object.keys(exports).length > 0 ? exports : void 0
10950
+ };
10700
10951
  }
10701
- __name(hasDefinedEnvironments, "hasDefinedEnvironments");
10702
- function applyServiceAndEnvironmentTags(config, tags) {
10703
- const env = config.targetEnvironment;
10704
- const serviceName = config.topLevelName;
10705
- const shouldApplyTags = hasDefinedEnvironments(config);
10706
- if (shouldApplyTags && !serviceName) {
10707
- logger.warn(
10708
- "No top-level `name` has been defined in Wrangler configuration. Add a top-level `name` to group this Worker together with its sibling environments in the Cloudflare dashboard."
10709
- );
10952
+ __name(resolveExportsUploadPayload, "resolveExportsUploadPayload");
10953
+ function renderExportsReconciliationSuccess(result) {
10954
+ const hasAnyContent = result.created.length > 0 || result.updated.length > 0 || result.deleted.length > 0 || result.renamed.length > 0 || result.transferred.length > 0 || result.transfer_pending.length > 0 || result.warnings.length > 0 || result.info.length > 0 || result.removable_entries.length > 0;
10955
+ if (!hasAnyContent) {
10956
+ return;
10710
10957
  }
10711
- const serviceTag = shouldApplyTags && serviceName ? `${SERVICE_TAG_PREFIX}${serviceName}` : null;
10712
- const environmentTag = serviceTag && env ? `${ENVIRONMENT_TAG_PREFIX}${env}` : null;
10713
- tags = tags.filter(
10714
- (tag) => !tag.startsWith(SERVICE_TAG_PREFIX) && !tag.startsWith(ENVIRONMENT_TAG_PREFIX)
10715
- );
10716
- if (serviceTag) {
10717
- tags.push(serviceTag);
10958
+ logger.log("");
10959
+ logger.log(bold("Durable Object exports reconciliation:"));
10960
+ if (result.created.length > 0) {
10961
+ logger.log(` Created: ${result.created.join(", ")}`);
10718
10962
  }
10719
- if (environmentTag) {
10720
- tags.push(environmentTag);
10963
+ if (result.updated.length > 0) {
10964
+ logger.log(` Updated: ${result.updated.join(", ")}`);
10721
10965
  }
10722
- return tags;
10966
+ if (result.deleted.length > 0) {
10967
+ logger.log(` Deleted: ${result.deleted.join(", ")}`);
10968
+ }
10969
+ if (result.renamed.length > 0) {
10970
+ const renames = result.renamed.map((r) => `${r.from} \u2192 ${r.to}`).join(", ");
10971
+ logger.log(` Renamed: ${renames}`);
10972
+ }
10973
+ for (const t of result.transferred) {
10974
+ logger.log(` Transferred (${t.phase}): ${t.class} \u2192 ${t.to}`);
10975
+ }
10976
+ for (const t of result.transfer_pending) {
10977
+ logger.log(` Transfer pending: ${t.class} \u2190 ${t.from}`);
10978
+ }
10979
+ if (result.warnings.length > 0) {
10980
+ logger.log("");
10981
+ logger.warn(bold(" Warnings:"));
10982
+ for (const w of result.warnings) {
10983
+ logger.warn(yellow(` [${w.scenario}] ${w.class}: ${w.message}`));
10984
+ }
10985
+ }
10986
+ if (result.info.length > 0) {
10987
+ logger.log("");
10988
+ logger.log(dim(" Info:"));
10989
+ for (const info of result.info) {
10990
+ let line = dim(` [${info.scenario}] ${info.class}: ${info.message}`);
10991
+ if (info.referencing_scripts && info.referencing_scripts.length > 0) {
10992
+ line += dim(` (referenced by: ${info.referencing_scripts.join(", ")})`);
10993
+ }
10994
+ logger.log(line);
10995
+ }
10996
+ }
10997
+ if (result.removable_entries.length > 0) {
10998
+ logger.log("");
10999
+ logger.log(
11000
+ dim(
11001
+ ` Safe to remove from \`exports\`: ${result.removable_entries.join(", ")}`
11002
+ )
11003
+ );
11004
+ }
11005
+ logger.log("");
10723
11006
  }
10724
- __name(applyServiceAndEnvironmentTags, "applyServiceAndEnvironmentTags");
10725
- function warnOnErrorUpdatingServiceAndEnvironmentTags() {
10726
- logger.warn(
10727
- "Could not apply service and environment tags. This Worker will not appear grouped together with its sibling environments in the Cloudflare dashboard."
10728
- );
11007
+ __name(renderExportsReconciliationSuccess, "renderExportsReconciliationSuccess");
11008
+ function renderExportsReconciliationError(details) {
11009
+ const lines = ["Durable Object exports reconciliation failed:"];
11010
+ for (const detail of details) {
11011
+ lines.push(
11012
+ red(` \u2718 [${detail.scenario}] class '${detail.class}': ${detail.message}`)
11013
+ );
11014
+ if (detail.suggestion) {
11015
+ lines.push(` Suggestion: ${detail.suggestion}`);
11016
+ }
11017
+ if (detail.referencing_scripts && detail.referencing_scripts.length > 0) {
11018
+ lines.push(
11019
+ ` Referencing scripts: ${detail.referencing_scripts.join(", ")}`
11020
+ );
11021
+ }
11022
+ }
11023
+ return lines.join("\n");
10729
11024
  }
10730
- __name(warnOnErrorUpdatingServiceAndEnvironmentTags, "warnOnErrorUpdatingServiceAndEnvironmentTags");
10731
- function tagsAreEqual(a, b) {
10732
- return a.length === b.length && a.every((el, i) => b[i] === el);
11025
+ __name(renderExportsReconciliationError, "renderExportsReconciliationError");
11026
+ function isExportsReconciliationErrorDetails(value) {
11027
+ if (!Array.isArray(value)) {
11028
+ return false;
11029
+ }
11030
+ for (const entry of value) {
11031
+ if (typeof entry !== "object" || entry === null || typeof entry.class !== "string" || typeof entry.scenario !== "string" || typeof entry.message !== "string") {
11032
+ return false;
11033
+ }
11034
+ }
11035
+ return true;
10733
11036
  }
10734
- __name(tagsAreEqual, "tagsAreEqual");
11037
+ __name(isExportsReconciliationErrorDetails, "isExportsReconciliationErrorDetails");
10735
11038
 
10736
11039
  // ../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/esm/index.js
10737
11040
  function dedent(templ) {
@@ -10825,9 +11128,9 @@ async function diagnoseStartupError(err, workerBundle, projectRoot, analyseBundl
10825
11128
  "startup-profile",
10826
11129
  false
10827
11130
  );
10828
- const profile = path3__default.relative(
11131
+ const profile = path2__default.relative(
10829
11132
  projectRoot ?? process.cwd(),
10830
- path3__default.join(tmpDir.path, `worker.cpuprofile`)
11133
+ path2__default.join(tmpDir.path, `worker.cpuprofile`)
10831
11134
  );
10832
11135
  await writeFile(profile, JSON.stringify(cpuProfile));
10833
11136
  errorMessage += esm_default2`
@@ -10918,7 +11221,7 @@ async function parseBulkInputToObject(input, includeNull = false) {
10918
11221
  let secretFormat;
10919
11222
  if (input) {
10920
11223
  secretSource = "file";
10921
- const jsonFilePath = path3__default.resolve(input);
11224
+ const jsonFilePath = path2__default.resolve(input);
10922
11225
  const fileContent = readFileSync$2(jsonFilePath);
10923
11226
  try {
10924
11227
  content = parseJSON$1(fileContent);
@@ -12694,11 +12997,6 @@ async function createAgentMemoryNamespace(complianceConfig, accountId, namespace
12694
12997
  );
12695
12998
  }
12696
12999
  __name(createAgentMemoryNamespace, "createAgentMemoryNamespace");
12697
-
12698
- // src/deploy/helpers/error-codes.ts
12699
- var INVALID_INHERIT_BINDING_CODE = 10057;
12700
-
12701
- // src/deploy/helpers/secrets-validation.ts
12702
13000
  function addRequiredSecretsInheritBindings(config, bindings, options) {
12703
13001
  if (!config.secrets?.required?.length) {
12704
13002
  return;
@@ -12712,9 +13010,12 @@ function addRequiredSecretsInheritBindings(config, bindings, options) {
12712
13010
  if (options.type === "deploy" && !options.workerExists) {
12713
13011
  throw new UserError$1(
12714
13012
  `The following required secrets have not been set: ${inheritedSecrets.join(", ")}
12715
- Use \`wrangler secret put <NAME>\` to set secrets before deploying.
13013
+ This Worker does not exist yet, so secrets cannot be set in advance with \`wrangler secret put\`.
13014
+ To deploy a new Worker with secrets, supply them via a secrets file:
13015
+ wrangler deploy --secrets-file <path-to-file>
13016
+ where the file contains lines in the format \`SECRET_NAME=value\` (or JSON).
12716
13017
  See https://developers.cloudflare.com/workers/configuration/secrets/#secrets-on-deployed-workers for more information.`,
12717
- { telemetryMessage: "required secrets missing before deploy" }
13018
+ { telemetryMessage: "required secrets missing before first deploy" }
12718
13019
  );
12719
13020
  }
12720
13021
  for (const secretName of inheritedSecrets) {
@@ -12729,9 +13030,13 @@ function handleMissingSecretsError(err, config, options) {
12729
13030
  const missingSecretNames = err.notes.map((note) => note.text.match(/^inherit binding '(.+?)' is invalid/)).filter((match) => match !== null).map((match) => match[1]).filter((secretName) => config.secrets?.required?.includes(secretName));
12730
13031
  if (missingSecretNames.length > 0) {
12731
13032
  err.preventReport();
13033
+ const secretPutCommand = `wrangler ${options.type === "deploy" ? "" : "versions "}secret put`;
13034
+ const secretsFileCommand = `wrangler ${options.type === "deploy" ? "deploy" : "versions upload"} --secrets-file <path-to-file>`;
13035
+ const action = options.type === "deploy" ? "deploying" : "uploading";
12732
13036
  throw new UserError$1(
12733
13037
  `The following required secrets have not been set: ${missingSecretNames.join(", ")}
12734
- Use \`wrangler ${options.type === "deploy" ? "secret put" : "versions secret put"} <NAME>\` to set secrets before ${options.type === "deploy" ? "deploying" : "uploading"}.
13038
+ Use \`${secretPutCommand} <NAME>\` to set secrets before ${action},
13039
+ or supply them when ${action} with \`${secretsFileCommand}\`.
12735
13040
  See https://developers.cloudflare.com/workers/configuration/secrets/#secrets-on-deployed-workers for more information.`,
12736
13041
  { telemetryMessage: "required secrets missing during upload or deploy" }
12737
13042
  );
@@ -13920,13 +14225,13 @@ var validateRoutes = /* @__PURE__ */ __name((routes, assets) => {
13920
14225
  );
13921
14226
  }
13922
14227
  if (mountedAssetRoutes.length > 0 && assets?.directory !== void 0) {
13923
- const relativeAssetsDir = path3__default.relative(process.cwd(), assets.directory);
14228
+ const relativeAssetsDir = path2__default.relative(process.cwd(), assets.directory);
13924
14229
  const warnFn = logger.once?.warn ?? logger.warn;
13925
14230
  warnFn(
13926
14231
  `Warning: The following routes will attempt to serve Assets on a configured path:
13927
14232
  ${mountedAssetRoutes.map((route) => {
13928
14233
  const routeNoScheme = route.replace(/https?:\/\//g, "");
13929
- const assetPath = path3__default.join(
14234
+ const assetPath = path2__default.join(
13930
14235
  relativeAssetsDir,
13931
14236
  routeNoScheme.substring(routeNoScheme.indexOf("/"))
13932
14237
  );
@@ -14182,20 +14487,24 @@ async function deploy(props, config, buildResult, callbacks) {
14182
14487
  content,
14183
14488
  sourceMaps
14184
14489
  } = buildResult;
14185
- const migrations = !isDryRun ? await getMigrationsToUpload(scriptName, {
14490
+ const { migrations, exports } = await resolveExportsUploadPayload({
14491
+ scriptName,
14492
+ isDryRun,
14186
14493
  accountId,
14187
14494
  config,
14188
14495
  useServiceEnvironments: useServiceEnvironments(config),
14189
14496
  env: props.env,
14190
14497
  dispatchNamespace: props.dispatchNamespace
14191
- }) : void 0;
14192
- const assetsJwt = assetsOptions && !isDryRun ? await syncAssets(
14498
+ });
14499
+ const assetsUploadResult = assetsOptions && !isDryRun ? await syncAssets(
14193
14500
  config,
14194
14501
  accountId,
14195
14502
  assetsOptions.directory,
14196
14503
  scriptName,
14197
14504
  props.dispatchNamespace
14198
14505
  ) : void 0;
14506
+ const assetsJwt = assetsUploadResult?.jwt;
14507
+ const assetUploadStats = assetsUploadResult?.assetUploadStats;
14199
14508
  if (assetsOptions && isDryRun) {
14200
14509
  await buildAssetManifest(assetsOptions.directory);
14201
14510
  }
@@ -14246,7 +14555,7 @@ async function deploy(props, config, buildResult, callbacks) {
14246
14555
  });
14247
14556
  }
14248
14557
  const placement = parseConfigPlacement(config);
14249
- const entryPointName = path3__default.basename(resolvedEntryPointPath);
14558
+ const entryPointName = path2__default.basename(resolvedEntryPointPath);
14250
14559
  const main = {
14251
14560
  name: entryPointName,
14252
14561
  filePath: resolvedEntryPointPath,
@@ -14257,6 +14566,7 @@ async function deploy(props, config, buildResult, callbacks) {
14257
14566
  name: scriptName,
14258
14567
  main,
14259
14568
  migrations,
14569
+ exports,
14260
14570
  modules,
14261
14571
  containers: config.containers,
14262
14572
  sourceMaps,
@@ -14289,10 +14599,10 @@ async function deploy(props, config, buildResult, callbacks) {
14289
14599
  0
14290
14600
  );
14291
14601
  await printBundleSize(
14292
- { name: path3__default.basename(resolvedEntryPointPath), content },
14602
+ { name: path2__default.basename(resolvedEntryPointPath), content },
14293
14603
  modules
14294
14604
  );
14295
- const canUseNewVersionsDeploymentsApi = workerExists && props.dispatchNamespace === void 0 && !useServiceEnvironments2 && format3 === "modules" && migrations === void 0 && !config.first_party_worker && config.containers === void 0;
14605
+ const canUseNewVersionsDeploymentsApi = workerExists && props.dispatchNamespace === void 0 && !useServiceEnvironments2 && format3 === "modules" && migrations === void 0 && !hasDurableObjectExports(config.exports) && !config.first_party_worker && config.containers === void 0;
14296
14606
  let workerBundle;
14297
14607
  const dockerPath = getDockerPath();
14298
14608
  if (normalisedContainerConfig.length && props.containersRollout !== "none") {
@@ -14424,7 +14734,7 @@ async function deploy(props, config, buildResult, callbacks) {
14424
14734
  startup_time_ms: versionResult.startup_time_ms
14425
14735
  };
14426
14736
  } else {
14427
- result = await retryOnAPIFailure(
14737
+ const uploadResult = await retryOnAPIFailure(
14428
14738
  async () => fetchResult(
14429
14739
  config,
14430
14740
  workerUrl,
@@ -14442,6 +14752,12 @@ async function deploy(props, config, buildResult, callbacks) {
14442
14752
  ),
14443
14753
  logger
14444
14754
  );
14755
+ result = uploadResult;
14756
+ if (uploadResult.exports_reconciliation) {
14757
+ renderExportsReconciliationSuccess(
14758
+ uploadResult.exports_reconciliation
14759
+ );
14760
+ }
14445
14761
  const nextTags = applyServiceAndEnvironmentTags(config, tags);
14446
14762
  if (!tagsAreEqual(tags, nextTags)) {
14447
14763
  try {
@@ -14497,6 +14813,13 @@ async function deploy(props, config, buildResult, callbacks) {
14497
14813
  { unsafeMetadata: config.unsafe?.metadata }
14498
14814
  );
14499
14815
  }
14816
+ if (err instanceof APIError && err.code === EXPORTS_RECONCILIATION_ERROR_CODE && isExportsReconciliationErrorDetails(err.meta?.details)) {
14817
+ err.preventReport();
14818
+ throw new UserError$1(
14819
+ renderExportsReconciliationError(err.meta.details),
14820
+ { telemetryMessage: "deploy do exports reconciliation failed" }
14821
+ );
14822
+ }
14500
14823
  const message = await helpIfErrorIsSizeOrScriptStartup(
14501
14824
  err,
14502
14825
  dependencies,
@@ -14540,7 +14863,7 @@ async function deploy(props, config, buildResult, callbacks) {
14540
14863
  }
14541
14864
  }
14542
14865
  if (props.outfile) {
14543
- mkdirSync(path3__default.dirname(props.outfile), { recursive: true });
14866
+ mkdirSync(path2__default.dirname(props.outfile), { recursive: true });
14544
14867
  const serializedFormData = await new Response(workerBundle).arrayBuffer();
14545
14868
  writeFileSync(props.outfile, Buffer.from(serializedFormData));
14546
14869
  }
@@ -14560,7 +14883,7 @@ async function deploy(props, config, buildResult, callbacks) {
14560
14883
  }
14561
14884
  if (props.dispatchNamespace !== void 0) {
14562
14885
  deployWfpUserWorker(props.dispatchNamespace, versionId);
14563
- return { versionId, workerTag };
14886
+ return { versionId, workerTag, assetUploadStats };
14564
14887
  }
14565
14888
  assert4(accountId);
14566
14889
  const targets = await triggersDeploy({
@@ -14578,10 +14901,23 @@ async function deploy(props, config, buildResult, callbacks) {
14578
14901
  sourceMapSize,
14579
14902
  versionId,
14580
14903
  workerTag,
14904
+ assetUploadStats,
14581
14905
  targets: targets ?? []
14582
14906
  };
14583
14907
  }
14584
14908
  __name(deploy, "deploy");
14909
+
14910
+ // src/deploy/helpers/binding-depends-on-export.ts
14911
+ function renderBindingDependsOnExportError(serverMessage) {
14912
+ const trimmed = serverMessage.trim();
14913
+ if (trimmed.length > 0) {
14914
+ return trimmed;
14915
+ }
14916
+ return "A Durable Object binding references a class declared in `exports` but not yet provisioned. Declarative `exports` are reconciled when the version is deployed. Deploy this version to provision the class, or remove the binding and access the Durable Object via `ctx.exports.<ClassName>` until then.";
14917
+ }
14918
+ __name(renderBindingDependsOnExportError, "renderBindingDependsOnExportError");
14919
+
14920
+ // src/deploy/versions-upload.ts
14585
14921
  async function versionsUpload(props, config, buildResult, callbacks) {
14586
14922
  const { entry, compatibilityDate, compatibilityFlags, keepVars, accountId } = props;
14587
14923
  const assetsOptions = resolveAssetOptions(props, config);
@@ -14613,14 +14949,17 @@ async function versionsUpload(props, config, buildResult, callbacks) {
14613
14949
  hidden: true
14614
14950
  };
14615
14951
  }
14616
- const migrations = !props.dryRun ? await getMigrationsToUpload(scriptName, {
14952
+ const { migrations, exports } = await resolveExportsUploadPayload({
14953
+ scriptName,
14954
+ isDryRun: props.dryRun,
14617
14955
  accountId,
14618
14956
  config,
14619
14957
  useServiceEnvironments: useServiceEnvironments(config),
14620
14958
  env: props.env,
14621
14959
  dispatchNamespace: void 0
14622
- }) : void 0;
14623
- const assetsJwt = assetsOptions && !props.dryRun ? await syncAssets(config, accountId, assetsOptions.directory, scriptName) : void 0;
14960
+ });
14961
+ const assetsUploadResult = assetsOptions && !props.dryRun ? await syncAssets(config, accountId, assetsOptions.directory, scriptName) : void 0;
14962
+ const assetsJwt = assetsUploadResult?.jwt;
14624
14963
  if (props.secretsFile) {
14625
14964
  const secretsResult = await parseBulkInputToObject(props.secretsFile);
14626
14965
  if (secretsResult) {
@@ -14636,7 +14975,7 @@ async function versionsUpload(props, config, buildResult, callbacks) {
14636
14975
  }
14637
14976
  addRequiredSecretsInheritBindings(config, bindings, { type: "upload" });
14638
14977
  const placement = parseConfigPlacement(config);
14639
- const entryPointName = path3__default.basename(resolvedEntryPointPath);
14978
+ const entryPointName = path2__default.basename(resolvedEntryPointPath);
14640
14979
  const main = {
14641
14980
  name: entryPointName,
14642
14981
  filePath: resolvedEntryPointPath,
@@ -14646,6 +14985,7 @@ async function versionsUpload(props, config, buildResult, callbacks) {
14646
14985
  const worker = {
14647
14986
  main,
14648
14987
  migrations,
14988
+ exports,
14649
14989
  modules,
14650
14990
  containers: config.containers,
14651
14991
  sourceMaps,
@@ -14678,7 +15018,7 @@ async function versionsUpload(props, config, buildResult, callbacks) {
14678
15018
  // cache is a versioned setting
14679
15019
  };
14680
15020
  await printBundleSize(
14681
- { name: path3__default.basename(resolvedEntryPointPath), content },
15021
+ { name: path2__default.basename(resolvedEntryPointPath), content },
14682
15022
  modules
14683
15023
  );
14684
15024
  let workerBundle;
@@ -14749,6 +15089,13 @@ async function versionsUpload(props, config, buildResult, callbacks) {
14749
15089
  { unsafeMetadata: config.unsafe?.metadata }
14750
15090
  );
14751
15091
  }
15092
+ if (err instanceof APIError && err.code === ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE) {
15093
+ err.preventReport();
15094
+ const serverMessage = err.notes[0]?.text.replace(` [code: ${ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE}]`, "").trim() ?? "";
15095
+ throw new UserError$1(renderBindingDependsOnExportError(serverMessage), {
15096
+ telemetryMessage: "versions upload binding depends on unprovisioned export"
15097
+ });
15098
+ }
14752
15099
  const message = await helpIfErrorIsSizeOrScriptStartup(
14753
15100
  err,
14754
15101
  dependencies,
@@ -14794,7 +15141,7 @@ async function versionsUpload(props, config, buildResult, callbacks) {
14794
15141
  }
14795
15142
  }
14796
15143
  if (props.outfile) {
14797
- mkdirSync(path3__default.dirname(props.outfile), { recursive: true });
15144
+ mkdirSync(path2__default.dirname(props.outfile), { recursive: true });
14798
15145
  const serializedFormData = await new Response(workerBundle).arrayBuffer();
14799
15146
  writeFileSync(props.outfile, Buffer.from(serializedFormData));
14800
15147
  }
@@ -14834,7 +15181,13 @@ Changes to non-versioned settings (config properties 'logpush' or 'tail_consumer
14834
15181
  Changes to triggers (routes, custom domains, cron schedules, etc) must be applied with the command ${cmdTriggersDeploy}
14835
15182
  `)
14836
15183
  );
14837
- return { versionId, workerTag, versionPreviewUrl, versionPreviewAliasUrl };
15184
+ return {
15185
+ versionId,
15186
+ workerTag,
15187
+ assetUploadStats: assetsUploadResult?.assetUploadStats,
15188
+ versionPreviewUrl,
15189
+ versionPreviewAliasUrl
15190
+ };
14838
15191
  }
14839
15192
  __name(versionsUpload, "versionsUpload");
14840
15193
  var MAX_DNS_LABEL_LENGTH = 63;
@@ -14924,6 +15277,23 @@ function validateNodeCompatMode(compatibilityDateStr = "2000-01-01", compatibili
14924
15277
  return mode;
14925
15278
  }
14926
15279
  __name(validateNodeCompatMode, "validateNodeCompatMode");
15280
+
15281
+ // src/deploy/helpers/inconsistent-exports.ts
15282
+ function renderInconsistentExportsAcrossVersionsError(serverMessage) {
15283
+ return [
15284
+ serverMessage,
15285
+ "",
15286
+ "All versions in a percentage-split deployment must declare identical Durable Object `exports`. Cloudflare requires this so traffic on one branch can't route to code referencing unprovisioned or just-deleted DO namespaces.",
15287
+ "",
15288
+ "What to do:",
15289
+ " 1. Deploy the version that changes `exports` at 100% first:",
15290
+ " wrangler versions deploy <new-version-id>@100%",
15291
+ " 2. Once that deploy is stable, run your percentage-split deploy.",
15292
+ "",
15293
+ "Learn more: https://developers.cloudflare.com/workers/configuration/versions-and-deployments/gradual-deployments/#gradual-deployments-for-durable-objects"
15294
+ ].join("\n");
15295
+ }
15296
+ __name(renderInconsistentExportsAcrossVersionsError, "renderInconsistentExportsAcrossVersionsError");
14927
15297
  /*!
14928
15298
  * Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com)
14929
15299
  *
@@ -14946,4 +15316,4 @@ __name(validateNodeCompatMode, "validateNodeCompatMode");
14946
15316
  * THE SOFTWARE.
14947
15317
  */
14948
15318
 
14949
- export { INVALID_INHERIT_BINDING_CODE, InputWorkerSchema, NoInputError, OutputWorkerSchema, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKFLOW_NOT_FOUND_CODE, addRequiredSecretsInheritBindings, addWorkersSitesBindings, applyServiceAndEnvironmentTags, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, confirmLatestDeploymentOverwrite, convertConfigToBindings, convertToWranglerConfig, createDeployment, createTruncatedAlias, createWorkerUploadForm, deletePullConsumer, deleteWorkerConsumer, deploy, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, ensureQueuesExistByConfig, extractBindingsOfType, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, fromMimeType, generatePreviewAlias, getBindings, getBranchName, getConfigPatch, getDeployConfirmFunction, getMigrationsToUpload, getQueue, getRemoteConfigDiff, getSettings, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, handleUnsafeCapnp, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isJwtExpired, isModifiedDiffValue, isNonDestructive, isUnsafeBindingType, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, moduleTypeMimeType, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, postConsumer, printBindings, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderRoute, resolveAssetOptions, sanitizeBranchName, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, useServiceEnvironments, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, warnOnErrorUpdatingServiceAndEnvironmentTags, warnOrError, workerNotFoundErrorMessage };
15319
+ export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, EXPORTS_RECONCILIATION_ERROR_CODE, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, InputWorkerSchema, NoInputError, OutputWorkerSchema, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKFLOW_NOT_FOUND_CODE, addRequiredSecretsInheritBindings, addWorkersSitesBindings, applyServiceAndEnvironmentTags, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, confirmLatestDeploymentOverwrite, convertConfigToBindings, convertToWranglerConfig, createDeployment, createTruncatedAlias, createWorkerUploadForm, decodeJwtPayload, deletePullConsumer, deleteWorkerConsumer, deploy, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, ensureQueuesExistByConfig, extractBindingsOfType, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, fromMimeType, generatePreviewAlias, getBindings, getBranchName, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getMigrationsToUpload, getQueue, getRemoteConfigDiff, getSettings, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, handleUnsafeCapnp, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isUnsafeBindingType, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, moduleTypeMimeType, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, postConsumer, printBindings, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, sanitizeBranchName, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, useServiceEnvironments, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, warnOnErrorUpdatingServiceAndEnvironmentTags, warnOrError, workerNotFoundErrorMessage };