wrangler 0.0.0-e2a26a0 → 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 (157) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +49 -5
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4886 -0
  6. package/package.json +54 -27
  7. package/pages/functions/buildPlugin.ts +105 -0
  8. package/pages/functions/buildWorker.ts +93 -4
  9. package/pages/functions/filepath-routing.test.ts +223 -36
  10. package/pages/functions/filepath-routing.ts +78 -120
  11. package/pages/functions/routes.ts +13 -17
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +24 -17
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3548 -0
  16. package/src/__tests__/dev.test.tsx +1049 -65
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  19. package/src/__tests__/helpers/mock-account-id.ts +26 -8
  20. package/src/__tests__/helpers/mock-bin.ts +4 -1
  21. package/src/__tests__/helpers/mock-cfetch.ts +12 -8
  22. package/src/__tests__/helpers/mock-console.ts +49 -8
  23. package/src/__tests__/helpers/mock-dialogs.ts +99 -11
  24. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  25. package/src/__tests__/helpers/mock-istty.ts +27 -0
  26. package/src/__tests__/helpers/mock-kv.ts +9 -16
  27. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  28. package/src/__tests__/helpers/mock-process.ts +24 -0
  29. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  30. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  31. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  32. package/src/__tests__/helpers/run-wrangler.ts +5 -3
  33. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  34. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  35. package/src/__tests__/https-options.test.ts +130 -0
  36. package/src/__tests__/index.test.ts +150 -435
  37. package/src/__tests__/init.test.ts +1992 -0
  38. package/src/__tests__/jest.setup.ts +75 -5
  39. package/src/__tests__/kv.test.ts +634 -253
  40. package/src/__tests__/logger.test.ts +141 -0
  41. package/src/__tests__/package-manager.test.ts +156 -9
  42. package/src/__tests__/pages.test.ts +754 -0
  43. package/src/__tests__/parse.test.ts +330 -0
  44. package/src/__tests__/publish.test.ts +5895 -961
  45. package/src/__tests__/r2.test.ts +233 -0
  46. package/src/__tests__/route.test.ts +45 -0
  47. package/src/__tests__/secret.test.ts +362 -91
  48. package/src/__tests__/tail.test.ts +690 -0
  49. package/src/__tests__/user.test.ts +132 -0
  50. package/src/__tests__/whoami.test.tsx +60 -7
  51. package/src/abort.d.ts +3 -0
  52. package/src/bundle-reporter.tsx +29 -0
  53. package/src/bundle.ts +204 -0
  54. package/src/cfetch/index.ts +27 -8
  55. package/src/cfetch/internal.ts +75 -34
  56. package/src/cli.ts +6 -2
  57. package/src/config/README.md +107 -0
  58. package/src/config/config.ts +243 -0
  59. package/src/config/diagnostics.ts +80 -0
  60. package/src/config/environment.ts +420 -0
  61. package/src/config/index.ts +225 -0
  62. package/src/config/validation-helpers.ts +584 -0
  63. package/src/config/validation.ts +1580 -0
  64. package/src/config-cache.ts +45 -0
  65. package/src/create-worker-preview.ts +185 -0
  66. package/src/create-worker-upload-form.ts +254 -0
  67. package/src/dev/dev-vars.ts +36 -0
  68. package/src/dev/dev.tsx +399 -0
  69. package/src/dev/local.tsx +321 -0
  70. package/src/dev/remote.tsx +249 -0
  71. package/src/dev/use-esbuild.ts +112 -0
  72. package/src/dialogs.tsx +64 -6
  73. package/src/durable.ts +102 -0
  74. package/src/entry.ts +328 -0
  75. package/src/environment-variables.ts +35 -0
  76. package/src/errors.ts +11 -0
  77. package/src/generate-auth-url.ts +33 -0
  78. package/src/generate-random-state.ts +16 -0
  79. package/src/git-client.ts +42 -0
  80. package/src/https-options.ts +123 -0
  81. package/src/index.tsx +1804 -1009
  82. package/src/inspect.ts +80 -14
  83. package/src/intl-polyfill.d.ts +139 -0
  84. package/src/{kv.tsx → kv.ts} +193 -69
  85. package/src/logger.ts +73 -0
  86. package/src/miniflare-cli/README.md +30 -0
  87. package/src/miniflare-cli/enum-keys.ts +17 -0
  88. package/src/miniflare-cli/index.ts +41 -0
  89. package/src/miniflare-cli/request-context.ts +40 -0
  90. package/src/module-collection.ts +226 -31
  91. package/src/open-in-browser.ts +17 -0
  92. package/src/package-manager.ts +79 -25
  93. package/src/pages.tsx +1131 -84
  94. package/src/parse.ts +222 -0
  95. package/src/proxy.ts +176 -70
  96. package/src/publish.ts +637 -308
  97. package/src/r2.ts +50 -0
  98. package/src/selfsigned.d.ts +29 -0
  99. package/src/sites.tsx +185 -57
  100. package/src/tail/filters.ts +279 -0
  101. package/src/tail/index.ts +299 -0
  102. package/src/tail/printing.ts +67 -0
  103. package/src/update-check.ts +19 -0
  104. package/src/user.tsx +349 -166
  105. package/src/whoami.tsx +5 -3
  106. package/src/{api/worker.ts → worker.ts} +65 -39
  107. package/src/zones.ts +73 -0
  108. package/templates/gitignore +171 -0
  109. package/templates/new-worker-scheduled.js +17 -0
  110. package/templates/new-worker-scheduled.ts +32 -0
  111. package/templates/new-worker.js +1 -1
  112. package/templates/new-worker.ts +17 -2
  113. package/templates/no-op-worker.js +10 -0
  114. package/templates/static-asset-facade.js +3 -7
  115. package/templates/tsconfig.json +105 -0
  116. package/wrangler-dist/cli.js +77463 -75999
  117. package/src/__tests__/helpers/mock-user.ts +0 -27
  118. package/src/__tests__/logout.test.ts +0 -50
  119. package/src/api/form_data.ts +0 -134
  120. package/src/api/preview.ts +0 -128
  121. package/src/config.ts +0 -641
  122. package/src/dev.tsx +0 -834
  123. package/src/tail.tsx +0 -73
  124. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  125. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  126. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  127. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  128. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  129. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  130. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  131. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  132. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  133. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  134. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  135. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  136. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  137. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  138. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  139. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  140. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  141. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  142. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  143. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  144. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  145. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  146. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  147. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  148. package/vendor/wrangler-mime/LICENSE +0 -21
  149. package/vendor/wrangler-mime/Mime.js +0 -97
  150. package/vendor/wrangler-mime/README.md +0 -187
  151. package/vendor/wrangler-mime/cli.js +0 -46
  152. package/vendor/wrangler-mime/index.js +0 -4
  153. package/vendor/wrangler-mime/lite.js +0 -4
  154. package/vendor/wrangler-mime/package.json +0 -52
  155. package/vendor/wrangler-mime/types/other.js +0 -1
  156. package/vendor/wrangler-mime/types/standard.js +0 -1
  157. package/wrangler-dist/cli.js.map +0 -7
package/src/publish.ts CHANGED
@@ -1,410 +1,739 @@
1
1
  import assert from "node:assert";
2
- import { readFile } from "node:fs/promises";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { URLSearchParams } from "node:url";
5
- import * as esbuild from "esbuild";
6
- import { execaCommand } from "execa";
7
5
  import tmp from "tmp-promise";
8
- import { toFormData } from "./api/form_data";
9
- import { fetchResult } from "./cfetch";
10
- import makeModuleCollector from "./module-collection";
6
+ import { bundleWorker } from "./bundle";
7
+ import { printBundleSize } from "./bundle-reporter";
8
+ import { fetchListResult, fetchResult } from "./cfetch";
9
+ import { printBindings } from "./config";
10
+ import { createWorkerUploadForm } from "./create-worker-upload-form";
11
+ import { confirm } from "./dialogs";
12
+ import { getMigrationsToUpload } from "./durable";
13
+ import { logger } from "./logger";
14
+ import { ParseError } from "./parse";
11
15
  import { syncAssets } from "./sites";
12
- import type { CfWorkerInit } from "./api/worker";
16
+ import { getZoneForRoute } from "./zones";
13
17
  import type { Config } from "./config";
18
+ import type {
19
+ Route,
20
+ ZoneIdRoute,
21
+ ZoneNameRoute,
22
+ CustomDomainRoute,
23
+ } from "./config/environment";
24
+ import type { Entry } from "./entry";
14
25
  import type { AssetPaths } from "./sites";
15
- import type { Metafile } from "esbuild";
16
-
17
- type CfScriptFormat = undefined | "modules" | "service-worker";
26
+ import type { CfWorkerInit } from "./worker";
18
27
 
19
28
  type Props = {
20
29
  config: Config;
21
- format: CfScriptFormat | undefined;
22
- script: string | undefined;
30
+ accountId: string | undefined;
31
+ entry: Entry;
32
+ rules: Config["rules"];
23
33
  name: string | undefined;
24
34
  env: string | undefined;
25
35
  compatibilityDate: string | undefined;
26
36
  compatibilityFlags: string[] | undefined;
27
37
  assetPaths: AssetPaths | undefined;
28
- triggers: (string | number)[] | undefined;
29
- routes: (string | number)[] | undefined;
38
+ triggers: string[] | undefined;
39
+ routes: string[] | undefined;
30
40
  legacyEnv: boolean | undefined;
31
- jsxFactory: undefined | string;
32
- jsxFragment: undefined | string;
33
- experimentalPublic: boolean;
41
+ jsxFactory: string | undefined;
42
+ jsxFragment: string | undefined;
43
+ tsconfig: string | undefined;
44
+ isWorkersSite: boolean;
45
+ minify: boolean | undefined;
46
+ nodeCompat: boolean | undefined;
47
+ outDir: string | undefined;
48
+ dryRun: boolean | undefined;
34
49
  };
35
50
 
51
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
52
+
36
53
  function sleep(ms: number) {
37
54
  return new Promise((resolve) => setTimeout(resolve, ms));
38
55
  }
39
56
 
40
- export default async function publish(props: Props): Promise<void> {
41
- if (props.experimentalPublic && props.format === "service-worker") {
42
- // TODO: check config too
43
- throw new Error(
44
- "You cannot publish in the service worker format with a public directory."
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
45
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
+ }
46
77
  }
47
- // TODO: warn if git/hg has uncommitted changes
48
- const { config } = props;
49
- const {
50
- account_id: accountId,
51
- build,
52
- // @ts-expect-error hidden
53
- __path__,
54
- } = config;
78
+ return result;
79
+ }
55
80
 
56
- const envRootObj =
57
- props.env && config.env ? config.env[props.env] || {} : config;
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
+ }
58
94
 
59
- assert(
60
- envRootObj.compatibility_date || props.compatibilityDate,
61
- "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."
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
62
102
  );
103
+ }
63
104
 
64
- if (accountId === undefined) {
65
- throw new Error("No account_id provided.");
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
+
223
+ export default async function publish(props: Props): Promise<void> {
224
+ // TODO: warn if git/hg has uncommitted changes
225
+ const { config, accountId } = props;
226
+
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.`);
66
238
  }
67
239
 
68
240
  const triggers = props.triggers || config.triggers?.crons;
69
- const routes = props.routes || config.routes;
241
+ const routes =
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
+ }
262
+
263
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
264
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
70
265
 
71
266
  const jsxFactory = props.jsxFactory || config.jsx_factory;
72
267
  const jsxFragment = props.jsxFragment || config.jsx_fragment;
73
268
 
74
- assert(config.account_id, "missing account id");
269
+ const minify = props.minify ?? config.minify;
270
+
271
+ const nodeCompat = props.nodeCompat ?? config.node_compat;
272
+ if (nodeCompat) {
273
+ logger.warn(
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."
275
+ );
276
+ }
75
277
 
76
- let scriptName = props.name || config.name;
278
+ const scriptName = props.name;
77
279
  assert(
78
280
  scriptName,
79
281
  'You need to provide a name when publishing a worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`'
80
282
  );
81
283
 
82
- if (config.site?.["entry-point"]) {
83
- console.warn(
84
- "Deprecation notice: The `site.entry-point` config field is no longer used.\n" +
85
- "The entry-point should be specified via the command line (e.g. `wrangler publish path/to/script`) or the `build.upload.main` config field.\n" +
86
- "Please remove the `site.entry-point` field from the `wrangler.toml` file."
87
- );
88
- }
89
-
90
284
  assert(
91
285
  !config.site || config.site.bucket,
92
- "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."
93
287
  );
94
288
 
95
- let file: string;
96
- if (props.script) {
97
- // If the script name comes from the command line it is relative to the current working directory.
98
- file = path.resolve(props.script);
99
- } else {
100
- // If the script name comes from the config, then it is relative to the wrangler.toml file.
101
- if (build?.upload?.main === undefined) {
102
- throw new Error(
103
- "Missing entry-point: The entry-point should be specified via the command line (e.g. `wrangler publish path/to/script`) or the `build.upload.main` config field."
104
- );
105
- }
106
- file = path.resolve(path.dirname(__path__), build.upload.main);
289
+ if (props.outDir) {
290
+ // we're using a custom output directory,
291
+ // so let's first ensure it exists
292
+ mkdirSync(props.outDir, { recursive: true });
293
+ // add a README
294
+ const readmePath = path.join(props.outDir, "README.md");
295
+ writeFileSync(
296
+ readmePath,
297
+ `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
298
+ );
107
299
  }
108
300
 
109
- if (props.legacyEnv) {
110
- scriptName += props.env ? `-${props.env}` : "";
111
- }
301
+ const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
112
302
  const envName = props.env ?? "production";
113
303
 
114
- const destination = await tmp.dir({ unsafeCleanup: true });
115
- if (props.config.build?.command) {
116
- // TODO: add a deprecation message here?
117
- console.log("running:", props.config.build.command);
118
- await execaCommand(props.config.build.command, {
119
- shell: true,
120
- stdout: "inherit",
121
- stderr: "inherit",
122
- ...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
123
- });
124
- }
125
-
126
- const moduleCollector = makeModuleCollector();
127
- const result = await esbuild.build({
128
- ...(props.experimentalPublic
129
- ? {
130
- stdin: {
131
- contents: (
132
- await readFile(
133
- path.join(__dirname, "../templates/static-asset-facade.js"),
134
- "utf8"
135
- )
136
- ).replace("__ENTRY_POINT__", file),
137
- sourcefile: "static-asset-facade.js",
138
- resolveDir: path.dirname(file),
139
- },
140
- nodePaths: [path.join(__dirname, "../vendor")],
141
- }
142
- : { entryPoints: [file] }),
143
- bundle: true,
144
- outdir: destination.path,
145
- external: ["__STATIC_CONTENT_MANIFEST"],
146
- format: "esm",
147
- sourcemap: true,
148
- metafile: true,
149
- conditions: ["worker", "browser"],
150
- loader: {
151
- ".js": "jsx",
152
- ".html": "text",
153
- ".pem": "text",
154
- ".txt": "text",
155
- },
156
- plugins: [moduleCollector.plugin],
157
- ...(jsxFactory && { jsxFactory }),
158
- ...(jsxFragment && { jsxFragment }),
159
- });
304
+ const start = Date.now();
305
+ const notProd = Boolean(!props.legacyEnv && props.env);
306
+ const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
307
+ const workerUrl = notProd
308
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
309
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`;
160
310
 
161
- // result.metafile is defined because of the `metafile: true` option above.
162
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
163
- const metafile = result.metafile!;
164
- const entryPoints = Object.entries(metafile.outputs).filter(
165
- ([_path, output]) => output.entryPoint !== undefined
166
- );
167
- assert(
168
- entryPoints.length > 0,
169
- `Cannot find entry-point "${file}" in generated bundle.` +
170
- listEntryPoints(entryPoints)
171
- );
172
- assert(
173
- entryPoints.length < 2,
174
- "More than one entry-point found for generated bundle." +
175
- listEntryPoints(entryPoints)
176
- );
177
- const entryPointExports = entryPoints[0][1].exports;
178
- const resolvedEntryPointPath = entryPoints[0][0];
179
- const { format } = props;
180
- const bundle = {
181
- type: entryPointExports.length > 0 ? "esm" : "commonjs",
182
- exports: entryPointExports,
183
- };
311
+ let available_on_subdomain; // we'll set this later
184
312
 
185
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
186
- // That way we'll be able to accurately tell if this is a service worker or not.
313
+ const { format } = props.entry;
187
314
 
188
- if (format === "modules" && bundle.type === "commonjs") {
189
- console.error("⎔ Cannot use modules with a commonjs bundle.");
190
- // TODO: a much better error message here, with what to do next
191
- return;
192
- }
193
- if (format === "service-worker" && bundle.type !== "esm") {
194
- console.error("⎔ Cannot use service-worker with a esm bundle.");
195
- // TODO: a much better error message here, with what to do next
196
- return;
315
+ if (
316
+ !props.isWorkersSite &&
317
+ Boolean(props.assetPaths) &&
318
+ format === "service-worker"
319
+ ) {
320
+ throw new Error(
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/"
322
+ );
197
323
  }
198
324
 
199
- let content = await readFile(resolvedEntryPointPath, { encoding: "utf-8" });
200
- await destination.cleanup();
325
+ if (config.wasm_modules && format === "modules") {
326
+ throw new Error(
327
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
328
+ );
329
+ }
201
330
 
202
- // if config.migrations
203
- // get current migration tag
204
- let migrations;
205
- if (config.migrations !== undefined) {
206
- const scripts = await fetchResult<{ id: string; migration_tag: string }[]>(
207
- `/accounts/${accountId}/workers/scripts`
331
+ if (config.text_blobs && format === "modules") {
332
+ throw new Error(
333
+ "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
208
334
  );
209
- const script = scripts.find(({ id }) => id === scriptName);
210
- if (script?.migration_tag) {
211
- // was already published once
212
- const foundIndex = config.migrations.findIndex(
213
- (migration) => migration.tag === script.migration_tag
214
- );
215
- if (foundIndex === -1) {
216
- console.warn(
217
- `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...`
218
- );
219
- migrations = {
220
- old_tag: script.migration_tag,
221
- new_tag: config.migrations[config.migrations.length - 1].tag,
222
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
223
- };
224
- } else {
225
- migrations = {
226
- old_tag: script.migration_tag,
227
- new_tag: config.migrations[config.migrations.length - 1].tag,
228
- steps: config.migrations
229
- .slice(foundIndex + 1)
230
- .map(({ tag: _tag, ...rest }) => rest),
231
- };
232
- }
233
- } else {
234
- migrations = {
235
- new_tag: config.migrations[config.migrations.length - 1].tag,
236
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
237
- };
238
- }
239
335
  }
240
336
 
241
- const assets = await syncAssets(
242
- accountId,
243
- scriptName,
244
- props.assetPaths,
245
- false,
246
- props.env
247
- );
337
+ if (config.data_blobs && format === "modules") {
338
+ throw new Error(
339
+ "You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
340
+ );
341
+ }
342
+ try {
343
+ const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
344
+ props.entry,
345
+ typeof destination === "string" ? destination : destination.path,
346
+ {
347
+ serveAssetsFromWorker:
348
+ !props.isWorkersSite && Boolean(props.assetPaths),
349
+ jsxFactory,
350
+ jsxFragment,
351
+ rules: props.rules,
352
+ tsconfig: props.tsconfig ?? config.tsconfig,
353
+ minify,
354
+ nodeCompat,
355
+ }
356
+ );
248
357
 
249
- const bindings: CfWorkerInit["bindings"] = {
250
- kv_namespaces: (envRootObj.kv_namespaces || []).concat(
251
- assets.namespace
252
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
253
- : []
254
- ),
255
- vars: envRootObj.vars,
256
- durable_objects: envRootObj.durable_objects,
257
- services: envRootObj.experimental_services,
258
- };
358
+ const content = readFileSync(resolvedEntryPointPath, {
359
+ encoding: "utf-8",
360
+ });
259
361
 
260
- const workerType = bundle.type === "esm" ? "esm" : "commonjs";
261
- if (workerType !== "esm" && assets.manifest) {
262
- content = `const __STATIC_CONTENT_MANIFEST = ${JSON.stringify(
263
- assets.manifest
264
- )};\n${content}`;
265
- }
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;
371
+
372
+ const assets = await syncAssets(
373
+ accountId,
374
+ // When we're using the newer service environments, we wouldn't
375
+ // have added the env name on to the script name. However, we must
376
+ // include it in the kv namespace name regardless (since there's no
377
+ // concept of service environments for kv namespaces yet).
378
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
379
+ props.assetPaths,
380
+ false,
381
+ props.dryRun
382
+ );
266
383
 
267
- const worker: CfWorkerInit = {
268
- name: scriptName,
269
- main: {
270
- name: path.basename(resolvedEntryPointPath),
271
- content: content,
272
- type: workerType,
273
- },
274
- bindings,
275
- ...(migrations && { migrations }),
276
- modules: moduleCollector.modules.concat(
277
- assets.manifest && workerType === "esm"
278
- ? {
279
- name: "__STATIC_CONTENT_MANIFEST",
280
- content: JSON.stringify(assets.manifest),
281
- type: "text",
282
- }
283
- : []
284
- ),
285
- compatibility_date: config.compatibility_date,
286
- compatibility_flags: config.compatibility_flags,
287
- usage_model: config.usage_model,
288
- };
384
+ const bindings: CfWorkerInit["bindings"] = {
385
+ kv_namespaces: (config.kv_namespaces || []).concat(
386
+ assets.namespace
387
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
388
+ : []
389
+ ),
390
+ vars: config.vars,
391
+ wasm_modules: config.wasm_modules,
392
+ text_blobs: {
393
+ ...config.text_blobs,
394
+ ...(assets.manifest &&
395
+ format === "service-worker" && {
396
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
397
+ }),
398
+ },
399
+ data_blobs: config.data_blobs,
400
+ durable_objects: config.durable_objects,
401
+ r2_buckets: config.r2_buckets,
402
+ services: config.services,
403
+ unsafe: config.unsafe?.bindings,
404
+ };
405
+
406
+ if (assets.manifest) {
407
+ modules.push({
408
+ name: "__STATIC_CONTENT_MANIFEST",
409
+ content: JSON.stringify(assets.manifest),
410
+ type: "text",
411
+ });
412
+ }
289
413
 
290
- const start = Date.now();
291
- function formatTime(duration: number) {
292
- return `(${(duration / 1000).toFixed(2)} sec)`;
414
+ const worker: CfWorkerInit = {
415
+ name: scriptName,
416
+ main: {
417
+ name: path.basename(resolvedEntryPointPath),
418
+ content: content,
419
+ type: bundleType,
420
+ },
421
+ bindings,
422
+ migrations,
423
+ modules,
424
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
425
+ compatibility_flags:
426
+ props.compatibilityFlags ?? config.compatibility_flags,
427
+ usage_model: config.usage_model,
428
+ };
429
+
430
+ const withoutStaticAssets = {
431
+ ...bindings,
432
+ kv_namespaces: config.kv_namespaces,
433
+ text_blobs: config.text_blobs,
434
+ };
435
+ printBindings(withoutStaticAssets);
436
+
437
+ if (!props.dryRun) {
438
+ // Upload the script so it has time to propagate.
439
+ // We can also now tell whether available_on_subdomain is set
440
+ available_on_subdomain = (
441
+ await fetchResult<{ available_on_subdomain: boolean }>(
442
+ workerUrl,
443
+ {
444
+ method: "PUT",
445
+ body: createWorkerUploadForm(worker),
446
+ },
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
+ })
453
+ )
454
+ ).available_on_subdomain;
455
+ }
456
+ void printBundleSize(
457
+ { name: path.basename(resolvedEntryPointPath), content: content },
458
+ modules
459
+ );
460
+ } finally {
461
+ if (typeof destination !== "string") {
462
+ // this means we're using a temp dir,
463
+ // so let's clean up before we proceed
464
+ await destination.cleanup();
465
+ }
293
466
  }
294
467
 
295
- const notProd = !props.legacyEnv && props.env;
296
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
297
- const workerUrl = notProd
298
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
299
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
300
-
301
- // Upload the script so it has time to propagate.
302
- const { available_on_subdomain } = await fetchResult(
303
- workerUrl,
304
- {
305
- method: "PUT",
306
- body: toFormData(worker),
307
- },
308
- new URLSearchParams({ available_on_subdomains: "true" })
309
- );
468
+ if (props.dryRun) {
469
+ logger.log(`--dry-run: exiting now.`);
470
+ return;
471
+ }
472
+ assert(accountId, "Missing accountId");
310
473
 
311
474
  const uploadMs = Date.now() - start;
312
- console.log("Uploaded", workerName, formatTime(uploadMs));
313
475
  const deployments: Promise<string[]>[] = [];
314
476
 
315
- const userSubdomain = (
316
- await fetchResult<{ subdomain: string }>(
317
- `/accounts/${accountId}/workers/subdomain`
318
- )
319
- ).subdomain;
320
-
321
- const scriptURL =
322
- props.legacyEnv || !props.env
323
- ? `${scriptName}.${userSubdomain}.workers.dev`
324
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
325
-
326
- // Enable the `workers.dev` subdomain.
327
- // TODO: Make this configurable.
328
- if (!available_on_subdomain) {
329
- deployments.push(
330
- fetchResult(`${workerUrl}/subdomain`, {
477
+ if (deployToWorkersDev) {
478
+ // Deploy to a subdomain of `workers.dev`
479
+ const userSubdomain = await getSubdomain(accountId);
480
+ const scriptURL =
481
+ props.legacyEnv || !props.env
482
+ ? `${scriptName}.${userSubdomain}.workers.dev`
483
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
484
+ if (!available_on_subdomain) {
485
+ // Enable the `workers.dev` subdomain.
486
+ deployments.push(
487
+ fetchResult(`${workerUrl}/subdomain`, {
488
+ method: "POST",
489
+ body: JSON.stringify({ enabled: true }),
490
+ headers: {
491
+ "Content-Type": "application/json",
492
+ },
493
+ })
494
+ .then(() => [scriptURL])
495
+ // Add a delay when the subdomain is first created.
496
+ // This is to prevent an issue where a negative cache-hit
497
+ // causes the subdomain to be unavailable for 30 seconds.
498
+ // This is a temporary measure until we fix this on the edge.
499
+ .then(async (url) => {
500
+ await sleep(3000);
501
+ return url;
502
+ })
503
+ );
504
+ } else {
505
+ deployments.push(Promise.resolve([scriptURL]));
506
+ }
507
+ } else {
508
+ if (available_on_subdomain) {
509
+ // Disable the workers.dev deployment
510
+ await fetchResult(`${workerUrl}/subdomain`, {
331
511
  method: "POST",
332
- body: JSON.stringify({ enabled: true }),
512
+ body: JSON.stringify({ enabled: false }),
333
513
  headers: {
334
514
  "Content-Type": "application/json",
335
515
  },
336
- })
337
- .then(() => [scriptURL])
338
- // Add a delay when the subdomain is first created.
339
- // This is to prevent an issue where a negative cache-hit
340
- // causes the subdomain to be unavailable for 30 seconds.
341
- // This is a temporary measure until we fix this on the edge.
342
- .then(async (url) => {
343
- await sleep(3000);
344
- return url;
345
- })
346
- );
347
- } else {
348
- deployments.push(Promise.resolve([scriptURL]));
516
+ });
517
+ }
349
518
  }
350
519
 
520
+ logger.log("Uploaded", workerName, formatTime(uploadMs));
521
+
351
522
  // Update routing table for the script.
352
- if (routes && routes.length) {
523
+ if (routesOnly.length > 0) {
353
524
  deployments.push(
354
- fetchResult(`${workerUrl}/routes`, {
355
- // TODO: PATCH will not delete previous routes on this script,
356
- // whereas PUT will. We need to decide on the default behaviour
357
- // and how to configure it.
358
- method: "PUT",
359
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
360
- headers: {
361
- "Content-Type": "application/json",
362
- },
363
- }).then(() => {
364
- if (routes.length > 10) {
365
- return routes
525
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
526
+ if (routesOnly.length > 10) {
527
+ return routesOnly
366
528
  .slice(0, 9)
367
- .map(String)
368
- .concat([`...and ${routes.length - 10} more routes`]);
529
+ .map((route) => renderRoute(route))
530
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
369
531
  }
370
- return routes.map(String);
532
+ return routesOnly.map((route) => renderRoute(route));
371
533
  })
372
534
  );
373
535
  }
374
536
 
537
+ // Update custom domains for the script
538
+ if (customDomainsOnly.length > 0) {
539
+ deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
540
+ }
541
+
375
542
  // Configure any schedules for the script.
376
543
  // TODO: rename this to `schedules`?
377
544
  if (triggers && triggers.length) {
378
545
  deployments.push(
379
546
  fetchResult(`${workerUrl}/schedules`, {
380
- // TODO: Unlike routes, this endpoint does not support PATCH.
381
- // So technically, this will override any previous schedules.
382
- // We should change the endpoint to support PATCH.
547
+ // Note: PUT will override previous schedules on this script.
383
548
  method: "PUT",
384
549
  body: JSON.stringify(triggers.map((cron) => ({ cron }))),
385
550
  headers: {
386
551
  "Content-Type": "application/json",
387
552
  },
388
- }).then(() => triggers.map(String))
553
+ }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
389
554
  );
390
555
  }
391
556
 
392
- if (!deployments.length) {
393
- return;
394
- }
395
-
396
557
  const targets = await Promise.all(deployments);
397
558
  const deployMs = Date.now() - start - uploadMs;
398
- console.log("Deployed", workerName, formatTime(deployMs));
399
- for (const target of targets.flat()) {
400
- console.log(" ", target);
559
+
560
+ if (deployments.length > 0) {
561
+ logger.log("Published", workerName, formatTime(deployMs));
562
+ for (const target of targets.flat()) {
563
+ logger.log(" ", target);
564
+ }
565
+ } else {
566
+ logger.log("No publish targets for", workerName, formatTime(deployMs));
567
+ }
568
+ }
569
+
570
+ function formatTime(duration: number) {
571
+ return `(${(duration / 1000).toFixed(2)} sec)`;
572
+ }
573
+
574
+ async function getSubdomain(accountId: string): Promise<string> {
575
+ try {
576
+ const { subdomain } = await fetchResult(
577
+ `/accounts/${accountId}/workers/subdomain`
578
+ );
579
+ return subdomain;
580
+ } catch (e) {
581
+ const error = e as { code?: number };
582
+ if (typeof error === "object" && !!error && error.code === 10007) {
583
+ // 10007 error code: not found
584
+ // https://api.cloudflare.com/#worker-subdomain-get-subdomain
585
+
586
+ const errorMessage =
587
+ "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
588
+ const solutionMessage =
589
+ "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
590
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
591
+
592
+ throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
593
+ } else {
594
+ throw e;
595
+ }
596
+ }
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
+ }
401
631
  }
402
632
  }
403
633
 
404
- function listEntryPoints(
405
- outputs: [string, ValueOf<Metafile["outputs"]>][]
406
- ): string {
407
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
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;
408
735
  }
409
736
 
410
- type ValueOf<T> = T[keyof T];
737
+ function isAuthenticationError(e: unknown): e is ParseError {
738
+ return e instanceof ParseError && (e as { code?: number }).code === 10000;
739
+ }