wrangler 0.0.0-e2f9bb2 → 0.0.0-e322475

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.
Files changed (103) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +3 -1
  3. package/bin/wrangler.js +36 -4
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +15 -7
  6. package/pages/functions/buildPlugin.ts +13 -0
  7. package/pages/functions/buildWorker.ts +14 -1
  8. package/pages/functions/template-plugin.ts +3 -2
  9. package/src/__tests__/configuration.test.ts +652 -229
  10. package/src/__tests__/dev.test.tsx +372 -79
  11. package/src/__tests__/helpers/mock-cfetch.ts +2 -2
  12. package/src/__tests__/helpers/mock-console.ts +11 -1
  13. package/src/__tests__/helpers/mock-dialogs.ts +75 -11
  14. package/src/__tests__/helpers/mock-process.ts +24 -0
  15. package/src/__tests__/index.test.ts +81 -72
  16. package/src/__tests__/init.test.ts +1360 -410
  17. package/src/__tests__/jest.setup.ts +38 -0
  18. package/src/__tests__/kv.test.ts +218 -152
  19. package/src/__tests__/logger.test.ts +26 -0
  20. package/src/__tests__/package-manager.test.ts +154 -7
  21. package/src/__tests__/pages.test.ts +478 -53
  22. package/src/__tests__/parse.test.ts +8 -0
  23. package/src/__tests__/publish.test.ts +1614 -333
  24. package/src/__tests__/r2.test.ts +55 -36
  25. package/src/__tests__/secret.test.ts +39 -4
  26. package/src/__tests__/user.test.ts +1 -0
  27. package/src/__tests__/whoami.test.tsx +34 -0
  28. package/src/abort.d.ts +3 -0
  29. package/src/bundle-reporter.tsx +29 -0
  30. package/src/bundle.ts +42 -7
  31. package/src/cfetch/index.ts +21 -4
  32. package/src/cfetch/internal.ts +25 -20
  33. package/src/config/config.ts +11 -2
  34. package/src/config/environment.ts +41 -15
  35. package/src/config/index.ts +162 -0
  36. package/src/config/validation-helpers.ts +10 -1
  37. package/src/config/validation.ts +234 -78
  38. package/src/create-worker-preview.ts +32 -22
  39. package/src/create-worker-upload-form.ts +22 -8
  40. package/src/dev/dev.tsx +48 -67
  41. package/src/dev/local.tsx +16 -7
  42. package/src/dev/remote.tsx +57 -21
  43. package/src/dev/use-esbuild.ts +1 -7
  44. package/src/dialogs.tsx +48 -0
  45. package/src/durable.ts +102 -0
  46. package/src/entry.ts +71 -10
  47. package/src/generate-auth-url.ts +33 -0
  48. package/src/generate-random-state.ts +16 -0
  49. package/src/git-client.ts +42 -0
  50. package/src/index.tsx +619 -338
  51. package/src/inspect.ts +39 -0
  52. package/src/kv.ts +116 -27
  53. package/src/logger.ts +8 -1
  54. package/src/open-in-browser.ts +3 -12
  55. package/src/package-manager.ts +50 -3
  56. package/src/pages.tsx +434 -207
  57. package/src/parse.ts +44 -5
  58. package/src/proxy.ts +66 -44
  59. package/src/publish.ts +407 -137
  60. package/src/sites.tsx +103 -28
  61. package/src/user.tsx +35 -26
  62. package/src/whoami.tsx +3 -2
  63. package/src/worker.ts +10 -1
  64. package/src/zones.ts +73 -0
  65. package/templates/new-worker-scheduled.js +17 -0
  66. package/templates/new-worker-scheduled.ts +32 -0
  67. package/templates/new-worker.ts +16 -1
  68. package/templates/no-op-worker.js +10 -0
  69. package/templates/static-asset-facade.js +2 -6
  70. package/wrangler-dist/cli.js +46122 -32396
  71. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  72. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  73. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  74. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  75. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  76. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  77. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  78. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  79. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  80. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  81. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  82. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  83. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  84. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  85. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  86. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  87. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  88. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  89. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  90. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  91. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  92. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  93. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  94. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  95. package/vendor/wrangler-mime/LICENSE +0 -21
  96. package/vendor/wrangler-mime/Mime.js +0 -97
  97. package/vendor/wrangler-mime/README.md +0 -187
  98. package/vendor/wrangler-mime/cli.js +0 -46
  99. package/vendor/wrangler-mime/index.js +0 -4
  100. package/vendor/wrangler-mime/lite.js +0 -4
  101. package/vendor/wrangler-mime/package.json +0 -52
  102. package/vendor/wrangler-mime/types/other.js +0 -1
  103. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/publish.ts CHANGED
@@ -4,18 +4,30 @@ import path from "node:path";
4
4
  import { URLSearchParams } from "node:url";
5
5
  import tmp from "tmp-promise";
6
6
  import { bundleWorker } from "./bundle";
7
- import { fetchResult } from "./cfetch";
7
+ import { printBundleSize } from "./bundle-reporter";
8
+ import { fetchListResult, fetchResult } from "./cfetch";
9
+ import { printBindings } from "./config";
8
10
  import { createWorkerUploadForm } from "./create-worker-upload-form";
11
+ import { confirm } from "./dialogs";
12
+ import { getMigrationsToUpload } from "./durable";
9
13
  import { logger } from "./logger";
14
+ import { ParseError } from "./parse";
10
15
  import { syncAssets } from "./sites";
16
+ import { getZoneForRoute } from "./zones";
11
17
  import type { Config } from "./config";
18
+ import type {
19
+ Route,
20
+ ZoneIdRoute,
21
+ ZoneNameRoute,
22
+ CustomDomainRoute,
23
+ } from "./config/environment";
12
24
  import type { Entry } from "./entry";
13
25
  import type { AssetPaths } from "./sites";
14
26
  import type { CfWorkerInit } from "./worker";
15
27
 
16
28
  type Props = {
17
29
  config: Config;
18
- accountId: string;
30
+ accountId: string | undefined;
19
31
  entry: Entry;
20
32
  rules: Config["rules"];
21
33
  name: string | undefined;
@@ -29,29 +41,224 @@ type Props = {
29
41
  jsxFactory: string | undefined;
30
42
  jsxFragment: string | undefined;
31
43
  tsconfig: string | undefined;
32
- experimentalPublic: boolean;
44
+ isWorkersSite: boolean;
33
45
  minify: boolean | undefined;
34
46
  nodeCompat: boolean | undefined;
35
47
  outDir: string | undefined;
36
48
  dryRun: boolean | undefined;
37
49
  };
38
50
 
51
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
52
+
39
53
  function sleep(ms: number) {
40
54
  return new Promise((resolve) => setTimeout(resolve, ms));
41
55
  }
42
56
 
57
+ function renderRoute(route: Route): string {
58
+ let result = "";
59
+ if (typeof route === "string") {
60
+ result = route;
61
+ } else {
62
+ result = route.pattern;
63
+ const isCustomDomain = Boolean(
64
+ "custom_domain" in route && route.custom_domain
65
+ );
66
+ if (isCustomDomain && "zone_id" in route) {
67
+ result += ` (custom domain - zone id: ${route.zone_id})`;
68
+ } else if (isCustomDomain && "zone_name" in route) {
69
+ result += ` (custom domain - zone name: ${route.zone_name})`;
70
+ } else if (isCustomDomain) {
71
+ result += ` (custom domain)`;
72
+ } else if ("zone_id" in route) {
73
+ result += ` (zone id: ${route.zone_id})`;
74
+ } else if ("zone_name" in route) {
75
+ result += ` (zone name: ${route.zone_name})`;
76
+ }
77
+ }
78
+ return result;
79
+ }
80
+
81
+ // this function takes a string with quotes in it
82
+ // (i.e. `hello "world", if that really is your name`)
83
+ // and peels out the first instance of a substring
84
+ // bounded by quotes (so, in the example above, `world`)
85
+ //
86
+ // this is useful because the /domains api will return
87
+ // which domains conflicted in an error message, bounded
88
+ // by a string, which we can use to provide helpful
89
+ // messages to a user
90
+ function getQuoteBoundedSubstring(content: string) {
91
+ const matches = content.split('"');
92
+ return matches[1] ?? "";
93
+ }
94
+
95
+ function isOriginConflictError(
96
+ e: unknown
97
+ ): e is { code: 100116; message: string; notes: Array<{ text: string }> } {
98
+ return (
99
+ typeof e === "object" &&
100
+ e !== null &&
101
+ (e as { code: number }).code === 100116
102
+ );
103
+ }
104
+
105
+ function isDNSConflictError(
106
+ e: unknown
107
+ ): e is { code: 100117; message: string; notes: Array<{ text: string }> } {
108
+ return (
109
+ typeof e === "object" &&
110
+ e !== null &&
111
+ (e as { code: number }).code === 100117
112
+ );
113
+ }
114
+
115
+ // empty error class to throw and then explicitly catch via `instanceof`
116
+ class CustomDomainOverrideRejected extends Error {}
117
+
118
+ // publishing to custom domains involves a few more steps than just updating
119
+ // the routing table, and thus the api implementing it is fairly defensive -
120
+ // it will error eagerly on conflicts against existing domains or existing
121
+ // managed DNS records
122
+ //
123
+ // however, you can pass params to override the errors. we start on the
124
+ // defensive path, and if one of these errors occur, we prompt the user
125
+ // for confirmation that they do indeed want to override the conflicts, and
126
+ // then retry the request with the right override added
127
+ //
128
+ // if a user does not confirm that they want to override, we skip publishing
129
+ // to these custom domains, but continue on through the rest of the
130
+ // publish stage
131
+ function publishCustomDomains(
132
+ workerUrl: string,
133
+ domains: Array<RouteObject>
134
+ ): Promise<string[]> {
135
+ const config = {
136
+ override_scope: true,
137
+ override_existing_origin: false,
138
+ override_existing_dns_record: false,
139
+ };
140
+ const origins = domains.map((domainRoute) => {
141
+ return {
142
+ hostname: domainRoute.pattern,
143
+ zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
144
+ zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
145
+ };
146
+ });
147
+
148
+ if (!process.stdout.isTTY) {
149
+ // running in non-interactive mode.
150
+ // existing origins / dns records are not indicative of errors,
151
+ // so we aggressively update rather than aggressively fail
152
+ config.override_existing_origin = true;
153
+ config.override_existing_dns_record = true;
154
+ }
155
+
156
+ // Mixing promise chains with async/await is funky, but it allows us to keep related
157
+ // logic synchronous-looking (i.e. prompting for confirmation and then re-requesting)
158
+ // while retaining the flexibility of promise chain fall-throughs. We can group error
159
+ // handling logic in dedicated catch calls, and all we have to do is re-throw an
160
+ // error and it will pass down to the next catch call
161
+ return fetchResult(`${workerUrl}/domains`, {
162
+ method: "PUT",
163
+ body: JSON.stringify({ ...config, origins }),
164
+ headers: {
165
+ "Content-Type": "application/json",
166
+ },
167
+ })
168
+ .catch(async (err) => {
169
+ if (isOriginConflictError(err)) {
170
+ const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
171
+ const shouldContinue = await confirm(
172
+ `Custom Domains already exist for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
173
+ );
174
+ if (!shouldContinue) {
175
+ throw new CustomDomainOverrideRejected();
176
+ }
177
+ config.override_existing_origin = true;
178
+ await fetchResult(`${workerUrl}/domains`, {
179
+ method: "PUT",
180
+ body: JSON.stringify({ ...config, origins }),
181
+ headers: {
182
+ "Content-Type": "application/json",
183
+ },
184
+ });
185
+ } else {
186
+ throw err;
187
+ }
188
+ })
189
+ .catch(async (err) => {
190
+ if (isDNSConflictError(err)) {
191
+ const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
192
+ const shouldContinue = await confirm(
193
+ `You already have conflicting DNS records for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
194
+ );
195
+ if (!shouldContinue) {
196
+ throw new CustomDomainOverrideRejected();
197
+ }
198
+ config.override_existing_dns_record = true;
199
+ await fetchResult(`${workerUrl}/domains`, {
200
+ method: "PUT",
201
+ body: JSON.stringify({ ...config, origins }),
202
+ headers: {
203
+ "Content-Type": "application/json",
204
+ },
205
+ });
206
+ } else {
207
+ throw err;
208
+ }
209
+ })
210
+ .then(() => domains.map((domain) => renderRoute(domain)))
211
+ .catch((err) => {
212
+ if (err instanceof CustomDomainOverrideRejected) {
213
+ return [
214
+ domains.length > 1
215
+ ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
216
+ : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
217
+ ];
218
+ }
219
+ throw err;
220
+ });
221
+ }
222
+
43
223
  export default async function publish(props: Props): Promise<void> {
44
224
  // TODO: warn if git/hg has uncommitted changes
45
225
  const { config, accountId } = props;
46
226
 
47
- assert(
48
- props.compatibilityDate || config.compatibility_date,
49
- "A compatibility_date is required when publishing. Add one to your wrangler.toml file, or pass it in your terminal as --compatibility-date. See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
50
- );
227
+ if (!(props.compatibilityDate || config.compatibility_date)) {
228
+ const compatibilityDateStr = `${new Date().getFullYear()}-${(
229
+ new Date().getMonth() + ""
230
+ ).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
231
+
232
+ throw new Error(`A compatibility_date is required when publishing. Add the following to your wrangler.toml file:.
233
+ \`\`\`
234
+ compatibility_date = "${compatibilityDateStr}"
235
+ \`\`\`
236
+ Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
237
+ See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
238
+ }
51
239
 
52
240
  const triggers = props.triggers || config.triggers?.crons;
53
241
  const routes =
54
242
  props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
243
+ const routesOnly: Array<Route> = [];
244
+ const customDomainsOnly: Array<RouteObject> = [];
245
+ for (const route of routes) {
246
+ if (typeof route !== "string" && route.custom_domain) {
247
+ if (route.pattern.includes("*")) {
248
+ throw new Error(
249
+ `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
250
+ );
251
+ }
252
+ if (route.pattern.includes("/")) {
253
+ throw new Error(
254
+ `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
255
+ );
256
+ }
257
+ customDomainsOnly.push(route);
258
+ } else {
259
+ routesOnly.push(route);
260
+ }
261
+ }
55
262
 
56
263
  // deployToWorkersDev defaults to true only if there aren't any routes defined
57
264
  const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
@@ -64,7 +271,7 @@ export default async function publish(props: Props): Promise<void> {
64
271
  const nodeCompat = props.nodeCompat ?? config.node_compat;
65
272
  if (nodeCompat) {
66
273
  logger.warn(
67
- "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
274
+ "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
68
275
  );
69
276
  }
70
277
 
@@ -76,7 +283,7 @@ export default async function publish(props: Props): Promise<void> {
76
283
 
77
284
  assert(
78
285
  !config.site || config.site.bucket,
79
- "A [site] definition requires a `bucket` field with a path to the site's public directory."
286
+ "A [site] definition requires a `bucket` field with a path to the site's assets directory."
80
287
  );
81
288
 
82
289
  if (props.outDir) {
@@ -95,7 +302,7 @@ export default async function publish(props: Props): Promise<void> {
95
302
  const envName = props.env ?? "production";
96
303
 
97
304
  const start = Date.now();
98
- const notProd = !props.legacyEnv && props.env;
305
+ const notProd = Boolean(!props.legacyEnv && props.env);
99
306
  const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
100
307
  const workerUrl = notProd
101
308
  ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
@@ -105,9 +312,13 @@ export default async function publish(props: Props): Promise<void> {
105
312
 
106
313
  const { format } = props.entry;
107
314
 
108
- if (props.experimentalPublic && format === "service-worker") {
315
+ if (
316
+ !props.isWorkersSite &&
317
+ Boolean(props.assetPaths) &&
318
+ format === "service-worker"
319
+ ) {
109
320
  throw new Error(
110
- "You cannot publish in the service-worker format with a public directory."
321
+ "You cannot use the service-worker format with an `assets` directory yet. For information on how to migrate to the module-worker format, see: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
111
322
  );
112
323
  }
113
324
 
@@ -133,7 +344,8 @@ export default async function publish(props: Props): Promise<void> {
133
344
  props.entry,
134
345
  typeof destination === "string" ? destination : destination.path,
135
346
  {
136
- serveAssetsFromWorker: props.experimentalPublic,
347
+ serveAssetsFromWorker:
348
+ !props.isWorkersSite && Boolean(props.assetPaths),
137
349
  jsxFactory,
138
350
  jsxFragment,
139
351
  rules: props.rules,
@@ -143,103 +355,19 @@ export default async function publish(props: Props): Promise<void> {
143
355
  }
144
356
  );
145
357
 
146
- // Some validation of durable objects + migrations
147
- if (config.durable_objects.bindings.length > 0) {
148
- // intrinsic [durable_objects] implies [migrations]
149
- const exportedDurableObjects = config.durable_objects.bindings.filter(
150
- (binding) => !binding.script_name
151
- );
152
- if (exportedDurableObjects.length > 0 && config.migrations.length === 0) {
153
- logger.warn(
154
- `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${exportedDurableObjects.map(
155
- (durable) => durable.class_name
156
- )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
157
- );
158
- }
159
- }
160
-
161
358
  const content = readFileSync(resolvedEntryPointPath, {
162
359
  encoding: "utf-8",
163
360
  });
164
361
 
165
- // if config.migrations
166
- let migrations;
167
- if (config.migrations.length > 0) {
168
- // get current migration tag
169
- type ScriptData = { id: string; migration_tag?: string };
170
- let script: ScriptData | undefined;
171
- if (!props.legacyEnv) {
172
- try {
173
- if (props.env) {
174
- const scriptData = await fetchResult<{
175
- script: ScriptData;
176
- }>(
177
- `/accounts/${accountId}/workers/services/${scriptName}/environments/${props.env}`
178
- );
179
- script = scriptData.script;
180
- } else {
181
- const scriptData = await fetchResult<{
182
- default_environment: {
183
- script: ScriptData;
184
- };
185
- }>(`/accounts/${accountId}/workers/services/${scriptName}`);
186
- script = scriptData.default_environment.script;
187
- }
188
- } catch (err) {
189
- if (
190
- ![
191
- 10090, // corresponds to workers.api.error.service_not_found, so the script wasn't previously published at all
192
- 10092, // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
193
- ].includes((err as { code: number }).code)
194
- ) {
195
- throw err;
196
- }
197
- // else it's a 404, no script found, and we can proceed
198
- }
199
- } else {
200
- const scripts = await fetchResult<ScriptData[]>(
201
- `/accounts/${accountId}/workers/scripts`
202
- );
203
- script = scripts.find(({ id }) => id === scriptName);
204
- }
205
-
206
- if (script?.migration_tag) {
207
- // was already published once
208
- const scriptMigrationTag = script.migration_tag;
209
- const foundIndex = config.migrations.findIndex(
210
- (migration) => migration.tag === scriptMigrationTag
211
- );
212
- if (foundIndex === -1) {
213
- logger.warn(
214
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
215
- );
216
- migrations = {
217
- old_tag: script.migration_tag,
218
- new_tag: config.migrations[config.migrations.length - 1].tag,
219
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
220
- };
221
- } else {
222
- if (foundIndex !== config.migrations.length - 1) {
223
- // there are new migrations to send up
224
- migrations = {
225
- old_tag: script.migration_tag,
226
- new_tag: config.migrations[config.migrations.length - 1].tag,
227
- steps: config.migrations
228
- .slice(foundIndex + 1)
229
- .map(({ tag: _tag, ...rest }) => rest),
230
- };
231
- }
232
- // else, we're up to date, no migrations to send
233
- }
234
- } else {
235
- // first time publishing durable objects to this script,
236
- // so we send all the migrations
237
- migrations = {
238
- new_tag: config.migrations[config.migrations.length - 1].tag,
239
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
240
- };
241
- }
242
- }
362
+ // durable object migrations
363
+ const migrations = !props.dryRun
364
+ ? await getMigrationsToUpload(scriptName, {
365
+ accountId,
366
+ config,
367
+ legacyEnv: props.legacyEnv,
368
+ env: props.env,
369
+ })
370
+ : undefined;
243
371
 
244
372
  const assets = await syncAssets(
245
373
  accountId,
@@ -271,6 +399,7 @@ export default async function publish(props: Props): Promise<void> {
271
399
  data_blobs: config.data_blobs,
272
400
  durable_objects: config.durable_objects,
273
401
  r2_buckets: config.r2_buckets,
402
+ services: config.services,
274
403
  unsafe: config.unsafe?.bindings,
275
404
  };
276
405
 
@@ -298,6 +427,13 @@ export default async function publish(props: Props): Promise<void> {
298
427
  usage_model: config.usage_model,
299
428
  };
300
429
 
430
+ const withoutStaticAssets = {
431
+ ...bindings,
432
+ kv_namespaces: config.kv_namespaces,
433
+ text_blobs: config.text_blobs,
434
+ };
435
+ printBindings(withoutStaticAssets);
436
+
301
437
  if (!props.dryRun) {
302
438
  // Upload the script so it has time to propagate.
303
439
  // We can also now tell whether available_on_subdomain is set
@@ -308,10 +444,19 @@ export default async function publish(props: Props): Promise<void> {
308
444
  method: "PUT",
309
445
  body: createWorkerUploadForm(worker),
310
446
  },
311
- new URLSearchParams({ include_subdomain_availability: "true" })
447
+ new URLSearchParams({
448
+ include_subdomain_availability: "true",
449
+ // pass excludeScript so the whole body of the
450
+ // script doesn't get included in the response
451
+ excludeScript: "true",
452
+ })
312
453
  )
313
454
  ).available_on_subdomain;
314
455
  }
456
+ void printBundleSize(
457
+ { name: path.basename(resolvedEntryPointPath), content: content },
458
+ modules
459
+ );
315
460
  } finally {
316
461
  if (typeof destination !== "string") {
317
462
  // this means we're using a temp dir,
@@ -324,6 +469,7 @@ export default async function publish(props: Props): Promise<void> {
324
469
  logger.log(`--dry-run: exiting now.`);
325
470
  return;
326
471
  }
472
+ assert(accountId, "Missing accountId");
327
473
 
328
474
  const uploadMs = Date.now() - start;
329
475
  const deployments: Promise<string[]>[] = [];
@@ -374,43 +520,25 @@ export default async function publish(props: Props): Promise<void> {
374
520
  logger.log("Uploaded", workerName, formatTime(uploadMs));
375
521
 
376
522
  // Update routing table for the script.
377
- if (routes.length > 0) {
523
+ if (routesOnly.length > 0) {
378
524
  deployments.push(
379
- fetchResult(`${workerUrl}/routes`, {
380
- // Note: PUT will delete previous routes on this script.
381
- method: "PUT",
382
- body: JSON.stringify(
383
- routes.map((route) =>
384
- typeof route !== "object" ? { pattern: route } : route
385
- )
386
- ),
387
- headers: {
388
- "Content-Type": "application/json",
389
- },
390
- }).then(() => {
391
- if (routes.length > 10) {
392
- return routes
525
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
526
+ if (routesOnly.length > 10) {
527
+ return routesOnly
393
528
  .slice(0, 9)
394
- .map((route) =>
395
- typeof route === "string"
396
- ? route
397
- : "zone_id" in route
398
- ? `${route.pattern} (zone id: ${route.zone_id})`
399
- : `${route.pattern} (zone name: ${route.zone_name})`
400
- )
401
- .concat([`...and ${routes.length - 10} more routes`]);
529
+ .map((route) => renderRoute(route))
530
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
402
531
  }
403
- return routes.map((route) =>
404
- typeof route === "string"
405
- ? route
406
- : "zone_id" in route
407
- ? `${route.pattern} (zone id: ${route.zone_id})`
408
- : `${route.pattern} (zone name: ${route.zone_name})`
409
- );
532
+ return routesOnly.map((route) => renderRoute(route));
410
533
  })
411
534
  );
412
535
  }
413
536
 
537
+ // Update custom domains for the script
538
+ if (customDomainsOnly.length > 0) {
539
+ deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
540
+ }
541
+
414
542
  // Configure any schedules for the script.
415
543
  // TODO: rename this to `schedules`?
416
544
  if (triggers && triggers.length) {
@@ -467,3 +595,145 @@ async function getSubdomain(accountId: string): Promise<string> {
467
595
  }
468
596
  }
469
597
  }
598
+
599
+ /**
600
+ * Associate the newly deployed Worker with the given routes.
601
+ */
602
+ async function publishRoutes(
603
+ routes: Route[],
604
+ {
605
+ workerUrl,
606
+ scriptName,
607
+ notProd,
608
+ }: { workerUrl: string; scriptName: string; notProd: boolean }
609
+ ): Promise<string[]> {
610
+ try {
611
+ return await fetchResult(`${workerUrl}/routes`, {
612
+ // Note: PUT will delete previous routes on this script.
613
+ method: "PUT",
614
+ body: JSON.stringify(
615
+ routes.map((route) =>
616
+ typeof route !== "object" ? { pattern: route } : route
617
+ )
618
+ ),
619
+ headers: {
620
+ "Content-Type": "application/json",
621
+ },
622
+ });
623
+ } catch (e) {
624
+ if (isAuthenticationError(e)) {
625
+ // An authentication error is probably due to a known issue,
626
+ // where the user is logged in via an API token that does not have "All Zones".
627
+ return await publishRoutesFallback(routes, { scriptName, notProd });
628
+ } else {
629
+ throw e;
630
+ }
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Try updating routes for the Worker using a less optimal zone-based API.
636
+ *
637
+ * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
638
+ */
639
+ async function publishRoutesFallback(
640
+ routes: Route[],
641
+ { scriptName, notProd }: { scriptName: string; notProd: boolean }
642
+ ) {
643
+ if (notProd) {
644
+ throw new Error(
645
+ "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
646
+ "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
647
+ );
648
+ }
649
+ logger.warn(
650
+ "The current authentication token does not have 'All Zones' permissions.\n" +
651
+ "Falling back to using the zone-based API endpoint to update each route individually.\n" +
652
+ "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
653
+ "Existing routes for this Worker in such zones will not be deleted."
654
+ );
655
+
656
+ const deployedRoutes: string[] = [];
657
+
658
+ // Collect the routes (and their zones) that will be deployed.
659
+ const activeZones = new Map<string, string>();
660
+ const routesToDeploy = new Map<string, string>();
661
+ for (const route of routes) {
662
+ const zone = await getZoneForRoute(route);
663
+ if (zone) {
664
+ activeZones.set(zone.id, zone.host);
665
+ routesToDeploy.set(
666
+ typeof route === "string" ? route : route.pattern,
667
+ zone.id
668
+ );
669
+ }
670
+ }
671
+
672
+ // Collect the routes that are already deployed.
673
+ const allRoutes = new Map<string, string>();
674
+ const alreadyDeployedRoutes = new Set<string>();
675
+ for (const [zone, host] of activeZones) {
676
+ try {
677
+ for (const { pattern, script } of await fetchListResult<{
678
+ pattern: string;
679
+ script: string;
680
+ }>(`/zones/${zone}/workers/routes`)) {
681
+ allRoutes.set(pattern, script);
682
+ if (script === scriptName) {
683
+ alreadyDeployedRoutes.add(pattern);
684
+ }
685
+ }
686
+ } catch (e) {
687
+ if (isAuthenticationError(e)) {
688
+ e.notes.push({
689
+ text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
690
+ });
691
+ }
692
+ throw e;
693
+ }
694
+ }
695
+
696
+ // Deploy each route that is not already deployed.
697
+ for (const [routePattern, zoneId] of routesToDeploy.entries()) {
698
+ if (allRoutes.has(routePattern)) {
699
+ const knownScript = allRoutes.get(routePattern);
700
+ if (knownScript === scriptName) {
701
+ // This route is already associated with this worker, so no need to hit the API.
702
+ alreadyDeployedRoutes.delete(routePattern);
703
+ continue;
704
+ } else {
705
+ throw new Error(
706
+ `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
707
+ );
708
+ }
709
+ }
710
+
711
+ const { pattern } = await fetchResult(`/zones/${zoneId}/workers/routes`, {
712
+ method: "POST",
713
+ body: JSON.stringify({
714
+ pattern: routePattern,
715
+ script: scriptName,
716
+ }),
717
+ headers: {
718
+ "Content-Type": "application/json",
719
+ },
720
+ });
721
+
722
+ deployedRoutes.push(pattern);
723
+ }
724
+
725
+ if (alreadyDeployedRoutes.size) {
726
+ logger.warn(
727
+ "Previously deployed routes:\n" +
728
+ "The following routes were already associated with this worker, and have not been deleted:\n" +
729
+ [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
730
+ "If these routes are not wanted then you can remove them in the dashboard."
731
+ );
732
+ }
733
+
734
+ return deployedRoutes;
735
+ }
736
+
737
+ function isAuthenticationError(e: unknown): e is ParseError {
738
+ return e instanceof ParseError && (e as { code?: number }).code === 10000;
739
+ }