wrangler 0.0.0-e6e1daba → 0.0.0-e6fea1318

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