wrangler 0.0.0-bfbb0be → 0.0.0-bfbe49d0

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