wrangler 0.0.0-e64812e → 0.0.0-e7a0cd5b

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 (291) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +150 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1451 -21
  5. package/package.json +190 -152
  6. package/src/__tests__/access.test.ts +25 -0
  7. package/src/__tests__/api-dev.test.ts +209 -0
  8. package/src/__tests__/api-devregistry.test.js +57 -0
  9. package/src/__tests__/api.test.ts +80 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +4017 -3363
  13. package/src/__tests__/d1.test.ts +72 -0
  14. package/src/__tests__/delete.test.ts +230 -0
  15. package/src/__tests__/deployments.test.ts +95 -0
  16. package/src/__tests__/dev.test.tsx +1480 -951
  17. package/src/__tests__/dialogs.test.tsx +40 -0
  18. package/src/__tests__/generate.test.ts +235 -0
  19. package/src/__tests__/get-host-from-url.test.ts +16 -0
  20. package/src/__tests__/guess-worker-format.test.ts +68 -68
  21. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  22. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  23. package/src/__tests__/helpers/mock-bin.ts +20 -20
  24. package/src/__tests__/helpers/mock-cfetch.ts +216 -94
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  28. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  29. package/src/__tests__/helpers/mock-istty.ts +65 -18
  30. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  31. package/src/__tests__/helpers/mock-kv.ts +27 -27
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
  33. package/src/__tests__/helpers/mock-process.ts +39 -0
  34. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  35. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  36. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  37. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  38. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  39. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  40. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  41. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  42. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  43. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  44. package/src/__tests__/helpers/msw/index.ts +21 -0
  45. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  46. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  47. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  48. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  52. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  53. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  54. package/src/__tests__/https-options.test.ts +142 -109
  55. package/src/__tests__/index.test.ts +239 -233
  56. package/src/__tests__/init.test.ts +2869 -1603
  57. package/src/__tests__/jest.setup.ts +159 -34
  58. package/src/__tests__/kv.test.ts +1660 -1466
  59. package/src/__tests__/logger.test.ts +100 -74
  60. package/src/__tests__/metrics.test.ts +450 -0
  61. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  62. package/src/__tests__/middleware.test.ts +726 -0
  63. package/src/__tests__/package-manager.test.ts +303 -303
  64. package/src/__tests__/pages.test.ts +2204 -735
  65. package/src/__tests__/parse.test.ts +252 -252
  66. package/src/__tests__/paths.test.ts +39 -0
  67. package/src/__tests__/publish.test.ts +7543 -5351
  68. package/src/__tests__/pubsub.test.ts +370 -0
  69. package/src/__tests__/queues.test.ts +371 -0
  70. package/src/__tests__/r2.test.ts +371 -228
  71. package/src/__tests__/route.test.ts +18 -18
  72. package/src/__tests__/secret.test.ts +622 -459
  73. package/src/__tests__/tail.test.ts +677 -567
  74. package/src/__tests__/test-old-node-version.js +31 -0
  75. package/src/__tests__/type-generation.test.ts +217 -0
  76. package/src/__tests__/user.test.ts +140 -116
  77. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  78. package/src/__tests__/validate-dev-props.test.ts +56 -0
  79. package/src/__tests__/version.test.ts +35 -0
  80. package/src/__tests__/whoami.test.tsx +264 -91
  81. package/src/__tests__/worker-namespace.test.ts +326 -0
  82. package/src/abort.d.ts +1 -1
  83. package/src/api/dev.ts +208 -0
  84. package/src/api/index.ts +2 -0
  85. package/src/bundle-reporter.tsx +68 -0
  86. package/src/bundle.ts +746 -161
  87. package/src/cfetch/index.ts +120 -81
  88. package/src/cfetch/internal.ts +209 -91
  89. package/src/cli.ts +23 -8
  90. package/src/config/config.ts +236 -195
  91. package/src/config/diagnostics.ts +61 -61
  92. package/src/config/environment.ts +500 -357
  93. package/src/config/index.ts +310 -193
  94. package/src/config/validation-helpers.ts +379 -357
  95. package/src/config/validation.ts +1941 -1367
  96. package/src/config-cache.ts +81 -41
  97. package/src/create-worker-preview.ts +239 -142
  98. package/src/create-worker-upload-form.ts +305 -238
  99. package/src/d1/backups.tsx +218 -0
  100. package/src/d1/create.tsx +54 -0
  101. package/src/d1/delete.tsx +56 -0
  102. package/src/d1/execute.tsx +299 -0
  103. package/src/d1/formatTimeAgo.ts +14 -0
  104. package/src/d1/index.ts +76 -0
  105. package/src/d1/list.tsx +48 -0
  106. package/src/d1/options.ts +12 -0
  107. package/src/d1/types.tsx +14 -0
  108. package/src/d1/utils.ts +39 -0
  109. package/src/delete.ts +108 -0
  110. package/src/deployments.ts +74 -0
  111. package/src/deprecated/index.ts +438 -0
  112. package/src/dev/dev-vars.ts +20 -17
  113. package/src/dev/dev.tsx +520 -352
  114. package/src/dev/get-local-persistence-path.tsx +31 -0
  115. package/src/dev/local.tsx +697 -298
  116. package/src/dev/remote.tsx +591 -215
  117. package/src/dev/start-server.ts +513 -0
  118. package/src/dev/use-esbuild.ts +183 -97
  119. package/src/dev/validate-dev-props.ts +31 -0
  120. package/src/dev-registry.tsx +201 -0
  121. package/src/dev.tsx +869 -0
  122. package/src/dialogs.tsx +126 -98
  123. package/src/dispatch-namespace.ts +207 -0
  124. package/src/durable.ts +87 -87
  125. package/src/entry.ts +235 -228
  126. package/src/environment-variables.ts +38 -23
  127. package/src/errors.ts +6 -6
  128. package/src/git-client.ts +124 -0
  129. package/src/global-wrangler-config-path.ts +26 -0
  130. package/src/https-options.ts +84 -80
  131. package/src/index.tsx +627 -2807
  132. package/src/init.ts +970 -0
  133. package/src/inspect.ts +698 -593
  134. package/src/intl-polyfill.d.ts +123 -123
  135. package/src/is-ci.ts +14 -0
  136. package/src/is-interactive.ts +16 -0
  137. package/src/kv/helpers.ts +430 -0
  138. package/src/kv/index.ts +596 -0
  139. package/src/logger.ts +67 -41
  140. package/src/metrics/index.ts +5 -0
  141. package/src/metrics/metrics-config.ts +239 -0
  142. package/src/metrics/metrics-dispatcher.ts +96 -0
  143. package/src/metrics/metrics-usage-headers.ts +24 -0
  144. package/src/metrics/send-event.ts +94 -0
  145. package/src/miniflare-cli/assets.ts +215 -0
  146. package/src/miniflare-cli/index.ts +205 -33
  147. package/src/miniflare-cli/request-context.ts +18 -18
  148. package/src/module-collection.ts +221 -212
  149. package/src/open-in-browser.ts +4 -6
  150. package/src/package-manager.ts +173 -128
  151. package/src/pages/build.tsx +238 -0
  152. package/src/pages/constants.ts +18 -0
  153. package/src/pages/deployments.tsx +106 -0
  154. package/src/pages/dev.tsx +693 -0
  155. package/src/pages/errors.ts +66 -0
  156. package/src/pages/functions/buildPlugin.ts +110 -0
  157. package/src/pages/functions/buildWorker.ts +156 -0
  158. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  159. package/src/pages/functions/filepath-routing.ts +189 -0
  160. package/src/pages/functions/identifiers.ts +78 -0
  161. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  162. package/src/pages/functions/routes-consolidation.ts +73 -0
  163. package/src/pages/functions/routes-transformation.test.ts +282 -0
  164. package/src/pages/functions/routes-transformation.ts +115 -0
  165. package/src/pages/functions/routes-validation.test.ts +403 -0
  166. package/src/pages/functions/routes-validation.ts +202 -0
  167. package/src/pages/functions/routes.ts +151 -0
  168. package/src/pages/functions.tsx +82 -0
  169. package/src/pages/hash.tsx +13 -0
  170. package/src/pages/index.tsx +94 -0
  171. package/src/pages/projects.tsx +169 -0
  172. package/src/pages/publish.tsx +436 -0
  173. package/src/pages/types.ts +49 -0
  174. package/src/pages/upload.tsx +425 -0
  175. package/src/pages/utils.ts +12 -0
  176. package/src/parse.ts +209 -125
  177. package/src/paths.ts +53 -8
  178. package/src/proxy.ts +618 -394
  179. package/src/publish/index.ts +270 -0
  180. package/src/publish/publish.ts +1035 -0
  181. package/src/pubsub/index.ts +286 -0
  182. package/src/pubsub/pubsub-commands.tsx +624 -0
  183. package/src/queues/cli/commands/consumer/add.ts +71 -0
  184. package/src/queues/cli/commands/consumer/index.ts +22 -0
  185. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  186. package/src/queues/cli/commands/create.ts +25 -0
  187. package/src/queues/cli/commands/delete.ts +26 -0
  188. package/src/queues/cli/commands/index.ts +33 -0
  189. package/src/queues/cli/commands/list.ts +25 -0
  190. package/src/queues/client.ts +135 -0
  191. package/src/r2/helpers.ts +131 -0
  192. package/src/r2/index.ts +277 -0
  193. package/src/routes.ts +140 -0
  194. package/src/secret/index.ts +379 -0
  195. package/src/selfsigned.d.ts +23 -23
  196. package/src/sites.tsx +280 -203
  197. package/src/tail/createTail.ts +315 -0
  198. package/src/tail/filters.ts +108 -110
  199. package/src/tail/index.ts +211 -296
  200. package/src/tail/printing.ts +86 -46
  201. package/src/type-generation.ts +159 -0
  202. package/src/update-check.ts +11 -11
  203. package/src/user/access.ts +69 -0
  204. package/src/user/choose-account.tsx +69 -0
  205. package/src/user/env-vars.ts +46 -0
  206. package/src/user/generate-auth-url.ts +33 -0
  207. package/src/user/generate-random-state.ts +16 -0
  208. package/src/user/index.ts +3 -0
  209. package/src/user/user.tsx +1192 -0
  210. package/src/utils/collectKeyValues.ts +14 -0
  211. package/src/whoami.tsx +141 -42
  212. package/src/worker.ts +168 -106
  213. package/src/yargs-types.ts +20 -0
  214. package/src/zones.ts +191 -0
  215. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  216. package/templates/checked-fetch.js +17 -0
  217. package/templates/d1-beta-facade.js +174 -0
  218. package/templates/experimental-local-cache-stubs.js +27 -0
  219. package/templates/first-party-worker-module-facade.ts +18 -0
  220. package/templates/format-dev-errors.ts +32 -0
  221. package/templates/init-tests/test-jest-new-worker.js +25 -0
  222. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  223. package/templates/middleware/common.ts +62 -0
  224. package/templates/middleware/loader-modules.ts +84 -0
  225. package/templates/middleware/loader-sw.ts +213 -0
  226. package/templates/middleware/middleware-pretty-error.ts +40 -0
  227. package/templates/middleware/middleware-scheduled.ts +15 -0
  228. package/templates/new-worker-scheduled.js +3 -3
  229. package/templates/new-worker-scheduled.ts +15 -15
  230. package/templates/new-worker.js +3 -3
  231. package/templates/new-worker.ts +15 -15
  232. package/templates/no-op-worker.js +10 -0
  233. package/templates/pages-dev-pipeline.ts +28 -0
  234. package/templates/pages-dev-util.ts +52 -0
  235. package/templates/pages-shim.ts +9 -0
  236. package/templates/pages-template-plugin.ts +171 -0
  237. package/templates/pages-template-worker.ts +189 -0
  238. package/templates/serve-static-assets.ts +63 -0
  239. package/templates/service-bindings-module-facade.js +54 -0
  240. package/templates/service-bindings-sw-facade.js +42 -0
  241. package/templates/tsconfig.json +96 -95
  242. package/wrangler-dist/cli.d.ts +892 -0
  243. package/wrangler-dist/cli.js +145674 -108957
  244. package/pages/functions/buildPlugin.ts +0 -105
  245. package/pages/functions/buildWorker.ts +0 -151
  246. package/pages/functions/filepath-routing.ts +0 -189
  247. package/pages/functions/identifiers.ts +0 -78
  248. package/pages/functions/routes.ts +0 -156
  249. package/pages/functions/template-plugin.ts +0 -147
  250. package/pages/functions/template-worker.ts +0 -143
  251. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  252. package/src/kv.ts +0 -408
  253. package/src/miniflare-cli/enum-keys.ts +0 -17
  254. package/src/pages.tsx +0 -2038
  255. package/src/publish.ts +0 -583
  256. package/src/r2.ts +0 -50
  257. package/src/user.tsx +0 -1203
  258. package/templates/static-asset-facade.js +0 -47
  259. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  260. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  261. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  262. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  263. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  264. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  265. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  266. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  267. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  268. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  269. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  270. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  271. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  272. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  273. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  274. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  275. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  276. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  277. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  278. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  279. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  280. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  281. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  282. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  283. package/vendor/wrangler-mime/LICENSE +0 -21
  284. package/vendor/wrangler-mime/Mime.js +0 -97
  285. package/vendor/wrangler-mime/README.md +0 -187
  286. package/vendor/wrangler-mime/cli.js +0 -46
  287. package/vendor/wrangler-mime/index.js +0 -4
  288. package/vendor/wrangler-mime/lite.js +0 -4
  289. package/vendor/wrangler-mime/package.json +0 -52
  290. package/vendor/wrangler-mime/types/other.js +0 -1
  291. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -0,0 +1,1035 @@
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 chalk from "chalk";
6
+ import tmp from "tmp-promise";
7
+ import { bundleWorker } from "../bundle";
8
+ import {
9
+ printBundleSize,
10
+ printOffendingDependencies,
11
+ } from "../bundle-reporter";
12
+ import { fetchListResult, fetchResult } from "../cfetch";
13
+ import { printBindings } from "../config";
14
+ import { createWorkerUploadForm } from "../create-worker-upload-form";
15
+ import { confirm, fromDashMessagePrompt } from "../dialogs";
16
+ import { getMigrationsToUpload } from "../durable";
17
+ import { logger } from "../logger";
18
+ import { getMetricsUsageHeaders } from "../metrics";
19
+ import { ParseError } from "../parse";
20
+ import { getQueue, putConsumer } from "../queues/client";
21
+ import { getWorkersDevSubdomain } from "../routes";
22
+ import { syncAssets } from "../sites";
23
+ import { identifyD1BindingsAsBeta } from "../worker";
24
+ import { getZoneForRoute } from "../zones";
25
+ import type { FetchError } from "../cfetch";
26
+ import type { Config } from "../config";
27
+ import type {
28
+ Route,
29
+ ZoneIdRoute,
30
+ ZoneNameRoute,
31
+ CustomDomainRoute,
32
+ } from "../config/environment";
33
+ import type { DeploymentListRes } from "../deployments";
34
+ import type { Entry } from "../entry";
35
+ import type { PutConsumerBody } from "../queues/client";
36
+ import type { AssetPaths } from "../sites";
37
+ import type { CfWorkerInit } from "../worker";
38
+
39
+ type Props = {
40
+ config: Config;
41
+ accountId: string | undefined;
42
+ entry: Entry;
43
+ rules: Config["rules"];
44
+ name: string | undefined;
45
+ env: string | undefined;
46
+ compatibilityDate: string | undefined;
47
+ compatibilityFlags: string[] | undefined;
48
+ assetPaths: AssetPaths | undefined;
49
+ vars: Record<string, string> | undefined;
50
+ defines: Record<string, string> | undefined;
51
+ triggers: string[] | undefined;
52
+ routes: string[] | undefined;
53
+ legacyEnv: boolean | undefined;
54
+ jsxFactory: string | undefined;
55
+ jsxFragment: string | undefined;
56
+ tsconfig: string | undefined;
57
+ isWorkersSite: boolean;
58
+ minify: boolean | undefined;
59
+ nodeCompat: boolean | undefined;
60
+ outDir: string | undefined;
61
+ dryRun: boolean | undefined;
62
+ noBundle: boolean | undefined;
63
+ keepVars: boolean | undefined;
64
+ logpush: boolean | undefined;
65
+ };
66
+
67
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
68
+
69
+ export type CustomDomain = {
70
+ id: string;
71
+ zone_id: string;
72
+ zone_name: string;
73
+ hostname: string;
74
+ service: string;
75
+ environment: string;
76
+ };
77
+ type UpdatedCustomDomain = CustomDomain & { modified: boolean };
78
+ type ConflictingCustomDomain = CustomDomain & {
79
+ external_dns_record_id?: string;
80
+ external_cert_id?: string;
81
+ };
82
+
83
+ export type CustomDomainChangeset = {
84
+ added: CustomDomain[];
85
+ removed: CustomDomain[];
86
+ updated: UpdatedCustomDomain[];
87
+ conflicting: ConflictingCustomDomain[];
88
+ };
89
+
90
+ function sleep(ms: number) {
91
+ return new Promise((resolve) => setTimeout(resolve, ms));
92
+ }
93
+
94
+ const scriptStartupErrorRegex = /startup/i;
95
+
96
+ function errIsScriptSizeOrStartupErr(err: unknown) {
97
+ if (!err) return false;
98
+
99
+ // 10027 = workers.api.error.script_too_large
100
+ if ((err as { code: number }).code === 10027) {
101
+ return true;
102
+ }
103
+
104
+ // 10021 = validation error
105
+ // no explicit error code for more granular errors than "invalid script"
106
+ // but the error will contain a string error message directly from the
107
+ // validator.
108
+ // the error always SHOULD look like "Script startup exceeded CPU limit."
109
+ // (or the less likely "Script startup exceeded memory limits.")
110
+ if (
111
+ (err as { code: number }).code === 10021 &&
112
+ err instanceof ParseError &&
113
+ scriptStartupErrorRegex.test(err.notes[0]?.text)
114
+ ) {
115
+ return true;
116
+ }
117
+
118
+ return false;
119
+ }
120
+
121
+ function renderRoute(route: Route): string {
122
+ let result = "";
123
+ if (typeof route === "string") {
124
+ result = route;
125
+ } else {
126
+ result = route.pattern;
127
+ const isCustomDomain = Boolean(
128
+ "custom_domain" in route && route.custom_domain
129
+ );
130
+ if (isCustomDomain && "zone_id" in route) {
131
+ result += ` (custom domain - zone id: ${route.zone_id})`;
132
+ } else if (isCustomDomain && "zone_name" in route) {
133
+ result += ` (custom domain - zone name: ${route.zone_name})`;
134
+ } else if (isCustomDomain) {
135
+ result += ` (custom domain)`;
136
+ } else if ("zone_id" in route) {
137
+ result += ` (zone id: ${route.zone_id})`;
138
+ } else if ("zone_name" in route) {
139
+ result += ` (zone name: ${route.zone_name})`;
140
+ }
141
+ }
142
+ return result;
143
+ }
144
+
145
+ // publishing to custom domains involves a few more steps than just updating
146
+ // the routing table, and thus the api implementing it is fairly defensive -
147
+ // it will error eagerly on conflicts against existing domains or existing
148
+ // managed DNS records
149
+
150
+ // however, you can pass params to override the errors. to know if we should
151
+ // override the current state, we generate a "changeset" of required actions
152
+ // to get to the state we want (specified by the list of custom domains). the
153
+ // changeset returns an "updated" collection (existing custom domains
154
+ // connected to other scripts) and a "conflicting" collection (the requested
155
+ // custom domains that have a managed, conflicting DNS record preventing the
156
+ // host's use as a custom domain). with this information, we can prompt to
157
+ // the user what will occur if we create the custom domains requested, and
158
+ // add the override param if they confirm the action
159
+ //
160
+ // if a user does not confirm that they want to override, we skip publishing
161
+ // to these custom domains, but continue on through the rest of the
162
+ // publish stage
163
+ async function publishCustomDomains(
164
+ workerUrl: string,
165
+ accountId: string,
166
+ domains: Array<RouteObject>
167
+ ): Promise<string[]> {
168
+ const config = {
169
+ override_scope: true,
170
+ override_existing_origin: false,
171
+ override_existing_dns_record: false,
172
+ };
173
+ const origins = domains.map((domainRoute) => {
174
+ return {
175
+ hostname: domainRoute.pattern,
176
+ zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
177
+ zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
178
+ };
179
+ });
180
+
181
+ const fail = () => {
182
+ return [
183
+ domains.length > 1
184
+ ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
185
+ : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
186
+ ];
187
+ };
188
+
189
+ if (!process.stdout.isTTY) {
190
+ // running in non-interactive mode.
191
+ // existing origins / dns records are not indicative of errors,
192
+ // so we aggressively update rather than aggressively fail
193
+ config.override_existing_origin = true;
194
+ config.override_existing_dns_record = true;
195
+ } else {
196
+ // get a changeset for operations required to achieve a state with the requested domains
197
+ const changeset = await fetchResult<CustomDomainChangeset>(
198
+ `${workerUrl}/domains/changeset?replace_state=true`,
199
+ {
200
+ method: "POST",
201
+ body: JSON.stringify(origins),
202
+ headers: {
203
+ "Content-Type": "application/json",
204
+ },
205
+ }
206
+ );
207
+
208
+ const updatesRequired = changeset.updated.filter(
209
+ (domain) => domain.modified
210
+ );
211
+ if (updatesRequired.length > 0) {
212
+ // find out which scripts the conflict domains are already attached to
213
+ // so we can provide that in the confirmation prompt
214
+ const existing = await Promise.all(
215
+ updatesRequired.map((domain) =>
216
+ fetchResult<CustomDomain>(
217
+ `/accounts/${accountId}/workers/domains/records/${domain.id}`
218
+ )
219
+ )
220
+ );
221
+ const existingRendered = existing
222
+ .map(
223
+ (domain) =>
224
+ `\t• ${domain.hostname} (used as a domain for "${domain.service}")`
225
+ )
226
+ .join("\n");
227
+ const message = `Custom Domains already exist for these domains:
228
+ ${existingRendered}
229
+ Update them to point to this script instead?`;
230
+ if (!(await confirm(message))) return fail();
231
+ config.override_existing_origin = true;
232
+ }
233
+
234
+ if (changeset.conflicting.length > 0) {
235
+ const conflicitingRendered = changeset.conflicting
236
+ .map((domain) => `\t• ${domain.hostname}`)
237
+ .join("\n");
238
+ const message = `You already have DNS records that conflict for these Custom Domains:
239
+ ${conflicitingRendered}
240
+ Update them to point to this script instead?`;
241
+ if (!(await confirm(message))) return fail();
242
+ config.override_existing_dns_record = true;
243
+ }
244
+ }
245
+
246
+ // publish to domains
247
+ await fetchResult(`${workerUrl}/domains/records`, {
248
+ method: "PUT",
249
+ body: JSON.stringify({ ...config, origins }),
250
+ headers: {
251
+ "Content-Type": "application/json",
252
+ },
253
+ });
254
+
255
+ return domains.map((domain) => renderRoute(domain));
256
+ }
257
+
258
+ export default async function publish(props: Props): Promise<void> {
259
+ // TODO: warn if git/hg has uncommitted changes
260
+ const { config, accountId, name } = props;
261
+ if (accountId && name) {
262
+ try {
263
+ const serviceMetaData = await fetchResult(
264
+ `/accounts/${accountId}/workers/services/${name}`
265
+ );
266
+ const { default_environment } = serviceMetaData as {
267
+ default_environment: {
268
+ script: { last_deployed_from: "dash" | "wrangler" | "api" };
269
+ };
270
+ };
271
+
272
+ if (
273
+ (await fromDashMessagePrompt(
274
+ default_environment.script.last_deployed_from
275
+ )) === false
276
+ )
277
+ return;
278
+ } catch (e) {
279
+ // code: 10090, message: workers.api.error.service_not_found
280
+ // is thrown from the above fetchResult on the first publish of a Worker
281
+ if ((e as { code?: number }).code !== 10090) {
282
+ logger.error(e);
283
+ }
284
+ }
285
+ }
286
+
287
+ if (!(props.compatibilityDate || config.compatibility_date)) {
288
+ const compatibilityDateStr = `${new Date().getFullYear()}-${(
289
+ new Date().getMonth() +
290
+ 1 +
291
+ ""
292
+ ).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
293
+
294
+ throw new Error(`A compatibility_date is required when publishing. Add the following to your wrangler.toml file:.
295
+ \`\`\`
296
+ compatibility_date = "${compatibilityDateStr}"
297
+ \`\`\`
298
+ Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
299
+ See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
300
+ }
301
+
302
+ const triggers = props.triggers || config.triggers?.crons;
303
+ const routes =
304
+ props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
305
+ const routesOnly: Array<Route> = [];
306
+ const customDomainsOnly: Array<RouteObject> = [];
307
+ for (const route of routes) {
308
+ if (typeof route !== "string" && route.custom_domain) {
309
+ if (route.pattern.includes("*")) {
310
+ throw new Error(
311
+ `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
312
+ );
313
+ }
314
+ if (route.pattern.includes("/")) {
315
+ throw new Error(
316
+ `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
317
+ );
318
+ }
319
+ customDomainsOnly.push(route);
320
+ } else {
321
+ routesOnly.push(route);
322
+ }
323
+ }
324
+
325
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
326
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
327
+
328
+ const jsxFactory = props.jsxFactory || config.jsx_factory;
329
+ const jsxFragment = props.jsxFragment || config.jsx_fragment;
330
+ const keepVars = props.keepVars ?? config.keep_vars;
331
+
332
+ const minify = props.minify ?? config.minify;
333
+
334
+ const nodeCompat = props.nodeCompat ?? config.node_compat;
335
+ if (nodeCompat) {
336
+ logger.warn(
337
+ "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."
338
+ );
339
+ }
340
+
341
+ // Warn if user tries minify or node-compat with no-bundle
342
+ if (props.noBundle && minify) {
343
+ logger.warn(
344
+ "`--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."
345
+ );
346
+ }
347
+
348
+ if (props.noBundle && nodeCompat) {
349
+ logger.warn(
350
+ "`--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."
351
+ );
352
+ }
353
+
354
+ const scriptName = props.name;
355
+ assert(
356
+ scriptName,
357
+ '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>"`'
358
+ );
359
+
360
+ assert(
361
+ !config.site || config.site.bucket,
362
+ "A [site] definition requires a `bucket` field with a path to the site's assets directory."
363
+ );
364
+
365
+ if (props.outDir) {
366
+ // we're using a custom output directory,
367
+ // so let's first ensure it exists
368
+ mkdirSync(props.outDir, { recursive: true });
369
+ // add a README
370
+ const readmePath = path.join(props.outDir, "README.md");
371
+ writeFileSync(
372
+ readmePath,
373
+ `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
374
+ );
375
+ }
376
+
377
+ const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
378
+ const envName = props.env ?? "production";
379
+
380
+ const start = Date.now();
381
+ const notProd = Boolean(!props.legacyEnv && props.env);
382
+ const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
383
+ const workerUrl = notProd
384
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
385
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`;
386
+
387
+ let available_on_subdomain: boolean | undefined = undefined; // we'll set this later
388
+ let scriptTag: string | null = null;
389
+
390
+ const { format } = props.entry;
391
+
392
+ if (
393
+ !props.isWorkersSite &&
394
+ Boolean(props.assetPaths) &&
395
+ format === "service-worker"
396
+ ) {
397
+ throw new Error(
398
+ "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/"
399
+ );
400
+ }
401
+
402
+ if (config.wasm_modules && format === "modules") {
403
+ throw new Error(
404
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
405
+ );
406
+ }
407
+
408
+ if (config.text_blobs && format === "modules") {
409
+ throw new Error(
410
+ "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"
411
+ );
412
+ }
413
+
414
+ if (config.data_blobs && format === "modules") {
415
+ throw new Error(
416
+ "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"
417
+ );
418
+ }
419
+ try {
420
+ if (props.noBundle) {
421
+ // if we're not building, let's just copy the entry to the destination directory
422
+ const destinationDir =
423
+ typeof destination === "string" ? destination : destination.path;
424
+ mkdirSync(destinationDir, { recursive: true });
425
+ writeFileSync(
426
+ path.join(destinationDir, path.basename(props.entry.file)),
427
+ readFileSync(props.entry.file, "utf-8")
428
+ );
429
+ }
430
+
431
+ // If we are using d1 bindings, and are not bundling the worker
432
+ // we should error here as the d1 shim won't be added
433
+ const betaD1Shims = identifyD1BindingsAsBeta(config.d1_databases);
434
+ if (
435
+ Array.isArray(betaD1Shims) &&
436
+ betaD1Shims.length > 0 &&
437
+ props.noBundle
438
+ ) {
439
+ throw new Error(
440
+ "While in beta, you cannot use D1 bindings without bundling your worker. Please remove `no_bundle` from your wrangler.toml file or remove the `--no-bundle` flag to access D1 bindings."
441
+ );
442
+ }
443
+
444
+ const {
445
+ modules,
446
+ dependencies,
447
+ resolvedEntryPointPath,
448
+ bundleType,
449
+ }: Awaited<ReturnType<typeof bundleWorker>> = props.noBundle
450
+ ? // we can skip the whole bundling step and mock a bundle here
451
+ {
452
+ modules: [],
453
+ dependencies: {},
454
+ resolvedEntryPointPath: props.entry.file,
455
+ bundleType: props.entry.format === "modules" ? "esm" : "commonjs",
456
+ stop: undefined,
457
+ }
458
+ : await bundleWorker(
459
+ props.entry,
460
+ typeof destination === "string" ? destination : destination.path,
461
+ {
462
+ serveAssetsFromWorker:
463
+ !props.isWorkersSite && Boolean(props.assetPaths),
464
+ betaD1Shims: identifyD1BindingsAsBeta(config.d1_databases)?.map(
465
+ (db) => db.binding
466
+ ),
467
+ jsxFactory,
468
+ jsxFragment,
469
+ rules: props.rules,
470
+ tsconfig: props.tsconfig ?? config.tsconfig,
471
+ minify,
472
+ nodeCompat,
473
+ define: { ...config.define, ...props.defines },
474
+ checkFetch: false,
475
+ assets: config.assets && {
476
+ ...config.assets,
477
+ // enable the cache when publishing
478
+ bypassCache: false,
479
+ },
480
+ services: config.services,
481
+ // We don't set workerDefinitions here,
482
+ // because we don't want to apply the dev-time
483
+ // facades on top of it
484
+ workerDefinitions: undefined,
485
+ firstPartyWorkerDevFacade: false,
486
+ // We want to know if the build is for development or publishing
487
+ // This could potentially cause issues as we no longer have identical behaviour between dev and publish?
488
+ targetConsumer: "publish",
489
+ local: false,
490
+ experimentalLocalStubCache: false,
491
+ }
492
+ );
493
+
494
+ const content = readFileSync(resolvedEntryPointPath, {
495
+ encoding: "utf-8",
496
+ });
497
+
498
+ // durable object migrations
499
+ const migrations = !props.dryRun
500
+ ? await getMigrationsToUpload(scriptName, {
501
+ accountId,
502
+ config,
503
+ legacyEnv: props.legacyEnv,
504
+ env: props.env,
505
+ })
506
+ : undefined;
507
+
508
+ const assets = await syncAssets(
509
+ accountId,
510
+ // When we're using the newer service environments, we wouldn't
511
+ // have added the env name on to the script name. However, we must
512
+ // include it in the kv namespace name regardless (since there's no
513
+ // concept of service environments for kv namespaces yet).
514
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
515
+ props.assetPaths,
516
+ false,
517
+ props.dryRun
518
+ );
519
+
520
+ const bindings: CfWorkerInit["bindings"] = {
521
+ kv_namespaces: (config.kv_namespaces || []).concat(
522
+ assets.namespace
523
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
524
+ : []
525
+ ),
526
+ vars: { ...config.vars, ...props.vars },
527
+ metadata_binding: config.metadata_binding,
528
+ wasm_modules: config.wasm_modules,
529
+ text_blobs: {
530
+ ...config.text_blobs,
531
+ ...(assets.manifest &&
532
+ format === "service-worker" && {
533
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
534
+ }),
535
+ },
536
+ data_blobs: config.data_blobs,
537
+ durable_objects: config.durable_objects,
538
+ queues: config.queues.producers?.map((producer) => {
539
+ return { binding: producer.binding, queue_name: producer.queue };
540
+ }),
541
+ r2_buckets: config.r2_buckets,
542
+ d1_databases: identifyD1BindingsAsBeta(config.d1_databases),
543
+ services: config.services,
544
+ dispatch_namespaces: config.dispatch_namespaces,
545
+ logfwdr: config.logfwdr,
546
+ unsafe: config.unsafe?.bindings,
547
+ };
548
+
549
+ if (assets.manifest) {
550
+ modules.push({
551
+ name: "__STATIC_CONTENT_MANIFEST",
552
+ content: JSON.stringify(assets.manifest),
553
+ type: "text",
554
+ });
555
+ }
556
+
557
+ const worker: CfWorkerInit = {
558
+ name: scriptName,
559
+ main: {
560
+ name: path.basename(resolvedEntryPointPath),
561
+ content: content,
562
+ type: bundleType,
563
+ },
564
+ bindings,
565
+ migrations,
566
+ modules,
567
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
568
+ compatibility_flags:
569
+ props.compatibilityFlags ?? config.compatibility_flags,
570
+ usage_model: config.usage_model,
571
+ keepVars,
572
+ logpush: props.logpush !== undefined ? props.logpush : config.logpush,
573
+ };
574
+
575
+ // As this is not deterministic for testing, we detect if in a jest environment and run asynchronously
576
+ // We do not care about the timing outside of testing
577
+ const bundleSizePromise = printBundleSize(
578
+ { name: path.basename(resolvedEntryPointPath), content: content },
579
+ modules
580
+ );
581
+ if (process.env.JEST_WORKER_ID !== undefined) await bundleSizePromise;
582
+ else void bundleSizePromise;
583
+
584
+ const withoutStaticAssets = {
585
+ ...bindings,
586
+ kv_namespaces: config.kv_namespaces,
587
+ text_blobs: config.text_blobs,
588
+ };
589
+
590
+ // mask anything that was overridden in cli args
591
+ // so that we don't log potential secrets into the terminal
592
+ const maskedVars = { ...withoutStaticAssets.vars };
593
+ for (const key of Object.keys(maskedVars)) {
594
+ if (maskedVars[key] !== config.vars[key]) {
595
+ // This means it was overridden in cli args
596
+ // so let's mask it
597
+ maskedVars[key] = "(hidden)";
598
+ }
599
+ }
600
+
601
+ printBindings({ ...withoutStaticAssets, vars: maskedVars });
602
+
603
+ await ensureQueuesExist(config);
604
+
605
+ if (!props.dryRun) {
606
+ // Upload the script so it has time to propagate.
607
+ // We can also now tell whether available_on_subdomain is set
608
+ try {
609
+ const result = await fetchResult<{
610
+ available_on_subdomain: boolean;
611
+ id: string | null;
612
+ etag: string | null;
613
+ pipeline_hash: string | null;
614
+ tag: string | null;
615
+ }>(
616
+ workerUrl,
617
+ {
618
+ method: "PUT",
619
+ body: createWorkerUploadForm(worker),
620
+ headers: await getMetricsUsageHeaders(config.send_metrics),
621
+ },
622
+ new URLSearchParams({
623
+ include_subdomain_availability: "true",
624
+ // pass excludeScript so the whole body of the
625
+ // script doesn't get included in the response
626
+ excludeScript: "true",
627
+ })
628
+ );
629
+
630
+ available_on_subdomain = result.available_on_subdomain;
631
+ scriptTag = result.tag;
632
+
633
+ if (config.first_party_worker) {
634
+ // Print some useful information returned after publishing
635
+ // Not all fields will be populated for every worker
636
+ // These fields are likely to be scraped by tools, so do not rename
637
+ if (result.id) logger.log("Worker ID: ", result.id);
638
+ if (result.etag) logger.log("Worker ETag: ", result.etag);
639
+ if (result.pipeline_hash)
640
+ logger.log("Worker PipelineHash: ", result.pipeline_hash);
641
+ }
642
+ } catch (err) {
643
+ if (errIsScriptSizeOrStartupErr(err)) {
644
+ printOffendingDependencies(dependencies);
645
+ }
646
+ throw err;
647
+ }
648
+ }
649
+ } finally {
650
+ if (typeof destination !== "string") {
651
+ // this means we're using a temp dir,
652
+ // so let's clean up before we proceed
653
+ await destination.cleanup();
654
+ }
655
+ }
656
+
657
+ if (props.dryRun) {
658
+ logger.log(`--dry-run: exiting now.`);
659
+ return;
660
+ }
661
+ assert(accountId, "Missing accountId");
662
+
663
+ const uploadMs = Date.now() - start;
664
+ const deployments: Promise<string[]>[] = [];
665
+
666
+ if (deployToWorkersDev) {
667
+ // Deploy to a subdomain of `workers.dev`
668
+ const userSubdomain = await getWorkersDevSubdomain(accountId);
669
+ const scriptURL =
670
+ props.legacyEnv || !props.env
671
+ ? `${scriptName}.${userSubdomain}.workers.dev`
672
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
673
+ if (!available_on_subdomain) {
674
+ // Enable the `workers.dev` subdomain.
675
+ deployments.push(
676
+ fetchResult(`${workerUrl}/subdomain`, {
677
+ method: "POST",
678
+ body: JSON.stringify({ enabled: true }),
679
+ headers: {
680
+ "Content-Type": "application/json",
681
+ },
682
+ })
683
+ .then(() => [scriptURL])
684
+ // Add a delay when the subdomain is first created.
685
+ // This is to prevent an issue where a negative cache-hit
686
+ // causes the subdomain to be unavailable for 30 seconds.
687
+ // This is a temporary measure until we fix this on the edge.
688
+ .then(async (url) => {
689
+ await sleep(3000);
690
+ return url;
691
+ })
692
+ );
693
+ } else {
694
+ deployments.push(Promise.resolve([scriptURL]));
695
+ }
696
+ } else {
697
+ if (available_on_subdomain) {
698
+ // Disable the workers.dev deployment
699
+ await fetchResult(`${workerUrl}/subdomain`, {
700
+ method: "POST",
701
+ body: JSON.stringify({ enabled: false }),
702
+ headers: {
703
+ "Content-Type": "application/json",
704
+ },
705
+ });
706
+ } else if (routes.length !== 0) {
707
+ // if you get to this point it's because
708
+ // you're trying to deploy a worker to a custom
709
+ // domain that's already bound to another worker.
710
+ // so this thing is about finding workers that have
711
+ // bindings to the routes you're trying to deploy to.
712
+ //
713
+ // the logic is kinda similar (read: duplicated) from publishRoutesFallback,
714
+ // except here we know we have a good API token or whatever so we don't need
715
+ // to bother with all the error handling tomfoolery.
716
+ const routesWithOtherBindings: Record<string, string[]> = {};
717
+ for (const route of routes) {
718
+ const zone = await getZoneForRoute(route);
719
+ if (!zone) {
720
+ continue;
721
+ }
722
+
723
+ const routePattern = typeof route === "string" ? route : route.pattern;
724
+ const routesInZone = await fetchListResult<{
725
+ pattern: string;
726
+ script: string;
727
+ }>(`/zones/${zone.id}/workers/routes`);
728
+
729
+ routesInZone.forEach(({ script, pattern }) => {
730
+ if (pattern === routePattern && script !== scriptName) {
731
+ if (!(script in routesWithOtherBindings)) {
732
+ routesWithOtherBindings[script] = [];
733
+ }
734
+
735
+ routesWithOtherBindings[script].push(pattern);
736
+ }
737
+ });
738
+ }
739
+
740
+ if (Object.keys(routesWithOtherBindings).length > 0) {
741
+ let errorMessage =
742
+ "Can't publish a worker to routes that are assigned to another worker.\n";
743
+
744
+ for (const worker in routesWithOtherBindings) {
745
+ const assignedRoutes = routesWithOtherBindings[worker];
746
+ errorMessage += `"${worker}" is already assigned to routes:\n${assignedRoutes.map(
747
+ (r) => ` - ${chalk.underline(r)}\n`
748
+ )}`;
749
+ }
750
+
751
+ const resolution =
752
+ "Unassign other workers from the routes you want to publish to, and then try again.";
753
+ const dashLink = `Visit ${chalk.blue(
754
+ chalk.underline(
755
+ `https://dash.cloudflare.com/${accountId}/workers/overview`
756
+ )
757
+ )} to unassign a worker from a route.`;
758
+
759
+ throw new Error(`${errorMessage}\n${resolution}\n${dashLink}`);
760
+ }
761
+ }
762
+ }
763
+
764
+ logger.log("Uploaded", workerName, formatTime(uploadMs));
765
+
766
+ // Update routing table for the script.
767
+ if (routesOnly.length > 0) {
768
+ deployments.push(
769
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
770
+ if (routesOnly.length > 10) {
771
+ return routesOnly
772
+ .slice(0, 9)
773
+ .map((route) => renderRoute(route))
774
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
775
+ }
776
+ return routesOnly.map((route) => renderRoute(route));
777
+ })
778
+ );
779
+ }
780
+
781
+ // Update custom domains for the script
782
+ if (customDomainsOnly.length > 0) {
783
+ deployments.push(
784
+ publishCustomDomains(workerUrl, accountId, customDomainsOnly)
785
+ );
786
+ }
787
+
788
+ // Configure any schedules for the script.
789
+ // TODO: rename this to `schedules`?
790
+ if (triggers && triggers.length) {
791
+ deployments.push(
792
+ fetchResult(`${workerUrl}/schedules`, {
793
+ // Note: PUT will override previous schedules on this script.
794
+ method: "PUT",
795
+ body: JSON.stringify(triggers.map((cron) => ({ cron }))),
796
+ headers: {
797
+ "Content-Type": "application/json",
798
+ },
799
+ }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
800
+ );
801
+ }
802
+
803
+ if (config.queues.consumers && config.queues.consumers.length) {
804
+ deployments.push(...updateQueueConsumers(config));
805
+ }
806
+
807
+ const targets = await Promise.all(deployments);
808
+ const deployMs = Date.now() - start - uploadMs;
809
+
810
+ if (deployments.length > 0) {
811
+ logger.log("Published", workerName, formatTime(deployMs));
812
+ for (const target of targets.flat()) {
813
+ // Append protocol only on workers.dev domains
814
+ logger.log(
815
+ " ",
816
+ (target.endsWith("workers.dev") ? "https://" : "") + target
817
+ );
818
+ }
819
+ } else {
820
+ logger.log("No publish targets for", workerName, formatTime(deployMs));
821
+ }
822
+
823
+ try {
824
+ const deploymentsList = await fetchResult<DeploymentListRes>(
825
+ `/accounts/${accountId}/workers/versions/by-script/${scriptTag}`
826
+ );
827
+
828
+ logger.log("Current Deployment:", deploymentsList.latest.number);
829
+ } catch (e) {
830
+ if ((e as { code: number }).code === 10023) {
831
+ // TODO: remove this try/catch once versions is completely rolled out
832
+ }
833
+ throw e;
834
+ }
835
+ }
836
+
837
+ function formatTime(duration: number) {
838
+ return `(${(duration / 1000).toFixed(2)} sec)`;
839
+ }
840
+
841
+ /**
842
+ * Associate the newly deployed Worker with the given routes.
843
+ */
844
+ async function publishRoutes(
845
+ routes: Route[],
846
+ {
847
+ workerUrl,
848
+ scriptName,
849
+ notProd,
850
+ }: { workerUrl: string; scriptName: string; notProd: boolean }
851
+ ): Promise<string[]> {
852
+ try {
853
+ return await fetchResult(`${workerUrl}/routes`, {
854
+ // Note: PUT will delete previous routes on this script.
855
+ method: "PUT",
856
+ body: JSON.stringify(
857
+ routes.map((route) =>
858
+ typeof route !== "object" ? { pattern: route } : route
859
+ )
860
+ ),
861
+ headers: {
862
+ "Content-Type": "application/json",
863
+ },
864
+ });
865
+ } catch (e) {
866
+ if (isAuthenticationError(e)) {
867
+ // An authentication error is probably due to a known issue,
868
+ // where the user is logged in via an API token that does not have "All Zones".
869
+ return await publishRoutesFallback(routes, { scriptName, notProd });
870
+ } else {
871
+ throw e;
872
+ }
873
+ }
874
+ }
875
+
876
+ /**
877
+ * Try updating routes for the Worker using a less optimal zone-based API.
878
+ *
879
+ * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
880
+ */
881
+ async function publishRoutesFallback(
882
+ routes: Route[],
883
+ { scriptName, notProd }: { scriptName: string; notProd: boolean }
884
+ ) {
885
+ if (notProd) {
886
+ throw new Error(
887
+ "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
888
+ "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
889
+ );
890
+ }
891
+ logger.warn(
892
+ "The current authentication token does not have 'All Zones' permissions.\n" +
893
+ "Falling back to using the zone-based API endpoint to update each route individually.\n" +
894
+ "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
895
+ "Existing routes for this Worker in such zones will not be deleted."
896
+ );
897
+
898
+ const deployedRoutes: string[] = [];
899
+
900
+ // Collect the routes (and their zones) that will be deployed.
901
+ const activeZones = new Map<string, string>();
902
+ const routesToDeploy = new Map<string, string>();
903
+ for (const route of routes) {
904
+ const zone = await getZoneForRoute(route);
905
+ if (zone) {
906
+ activeZones.set(zone.id, zone.host);
907
+ routesToDeploy.set(
908
+ typeof route === "string" ? route : route.pattern,
909
+ zone.id
910
+ );
911
+ }
912
+ }
913
+
914
+ // Collect the routes that are already deployed.
915
+ const allRoutes = new Map<string, string>();
916
+ const alreadyDeployedRoutes = new Set<string>();
917
+ for (const [zone, host] of activeZones) {
918
+ try {
919
+ for (const { pattern, script } of await fetchListResult<{
920
+ pattern: string;
921
+ script: string;
922
+ }>(`/zones/${zone}/workers/routes`)) {
923
+ allRoutes.set(pattern, script);
924
+ if (script === scriptName) {
925
+ alreadyDeployedRoutes.add(pattern);
926
+ }
927
+ }
928
+ } catch (e) {
929
+ if (isAuthenticationError(e)) {
930
+ e.notes.push({
931
+ text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
932
+ });
933
+ }
934
+ throw e;
935
+ }
936
+ }
937
+
938
+ // Deploy each route that is not already deployed.
939
+ for (const [routePattern, zoneId] of routesToDeploy.entries()) {
940
+ if (allRoutes.has(routePattern)) {
941
+ const knownScript = allRoutes.get(routePattern);
942
+ if (knownScript === scriptName) {
943
+ // This route is already associated with this worker, so no need to hit the API.
944
+ alreadyDeployedRoutes.delete(routePattern);
945
+ continue;
946
+ } else {
947
+ throw new Error(
948
+ `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
949
+ );
950
+ }
951
+ }
952
+
953
+ const { pattern } = await fetchResult<{ pattern: string }>(
954
+ `/zones/${zoneId}/workers/routes`,
955
+ {
956
+ method: "POST",
957
+ body: JSON.stringify({
958
+ pattern: routePattern,
959
+ script: scriptName,
960
+ }),
961
+ headers: {
962
+ "Content-Type": "application/json",
963
+ },
964
+ }
965
+ );
966
+
967
+ deployedRoutes.push(pattern);
968
+ }
969
+
970
+ if (alreadyDeployedRoutes.size) {
971
+ logger.warn(
972
+ "Previously deployed routes:\n" +
973
+ "The following routes were already associated with this worker, and have not been deleted:\n" +
974
+ [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
975
+ "If these routes are not wanted then you can remove them in the dashboard."
976
+ );
977
+ }
978
+
979
+ return deployedRoutes;
980
+ }
981
+
982
+ function isAuthenticationError(e: unknown): e is ParseError {
983
+ return e instanceof ParseError && (e as { code?: number }).code === 10000;
984
+ }
985
+
986
+ async function ensureQueuesExist(config: Config) {
987
+ const producers = (config.queues.producers || []).map(
988
+ (producer) => producer.queue
989
+ );
990
+ const consumers = (config.queues.consumers || []).map(
991
+ (consumer) => consumer.queue
992
+ );
993
+
994
+ const queueNames = producers.concat(consumers);
995
+ for (const queue of queueNames) {
996
+ try {
997
+ await getQueue(config, queue);
998
+ } catch (err) {
999
+ const queueErr = err as FetchError;
1000
+ if (queueErr.code === 100123) {
1001
+ // queue_not_found
1002
+ throw new Error(
1003
+ `Queue "${queue}" does not exist. To create it, run: wrangler queues create ${queue}`
1004
+ );
1005
+ }
1006
+ throw err;
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ function updateQueueConsumers(config: Config): Promise<string[]>[] {
1012
+ const consumers = config.queues.consumers || [];
1013
+ return consumers.map((consumer) => {
1014
+ const body: PutConsumerBody = {
1015
+ dead_letter_queue: consumer.dead_letter_queue,
1016
+ settings: {
1017
+ batch_size: consumer.max_batch_size,
1018
+ max_retries: consumer.max_retries,
1019
+ max_wait_time_ms: consumer.max_batch_timeout
1020
+ ? 1000 * consumer.max_batch_timeout
1021
+ : undefined,
1022
+ },
1023
+ };
1024
+
1025
+ if (config.name === undefined) {
1026
+ // TODO: how can we reliably get the current script name?
1027
+ throw new Error("Script name is required to update queue consumers");
1028
+ }
1029
+ const scriptName = config.name;
1030
+ const envName = undefined; // TODO: script environment for wrangler publish?
1031
+ return putConsumer(config, consumer.queue, scriptName, envName, body).then(
1032
+ () => [`Consumer for ${consumer.queue}`]
1033
+ );
1034
+ });
1035
+ }