wrangler 0.0.0-e6c9c5c0 → 0.0.0-e6ddf8a7

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 (285) hide show
  1. package/README.md +12 -14
  2. package/bin/wrangler.js +14 -75
  3. package/package.json +210 -194
  4. package/templates/__tests__/tsconfig.json +1 -1
  5. package/templates/checked-fetch.js +19 -4
  6. package/templates/facade.d.ts +4 -1
  7. package/templates/gitignore +1 -0
  8. package/templates/middleware/common.ts +9 -4
  9. package/templates/middleware/loader-modules.ts +64 -11
  10. package/templates/middleware/loader-sw.ts +2 -7
  11. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  12. package/templates/middleware/middleware-miniflare3-json-error.ts +18 -5
  13. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  14. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  15. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  16. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  17. package/templates/modules-watch-stub.js +4 -0
  18. package/templates/new-worker-scheduled.ts +1 -1
  19. package/templates/new-worker.ts +4 -1
  20. package/templates/pages-dev-util.ts +4 -1
  21. package/templates/pages-shim.ts +0 -3
  22. package/templates/pages-template-plugin.ts +19 -5
  23. package/templates/pages-template-worker.ts +11 -2
  24. package/templates/tsconfig.init.json +1 -2
  25. package/templates/tsconfig.json +1 -1
  26. package/wrangler-dist/cli.d.ts +842 -128
  27. package/wrangler-dist/cli.js +110076 -103044
  28. package/wrangler-dist/wasm-sync.wasm +0 -0
  29. package/import_meta_url.js +0 -3
  30. package/miniflare-config-stubs/.env.empty +0 -0
  31. package/miniflare-config-stubs/package.empty.json +0 -1
  32. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  33. package/miniflare-dist/index.mjs +0 -6364
  34. package/src/__tests__/access.test.ts +0 -25
  35. package/src/__tests__/api-dev.test.ts +0 -238
  36. package/src/__tests__/api-devregistry.test.js +0 -64
  37. package/src/__tests__/api.test.ts +0 -80
  38. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  39. package/src/__tests__/config-cache.test.ts +0 -42
  40. package/src/__tests__/configuration.test.ts +0 -4163
  41. package/src/__tests__/d1/d1.test.ts +0 -127
  42. package/src/__tests__/d1/splitter.test.ts +0 -255
  43. package/src/__tests__/delete.test.ts +0 -266
  44. package/src/__tests__/deployments.test.ts +0 -105
  45. package/src/__tests__/dev.test.tsx +0 -1586
  46. package/src/__tests__/generate.test.ts +0 -238
  47. package/src/__tests__/get-host-from-url.test.ts +0 -16
  48. package/src/__tests__/guess-worker-format.test.ts +0 -85
  49. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  50. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  51. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  52. package/src/__tests__/helpers/mock-auth-domain.ts +0 -20
  53. package/src/__tests__/helpers/mock-bin.ts +0 -36
  54. package/src/__tests__/helpers/mock-console.ts +0 -106
  55. package/src/__tests__/helpers/mock-dialogs.ts +0 -139
  56. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -11
  57. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  58. package/src/__tests__/helpers/mock-istty.ts +0 -74
  59. package/src/__tests__/helpers/mock-known-routes.ts +0 -12
  60. package/src/__tests__/helpers/mock-kv.ts +0 -46
  61. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -263
  62. package/src/__tests__/helpers/mock-process.ts +0 -34
  63. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  64. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  65. package/src/__tests__/helpers/msw/blob-worker.cjs +0 -19
  66. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  67. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -69
  68. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -81
  69. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -31
  70. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -60
  71. package/src/__tests__/helpers/msw/handlers/script.ts +0 -56
  72. package/src/__tests__/helpers/msw/handlers/user.ts +0 -52
  73. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -20
  74. package/src/__tests__/helpers/msw/index.ts +0 -50
  75. package/src/__tests__/helpers/msw/read-file-sync.js +0 -61
  76. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  77. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  78. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  79. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  80. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  81. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  82. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  83. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  84. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  85. package/src/__tests__/https-options.test.ts +0 -163
  86. package/src/__tests__/index.test.ts +0 -268
  87. package/src/__tests__/init.test.ts +0 -3164
  88. package/src/__tests__/jest.setup.ts +0 -175
  89. package/src/__tests__/kv.test.ts +0 -1788
  90. package/src/__tests__/logger.test.ts +0 -141
  91. package/src/__tests__/logout.test.ts +0 -47
  92. package/src/__tests__/metrics.test.ts +0 -493
  93. package/src/__tests__/middleware.scheduled.test.ts +0 -145
  94. package/src/__tests__/middleware.test.ts +0 -750
  95. package/src/__tests__/package-manager.test.ts +0 -353
  96. package/src/__tests__/pages-deployment-tail.test.ts +0 -955
  97. package/src/__tests__/pages.test.ts +0 -2898
  98. package/src/__tests__/parse.test.ts +0 -330
  99. package/src/__tests__/paths.test.ts +0 -39
  100. package/src/__tests__/publish.test.ts +0 -8117
  101. package/src/__tests__/pubsub.test.ts +0 -490
  102. package/src/__tests__/queues.test.ts +0 -522
  103. package/src/__tests__/r2.test.ts +0 -369
  104. package/src/__tests__/route.test.ts +0 -45
  105. package/src/__tests__/secret.test.ts +0 -693
  106. package/src/__tests__/tail.test.ts +0 -958
  107. package/src/__tests__/test-old-node-version.js +0 -31
  108. package/src/__tests__/tsconfig-sanity.ts +0 -12
  109. package/src/__tests__/tsconfig.json +0 -8
  110. package/src/__tests__/tsconfig.tsbuildinfo +0 -1
  111. package/src/__tests__/type-generation.test.ts +0 -233
  112. package/src/__tests__/user.test.ts +0 -118
  113. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  114. package/src/__tests__/validate-dev-props.test.ts +0 -56
  115. package/src/__tests__/version.test.ts +0 -35
  116. package/src/__tests__/whoami.test.tsx +0 -172
  117. package/src/__tests__/worker-namespace.test.ts +0 -334
  118. package/src/abort.d.ts +0 -3
  119. package/src/api/dev.ts +0 -259
  120. package/src/api/index.ts +0 -3
  121. package/src/api/pages/index.ts +0 -5
  122. package/src/api/pages/publish.tsx +0 -321
  123. package/src/bundle-reporter.ts +0 -68
  124. package/src/bundle.ts +0 -875
  125. package/src/cfetch/index.ts +0 -158
  126. package/src/cfetch/internal.ts +0 -258
  127. package/src/cli.ts +0 -28
  128. package/src/config/README.md +0 -107
  129. package/src/config/config.ts +0 -275
  130. package/src/config/diagnostics.ts +0 -80
  131. package/src/config/environment.ts +0 -579
  132. package/src/config/index.ts +0 -358
  133. package/src/config/validation-helpers.ts +0 -597
  134. package/src/config/validation.ts +0 -2151
  135. package/src/config-cache.ts +0 -85
  136. package/src/create-worker-preview.ts +0 -282
  137. package/src/create-worker-upload-form.ts +0 -325
  138. package/src/d1/backups.tsx +0 -219
  139. package/src/d1/constants.ts +0 -2
  140. package/src/d1/create.tsx +0 -63
  141. package/src/d1/delete.ts +0 -56
  142. package/src/d1/execute.tsx +0 -323
  143. package/src/d1/formatTimeAgo.ts +0 -14
  144. package/src/d1/index.ts +0 -101
  145. package/src/d1/list.tsx +0 -48
  146. package/src/d1/migrations/apply.tsx +0 -197
  147. package/src/d1/migrations/create.tsx +0 -77
  148. package/src/d1/migrations/helpers.ts +0 -147
  149. package/src/d1/migrations/index.ts +0 -3
  150. package/src/d1/migrations/list.tsx +0 -79
  151. package/src/d1/migrations/options.ts +0 -18
  152. package/src/d1/options.ts +0 -22
  153. package/src/d1/splitter.ts +0 -161
  154. package/src/d1/types.ts +0 -24
  155. package/src/d1/utils.ts +0 -48
  156. package/src/delete.ts +0 -103
  157. package/src/deployments.ts +0 -93
  158. package/src/deprecated/index.ts +0 -145
  159. package/src/dev/dev-vars.ts +0 -39
  160. package/src/dev/dev.tsx +0 -614
  161. package/src/dev/get-local-persistence-path.ts +0 -31
  162. package/src/dev/local.tsx +0 -923
  163. package/src/dev/remote.tsx +0 -632
  164. package/src/dev/start-server.ts +0 -538
  165. package/src/dev/use-esbuild.ts +0 -205
  166. package/src/dev/validate-dev-props.ts +0 -31
  167. package/src/dev-registry.ts +0 -201
  168. package/src/dev.tsx +0 -949
  169. package/src/dialogs.ts +0 -136
  170. package/src/dispatch-namespace.ts +0 -207
  171. package/src/docs/index.ts +0 -98
  172. package/src/durable.ts +0 -102
  173. package/src/entry.ts +0 -328
  174. package/src/environment-variables/factory.ts +0 -88
  175. package/src/environment-variables/misc-variables.ts +0 -30
  176. package/src/errors.ts +0 -11
  177. package/src/generate/index.ts +0 -300
  178. package/src/git-client.ts +0 -135
  179. package/src/global-wrangler-config-path.ts +0 -26
  180. package/src/https-options.ts +0 -127
  181. package/src/index.ts +0 -694
  182. package/src/init.ts +0 -1024
  183. package/src/inspect.ts +0 -767
  184. package/src/intl-polyfill.d.ts +0 -139
  185. package/src/is-ci.ts +0 -14
  186. package/src/is-interactive.ts +0 -16
  187. package/src/jest.d.ts +0 -4
  188. package/src/kv/helpers.ts +0 -430
  189. package/src/kv/index.ts +0 -596
  190. package/src/logger.ts +0 -104
  191. package/src/metrics/index.ts +0 -5
  192. package/src/metrics/metrics-config.ts +0 -239
  193. package/src/metrics/metrics-dispatcher.ts +0 -96
  194. package/src/metrics/metrics-usage-headers.ts +0 -24
  195. package/src/metrics/send-event.ts +0 -98
  196. package/src/miniflare-cli/README.md +0 -30
  197. package/src/miniflare-cli/assets.ts +0 -250
  198. package/src/miniflare-cli/index.ts +0 -210
  199. package/src/miniflare-cli/request-context.ts +0 -40
  200. package/src/miniflare-cli/tsconfig.json +0 -9
  201. package/src/miniflare-cli/tsconfig.tsbuildinfo +0 -1
  202. package/src/miniflare-cli/types.ts +0 -11
  203. package/src/module-collection.ts +0 -267
  204. package/src/open-in-browser.ts +0 -17
  205. package/src/package-manager.ts +0 -219
  206. package/src/pages/build.ts +0 -150
  207. package/src/pages/buildFunctions.ts +0 -129
  208. package/src/pages/constants.ts +0 -18
  209. package/src/pages/deployment-tails.ts +0 -284
  210. package/src/pages/deployments.tsx +0 -84
  211. package/src/pages/dev.ts +0 -716
  212. package/src/pages/errors.ts +0 -66
  213. package/src/pages/functions/buildPlugin.ts +0 -90
  214. package/src/pages/functions/buildWorker.ts +0 -288
  215. package/src/pages/functions/filepath-routing.test.ts +0 -234
  216. package/src/pages/functions/filepath-routing.ts +0 -189
  217. package/src/pages/functions/identifiers.ts +0 -78
  218. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  219. package/src/pages/functions/routes-consolidation.ts +0 -73
  220. package/src/pages/functions/routes-transformation.test.ts +0 -282
  221. package/src/pages/functions/routes-transformation.ts +0 -115
  222. package/src/pages/functions/routes-validation.test.ts +0 -403
  223. package/src/pages/functions/routes-validation.ts +0 -202
  224. package/src/pages/functions/routes.ts +0 -151
  225. package/src/pages/functions/tsconfig.json +0 -8
  226. package/src/pages/functions/tsconfig.tsbuildinfo +0 -1
  227. package/src/pages/functions.ts +0 -82
  228. package/src/pages/hash.ts +0 -13
  229. package/src/pages/index.ts +0 -102
  230. package/src/pages/projects.tsx +0 -167
  231. package/src/pages/prompt-select-project.tsx +0 -31
  232. package/src/pages/publish.tsx +0 -263
  233. package/src/pages/types.ts +0 -41
  234. package/src/pages/upload.tsx +0 -447
  235. package/src/pages/utils.ts +0 -23
  236. package/src/parse.ts +0 -286
  237. package/src/paths.ts +0 -71
  238. package/src/proxy.ts +0 -694
  239. package/src/publish/index.ts +0 -270
  240. package/src/publish/publish.ts +0 -1064
  241. package/src/pubsub/index.ts +0 -286
  242. package/src/pubsub/pubsub-commands.ts +0 -624
  243. package/src/queues/cli/commands/consumer/add.ts +0 -71
  244. package/src/queues/cli/commands/consumer/index.ts +0 -22
  245. package/src/queues/cli/commands/consumer/remove.ts +0 -38
  246. package/src/queues/cli/commands/create.ts +0 -25
  247. package/src/queues/cli/commands/delete.ts +0 -26
  248. package/src/queues/cli/commands/index.ts +0 -36
  249. package/src/queues/cli/commands/list.ts +0 -25
  250. package/src/queues/client.ts +0 -135
  251. package/src/queues/utils.ts +0 -18
  252. package/src/r2/constants.ts +0 -4
  253. package/src/r2/helpers.ts +0 -131
  254. package/src/r2/index.ts +0 -289
  255. package/src/routes.ts +0 -140
  256. package/src/secret/index.ts +0 -379
  257. package/src/selfsigned.d.ts +0 -29
  258. package/src/sites.ts +0 -372
  259. package/src/tail/createTail.ts +0 -406
  260. package/src/tail/filters.ts +0 -277
  261. package/src/tail/index.ts +0 -213
  262. package/src/tail/printing.ts +0 -122
  263. package/src/tsconfig-sanity.ts +0 -16
  264. package/src/type-generation.ts +0 -181
  265. package/src/update-check.ts +0 -19
  266. package/src/user/access.ts +0 -68
  267. package/src/user/auth-variables.ts +0 -113
  268. package/src/user/choose-account.tsx +0 -39
  269. package/src/user/generate-auth-url.ts +0 -33
  270. package/src/user/generate-random-state.ts +0 -16
  271. package/src/user/index.ts +0 -2
  272. package/src/user/user.ts +0 -1232
  273. package/src/utils/collectKeyValues.ts +0 -14
  274. package/src/whoami.ts +0 -135
  275. package/src/worker.ts +0 -251
  276. package/src/yargs-types.ts +0 -24
  277. package/src/zones.ts +0 -191
  278. package/templates/__tests__/tsconfig.tsbuildinfo +0 -1
  279. package/templates/d1-beta-facade.js +0 -241
  280. package/templates/first-party-worker-module-facade.ts +0 -19
  281. package/templates/format-dev-errors.ts +0 -33
  282. package/templates/serve-static-assets.ts +0 -65
  283. package/templates/service-bindings-module-facade.js +0 -54
  284. package/templates/service-bindings-sw-facade.js +0 -42
  285. package/templates/tsconfig.tsbuildinfo +0 -1
@@ -1,1064 +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 { DeploymentListRes } from "../deployments";
34
- import type { Entry } from "../entry";
35
- import type { PutConsumerBody } from "../queues/client";
36
- import type { AssetPaths } from "../sites";
37
- import type { CfWorkerInit } from "../worker";
38
-
39
- type Props = {
40
- config: Config;
41
- accountId: string | undefined;
42
- entry: Entry;
43
- rules: Config["rules"];
44
- name: string | undefined;
45
- env: string | undefined;
46
- compatibilityDate: string | undefined;
47
- compatibilityFlags: string[] | undefined;
48
- assetPaths: AssetPaths | undefined;
49
- vars: Record<string, string> | undefined;
50
- defines: Record<string, string> | undefined;
51
- triggers: string[] | undefined;
52
- routes: string[] | undefined;
53
- legacyEnv: boolean | undefined;
54
- jsxFactory: string | undefined;
55
- jsxFragment: string | undefined;
56
- tsconfig: string | undefined;
57
- isWorkersSite: boolean;
58
- minify: boolean | undefined;
59
- nodeCompat: boolean | undefined;
60
- outDir: string | undefined;
61
- dryRun: boolean | undefined;
62
- noBundle: boolean | undefined;
63
- keepVars: boolean | undefined;
64
- logpush: boolean | undefined;
65
- };
66
-
67
- type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
68
-
69
- export type CustomDomain = {
70
- id: string;
71
- zone_id: string;
72
- zone_name: string;
73
- hostname: string;
74
- service: string;
75
- environment: string;
76
- };
77
- type UpdatedCustomDomain = CustomDomain & { modified: boolean };
78
- type ConflictingCustomDomain = CustomDomain & {
79
- external_dns_record_id?: string;
80
- external_cert_id?: string;
81
- };
82
-
83
- export type CustomDomainChangeset = {
84
- added: CustomDomain[];
85
- removed: CustomDomain[];
86
- updated: UpdatedCustomDomain[];
87
- conflicting: ConflictingCustomDomain[];
88
- };
89
-
90
- function sleep(ms: number) {
91
- return new Promise((resolve) => setTimeout(resolve, ms));
92
- }
93
-
94
- const scriptStartupErrorRegex = /startup/i;
95
-
96
- function 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
- logfwdr: config.logfwdr,
555
- unsafe: config.unsafe?.bindings,
556
- };
557
-
558
- if (assets.manifest) {
559
- modules.push({
560
- name: "__STATIC_CONTENT_MANIFEST",
561
- content: JSON.stringify(assets.manifest),
562
- type: "text",
563
- });
564
- }
565
-
566
- const worker: CfWorkerInit = {
567
- name: scriptName,
568
- main: {
569
- name: path.basename(resolvedEntryPointPath),
570
- content: content,
571
- type: bundleType,
572
- },
573
- bindings,
574
- migrations,
575
- modules,
576
- compatibility_date: props.compatibilityDate ?? config.compatibility_date,
577
- compatibility_flags:
578
- props.compatibilityFlags ?? config.compatibility_flags,
579
- usage_model: config.usage_model,
580
- keepVars,
581
- logpush: props.logpush !== undefined ? props.logpush : config.logpush,
582
- };
583
-
584
- // As this is not deterministic for testing, we detect if in a jest environment and run asynchronously
585
- // We do not care about the timing outside of testing
586
- const bundleSizePromise = printBundleSize(
587
- { name: path.basename(resolvedEntryPointPath), content: content },
588
- modules
589
- );
590
- if (process.env.JEST_WORKER_ID !== undefined) await bundleSizePromise;
591
- else void bundleSizePromise;
592
-
593
- const withoutStaticAssets = {
594
- ...bindings,
595
- kv_namespaces: config.kv_namespaces,
596
- text_blobs: config.text_blobs,
597
- };
598
-
599
- // mask anything that was overridden in cli args
600
- // so that we don't log potential secrets into the terminal
601
- const maskedVars = { ...withoutStaticAssets.vars };
602
- for (const key of Object.keys(maskedVars)) {
603
- if (maskedVars[key] !== config.vars[key]) {
604
- // This means it was overridden in cli args
605
- // so let's mask it
606
- maskedVars[key] = "(hidden)";
607
- }
608
- }
609
-
610
- printBindings({ ...withoutStaticAssets, vars: maskedVars });
611
-
612
- await ensureQueuesExist(config);
613
-
614
- if (!props.dryRun) {
615
- // Upload the script so it has time to propagate.
616
- // We can also now tell whether available_on_subdomain is set
617
- try {
618
- const result = await fetchResult<{
619
- available_on_subdomain: boolean;
620
- id: string | null;
621
- etag: string | null;
622
- pipeline_hash: string | null;
623
- tag: string | null;
624
- }>(
625
- workerUrl,
626
- {
627
- method: "PUT",
628
- body: createWorkerUploadForm(worker),
629
- headers: await getMetricsUsageHeaders(config.send_metrics),
630
- },
631
- new URLSearchParams({
632
- include_subdomain_availability: "true",
633
- // pass excludeScript so the whole body of the
634
- // script doesn't get included in the response
635
- excludeScript: "true",
636
- })
637
- );
638
-
639
- available_on_subdomain = result.available_on_subdomain;
640
- scriptTag = result.tag;
641
-
642
- if (config.first_party_worker) {
643
- // Print some useful information returned after publishing
644
- // Not all fields will be populated for every worker
645
- // These fields are likely to be scraped by tools, so do not rename
646
- if (result.id) logger.log("Worker ID: ", result.id);
647
- if (result.etag) logger.log("Worker ETag: ", result.etag);
648
- if (result.pipeline_hash)
649
- logger.log("Worker PipelineHash: ", result.pipeline_hash);
650
- }
651
- } catch (err) {
652
- helpIfErrorIsSizeOrScriptStartup(err, dependencies);
653
- throw err;
654
- }
655
- }
656
- } finally {
657
- if (typeof destination !== "string") {
658
- // this means we're using a temp dir,
659
- // so let's clean up before we proceed
660
- await destination.cleanup();
661
- }
662
- }
663
-
664
- if (props.dryRun) {
665
- logger.log(`--dry-run: exiting now.`);
666
- return;
667
- }
668
- assert(accountId, "Missing accountId");
669
-
670
- const uploadMs = Date.now() - start;
671
- const deployments: Promise<string[]>[] = [];
672
-
673
- if (deployToWorkersDev) {
674
- // Deploy to a subdomain of `workers.dev`
675
- const userSubdomain = await getWorkersDevSubdomain(accountId);
676
- const scriptURL =
677
- props.legacyEnv || !props.env
678
- ? `${scriptName}.${userSubdomain}.workers.dev`
679
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
680
- if (!available_on_subdomain) {
681
- // Enable the `workers.dev` subdomain.
682
- deployments.push(
683
- fetchResult(`${workerUrl}/subdomain`, {
684
- method: "POST",
685
- body: JSON.stringify({ enabled: true }),
686
- headers: {
687
- "Content-Type": "application/json",
688
- },
689
- })
690
- .then(() => [scriptURL])
691
- // Add a delay when the subdomain is first created.
692
- // This is to prevent an issue where a negative cache-hit
693
- // causes the subdomain to be unavailable for 30 seconds.
694
- // This is a temporary measure until we fix this on the edge.
695
- .then(async (url) => {
696
- await sleep(3000);
697
- return url;
698
- })
699
- );
700
- } else {
701
- deployments.push(Promise.resolve([scriptURL]));
702
- }
703
- } else {
704
- if (available_on_subdomain) {
705
- // Disable the workers.dev deployment
706
- await fetchResult(`${workerUrl}/subdomain`, {
707
- method: "POST",
708
- body: JSON.stringify({ enabled: false }),
709
- headers: {
710
- "Content-Type": "application/json",
711
- },
712
- });
713
- } else if (routes.length !== 0) {
714
- // if you get to this point it's because
715
- // you're trying to deploy a worker to a custom
716
- // domain that's already bound to another worker.
717
- // so this thing is about finding workers that have
718
- // bindings to the routes you're trying to deploy to.
719
- //
720
- // the logic is kinda similar (read: duplicated) from publishRoutesFallback,
721
- // except here we know we have a good API token or whatever so we don't need
722
- // to bother with all the error handling tomfoolery.
723
- const routesWithOtherBindings: Record<string, string[]> = {};
724
- for (const route of routes) {
725
- const zone = await getZoneForRoute(route);
726
- if (!zone) {
727
- continue;
728
- }
729
-
730
- const routePattern = typeof route === "string" ? route : route.pattern;
731
- const routesInZone = await fetchListResult<{
732
- pattern: string;
733
- script: string;
734
- }>(`/zones/${zone.id}/workers/routes`);
735
-
736
- routesInZone.forEach(({ script, pattern }) => {
737
- if (pattern === routePattern && script !== scriptName) {
738
- if (!(script in routesWithOtherBindings)) {
739
- routesWithOtherBindings[script] = [];
740
- }
741
-
742
- routesWithOtherBindings[script].push(pattern);
743
- }
744
- });
745
- }
746
-
747
- if (Object.keys(routesWithOtherBindings).length > 0) {
748
- let errorMessage =
749
- "Can't publish a worker to routes that are assigned to another worker.\n";
750
-
751
- for (const worker in routesWithOtherBindings) {
752
- const assignedRoutes = routesWithOtherBindings[worker];
753
- errorMessage += `"${worker}" is already assigned to routes:\n${assignedRoutes.map(
754
- (r) => ` - ${chalk.underline(r)}\n`
755
- )}`;
756
- }
757
-
758
- const resolution =
759
- "Unassign other workers from the routes you want to publish to, and then try again.";
760
- const dashLink = `Visit ${chalk.blue(
761
- chalk.underline(
762
- `https://dash.cloudflare.com/${accountId}/workers/overview`
763
- )
764
- )} to unassign a worker from a route.`;
765
-
766
- throw new Error(`${errorMessage}\n${resolution}\n${dashLink}`);
767
- }
768
- }
769
- }
770
-
771
- logger.log("Uploaded", workerName, formatTime(uploadMs));
772
-
773
- // Update routing table for the script.
774
- if (routesOnly.length > 0) {
775
- deployments.push(
776
- publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
777
- if (routesOnly.length > 10) {
778
- return routesOnly
779
- .slice(0, 9)
780
- .map((route) => renderRoute(route))
781
- .concat([`...and ${routesOnly.length - 10} more routes`]);
782
- }
783
- return routesOnly.map((route) => renderRoute(route));
784
- })
785
- );
786
- }
787
-
788
- // Update custom domains for the script
789
- if (customDomainsOnly.length > 0) {
790
- deployments.push(
791
- publishCustomDomains(workerUrl, accountId, customDomainsOnly)
792
- );
793
- }
794
-
795
- // Configure any schedules for the script.
796
- // TODO: rename this to `schedules`?
797
- if (triggers && triggers.length) {
798
- deployments.push(
799
- fetchResult(`${workerUrl}/schedules`, {
800
- // Note: PUT will override previous schedules on this script.
801
- method: "PUT",
802
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
803
- headers: {
804
- "Content-Type": "application/json",
805
- },
806
- }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
807
- );
808
- }
809
-
810
- if (config.queues.consumers && config.queues.consumers.length) {
811
- deployments.push(...updateQueueConsumers(config));
812
- }
813
-
814
- const targets = await Promise.all(deployments);
815
- const deployMs = Date.now() - start - uploadMs;
816
-
817
- if (deployments.length > 0) {
818
- logger.log("Published", workerName, formatTime(deployMs));
819
- for (const target of targets.flat()) {
820
- // Append protocol only on workers.dev domains
821
- logger.log(
822
- " ",
823
- (target.endsWith("workers.dev") ? "https://" : "") + target
824
- );
825
- }
826
- } else {
827
- logger.log("No publish targets for", workerName, formatTime(deployMs));
828
- }
829
-
830
- try {
831
- const deploymentsList = await fetchResult<DeploymentListRes>(
832
- `/accounts/${accountId}/workers/deployments/by-script/${scriptTag}`
833
- );
834
-
835
- logger.log("Current Deployment ID:", deploymentsList.latest.id);
836
- } catch (e) {
837
- if ((e as { code: number }).code === 10023) {
838
- // TODO: remove this try/catch once deployments is completely rolled out
839
- } else {
840
- throw e;
841
- }
842
- }
843
- }
844
-
845
- export function helpIfErrorIsSizeOrScriptStartup(
846
- err: unknown,
847
- dependencies: { [path: string]: { bytesInOutput: number } }
848
- ) {
849
- if (errIsScriptSize(err)) {
850
- printOffendingDependencies(dependencies);
851
- } else if (errIsStartupErr(err)) {
852
- const youFailed =
853
- "Your Worker failed validation because it exceeded startup limits.";
854
- const heresWhy =
855
- "To ensure fast responses, we place constraints on Worker startup -- like how much CPU it can use, or how long it can take.";
856
- const heresTheProblem =
857
- "Your Worker failed validation, which means it hit one of these startup limits.";
858
- const heresTheSolution =
859
- "Try reducing the amount of work done during startup (outside the event handler), either by removing code or relocating it inside the event handler.";
860
- logger.warn(
861
- [youFailed, heresWhy, heresTheProblem, heresTheSolution].join("\n")
862
- );
863
- }
864
- }
865
-
866
- function formatTime(duration: number) {
867
- return `(${(duration / 1000).toFixed(2)} sec)`;
868
- }
869
-
870
- /**
871
- * Associate the newly deployed Worker with the given routes.
872
- */
873
- async function publishRoutes(
874
- routes: Route[],
875
- {
876
- workerUrl,
877
- scriptName,
878
- notProd,
879
- }: { workerUrl: string; scriptName: string; notProd: boolean }
880
- ): Promise<string[]> {
881
- try {
882
- return await fetchResult(`${workerUrl}/routes`, {
883
- // Note: PUT will delete previous routes on this script.
884
- method: "PUT",
885
- body: JSON.stringify(
886
- routes.map((route) =>
887
- typeof route !== "object" ? { pattern: route } : route
888
- )
889
- ),
890
- headers: {
891
- "Content-Type": "application/json",
892
- },
893
- });
894
- } catch (e) {
895
- if (isAuthenticationError(e)) {
896
- // An authentication error is probably due to a known issue,
897
- // where the user is logged in via an API token that does not have "All Zones".
898
- return await publishRoutesFallback(routes, { scriptName, notProd });
899
- } else {
900
- throw e;
901
- }
902
- }
903
- }
904
-
905
- /**
906
- * Try updating routes for the Worker using a less optimal zone-based API.
907
- *
908
- * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
909
- */
910
- async function publishRoutesFallback(
911
- routes: Route[],
912
- { scriptName, notProd }: { scriptName: string; notProd: boolean }
913
- ) {
914
- if (notProd) {
915
- throw new Error(
916
- "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
917
- "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
918
- );
919
- }
920
- logger.warn(
921
- "The current authentication token does not have 'All Zones' permissions.\n" +
922
- "Falling back to using the zone-based API endpoint to update each route individually.\n" +
923
- "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
924
- "Existing routes for this Worker in such zones will not be deleted."
925
- );
926
-
927
- const deployedRoutes: string[] = [];
928
-
929
- // Collect the routes (and their zones) that will be deployed.
930
- const activeZones = new Map<string, string>();
931
- const routesToDeploy = new Map<string, string>();
932
- for (const route of routes) {
933
- const zone = await getZoneForRoute(route);
934
- if (zone) {
935
- activeZones.set(zone.id, zone.host);
936
- routesToDeploy.set(
937
- typeof route === "string" ? route : route.pattern,
938
- zone.id
939
- );
940
- }
941
- }
942
-
943
- // Collect the routes that are already deployed.
944
- const allRoutes = new Map<string, string>();
945
- const alreadyDeployedRoutes = new Set<string>();
946
- for (const [zone, host] of activeZones) {
947
- try {
948
- for (const { pattern, script } of await fetchListResult<{
949
- pattern: string;
950
- script: string;
951
- }>(`/zones/${zone}/workers/routes`)) {
952
- allRoutes.set(pattern, script);
953
- if (script === scriptName) {
954
- alreadyDeployedRoutes.add(pattern);
955
- }
956
- }
957
- } catch (e) {
958
- if (isAuthenticationError(e)) {
959
- e.notes.push({
960
- text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
961
- });
962
- }
963
- throw e;
964
- }
965
- }
966
-
967
- // Deploy each route that is not already deployed.
968
- for (const [routePattern, zoneId] of routesToDeploy.entries()) {
969
- if (allRoutes.has(routePattern)) {
970
- const knownScript = allRoutes.get(routePattern);
971
- if (knownScript === scriptName) {
972
- // This route is already associated with this worker, so no need to hit the API.
973
- alreadyDeployedRoutes.delete(routePattern);
974
- continue;
975
- } else {
976
- throw new Error(
977
- `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
978
- );
979
- }
980
- }
981
-
982
- const { pattern } = await fetchResult<{ pattern: string }>(
983
- `/zones/${zoneId}/workers/routes`,
984
- {
985
- method: "POST",
986
- body: JSON.stringify({
987
- pattern: routePattern,
988
- script: scriptName,
989
- }),
990
- headers: {
991
- "Content-Type": "application/json",
992
- },
993
- }
994
- );
995
-
996
- deployedRoutes.push(pattern);
997
- }
998
-
999
- if (alreadyDeployedRoutes.size) {
1000
- logger.warn(
1001
- "Previously deployed routes:\n" +
1002
- "The following routes were already associated with this worker, and have not been deleted:\n" +
1003
- [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
1004
- "If these routes are not wanted then you can remove them in the dashboard."
1005
- );
1006
- }
1007
-
1008
- return deployedRoutes;
1009
- }
1010
-
1011
- function isAuthenticationError(e: unknown): e is ParseError {
1012
- return e instanceof ParseError && (e as { code?: number }).code === 10000;
1013
- }
1014
-
1015
- async function ensureQueuesExist(config: Config) {
1016
- const producers = (config.queues.producers || []).map(
1017
- (producer) => producer.queue
1018
- );
1019
- const consumers = (config.queues.consumers || []).map(
1020
- (consumer) => consumer.queue
1021
- );
1022
-
1023
- const queueNames = producers.concat(consumers);
1024
- for (const queue of queueNames) {
1025
- try {
1026
- await getQueue(config, queue);
1027
- } catch (err) {
1028
- const queueErr = err as FetchError;
1029
- if (queueErr.code === 11000) {
1030
- // queue_not_found
1031
- throw new Error(
1032
- `Queue "${queue}" does not exist. To create it, run: wrangler queues create ${queue}`
1033
- );
1034
- }
1035
- throw err;
1036
- }
1037
- }
1038
- }
1039
-
1040
- function updateQueueConsumers(config: Config): Promise<string[]>[] {
1041
- const consumers = config.queues.consumers || [];
1042
- return consumers.map((consumer) => {
1043
- const body: PutConsumerBody = {
1044
- dead_letter_queue: consumer.dead_letter_queue,
1045
- settings: {
1046
- batch_size: consumer.max_batch_size,
1047
- max_retries: consumer.max_retries,
1048
- max_wait_time_ms: consumer.max_batch_timeout
1049
- ? 1000 * consumer.max_batch_timeout
1050
- : undefined,
1051
- },
1052
- };
1053
-
1054
- if (config.name === undefined) {
1055
- // TODO: how can we reliably get the current script name?
1056
- throw new Error("Script name is required to update queue consumers");
1057
- }
1058
- const scriptName = config.name;
1059
- const envName = undefined; // TODO: script environment for wrangler publish?
1060
- return putConsumer(config, consumer.queue, scriptName, envName, body).then(
1061
- () => [`Consumer for ${consumer.queue}`]
1062
- );
1063
- });
1064
- }