wrangler 0.0.0-eebdb6c → 0.0.0-eec88346

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