wrangler 0.0.0-e9e9872 → 0.0.0-e9f8a2fa

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 (178) hide show
  1. package/README.md +25 -13
  2. package/bin/wrangler.js +51 -61
  3. package/config-schema.json +2939 -0
  4. package/package.json +222 -160
  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 +0 -4
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +133 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  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-pretty-error.ts +40 -0
  20. package/templates/middleware/middleware-scheduled.ts +15 -0
  21. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  22. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  23. package/templates/modules-watch-stub.js +4 -0
  24. package/templates/new-worker-scheduled.ts +1 -1
  25. package/templates/new-worker.js +1 -1
  26. package/templates/new-worker.ts +4 -1
  27. package/templates/pages-dev-pipeline.ts +32 -0
  28. package/templates/pages-dev-util.ts +55 -0
  29. package/templates/pages-shim.ts +9 -0
  30. package/templates/pages-template-plugin.ts +53 -18
  31. package/templates/pages-template-worker.ts +49 -12
  32. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  33. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  34. package/templates/tsconfig-sanity.ts +11 -0
  35. package/templates/tsconfig.init.json +105 -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 +240 -0
  40. package/wrangler-dist/ProxyWorker.js.map +6 -0
  41. package/wrangler-dist/cli.d.ts +23879 -146
  42. package/wrangler-dist/cli.js +186358 -107113
  43. package/wrangler-dist/wasm-sync.wasm +0 -0
  44. package/import_meta_url.js +0 -3
  45. package/miniflare-config-stubs/.env.empty +0 -0
  46. package/miniflare-config-stubs/package.empty.json +0 -1
  47. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  48. package/miniflare-dist/index.mjs +0 -4894
  49. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  50. package/src/__tests__/config-cache.test.ts +0 -42
  51. package/src/__tests__/configuration.test.ts +0 -3946
  52. package/src/__tests__/dev.test.tsx +0 -1159
  53. package/src/__tests__/guess-worker-format.test.ts +0 -85
  54. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  55. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  56. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  57. package/src/__tests__/helpers/mock-bin.ts +0 -36
  58. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  59. package/src/__tests__/helpers/mock-console.ts +0 -97
  60. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  61. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  62. package/src/__tests__/helpers/mock-istty.ts +0 -74
  63. package/src/__tests__/helpers/mock-kv.ts +0 -33
  64. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  65. package/src/__tests__/helpers/mock-process.ts +0 -39
  66. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  67. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  68. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  69. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  70. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  71. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  72. package/src/__tests__/https-options.test.ts +0 -163
  73. package/src/__tests__/index.test.ts +0 -262
  74. package/src/__tests__/init.test.ts +0 -1992
  75. package/src/__tests__/jest.setup.ts +0 -120
  76. package/src/__tests__/kv.test.ts +0 -1650
  77. package/src/__tests__/logger.test.ts +0 -141
  78. package/src/__tests__/package-manager.test.ts +0 -353
  79. package/src/__tests__/pages.test.ts +0 -1254
  80. package/src/__tests__/parse.test.ts +0 -330
  81. package/src/__tests__/publish.test.ts +0 -6595
  82. package/src/__tests__/pubsub.test.ts +0 -367
  83. package/src/__tests__/r2.test.ts +0 -233
  84. package/src/__tests__/route.test.ts +0 -45
  85. package/src/__tests__/secret.test.ts +0 -492
  86. package/src/__tests__/tail.test.ts +0 -698
  87. package/src/__tests__/user.test.ts +0 -143
  88. package/src/__tests__/whoami.test.tsx +0 -230
  89. package/src/__tests__/worker-namespace.test.ts +0 -327
  90. package/src/abort.d.ts +0 -3
  91. package/src/api/dev.ts +0 -52
  92. package/src/api/index.ts +0 -1
  93. package/src/bundle-reporter.tsx +0 -29
  94. package/src/bundle.ts +0 -212
  95. package/src/cfetch/index.ts +0 -121
  96. package/src/cfetch/internal.ts +0 -149
  97. package/src/cli.ts +0 -27
  98. package/src/config/README.md +0 -107
  99. package/src/config/config.ts +0 -243
  100. package/src/config/diagnostics.ts +0 -80
  101. package/src/config/environment.ts +0 -453
  102. package/src/config/index.ts +0 -238
  103. package/src/config/validation-helpers.ts +0 -584
  104. package/src/config/validation.ts +0 -1745
  105. package/src/config-cache.ts +0 -83
  106. package/src/create-worker-preview.ts +0 -255
  107. package/src/create-worker-upload-form.ts +0 -263
  108. package/src/dev/dev-vars.ts +0 -36
  109. package/src/dev/dev.tsx +0 -417
  110. package/src/dev/local.tsx +0 -354
  111. package/src/dev/remote.tsx +0 -382
  112. package/src/dev/use-esbuild.ts +0 -150
  113. package/src/dev.tsx +0 -538
  114. package/src/dialogs.tsx +0 -135
  115. package/src/durable.ts +0 -102
  116. package/src/entry.ts +0 -328
  117. package/src/environment-variables.ts +0 -35
  118. package/src/errors.ts +0 -11
  119. package/src/faye-websocket.d.ts +0 -6
  120. package/src/generate.ts +0 -33
  121. package/src/git-client.ts +0 -42
  122. package/src/global-wrangler-config-path.ts +0 -26
  123. package/src/https-options.ts +0 -127
  124. package/src/index.tsx +0 -1896
  125. package/src/init.ts +0 -549
  126. package/src/inspect.ts +0 -662
  127. package/src/intl-polyfill.d.ts +0 -139
  128. package/src/is-interactive.ts +0 -12
  129. package/src/kv.ts +0 -430
  130. package/src/logger.ts +0 -73
  131. package/src/miniflare-cli/README.md +0 -30
  132. package/src/miniflare-cli/enum-keys.ts +0 -17
  133. package/src/miniflare-cli/index.ts +0 -53
  134. package/src/miniflare-cli/request-context.ts +0 -40
  135. package/src/module-collection.ts +0 -258
  136. package/src/open-in-browser.ts +0 -17
  137. package/src/package-manager.ts +0 -219
  138. package/src/pages/build.tsx +0 -202
  139. package/src/pages/constants.ts +0 -7
  140. package/src/pages/deployments.tsx +0 -101
  141. package/src/pages/dev.tsx +0 -964
  142. package/src/pages/functions/buildPlugin.ts +0 -105
  143. package/src/pages/functions/buildWorker.ts +0 -151
  144. package/src/pages/functions/filepath-routing.test.ts +0 -234
  145. package/src/pages/functions/filepath-routing.ts +0 -189
  146. package/src/pages/functions/identifiers.ts +0 -78
  147. package/src/pages/functions/routes.ts +0 -151
  148. package/src/pages/index.tsx +0 -84
  149. package/src/pages/projects.tsx +0 -157
  150. package/src/pages/publish.tsx +0 -335
  151. package/src/pages/types.ts +0 -40
  152. package/src/pages/upload.tsx +0 -396
  153. package/src/pages/utils.ts +0 -12
  154. package/src/parse.ts +0 -286
  155. package/src/paths.ts +0 -26
  156. package/src/preview.ts +0 -31
  157. package/src/proxy.ts +0 -476
  158. package/src/publish.ts +0 -780
  159. package/src/pubsub/index.ts +0 -286
  160. package/src/pubsub/pubsub-commands.tsx +0 -577
  161. package/src/r2.ts +0 -50
  162. package/src/selfsigned.d.ts +0 -29
  163. package/src/sites.tsx +0 -372
  164. package/src/tail/filters.ts +0 -279
  165. package/src/tail/index.ts +0 -299
  166. package/src/tail/printing.ts +0 -67
  167. package/src/update-check.ts +0 -19
  168. package/src/user/choose-account.tsx +0 -60
  169. package/src/user/env-vars.ts +0 -46
  170. package/src/user/generate-auth-url.ts +0 -33
  171. package/src/user/generate-random-state.ts +0 -16
  172. package/src/user/index.ts +0 -3
  173. package/src/user/user.tsx +0 -1170
  174. package/src/whoami.tsx +0 -90
  175. package/src/worker-namespace.ts +0 -190
  176. package/src/worker.ts +0 -191
  177. package/src/zones.ts +0 -76
  178. package/templates/static-asset-facade.js +0 -49
package/src/publish.ts DELETED
@@ -1,780 +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 tmp from "tmp-promise";
6
- import { bundleWorker } from "./bundle";
7
- import { printBundleSize } from "./bundle-reporter";
8
- import { fetchListResult, fetchResult } from "./cfetch";
9
- import { printBindings } from "./config";
10
- import { createWorkerUploadForm } from "./create-worker-upload-form";
11
- import { confirm } from "./dialogs";
12
- import { getMigrationsToUpload } from "./durable";
13
- import { logger } from "./logger";
14
- import { ParseError } from "./parse";
15
- import { syncAssets } from "./sites";
16
- import { getZoneForRoute } from "./zones";
17
- import type { Config } from "./config";
18
- import type {
19
- Route,
20
- ZoneIdRoute,
21
- ZoneNameRoute,
22
- CustomDomainRoute,
23
- } from "./config/environment";
24
- import type { Entry } from "./entry";
25
- import type { AssetPaths } from "./sites";
26
- import type { CfWorkerInit } from "./worker";
27
-
28
- type Props = {
29
- config: Config;
30
- accountId: string | undefined;
31
- entry: Entry;
32
- rules: Config["rules"];
33
- name: string | undefined;
34
- env: string | undefined;
35
- compatibilityDate: string | undefined;
36
- compatibilityFlags: string[] | undefined;
37
- assetPaths: AssetPaths | undefined;
38
- triggers: string[] | undefined;
39
- routes: string[] | undefined;
40
- legacyEnv: boolean | undefined;
41
- jsxFactory: string | undefined;
42
- jsxFragment: string | undefined;
43
- tsconfig: string | undefined;
44
- isWorkersSite: boolean;
45
- minify: boolean | undefined;
46
- nodeCompat: boolean | undefined;
47
- outDir: string | undefined;
48
- dryRun: boolean | undefined;
49
- noBundle: boolean | undefined;
50
- };
51
-
52
- type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
53
-
54
- function sleep(ms: number) {
55
- return new Promise((resolve) => setTimeout(resolve, ms));
56
- }
57
-
58
- function renderRoute(route: Route): string {
59
- let result = "";
60
- if (typeof route === "string") {
61
- result = route;
62
- } else {
63
- result = route.pattern;
64
- const isCustomDomain = Boolean(
65
- "custom_domain" in route && route.custom_domain
66
- );
67
- if (isCustomDomain && "zone_id" in route) {
68
- result += ` (custom domain - zone id: ${route.zone_id})`;
69
- } else if (isCustomDomain && "zone_name" in route) {
70
- result += ` (custom domain - zone name: ${route.zone_name})`;
71
- } else if (isCustomDomain) {
72
- result += ` (custom domain)`;
73
- } else if ("zone_id" in route) {
74
- result += ` (zone id: ${route.zone_id})`;
75
- } else if ("zone_name" in route) {
76
- result += ` (zone name: ${route.zone_name})`;
77
- }
78
- }
79
- return result;
80
- }
81
-
82
- // this function takes a string with quotes in it
83
- // (i.e. `hello "world", if that really is your name`)
84
- // and peels out the first instance of a substring
85
- // bounded by quotes (so, in the example above, `world`)
86
- //
87
- // this is useful because the /domains api will return
88
- // which domains conflicted in an error message, bounded
89
- // by a string, which we can use to provide helpful
90
- // messages to a user
91
- function getQuoteBoundedSubstring(content: string) {
92
- const matches = content.split('"');
93
- return matches[1] ?? "";
94
- }
95
-
96
- function isOriginConflictError(
97
- e: unknown
98
- ): e is { code: 100116; message: string; notes: Array<{ text: string }> } {
99
- return (
100
- typeof e === "object" &&
101
- e !== null &&
102
- (e as { code: number }).code === 100116
103
- );
104
- }
105
-
106
- function isDNSConflictError(
107
- e: unknown
108
- ): e is { code: 100117; message: string; notes: Array<{ text: string }> } {
109
- return (
110
- typeof e === "object" &&
111
- e !== null &&
112
- (e as { code: number }).code === 100117
113
- );
114
- }
115
-
116
- // empty error class to throw and then explicitly catch via `instanceof`
117
- class CustomDomainOverrideRejected extends Error {}
118
-
119
- // publishing to custom domains involves a few more steps than just updating
120
- // the routing table, and thus the api implementing it is fairly defensive -
121
- // it will error eagerly on conflicts against existing domains or existing
122
- // managed DNS records
123
- //
124
- // however, you can pass params to override the errors. we start on the
125
- // defensive path, and if one of these errors occur, we prompt the user
126
- // for confirmation that they do indeed want to override the conflicts, and
127
- // then retry the request with the right override added
128
- //
129
- // if a user does not confirm that they want to override, we skip publishing
130
- // to these custom domains, but continue on through the rest of the
131
- // publish stage
132
- function publishCustomDomains(
133
- workerUrl: string,
134
- domains: Array<RouteObject>
135
- ): Promise<string[]> {
136
- const config = {
137
- override_scope: true,
138
- override_existing_origin: false,
139
- override_existing_dns_record: false,
140
- };
141
- const origins = domains.map((domainRoute) => {
142
- return {
143
- hostname: domainRoute.pattern,
144
- zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
145
- zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
146
- };
147
- });
148
-
149
- if (!process.stdout.isTTY) {
150
- // running in non-interactive mode.
151
- // existing origins / dns records are not indicative of errors,
152
- // so we aggressively update rather than aggressively fail
153
- config.override_existing_origin = true;
154
- config.override_existing_dns_record = true;
155
- }
156
-
157
- // Mixing promise chains with async/await is funky, but it allows us to keep related
158
- // logic synchronous-looking (i.e. prompting for confirmation and then re-requesting)
159
- // while retaining the flexibility of promise chain fall-throughs. We can group error
160
- // handling logic in dedicated catch calls, and all we have to do is re-throw an
161
- // error and it will pass down to the next catch call
162
- return fetchResult(`${workerUrl}/domains`, {
163
- method: "PUT",
164
- body: JSON.stringify({ ...config, origins }),
165
- headers: {
166
- "Content-Type": "application/json",
167
- },
168
- })
169
- .catch(async (err) => {
170
- if (isOriginConflictError(err)) {
171
- const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
172
- const shouldContinue = await confirm(
173
- `Custom Domains already exist for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
174
- );
175
- if (!shouldContinue) {
176
- throw new CustomDomainOverrideRejected();
177
- }
178
- config.override_existing_origin = true;
179
- await fetchResult(`${workerUrl}/domains`, {
180
- method: "PUT",
181
- body: JSON.stringify({ ...config, origins }),
182
- headers: {
183
- "Content-Type": "application/json",
184
- },
185
- });
186
- } else {
187
- throw err;
188
- }
189
- })
190
- .catch(async (err) => {
191
- if (isDNSConflictError(err)) {
192
- const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
193
- const shouldContinue = await confirm(
194
- `You already have conflicting DNS records for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
195
- );
196
- if (!shouldContinue) {
197
- throw new CustomDomainOverrideRejected();
198
- }
199
- config.override_existing_dns_record = true;
200
- await fetchResult(`${workerUrl}/domains`, {
201
- method: "PUT",
202
- body: JSON.stringify({ ...config, origins }),
203
- headers: {
204
- "Content-Type": "application/json",
205
- },
206
- });
207
- } else {
208
- throw err;
209
- }
210
- })
211
- .then(() => domains.map((domain) => renderRoute(domain)))
212
- .catch((err) => {
213
- if (err instanceof CustomDomainOverrideRejected) {
214
- return [
215
- domains.length > 1
216
- ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
217
- : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
218
- ];
219
- }
220
- throw err;
221
- });
222
- }
223
-
224
- export default async function publish(props: Props): Promise<void> {
225
- // TODO: warn if git/hg has uncommitted changes
226
- const { config, accountId } = props;
227
-
228
- if (!(props.compatibilityDate || config.compatibility_date)) {
229
- const compatibilityDateStr = `${new Date().getFullYear()}-${(
230
- new Date().getMonth() + ""
231
- ).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
232
-
233
- throw new Error(`A compatibility_date is required when publishing. Add the following to your wrangler.toml file:.
234
- \`\`\`
235
- compatibility_date = "${compatibilityDateStr}"
236
- \`\`\`
237
- Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
238
- See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
239
- }
240
-
241
- const triggers = props.triggers || config.triggers?.crons;
242
- const routes =
243
- props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
244
- const routesOnly: Array<Route> = [];
245
- const customDomainsOnly: Array<RouteObject> = [];
246
- for (const route of routes) {
247
- if (typeof route !== "string" && route.custom_domain) {
248
- if (route.pattern.includes("*")) {
249
- throw new Error(
250
- `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
251
- );
252
- }
253
- if (route.pattern.includes("/")) {
254
- throw new Error(
255
- `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
256
- );
257
- }
258
- customDomainsOnly.push(route);
259
- } else {
260
- routesOnly.push(route);
261
- }
262
- }
263
-
264
- // deployToWorkersDev defaults to true only if there aren't any routes defined
265
- const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
266
-
267
- const jsxFactory = props.jsxFactory || config.jsx_factory;
268
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
269
-
270
- const minify = props.minify ?? config.minify;
271
-
272
- const nodeCompat = props.nodeCompat ?? config.node_compat;
273
- if (nodeCompat) {
274
- logger.warn(
275
- "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."
276
- );
277
- }
278
-
279
- const scriptName = props.name;
280
- assert(
281
- scriptName,
282
- '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>"`'
283
- );
284
-
285
- assert(
286
- !config.site || config.site.bucket,
287
- "A [site] definition requires a `bucket` field with a path to the site's assets directory."
288
- );
289
-
290
- if (props.outDir) {
291
- // we're using a custom output directory,
292
- // so let's first ensure it exists
293
- mkdirSync(props.outDir, { recursive: true });
294
- // add a README
295
- const readmePath = path.join(props.outDir, "README.md");
296
- writeFileSync(
297
- readmePath,
298
- `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
299
- );
300
- }
301
-
302
- const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
303
- const envName = props.env ?? "production";
304
-
305
- const start = Date.now();
306
- const notProd = Boolean(!props.legacyEnv && props.env);
307
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
308
- const workerUrl = notProd
309
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
310
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
311
-
312
- let available_on_subdomain; // we'll set this later
313
-
314
- const { format } = props.entry;
315
-
316
- if (
317
- !props.isWorkersSite &&
318
- Boolean(props.assetPaths) &&
319
- format === "service-worker"
320
- ) {
321
- throw new Error(
322
- "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/"
323
- );
324
- }
325
-
326
- if (config.wasm_modules && format === "modules") {
327
- throw new Error(
328
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
329
- );
330
- }
331
-
332
- if (config.text_blobs && format === "modules") {
333
- throw new Error(
334
- "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"
335
- );
336
- }
337
-
338
- if (config.data_blobs && format === "modules") {
339
- throw new Error(
340
- "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"
341
- );
342
- }
343
- try {
344
- if (props.noBundle) {
345
- // if we're not building, let's just copy the entry to the destination directory
346
- const destinationDir =
347
- typeof destination === "string" ? destination : destination.path;
348
- mkdirSync(destinationDir, { recursive: true });
349
- writeFileSync(
350
- path.join(destinationDir, path.basename(props.entry.file)),
351
- readFileSync(props.entry.file, "utf-8")
352
- );
353
- }
354
-
355
- const {
356
- modules,
357
- resolvedEntryPointPath,
358
- bundleType,
359
- }: Awaited<ReturnType<typeof bundleWorker>> = props.noBundle
360
- ? // we can skip the whole bundling step and mock a bundle here
361
- {
362
- modules: [],
363
- resolvedEntryPointPath: props.entry.file,
364
- bundleType: props.entry.format === "modules" ? "esm" : "commonjs",
365
- stop: undefined,
366
- }
367
- : await bundleWorker(
368
- props.entry,
369
- typeof destination === "string" ? destination : destination.path,
370
- {
371
- serveAssetsFromWorker:
372
- !props.isWorkersSite && Boolean(props.assetPaths),
373
- jsxFactory,
374
- jsxFragment,
375
- rules: props.rules,
376
- tsconfig: props.tsconfig ?? config.tsconfig,
377
- minify,
378
- nodeCompat,
379
- define: config.define,
380
- checkFetch: false,
381
- }
382
- );
383
-
384
- const content = readFileSync(resolvedEntryPointPath, {
385
- encoding: "utf-8",
386
- });
387
-
388
- // durable object migrations
389
- const migrations = !props.dryRun
390
- ? await getMigrationsToUpload(scriptName, {
391
- accountId,
392
- config,
393
- legacyEnv: props.legacyEnv,
394
- env: props.env,
395
- })
396
- : undefined;
397
-
398
- const assets = await syncAssets(
399
- accountId,
400
- // When we're using the newer service environments, we wouldn't
401
- // have added the env name on to the script name. However, we must
402
- // include it in the kv namespace name regardless (since there's no
403
- // concept of service environments for kv namespaces yet).
404
- scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
405
- props.assetPaths,
406
- false,
407
- props.dryRun
408
- );
409
-
410
- const bindings: CfWorkerInit["bindings"] = {
411
- kv_namespaces: (config.kv_namespaces || []).concat(
412
- assets.namespace
413
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
414
- : []
415
- ),
416
- vars: config.vars,
417
- wasm_modules: config.wasm_modules,
418
- text_blobs: {
419
- ...config.text_blobs,
420
- ...(assets.manifest &&
421
- format === "service-worker" && {
422
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
423
- }),
424
- },
425
- data_blobs: config.data_blobs,
426
- durable_objects: config.durable_objects,
427
- r2_buckets: config.r2_buckets,
428
- services: config.services,
429
- worker_namespaces: config.worker_namespaces,
430
- unsafe: config.unsafe?.bindings,
431
- };
432
-
433
- if (assets.manifest) {
434
- modules.push({
435
- name: "__STATIC_CONTENT_MANIFEST",
436
- content: JSON.stringify(assets.manifest),
437
- type: "text",
438
- });
439
- }
440
-
441
- const worker: CfWorkerInit = {
442
- name: scriptName,
443
- main: {
444
- name: path.basename(resolvedEntryPointPath),
445
- content: content,
446
- type: bundleType,
447
- },
448
- bindings,
449
- migrations,
450
- modules,
451
- compatibility_date: props.compatibilityDate ?? config.compatibility_date,
452
- compatibility_flags:
453
- props.compatibilityFlags ?? config.compatibility_flags,
454
- usage_model: config.usage_model,
455
- };
456
-
457
- void printBundleSize(
458
- { name: path.basename(resolvedEntryPointPath), content: content },
459
- modules
460
- );
461
-
462
- const withoutStaticAssets = {
463
- ...bindings,
464
- kv_namespaces: config.kv_namespaces,
465
- text_blobs: config.text_blobs,
466
- };
467
- printBindings(withoutStaticAssets);
468
-
469
- if (!props.dryRun) {
470
- // Upload the script so it has time to propagate.
471
- // We can also now tell whether available_on_subdomain is set
472
- const result = await fetchResult<{
473
- available_on_subdomain: boolean;
474
- id: string | null;
475
- etag: string | null;
476
- pipeline_hash: string | null;
477
- }>(
478
- workerUrl,
479
- {
480
- method: "PUT",
481
- body: createWorkerUploadForm(worker),
482
- },
483
- new URLSearchParams({
484
- include_subdomain_availability: "true",
485
- // pass excludeScript so the whole body of the
486
- // script doesn't get included in the response
487
- excludeScript: "true",
488
- })
489
- );
490
-
491
- available_on_subdomain = result.available_on_subdomain;
492
-
493
- // Print some useful information returned after publishing
494
- // Not all fields will be populated for every worker
495
- // These fields are likely to be scraped by tools, so do not rename
496
- if (result.id) logger.log("Worker ID: ", result.id);
497
- if (result.etag) logger.log("Worker ETag: ", result.etag);
498
- if (result.pipeline_hash)
499
- logger.log("Worker PipelineHash: ", result.pipeline_hash);
500
- }
501
- } finally {
502
- if (typeof destination !== "string") {
503
- // this means we're using a temp dir,
504
- // so let's clean up before we proceed
505
- await destination.cleanup();
506
- }
507
- }
508
-
509
- if (props.dryRun) {
510
- logger.log(`--dry-run: exiting now.`);
511
- return;
512
- }
513
- assert(accountId, "Missing accountId");
514
-
515
- const uploadMs = Date.now() - start;
516
- const deployments: Promise<string[]>[] = [];
517
-
518
- if (deployToWorkersDev) {
519
- // Deploy to a subdomain of `workers.dev`
520
- const userSubdomain = await getSubdomain(accountId);
521
- const scriptURL =
522
- props.legacyEnv || !props.env
523
- ? `${scriptName}.${userSubdomain}.workers.dev`
524
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
525
- if (!available_on_subdomain) {
526
- // Enable the `workers.dev` subdomain.
527
- deployments.push(
528
- fetchResult(`${workerUrl}/subdomain`, {
529
- method: "POST",
530
- body: JSON.stringify({ enabled: true }),
531
- headers: {
532
- "Content-Type": "application/json",
533
- },
534
- })
535
- .then(() => [scriptURL])
536
- // Add a delay when the subdomain is first created.
537
- // This is to prevent an issue where a negative cache-hit
538
- // causes the subdomain to be unavailable for 30 seconds.
539
- // This is a temporary measure until we fix this on the edge.
540
- .then(async (url) => {
541
- await sleep(3000);
542
- return url;
543
- })
544
- );
545
- } else {
546
- deployments.push(Promise.resolve([scriptURL]));
547
- }
548
- } else {
549
- if (available_on_subdomain) {
550
- // Disable the workers.dev deployment
551
- await fetchResult(`${workerUrl}/subdomain`, {
552
- method: "POST",
553
- body: JSON.stringify({ enabled: false }),
554
- headers: {
555
- "Content-Type": "application/json",
556
- },
557
- });
558
- }
559
- }
560
-
561
- logger.log("Uploaded", workerName, formatTime(uploadMs));
562
-
563
- // Update routing table for the script.
564
- if (routesOnly.length > 0) {
565
- deployments.push(
566
- publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
567
- if (routesOnly.length > 10) {
568
- return routesOnly
569
- .slice(0, 9)
570
- .map((route) => renderRoute(route))
571
- .concat([`...and ${routesOnly.length - 10} more routes`]);
572
- }
573
- return routesOnly.map((route) => renderRoute(route));
574
- })
575
- );
576
- }
577
-
578
- // Update custom domains for the script
579
- if (customDomainsOnly.length > 0) {
580
- deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
581
- }
582
-
583
- // Configure any schedules for the script.
584
- // TODO: rename this to `schedules`?
585
- if (triggers && triggers.length) {
586
- deployments.push(
587
- fetchResult(`${workerUrl}/schedules`, {
588
- // Note: PUT will override previous schedules on this script.
589
- method: "PUT",
590
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
591
- headers: {
592
- "Content-Type": "application/json",
593
- },
594
- }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
595
- );
596
- }
597
-
598
- const targets = await Promise.all(deployments);
599
- const deployMs = Date.now() - start - uploadMs;
600
-
601
- if (deployments.length > 0) {
602
- logger.log("Published", workerName, formatTime(deployMs));
603
- for (const target of targets.flat()) {
604
- logger.log(" ", target);
605
- }
606
- } else {
607
- logger.log("No publish targets for", workerName, formatTime(deployMs));
608
- }
609
- }
610
-
611
- function formatTime(duration: number) {
612
- return `(${(duration / 1000).toFixed(2)} sec)`;
613
- }
614
-
615
- async function getSubdomain(accountId: string): Promise<string> {
616
- try {
617
- const { subdomain } = await fetchResult(
618
- `/accounts/${accountId}/workers/subdomain`
619
- );
620
- return subdomain;
621
- } catch (e) {
622
- const error = e as { code?: number };
623
- if (typeof error === "object" && !!error && error.code === 10007) {
624
- // 10007 error code: not found
625
- // https://api.cloudflare.com/#worker-subdomain-get-subdomain
626
-
627
- const errorMessage =
628
- "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
629
- const solutionMessage =
630
- "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
631
- const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
632
-
633
- throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
634
- } else {
635
- throw e;
636
- }
637
- }
638
- }
639
-
640
- /**
641
- * Associate the newly deployed Worker with the given routes.
642
- */
643
- async function publishRoutes(
644
- routes: Route[],
645
- {
646
- workerUrl,
647
- scriptName,
648
- notProd,
649
- }: { workerUrl: string; scriptName: string; notProd: boolean }
650
- ): Promise<string[]> {
651
- try {
652
- return await fetchResult(`${workerUrl}/routes`, {
653
- // Note: PUT will delete previous routes on this script.
654
- method: "PUT",
655
- body: JSON.stringify(
656
- routes.map((route) =>
657
- typeof route !== "object" ? { pattern: route } : route
658
- )
659
- ),
660
- headers: {
661
- "Content-Type": "application/json",
662
- },
663
- });
664
- } catch (e) {
665
- if (isAuthenticationError(e)) {
666
- // An authentication error is probably due to a known issue,
667
- // where the user is logged in via an API token that does not have "All Zones".
668
- return await publishRoutesFallback(routes, { scriptName, notProd });
669
- } else {
670
- throw e;
671
- }
672
- }
673
- }
674
-
675
- /**
676
- * Try updating routes for the Worker using a less optimal zone-based API.
677
- *
678
- * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
679
- */
680
- async function publishRoutesFallback(
681
- routes: Route[],
682
- { scriptName, notProd }: { scriptName: string; notProd: boolean }
683
- ) {
684
- if (notProd) {
685
- throw new Error(
686
- "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
687
- "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
688
- );
689
- }
690
- logger.warn(
691
- "The current authentication token does not have 'All Zones' permissions.\n" +
692
- "Falling back to using the zone-based API endpoint to update each route individually.\n" +
693
- "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
694
- "Existing routes for this Worker in such zones will not be deleted."
695
- );
696
-
697
- const deployedRoutes: string[] = [];
698
-
699
- // Collect the routes (and their zones) that will be deployed.
700
- const activeZones = new Map<string, string>();
701
- const routesToDeploy = new Map<string, string>();
702
- for (const route of routes) {
703
- const zone = await getZoneForRoute(route);
704
- if (zone) {
705
- activeZones.set(zone.id, zone.host);
706
- routesToDeploy.set(
707
- typeof route === "string" ? route : route.pattern,
708
- zone.id
709
- );
710
- }
711
- }
712
-
713
- // Collect the routes that are already deployed.
714
- const allRoutes = new Map<string, string>();
715
- const alreadyDeployedRoutes = new Set<string>();
716
- for (const [zone, host] of activeZones) {
717
- try {
718
- for (const { pattern, script } of await fetchListResult<{
719
- pattern: string;
720
- script: string;
721
- }>(`/zones/${zone}/workers/routes`)) {
722
- allRoutes.set(pattern, script);
723
- if (script === scriptName) {
724
- alreadyDeployedRoutes.add(pattern);
725
- }
726
- }
727
- } catch (e) {
728
- if (isAuthenticationError(e)) {
729
- e.notes.push({
730
- text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
731
- });
732
- }
733
- throw e;
734
- }
735
- }
736
-
737
- // Deploy each route that is not already deployed.
738
- for (const [routePattern, zoneId] of routesToDeploy.entries()) {
739
- if (allRoutes.has(routePattern)) {
740
- const knownScript = allRoutes.get(routePattern);
741
- if (knownScript === scriptName) {
742
- // This route is already associated with this worker, so no need to hit the API.
743
- alreadyDeployedRoutes.delete(routePattern);
744
- continue;
745
- } else {
746
- throw new Error(
747
- `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
748
- );
749
- }
750
- }
751
-
752
- const { pattern } = await fetchResult(`/zones/${zoneId}/workers/routes`, {
753
- method: "POST",
754
- body: JSON.stringify({
755
- pattern: routePattern,
756
- script: scriptName,
757
- }),
758
- headers: {
759
- "Content-Type": "application/json",
760
- },
761
- });
762
-
763
- deployedRoutes.push(pattern);
764
- }
765
-
766
- if (alreadyDeployedRoutes.size) {
767
- logger.warn(
768
- "Previously deployed routes:\n" +
769
- "The following routes were already associated with this worker, and have not been deleted:\n" +
770
- [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
771
- "If these routes are not wanted then you can remove them in the dashboard."
772
- );
773
- }
774
-
775
- return deployedRoutes;
776
- }
777
-
778
- function isAuthenticationError(e: unknown): e is ParseError {
779
- return e instanceof ParseError && (e as { code?: number }).code === 10000;
780
- }