wrangler 0.0.0-e9ab55a → 0.0.0-ed4f2ef

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 (102) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +12 -3
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +33 -16
  6. package/pages/functions/buildWorker.ts +1 -1
  7. package/pages/functions/filepath-routing.test.ts +212 -28
  8. package/pages/functions/filepath-routing.ts +83 -130
  9. package/pages/functions/routes.ts +11 -18
  10. package/pages/functions/template-worker.ts +3 -9
  11. package/src/__tests__/configuration.test.ts +2874 -0
  12. package/src/__tests__/dev.test.tsx +582 -61
  13. package/src/__tests__/guess-worker-format.test.ts +83 -0
  14. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  15. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  16. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  17. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  18. package/src/__tests__/helpers/mock-bin.ts +36 -0
  19. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +52 -16
  20. package/src/__tests__/helpers/mock-console.ts +70 -0
  21. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  22. package/src/__tests__/helpers/mock-kv.ts +33 -0
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +178 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  29. package/src/__tests__/https-options.test.ts +127 -0
  30. package/src/__tests__/index.test.ts +777 -77
  31. package/src/__tests__/jest.setup.ts +58 -6
  32. package/src/__tests__/kv.test.ts +716 -462
  33. package/src/__tests__/package-manager.test.ts +206 -0
  34. package/src/__tests__/pages.test.ts +180 -0
  35. package/src/__tests__/parse.test.ts +322 -0
  36. package/src/__tests__/publish.test.ts +3915 -71
  37. package/src/__tests__/r2.test.ts +198 -0
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +425 -0
  40. package/src/__tests__/sentry.test.ts +146 -0
  41. package/src/__tests__/tail.test.ts +638 -0
  42. package/src/__tests__/user.test.ts +83 -0
  43. package/src/__tests__/whoami.test.tsx +95 -0
  44. package/src/bundle.ts +155 -0
  45. package/src/cfetch/index.ts +21 -19
  46. package/src/cfetch/internal.ts +92 -22
  47. package/src/cli.ts +14 -2
  48. package/src/config/README.md +107 -0
  49. package/src/config/config.ts +229 -0
  50. package/src/config/diagnostics.ts +80 -0
  51. package/src/config/environment.ts +371 -0
  52. package/src/config/index.ts +62 -0
  53. package/src/config/validation-helpers.ts +557 -0
  54. package/src/config/validation.ts +1240 -0
  55. package/src/{api/preview.ts → create-worker-preview.ts} +69 -24
  56. package/src/create-worker-upload-form.ts +240 -0
  57. package/src/dev/dev.tsx +413 -0
  58. package/src/dev/local.tsx +287 -0
  59. package/src/dev/remote.tsx +209 -0
  60. package/src/dev/use-esbuild.ts +109 -0
  61. package/src/dialogs.tsx +2 -2
  62. package/src/entry.ts +256 -0
  63. package/src/environment-variables.ts +33 -0
  64. package/src/errors.ts +11 -0
  65. package/src/https-options.ts +122 -0
  66. package/src/index.tsx +1310 -849
  67. package/src/inspect.ts +102 -21
  68. package/src/intl-polyfill.d.ts +139 -0
  69. package/src/{kv.tsx → kv.ts} +104 -61
  70. package/src/miniflare-cli/README.md +30 -0
  71. package/src/miniflare-cli/enum-keys.ts +17 -0
  72. package/src/miniflare-cli/index.ts +38 -0
  73. package/src/module-collection.ts +228 -35
  74. package/src/open-in-browser.ts +25 -0
  75. package/src/package-manager.ts +126 -0
  76. package/src/pages.tsx +214 -48
  77. package/src/parse.ts +183 -0
  78. package/src/paths.ts +26 -0
  79. package/src/proxy.ts +192 -39
  80. package/src/publish.ts +321 -318
  81. package/src/r2.ts +50 -0
  82. package/src/reporting.ts +131 -0
  83. package/src/selfsigned.d.ts +29 -0
  84. package/src/sites.tsx +224 -62
  85. package/src/tail/filters.ts +279 -0
  86. package/src/tail/index.ts +299 -0
  87. package/src/tail/printing.ts +62 -0
  88. package/src/user.tsx +317 -178
  89. package/src/whoami.tsx +69 -0
  90. package/src/{api/worker.ts → worker.ts} +54 -37
  91. package/templates/new-worker.js +15 -0
  92. package/templates/new-worker.ts +15 -0
  93. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  94. package/templates/tsconfig.json +105 -0
  95. package/wrangler-dist/cli.js +131262 -112648
  96. package/wrangler-dist/cli.js.map +3 -3
  97. package/src/__tests__/run-in-tmp.ts +0 -19
  98. package/src/__tests__/run-wrangler.ts +0 -32
  99. package/src/api/form_data.ts +0 -131
  100. package/src/config.ts +0 -646
  101. package/src/dev.tsx +0 -784
  102. package/src/tail.tsx +0 -73
package/src/publish.ts CHANGED
@@ -1,34 +1,34 @@
1
1
  import assert from "node:assert";
2
+ import { readFileSync } from "node:fs";
2
3
  import path from "node:path";
3
- import { readFile } from "node:fs/promises";
4
- import * as esbuild from "esbuild";
5
- import type { Metafile } from "esbuild";
6
- import { execa } from "execa";
4
+ import { URLSearchParams } from "node:url";
7
5
  import tmp from "tmp-promise";
8
- import type { CfWorkerInit } from "./api/worker";
9
- import { toFormData } from "./api/form_data";
6
+ import { bundleWorker } from "./bundle";
10
7
  import { fetchResult } from "./cfetch";
11
- import type { Config } from "./config";
12
- import makeModuleCollector from "./module-collection";
8
+ import { createWorkerUploadForm } from "./create-worker-upload-form";
13
9
  import { syncAssets } from "./sites";
14
-
15
- type CfScriptFormat = undefined | "modules" | "service-worker";
10
+ import type { Config } from "./config";
11
+ import type { Entry } from "./entry";
12
+ import type { AssetPaths } from "./sites";
13
+ import type { CfWorkerInit } from "./worker";
16
14
 
17
15
  type Props = {
18
16
  config: Config;
19
- format?: CfScriptFormat;
20
- script?: string;
21
- name?: string;
22
- env?: string;
23
- compatibilityDate?: string;
24
- compatibilityFlags?: string[];
25
- public?: string;
26
- site?: string;
27
- triggers?: (string | number)[];
28
- routes?: (string | number)[];
29
- legacyEnv?: boolean;
17
+ accountId: string;
18
+ entry: Entry;
19
+ rules: Config["rules"];
20
+ name: string | undefined;
21
+ env: string | undefined;
22
+ compatibilityDate: string | undefined;
23
+ compatibilityFlags: string[] | undefined;
24
+ assetPaths: AssetPaths | undefined;
25
+ triggers: (string | number)[] | undefined;
26
+ routes: (string | number)[] | undefined;
27
+ legacyEnv: boolean | undefined;
30
28
  jsxFactory: undefined | string;
31
29
  jsxFragment: undefined | string;
30
+ tsconfig: undefined | string;
31
+ experimentalPublic: boolean;
32
32
  };
33
33
 
34
34
  function sleep(ms: number) {
@@ -36,347 +36,350 @@ function sleep(ms: number) {
36
36
  }
37
37
 
38
38
  export default async function publish(props: Props): Promise<void> {
39
- if (props.public && props.format === "service-worker") {
40
- // TODO: check config too
41
- throw new Error(
42
- "You cannot use the service worker format with a public directory."
43
- );
44
- }
45
39
  // TODO: warn if git/hg has uncommitted changes
46
- const { config } = props;
47
- const {
48
- account_id: accountId,
49
- build,
50
- // @ts-expect-error hidden
51
- __path__,
52
- } = config;
53
-
54
- const envRootObj =
55
- props.env && config.env ? config.env[props.env] || {} : config;
40
+ const { config, accountId } = props;
56
41
 
57
42
  assert(
58
- envRootObj.compatibility_date || props.compatibilityDate,
59
- "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."
43
+ props.compatibilityDate || config.compatibility_date,
44
+ "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."
60
45
  );
61
46
 
62
- if (accountId === undefined) {
63
- throw new Error("No account_id provided.");
64
- }
65
-
66
47
  const triggers = props.triggers || config.triggers?.crons;
67
- const routes = props.routes || config.routes;
48
+ const routes =
49
+ props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
50
+
51
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
52
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
68
53
 
69
54
  const jsxFactory = props.jsxFactory || config.jsx_factory;
70
55
  const jsxFragment = props.jsxFragment || config.jsx_fragment;
71
56
 
72
- assert(config.account_id, "missing account id");
73
-
74
- let scriptName = props.name || config.name;
57
+ const scriptName = props.name;
75
58
  assert(
76
59
  scriptName,
77
60
  '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>"`'
78
61
  );
79
62
 
80
- let file: string;
81
- if (props.script) {
82
- // If the script name comes from the command line it is relative to the current working directory.
83
- file = path.resolve(props.script);
84
- } else {
85
- // If the script name comes from the config, then it is relative to the wrangler.toml file.
86
- assert(build?.upload?.main, "missing main file");
87
- file = path.resolve(path.dirname(__path__), build.upload.main);
88
- }
89
-
90
- if (props.legacyEnv) {
91
- scriptName += props.env ? `-${props.env}` : "";
92
- }
93
- const envName = props.env ?? "production";
63
+ assert(
64
+ !config.site || config.site.bucket,
65
+ "A [site] definition requires a `bucket` field with a path to the site's public directory."
66
+ );
94
67
 
95
68
  const destination = await tmp.dir({ unsafeCleanup: true });
96
- if (props.config.build?.command) {
97
- // TODO: add a deprecation message here?
98
- console.log("running:", props.config.build.command);
99
- const buildCommandPieces = props.config.build.command.split(" ");
100
- await execa(buildCommandPieces[0], buildCommandPieces.slice(1), {
101
- stdout: "inherit",
102
- stderr: "inherit",
103
- ...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
104
- });
105
- }
69
+ try {
70
+ const envName = props.env ?? "production";
106
71
 
107
- const moduleCollector = makeModuleCollector();
108
- const result = await esbuild.build({
109
- ...(props.public
110
- ? {
111
- stdin: {
112
- contents: (
113
- await readFile(
114
- path.join(__dirname, "../static-asset-facade.js"),
115
- "utf8"
116
- )
117
- ).replace("__ENTRY_POINT__", file),
118
- sourcefile: "static-asset-facade.js",
119
- resolveDir: path.dirname(file),
120
- },
121
- }
122
- : { entryPoints: [file] }),
123
- bundle: true,
124
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
125
- outdir: destination.path,
126
- external: ["__STATIC_CONTENT_MANIFEST"],
127
- format: "esm",
128
- sourcemap: true,
129
- metafile: true,
130
- conditions: ["worker", "browser"],
131
- loader: {
132
- ".js": "jsx",
133
- },
134
- plugins: [moduleCollector.plugin],
135
- ...(jsxFactory && { jsxFactory }),
136
- ...(jsxFragment && { jsxFragment }),
137
- });
138
-
139
- // result.metafile is defined because of the `metafile: true` option above.
140
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
141
- const metafile = result.metafile!;
142
- const entryPoints = Object.values(metafile.outputs).filter(
143
- (output) => output.entryPoint !== undefined
144
- );
145
- assert(
146
- entryPoints.length > 0,
147
- `Cannot find entry-point "${file}" in generated bundle.` +
148
- listEntryPoints(entryPoints)
149
- );
150
- assert(
151
- entryPoints.length < 2,
152
- "More than one entry-point found for generated bundle." +
153
- listEntryPoints(entryPoints)
154
- );
155
- const entryPointExports = entryPoints[0].exports;
156
- const resolvedEntryPointPath = path.resolve(
157
- destination.path,
158
- // We know that entryPoint is not null because we filtered out those without above.
159
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
160
- entryPoints[0].entryPoint!
161
- );
162
- const { format } = props;
163
- const bundle = {
164
- type: entryPointExports.length > 0 ? "esm" : "commonjs",
165
- exports: entryPointExports,
166
- };
167
-
168
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
169
- // That way we'll be able to accurately tell if this is a service worker or not.
170
-
171
- if (format === "modules" && bundle.type === "commonjs") {
172
- console.error("⎔ Cannot use modules with a commonjs bundle.");
173
- // TODO: a much better error message here, with what to do next
174
- return;
175
- }
176
- if (format === "service-worker" && bundle.type !== "esm") {
177
- console.error("⎔ Cannot use service-worker with a esm bundle.");
178
- // TODO: a much better error message here, with what to do next
179
- return;
180
- }
72
+ const { format } = props.entry;
181
73
 
182
- const content = await readFile(resolvedEntryPointPath, { encoding: "utf-8" });
183
- await destination.cleanup();
74
+ if (props.experimentalPublic && format === "service-worker") {
75
+ // TODO: check config too
76
+ throw new Error(
77
+ "You cannot publish in the service-worker format with a public directory."
78
+ );
79
+ }
184
80
 
185
- // if config.migrations
186
- // get current migration tag
187
- let migrations;
188
- if (config.migrations !== undefined) {
189
- const scripts = await fetchResult<{ id: string; migration_tag: string }[]>(
190
- `/accounts/${accountId}/workers/scripts`
81
+ if (config.wasm_modules && format === "modules") {
82
+ throw new Error(
83
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
84
+ );
85
+ }
86
+
87
+ if (config.text_blobs && format === "modules") {
88
+ throw new Error(
89
+ "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"
90
+ );
91
+ }
92
+
93
+ if (config.data_blobs && format === "modules") {
94
+ throw new Error(
95
+ "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"
96
+ );
97
+ }
98
+
99
+ const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
100
+ props.entry,
101
+ destination.path,
102
+ {
103
+ serveAssetsFromWorker: props.experimentalPublic,
104
+ jsxFactory,
105
+ jsxFragment,
106
+ rules: props.rules,
107
+ tsconfig: props.tsconfig ?? config.tsconfig,
108
+ }
191
109
  );
192
- const script = scripts.find(({ id }) => id === scriptName);
193
- if (script?.migration_tag) {
194
- // was already published once
195
- const foundIndex = config.migrations.findIndex(
196
- (migration) => migration.tag === script.migration_tag
110
+
111
+ // Some validation of durable objects + migrations
112
+ if (config.durable_objects.bindings.length > 0) {
113
+ // TODO: implement durable objects for service environments
114
+ if (!props.legacyEnv) {
115
+ throw new Error(
116
+ "Publishing Durable Objects to a service environment is not currently supported. This is being tracked at https://github.com/cloudflare/wrangler2/issues/739"
117
+ );
118
+ }
119
+
120
+ // intrinsic [durable_objects] implies [migrations]
121
+ const exportedDurableObjects = config.durable_objects.bindings.filter(
122
+ (binding) => !binding.script_name
197
123
  );
198
- if (foundIndex === -1) {
124
+ if (exportedDurableObjects.length > 0 && config.migrations.length === 0) {
199
125
  console.warn(
200
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
126
+ `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${exportedDurableObjects.map(
127
+ (durable) => durable.class_name
128
+ )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
201
129
  );
202
- migrations = {
203
- old_tag: script.migration_tag,
204
- new_tag: config.migrations[config.migrations.length - 1].tag,
205
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
206
- };
130
+ }
131
+ }
132
+
133
+ const content = readFileSync(resolvedEntryPointPath, {
134
+ encoding: "utf-8",
135
+ });
136
+
137
+ // if config.migrations
138
+ let migrations;
139
+ if (config.migrations.length > 0) {
140
+ // get current migration tag
141
+ const scripts = await fetchResult<
142
+ { id: string; migration_tag: string }[]
143
+ >(`/accounts/${accountId}/workers/scripts`);
144
+ const script = scripts.find(({ id }) => id === scriptName);
145
+ if (script?.migration_tag) {
146
+ // was already published once
147
+ const foundIndex = config.migrations.findIndex(
148
+ (migration) => migration.tag === script.migration_tag
149
+ );
150
+ if (foundIndex === -1) {
151
+ console.warn(
152
+ `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
153
+ );
154
+ migrations = {
155
+ old_tag: script.migration_tag,
156
+ new_tag: config.migrations[config.migrations.length - 1].tag,
157
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
158
+ };
159
+ } else {
160
+ if (foundIndex !== config.migrations.length - 1) {
161
+ // there are new migrations to send up
162
+ migrations = {
163
+ old_tag: script.migration_tag,
164
+ new_tag: config.migrations[config.migrations.length - 1].tag,
165
+ steps: config.migrations
166
+ .slice(foundIndex + 1)
167
+ .map(({ tag: _tag, ...rest }) => rest),
168
+ };
169
+ }
170
+ // else, we're up to date, no migrations to send
171
+ }
207
172
  } else {
173
+ // first time publishing durable objects to this script,
174
+ // so we send all the migrations
208
175
  migrations = {
209
- old_tag: script.migration_tag,
210
176
  new_tag: config.migrations[config.migrations.length - 1].tag,
211
- steps: config.migrations
212
- .slice(foundIndex + 1)
213
- .map(({ tag: _tag, ...rest }) => rest),
177
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
214
178
  };
215
179
  }
216
- } else {
217
- migrations = {
218
- new_tag: config.migrations[config.migrations.length - 1].tag,
219
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
220
- };
221
180
  }
222
- }
223
181
 
224
- const assetPath = props.public || props.site || props.config.site?.bucket; // TODO: allow both
225
- const assets = assetPath
226
- ? await syncAssets(accountId, scriptName, assetPath, false)
227
- : { manifest: undefined, namespace: undefined };
228
-
229
- const bindings: CfWorkerInit["bindings"] = {
230
- kv_namespaces: envRootObj.kv_namespaces?.concat(
231
- assets.namespace
232
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
233
- : []
234
- ),
235
- vars: envRootObj.vars,
236
- durable_objects: envRootObj.durable_objects,
237
- services: envRootObj.experimental_services,
238
- };
239
-
240
- const worker: CfWorkerInit = {
241
- name: scriptName,
242
- main: {
243
- name: path.basename(resolvedEntryPointPath),
244
- content: content,
245
- type: bundle.type === "esm" ? "esm" : "commonjs",
246
- },
247
- bindings,
248
- ...(migrations && { migrations }),
249
- modules: moduleCollector.modules.concat(
250
- assets.manifest
251
- ? {
252
- name: "__STATIC_CONTENT_MANIFEST",
253
- content: JSON.stringify(assets.manifest),
254
- type: "text",
255
- }
256
- : []
257
- ),
258
- compatibility_date: config.compatibility_date,
259
- compatibility_flags: config.compatibility_flags,
260
- usage_model: config.usage_model,
261
- };
262
-
263
- const start = Date.now();
264
- function formatTime(duration: number) {
265
- return `(${(duration / 1000).toFixed(2)} sec)`;
266
- }
182
+ const assets = await syncAssets(
183
+ accountId,
184
+ // When we're using the newer service environments, we wouldn't
185
+ // have added the env name on to the script name. However, we must
186
+ // include it in the kv namespace name regardless (since there's no
187
+ // concept of service environments for kv namespaces yet).
188
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
189
+ props.assetPaths,
190
+ false
191
+ );
267
192
 
268
- const notProd = !props.legacyEnv && props.env;
269
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
270
- const workerUrl = notProd
271
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
272
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
273
-
274
- // Upload the script so it has time to propagate.
275
- const { available_on_subdomain } = await fetchResult(
276
- workerUrl,
277
- {
278
- method: "PUT",
279
- // @ts-expect-error: TODO: fix this type error!
280
- body: toFormData(worker),
281
- },
282
- new URLSearchParams({ available_on_subdomains: "true" })
283
- );
193
+ const bindings: CfWorkerInit["bindings"] = {
194
+ kv_namespaces: (config.kv_namespaces || []).concat(
195
+ assets.namespace
196
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
197
+ : []
198
+ ),
199
+ vars: config.vars,
200
+ wasm_modules: config.wasm_modules,
201
+ text_blobs: {
202
+ ...config.text_blobs,
203
+ ...(assets.manifest &&
204
+ format === "service-worker" && {
205
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
206
+ }),
207
+ },
208
+ data_blobs: config.data_blobs,
209
+ durable_objects: config.durable_objects,
210
+ r2_buckets: config.r2_buckets,
211
+ unsafe: config.unsafe?.bindings,
212
+ };
213
+
214
+ if (assets.manifest) {
215
+ modules.push({
216
+ name: "__STATIC_CONTENT_MANIFEST",
217
+ content: JSON.stringify(assets.manifest),
218
+ type: "text",
219
+ });
220
+ }
284
221
 
285
- const uploadMs = Date.now() - start;
286
- console.log("Uploaded", workerName, formatTime(uploadMs));
287
- const deployments: Promise<string[]>[] = [];
222
+ const worker: CfWorkerInit = {
223
+ name: scriptName,
224
+ main: {
225
+ name: path.basename(resolvedEntryPointPath),
226
+ content: content,
227
+ type: bundleType,
228
+ },
229
+ bindings,
230
+ migrations,
231
+ modules,
232
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
233
+ compatibility_flags:
234
+ props.compatibilityFlags ?? config.compatibility_flags,
235
+ usage_model: config.usage_model,
236
+ };
237
+
238
+ const start = Date.now();
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 propagate.
246
+ const { available_on_subdomain } = await fetchResult(
247
+ workerUrl,
248
+ {
249
+ method: "PUT",
250
+ body: createWorkerUploadForm(worker),
251
+ },
252
+ new URLSearchParams({ available_on_subdomain: "true" })
253
+ );
288
254
 
289
- const userSubdomain = (
290
- await fetchResult<{ subdomain: string }>(
291
- `/accounts/${accountId}/workers/subdomain`
292
- )
293
- ).subdomain;
294
-
295
- const scriptURL =
296
- props.legacyEnv || !props.env
297
- ? `${scriptName}.${userSubdomain}.workers.dev`
298
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
299
-
300
- // Enable the `workers.dev` subdomain.
301
- // TODO: Make this configurable.
302
- if (!available_on_subdomain) {
303
- deployments.push(
304
- fetchResult(`${workerUrl}/subdomain`, {
255
+ const uploadMs = Date.now() - start;
256
+ const deployments: Promise<string[]>[] = [];
257
+
258
+ if (deployToWorkersDev) {
259
+ // Deploy to a subdomain of `workers.dev`
260
+ const userSubdomain = await getSubdomain(accountId);
261
+ const scriptURL =
262
+ props.legacyEnv || !props.env
263
+ ? `${scriptName}.${userSubdomain}.workers.dev`
264
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
265
+ if (!available_on_subdomain) {
266
+ // Enable the `workers.dev` subdomain.
267
+ deployments.push(
268
+ fetchResult(`${workerUrl}/subdomain`, {
269
+ method: "POST",
270
+ body: JSON.stringify({ enabled: true }),
271
+ headers: {
272
+ "Content-Type": "application/json",
273
+ },
274
+ })
275
+ .then(() => [scriptURL])
276
+ // Add a delay when the subdomain is first created.
277
+ // This is to prevent an issue where a negative cache-hit
278
+ // causes the subdomain to be unavailable for 30 seconds.
279
+ // This is a temporary measure until we fix this on the edge.
280
+ .then(async (url) => {
281
+ await sleep(3000);
282
+ return url;
283
+ })
284
+ );
285
+ } else {
286
+ deployments.push(Promise.resolve([scriptURL]));
287
+ }
288
+ } else {
289
+ // Disable the workers.dev deployment
290
+ await fetchResult(`${workerUrl}/subdomain`, {
305
291
  method: "POST",
306
- body: JSON.stringify({ enabled: true }),
292
+ body: JSON.stringify({ enabled: false }),
307
293
  headers: {
308
294
  "Content-Type": "application/json",
309
295
  },
310
- })
311
- .then(() => [scriptURL])
312
- // Add a delay when the subdomain is first created.
313
- // This is to prevent an issue where a negative cache-hit
314
- // causes the subdomain to be unavailable for 30 seconds.
315
- // This is a temporary measure until we fix this on the edge.
316
- .then(async (url) => {
317
- await sleep(3000);
318
- return url;
319
- })
320
- );
321
- } else {
322
- deployments.push(Promise.resolve([scriptURL]));
323
- }
296
+ });
297
+ }
324
298
 
325
- // Update routing table for the script.
326
- if (routes && routes.length) {
327
- deployments.push(
328
- fetchResult(`${workerUrl}/routes`, {
329
- // TODO: PATCH will not delete previous routes on this script,
330
- // whereas PUT will. We need to decide on the default behaviour
331
- // and how to configure it.
332
- method: "PUT",
333
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
334
- headers: {
335
- "Content-Type": "application/json",
336
- },
337
- }).then(() => {
338
- if (routes.length > 10) {
339
- return routes
340
- .slice(0, 9)
341
- .map(String)
342
- .concat([`...and ${routes.length - 10} more routes`]);
343
- }
344
- return routes.map(String);
345
- })
346
- );
347
- }
299
+ console.log("Uploaded", workerName, formatTime(uploadMs));
300
+
301
+ // Update routing table for the script.
302
+ if (routes.length > 0) {
303
+ deployments.push(
304
+ fetchResult(`${workerUrl}/routes`, {
305
+ // TODO: PATCH will not delete previous routes on this script,
306
+ // whereas PUT will. We need to decide on the default behaviour
307
+ // and how to configure it.
308
+ method: "PUT",
309
+ body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
310
+ headers: {
311
+ "Content-Type": "application/json",
312
+ },
313
+ }).then(() => {
314
+ if (routes.length > 10) {
315
+ return routes
316
+ .slice(0, 9)
317
+ .map(String)
318
+ .concat([`...and ${routes.length - 10} more routes`]);
319
+ }
320
+ return routes.map(String);
321
+ })
322
+ );
323
+ }
348
324
 
349
- // Configure any schedules for the script.
350
- // TODO: rename this to `schedules`?
351
- if (triggers && triggers.length) {
352
- deployments.push(
353
- fetchResult(`${workerUrl}/schedules`, {
354
- // TODO: Unlike routes, this endpoint does not support PATCH.
355
- // So technically, this will override any previous schedules.
356
- // We should change the endpoint to support PATCH.
357
- method: "PUT",
358
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
359
- headers: {
360
- "Content-Type": "application/json",
361
- },
362
- }).then(() => triggers.map(String))
363
- );
364
- }
325
+ // Configure any schedules for the script.
326
+ // TODO: rename this to `schedules`?
327
+ if (triggers && triggers.length) {
328
+ deployments.push(
329
+ fetchResult(`${workerUrl}/schedules`, {
330
+ // TODO: Unlike routes, this endpoint does not support PATCH.
331
+ // So technically, this will override any previous schedules.
332
+ // We should change the endpoint to support PATCH.
333
+ method: "PUT",
334
+ body: JSON.stringify(triggers.map((cron) => ({ cron }))),
335
+ headers: {
336
+ "Content-Type": "application/json",
337
+ },
338
+ }).then(() => triggers.map(String))
339
+ );
340
+ }
365
341
 
366
- if (!deployments.length) {
367
- return;
368
- }
342
+ const targets = await Promise.all(deployments);
343
+ const deployMs = Date.now() - start - uploadMs;
369
344
 
370
- const targets = await Promise.all(deployments);
371
- const deployMs = Date.now() - start - uploadMs;
372
- console.log("Deployed", workerName, formatTime(deployMs));
373
- for (const target of targets.flat()) {
374
- console.log(" ", target);
345
+ if (deployments.length > 0) {
346
+ console.log("Published", workerName, formatTime(deployMs));
347
+ for (const target of targets.flat()) {
348
+ console.log(" ", target);
349
+ }
350
+ } else {
351
+ console.log("No publish targets for", workerName, formatTime(deployMs));
352
+ }
353
+ } finally {
354
+ await destination.cleanup();
375
355
  }
376
356
  }
377
357
 
378
- function listEntryPoints(outputs: ValueOf<Metafile["outputs"]>[]): string {
379
- return outputs.map((output) => output.entryPoint).join("\n");
358
+ function formatTime(duration: number) {
359
+ return `(${(duration / 1000).toFixed(2)} sec)`;
380
360
  }
381
361
 
382
- type ValueOf<T> = T[keyof T];
362
+ async function getSubdomain(accountId: string): Promise<string> {
363
+ try {
364
+ const { subdomain } = await fetchResult(
365
+ `/accounts/${accountId}/workers/subdomain`
366
+ );
367
+ return subdomain;
368
+ } catch (e) {
369
+ const error = e as { code?: number };
370
+ if (typeof error === "object" && !!error && error.code === 10007) {
371
+ // 10007 error code: not found
372
+ // https://api.cloudflare.com/#worker-subdomain-get-subdomain
373
+
374
+ const errorMessage =
375
+ "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
376
+ const solutionMessage =
377
+ "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
378
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
379
+
380
+ throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
381
+ } else {
382
+ throw e;
383
+ }
384
+ }
385
+ }