wrangler 0.0.0-bf67bf2 → 0.0.0-bfbb0be

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 (179) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +106 -5
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4886 -0
  6. package/package.json +76 -36
  7. package/src/__tests__/config-cache.test.ts +36 -0
  8. package/src/__tests__/configuration.test.ts +3548 -0
  9. package/src/__tests__/dev.test.tsx +1055 -0
  10. package/src/__tests__/guess-worker-format.test.ts +85 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  17. package/src/__tests__/helpers/mock-console.ts +97 -0
  18. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  20. package/src/__tests__/helpers/mock-istty.ts +32 -0
  21. package/src/__tests__/helpers/mock-kv.ts +33 -0
  22. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  23. package/src/__tests__/helpers/mock-process.ts +39 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +130 -0
  31. package/src/__tests__/index.test.ts +235 -130
  32. package/src/__tests__/init.test.ts +1992 -0
  33. package/src/__tests__/jest.setup.ts +107 -0
  34. package/src/__tests__/kv.test.ts +1619 -0
  35. package/src/__tests__/logger.test.ts +141 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1242 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6188 -0
  40. package/src/__tests__/r2.test.ts +233 -0
  41. package/src/__tests__/route.test.ts +45 -0
  42. package/src/__tests__/secret.test.ts +486 -0
  43. package/src/__tests__/tail.test.ts +690 -0
  44. package/src/__tests__/user.test.ts +132 -0
  45. package/src/__tests__/whoami.test.tsx +139 -0
  46. package/src/abort.d.ts +3 -0
  47. package/src/bundle-reporter.tsx +29 -0
  48. package/src/bundle.ts +204 -0
  49. package/src/cfetch/index.ts +121 -0
  50. package/src/cfetch/internal.ts +142 -0
  51. package/src/cli.ts +10 -7
  52. package/src/config/README.md +107 -0
  53. package/src/config/config.ts +243 -0
  54. package/src/config/diagnostics.ts +80 -0
  55. package/src/config/environment.ts +420 -0
  56. package/src/config/index.ts +225 -0
  57. package/src/config/validation-helpers.ts +584 -0
  58. package/src/config/validation.ts +1580 -0
  59. package/src/config-cache.ts +44 -0
  60. package/src/create-worker-preview.ts +185 -0
  61. package/src/create-worker-upload-form.ts +254 -0
  62. package/src/dev/dev-vars.ts +36 -0
  63. package/src/dev/dev.tsx +399 -0
  64. package/src/dev/local.tsx +321 -0
  65. package/src/dev/remote.tsx +282 -0
  66. package/src/dev/use-esbuild.ts +112 -0
  67. package/src/dialogs.tsx +68 -18
  68. package/src/durable.ts +102 -0
  69. package/src/entry.ts +328 -0
  70. package/src/environment-variables.ts +35 -0
  71. package/src/errors.ts +11 -0
  72. package/src/git-client.ts +42 -0
  73. package/src/https-options.ts +123 -0
  74. package/src/index.tsx +2092 -1029
  75. package/src/inspect.ts +662 -0
  76. package/src/intl-polyfill.d.ts +139 -0
  77. package/src/kv.ts +408 -0
  78. package/src/logger.ts +73 -0
  79. package/src/miniflare-cli/README.md +30 -0
  80. package/src/miniflare-cli/enum-keys.ts +17 -0
  81. package/src/miniflare-cli/index.ts +41 -0
  82. package/src/miniflare-cli/request-context.ts +40 -0
  83. package/src/module-collection.ts +258 -0
  84. package/src/open-in-browser.ts +17 -0
  85. package/src/package-manager.ts +174 -0
  86. package/src/pages/build.tsx +202 -0
  87. package/src/pages/constants.ts +7 -0
  88. package/src/pages/deployments.tsx +101 -0
  89. package/src/pages/dev.tsx +948 -0
  90. package/src/pages/functions/buildPlugin.ts +105 -0
  91. package/src/pages/functions/buildWorker.ts +151 -0
  92. package/src/pages/functions/filepath-routing.test.ts +234 -0
  93. package/src/pages/functions/filepath-routing.ts +189 -0
  94. package/src/pages/functions/identifiers.ts +78 -0
  95. package/src/pages/functions/routes.ts +151 -0
  96. package/src/pages/index.tsx +84 -0
  97. package/src/pages/projects.tsx +157 -0
  98. package/src/pages/publish.tsx +325 -0
  99. package/src/pages/types.ts +40 -0
  100. package/src/pages/upload.tsx +363 -0
  101. package/src/pages/utils.ts +12 -0
  102. package/src/parse.ts +222 -0
  103. package/src/paths.ts +26 -0
  104. package/src/proxy.ts +476 -0
  105. package/src/publish.ts +661 -272
  106. package/src/r2.ts +50 -0
  107. package/src/selfsigned.d.ts +29 -0
  108. package/src/sites.tsx +316 -59
  109. package/src/tail/filters.ts +279 -0
  110. package/src/tail/index.ts +299 -0
  111. package/src/tail/printing.ts +67 -0
  112. package/src/update-check.ts +19 -0
  113. package/src/user/choose-account.tsx +60 -0
  114. package/src/user/env-vars.ts +17 -0
  115. package/src/user/generate-auth-url.ts +33 -0
  116. package/src/user/generate-random-state.ts +16 -0
  117. package/src/user/index.ts +3 -0
  118. package/src/{user.tsx → user/user.tsx} +380 -276
  119. package/src/whoami.tsx +71 -0
  120. package/src/worker.ts +181 -0
  121. package/src/zones.ts +73 -0
  122. package/templates/gitignore +171 -0
  123. package/templates/new-worker-scheduled.js +17 -0
  124. package/templates/new-worker-scheduled.ts +32 -0
  125. package/templates/new-worker.js +15 -0
  126. package/templates/new-worker.ts +30 -0
  127. package/templates/no-op-worker.js +10 -0
  128. package/templates/pages-template-plugin.ts +155 -0
  129. package/templates/pages-template-worker.ts +161 -0
  130. package/{static-asset-facade.js → templates/static-asset-facade.js} +3 -7
  131. package/templates/tsconfig.json +105 -0
  132. package/wrangler-dist/cli.js +100313 -110298
  133. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  134. package/src/__tests__/mock-cfetch.js +0 -46
  135. package/src/api/form_data.ts +0 -158
  136. package/src/api/inspect.ts +0 -441
  137. package/src/api/preview.ts +0 -123
  138. package/src/api/worker.ts +0 -157
  139. package/src/cfetch.ts +0 -72
  140. package/src/config.ts +0 -124
  141. package/src/dev.tsx +0 -736
  142. package/src/kv.tsx +0 -211
  143. package/src/pages.tsx +0 -340
  144. package/src/tail.tsx +0 -71
  145. package/src/util/fetch.ts +0 -74
  146. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  147. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  148. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  149. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  150. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  151. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  152. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  153. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  154. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  155. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  156. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  157. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  158. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  159. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  160. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  161. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  162. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  163. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  164. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  165. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  166. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  167. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  168. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  169. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  170. package/vendor/wrangler-mime/LICENSE +0 -21
  171. package/vendor/wrangler-mime/Mime.js +0 -97
  172. package/vendor/wrangler-mime/README.md +0 -187
  173. package/vendor/wrangler-mime/cli.js +0 -46
  174. package/vendor/wrangler-mime/index.js +0 -4
  175. package/vendor/wrangler-mime/lite.js +0 -4
  176. package/vendor/wrangler-mime/package.json +0 -52
  177. package/vendor/wrangler-mime/types/other.js +0 -1
  178. package/vendor/wrangler-mime/types/standard.js +0 -1
  179. package/wrangler-dist/cli.js.map +0 -7
package/src/publish.ts CHANGED
@@ -1,350 +1,739 @@
1
- import type { CfWorkerInit } from "./api/worker";
2
- import { toFormData } from "./api/form_data";
3
- import esbuild from "esbuild";
4
- import tmp from "tmp-promise";
5
- import type { Config } from "./config";
6
- import path from "path";
7
- import { readFile } from "fs/promises";
8
- import cfetch from "./cfetch";
9
1
  import assert from "node:assert";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { URLSearchParams } from "node:url";
5
+ import tmp from "tmp-promise";
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";
10
15
  import { syncAssets } from "./sites";
11
- import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
12
- import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
13
-
14
- type CfScriptFormat = void | "modules" | "service-worker";
16
+ import { getZoneForRoute } from "./zones";
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";
25
+ import type { AssetPaths } from "./sites";
26
+ import type { CfWorkerInit } from "./worker";
15
27
 
16
28
  type Props = {
17
29
  config: Config;
18
- format?: CfScriptFormat;
19
- script?: string;
20
- name?: string;
21
- env?: string;
22
- public?: string;
23
- site?: string;
24
- triggers?: (string | number)[];
25
- routes?: (string | number)[];
26
- legacyEnv?: boolean;
27
- jsxFactory: void | string;
28
- jsxFragment: void | string;
29
- polyfillNode: void | boolean;
30
+ accountId: string | undefined;
31
+ entry: Entry;
32
+ rules: Config["rules"];
33
+ name: string | undefined;
34
+ env: string | undefined;
35
+ compatibilityDate: string | undefined;
36
+ compatibilityFlags: string[] | undefined;
37
+ assetPaths: AssetPaths | undefined;
38
+ triggers: string[] | undefined;
39
+ routes: string[] | undefined;
40
+ legacyEnv: boolean | undefined;
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;
30
49
  };
31
50
 
51
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
52
+
32
53
  function sleep(ms: number) {
33
54
  return new Promise((resolve) => setTimeout(resolve, ms));
34
55
  }
35
56
 
36
- export default async function publish(props: Props): Promise<void> {
37
- if (props.public && props.format === "service-worker") {
38
- // TODO: check config too
39
- throw new Error(
40
- "You cannot use 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
41
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
+ }
42
77
  }
43
- // TODO: warn if git/hg has uncommitted changes
44
- const { config } = props;
45
- const {
46
- account_id: accountId,
47
- build,
48
- // @ts-expect-error hidden
49
- __path__,
50
- } = config;
78
+ return result;
79
+ }
51
80
 
52
- const triggers = props.triggers || config.triggers?.crons;
53
- const routes = props.routes || config.routes;
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
+ }
54
94
 
55
- const jsxFactory = props.jsxFactory || config.jsx_factory;
56
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
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
+ }
57
104
 
58
- assert(config.account_id, "missing account id");
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
+ }
59
114
 
60
- let file: string;
61
- if (props.script) {
62
- file = props.script;
63
- assert(props.name, "name is required when using script");
64
- } else {
65
- assert(build?.upload?.main, "missing main file");
66
- assert(config.name, "missing name");
67
- file = path.join(path.dirname(__path__), build.upload.main);
68
- }
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
+ });
69
147
 
70
- let scriptName = props.script ? props.name : config.name;
71
- if (props.legacyEnv) {
72
- scriptName += props.env ? `-${props.env}` : "";
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;
73
154
  }
74
- const envName = props.env ?? "production";
75
155
 
76
- const destination = await tmp.dir({ unsafeCleanup: true });
77
-
78
- const result = await esbuild.build({
79
- ...(props.public
80
- ? {
81
- stdin: {
82
- contents: (
83
- await readFile(
84
- path.join(__dirname, "../static-asset-facade.js"),
85
- "utf8"
86
- )
87
- ).replace("__ENTRY_POINT__", path.join(process.cwd(), file)),
88
- sourcefile: "static-asset-facade.js",
89
- resolveDir: path.dirname(file),
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",
90
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();
91
197
  }
92
- : { entryPoints: [file] }),
93
- bundle: true,
94
- define: {
95
- ...((props.polyfillNode ?? config.polyfill_node) && {
96
- global: "globalThis",
97
- }),
98
- },
99
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
100
- outdir: destination.path,
101
- external: ["__STATIC_CONTENT_MANIFEST"],
102
- format: "esm",
103
- plugins:
104
- props.polyfillNode ?? config.polyfill_node
105
- ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
106
- : undefined,
107
- sourcemap: true,
108
- metafile: true,
109
- loader: {
110
- ".js": "jsx",
111
- },
112
- ...(jsxFactory && { jsxFactory }),
113
- ...(jsxFragment && { jsxFragment }),
114
- });
115
-
116
- const chunks = Object.entries(result.metafile.outputs).find(
117
- ([_path, { entryPoint }]) =>
118
- entryPoint ===
119
- (props.public
120
- ? path.join(path.dirname(file), "static-asset-facade.js")
121
- : file)
122
- );
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
+ }
123
222
 
124
- const { format } = props;
125
- const bundle = {
126
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
127
- exports: chunks[1].exports,
128
- };
223
+ export default async function publish(props: Props): Promise<void> {
224
+ // TODO: warn if git/hg has uncommitted changes
225
+ const { config, accountId } = props;
129
226
 
130
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
131
- // That way we'll be able to accurately tell if this is a service worker or not.
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")}`;
132
231
 
133
- if (format === "modules" && bundle.type === "commonjs") {
134
- console.error("⎔ Cannot use modules with a commonjs bundle.");
135
- // TODO: a much better error message here, with what to do next
136
- return;
137
- }
138
- if (format === "service-worker" && bundle.type !== "esm") {
139
- console.error("⎔ Cannot use service-worker with a esm bundle.");
140
- // TODO: a much better error message here, with what to do next
141
- return;
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.`);
142
238
  }
143
239
 
144
- const content = await readFile(chunks[0], { encoding: "utf-8" });
145
- destination.cleanup();
146
-
147
- // if config.migrations
148
- // get current migration tag
149
- let migrations;
150
- if ("migrations" in config) {
151
- const scripts = await cfetch<{ id: string; migration_tag: string }[]>(
152
- `/accounts/${accountId}/workers/scripts`
153
- );
154
- const script = scripts.find((script) => script.id === scriptName);
155
- if (script?.migration_tag) {
156
- // was already published once
157
- const foundIndex = config.migrations.findIndex(
158
- (migration) => migration.tag === script.migration_tag
159
- );
160
- if (foundIndex === -1) {
161
- console.warn(
162
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already delated it. Applying all available migrations to the script...`
240
+ const triggers = props.triggers || config.triggers?.crons;
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`
163
250
  );
164
- migrations = {
165
- old_tag: script.migration_tag,
166
- new_tag: config.migrations[config.migrations.length - 1].tag,
167
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
168
- };
169
- } else {
170
- migrations = {
171
- old_tag: script.migration_tag,
172
- new_tag: config.migrations[config.migrations.length - 1].tag,
173
- steps: config.migrations
174
- .slice(foundIndex + 1)
175
- .map(({ tag: _tag, ...rest }) => rest),
176
- };
177
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);
178
258
  } else {
179
- migrations = {
180
- new_tag: config.migrations[config.migrations.length - 1].tag,
181
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
182
- };
259
+ routesOnly.push(route);
183
260
  }
184
261
  }
185
262
 
186
- const assets =
187
- props.public || props.site || props.config.site?.bucket // TODO: allow both
188
- ? await syncAssets(
189
- accountId,
190
- scriptName,
191
- props.public || props.site || props.config.site?.bucket,
192
- false
193
- )
194
- : { manifest: undefined, namespace: undefined };
263
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
264
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
195
265
 
196
- const envRootObj = props.env ? config.env[props.env] || {} : config;
266
+ const jsxFactory = props.jsxFactory || config.jsx_factory;
267
+ const jsxFragment = props.jsxFragment || config.jsx_fragment;
197
268
 
198
- const worker: CfWorkerInit = {
199
- main: {
200
- name: scriptName,
201
- content: content,
202
- type: bundle.type === "esm" ? "esm" : "commonjs",
203
- },
204
- variables: {
205
- ...(envRootObj?.vars || {}),
206
- ...(envRootObj?.kv_namespaces || []).reduce(
207
- (obj, { binding, preview_id: _preview_id, id }) => {
208
- return { ...obj, [binding]: { namespaceId: id } };
209
- },
210
- {}
211
- ),
212
- ...(envRootObj?.durable_objects?.bindings || []).reduce(
213
- (obj, { name, class_name, script_name }) => {
214
- return {
215
- ...obj,
216
- [name]: { class_name, ...(script_name && { script_name }) },
217
- };
218
- },
219
- {}
220
- ),
221
- ...(assets.namespace
222
- ? { __STATIC_CONTENT: { namespaceId: assets.namespace } }
223
- : {}),
224
- },
225
- ...(migrations && { migrations }),
226
- modules: assets.manifest
227
- ? [].concat({
228
- name: "__STATIC_CONTENT_MANIFEST",
229
- content: JSON.stringify(assets.manifest),
230
- type: "text",
231
- })
232
- : [],
233
- compatibility_date: config.compatibility_date,
234
- compatibility_flags: config.compatibility_flags,
235
- usage_model: config.usage_model,
236
- };
269
+ const minify = props.minify ?? config.minify;
237
270
 
238
- const start = Date.now();
239
- function formatTime(duration: number) {
240
- return `(${(duration / 1000).toFixed(2)} sec)`;
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
+ );
241
276
  }
242
277
 
243
- const notProd = !props.legacyEnv && props.env;
278
+ const scriptName = props.name;
279
+ assert(
280
+ scriptName,
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>"`'
282
+ );
283
+
284
+ assert(
285
+ !config.site || config.site.bucket,
286
+ "A [site] definition requires a `bucket` field with a path to the site's assets directory."
287
+ );
288
+
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
+ );
299
+ }
300
+
301
+ const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
302
+ const envName = props.env ?? "production";
303
+
304
+ const start = Date.now();
305
+ const notProd = Boolean(!props.legacyEnv && props.env);
244
306
  const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
245
307
  const workerUrl = notProd
246
308
  ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
247
309
  : `/accounts/${accountId}/workers/scripts/${scriptName}`;
248
310
 
249
- // Upload the script so it has time to propogate.
250
- const { available_on_subdomain } = await cfetch(
251
- `${workerUrl}?available_on_subdomain=true`,
252
- {
253
- method: "PUT",
254
- // @ts-expect-error: TODO: fix this type error!
255
- body: toFormData(worker),
311
+ let available_on_subdomain; // we'll set this later
312
+
313
+ const { format } = props.entry;
314
+
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
+ );
323
+ }
324
+
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
+ }
330
+
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"
334
+ );
335
+ }
336
+
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
+ );
357
+
358
+ const content = readFileSync(resolvedEntryPointPath, {
359
+ encoding: "utf-8",
360
+ });
361
+
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
+ );
383
+
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
+ });
256
412
  }
257
- );
258
413
 
259
- const uploadMs = Date.now() - start;
260
- console.log("Uploaded", workerName, formatTime(uploadMs));
261
- const deployments: Promise<string[]>[] = [];
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
+ };
262
429
 
263
- const userSubdomain = (
264
- await cfetch<{ subdomain: string }>(
265
- `/accounts/${accountId}/workers/subdomain`
266
- )
267
- ).subdomain;
430
+ const withoutStaticAssets = {
431
+ ...bindings,
432
+ kv_namespaces: config.kv_namespaces,
433
+ text_blobs: config.text_blobs,
434
+ };
435
+ printBindings(withoutStaticAssets);
268
436
 
269
- const scriptURL =
270
- props.legacyEnv || !props.env
271
- ? `${scriptName}.${userSubdomain}.workers.dev`
272
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
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
+ }
466
+ }
273
467
 
274
- // Enable the `workers.dev` subdomain.
275
- // TODO: Make this configurable.
276
- if (!available_on_subdomain) {
277
- deployments.push(
278
- cfetch(`${workerUrl}/subdomain`, {
468
+ if (props.dryRun) {
469
+ logger.log(`--dry-run: exiting now.`);
470
+ return;
471
+ }
472
+ assert(accountId, "Missing accountId");
473
+
474
+ const uploadMs = Date.now() - start;
475
+ const deployments: Promise<string[]>[] = [];
476
+
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`, {
279
511
  method: "POST",
280
- body: JSON.stringify({ enabled: true }),
512
+ body: JSON.stringify({ enabled: false }),
281
513
  headers: {
282
514
  "Content-Type": "application/json",
283
515
  },
284
- })
285
- .then(() => [scriptURL])
286
- // Add a delay when the subdomain is first created.
287
- // This is to prevent an issue where a negative cache-hit
288
- // causes the subdomain to be unavailable for 30 seconds.
289
- // This is a temporary measure until we fix this on the edge.
290
- .then((url) => {
291
- sleep(3000);
292
- return url;
293
- })
294
- );
295
- } else {
296
- deployments.push(Promise.resolve([scriptURL]));
516
+ });
517
+ }
297
518
  }
298
519
 
520
+ logger.log("Uploaded", workerName, formatTime(uploadMs));
521
+
299
522
  // Update routing table for the script.
300
- if (routes && routes.length) {
523
+ if (routesOnly.length > 0) {
301
524
  deployments.push(
302
- cfetch(`${workerUrl}/routes`, {
303
- // TODO: PATCH will not delete previous routes on this script,
304
- // whereas PUT will. We need to decide on the default behaviour
305
- // and how to configure it.
306
- method: "PUT",
307
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
308
- headers: {
309
- "Content-Type": "application/json",
310
- },
311
- }).then(() => {
312
- if (routes.length > 10) {
313
- return routes
525
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
526
+ if (routesOnly.length > 10) {
527
+ return routesOnly
314
528
  .slice(0, 9)
315
- .map(String)
316
- .concat([`...and ${routes.length - 10} more routes`]);
529
+ .map((route) => renderRoute(route))
530
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
317
531
  }
318
- return routes.map(String);
532
+ return routesOnly.map((route) => renderRoute(route));
319
533
  })
320
534
  );
321
535
  }
322
536
 
537
+ // Update custom domains for the script
538
+ if (customDomainsOnly.length > 0) {
539
+ deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
540
+ }
541
+
323
542
  // Configure any schedules for the script.
324
543
  // TODO: rename this to `schedules`?
325
544
  if (triggers && triggers.length) {
326
545
  deployments.push(
327
- cfetch(`${workerUrl}/schedules`, {
328
- // TODO: Unlike routes, this endpoint does not support PATCH.
329
- // So technically, this will override any previous schedules.
330
- // We should change the endpoint to support PATCH.
546
+ fetchResult(`${workerUrl}/schedules`, {
547
+ // Note: PUT will override previous schedules on this script.
331
548
  method: "PUT",
332
549
  body: JSON.stringify(triggers.map((cron) => ({ cron }))),
333
550
  headers: {
334
551
  "Content-Type": "application/json",
335
552
  },
336
- }).then(() => triggers.map(String))
553
+ }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
337
554
  );
338
555
  }
339
556
 
340
- if (!deployments.length) {
341
- return;
342
- }
343
-
344
557
  const targets = await Promise.all(deployments);
345
558
  const deployMs = Date.now() - start - uploadMs;
346
- console.log("Deployed", workerName, formatTime(deployMs));
347
- for (const target of targets.flat()) {
348
- 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));
349
567
  }
350
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
+ }
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
+ }