wrangler 0.0.0-e2f9bb2 → 0.0.0-e305903a

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