wrangler 0.0.0-ecc8b172 → 0.0.0-ecded1af1

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