wrangler 0.0.0-e88a54e → 0.0.0-e8e684c7

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 (222) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +161 -29
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5484 -21
  6. package/package.json +173 -143
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +4016 -2786
  10. package/src/__tests__/dev.test.tsx +1305 -483
  11. package/src/__tests__/generate.test.ts +91 -0
  12. package/src/__tests__/guess-worker-format.test.ts +75 -48
  13. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  14. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  15. package/src/__tests__/helpers/mock-bin.ts +20 -20
  16. package/src/__tests__/helpers/mock-cfetch.ts +182 -93
  17. package/src/__tests__/helpers/mock-console.ts +59 -32
  18. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  19. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  23. package/src/__tests__/helpers/mock-kv.ts +26 -26
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  25. package/src/__tests__/helpers/mock-process.ts +39 -0
  26. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  27. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  28. package/src/__tests__/helpers/run-in-tmp.ts +28 -22
  29. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  30. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  31. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  32. package/src/__tests__/https-options.test.ts +144 -108
  33. package/src/__tests__/index.test.ts +229 -975
  34. package/src/__tests__/init.test.ts +2170 -0
  35. package/src/__tests__/jest.setup.ts +122 -34
  36. package/src/__tests__/kv.test.ts +1376 -1087
  37. package/src/__tests__/logger.test.ts +141 -0
  38. package/src/__tests__/metrics.test.ts +450 -0
  39. package/src/__tests__/package-manager.test.ts +312 -165
  40. package/src/__tests__/pages.test.ts +1270 -39
  41. package/src/__tests__/parse.test.ts +253 -245
  42. package/src/__tests__/publish.test.ts +6878 -2627
  43. package/src/__tests__/pubsub.test.ts +367 -0
  44. package/src/__tests__/r2.test.ts +328 -190
  45. package/src/__tests__/route.test.ts +22 -22
  46. package/src/__tests__/secret.test.ts +474 -407
  47. package/src/__tests__/tail.test.ts +679 -441
  48. package/src/__tests__/test-old-node-version.js +31 -0
  49. package/src/__tests__/user.test.ts +155 -0
  50. package/src/__tests__/validate-dev-props.test.ts +56 -0
  51. package/src/__tests__/version.test.ts +35 -0
  52. package/src/__tests__/whoami.test.tsx +276 -87
  53. package/src/__tests__/worker-namespace.test.ts +329 -0
  54. package/src/abort.d.ts +3 -0
  55. package/src/api/dev.ts +93 -0
  56. package/src/api/index.ts +1 -0
  57. package/src/bundle-reporter.tsx +29 -0
  58. package/src/bundle.ts +441 -110
  59. package/src/cfetch/index.ts +83 -66
  60. package/src/cfetch/internal.ts +251 -92
  61. package/src/cli.ts +22 -14
  62. package/src/config/README.md +1 -1
  63. package/src/config/config.ts +224 -179
  64. package/src/config/diagnostics.ts +61 -61
  65. package/src/config/environment.ts +430 -311
  66. package/src/config/index.ts +227 -38
  67. package/src/config/validation-helpers.ts +414 -303
  68. package/src/config/validation.ts +1745 -973
  69. package/src/config-cache.ts +85 -0
  70. package/src/create-worker-preview.ts +209 -118
  71. package/src/create-worker-upload-form.ts +275 -201
  72. package/src/dev/dev-vars.ts +36 -0
  73. package/src/dev/dev.tsx +488 -307
  74. package/src/dev/local.tsx +427 -210
  75. package/src/dev/remote.tsx +407 -188
  76. package/src/dev/use-esbuild.ts +156 -78
  77. package/src/dev/validate-dev-props.ts +31 -0
  78. package/src/dev-registry.tsx +160 -0
  79. package/src/dev.tsx +696 -0
  80. package/src/dialogs.tsx +115 -57
  81. package/src/dispatch-namespace.ts +206 -0
  82. package/src/durable.ts +102 -0
  83. package/src/entry.ts +267 -147
  84. package/src/environment-variables.ts +25 -23
  85. package/src/errors.ts +11 -0
  86. package/src/faye-websocket.d.ts +6 -0
  87. package/src/generate.ts +131 -0
  88. package/src/git-client.ts +42 -0
  89. package/src/global-wrangler-config-path.ts +26 -0
  90. package/src/https-options.ts +85 -80
  91. package/src/index.tsx +2191 -2304
  92. package/src/init.ts +622 -0
  93. package/src/inspect.ts +687 -557
  94. package/src/intl-polyfill.d.ts +139 -0
  95. package/src/is-ci.ts +14 -0
  96. package/src/is-interactive.ts +12 -0
  97. package/src/kv.ts +353 -242
  98. package/src/logger.ts +73 -0
  99. package/src/metrics/index.ts +5 -0
  100. package/src/metrics/metrics-config.ts +239 -0
  101. package/src/metrics/metrics-dispatcher.ts +96 -0
  102. package/src/metrics/metrics-usage-headers.ts +24 -0
  103. package/src/metrics/send-event.ts +92 -0
  104. package/src/miniflare-cli/assets.ts +554 -0
  105. package/src/miniflare-cli/enum-keys.ts +8 -8
  106. package/src/miniflare-cli/index.ts +199 -29
  107. package/src/miniflare-cli/request-context.ts +40 -0
  108. package/src/module-collection.ts +213 -213
  109. package/src/open-in-browser.ts +8 -16
  110. package/src/package-manager.ts +183 -90
  111. package/src/pages/build.tsx +238 -0
  112. package/src/pages/constants.ts +12 -0
  113. package/src/pages/deployments.tsx +106 -0
  114. package/src/pages/dev.tsx +528 -0
  115. package/src/pages/errors.ts +22 -0
  116. package/src/pages/functions/buildPlugin.ts +109 -0
  117. package/src/pages/functions/buildWorker.ts +155 -0
  118. package/src/pages/functions/filepath-routing.test.ts +234 -0
  119. package/src/pages/functions/filepath-routing.ts +189 -0
  120. package/src/pages/functions/identifiers.ts +78 -0
  121. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  122. package/src/pages/functions/routes-consolidation.ts +73 -0
  123. package/src/pages/functions/routes-transformation.test.ts +271 -0
  124. package/src/pages/functions/routes-transformation.ts +122 -0
  125. package/src/pages/functions/routes.ts +151 -0
  126. package/src/pages/functions.tsx +96 -0
  127. package/src/pages/index.tsx +94 -0
  128. package/src/pages/projects.tsx +169 -0
  129. package/src/pages/publish.tsx +391 -0
  130. package/src/pages/types.ts +49 -0
  131. package/src/pages/upload.tsx +413 -0
  132. package/src/pages/utils.ts +12 -0
  133. package/src/parse.ts +224 -121
  134. package/src/paths.ts +6 -6
  135. package/src/preview.ts +31 -0
  136. package/src/proxy.ts +416 -370
  137. package/src/publish.ts +796 -321
  138. package/src/pubsub/index.ts +286 -0
  139. package/src/pubsub/pubsub-commands.tsx +623 -0
  140. package/src/r2.ts +100 -19
  141. package/src/selfsigned.d.ts +23 -23
  142. package/src/sites.tsx +281 -189
  143. package/src/tail/filters.ts +111 -109
  144. package/src/tail/index.ts +230 -217
  145. package/src/tail/printing.ts +92 -47
  146. package/src/update-check.ts +19 -0
  147. package/src/user/choose-account.tsx +69 -0
  148. package/src/user/env-vars.ts +46 -0
  149. package/src/user/generate-auth-url.ts +33 -0
  150. package/src/user/generate-random-state.ts +16 -0
  151. package/src/user/index.ts +3 -0
  152. package/src/user/user.tsx +1191 -0
  153. package/src/whoami.tsx +142 -42
  154. package/src/worker.ts +135 -94
  155. package/src/zones.ts +167 -0
  156. package/templates/checked-fetch.js +17 -0
  157. package/templates/first-party-worker-module-facade.ts +18 -0
  158. package/templates/format-dev-errors.ts +32 -0
  159. package/templates/gitignore +171 -0
  160. package/templates/new-worker-scheduled.js +17 -0
  161. package/templates/new-worker-scheduled.ts +32 -0
  162. package/templates/new-worker.js +3 -3
  163. package/templates/new-worker.ts +18 -3
  164. package/templates/no-op-worker.js +10 -0
  165. package/templates/pages-shim.ts +9 -0
  166. package/templates/pages-template-plugin.ts +167 -0
  167. package/templates/pages-template-worker.ts +172 -0
  168. package/templates/serve-static-assets.ts +63 -0
  169. package/templates/service-bindings-module-facade.js +54 -0
  170. package/templates/service-bindings-sw-facade.js +42 -0
  171. package/templates/tsconfig.json +95 -95
  172. package/wrangler-dist/cli.d.ts +338 -0
  173. package/wrangler-dist/cli.js +124611 -112403
  174. package/miniflare-dist/index.mjs.map +0 -7
  175. package/pages/functions/buildWorker.ts +0 -62
  176. package/pages/functions/filepath-routing.test.ts +0 -223
  177. package/pages/functions/filepath-routing.ts +0 -181
  178. package/pages/functions/identifiers.ts +0 -78
  179. package/pages/functions/routes.ts +0 -151
  180. package/pages/functions/template-worker.ts +0 -130
  181. package/src/__tests__/dev2.test.tsx +0 -154
  182. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  183. package/src/__tests__/logout.test.ts +0 -52
  184. package/src/__tests__/sentry.test.ts +0 -146
  185. package/src/pages.tsx +0 -1047
  186. package/src/reporting.ts +0 -131
  187. package/src/user.tsx +0 -1118
  188. package/templates/static-asset-facade.js +0 -47
  189. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  190. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  191. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  192. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  193. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  194. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  195. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  196. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  201. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  202. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  203. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  204. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  205. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  206. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  207. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  209. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  210. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  211. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  212. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  213. package/vendor/wrangler-mime/LICENSE +0 -21
  214. package/vendor/wrangler-mime/Mime.js +0 -97
  215. package/vendor/wrangler-mime/README.md +0 -187
  216. package/vendor/wrangler-mime/cli.js +0 -46
  217. package/vendor/wrangler-mime/index.js +0 -4
  218. package/vendor/wrangler-mime/lite.js +0 -4
  219. package/vendor/wrangler-mime/package.json +0 -52
  220. package/vendor/wrangler-mime/types/other.js +0 -1
  221. package/vendor/wrangler-mime/types/standard.js +0 -1
  222. package/wrangler-dist/cli.js.map +0 -7
package/src/publish.ts CHANGED
@@ -1,347 +1,822 @@
1
1
  import assert from "node:assert";
2
- import { readFileSync } from "node:fs";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { URLSearchParams } from "node:url";
5
5
  import tmp from "tmp-promise";
6
6
  import { bundleWorker } from "./bundle";
7
- import { fetchResult } from "./cfetch";
7
+ import { printBundleSize } from "./bundle-reporter";
8
+ import { fetchListResult, fetchResult } from "./cfetch";
9
+ import { printBindings } from "./config";
8
10
  import { createWorkerUploadForm } from "./create-worker-upload-form";
11
+ import { confirm } from "./dialogs";
12
+ import { getMigrationsToUpload } from "./durable";
13
+ import { logger } from "./logger";
14
+ import { getMetricsUsageHeaders } from "./metrics";
15
+ import { ParseError } from "./parse";
9
16
  import { syncAssets } from "./sites";
17
+ import { getZoneForRoute } from "./zones";
10
18
  import type { Config } from "./config";
19
+ import type {
20
+ Route,
21
+ ZoneIdRoute,
22
+ ZoneNameRoute,
23
+ CustomDomainRoute,
24
+ } from "./config/environment";
11
25
  import type { Entry } from "./entry";
12
26
  import type { AssetPaths } from "./sites";
13
27
  import type { CfWorkerInit } from "./worker";
14
28
 
15
29
  type Props = {
16
- config: Config;
17
- accountId: string;
18
- entry: Entry;
19
- rules: Config["rules"];
20
- name: string | undefined;
21
- env: string | undefined;
22
- compatibilityDate: string | undefined;
23
- compatibilityFlags: string[] | undefined;
24
- assetPaths: AssetPaths | undefined;
25
- triggers: (string | number)[] | undefined;
26
- routes: (string | number)[] | undefined;
27
- legacyEnv: boolean | undefined;
28
- jsxFactory: undefined | string;
29
- jsxFragment: undefined | string;
30
- experimentalPublic: boolean;
30
+ config: Config;
31
+ accountId: string | undefined;
32
+ entry: Entry;
33
+ rules: Config["rules"];
34
+ name: string | undefined;
35
+ env: string | undefined;
36
+ compatibilityDate: string | undefined;
37
+ compatibilityFlags: string[] | undefined;
38
+ assetPaths: AssetPaths | undefined;
39
+ vars: Record<string, string> | undefined;
40
+ defines: Record<string, string> | undefined;
41
+ triggers: string[] | undefined;
42
+ routes: string[] | undefined;
43
+ legacyEnv: boolean | undefined;
44
+ jsxFactory: string | undefined;
45
+ jsxFragment: string | undefined;
46
+ tsconfig: string | undefined;
47
+ isWorkersSite: boolean;
48
+ minify: boolean | undefined;
49
+ nodeCompat: boolean | undefined;
50
+ outDir: string | undefined;
51
+ dryRun: boolean | undefined;
52
+ noBundle: boolean | undefined;
53
+ };
54
+
55
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
56
+
57
+ export type CustomDomain = {
58
+ id: string;
59
+ zone_id: string;
60
+ zone_name: string;
61
+ hostname: string;
62
+ service: string;
63
+ environment: string;
64
+ };
65
+ type UpdatedCustomDomain = CustomDomain & { modified: boolean };
66
+ type ConflictingCustomDomain = CustomDomain & {
67
+ external_dns_record_id?: string;
68
+ external_cert_id?: string;
69
+ };
70
+
71
+ export type CustomDomainChangeset = {
72
+ added: CustomDomain[];
73
+ removed: CustomDomain[];
74
+ updated: UpdatedCustomDomain[];
75
+ conflicting: ConflictingCustomDomain[];
31
76
  };
32
77
 
33
78
  function sleep(ms: number) {
34
- return new Promise((resolve) => setTimeout(resolve, ms));
79
+ return new Promise((resolve) => setTimeout(resolve, ms));
80
+ }
81
+
82
+ function renderRoute(route: Route): string {
83
+ let result = "";
84
+ if (typeof route === "string") {
85
+ result = route;
86
+ } else {
87
+ result = route.pattern;
88
+ const isCustomDomain = Boolean(
89
+ "custom_domain" in route && route.custom_domain
90
+ );
91
+ if (isCustomDomain && "zone_id" in route) {
92
+ result += ` (custom domain - zone id: ${route.zone_id})`;
93
+ } else if (isCustomDomain && "zone_name" in route) {
94
+ result += ` (custom domain - zone name: ${route.zone_name})`;
95
+ } else if (isCustomDomain) {
96
+ result += ` (custom domain)`;
97
+ } else if ("zone_id" in route) {
98
+ result += ` (zone id: ${route.zone_id})`;
99
+ } else if ("zone_name" in route) {
100
+ result += ` (zone name: ${route.zone_name})`;
101
+ }
102
+ }
103
+ return result;
104
+ }
105
+
106
+ // publishing to custom domains involves a few more steps than just updating
107
+ // the routing table, and thus the api implementing it is fairly defensive -
108
+ // it will error eagerly on conflicts against existing domains or existing
109
+ // managed DNS records
110
+
111
+ // however, you can pass params to override the errors. to know if we should
112
+ // override the current state, we generate a "changeset" of required actions
113
+ // to get to the state we want (specified by the list of custom domains). the
114
+ // changeset returns an "updated" collection (existing custom domains
115
+ // connected to other scripts) and a "conflicting" collection (the requested
116
+ // custom domains that have a managed, conflicting DNS record preventing the
117
+ // host's use as a custom domain). with this information, we can prompt to
118
+ // the user what will occur if we create the custom domains requested, and
119
+ // add the override param if they confirm the action
120
+ //
121
+ // if a user does not confirm that they want to override, we skip publishing
122
+ // to these custom domains, but continue on through the rest of the
123
+ // publish stage
124
+ async function publishCustomDomains(
125
+ workerUrl: string,
126
+ accountId: string,
127
+ domains: Array<RouteObject>
128
+ ): Promise<string[]> {
129
+ const config = {
130
+ override_scope: true,
131
+ override_existing_origin: false,
132
+ override_existing_dns_record: false,
133
+ };
134
+ const origins = domains.map((domainRoute) => {
135
+ return {
136
+ hostname: domainRoute.pattern,
137
+ zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
138
+ zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
139
+ };
140
+ });
141
+
142
+ const fail = () => {
143
+ return [
144
+ domains.length > 1
145
+ ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
146
+ : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
147
+ ];
148
+ };
149
+
150
+ if (!process.stdout.isTTY) {
151
+ // running in non-interactive mode.
152
+ // existing origins / dns records are not indicative of errors,
153
+ // so we aggressively update rather than aggressively fail
154
+ config.override_existing_origin = true;
155
+ config.override_existing_dns_record = true;
156
+ } else {
157
+ // get a changeset for operations required to achieve a state with the requested domains
158
+ const changeset = await fetchResult<CustomDomainChangeset>(
159
+ `${workerUrl}/domains/changeset?replace_state=true`,
160
+ {
161
+ method: "POST",
162
+ body: JSON.stringify(origins),
163
+ headers: {
164
+ "Content-Type": "application/json",
165
+ },
166
+ }
167
+ );
168
+
169
+ const updatesRequired = changeset.updated.filter(
170
+ (domain) => domain.modified
171
+ );
172
+ if (updatesRequired.length > 0) {
173
+ // find out which scripts the conflict domains are already attached to
174
+ // so we can provide that in the confirmation prompt
175
+ const existing = await Promise.all(
176
+ updatesRequired.map((domain) =>
177
+ fetchResult<CustomDomain>(
178
+ `/accounts/${accountId}/workers/domains/records/${domain.id}`
179
+ )
180
+ )
181
+ );
182
+ const existingRendered = existing
183
+ .map(
184
+ (domain) =>
185
+ `\t• ${domain.hostname} (used as a domain for "${domain.service}")`
186
+ )
187
+ .join("\n");
188
+ const message = `Custom Domains already exist for these domains:
189
+ ${existingRendered}
190
+ Update them to point to this script instead?`;
191
+ if (!(await confirm(message))) return fail();
192
+ config.override_existing_origin = true;
193
+ }
194
+
195
+ if (changeset.conflicting.length > 0) {
196
+ const conflicitingRendered = changeset.conflicting
197
+ .map((domain) => `\t• ${domain.hostname}`)
198
+ .join("\n");
199
+ const message = `You already have DNS records that conflict for these Custom Domains:
200
+ ${conflicitingRendered}
201
+ Update them to point to this script instead?`;
202
+ if (!(await confirm(message))) return fail();
203
+ config.override_existing_dns_record = true;
204
+ }
205
+ }
206
+
207
+ // publish to domains
208
+ await fetchResult(`${workerUrl}/domains/records`, {
209
+ method: "PUT",
210
+ body: JSON.stringify({ ...config, origins }),
211
+ headers: {
212
+ "Content-Type": "application/json",
213
+ },
214
+ });
215
+
216
+ return domains.map((domain) => renderRoute(domain));
35
217
  }
36
218
 
37
219
  export default async function publish(props: Props): Promise<void> {
38
- // TODO: warn if git/hg has uncommitted changes
39
- const { config, accountId } = props;
40
-
41
- assert(
42
- props.compatibilityDate || config.compatibility_date,
43
- "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."
44
- );
45
-
46
- const triggers = props.triggers || config.triggers?.crons;
47
- const routes =
48
- props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
49
-
50
- const deployToWorkersDev = config.workers_dev;
51
-
52
- const jsxFactory = props.jsxFactory || config.jsx_factory;
53
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
54
-
55
- const scriptName = props.name;
56
- assert(
57
- scriptName,
58
- '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>"`'
59
- );
60
-
61
- assert(
62
- !config.site || config.site.bucket,
63
- "A [site] definition requires a `bucket` field with a path to the site's public directory."
64
- );
65
-
66
- const destination = await tmp.dir({ unsafeCleanup: true });
67
- try {
68
- const envName = props.env ?? "production";
69
-
70
- const { format } = props.entry;
71
-
72
- if (props.experimentalPublic && format === "service-worker") {
73
- // TODO: check config too
74
- throw new Error(
75
- "You cannot publish in the service worker format with a public directory."
76
- );
77
- }
78
-
79
- if (config.wasm_modules && format === "modules") {
80
- throw new Error(
81
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
82
- );
83
- }
84
-
85
- if (config.text_blobs && format === "modules") {
86
- throw new Error(
87
- "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[build.upload.rules]` in your wrangler.toml"
88
- );
89
- }
90
-
91
- const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
92
- props.entry,
93
- destination.path,
94
- {
95
- serveAssetsFromWorker: props.experimentalPublic,
96
- jsxFactory,
97
- jsxFragment,
98
- rules: props.rules,
99
- }
100
- );
101
-
102
- const content = readFileSync(resolvedEntryPointPath, {
103
- encoding: "utf-8",
104
- });
105
-
106
- // if config.migrations
107
- // get current migration tag
108
- let migrations;
109
- if (config.migrations.length > 0) {
110
- const scripts = await fetchResult<
111
- { id: string; migration_tag: string }[]
112
- >(`/accounts/${accountId}/workers/scripts`);
113
- const script = scripts.find(({ id }) => id === scriptName);
114
- if (script?.migration_tag) {
115
- // was already published once
116
- const foundIndex = config.migrations.findIndex(
117
- (migration) => migration.tag === script.migration_tag
118
- );
119
- if (foundIndex === -1) {
120
- console.warn(
121
- `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...`
122
- );
123
- migrations = {
124
- old_tag: script.migration_tag,
125
- new_tag: config.migrations[config.migrations.length - 1].tag,
126
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
127
- };
128
- } else {
129
- migrations = {
130
- old_tag: script.migration_tag,
131
- new_tag: config.migrations[config.migrations.length - 1].tag,
132
- steps: config.migrations
133
- .slice(foundIndex + 1)
134
- .map(({ tag: _tag, ...rest }) => rest),
135
- };
136
- }
137
- } else {
138
- migrations = {
139
- new_tag: config.migrations[config.migrations.length - 1].tag,
140
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
141
- };
142
- }
143
- }
144
-
145
- const assets = await syncAssets(
146
- accountId,
147
- // When we're using the newer service environments, we wouldn't
148
- // have added the env name on to the script name. However, we must
149
- // include it in the kv namespace name regardless (since there's no
150
- // concept of service environments for kv namespaces yet).
151
- scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
152
- props.assetPaths,
153
- false
154
- );
155
-
156
- const bindings: CfWorkerInit["bindings"] = {
157
- kv_namespaces: (config.kv_namespaces || []).concat(
158
- assets.namespace
159
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
160
- : []
161
- ),
162
- vars: config.vars,
163
- wasm_modules: config.wasm_modules,
164
- text_blobs: {
165
- ...config.text_blobs,
166
- ...(assets.manifest &&
167
- format === "service-worker" && {
168
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
169
- }),
170
- },
171
- durable_objects: config.durable_objects,
172
- r2_buckets: config.r2_buckets,
173
- unsafe: config.unsafe?.bindings,
174
- };
175
-
176
- if (assets.manifest) {
177
- modules.push({
178
- name: "__STATIC_CONTENT_MANIFEST",
179
- content: JSON.stringify(assets.manifest),
180
- type: "text",
181
- });
182
- }
183
-
184
- const worker: CfWorkerInit = {
185
- name: scriptName,
186
- main: {
187
- name: path.basename(resolvedEntryPointPath),
188
- content: content,
189
- type: bundleType,
190
- },
191
- bindings,
192
- migrations,
193
- modules,
194
- compatibility_date: props.compatibilityDate ?? config.compatibility_date,
195
- compatibility_flags:
196
- props.compatibilityFlags ?? config.compatibility_flags,
197
- usage_model: config.usage_model,
198
- };
199
-
200
- const start = Date.now();
201
- const notProd = !props.legacyEnv && props.env;
202
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
203
- const workerUrl = notProd
204
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
205
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
206
-
207
- // Upload the script so it has time to propagate.
208
- const { available_on_subdomain } = await fetchResult(
209
- workerUrl,
210
- {
211
- method: "PUT",
212
- body: createWorkerUploadForm(worker),
213
- },
214
- new URLSearchParams({ available_on_subdomain: "true" })
215
- );
216
-
217
- const uploadMs = Date.now() - start;
218
- const deployments: Promise<string[]>[] = [];
219
-
220
- if (deployToWorkersDev) {
221
- // Deploy to a subdomain of `workers.dev`
222
- const userSubdomain = await getSubdomain(accountId);
223
- const scriptURL =
224
- props.legacyEnv || !props.env
225
- ? `${scriptName}.${userSubdomain}.workers.dev`
226
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
227
- if (!available_on_subdomain) {
228
- // Enable the `workers.dev` subdomain.
229
- deployments.push(
230
- fetchResult(`${workerUrl}/subdomain`, {
231
- method: "POST",
232
- body: JSON.stringify({ enabled: true }),
233
- headers: {
234
- "Content-Type": "application/json",
235
- },
236
- })
237
- .then(() => [scriptURL])
238
- // Add a delay when the subdomain is first created.
239
- // This is to prevent an issue where a negative cache-hit
240
- // causes the subdomain to be unavailable for 30 seconds.
241
- // This is a temporary measure until we fix this on the edge.
242
- .then(async (url) => {
243
- await sleep(3000);
244
- return url;
245
- })
246
- );
247
- } else {
248
- deployments.push(Promise.resolve([scriptURL]));
249
- }
250
- } else {
251
- // Disable the workers.dev deployment
252
- await fetchResult(`${workerUrl}/subdomain`, {
253
- method: "POST",
254
- body: JSON.stringify({ enabled: false }),
255
- headers: {
256
- "Content-Type": "application/json",
257
- },
258
- });
259
- }
260
-
261
- console.log("Uploaded", workerName, formatTime(uploadMs));
262
-
263
- // Update routing table for the script.
264
- if (routes.length > 0) {
265
- deployments.push(
266
- fetchResult(`${workerUrl}/routes`, {
267
- // TODO: PATCH will not delete previous routes on this script,
268
- // whereas PUT will. We need to decide on the default behaviour
269
- // and how to configure it.
270
- method: "PUT",
271
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
272
- headers: {
273
- "Content-Type": "application/json",
274
- },
275
- }).then(() => {
276
- if (routes.length > 10) {
277
- return routes
278
- .slice(0, 9)
279
- .map(String)
280
- .concat([`...and ${routes.length - 10} more routes`]);
281
- }
282
- return routes.map(String);
283
- })
284
- );
285
- }
286
-
287
- // Configure any schedules for the script.
288
- // TODO: rename this to `schedules`?
289
- if (triggers && triggers.length) {
290
- deployments.push(
291
- fetchResult(`${workerUrl}/schedules`, {
292
- // TODO: Unlike routes, this endpoint does not support PATCH.
293
- // So technically, this will override any previous schedules.
294
- // We should change the endpoint to support PATCH.
295
- method: "PUT",
296
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
297
- headers: {
298
- "Content-Type": "application/json",
299
- },
300
- }).then(() => triggers.map(String))
301
- );
302
- }
303
-
304
- const targets = await Promise.all(deployments);
305
- const deployMs = Date.now() - start - uploadMs;
306
-
307
- if (deployments.length > 0) {
308
- console.log("Published", workerName, formatTime(deployMs));
309
- for (const target of targets.flat()) {
310
- console.log(" ", target);
311
- }
312
- } else {
313
- console.log("No publish targets for", workerName, formatTime(deployMs));
314
- }
315
- } finally {
316
- await destination.cleanup();
317
- }
220
+ // TODO: warn if git/hg has uncommitted changes
221
+ const { config, accountId } = props;
222
+
223
+ if (!(props.compatibilityDate || config.compatibility_date)) {
224
+ const compatibilityDateStr = `${new Date().getFullYear()}-${(
225
+ new Date().getMonth() + ""
226
+ ).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
227
+
228
+ throw new Error(`A compatibility_date is required when publishing. Add the following to your wrangler.toml file:.
229
+ \`\`\`
230
+ compatibility_date = "${compatibilityDateStr}"
231
+ \`\`\`
232
+ Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
233
+ See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
234
+ }
235
+
236
+ const triggers = props.triggers || config.triggers?.crons;
237
+ const routes =
238
+ props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
239
+ const routesOnly: Array<Route> = [];
240
+ const customDomainsOnly: Array<RouteObject> = [];
241
+ for (const route of routes) {
242
+ if (typeof route !== "string" && route.custom_domain) {
243
+ if (route.pattern.includes("*")) {
244
+ throw new Error(
245
+ `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
246
+ );
247
+ }
248
+ if (route.pattern.includes("/")) {
249
+ throw new Error(
250
+ `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
251
+ );
252
+ }
253
+ customDomainsOnly.push(route);
254
+ } else {
255
+ routesOnly.push(route);
256
+ }
257
+ }
258
+
259
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
260
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
261
+
262
+ const jsxFactory = props.jsxFactory || config.jsx_factory;
263
+ const jsxFragment = props.jsxFragment || config.jsx_fragment;
264
+
265
+ const minify = props.minify ?? config.minify;
266
+
267
+ const nodeCompat = props.nodeCompat ?? config.node_compat;
268
+ if (nodeCompat) {
269
+ logger.warn(
270
+ "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."
271
+ );
272
+ }
273
+
274
+ // Warn if user tries minify or node-compat with no-bundle
275
+ if (props.noBundle && minify) {
276
+ logger.warn(
277
+ "`--minify` and `--no-bundle` can't be used together. If you want to minify your Worker and disable Wrangler's bundling, please minify as part of your own bundling process."
278
+ );
279
+ }
280
+
281
+ if (props.noBundle && nodeCompat) {
282
+ logger.warn(
283
+ "`--node-compat` and `--no-bundle` can't be used together. If you want to polyfill Node.js built-ins and disable Wrangler's bundling, please polyfill as part of your own bundling process."
284
+ );
285
+ }
286
+
287
+ const scriptName = props.name;
288
+ assert(
289
+ scriptName,
290
+ '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>"`'
291
+ );
292
+
293
+ assert(
294
+ !config.site || config.site.bucket,
295
+ "A [site] definition requires a `bucket` field with a path to the site's assets directory."
296
+ );
297
+
298
+ if (props.outDir) {
299
+ // we're using a custom output directory,
300
+ // so let's first ensure it exists
301
+ mkdirSync(props.outDir, { recursive: true });
302
+ // add a README
303
+ const readmePath = path.join(props.outDir, "README.md");
304
+ writeFileSync(
305
+ readmePath,
306
+ `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
307
+ );
308
+ }
309
+
310
+ const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
311
+ const envName = props.env ?? "production";
312
+
313
+ const start = Date.now();
314
+ const notProd = Boolean(!props.legacyEnv && props.env);
315
+ const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
316
+ const workerUrl = notProd
317
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
318
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`;
319
+
320
+ let available_on_subdomain; // we'll set this later
321
+
322
+ const { format } = props.entry;
323
+
324
+ if (
325
+ !props.isWorkersSite &&
326
+ Boolean(props.assetPaths) &&
327
+ format === "service-worker"
328
+ ) {
329
+ throw new Error(
330
+ "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/"
331
+ );
332
+ }
333
+
334
+ if (config.wasm_modules && format === "modules") {
335
+ throw new Error(
336
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
337
+ );
338
+ }
339
+
340
+ if (config.text_blobs && format === "modules") {
341
+ throw new Error(
342
+ "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"
343
+ );
344
+ }
345
+
346
+ if (config.data_blobs && format === "modules") {
347
+ throw new Error(
348
+ "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"
349
+ );
350
+ }
351
+ try {
352
+ if (props.noBundle) {
353
+ // if we're not building, let's just copy the entry to the destination directory
354
+ const destinationDir =
355
+ typeof destination === "string" ? destination : destination.path;
356
+ mkdirSync(destinationDir, { recursive: true });
357
+ writeFileSync(
358
+ path.join(destinationDir, path.basename(props.entry.file)),
359
+ readFileSync(props.entry.file, "utf-8")
360
+ );
361
+ }
362
+
363
+ const {
364
+ modules,
365
+ resolvedEntryPointPath,
366
+ bundleType,
367
+ }: Awaited<ReturnType<typeof bundleWorker>> = props.noBundle
368
+ ? // we can skip the whole bundling step and mock a bundle here
369
+ {
370
+ modules: [],
371
+ resolvedEntryPointPath: props.entry.file,
372
+ bundleType: props.entry.format === "modules" ? "esm" : "commonjs",
373
+ stop: undefined,
374
+ }
375
+ : await bundleWorker(
376
+ props.entry,
377
+ typeof destination === "string" ? destination : destination.path,
378
+ {
379
+ serveAssetsFromWorker:
380
+ !props.isWorkersSite && Boolean(props.assetPaths),
381
+ jsxFactory,
382
+ jsxFragment,
383
+ rules: props.rules,
384
+ tsconfig: props.tsconfig ?? config.tsconfig,
385
+ minify,
386
+ nodeCompat,
387
+ define: { ...config.define, ...props.defines },
388
+ checkFetch: false,
389
+ assets: config.assets && {
390
+ ...config.assets,
391
+ // enable the cache when publishing
392
+ bypassCache: false,
393
+ },
394
+ services: config.services,
395
+ // We don't set workerDefinitions here,
396
+ // because we don't want to apply the dev-time
397
+ // facades on top of it
398
+ workerDefinitions: undefined,
399
+ firstPartyWorkerDevFacade: false,
400
+ }
401
+ );
402
+
403
+ const content = readFileSync(resolvedEntryPointPath, {
404
+ encoding: "utf-8",
405
+ });
406
+
407
+ // durable object migrations
408
+ const migrations = !props.dryRun
409
+ ? await getMigrationsToUpload(scriptName, {
410
+ accountId,
411
+ config,
412
+ legacyEnv: props.legacyEnv,
413
+ env: props.env,
414
+ })
415
+ : undefined;
416
+
417
+ const assets = await syncAssets(
418
+ accountId,
419
+ // When we're using the newer service environments, we wouldn't
420
+ // have added the env name on to the script name. However, we must
421
+ // include it in the kv namespace name regardless (since there's no
422
+ // concept of service environments for kv namespaces yet).
423
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
424
+ props.assetPaths,
425
+ false,
426
+ props.dryRun
427
+ );
428
+
429
+ const bindings: CfWorkerInit["bindings"] = {
430
+ kv_namespaces: (config.kv_namespaces || []).concat(
431
+ assets.namespace
432
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
433
+ : []
434
+ ),
435
+ vars: { ...config.vars, ...props.vars },
436
+ wasm_modules: config.wasm_modules,
437
+ text_blobs: {
438
+ ...config.text_blobs,
439
+ ...(assets.manifest &&
440
+ format === "service-worker" && {
441
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
442
+ }),
443
+ },
444
+ data_blobs: config.data_blobs,
445
+ durable_objects: config.durable_objects,
446
+ r2_buckets: config.r2_buckets,
447
+ services: config.services,
448
+ dispatch_namespaces: config.dispatch_namespaces,
449
+ logfwdr: config.logfwdr,
450
+ unsafe: config.unsafe?.bindings,
451
+ };
452
+
453
+ if (assets.manifest) {
454
+ modules.push({
455
+ name: "__STATIC_CONTENT_MANIFEST",
456
+ content: JSON.stringify(assets.manifest),
457
+ type: "text",
458
+ });
459
+ }
460
+
461
+ const worker: CfWorkerInit = {
462
+ name: scriptName,
463
+ main: {
464
+ name: path.basename(resolvedEntryPointPath),
465
+ content: content,
466
+ type: bundleType,
467
+ },
468
+ bindings,
469
+ migrations,
470
+ modules,
471
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
472
+ compatibility_flags:
473
+ props.compatibilityFlags ?? config.compatibility_flags,
474
+ usage_model: config.usage_model,
475
+ keep_bindings: true,
476
+ };
477
+
478
+ void printBundleSize(
479
+ { name: path.basename(resolvedEntryPointPath), content: content },
480
+ modules
481
+ );
482
+
483
+ const withoutStaticAssets = {
484
+ ...bindings,
485
+ kv_namespaces: config.kv_namespaces,
486
+ text_blobs: config.text_blobs,
487
+ };
488
+
489
+ // mask anything that was overridden in cli args
490
+ // so that we don't log potential secrets into the terminal
491
+ const maskedVars = { ...withoutStaticAssets.vars };
492
+ for (const key of Object.keys(maskedVars)) {
493
+ if (maskedVars[key] !== config.vars[key]) {
494
+ // This means it was overridden in cli args
495
+ // so let's mask it
496
+ maskedVars[key] = "(hidden)";
497
+ }
498
+ }
499
+
500
+ printBindings({ ...withoutStaticAssets, vars: maskedVars });
501
+
502
+ if (!props.dryRun) {
503
+ // Upload the script so it has time to propagate.
504
+ // We can also now tell whether available_on_subdomain is set
505
+ const result = await fetchResult<{
506
+ available_on_subdomain: boolean;
507
+ id: string | null;
508
+ etag: string | null;
509
+ pipeline_hash: string | null;
510
+ }>(
511
+ workerUrl,
512
+ {
513
+ method: "PUT",
514
+ body: createWorkerUploadForm(worker),
515
+ headers: await getMetricsUsageHeaders(config.send_metrics),
516
+ },
517
+ new URLSearchParams({
518
+ include_subdomain_availability: "true",
519
+ // pass excludeScript so the whole body of the
520
+ // script doesn't get included in the response
521
+ excludeScript: "true",
522
+ })
523
+ );
524
+
525
+ available_on_subdomain = result.available_on_subdomain;
526
+
527
+ if (config.first_party_worker) {
528
+ // Print some useful information returned after publishing
529
+ // Not all fields will be populated for every worker
530
+ // These fields are likely to be scraped by tools, so do not rename
531
+ if (result.id) logger.log("Worker ID: ", result.id);
532
+ if (result.etag) logger.log("Worker ETag: ", result.etag);
533
+ if (result.pipeline_hash)
534
+ logger.log("Worker PipelineHash: ", result.pipeline_hash);
535
+ }
536
+ }
537
+ } finally {
538
+ if (typeof destination !== "string") {
539
+ // this means we're using a temp dir,
540
+ // so let's clean up before we proceed
541
+ await destination.cleanup();
542
+ }
543
+ }
544
+
545
+ if (props.dryRun) {
546
+ logger.log(`--dry-run: exiting now.`);
547
+ return;
548
+ }
549
+ assert(accountId, "Missing accountId");
550
+
551
+ const uploadMs = Date.now() - start;
552
+ const deployments: Promise<string[]>[] = [];
553
+
554
+ if (deployToWorkersDev) {
555
+ // Deploy to a subdomain of `workers.dev`
556
+ const userSubdomain = await getSubdomain(accountId);
557
+ const scriptURL =
558
+ props.legacyEnv || !props.env
559
+ ? `${scriptName}.${userSubdomain}.workers.dev`
560
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
561
+ if (!available_on_subdomain) {
562
+ // Enable the `workers.dev` subdomain.
563
+ deployments.push(
564
+ fetchResult(`${workerUrl}/subdomain`, {
565
+ method: "POST",
566
+ body: JSON.stringify({ enabled: true }),
567
+ headers: {
568
+ "Content-Type": "application/json",
569
+ },
570
+ })
571
+ .then(() => [scriptURL])
572
+ // Add a delay when the subdomain is first created.
573
+ // This is to prevent an issue where a negative cache-hit
574
+ // causes the subdomain to be unavailable for 30 seconds.
575
+ // This is a temporary measure until we fix this on the edge.
576
+ .then(async (url) => {
577
+ await sleep(3000);
578
+ return url;
579
+ })
580
+ );
581
+ } else {
582
+ deployments.push(Promise.resolve([scriptURL]));
583
+ }
584
+ } else {
585
+ if (available_on_subdomain) {
586
+ // Disable the workers.dev deployment
587
+ await fetchResult(`${workerUrl}/subdomain`, {
588
+ method: "POST",
589
+ body: JSON.stringify({ enabled: false }),
590
+ headers: {
591
+ "Content-Type": "application/json",
592
+ },
593
+ });
594
+ }
595
+ }
596
+
597
+ logger.log("Uploaded", workerName, formatTime(uploadMs));
598
+
599
+ // Update routing table for the script.
600
+ if (routesOnly.length > 0) {
601
+ deployments.push(
602
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
603
+ if (routesOnly.length > 10) {
604
+ return routesOnly
605
+ .slice(0, 9)
606
+ .map((route) => renderRoute(route))
607
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
608
+ }
609
+ return routesOnly.map((route) => renderRoute(route));
610
+ })
611
+ );
612
+ }
613
+
614
+ // Update custom domains for the script
615
+ if (customDomainsOnly.length > 0) {
616
+ deployments.push(
617
+ publishCustomDomains(workerUrl, accountId, customDomainsOnly)
618
+ );
619
+ }
620
+
621
+ // Configure any schedules for the script.
622
+ // TODO: rename this to `schedules`?
623
+ if (triggers && triggers.length) {
624
+ deployments.push(
625
+ fetchResult(`${workerUrl}/schedules`, {
626
+ // Note: PUT will override previous schedules on this script.
627
+ method: "PUT",
628
+ body: JSON.stringify(triggers.map((cron) => ({ cron }))),
629
+ headers: {
630
+ "Content-Type": "application/json",
631
+ },
632
+ }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
633
+ );
634
+ }
635
+
636
+ const targets = await Promise.all(deployments);
637
+ const deployMs = Date.now() - start - uploadMs;
638
+
639
+ if (deployments.length > 0) {
640
+ logger.log("Published", workerName, formatTime(deployMs));
641
+ for (const target of targets.flat()) {
642
+ // Append protocol only on workers.dev domains
643
+ logger.log(
644
+ " ",
645
+ (target.endsWith("workers.dev") ? "https://" : "") + target
646
+ );
647
+ }
648
+ } else {
649
+ logger.log("No publish targets for", workerName, formatTime(deployMs));
650
+ }
318
651
  }
319
652
 
320
653
  function formatTime(duration: number) {
321
- return `(${(duration / 1000).toFixed(2)} sec)`;
654
+ return `(${(duration / 1000).toFixed(2)} sec)`;
322
655
  }
323
656
 
324
657
  async function getSubdomain(accountId: string): Promise<string> {
325
- try {
326
- const { subdomain } = await fetchResult(
327
- `/accounts/${accountId}/workers/subdomain`
328
- );
329
- return subdomain;
330
- } catch (e) {
331
- const error = e as { code?: number };
332
- if (typeof error === "object" && !!error && error.code === 10007) {
333
- // 10007 error code: not found
334
- // https://api.cloudflare.com/#worker-subdomain-get-subdomain
335
-
336
- const errorMessage =
337
- "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
338
- const solutionMessage =
339
- "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
340
- const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
341
-
342
- throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
343
- } else {
344
- throw e;
345
- }
346
- }
658
+ try {
659
+ const { subdomain } = await fetchResult(
660
+ `/accounts/${accountId}/workers/subdomain`
661
+ );
662
+ return subdomain;
663
+ } catch (e) {
664
+ const error = e as { code?: number };
665
+ if (typeof error === "object" && !!error && error.code === 10007) {
666
+ // 10007 error code: not found
667
+ // https://api.cloudflare.com/#worker-subdomain-get-subdomain
668
+
669
+ const errorMessage =
670
+ "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
671
+ const solutionMessage =
672
+ "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
673
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
674
+
675
+ throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
676
+ } else {
677
+ throw e;
678
+ }
679
+ }
680
+ }
681
+
682
+ /**
683
+ * Associate the newly deployed Worker with the given routes.
684
+ */
685
+ async function publishRoutes(
686
+ routes: Route[],
687
+ {
688
+ workerUrl,
689
+ scriptName,
690
+ notProd,
691
+ }: { workerUrl: string; scriptName: string; notProd: boolean }
692
+ ): Promise<string[]> {
693
+ try {
694
+ return await fetchResult(`${workerUrl}/routes`, {
695
+ // Note: PUT will delete previous routes on this script.
696
+ method: "PUT",
697
+ body: JSON.stringify(
698
+ routes.map((route) =>
699
+ typeof route !== "object" ? { pattern: route } : route
700
+ )
701
+ ),
702
+ headers: {
703
+ "Content-Type": "application/json",
704
+ },
705
+ });
706
+ } catch (e) {
707
+ if (isAuthenticationError(e)) {
708
+ // An authentication error is probably due to a known issue,
709
+ // where the user is logged in via an API token that does not have "All Zones".
710
+ return await publishRoutesFallback(routes, { scriptName, notProd });
711
+ } else {
712
+ throw e;
713
+ }
714
+ }
715
+ }
716
+
717
+ /**
718
+ * Try updating routes for the Worker using a less optimal zone-based API.
719
+ *
720
+ * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
721
+ */
722
+ async function publishRoutesFallback(
723
+ routes: Route[],
724
+ { scriptName, notProd }: { scriptName: string; notProd: boolean }
725
+ ) {
726
+ if (notProd) {
727
+ throw new Error(
728
+ "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
729
+ "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
730
+ );
731
+ }
732
+ logger.warn(
733
+ "The current authentication token does not have 'All Zones' permissions.\n" +
734
+ "Falling back to using the zone-based API endpoint to update each route individually.\n" +
735
+ "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
736
+ "Existing routes for this Worker in such zones will not be deleted."
737
+ );
738
+
739
+ const deployedRoutes: string[] = [];
740
+
741
+ // Collect the routes (and their zones) that will be deployed.
742
+ const activeZones = new Map<string, string>();
743
+ const routesToDeploy = new Map<string, string>();
744
+ for (const route of routes) {
745
+ const zone = await getZoneForRoute(route);
746
+ if (zone) {
747
+ activeZones.set(zone.id, zone.host);
748
+ routesToDeploy.set(
749
+ typeof route === "string" ? route : route.pattern,
750
+ zone.id
751
+ );
752
+ }
753
+ }
754
+
755
+ // Collect the routes that are already deployed.
756
+ const allRoutes = new Map<string, string>();
757
+ const alreadyDeployedRoutes = new Set<string>();
758
+ for (const [zone, host] of activeZones) {
759
+ try {
760
+ for (const { pattern, script } of await fetchListResult<{
761
+ pattern: string;
762
+ script: string;
763
+ }>(`/zones/${zone}/workers/routes`)) {
764
+ allRoutes.set(pattern, script);
765
+ if (script === scriptName) {
766
+ alreadyDeployedRoutes.add(pattern);
767
+ }
768
+ }
769
+ } catch (e) {
770
+ if (isAuthenticationError(e)) {
771
+ e.notes.push({
772
+ text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
773
+ });
774
+ }
775
+ throw e;
776
+ }
777
+ }
778
+
779
+ // Deploy each route that is not already deployed.
780
+ for (const [routePattern, zoneId] of routesToDeploy.entries()) {
781
+ if (allRoutes.has(routePattern)) {
782
+ const knownScript = allRoutes.get(routePattern);
783
+ if (knownScript === scriptName) {
784
+ // This route is already associated with this worker, so no need to hit the API.
785
+ alreadyDeployedRoutes.delete(routePattern);
786
+ continue;
787
+ } else {
788
+ throw new Error(
789
+ `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
790
+ );
791
+ }
792
+ }
793
+
794
+ const { pattern } = await fetchResult(`/zones/${zoneId}/workers/routes`, {
795
+ method: "POST",
796
+ body: JSON.stringify({
797
+ pattern: routePattern,
798
+ script: scriptName,
799
+ }),
800
+ headers: {
801
+ "Content-Type": "application/json",
802
+ },
803
+ });
804
+
805
+ deployedRoutes.push(pattern);
806
+ }
807
+
808
+ if (alreadyDeployedRoutes.size) {
809
+ logger.warn(
810
+ "Previously deployed routes:\n" +
811
+ "The following routes were already associated with this worker, and have not been deleted:\n" +
812
+ [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
813
+ "If these routes are not wanted then you can remove them in the dashboard."
814
+ );
815
+ }
816
+
817
+ return deployedRoutes;
818
+ }
819
+
820
+ function isAuthenticationError(e: unknown): e is ParseError {
821
+ return e instanceof ParseError && (e as { code?: number }).code === 10000;
347
822
  }