wrangler 0.0.0-e928f94 → 0.0.0-e978986

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 (124) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +48 -4
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +74 -34
  6. package/pages/functions/buildPlugin.ts +105 -0
  7. package/pages/functions/buildWorker.ts +151 -0
  8. package/pages/functions/filepath-routing.test.ts +234 -0
  9. package/pages/functions/filepath-routing.ts +189 -0
  10. package/pages/functions/identifiers.ts +78 -0
  11. package/pages/functions/routes.ts +156 -0
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +143 -0
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3374 -0
  16. package/src/__tests__/dev.test.tsx +980 -0
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +130 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/helpers/mock-kv.ts +33 -0
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  31. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  32. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  33. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  34. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  35. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  36. package/src/__tests__/https-options.test.ts +130 -0
  37. package/src/__tests__/index.test.ts +233 -130
  38. package/src/__tests__/init.test.ts +1567 -0
  39. package/src/__tests__/jest.setup.ts +77 -0
  40. package/src/__tests__/kv.test.ts +1481 -0
  41. package/src/__tests__/logger.test.ts +115 -0
  42. package/src/__tests__/package-manager.test.ts +353 -0
  43. package/src/__tests__/pages.test.ts +657 -0
  44. package/src/__tests__/parse.test.ts +330 -0
  45. package/src/__tests__/publish.test.ts +5468 -0
  46. package/src/__tests__/r2.test.ts +233 -0
  47. package/src/__tests__/route.test.ts +45 -0
  48. package/src/__tests__/secret.test.ts +481 -0
  49. package/src/__tests__/tail.test.ts +690 -0
  50. package/src/__tests__/user.test.ts +131 -0
  51. package/src/__tests__/whoami.test.tsx +105 -0
  52. package/src/abort.d.ts +3 -0
  53. package/src/bundle.ts +200 -0
  54. package/src/cfetch/index.ts +121 -0
  55. package/src/cfetch/internal.ts +145 -0
  56. package/src/cli.ts +10 -7
  57. package/src/config/README.md +107 -0
  58. package/src/config/config.ts +234 -0
  59. package/src/config/diagnostics.ts +80 -0
  60. package/src/config/environment.ts +420 -0
  61. package/src/config/index.ts +225 -0
  62. package/src/config/validation-helpers.ts +575 -0
  63. package/src/config/validation.ts +1539 -0
  64. package/src/config-cache.ts +45 -0
  65. package/src/create-worker-preview.ts +185 -0
  66. package/src/create-worker-upload-form.ts +254 -0
  67. package/src/dev/dev-vars.ts +36 -0
  68. package/src/dev/dev.tsx +419 -0
  69. package/src/dev/local.tsx +318 -0
  70. package/src/dev/remote.tsx +227 -0
  71. package/src/dev/use-esbuild.ts +118 -0
  72. package/src/dialogs.tsx +67 -17
  73. package/src/durable.ts +102 -0
  74. package/src/entry.ts +322 -0
  75. package/src/environment-variables.ts +35 -0
  76. package/src/errors.ts +11 -0
  77. package/src/https-options.ts +123 -0
  78. package/src/index.tsx +2031 -1041
  79. package/src/inspect.ts +662 -0
  80. package/src/intl-polyfill.d.ts +139 -0
  81. package/src/kv.ts +408 -0
  82. package/src/logger.ts +66 -0
  83. package/src/miniflare-cli/README.md +30 -0
  84. package/src/miniflare-cli/enum-keys.ts +17 -0
  85. package/src/miniflare-cli/index.ts +41 -0
  86. package/src/miniflare-cli/request-context.ts +40 -0
  87. package/src/module-collection.ts +229 -35
  88. package/src/open-in-browser.ts +19 -0
  89. package/src/package-manager.ts +174 -0
  90. package/src/pages.tsx +1444 -260
  91. package/src/parse.ts +202 -0
  92. package/src/paths.ts +26 -0
  93. package/src/proxy.ts +465 -0
  94. package/src/publish.ts +498 -261
  95. package/src/r2.ts +50 -0
  96. package/src/selfsigned.d.ts +29 -0
  97. package/src/sites.tsx +240 -60
  98. package/src/tail/filters.ts +279 -0
  99. package/src/tail/index.ts +299 -0
  100. package/src/tail/printing.ts +67 -0
  101. package/src/update-check.ts +19 -0
  102. package/src/user.tsx +395 -221
  103. package/src/whoami.tsx +70 -0
  104. package/src/worker.ts +180 -0
  105. package/templates/gitignore +171 -0
  106. package/templates/new-worker-scheduled.js +17 -0
  107. package/templates/new-worker-scheduled.ts +32 -0
  108. package/templates/new-worker.js +15 -0
  109. package/templates/new-worker.ts +30 -0
  110. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  111. package/templates/tsconfig.json +105 -0
  112. package/wrangler-dist/cli.js +118298 -116056
  113. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  114. package/src/__tests__/mock-cfetch.js +0 -46
  115. package/src/api/form_data.ts +0 -141
  116. package/src/api/inspect.ts +0 -441
  117. package/src/api/preview.ts +0 -128
  118. package/src/api/worker.ts +0 -161
  119. package/src/cfetch.ts +0 -72
  120. package/src/config.ts +0 -122
  121. package/src/dev.tsx +0 -724
  122. package/src/kv.tsx +0 -211
  123. package/src/tail.tsx +0 -71
  124. package/wrangler-dist/cli.js.map +0 -7
package/src/publish.ts CHANGED
@@ -1,346 +1,583 @@
1
- import type { CfWorkerInit } from "./api/worker";
2
- import { toFormData } from "./api/form_data";
3
- import esbuild from "esbuild";
4
- import tmp from "tmp-promise";
5
- import type { Config } from "./config";
6
- import path from "path";
7
- import { readFile } from "fs/promises";
8
- import cfetch from "./cfetch";
9
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 { fetchResult } from "./cfetch";
8
+ import { printBindings } from "./config";
9
+ import { createWorkerUploadForm } from "./create-worker-upload-form";
10
+ import { confirm } from "./dialogs";
11
+ import { getMigrationsToUpload } from "./durable";
12
+ import { logger } from "./logger";
10
13
  import { syncAssets } from "./sites";
11
- import makeModuleCollector from "./module-collection";
12
-
13
- type CfScriptFormat = void | "modules" | "service-worker";
14
+ import type { Config } from "./config";
15
+ import type {
16
+ Route,
17
+ ZoneIdRoute,
18
+ ZoneNameRoute,
19
+ CustomDomainRoute,
20
+ } from "./config/environment";
21
+ import type { Entry } from "./entry";
22
+ import type { AssetPaths } from "./sites";
23
+ import type { CfWorkerInit } from "./worker";
14
24
 
15
25
  type Props = {
16
26
  config: Config;
17
- format?: CfScriptFormat;
18
- script?: string;
19
- name?: string;
20
- env?: string;
21
- public?: string;
22
- site?: string;
23
- triggers?: (string | number)[];
24
- routes?: (string | number)[];
25
- legacyEnv?: boolean;
26
- jsxFactory: void | string;
27
- jsxFragment: void | string;
27
+ accountId: string | undefined;
28
+ entry: Entry;
29
+ rules: Config["rules"];
30
+ name: string | undefined;
31
+ env: string | undefined;
32
+ compatibilityDate: string | undefined;
33
+ compatibilityFlags: string[] | undefined;
34
+ assetPaths: AssetPaths | undefined;
35
+ triggers: string[] | undefined;
36
+ routes: string[] | undefined;
37
+ legacyEnv: boolean | undefined;
38
+ jsxFactory: string | undefined;
39
+ jsxFragment: string | undefined;
40
+ tsconfig: string | undefined;
41
+ experimentalPublic: boolean;
42
+ minify: boolean | undefined;
43
+ nodeCompat: boolean | undefined;
44
+ outDir: string | undefined;
45
+ dryRun: boolean | undefined;
28
46
  };
29
47
 
48
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
49
+
30
50
  function sleep(ms: number) {
31
51
  return new Promise((resolve) => setTimeout(resolve, ms));
32
52
  }
33
53
 
34
- export default async function publish(props: Props): Promise<void> {
35
- if (props.public && props.format === "service-worker") {
36
- // TODO: check config too
37
- throw new Error(
38
- "You cannot use the service worker format with a public directory."
54
+ function renderRoute(route: Route): string {
55
+ let result = "";
56
+ if (typeof route === "string") {
57
+ result = route;
58
+ } else {
59
+ result = route.pattern;
60
+ const isCustomDomain = Boolean(
61
+ "custom_domain" in route && route.custom_domain
39
62
  );
63
+ if (isCustomDomain && "zone_id" in route) {
64
+ result += ` (custom domain - zone id: ${route.zone_id})`;
65
+ } else if (isCustomDomain && "zone_name" in route) {
66
+ result += ` (custom domain - zone name: ${route.zone_name})`;
67
+ } else if (isCustomDomain) {
68
+ result += ` (custom domain)`;
69
+ } else if ("zone_id" in route) {
70
+ result += ` (zone id: ${route.zone_id})`;
71
+ } else if ("zone_name" in route) {
72
+ result += ` (zone name: ${route.zone_name})`;
73
+ }
40
74
  }
75
+ return result;
76
+ }
77
+
78
+ // this function takes a string with quotes in it
79
+ // (i.e. `hello "world", if that really is your name`)
80
+ // and peels out the first instance of a substring
81
+ // bounded by quotes (so, in the example above, `world`)
82
+ //
83
+ // this is useful because the /domains api will return
84
+ // which domains conflicted in an error message, bounded
85
+ // by a string, which we can use to provide helpful
86
+ // messages to a user
87
+ function getQuoteBoundedSubstring(content: string) {
88
+ const matches = content.split('"');
89
+ return matches[1] ?? "";
90
+ }
91
+
92
+ function isOriginConflictError(
93
+ e: unknown
94
+ ): e is { code: 100116; message: string; notes: Array<{ text: string }> } {
95
+ return (
96
+ typeof e === "object" &&
97
+ e !== null &&
98
+ (e as { code: number }).code === 100116
99
+ );
100
+ }
101
+
102
+ function isDNSConflictError(
103
+ e: unknown
104
+ ): e is { code: 100117; message: string; notes: Array<{ text: string }> } {
105
+ return (
106
+ typeof e === "object" &&
107
+ e !== null &&
108
+ (e as { code: number }).code === 100117
109
+ );
110
+ }
111
+
112
+ // empty error class to throw and then explicitly catch via `instanceof`
113
+ class CustomDomainOverrideRejected extends Error {}
114
+
115
+ // publishing to custom domains involves a few more steps than just updating
116
+ // the routing table, and thus the api implementing it is fairly defensive -
117
+ // it will error eagerly on conflicts against existing domains or existing
118
+ // managed DNS records
119
+ //
120
+ // however, you can pass params to override the errors. we start on the
121
+ // defensive path, and if one of these errors occur, we prompt the user
122
+ // for confirmation that they do indeed want to override the conflicts, and
123
+ // then retry the request with the right override added
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
+ function publishCustomDomains(
129
+ workerUrl: string,
130
+ domains: Array<RouteObject>
131
+ ): Promise<string[]> {
132
+ const config = {
133
+ override_scope: true,
134
+ override_existing_origin: false,
135
+ override_existing_dns_record: false,
136
+ };
137
+ const origins = domains.map((domainRoute) => {
138
+ return {
139
+ hostname: domainRoute.pattern,
140
+ zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
141
+ zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
142
+ };
143
+ });
144
+
145
+ if (!process.stdout.isTTY) {
146
+ // running in non-interactive mode.
147
+ // existing origins / dns records are not indicative of errors,
148
+ // so we aggressively update rather than aggressively fail
149
+ config.override_existing_origin = true;
150
+ config.override_existing_dns_record = true;
151
+ }
152
+
153
+ // Mixing promise chains with async/await is funky, but it allows us to keep related
154
+ // logic synchronous-looking (i.e. prompting for confirmation and then re-requesting)
155
+ // while retaining the flexibility of promise chain fall-throughs. We can group error
156
+ // handling logic in dedicated catch calls, and all we have to do is re-throw an
157
+ // error and it will pass down to the next catch call
158
+ return fetchResult(`${workerUrl}/domains`, {
159
+ method: "PUT",
160
+ body: JSON.stringify({ ...config, origins }),
161
+ headers: {
162
+ "Content-Type": "application/json",
163
+ },
164
+ })
165
+ .catch(async (err) => {
166
+ if (isOriginConflictError(err)) {
167
+ const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
168
+ const shouldContinue = await confirm(
169
+ `Custom Domains already exist for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
170
+ );
171
+ if (!shouldContinue) {
172
+ throw new CustomDomainOverrideRejected();
173
+ }
174
+ config.override_existing_origin = true;
175
+ await fetchResult(`${workerUrl}/domains`, {
176
+ method: "PUT",
177
+ body: JSON.stringify({ ...config, origins }),
178
+ headers: {
179
+ "Content-Type": "application/json",
180
+ },
181
+ });
182
+ } else {
183
+ throw err;
184
+ }
185
+ })
186
+ .catch(async (err) => {
187
+ if (isDNSConflictError(err)) {
188
+ const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
189
+ const shouldContinue = await confirm(
190
+ `You already have conflicting DNS records for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
191
+ );
192
+ if (!shouldContinue) {
193
+ throw new CustomDomainOverrideRejected();
194
+ }
195
+ config.override_existing_dns_record = true;
196
+ await fetchResult(`${workerUrl}/domains`, {
197
+ method: "PUT",
198
+ body: JSON.stringify({ ...config, origins }),
199
+ headers: {
200
+ "Content-Type": "application/json",
201
+ },
202
+ });
203
+ } else {
204
+ throw err;
205
+ }
206
+ })
207
+ .then(() => domains.map((domain) => renderRoute(domain)))
208
+ .catch((err) => {
209
+ if (err instanceof CustomDomainOverrideRejected) {
210
+ return [
211
+ domains.length > 1
212
+ ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
213
+ : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
214
+ ];
215
+ }
216
+ throw err;
217
+ });
218
+ }
219
+
220
+ export default async function publish(props: Props): Promise<void> {
41
221
  // TODO: warn if git/hg has uncommitted changes
42
- const { config } = props;
43
- const {
44
- account_id: accountId,
45
- build,
46
- // @ts-expect-error hidden
47
- __path__,
48
- } = config;
222
+ const { config, accountId } = props;
223
+
224
+ assert(
225
+ props.compatibilityDate || config.compatibility_date,
226
+ "A compatibility_date is required when publishing. Add one to your wrangler.toml file, or pass it in your terminal as --compatibility-date. See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
227
+ );
49
228
 
50
229
  const triggers = props.triggers || config.triggers?.crons;
51
- const routes = props.routes || config.routes;
230
+ const routes =
231
+ props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
232
+ const routesOnly: Array<Route> = [];
233
+ const customDomainsOnly: Array<RouteObject> = [];
234
+ for (const route of routes) {
235
+ if (typeof route !== "string" && route.custom_domain) {
236
+ if (route.pattern.includes("*")) {
237
+ throw new Error(
238
+ `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
239
+ );
240
+ }
241
+ if (route.pattern.includes("/")) {
242
+ throw new Error(
243
+ `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
244
+ );
245
+ }
246
+ customDomainsOnly.push(route);
247
+ } else {
248
+ routesOnly.push(route);
249
+ }
250
+ }
251
+
252
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
253
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
52
254
 
53
255
  const jsxFactory = props.jsxFactory || config.jsx_factory;
54
256
  const jsxFragment = props.jsxFragment || config.jsx_fragment;
55
257
 
56
- assert(config.account_id, "missing account id");
258
+ const minify = props.minify ?? config.minify;
259
+
260
+ const nodeCompat = props.nodeCompat ?? config.node_compat;
261
+ if (nodeCompat) {
262
+ logger.warn(
263
+ "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
264
+ );
265
+ }
57
266
 
58
- let scriptName = props.name || config.name;
267
+ const scriptName = props.name;
59
268
  assert(
60
269
  scriptName,
61
270
  '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>"`'
62
271
  );
63
272
 
64
- let file: string;
65
- if (props.script) {
66
- file = props.script;
67
- } else {
68
- assert(build?.upload?.main, "missing main file");
69
- file = path.join(path.dirname(__path__), build.upload.main);
70
- }
273
+ assert(
274
+ !config.site || config.site.bucket,
275
+ "A [site] definition requires a `bucket` field with a path to the site's public directory."
276
+ );
71
277
 
72
- if (props.legacyEnv) {
73
- scriptName += props.env ? `-${props.env}` : "";
278
+ if (props.outDir) {
279
+ // we're using a custom output directory,
280
+ // so let's first ensure it exists
281
+ mkdirSync(props.outDir, { recursive: true });
282
+ // add a README
283
+ const readmePath = path.join(props.outDir, "README.md");
284
+ writeFileSync(
285
+ readmePath,
286
+ `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
287
+ );
74
288
  }
75
- const envName = props.env ?? "production";
76
289
 
77
- const destination = await tmp.dir({ unsafeCleanup: true });
78
-
79
- const moduleCollector = makeModuleCollector();
80
- const result = await esbuild.build({
81
- ...(props.public
82
- ? {
83
- stdin: {
84
- contents: (
85
- await readFile(
86
- path.join(__dirname, "../static-asset-facade.js"),
87
- "utf8"
88
- )
89
- ).replace("__ENTRY_POINT__", path.join(process.cwd(), file)),
90
- sourcefile: "static-asset-facade.js",
91
- resolveDir: path.dirname(file),
92
- },
93
- }
94
- : { entryPoints: [file] }),
95
- bundle: true,
96
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
97
- outdir: destination.path,
98
- external: ["__STATIC_CONTENT_MANIFEST"],
99
- format: "esm",
100
- sourcemap: true,
101
- metafile: true,
102
- conditions: ["worker", "browser"],
103
- loader: {
104
- ".js": "jsx",
105
- },
106
- plugins: [moduleCollector.plugin],
107
- ...(jsxFactory && { jsxFactory }),
108
- ...(jsxFragment && { jsxFragment }),
109
- });
290
+ const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
291
+ const envName = props.env ?? "production";
110
292
 
111
- const chunks = Object.entries(result.metafile.outputs).find(
112
- ([_path, { entryPoint }]) =>
113
- entryPoint ===
114
- (props.public
115
- ? path.join(path.dirname(file), "static-asset-facade.js")
116
- : file)
117
- );
293
+ const start = Date.now();
294
+ const notProd = !props.legacyEnv && props.env;
295
+ const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
296
+ const workerUrl = notProd
297
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
298
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`;
118
299
 
119
- const { format } = props;
120
- const bundle = {
121
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
122
- exports: chunks[1].exports,
123
- };
300
+ let available_on_subdomain; // we'll set this later
124
301
 
125
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
126
- // That way we'll be able to accurately tell if this is a service worker or not.
302
+ const { format } = props.entry;
127
303
 
128
- if (format === "modules" && bundle.type === "commonjs") {
129
- console.error("⎔ Cannot use modules with a commonjs bundle.");
130
- // TODO: a much better error message here, with what to do next
131
- return;
304
+ if (props.experimentalPublic && format === "service-worker") {
305
+ throw new Error(
306
+ "You cannot publish in the service-worker format with a public directory."
307
+ );
132
308
  }
133
- if (format === "service-worker" && bundle.type !== "esm") {
134
- console.error("⎔ Cannot use service-worker with a esm bundle.");
135
- // TODO: a much better error message here, with what to do next
136
- return;
309
+
310
+ if (config.wasm_modules && format === "modules") {
311
+ throw new Error(
312
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
313
+ );
137
314
  }
138
315
 
139
- const content = await readFile(chunks[0], { encoding: "utf-8" });
140
- destination.cleanup();
316
+ if (config.text_blobs && format === "modules") {
317
+ throw new Error(
318
+ "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"
319
+ );
320
+ }
141
321
 
142
- // if config.migrations
143
- // get current migration tag
144
- let migrations;
145
- if ("migrations" in config) {
146
- const scripts = await cfetch<{ id: string; migration_tag: string }[]>(
147
- `/accounts/${accountId}/workers/scripts`
322
+ if (config.data_blobs && format === "modules") {
323
+ throw new Error(
324
+ "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"
148
325
  );
149
- const script = scripts.find((script) => script.id === scriptName);
150
- if (script?.migration_tag) {
151
- // was already published once
152
- const foundIndex = config.migrations.findIndex(
153
- (migration) => migration.tag === script.migration_tag
154
- );
155
- if (foundIndex === -1) {
156
- console.warn(
157
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already delated it. Applying all available migrations to the script...`
158
- );
159
- migrations = {
160
- old_tag: script.migration_tag,
161
- new_tag: config.migrations[config.migrations.length - 1].tag,
162
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
163
- };
164
- } else {
165
- migrations = {
166
- old_tag: script.migration_tag,
167
- new_tag: config.migrations[config.migrations.length - 1].tag,
168
- steps: config.migrations
169
- .slice(foundIndex + 1)
170
- .map(({ tag: _tag, ...rest }) => rest),
171
- };
172
- }
173
- } else {
174
- migrations = {
175
- new_tag: config.migrations[config.migrations.length - 1].tag,
176
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
177
- };
178
- }
179
326
  }
327
+ try {
328
+ const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
329
+ props.entry,
330
+ typeof destination === "string" ? destination : destination.path,
331
+ {
332
+ serveAssetsFromWorker: props.experimentalPublic,
333
+ jsxFactory,
334
+ jsxFragment,
335
+ rules: props.rules,
336
+ tsconfig: props.tsconfig ?? config.tsconfig,
337
+ minify,
338
+ nodeCompat,
339
+ }
340
+ );
180
341
 
181
- const assets =
182
- props.public || props.site || props.config.site?.bucket // TODO: allow both
183
- ? await syncAssets(
184
- accountId,
185
- scriptName,
186
- props.public || props.site || props.config.site?.bucket,
187
- false
188
- )
189
- : { manifest: undefined, namespace: undefined };
342
+ const content = readFileSync(resolvedEntryPointPath, {
343
+ encoding: "utf-8",
344
+ });
190
345
 
191
- const envRootObj = props.env ? config.env[props.env] || {} : config;
346
+ // durable object migrations
347
+ const migrations = !props.dryRun
348
+ ? await getMigrationsToUpload(scriptName, {
349
+ accountId,
350
+ config,
351
+ legacyEnv: props.legacyEnv,
352
+ env: props.env,
353
+ })
354
+ : undefined;
355
+
356
+ const assets = await syncAssets(
357
+ accountId,
358
+ // When we're using the newer service environments, we wouldn't
359
+ // have added the env name on to the script name. However, we must
360
+ // include it in the kv namespace name regardless (since there's no
361
+ // concept of service environments for kv namespaces yet).
362
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
363
+ props.assetPaths,
364
+ false,
365
+ props.dryRun
366
+ );
192
367
 
193
- const worker: CfWorkerInit = {
194
- name: scriptName,
195
- main: {
196
- name: path.basename(chunks[0]),
197
- content: content,
198
- type: bundle.type === "esm" ? "esm" : "commonjs",
199
- },
200
- variables: {
201
- ...(envRootObj?.vars || {}),
202
- ...(envRootObj?.kv_namespaces || []).reduce(
203
- (obj, { binding, preview_id: _preview_id, id }) => {
204
- return { ...obj, [binding]: { namespaceId: id } };
205
- },
206
- {}
207
- ),
208
- ...(envRootObj?.durable_objects?.bindings || []).reduce(
209
- (obj, { name, class_name, script_name }) => {
210
- return {
211
- ...obj,
212
- [name]: { class_name, ...(script_name && { script_name }) },
213
- };
214
- },
215
- {}
368
+ const bindings: CfWorkerInit["bindings"] = {
369
+ kv_namespaces: (config.kv_namespaces || []).concat(
370
+ assets.namespace
371
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
372
+ : []
216
373
  ),
217
- ...(assets.namespace
218
- ? { __STATIC_CONTENT: { namespaceId: assets.namespace } }
219
- : {}),
220
- },
221
- ...(migrations && { migrations }),
222
- modules: assets.manifest
223
- ? moduleCollector.modules.concat({
224
- name: "__STATIC_CONTENT_MANIFEST",
225
- content: JSON.stringify(assets.manifest),
226
- type: "text",
227
- })
228
- : moduleCollector.modules,
229
- compatibility_date: config.compatibility_date,
230
- compatibility_flags: config.compatibility_flags,
231
- usage_model: config.usage_model,
232
- };
374
+ vars: config.vars,
375
+ wasm_modules: config.wasm_modules,
376
+ text_blobs: {
377
+ ...config.text_blobs,
378
+ ...(assets.manifest &&
379
+ format === "service-worker" && {
380
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
381
+ }),
382
+ },
383
+ data_blobs: config.data_blobs,
384
+ durable_objects: config.durable_objects,
385
+ r2_buckets: config.r2_buckets,
386
+ services: config.services,
387
+ unsafe: config.unsafe?.bindings,
388
+ };
389
+
390
+ if (assets.manifest) {
391
+ modules.push({
392
+ name: "__STATIC_CONTENT_MANIFEST",
393
+ content: JSON.stringify(assets.manifest),
394
+ type: "text",
395
+ });
396
+ }
233
397
 
234
- const start = Date.now();
235
- function formatTime(duration: number) {
236
- return `(${(duration / 1000).toFixed(2)} sec)`;
398
+ const worker: CfWorkerInit = {
399
+ name: scriptName,
400
+ main: {
401
+ name: path.basename(resolvedEntryPointPath),
402
+ content: content,
403
+ type: bundleType,
404
+ },
405
+ bindings,
406
+ migrations,
407
+ modules,
408
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
409
+ compatibility_flags:
410
+ props.compatibilityFlags ?? config.compatibility_flags,
411
+ usage_model: config.usage_model,
412
+ };
413
+
414
+ const withoutStaticAssets = {
415
+ ...bindings,
416
+ kv_namespaces: config.kv_namespaces,
417
+ text_blobs: config.text_blobs,
418
+ };
419
+ printBindings(withoutStaticAssets);
420
+
421
+ if (!props.dryRun) {
422
+ // Upload the script so it has time to propagate.
423
+ // We can also now tell whether available_on_subdomain is set
424
+ available_on_subdomain = (
425
+ await fetchResult<{ available_on_subdomain: boolean }>(
426
+ workerUrl,
427
+ {
428
+ method: "PUT",
429
+ body: createWorkerUploadForm(worker),
430
+ },
431
+ new URLSearchParams({ include_subdomain_availability: "true" })
432
+ )
433
+ ).available_on_subdomain;
434
+ }
435
+ } finally {
436
+ if (typeof destination !== "string") {
437
+ // this means we're using a temp dir,
438
+ // so let's clean up before we proceed
439
+ await destination.cleanup();
440
+ }
237
441
  }
238
442
 
239
- const notProd = !props.legacyEnv && props.env;
240
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
241
- const workerUrl = notProd
242
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
243
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
244
-
245
- // Upload the script so it has time to propogate.
246
- const { available_on_subdomain } = await cfetch(
247
- `${workerUrl}?available_on_subdomain=true`,
248
- {
249
- method: "PUT",
250
- // @ts-expect-error: TODO: fix this type error!
251
- body: toFormData(worker),
252
- }
253
- );
443
+ if (props.dryRun) {
444
+ logger.log(`--dry-run: exiting now.`);
445
+ return;
446
+ }
447
+ assert(accountId, "Missing accountId");
254
448
 
255
449
  const uploadMs = Date.now() - start;
256
- console.log("Uploaded", workerName, formatTime(uploadMs));
257
450
  const deployments: Promise<string[]>[] = [];
258
451
 
259
- const userSubdomain = (
260
- await cfetch<{ subdomain: string }>(
261
- `/accounts/${accountId}/workers/subdomain`
262
- )
263
- ).subdomain;
264
-
265
- const scriptURL =
266
- props.legacyEnv || !props.env
267
- ? `${scriptName}.${userSubdomain}.workers.dev`
268
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
269
-
270
- // Enable the `workers.dev` subdomain.
271
- // TODO: Make this configurable.
272
- if (!available_on_subdomain) {
273
- deployments.push(
274
- cfetch(`${workerUrl}/subdomain`, {
452
+ if (deployToWorkersDev) {
453
+ // Deploy to a subdomain of `workers.dev`
454
+ const userSubdomain = await getSubdomain(accountId);
455
+ const scriptURL =
456
+ props.legacyEnv || !props.env
457
+ ? `${scriptName}.${userSubdomain}.workers.dev`
458
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
459
+ if (!available_on_subdomain) {
460
+ // Enable the `workers.dev` subdomain.
461
+ deployments.push(
462
+ fetchResult(`${workerUrl}/subdomain`, {
463
+ method: "POST",
464
+ body: JSON.stringify({ enabled: true }),
465
+ headers: {
466
+ "Content-Type": "application/json",
467
+ },
468
+ })
469
+ .then(() => [scriptURL])
470
+ // Add a delay when the subdomain is first created.
471
+ // This is to prevent an issue where a negative cache-hit
472
+ // causes the subdomain to be unavailable for 30 seconds.
473
+ // This is a temporary measure until we fix this on the edge.
474
+ .then(async (url) => {
475
+ await sleep(3000);
476
+ return url;
477
+ })
478
+ );
479
+ } else {
480
+ deployments.push(Promise.resolve([scriptURL]));
481
+ }
482
+ } else {
483
+ if (available_on_subdomain) {
484
+ // Disable the workers.dev deployment
485
+ await fetchResult(`${workerUrl}/subdomain`, {
275
486
  method: "POST",
276
- body: JSON.stringify({ enabled: true }),
487
+ body: JSON.stringify({ enabled: false }),
277
488
  headers: {
278
489
  "Content-Type": "application/json",
279
490
  },
280
- })
281
- .then(() => [scriptURL])
282
- // Add a delay when the subdomain is first created.
283
- // This is to prevent an issue where a negative cache-hit
284
- // causes the subdomain to be unavailable for 30 seconds.
285
- // This is a temporary measure until we fix this on the edge.
286
- .then((url) => {
287
- sleep(3000);
288
- return url;
289
- })
290
- );
291
- } else {
292
- deployments.push(Promise.resolve([scriptURL]));
491
+ });
492
+ }
293
493
  }
294
494
 
495
+ logger.log("Uploaded", workerName, formatTime(uploadMs));
496
+
295
497
  // Update routing table for the script.
296
- if (routes && routes.length) {
498
+ if (routesOnly.length > 0) {
297
499
  deployments.push(
298
- cfetch(`${workerUrl}/routes`, {
299
- // TODO: PATCH will not delete previous routes on this script,
300
- // whereas PUT will. We need to decide on the default behaviour
301
- // and how to configure it.
500
+ fetchResult(`${workerUrl}/routes`, {
501
+ // Note: PUT will delete previous routes on this script.
302
502
  method: "PUT",
303
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
503
+ body: JSON.stringify(
504
+ routesOnly.map((route) =>
505
+ typeof route !== "object" ? { pattern: route } : route
506
+ )
507
+ ),
304
508
  headers: {
305
509
  "Content-Type": "application/json",
306
510
  },
307
511
  }).then(() => {
308
- if (routes.length > 10) {
309
- return routes
512
+ if (routesOnly.length > 10) {
513
+ return routesOnly
310
514
  .slice(0, 9)
311
- .map(String)
312
- .concat([`...and ${routes.length - 10} more routes`]);
515
+ .map((route) => renderRoute(route))
516
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
313
517
  }
314
- return routes.map(String);
518
+ return routesOnly.map((route) => renderRoute(route));
315
519
  })
316
520
  );
317
521
  }
318
522
 
523
+ // Update custom domains for the script
524
+ if (customDomainsOnly.length > 0) {
525
+ deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
526
+ }
527
+
319
528
  // Configure any schedules for the script.
320
529
  // TODO: rename this to `schedules`?
321
530
  if (triggers && triggers.length) {
322
531
  deployments.push(
323
- cfetch(`${workerUrl}/schedules`, {
324
- // TODO: Unlike routes, this endpoint does not support PATCH.
325
- // So technically, this will override any previous schedules.
326
- // We should change the endpoint to support PATCH.
532
+ fetchResult(`${workerUrl}/schedules`, {
533
+ // Note: PUT will override previous schedules on this script.
327
534
  method: "PUT",
328
535
  body: JSON.stringify(triggers.map((cron) => ({ cron }))),
329
536
  headers: {
330
537
  "Content-Type": "application/json",
331
538
  },
332
- }).then(() => triggers.map(String))
539
+ }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
333
540
  );
334
541
  }
335
542
 
336
- if (!deployments.length) {
337
- return;
338
- }
339
-
340
543
  const targets = await Promise.all(deployments);
341
544
  const deployMs = Date.now() - start - uploadMs;
342
- console.log("Deployed", workerName, formatTime(deployMs));
343
- for (const target of targets.flat()) {
344
- console.log(" ", target);
545
+
546
+ if (deployments.length > 0) {
547
+ logger.log("Published", workerName, formatTime(deployMs));
548
+ for (const target of targets.flat()) {
549
+ logger.log(" ", target);
550
+ }
551
+ } else {
552
+ logger.log("No publish targets for", workerName, formatTime(deployMs));
553
+ }
554
+ }
555
+
556
+ function formatTime(duration: number) {
557
+ return `(${(duration / 1000).toFixed(2)} sec)`;
558
+ }
559
+
560
+ async function getSubdomain(accountId: string): Promise<string> {
561
+ try {
562
+ const { subdomain } = await fetchResult(
563
+ `/accounts/${accountId}/workers/subdomain`
564
+ );
565
+ return subdomain;
566
+ } catch (e) {
567
+ const error = e as { code?: number };
568
+ if (typeof error === "object" && !!error && error.code === 10007) {
569
+ // 10007 error code: not found
570
+ // https://api.cloudflare.com/#worker-subdomain-get-subdomain
571
+
572
+ const errorMessage =
573
+ "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
574
+ const solutionMessage =
575
+ "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
576
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
577
+
578
+ throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
579
+ } else {
580
+ throw e;
581
+ }
345
582
  }
346
583
  }