wrangler 0.0.0-e151223 → 0.0.0-e273e09

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 (152) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +49 -5
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +54 -28
  6. package/pages/functions/buildPlugin.ts +105 -0
  7. package/pages/functions/buildWorker.ts +93 -4
  8. package/pages/functions/filepath-routing.test.ts +223 -36
  9. package/pages/functions/filepath-routing.ts +78 -120
  10. package/pages/functions/routes.ts +13 -17
  11. package/pages/functions/template-plugin.ts +147 -0
  12. package/pages/functions/template-worker.ts +24 -17
  13. package/src/__tests__/config-cache.test.ts +36 -0
  14. package/src/__tests__/configuration.test.ts +3487 -0
  15. package/src/__tests__/dev.test.tsx +977 -65
  16. package/src/__tests__/guess-worker-format.test.ts +85 -0
  17. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  18. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  19. package/src/__tests__/helpers/mock-account-id.ts +26 -8
  20. package/src/__tests__/helpers/mock-bin.ts +36 -0
  21. package/src/__tests__/helpers/mock-cfetch.ts +48 -10
  22. package/src/__tests__/helpers/mock-console.ts +39 -8
  23. package/src/__tests__/helpers/mock-dialogs.ts +67 -2
  24. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  25. package/src/__tests__/helpers/mock-istty.ts +27 -0
  26. package/src/__tests__/helpers/mock-kv.ts +9 -16
  27. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  28. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  29. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  30. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  31. package/src/__tests__/helpers/run-wrangler.ts +5 -3
  32. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  33. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  34. package/src/__tests__/https-options.test.ts +130 -0
  35. package/src/__tests__/index.test.ts +160 -309
  36. package/src/__tests__/init.test.ts +1637 -0
  37. package/src/__tests__/jest.setup.ts +49 -6
  38. package/src/__tests__/kv.test.ts +607 -275
  39. package/src/__tests__/logger.test.ts +115 -0
  40. package/src/__tests__/package-manager.test.ts +353 -0
  41. package/src/__tests__/pages.test.ts +754 -0
  42. package/src/__tests__/parse.test.ts +330 -0
  43. package/src/__tests__/publish.test.ts +5472 -939
  44. package/src/__tests__/r2.test.ts +233 -0
  45. package/src/__tests__/route.test.ts +45 -0
  46. package/src/__tests__/secret.test.ts +362 -91
  47. package/src/__tests__/tail.test.ts +690 -0
  48. package/src/__tests__/user.test.ts +131 -0
  49. package/src/__tests__/whoami.test.tsx +60 -7
  50. package/src/abort.d.ts +3 -0
  51. package/src/bundle.ts +197 -0
  52. package/src/cfetch/index.ts +28 -18
  53. package/src/cfetch/internal.ts +99 -29
  54. package/src/cli.ts +6 -2
  55. package/src/config/README.md +107 -0
  56. package/src/config/config.ts +234 -0
  57. package/src/config/diagnostics.ts +80 -0
  58. package/src/config/environment.ts +420 -0
  59. package/src/config/index.ts +225 -0
  60. package/src/config/validation-helpers.ts +584 -0
  61. package/src/config/validation.ts +1548 -0
  62. package/src/config-cache.ts +45 -0
  63. package/src/create-worker-preview.ts +185 -0
  64. package/src/create-worker-upload-form.ts +254 -0
  65. package/src/dev/dev-vars.ts +36 -0
  66. package/src/dev/dev.tsx +401 -0
  67. package/src/dev/local.tsx +326 -0
  68. package/src/dev/remote.tsx +237 -0
  69. package/src/dev/use-esbuild.ts +118 -0
  70. package/src/dialogs.tsx +64 -6
  71. package/src/durable.ts +102 -0
  72. package/src/entry.ts +322 -0
  73. package/src/environment-variables.ts +35 -0
  74. package/src/errors.ts +11 -0
  75. package/src/https-options.ts +123 -0
  76. package/src/index.tsx +1768 -982
  77. package/src/inspect.ts +80 -14
  78. package/src/intl-polyfill.d.ts +139 -0
  79. package/src/{kv.tsx → kv.ts} +199 -67
  80. package/src/logger.ts +66 -0
  81. package/src/miniflare-cli/README.md +30 -0
  82. package/src/miniflare-cli/enum-keys.ts +17 -0
  83. package/src/miniflare-cli/index.ts +41 -0
  84. package/src/miniflare-cli/request-context.ts +40 -0
  85. package/src/module-collection.ts +226 -31
  86. package/src/open-in-browser.ts +19 -0
  87. package/src/package-manager.ts +174 -0
  88. package/src/pages.tsx +1132 -84
  89. package/src/parse.ts +203 -0
  90. package/src/proxy.ts +170 -62
  91. package/src/publish.ts +617 -306
  92. package/src/r2.ts +50 -0
  93. package/src/selfsigned.d.ts +29 -0
  94. package/src/sites.tsx +143 -57
  95. package/src/tail/filters.ts +279 -0
  96. package/src/tail/index.ts +299 -0
  97. package/src/tail/printing.ts +67 -0
  98. package/src/update-check.ts +19 -0
  99. package/src/user.tsx +341 -146
  100. package/src/whoami.tsx +5 -3
  101. package/src/{api/worker.ts → worker.ts} +65 -39
  102. package/src/zones.ts +73 -0
  103. package/templates/gitignore +171 -0
  104. package/templates/new-worker-scheduled.js +17 -0
  105. package/templates/new-worker-scheduled.ts +32 -0
  106. package/templates/new-worker.js +15 -0
  107. package/templates/new-worker.ts +30 -0
  108. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -5
  109. package/templates/tsconfig.json +105 -0
  110. package/wrangler-dist/cli.js +77223 -75763
  111. package/src/__tests__/helpers/mock-user.ts +0 -27
  112. package/src/__tests__/logout.test.ts +0 -50
  113. package/src/api/form_data.ts +0 -134
  114. package/src/api/preview.ts +0 -128
  115. package/src/config.ts +0 -641
  116. package/src/dev.tsx +0 -834
  117. package/src/npm-installer.ts +0 -20
  118. package/src/tail.tsx +0 -73
  119. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  120. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  121. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  122. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  123. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  124. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  125. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  126. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  127. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  128. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  129. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  130. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  131. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  132. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  133. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  134. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  135. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  136. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  137. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  138. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  139. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  140. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  141. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  142. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  143. package/vendor/wrangler-mime/LICENSE +0 -21
  144. package/vendor/wrangler-mime/Mime.js +0 -97
  145. package/vendor/wrangler-mime/README.md +0 -187
  146. package/vendor/wrangler-mime/cli.js +0 -46
  147. package/vendor/wrangler-mime/index.js +0 -4
  148. package/vendor/wrangler-mime/lite.js +0 -4
  149. package/vendor/wrangler-mime/package.json +0 -52
  150. package/vendor/wrangler-mime/types/other.js +0 -1
  151. package/vendor/wrangler-mime/types/standard.js +0 -1
  152. package/wrangler-dist/cli.js.map +0 -7
package/src/index.tsx CHANGED
@@ -1,79 +1,199 @@
1
1
  import * as fs from "node:fs";
2
- import { readFile, writeFile } from "node:fs/promises";
3
- import path from "node:path/posix";
2
+ import { writeFile, mkdir } from "node:fs/promises";
3
+ import path from "node:path";
4
4
  import { setTimeout } from "node:timers/promises";
5
5
  import TOML from "@iarna/toml";
6
+ import chalk from "chalk";
7
+ import { watch } from "chokidar";
8
+ import { execa } from "execa";
6
9
  import { findUp } from "find-up";
10
+ import getPort from "get-port";
7
11
  import { render } from "ink";
8
12
  import React from "react";
9
13
  import onExit from "signal-exit";
14
+ import supportsColor from "supports-color";
15
+ import { setGlobalDispatcher, ProxyAgent } from "undici";
10
16
  import makeCLI from "yargs";
11
17
  import { version as wranglerVersion } from "../package.json";
12
- import { toFormData } from "./api/form_data";
13
- import { fetchResult, fetchRaw } from "./cfetch";
14
- import { normaliseAndValidateEnvironmentsConfig } from "./config";
15
- import Dev from "./dev";
16
- import { confirm, prompt } from "./dialogs";
18
+ import { fetchResult } from "./cfetch";
19
+ import { findWranglerToml, printBindings, readConfig } from "./config";
20
+ import { createWorkerUploadForm } from "./create-worker-upload-form";
21
+ import Dev from "./dev/dev";
22
+ import { getVarsForDev } from "./dev/dev-vars";
23
+ import { confirm, prompt, select } from "./dialogs";
24
+ import { getEntry } from "./entry";
25
+ import { DeprecationError } from "./errors";
17
26
  import {
18
- getNamespaceId,
19
- listNamespaces,
20
- listNamespaceKeys,
21
- putKeyValue,
22
- putBulkKeyValue,
23
- deleteBulkKeyValue,
24
- createNamespace,
25
- isValidNamespaceBinding,
27
+ getKVNamespaceId,
28
+ listKVNamespaces,
29
+ listKVNamespaceKeys,
30
+ putKVKeyValue,
31
+ putKVBulkKeyValue,
32
+ deleteKVBulkKeyValue,
33
+ createKVNamespace,
34
+ isValidKVNamespaceBinding,
35
+ getKVKeyValue,
36
+ isKVKeyValue,
37
+ unexpectedKVKeyValueProps,
38
+ deleteKVNamespace,
39
+ deleteKVKeyValue,
26
40
  } from "./kv";
27
- import { npm } from "./npm-installer";
28
- import { pages } from "./pages";
41
+ import { logger } from "./logger";
42
+ import { getPackageManager } from "./package-manager";
43
+ import { pages, pagesBetaWarning } from "./pages";
44
+ import {
45
+ formatMessage,
46
+ ParseError,
47
+ parseJSON,
48
+ parsePackageJSON,
49
+ parseTOML,
50
+ readFileSync,
51
+ } from "./parse";
29
52
  import publish from "./publish";
53
+ import { createR2Bucket, deleteR2Bucket, listR2Buckets } from "./r2";
30
54
  import { getAssetPaths } from "./sites";
31
- import { createTail } from "./tail";
55
+ import {
56
+ createTail,
57
+ jsonPrintLogs,
58
+ prettyPrintLogs,
59
+ translateCLICommandToFilterMessage,
60
+ } from "./tail";
61
+ import { updateCheck } from "./update-check";
32
62
  import {
33
63
  login,
34
64
  logout,
35
65
  listScopes,
36
- initialise as initialiseUserConfig,
37
- loginOrRefreshIfRequired,
38
- getAccountId,
39
66
  validateScopeKeys,
67
+ requireAuth,
40
68
  } from "./user";
41
69
  import { whoami } from "./whoami";
70
+ import { getZoneIdFromHost, getZoneForRoute } from "./zones";
42
71
 
43
72
  import type { Config } from "./config";
73
+ import type { TailCLIFilters } from "./tail";
74
+ import type { RawData } from "ws";
75
+ import type { CommandModule } from "yargs";
44
76
  import type Yargs from "yargs";
45
77
 
78
+ type ConfigPath = string | undefined;
79
+
46
80
  const resetColor = "\x1b[0m";
47
81
  const fgGreenColor = "\x1b[32m";
82
+ const DEFAULT_LOCAL_PORT = 8787;
83
+
84
+ const proxy =
85
+ process.env.https_proxy ||
86
+ process.env.HTTPS_PROXY ||
87
+ process.env.http_proxy ||
88
+ process.env.HTTP_PROXY ||
89
+ undefined;
48
90
 
49
- async function readConfig(configPath?: string): Promise<Config> {
50
- const config: Config = {};
51
- if (!configPath) {
52
- configPath = await findUp("wrangler.toml");
53
- // TODO - terminate this early instead of going all the way to the root
91
+ if (proxy) {
92
+ setGlobalDispatcher(new ProxyAgent(proxy));
93
+ }
94
+
95
+ function getRules(config: Config): Config["rules"] {
96
+ const rules = config.rules ?? config.build?.upload?.rules ?? [];
97
+
98
+ if (config.rules && config.build?.upload?.rules) {
99
+ throw new Error(
100
+ `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
101
+ );
54
102
  }
55
103
 
56
- if (configPath) {
57
- const tml: string = await readFile(configPath, "utf-8");
58
- const parsed = TOML.parse(tml) as Config;
59
- Object.assign(config, parsed);
104
+ if (config.build?.upload?.rules) {
105
+ logger.warn(
106
+ `Deprecation: The \`build.upload.rules\` config field is no longer used, the rules should be specified via the \`rules\` config field. Delete the \`build.upload\` field from the configuration file, and add this:
107
+
108
+ ${TOML.stringify({ rules: config.build.upload.rules })}`
109
+ );
60
110
  }
111
+ return rules;
112
+ }
113
+
114
+ async function printWranglerBanner() {
115
+ // Let's not print this in tests
116
+ if (typeof jest !== "undefined") {
117
+ return;
118
+ }
119
+
120
+ const text = ` ⛅️ wrangler ${wranglerVersion} ${await updateCheck()}`;
121
+
122
+ logger.log(
123
+ text +
124
+ "\n" +
125
+ (supportsColor.stdout
126
+ ? chalk.hex("#FF8800")("-".repeat(text.length))
127
+ : "-".repeat(text.length))
128
+ );
129
+ }
61
130
 
62
- normaliseAndValidateEnvironmentsConfig(config);
131
+ function isLegacyEnv(config: Config): boolean {
132
+ // We only read from config here, because we've already accounted for
133
+ // args["legacy-env"] in https://github.com/cloudflare/wrangler2/blob/b24aeb5722370c2e04bce97a84a1fa1e55725d79/packages/wrangler/src/config/validation.ts#L94-L98
134
+ return config.legacy_env;
135
+ }
63
136
 
64
- if ("experimental_services" in config) {
65
- console.warn(
66
- "The experimental_services field is only for cloudflare internal usage right now, and is subject to change. Please do not use this on production projects"
137
+ function getScriptName(
138
+ args: { name: string | undefined; env: string | undefined },
139
+ config: Config
140
+ ): string | undefined {
141
+ if (args.name && isLegacyEnv(config) && args.env) {
142
+ throw new CommandLineArgsError(
143
+ "In legacy environment mode you cannot use --name and --env together. If you want to specify a Worker name for a specific environment you can add the following to your wrangler.toml config:" +
144
+ `
145
+ [env.${args.env}]
146
+ name = "${args.name}"
147
+ `
67
148
  );
68
149
  }
69
150
 
70
- // todo: validate, add defaults
71
- // let's just do some basics for now
151
+ return args.name ?? config.name;
152
+ }
153
+
154
+ /**
155
+ * Alternative to the getScriptName() because special Legacy cases allowed "name", and "env" together in Wrangler1
156
+ */
157
+ function getLegacyScriptName(
158
+ args: { name: string | undefined; env: string | undefined },
159
+ config: Config
160
+ ) {
161
+ return args.name && args.env && isLegacyEnv(config)
162
+ ? `${args.name}-${args.env}`
163
+ : args.name ?? config.name;
164
+ }
72
165
 
73
- // @ts-expect-error we're being sneaky here for now
74
- config.__path__ = configPath;
166
+ /**
167
+ * Get a promise to the streamed input from stdin.
168
+ *
169
+ * This function can be used to grab the incoming stream of data from, say,
170
+ * piping the output of another process into the wrangler process.
171
+ */
172
+ function readFromStdin(): Promise<string> {
173
+ return new Promise((resolve, reject) => {
174
+ const stdin = process.stdin;
175
+ const chunks: string[] = [];
176
+
177
+ // When there is data ready to be read, the `readable` event will be triggered.
178
+ // In the handler for `readable` we call `read()` over and over until all the available data has been read.
179
+ stdin.on("readable", () => {
180
+ let chunk;
181
+ while (null !== (chunk = stdin.read())) {
182
+ chunks.push(chunk);
183
+ }
184
+ });
75
185
 
76
- return config;
186
+ // When the streamed data is complete the `end` event will be triggered.
187
+ // In the handler for `end` we join the chunks together and resolve the promise.
188
+ stdin.on("end", () => {
189
+ resolve(chunks.join(""));
190
+ });
191
+
192
+ // If there is an `error` event then the handler will reject the promise.
193
+ stdin.on("error", (err) => {
194
+ reject(err);
195
+ });
196
+ });
77
197
  }
78
198
 
79
199
  // a helper to demand one of a set of options
@@ -101,19 +221,27 @@ function demandOneOfOption(...options: string[]) {
101
221
  };
102
222
  }
103
223
 
224
+ /**
225
+ * Remove trailing white space from inputs.
226
+ * Matching Wrangler legacy behavior with handling inputs
227
+ */
228
+ function trimTrailingWhitespace(str: string) {
229
+ return str.trimEnd();
230
+ }
231
+
104
232
  class CommandLineArgsError extends Error {}
105
- class DeprecationError extends Error {}
106
- class NotImplementedError extends Error {}
107
233
 
108
- export async function main(argv: string[]): Promise<void> {
234
+ function createCLIParser(argv: string[]) {
109
235
  const wrangler = makeCLI(argv)
236
+ .strict()
110
237
  // We handle errors ourselves in a try-catch around `yargs.parse`.
111
238
  // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
112
239
  // Otherwise we just log the error that was thrown without any "help info".
113
240
  .showHelpOnFail(false)
114
241
  .fail((msg, error) => {
115
- if (!error) {
116
- // If there is only a `msg` then this came from yargs own validation, so wrap in a `CommandLineArgsError`.
242
+ if (!error || error.name === "YError") {
243
+ // If there is no error or the error is a "YError", then this came from yargs own validation
244
+ // Wrap it in a `CommandLineArgsError` so that we can handle it appropriately further up.
117
245
  error = new CommandLineArgsError(msg);
118
246
  }
119
247
  throw error;
@@ -121,7 +249,15 @@ export async function main(argv: string[]): Promise<void> {
121
249
  .scriptName("wrangler")
122
250
  .wrap(null);
123
251
 
124
- // the default is to simply print the help menu
252
+ // Default help command that supports the subcommands
253
+ const subHelp: CommandModule = {
254
+ command: ["*"],
255
+ handler: async (args) => {
256
+ setImmediate(() =>
257
+ wrangler.parse([...args._.map((a) => `${a}`), "--help"])
258
+ );
259
+ },
260
+ };
125
261
  wrangler.command(
126
262
  ["*"],
127
263
  false,
@@ -155,14 +291,19 @@ export async function main(argv: string[]): Promise<void> {
155
291
  default: "worker",
156
292
  })
157
293
  .positional("template", {
158
- describe: "a link to a GitHub template",
294
+ describe: "The URL of a GitHub template",
159
295
  default: "https://github.com/cloudflare/worker-template",
160
296
  });
161
297
  },
162
- () => {
298
+ (generateArgs) => {
163
299
  // "👯 [DEPRECATED]. Scaffold a Cloudflare Workers project from a public GitHub repository.",
164
300
  throw new DeprecationError(
165
- "`wrangler generate` has been deprecated, please refer to TODO://some/path for alternatives"
301
+ "`wrangler generate` has been deprecated.\n" +
302
+ "Try running `wrangler init` to generate a basic Worker, or cloning the template repository instead:\n\n" +
303
+ "```\n" +
304
+ `git clone ${generateArgs.template}\n` +
305
+ "```\n\n" +
306
+ "Please refer to https://developers.cloudflare.com/workers/wrangler/deprecations/#generate for more information."
166
307
  );
167
308
  }
168
309
  );
@@ -172,13 +313,32 @@ export async function main(argv: string[]): Promise<void> {
172
313
  "init [name]",
173
314
  "📥 Create a wrangler.toml configuration file",
174
315
  (yargs) => {
175
- return yargs.positional("name", {
176
- describe: "The name of your worker.",
177
- type: "string",
178
- });
316
+ return yargs
317
+ .positional("name", {
318
+ describe: "The name of your worker",
319
+ type: "string",
320
+ })
321
+ .option("type", {
322
+ describe: "The type of worker to create",
323
+ type: "string",
324
+ choices: ["rust", "javascript", "webpack"],
325
+ hidden: true,
326
+ deprecated: true,
327
+ })
328
+ .option("site", {
329
+ hidden: true,
330
+ type: "boolean",
331
+ deprecated: true,
332
+ })
333
+ .option("yes", {
334
+ describe: 'Answer "yes" to any prompts for new projects',
335
+ type: "boolean",
336
+ alias: "y",
337
+ });
179
338
  },
180
339
  async (args) => {
181
- if ("type" in args) {
340
+ await printWranglerBanner();
341
+ if (args.type) {
182
342
  let message = "The --type option is no longer supported.";
183
343
  if (args.type === "webpack") {
184
344
  message +=
@@ -188,9 +348,52 @@ export async function main(argv: string[]): Promise<void> {
188
348
  throw new CommandLineArgsError(message);
189
349
  }
190
350
 
191
- const destination = path.join(process.cwd(), "wrangler.toml");
192
- if (fs.existsSync(destination)) {
193
- console.warn(`${destination} file already exists!`);
351
+ const devDepsToInstall: string[] = [];
352
+ const instructions: string[] = [];
353
+ let shouldRunPackageManagerInstall = false;
354
+ const creationDirectory = path.resolve(process.cwd(), args.name ?? "");
355
+
356
+ if (args.site) {
357
+ const gitDirectory =
358
+ creationDirectory !== process.cwd()
359
+ ? path.basename(creationDirectory)
360
+ : "my-site";
361
+ const message =
362
+ "The --site option is no longer supported.\n" +
363
+ "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
364
+ "```\n" +
365
+ `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
366
+ `cd ${gitDirectory}\n` +
367
+ "```\n\n" +
368
+ "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
369
+ "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
370
+ throw new CommandLineArgsError(message);
371
+ }
372
+
373
+ // TODO: make sure args.name is a valid identifier for a worker name
374
+ const workerName = path
375
+ .basename(creationDirectory)
376
+ .toLowerCase()
377
+ .replaceAll(/[^a-z0-9\-_]/gm, "-");
378
+
379
+ const packageManager = await getPackageManager(creationDirectory);
380
+
381
+ // TODO: ask which directory to make the worker in (defaults to args.name)
382
+ // TODO: if args.name isn't provided, ask what to name the worker
383
+
384
+ const wranglerTomlDestination = path.join(
385
+ creationDirectory,
386
+ "./wrangler.toml"
387
+ );
388
+ let justCreatedWranglerToml = false;
389
+
390
+ if (fs.existsSync(wranglerTomlDestination)) {
391
+ logger.warn(
392
+ `${path.relative(
393
+ process.cwd(),
394
+ wranglerTomlDestination
395
+ )} already exists!`
396
+ );
194
397
  const shouldContinue = await confirm(
195
398
  "Do you want to continue initializing this project?"
196
399
  );
@@ -198,33 +401,91 @@ export async function main(argv: string[]): Promise<void> {
198
401
  return;
199
402
  }
200
403
  } else {
404
+ await mkdir(creationDirectory, { recursive: true });
201
405
  const compatibilityDate = new Date().toISOString().substring(0, 10);
406
+
202
407
  try {
203
408
  await writeFile(
204
- destination,
205
- `compatibility_date = "${compatibilityDate}"` + "\n"
409
+ wranglerTomlDestination,
410
+ TOML.stringify({
411
+ name: workerName,
412
+ compatibility_date: compatibilityDate,
413
+ }) + "\n"
414
+ );
415
+
416
+ logger.log(
417
+ `✨ Created ${path.relative(
418
+ process.cwd(),
419
+ wranglerTomlDestination
420
+ )}`
206
421
  );
207
- console.log(`✨ Successfully created wrangler.toml`);
208
- // TODO: suggest next steps?
422
+ justCreatedWranglerToml = true;
209
423
  } catch (err) {
210
424
  throw new Error(
211
- `Failed to create wrangler.toml.\n${err.message ?? err}`
425
+ `Failed to create ${path.relative(
426
+ process.cwd(),
427
+ wranglerTomlDestination
428
+ )}.\n${(err as Error).message ?? err}`
212
429
  );
213
430
  }
214
431
  }
215
432
 
216
- let pathToPackageJson = await findUp("package.json");
433
+ const yesFlag = args.yes ?? false;
434
+
435
+ const isInsideGitProject = Boolean(
436
+ await findUp(".git", { cwd: creationDirectory, type: "directory" })
437
+ );
438
+ let isGitInstalled;
439
+ try {
440
+ isGitInstalled = (await execa("git", ["--version"])).exitCode === 0;
441
+ } catch (err) {
442
+ isGitInstalled = false;
443
+ }
444
+ if (!isInsideGitProject && isGitInstalled) {
445
+ const shouldInitGit =
446
+ yesFlag ||
447
+ (await confirm("Would you like to use git to manage this Worker?"));
448
+ if (shouldInitGit) {
449
+ await execa("git", ["init"], {
450
+ cwd: creationDirectory,
451
+ });
452
+ await execa("git", ["branch", "-m", "main"], {
453
+ cwd: creationDirectory,
454
+ });
455
+ await writeFile(
456
+ path.join(creationDirectory, ".gitignore"),
457
+ readFileSync(path.join(__dirname, "../templates/gitignore"))
458
+ );
459
+ logger.log(
460
+ args.name && args.name !== "."
461
+ ? `✨ Initialized git repository at ${path.relative(
462
+ process.cwd(),
463
+ creationDirectory
464
+ )}`
465
+ : `✨ Initialized git repository`
466
+ );
467
+ }
468
+ }
469
+
470
+ let pathToPackageJson = await findUp("package.json", {
471
+ cwd: creationDirectory,
472
+ });
473
+ let shouldCreatePackageJson = false;
474
+
217
475
  if (!pathToPackageJson) {
218
476
  // If no package.json exists, ask to create one
219
- const shouldCreatePackageJson = await confirm(
220
- "No package.json found. Would you like to create one?"
221
- );
477
+ shouldCreatePackageJson =
478
+ yesFlag ||
479
+ (await confirm(
480
+ "No package.json found. Would you like to create one?"
481
+ ));
482
+
222
483
  if (shouldCreatePackageJson) {
223
484
  await writeFile(
224
- path.join(process.cwd(), "package.json"),
485
+ path.join(creationDirectory, "./package.json"),
225
486
  JSON.stringify(
226
487
  {
227
- name: "worker",
488
+ name: workerName,
228
489
  version: "0.0.0",
229
490
  devDependencies: {
230
491
  wrangler: wranglerVersion,
@@ -235,17 +496,21 @@ export async function main(argv: string[]): Promise<void> {
235
496
  " "
236
497
  ) + "\n"
237
498
  );
238
- await npm.install();
239
- console.log(`✨ Created package.json`);
240
- pathToPackageJson = path.join(process.cwd(), "package.json");
499
+
500
+ shouldRunPackageManagerInstall = true;
501
+ pathToPackageJson = path.join(creationDirectory, "package.json");
502
+ logger.log(
503
+ `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
504
+ );
241
505
  } else {
242
506
  return;
243
507
  }
244
508
  } else {
245
509
  // If package.json exists and wrangler isn't installed,
246
510
  // then ask to add wrangler to devDependencies
247
- const packageJson = JSON.parse(
248
- await readFile(pathToPackageJson, "utf-8")
511
+ const packageJson = parsePackageJSON(
512
+ readFileSync(pathToPackageJson),
513
+ pathToPackageJson
249
514
  );
250
515
  if (
251
516
  !(
@@ -253,54 +518,47 @@ export async function main(argv: string[]): Promise<void> {
253
518
  packageJson.dependencies?.wrangler
254
519
  )
255
520
  ) {
256
- const shouldInstall = await confirm(
257
- "Would you like to install wrangler into your package.json?"
258
- );
521
+ const shouldInstall =
522
+ yesFlag ||
523
+ (await confirm(
524
+ `Would you like to install wrangler into ${path.relative(
525
+ process.cwd(),
526
+ pathToPackageJson
527
+ )}?`
528
+ ));
259
529
  if (shouldInstall) {
260
- await npm.addDevDeps(`wrangler@${wranglerVersion}`);
261
- console.log(`✨ Installed wrangler`);
530
+ devDepsToInstall.push(`wrangler@${wranglerVersion}`);
262
531
  }
263
532
  }
264
533
  }
265
534
 
266
- let pathToTSConfig = await findUp("tsconfig.json");
535
+ let isTypescriptProject = false;
536
+ let pathToTSConfig = await findUp("tsconfig.json", {
537
+ cwd: creationDirectory,
538
+ });
267
539
  if (!pathToTSConfig) {
268
540
  // If there's no tsconfig, offer to create one
269
541
  // and install @cloudflare/workers-types
270
- if (await confirm("Would you like to use typescript?")) {
542
+ if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
543
+ isTypescriptProject = true;
271
544
  await writeFile(
272
- path.join(process.cwd(), "tsconfig.json"),
273
- JSON.stringify(
274
- {
275
- compilerOptions: {
276
- target: "es2021",
277
- module: "es2022",
278
- moduleResolution: "node",
279
- allowJs: true,
280
- allowSyntheticDefaultImports: true,
281
- isolatedModules: true,
282
- noEmit: true,
283
- lib: ["es2021"],
284
- resolveJsonModule: true,
285
- types: ["@cloudflare/workers-types"],
286
- },
287
- },
288
- null,
289
- " "
290
- ) + "\n"
545
+ path.join(creationDirectory, "./tsconfig.json"),
546
+ readFileSync(path.join(__dirname, "../templates/tsconfig.json"))
291
547
  );
292
- await npm.addDevDeps("@cloudflare/workers-types", "typescript");
293
-
294
- console.log(
295
- `✨ Created tsconfig.json, installed @cloudflare/workers-types into devDependencies`
548
+ devDepsToInstall.push("@cloudflare/workers-types");
549
+ devDepsToInstall.push("typescript");
550
+ pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
551
+ logger.log(
552
+ `✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`
296
553
  );
297
- pathToTSConfig = path.join(process.cwd(), "tsconfig.json");
298
554
  }
299
555
  } else {
556
+ isTypescriptProject = true;
300
557
  // If there's a tsconfig, check if @cloudflare/workers-types
301
558
  // is already installed, and offer to install it if not
302
- const packageJson = JSON.parse(
303
- await readFile(pathToPackageJson, "utf-8")
559
+ const packageJson = parsePackageJSON(
560
+ readFileSync(pathToPackageJson),
561
+ pathToPackageJson
304
562
  );
305
563
  if (
306
564
  !(
@@ -312,19 +570,271 @@ export async function main(argv: string[]): Promise<void> {
312
570
  "Would you like to install the type definitions for Workers into your package.json?"
313
571
  );
314
572
  if (shouldInstall) {
315
- await npm.addDevDeps("@cloudflare/workers-types");
573
+ devDepsToInstall.push("@cloudflare/workers-types");
316
574
  // We don't update the tsconfig.json because
317
575
  // it could be complicated in existing projects
318
576
  // and we don't want to break them. Instead, we simply
319
577
  // tell the user that they need to update their tsconfig.json
320
- console.log(
321
- `✨ Installed @cloudflare/workers-types.\nPlease add "@cloudflare/workers-types" to compilerOptions.types in your tsconfig.json`
578
+ instructions.push(
579
+ `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
580
+ process.cwd(),
581
+ pathToTSConfig
582
+ )}`
322
583
  );
323
- } else {
324
- return;
325
584
  }
326
585
  }
327
586
  }
587
+
588
+ const packageJsonContent = parsePackageJSON(
589
+ readFileSync(pathToPackageJson),
590
+ pathToPackageJson
591
+ );
592
+ const shouldWritePackageJsonScripts =
593
+ !packageJsonContent.scripts?.start &&
594
+ !packageJsonContent.scripts?.publish &&
595
+ shouldCreatePackageJson;
596
+
597
+ /*
598
+ * Passes the array of accumulated devDeps to install through to
599
+ * the package manager. Also generates a human-readable list
600
+ * of packages it installed.
601
+ * If there are no devDeps to install, optionally runs
602
+ * the package manager's install command.
603
+ */
604
+ async function installPackages(
605
+ shouldRunInstall: boolean,
606
+ depsToInstall: string[]
607
+ ) {
608
+ //lets install the devDeps they asked for
609
+ //and run their package manager's install command if needed
610
+ if (depsToInstall.length > 0) {
611
+ const formatter = new Intl.ListFormat("en", {
612
+ style: "long",
613
+ type: "conjunction",
614
+ });
615
+ await packageManager.addDevDeps(...depsToInstall);
616
+ const versionlessPackages = depsToInstall.map((dep) =>
617
+ dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
618
+ );
619
+
620
+ logger.log(
621
+ `✨ Installed ${formatter.format(
622
+ versionlessPackages
623
+ )} into devDependencies`
624
+ );
625
+ } else {
626
+ if (shouldRunInstall) {
627
+ await packageManager.install();
628
+ }
629
+ }
630
+ }
631
+
632
+ async function writePackageJsonScriptsAndUpdateWranglerToml(
633
+ isWritingScripts: boolean,
634
+ isCreatingWranglerToml: boolean,
635
+ packagePath: string,
636
+ scriptPath: string,
637
+ extraToml: TOML.JsonMap
638
+ ) {
639
+ if (isCreatingWranglerToml) {
640
+ // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
641
+ const parsedWranglerToml = parseTOML(
642
+ readFileSync(wranglerTomlDestination)
643
+ );
644
+ const newToml = {
645
+ name: parsedWranglerToml.name,
646
+ main: scriptPath,
647
+ compatibility_date: parsedWranglerToml.compatibility_date,
648
+ ...extraToml,
649
+ };
650
+ fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
651
+ }
652
+ const isNamedWorker =
653
+ isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
654
+
655
+ if (isWritingScripts) {
656
+ await writeFile(
657
+ packagePath,
658
+ JSON.stringify(
659
+ {
660
+ ...packageJsonContent,
661
+ scripts: {
662
+ ...packageJsonContent.scripts,
663
+ start: isCreatingWranglerToml
664
+ ? `wrangler dev`
665
+ : `wrangler dev ${scriptPath}`,
666
+ deploy: isCreatingWranglerToml
667
+ ? `wrangler publish`
668
+ : `wrangler publish ${scriptPath}`,
669
+ },
670
+ },
671
+ null,
672
+ 2
673
+ ) + "\n"
674
+ );
675
+ instructions.push(
676
+ `\nTo start developing your Worker, run \`${
677
+ isNamedWorker ? `cd ${args.name} && ` : ""
678
+ }npm start\``
679
+ );
680
+ instructions.push(
681
+ `To publish your Worker to the Internet, run \`npm run deploy\``
682
+ );
683
+ } else {
684
+ instructions.push(
685
+ `\nTo start developing your Worker, run \`npx wrangler dev\`${
686
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
687
+ }`
688
+ );
689
+ instructions.push(
690
+ `To publish your Worker to the Internet, run \`npx wrangler publish\`${
691
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
692
+ }`
693
+ );
694
+ }
695
+ }
696
+
697
+ async function getNewWorkerType(newWorkerFilename: string) {
698
+ return select(
699
+ `Would you like to create a Worker at ${newWorkerFilename}?`,
700
+ [
701
+ {
702
+ value: "none",
703
+ label: "None",
704
+ },
705
+ {
706
+ value: "fetch",
707
+ label: "Fetch handler",
708
+ },
709
+ {
710
+ value: "scheduled",
711
+ label: "Scheduled handler",
712
+ },
713
+ ],
714
+ 1
715
+ ) as Promise<"none" | "fetch" | "scheduled">;
716
+ }
717
+
718
+ function getNewWorkerTemplate(
719
+ lang: "js" | "ts",
720
+ workerType: "fetch" | "scheduled"
721
+ ) {
722
+ const templates = {
723
+ "js-fetch": "new-worker.js",
724
+ "js-scheduled": "new-worker-scheduled.js",
725
+ "ts-fetch": "new-worker.ts",
726
+ "ts-scheduled": "new-worker-scheduled.ts",
727
+ };
728
+
729
+ return templates[`${lang}-${workerType}`];
730
+ }
731
+
732
+ function getNewWorkerToml(
733
+ workerType: "fetch" | "scheduled"
734
+ ): TOML.JsonMap {
735
+ if (workerType === "scheduled") {
736
+ return {
737
+ triggers: {
738
+ crons: ["1 * * * *"],
739
+ },
740
+ };
741
+ }
742
+
743
+ return {};
744
+ }
745
+
746
+ if (isTypescriptProject) {
747
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
748
+ const newWorkerFilename = path.relative(
749
+ process.cwd(),
750
+ path.join(creationDirectory, "./src/index.ts")
751
+ );
752
+
753
+ const newWorkerType = yesFlag
754
+ ? "fetch"
755
+ : await getNewWorkerType(newWorkerFilename);
756
+
757
+ if (newWorkerType !== "none") {
758
+ const template = getNewWorkerTemplate("ts", newWorkerType);
759
+
760
+ await mkdir(path.join(creationDirectory, "./src"), {
761
+ recursive: true,
762
+ });
763
+ await writeFile(
764
+ path.join(creationDirectory, "./src/index.ts"),
765
+ readFileSync(path.join(__dirname, `../templates/${template}`))
766
+ );
767
+
768
+ logger.log(
769
+ `✨ Created ${path.relative(
770
+ process.cwd(),
771
+ path.join(creationDirectory, "./src/index.ts")
772
+ )}`
773
+ );
774
+
775
+ await writePackageJsonScriptsAndUpdateWranglerToml(
776
+ shouldWritePackageJsonScripts,
777
+ justCreatedWranglerToml,
778
+ pathToPackageJson,
779
+ "src/index.ts",
780
+ getNewWorkerToml(newWorkerType)
781
+ );
782
+ }
783
+ }
784
+ } else {
785
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
786
+ const newWorkerFilename = path.relative(
787
+ process.cwd(),
788
+ path.join(creationDirectory, "./src/index.js")
789
+ );
790
+
791
+ const newWorkerType = yesFlag
792
+ ? "fetch"
793
+ : await getNewWorkerType(newWorkerFilename);
794
+
795
+ if (newWorkerType !== "none") {
796
+ const template = getNewWorkerTemplate("js", newWorkerType);
797
+
798
+ await mkdir(path.join(creationDirectory, "./src"), {
799
+ recursive: true,
800
+ });
801
+ await writeFile(
802
+ path.join(creationDirectory, "./src/index.js"),
803
+ readFileSync(path.join(__dirname, `../templates/${template}`))
804
+ );
805
+
806
+ logger.log(
807
+ `✨ Created ${path.relative(
808
+ process.cwd(),
809
+ path.join(creationDirectory, "./src/index.js")
810
+ )}`
811
+ );
812
+
813
+ await writePackageJsonScriptsAndUpdateWranglerToml(
814
+ shouldWritePackageJsonScripts,
815
+ justCreatedWranglerToml,
816
+ pathToPackageJson,
817
+ "src/index.js",
818
+ getNewWorkerToml(newWorkerType)
819
+ );
820
+ }
821
+ }
822
+ }
823
+ // install packages as the final step of init
824
+ try {
825
+ await installPackages(shouldRunPackageManagerInstall, devDepsToInstall);
826
+ } catch (e) {
827
+ // fetching packages could fail due to loss of internet, etc
828
+ // we should let folks know we failed to fetch, but their
829
+ // workers project is still ready to go
830
+ logger.error(e instanceof Error ? e.message : e);
831
+ instructions.push(
832
+ "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
833
+ );
834
+ }
835
+
836
+ // let users know what to do now
837
+ instructions.forEach((instruction) => logger.log(instruction));
328
838
  }
329
839
  );
330
840
 
@@ -335,83 +845,34 @@ export async function main(argv: string[]): Promise<void> {
335
845
  (yargs) => {
336
846
  return yargs.option("env", {
337
847
  describe: "Perform on a specific environment",
848
+ type: "string",
338
849
  });
339
850
  },
340
- () => {
851
+ async (buildArgs) => {
341
852
  // "[DEPRECATED] 🦀 Build your project (if applicable)",
342
- throw new DeprecationError(
343
- "`wrangler build` has been deprecated, please refer to TODO://some/path for alternatives"
344
- );
345
- }
346
- );
347
853
 
348
- // login
349
- wrangler.command(
350
- // this needs scopes as an option?
351
- "login",
352
- false, // we don't need to show this in the menu
353
- // "🔓 Login to Cloudflare",
354
- (yargs) => {
355
- // TODO: This needs some copy editing
356
- // I mean, this entire app does, but this too.
357
- return yargs
358
- .option("scopes-list", {
359
- describe: "list all the available OAuth scopes with descriptions.",
854
+ const envFlag = buildArgs.env ? ` --env=${buildArgs.env}` : "";
855
+ logger.log(
856
+ formatMessage({
857
+ kind: "warning",
858
+ text: "Deprecation: `wrangler build` has been deprecated.",
859
+ notes: [
860
+ {
861
+ text: "Please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#build for more information.",
862
+ },
863
+ {
864
+ text: `Attempting to run \`wrangler publish --dry-run --outdir=dist${envFlag}\` for you instead:`,
865
+ },
866
+ ],
360
867
  })
361
- .option("scopes", {
362
- describe: "allows to choose your set of OAuth scopes.",
363
- array: true,
364
- type: "string",
365
- });
366
-
367
- // TODO: scopes
368
- },
369
- async (args) => {
370
- if (args["scopes-list"]) {
371
- listScopes();
372
- return;
373
- }
374
- if (args.scopes) {
375
- if (args.scopes.length === 0) {
376
- // don't allow no scopes to be passed, that would be weird
377
- listScopes();
378
- return;
379
- }
380
- if (!validateScopeKeys(args.scopes)) {
381
- throw new CommandLineArgsError(
382
- `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
383
- );
384
- }
385
- await login({ scopes: args.scopes });
386
- return;
387
- }
388
- await login();
389
-
390
- // TODO: would be nice if it optionally saved login
391
- // credentials inside node_modules/.cache or something
392
- // this way you could have multiple users on a single machine
393
- }
394
- );
395
-
396
- // logout
397
- wrangler.command(
398
- // this needs scopes as an option?
399
- "logout",
400
- false, // we don't need to show this in the menu
401
- // "🚪 Logout from Cloudflare",
402
- () => {},
403
- async () => {
404
- await logout();
405
- }
406
- );
868
+ );
407
869
 
408
- // whoami
409
- wrangler.command(
410
- "whoami",
411
- "🕵️ Retrieve your user info and test your auth config",
412
- () => {},
413
- async () => {
414
- await whoami();
870
+ await createCLIParser([
871
+ "publish",
872
+ "--dry-run",
873
+ "--outdir=dist",
874
+ ...(buildArgs.env ? ["--env", buildArgs.env] : []),
875
+ ]).parse();
415
876
  }
416
877
  );
417
878
 
@@ -423,43 +884,48 @@ export async function main(argv: string[]): Promise<void> {
423
884
  () => {
424
885
  // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
425
886
  throw new DeprecationError(
426
- "`wrangler config` has been deprecated, please refer to TODO://some/path for alternatives"
887
+ "`wrangler config` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#config for alternatives"
427
888
  );
428
889
  }
429
890
  );
430
891
 
431
892
  // dev
432
893
  wrangler.command(
433
- "dev <filename>",
894
+ "dev [script]",
434
895
  "👂 Start a local server for developing your worker",
435
896
  (yargs) => {
436
897
  return yargs
437
- .positional("filename", {
438
- describe: "entry point",
898
+ .positional("script", {
899
+ describe: "The path to an entry point for your worker",
439
900
  type: "string",
440
- demandOption: true,
441
901
  })
442
902
  .option("name", {
443
- describe: "name of the script",
903
+ describe: "Name of the worker",
444
904
  type: "string",
905
+ requiresArg: true,
445
906
  })
446
907
  .option("format", {
447
908
  choices: ["modules", "service-worker"] as const,
448
909
  describe: "Choose an entry type",
910
+ deprecated: true,
449
911
  })
450
912
  .option("env", {
451
913
  describe: "Perform on a specific environment",
452
914
  type: "string",
453
- // TODO: get choices for the toml file?
915
+ requiresArg: true,
916
+ alias: "e",
454
917
  })
455
918
  .option("compatibility-date", {
456
919
  describe: "Date to use for compatibility checks",
457
920
  type: "string",
921
+ requiresArg: true,
458
922
  })
459
923
  .option("compatibility-flags", {
460
924
  describe: "Flags to use for compatibility checks",
461
- type: "array",
462
925
  alias: "compatibility-flag",
926
+ type: "string",
927
+ requiresArg: true,
928
+ array: true,
463
929
  })
464
930
  .option("latest", {
465
931
  describe: "Use the latest version of the worker runtime",
@@ -467,154 +933,207 @@ export async function main(argv: string[]): Promise<void> {
467
933
  default: true,
468
934
  })
469
935
  .option("ip", {
470
- describe: "IP address to listen on",
936
+ describe: "IP address to listen on, defaults to `localhost`",
471
937
  type: "string",
472
- default: "127.0.0.1",
938
+ requiresArg: true,
473
939
  })
474
940
  .option("port", {
475
- describe: "Port to listen on, defaults to 8787",
941
+ describe: "Port to listen on",
476
942
  type: "number",
477
- default: 8787,
943
+ })
944
+ .option("inspector-port", {
945
+ describe: "Port for devtools to connect to",
946
+ type: "number",
947
+ })
948
+ .option("routes", {
949
+ describe: "Routes to upload",
950
+ alias: "route",
951
+ type: "string",
952
+ requiresArg: true,
953
+ array: true,
478
954
  })
479
955
  .option("host", {
480
956
  type: "string",
957
+ requiresArg: true,
481
958
  describe:
482
959
  "Host to forward requests to, defaults to the zone of project",
483
960
  })
484
961
  .option("local-protocol", {
485
- default: "http",
486
962
  describe: "Protocol to listen to requests on, defaults to http.",
487
- choices: ["http", "https"],
963
+ choices: ["http", "https"] as const,
488
964
  })
489
965
  .option("experimental-public", {
490
966
  describe: "Static assets to be served",
491
967
  type: "string",
968
+ requiresArg: true,
492
969
  })
493
970
  .option("site", {
494
971
  describe: "Root folder of static assets for Workers Sites",
495
972
  type: "string",
973
+ requiresArg: true,
496
974
  })
497
975
  .option("site-include", {
498
976
  describe:
499
977
  "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
500
978
  type: "string",
979
+ requiresArg: true,
501
980
  array: true,
502
981
  })
503
982
  .option("site-exclude", {
504
983
  describe:
505
984
  "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
506
985
  type: "string",
986
+ requiresArg: true,
507
987
  array: true,
508
988
  })
509
989
  .option("upstream-protocol", {
510
- default: "https",
511
990
  describe:
512
991
  "Protocol to forward requests to host on, defaults to https.",
513
- choices: ["http", "https"],
992
+ choices: ["http", "https"] as const,
514
993
  })
515
994
  .option("jsx-factory", {
516
995
  describe: "The function that is called for each JSX element",
517
996
  type: "string",
997
+ requiresArg: true,
518
998
  })
519
999
  .option("jsx-fragment", {
520
1000
  describe: "The function that is called for each JSX fragment",
521
1001
  type: "string",
1002
+ requiresArg: true,
1003
+ })
1004
+ .option("tsconfig", {
1005
+ describe: "Path to a custom tsconfig.json file",
1006
+ type: "string",
1007
+ requiresArg: true,
1008
+ })
1009
+ .option("local", {
1010
+ alias: "l",
1011
+ describe: "Run on my machine",
1012
+ type: "boolean",
1013
+ default: false, // I bet this will a point of contention. We'll revisit it.
1014
+ })
1015
+ .option("minify", {
1016
+ describe: "Minify the script",
1017
+ type: "boolean",
1018
+ })
1019
+ .option("node-compat", {
1020
+ describe: "Enable node.js compatibility",
1021
+ type: "boolean",
522
1022
  })
523
1023
  .option("experimental-enable-local-persistence", {
524
1024
  describe: "Enable persistence for this session (only for local mode)",
525
1025
  type: "boolean",
1026
+ })
1027
+ .option("inspect", {
1028
+ describe: "Enable dev tools",
1029
+ type: "boolean",
1030
+ deprecated: true,
1031
+ })
1032
+ .option("legacy-env", {
1033
+ type: "boolean",
1034
+ describe: "Use legacy environments",
1035
+ hidden: true,
526
1036
  });
527
1037
  },
528
1038
  async (args) => {
529
- const { filename, format } = args;
530
- const config = args.config as Config;
531
-
532
- if (args["experimental-public"]) {
533
- console.warn(
534
- "🚨 The --experimental-public field is experimental and will change in the future."
535
- );
536
- }
1039
+ let watcher: ReturnType<typeof watch> | undefined;
1040
+ try {
1041
+ await printWranglerBanner();
1042
+ const configPath =
1043
+ (args.config as ConfigPath) ||
1044
+ ((args.script &&
1045
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
1046
+ let config = readConfig(configPath, args);
1047
+
1048
+ if (config.configPath) {
1049
+ watcher = watch(config.configPath, {
1050
+ persistent: true,
1051
+ }).on("change", async (_event) => {
1052
+ // TODO: Do we need to handle different `_event` types differently?
1053
+ // e.g. what if the file is deleted, or added?
1054
+ config = readConfig(configPath, args);
1055
+ if (config.configPath) {
1056
+ logger.log(`${path.basename(config.configPath)} changed...`);
1057
+ rerender(await getDevReactElement(config));
1058
+ }
1059
+ });
1060
+ }
537
1061
 
538
- if (args.public) {
539
- throw new Error(
540
- "🚨 The --public field has been renamed to --experimental-public, and will change behaviour in the future."
541
- );
542
- }
1062
+ const entry = await getEntry(args, config, "dev");
543
1063
 
544
- if (config.site?.["entry-point"]) {
545
- console.warn(
546
- "Deprecation notice: The `site.entry-point` config field is no longer used.\n" +
547
- "The entry-point is specified via the command line (e.g. `wrangler dev path/to/script`).\n" +
548
- "Please remove the `site.entry-point` field from the `wrangler.toml` file."
549
- );
550
- }
1064
+ if (config.services && config.services.length > 0) {
1065
+ logger.warn(
1066
+ `This worker is bound to live services: ${config.services
1067
+ .map(
1068
+ (service) =>
1069
+ `${service.binding} (${service.service}${
1070
+ service.environment ? `@${service.environment}` : ""
1071
+ })`
1072
+ )
1073
+ .join(", ")}`
1074
+ );
1075
+ }
551
1076
 
552
- if (!args.local) {
553
- // -- snip, extract --
554
- const loggedIn = await loginOrRefreshIfRequired();
555
- if (!loggedIn) {
556
- // didn't login, let's just quit
557
- console.log("Did not login, quitting...");
558
- return;
1077
+ if (args.inspect) {
1078
+ logger.warn(
1079
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
1080
+ );
559
1081
  }
560
1082
 
561
- if (!config.account_id) {
562
- config.account_id = await getAccountId();
563
- if (!config.account_id) {
564
- throw new Error("No account id found, quitting...");
565
- }
1083
+ if (args["experimental-public"]) {
1084
+ logger.warn(
1085
+ "The --experimental-public field is experimental and will change in the future."
1086
+ );
566
1087
  }
567
- // -- snip, end --
568
- }
569
1088
 
570
- const environments = config.env ?? {};
571
- const envRootObj = args.env ? environments[args.env] || {} : config;
1089
+ if (args.public) {
1090
+ throw new Error(
1091
+ "The --public field has been renamed to --experimental-public, and will change behaviour in the future."
1092
+ );
1093
+ }
572
1094
 
573
- // TODO: this error shouldn't actually happen,
574
- // but we haven't fixed it internally yet
575
- if ("durable_objects" in envRootObj) {
576
- if (!(args.name || config.name)) {
577
- console.warn(
578
- 'A worker with durable objects needs to be named, or it may not work as expected. Add a "name" into wrangler.toml, or pass it in the command line with --name.'
1095
+ const upstreamProtocol =
1096
+ args["upstream-protocol"] || config.dev.upstream_protocol;
1097
+ if (upstreamProtocol === "http") {
1098
+ logger.warn(
1099
+ "Setting upstream-protocol to http is not currently implemented.\n" +
1100
+ "If this is required in your project, please add your use case to the following issue:\n" +
1101
+ "https://github.com/cloudflare/wrangler2/issues/583."
579
1102
  );
580
1103
  }
581
- // TODO: if not already published, publish a draft worker
582
- }
583
1104
 
584
- const { waitUntilExit } = render(
585
- <Dev
586
- name={args.name || config.name}
587
- entry={path.relative(process.cwd(), filename)}
588
- env={args.env}
589
- buildCommand={config.build || {}}
590
- format={format}
591
- initialMode={args.local ? "local" : "remote"}
592
- jsxFactory={args["jsx-factory"] || envRootObj?.jsx_factory}
593
- jsxFragment={args["jsx-fragment"] || envRootObj?.jsx_fragment}
594
- enableLocalPersistence={
595
- args["experimental-enable-local-persistence"] || false
596
- }
597
- accountId={config.account_id}
598
- assetPaths={getAssetPaths(
599
- config,
600
- args.site,
601
- args.siteInclude,
602
- args.siteExclude
603
- )}
604
- port={args.port || config.dev?.port}
605
- public={args["experimental-public"]}
606
- compatibilityDate={
607
- args["compatibility-date"] ||
608
- config.compatibility_date ||
609
- new Date().toISOString().substring(0, 10)
1105
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
1106
+
1107
+ // Compute zone info from the `host` and `route` args and config;
1108
+ let host = args.host || config.dev.host;
1109
+ let zoneId: string | undefined;
1110
+
1111
+ if (!args.local) {
1112
+ if (host) {
1113
+ zoneId = await getZoneIdFromHost(host);
610
1114
  }
611
- compatibilityFlags={
612
- (args["compatibility-flags"] as string[]) ||
613
- config.compatibility_flags
1115
+ const routes = args.routes || config.route || config.routes;
1116
+ if (!zoneId && routes) {
1117
+ const firstRoute = Array.isArray(routes) ? routes[0] : routes;
1118
+ const zone = await getZoneForRoute(firstRoute);
1119
+ if (zone) {
1120
+ zoneId = zone.id;
1121
+ host = zone.host;
1122
+ }
614
1123
  }
615
- usageModel={config.usage_model}
616
- bindings={{
617
- kv_namespaces: envRootObj.kv_namespaces?.map(
1124
+ }
1125
+
1126
+ const nodeCompat = args.nodeCompat ?? config.node_compat;
1127
+ if (nodeCompat) {
1128
+ logger.warn(
1129
+ "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."
1130
+ );
1131
+ }
1132
+
1133
+ // eslint-disable-next-line no-inner-declarations
1134
+ async function getBindings(configParam: Config) {
1135
+ return {
1136
+ kv_namespaces: configParam.kv_namespaces?.map(
618
1137
  ({ binding, preview_id, id: _id }) => {
619
1138
  // In `dev`, we make folks use a separate kv namespace called
620
1139
  // `preview_id` instead of `id` so that they don't
@@ -635,13 +1154,111 @@ export async function main(argv: string[]): Promise<void> {
635
1154
  };
636
1155
  }
637
1156
  ),
638
- vars: envRootObj.vars,
639
- durable_objects: envRootObj.durable_objects,
640
- services: envRootObj.experimental_services,
641
- }}
642
- />
643
- );
644
- await waitUntilExit();
1157
+ // Use a copy of combinedVars since we're modifying it later
1158
+ vars: getVarsForDev(configParam),
1159
+ wasm_modules: configParam.wasm_modules,
1160
+ text_blobs: configParam.text_blobs,
1161
+ data_blobs: configParam.data_blobs,
1162
+ durable_objects: configParam.durable_objects,
1163
+ r2_buckets: configParam.r2_buckets?.map(
1164
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
1165
+ // same idea as kv namespace preview id,
1166
+ // same copy-on-write TODO
1167
+ if (!preview_bucket_name) {
1168
+ throw new Error(
1169
+ `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
1170
+ );
1171
+ }
1172
+ return {
1173
+ binding,
1174
+ bucket_name: preview_bucket_name,
1175
+ };
1176
+ }
1177
+ ),
1178
+ services: configParam.services,
1179
+ unsafe: configParam.unsafe?.bindings,
1180
+ };
1181
+ }
1182
+
1183
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
1184
+ const getInspectorPort = memoizeGetPort(9229);
1185
+
1186
+ // eslint-disable-next-line no-inner-declarations
1187
+ async function getDevReactElement(configParam: Config) {
1188
+ // now log all available bindings into the terminal
1189
+ const bindings = await getBindings(configParam);
1190
+ // mask anything that was overridden in .dev.vars
1191
+ // so that we don't log potential secrets into the terminal
1192
+ const maskedVars = { ...bindings.vars };
1193
+ for (const key of Object.keys(maskedVars)) {
1194
+ if (maskedVars[key] !== configParam.vars[key]) {
1195
+ // This means it was overridden in .dev.vars
1196
+ // so let's mask it
1197
+ maskedVars[key] = "(hidden)";
1198
+ }
1199
+ }
1200
+
1201
+ printBindings({
1202
+ ...bindings,
1203
+ vars: maskedVars,
1204
+ });
1205
+
1206
+ return (
1207
+ <Dev
1208
+ name={getScriptName(args, config)}
1209
+ entry={entry}
1210
+ env={args.env}
1211
+ zone={zoneId}
1212
+ host={host}
1213
+ rules={getRules(config)}
1214
+ legacyEnv={isLegacyEnv(config)}
1215
+ minify={args.minify ?? config.minify}
1216
+ nodeCompat={nodeCompat}
1217
+ build={config.build || {}}
1218
+ initialMode={args.local ? "local" : "remote"}
1219
+ jsxFactory={args["jsx-factory"] || config.jsx_factory}
1220
+ jsxFragment={args["jsx-fragment"] || config.jsx_fragment}
1221
+ tsconfig={args.tsconfig ?? config.tsconfig}
1222
+ upstreamProtocol={upstreamProtocol}
1223
+ localProtocol={
1224
+ args["local-protocol"] || config.dev.local_protocol
1225
+ }
1226
+ enableLocalPersistence={
1227
+ args["experimental-enable-local-persistence"] || false
1228
+ }
1229
+ accountId={config.account_id}
1230
+ assetPaths={getAssetPaths(
1231
+ config,
1232
+ args.site,
1233
+ args.siteInclude,
1234
+ args.siteExclude
1235
+ )}
1236
+ port={args.port || config.dev.port || (await getLocalPort())}
1237
+ ip={args.ip || config.dev.ip}
1238
+ inspectorPort={
1239
+ args["inspector-port"] ?? (await getInspectorPort())
1240
+ }
1241
+ public={args["experimental-public"]}
1242
+ compatibilityDate={getDevCompatibilityDate(
1243
+ config,
1244
+ args["compatibility-date"]
1245
+ )}
1246
+ compatibilityFlags={
1247
+ args["compatibility-flags"] || config.compatibility_flags
1248
+ }
1249
+ usageModel={config.usage_model}
1250
+ bindings={bindings}
1251
+ crons={config.triggers.crons}
1252
+ />
1253
+ );
1254
+ }
1255
+ const { waitUntilExit, rerender } = render(
1256
+ await getDevReactElement(config)
1257
+ );
1258
+ await waitUntilExit();
1259
+ } finally {
1260
+ await watcher?.close();
1261
+ }
645
1262
  }
646
1263
  );
647
1264
 
@@ -653,24 +1270,41 @@ export async function main(argv: string[]): Promise<void> {
653
1270
  return yargs
654
1271
  .option("env", {
655
1272
  type: "string",
1273
+ requiresArg: true,
656
1274
  describe: "Perform on a specific environment",
1275
+ alias: "e",
657
1276
  })
658
1277
  .positional("script", {
659
- describe: "script to upload",
1278
+ describe: "The path to an entry point for your worker",
660
1279
  type: "string",
1280
+ requiresArg: true,
661
1281
  })
662
1282
  .option("name", {
663
- describe: "name to use when uploading",
1283
+ describe: "Name of the worker",
664
1284
  type: "string",
1285
+ requiresArg: true,
1286
+ })
1287
+ .option("outdir", {
1288
+ describe: "Output directory for the bundled worker",
1289
+ type: "string",
1290
+ requiresArg: true,
1291
+ })
1292
+ .option("format", {
1293
+ choices: ["modules", "service-worker"] as const,
1294
+ describe: "Choose an entry type",
1295
+ deprecated: true,
665
1296
  })
666
1297
  .option("compatibility-date", {
667
1298
  describe: "Date to use for compatibility checks",
668
1299
  type: "string",
1300
+ requiresArg: true,
669
1301
  })
670
1302
  .option("compatibility-flags", {
671
1303
  describe: "Flags to use for compatibility checks",
672
- type: "array",
673
1304
  alias: "compatibility-flag",
1305
+ type: "string",
1306
+ requiresArg: true,
1307
+ array: true,
674
1308
  })
675
1309
  .option("latest", {
676
1310
  describe: "Use the latest version of the worker runtime",
@@ -680,91 +1314,100 @@ export async function main(argv: string[]): Promise<void> {
680
1314
  .option("experimental-public", {
681
1315
  describe: "Static assets to be served",
682
1316
  type: "string",
1317
+ requiresArg: true,
683
1318
  })
684
1319
  .option("site", {
685
1320
  describe: "Root folder of static assets for Workers Sites",
686
1321
  type: "string",
1322
+ requiresArg: true,
687
1323
  })
688
1324
  .option("site-include", {
689
1325
  describe:
690
1326
  "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
691
1327
  type: "string",
1328
+ requiresArg: true,
692
1329
  array: true,
693
1330
  })
694
1331
  .option("site-exclude", {
695
1332
  describe:
696
1333
  "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
697
1334
  type: "string",
1335
+ requiresArg: true,
698
1336
  array: true,
699
1337
  })
700
1338
  .option("triggers", {
701
1339
  describe: "cron schedules to attach",
702
1340
  alias: ["schedule", "schedules"],
703
- type: "array",
1341
+ type: "string",
1342
+ requiresArg: true,
1343
+ array: true,
704
1344
  })
705
1345
  .option("routes", {
706
- describe: "routes to upload",
1346
+ describe: "Routes to upload",
707
1347
  alias: "route",
708
- type: "array",
709
- })
710
- .option("services", {
711
- describe: "experimental support for services",
712
- type: "boolean",
713
- default: "false",
714
- hidden: true,
1348
+ type: "string",
1349
+ requiresArg: true,
1350
+ array: true,
715
1351
  })
716
1352
  .option("jsx-factory", {
717
1353
  describe: "The function that is called for each JSX element",
718
1354
  type: "string",
1355
+ requiresArg: true,
719
1356
  })
720
1357
  .option("jsx-fragment", {
721
1358
  describe: "The function that is called for each JSX fragment",
722
1359
  type: "string",
1360
+ requiresArg: true,
1361
+ })
1362
+ .option("tsconfig", {
1363
+ describe: "Path to a custom tsconfig.json file",
1364
+ type: "string",
1365
+ requiresArg: true,
1366
+ })
1367
+ .option("minify", {
1368
+ describe: "Minify the script",
1369
+ type: "boolean",
1370
+ })
1371
+ .option("node-compat", {
1372
+ describe: "Enable node.js compatibility",
1373
+ type: "boolean",
1374
+ })
1375
+ .option("dry-run", {
1376
+ describe: "Don't actually publish",
1377
+ type: "boolean",
1378
+ })
1379
+ .option("legacy-env", {
1380
+ type: "boolean",
1381
+ describe: "Use legacy environments",
1382
+ hidden: true,
723
1383
  });
724
1384
  },
725
1385
  async (args) => {
726
- if (args.local) {
727
- throw new NotImplementedError(
728
- "🚫 Local publishing is not yet supported"
729
- );
730
- }
731
-
1386
+ await printWranglerBanner();
732
1387
  if (args["experimental-public"]) {
733
- console.warn(
734
- "🚨 The --experimental-public field is experimental and will change in the future."
1388
+ logger.warn(
1389
+ "The --experimental-public field is experimental and will change in the future."
735
1390
  );
736
1391
  }
737
1392
  if (args.public) {
738
1393
  throw new Error(
739
- "🚨 The --public field has been renamed to --experimental-public, and will change behaviour in the future."
1394
+ "The --public field has been renamed to --experimental-public, and will change behaviour in the future."
740
1395
  );
741
1396
  }
742
1397
 
743
- const config = args.config as Config;
1398
+ const configPath =
1399
+ (args.config as ConfigPath) ||
1400
+ (args.script && findWranglerToml(path.dirname(args.script)));
1401
+ const config = readConfig(configPath, args);
1402
+ const entry = await getEntry(args, config, "publish");
744
1403
 
745
1404
  if (args.latest) {
746
- console.warn(
747
- "⚠️ Using the latest version of the Workers runtime. To silence this warning, please choose a specific version of the runtime with --compatibility-date, or add a compatibility_date to your wrangler.toml.\n"
1405
+ logger.warn(
1406
+ "Using the latest version of the Workers runtime. To silence this warning, please choose a specific version of the runtime with --compatibility-date, or add a compatibility_date to your wrangler.toml.\n"
748
1407
  );
749
1408
  }
750
1409
 
751
- if (!args.local) {
752
- // -- snip, extract --
753
- const loggedIn = await loginOrRefreshIfRequired();
754
- if (!loggedIn) {
755
- // didn't login, let's just quit
756
- console.log("Did not login, quitting...");
757
- return;
758
- }
759
-
760
- if (!config.account_id) {
761
- config.account_id = await getAccountId();
762
- if (!config.account_id) {
763
- throw new Error("No account id found, quitting...");
764
- }
765
- }
766
- // -- snip, end --
767
- }
1410
+ const accountId = args.dryRun ? undefined : await requireAuth(config);
768
1411
 
769
1412
  const assetPaths = getAssetPaths(
770
1413
  config,
@@ -772,23 +1415,30 @@ export async function main(argv: string[]): Promise<void> {
772
1415
  args.siteInclude,
773
1416
  args.siteExclude
774
1417
  );
1418
+
775
1419
  await publish({
776
- config: args.config as Config,
777
- name: args.name,
778
- script: args.script,
1420
+ config,
1421
+ accountId,
1422
+ name: getScriptName(args, config),
1423
+ rules: getRules(config),
1424
+ entry,
779
1425
  env: args.env,
780
1426
  compatibilityDate: args.latest
781
1427
  ? new Date().toISOString().substring(0, 10)
782
1428
  : args["compatibility-date"],
783
- compatibilityFlags: args["compatibility-flags"] as string[],
1429
+ compatibilityFlags: args["compatibility-flags"],
784
1430
  triggers: args.triggers,
785
1431
  jsxFactory: args["jsx-factory"],
786
1432
  jsxFragment: args["jsx-fragment"],
1433
+ tsconfig: args.tsconfig,
787
1434
  routes: args.routes,
788
1435
  assetPaths,
789
- format: undefined, // TODO: add args for this
790
- legacyEnv: undefined, // TODO: get this from somewhere... config?
1436
+ legacyEnv: isLegacyEnv(config),
1437
+ minify: args.minify,
1438
+ nodeCompat: args.nodeCompat,
791
1439
  experimentalPublic: args["experimental-public"] !== undefined,
1440
+ outDir: args.outdir,
1441
+ dryRun: args.dryRun,
792
1442
  });
793
1443
  }
794
1444
  );
@@ -796,119 +1446,147 @@ export async function main(argv: string[]): Promise<void> {
796
1446
  // tail
797
1447
  wrangler.command(
798
1448
  "tail [name]",
799
- "🦚 Starts a log tailing session for a deployed Worker.",
1449
+ "🦚 Starts a log tailing session for a published Worker.",
800
1450
  (yargs) => {
801
- return (
802
- yargs
803
- .positional("name", {
804
- describe: "name of the worker",
805
- type: "string",
806
- })
807
- // TODO: auto-detect if this should be json or pretty based on atty
808
- .option("format", {
809
- default: "json",
810
- choices: ["json", "pretty"],
811
- describe: "The format of log entries",
812
- })
813
- .option("status", {
814
- choices: ["ok", "error", "canceled"],
815
- describe: "Filter by invocation status",
816
- })
817
- .option("header", {
818
- type: "string",
819
- describe: "Filter by HTTP header",
820
- })
821
- .option("method", {
822
- type: "string",
823
- describe: "Filter by HTTP method",
824
- })
825
- .option("sampling-rate", {
826
- type: "number",
827
- describe: "Adds a percentage of requests to log sampling rate",
828
- })
829
- .option("search", {
830
- type: "string",
831
- describe: "Filter by a text match in console.log messages",
832
- })
833
- .option("env", {
834
- type: "string",
835
- describe: "Perform on a specific environment",
836
- })
837
- );
838
- // TODO: filter by client ip, which can be 'self' or an ip address
1451
+ return yargs
1452
+ .positional("name", {
1453
+ describe: "Name of the worker",
1454
+ type: "string",
1455
+ })
1456
+ .option("format", {
1457
+ default: process.stdout.isTTY ? "pretty" : "json",
1458
+ choices: ["json", "pretty"],
1459
+ describe: "The format of log entries",
1460
+ })
1461
+ .option("status", {
1462
+ choices: ["ok", "error", "canceled"],
1463
+ describe: "Filter by invocation status",
1464
+ array: true,
1465
+ })
1466
+ .option("header", {
1467
+ type: "string",
1468
+ requiresArg: true,
1469
+ describe: "Filter by HTTP header",
1470
+ })
1471
+ .option("method", {
1472
+ type: "string",
1473
+ requiresArg: true,
1474
+ describe: "Filter by HTTP method",
1475
+ array: true,
1476
+ })
1477
+ .option("sampling-rate", {
1478
+ type: "number",
1479
+ describe: "Adds a percentage of requests to log sampling rate",
1480
+ })
1481
+ .option("search", {
1482
+ type: "string",
1483
+ requiresArg: true,
1484
+ describe: "Filter by a text match in console.log messages",
1485
+ })
1486
+ .option("ip", {
1487
+ type: "string",
1488
+ requiresArg: true,
1489
+ describe:
1490
+ 'Filter by the IP address the request originates from. Use "self" to filter for your own IP',
1491
+ array: true,
1492
+ })
1493
+ .option("env", {
1494
+ type: "string",
1495
+ requiresArg: true,
1496
+ describe: "Perform on a specific environment",
1497
+ alias: "e",
1498
+ })
1499
+ .option("debug", {
1500
+ type: "boolean",
1501
+ hidden: true,
1502
+ default: false,
1503
+ describe:
1504
+ "If a log would have been filtered out, send it through anyway alongside the filter which would have blocked it.",
1505
+ })
1506
+ .option("legacy-env", {
1507
+ type: "boolean",
1508
+ describe: "Use legacy environments",
1509
+ hidden: true,
1510
+ });
839
1511
  },
840
1512
  async (args) => {
841
- if (args.local) {
842
- throw new NotImplementedError(
843
- `local mode is not yet supported for this command`
844
- );
1513
+ if (args.format === "pretty") {
1514
+ await printWranglerBanner();
845
1515
  }
1516
+ const config = readConfig(args.config as ConfigPath, args);
846
1517
 
847
- const config = args.config as Config;
1518
+ const scriptName = getLegacyScriptName(args, config);
848
1519
 
849
- if (!(args.name || config.name)) {
1520
+ if (!scriptName) {
850
1521
  throw new Error("Missing script name");
851
1522
  }
852
- const scriptName = `${args.name || config.name}${
853
- args.env ? `-${args.env}` : ""
854
- }`;
855
1523
 
856
- // -- snip, extract --
857
- const loggedIn = await loginOrRefreshIfRequired();
858
- if (!loggedIn) {
859
- // didn't login, let's just quit
860
- console.log("Did not login, quitting...");
861
- return;
862
- }
863
-
864
- if (!config.account_id) {
865
- config.account_id = await getAccountId();
866
- if (!config.account_id) {
867
- throw new Error("No account id found, quitting...");
868
- }
869
- }
870
- // -- snip, end --
1524
+ const accountId = await requireAuth(config);
871
1525
 
872
- const accountId = config.account_id;
873
-
874
- const filters = {
875
- status: args.status as "ok" | "error" | "canceled",
1526
+ const cliFilters: TailCLIFilters = {
1527
+ status: args.status as ("ok" | "error" | "canceled")[] | undefined,
876
1528
  header: args.header,
877
1529
  method: args.method,
878
- "sampling-rate": args["sampling-rate"],
1530
+ samplingRate: args["sampling-rate"],
879
1531
  search: args.search,
1532
+ clientIp: args.ip,
880
1533
  };
881
1534
 
882
- const { tail, expiration, /* sendHeartbeat, */ deleteTail } =
883
- await createTail(accountId, scriptName, filters);
1535
+ const filters = translateCLICommandToFilterMessage(
1536
+ cliFilters,
1537
+ args.debug
1538
+ );
884
1539
 
885
- console.log(
886
- `successfully created tail, expires at ${expiration.toLocaleString()}`
1540
+ const { tail, expiration, deleteTail } = await createTail(
1541
+ accountId,
1542
+ scriptName,
1543
+ filters,
1544
+ !isLegacyEnv(config) ? args.env : undefined
887
1545
  );
888
1546
 
1547
+ const scriptDisplayName = `${scriptName}${
1548
+ args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1549
+ }`;
1550
+
1551
+ if (args.format === "pretty") {
1552
+ logger.log(
1553
+ `Successfully created tail, expires at ${expiration.toLocaleString()}`
1554
+ );
1555
+ }
1556
+
889
1557
  onExit(async () => {
890
1558
  tail.terminate();
891
1559
  await deleteTail();
892
1560
  });
893
1561
 
894
- tail.on("message", (data) => {
895
- console.log(JSON.stringify(JSON.parse(data.toString()), null, " "));
896
- });
1562
+ const printLog: (data: RawData) => void =
1563
+ args.format === "pretty" ? prettyPrintLogs : jsonPrintLogs;
1564
+
1565
+ tail.on("message", printLog);
897
1566
 
898
1567
  while (tail.readyState !== tail.OPEN) {
899
1568
  switch (tail.readyState) {
900
1569
  case tail.CONNECTING:
901
- await setTimeout(1000);
1570
+ await setTimeout(100);
902
1571
  break;
903
1572
  case tail.CLOSING:
904
- await setTimeout(1000);
1573
+ await setTimeout(100);
905
1574
  break;
906
1575
  case tail.CLOSED:
907
- process.exit(1);
1576
+ throw new Error(
1577
+ `Connection to ${scriptDisplayName} closed unexpectedly.`
1578
+ );
908
1579
  }
909
1580
  }
910
1581
 
911
- console.log(`Connected to ${scriptName}, waiting for logs...`);
1582
+ if (args.format === "pretty") {
1583
+ logger.log(`Connected to ${scriptDisplayName}, waiting for logs...`);
1584
+ }
1585
+
1586
+ tail.on("close", async () => {
1587
+ tail.terminate();
1588
+ await deleteTail();
1589
+ });
912
1590
  }
913
1591
  );
914
1592
 
@@ -919,17 +1597,16 @@ export async function main(argv: string[]): Promise<void> {
919
1597
  (yargs) => {
920
1598
  return yargs
921
1599
  .positional("method", {
1600
+ type: "string",
922
1601
  describe: "Type of request to preview your worker",
923
- choices: ["GET", "POST"],
924
- default: ["GET"],
925
1602
  })
926
1603
  .positional("body", {
927
1604
  type: "string",
928
1605
  describe: "Body string to post to your preview worker request.",
929
- default: "Null",
930
1606
  })
931
1607
  .option("env", {
932
1608
  type: "string",
1609
+ requiresArg: true,
933
1610
  describe: "Perform on a specific environment",
934
1611
  })
935
1612
  .option("watch", {
@@ -938,15 +1615,110 @@ export async function main(argv: string[]): Promise<void> {
938
1615
  type: "boolean",
939
1616
  });
940
1617
  },
941
- () => {
942
- // "🔬 [DEPRECATED] Preview your code temporarily on https://cloudflareworkers.com"
943
- throw new DeprecationError(
944
- "`wrangler preview` has been deprecated, please refer to TODO://some/path for alternatives"
1618
+ async (args) => {
1619
+ if (args.method || args.body) {
1620
+ throw new DeprecationError(
1621
+ "The `wrangler preview` command has been deprecated.\n" +
1622
+ "Try using `wrangler dev` to to try out a worker during development.\n"
1623
+ );
1624
+ }
1625
+
1626
+ // Delegate to `wrangler dev`
1627
+ logger.warn(
1628
+ "***************************************************\n" +
1629
+ "The `wrangler preview` command has been deprecated.\n" +
1630
+ "Attempting to run `wrangler dev` instead.\n" +
1631
+ "***************************************************\n"
945
1632
  );
1633
+
1634
+ const config = readConfig(args.config as ConfigPath, args);
1635
+ const entry = await getEntry({}, config, "dev");
1636
+
1637
+ const accountId = await requireAuth(config);
1638
+
1639
+ const { waitUntilExit } = render(
1640
+ <Dev
1641
+ name={config.name}
1642
+ entry={entry}
1643
+ rules={getRules(config)}
1644
+ env={args.env}
1645
+ zone={undefined}
1646
+ host={undefined}
1647
+ legacyEnv={isLegacyEnv(config)}
1648
+ build={config.build || {}}
1649
+ minify={undefined}
1650
+ nodeCompat={config.node_compat}
1651
+ initialMode={args.local ? "local" : "remote"}
1652
+ jsxFactory={config.jsx_factory}
1653
+ jsxFragment={config.jsx_fragment}
1654
+ tsconfig={config.tsconfig}
1655
+ upstreamProtocol={config.dev.upstream_protocol}
1656
+ localProtocol={config.dev.local_protocol}
1657
+ enableLocalPersistence={false}
1658
+ accountId={accountId}
1659
+ assetPaths={undefined}
1660
+ port={
1661
+ config.dev.port || (await getPort({ port: DEFAULT_LOCAL_PORT }))
1662
+ }
1663
+ ip={config.dev.ip}
1664
+ public={undefined}
1665
+ compatibilityDate={getDevCompatibilityDate(config)}
1666
+ compatibilityFlags={config.compatibility_flags}
1667
+ usageModel={config.usage_model}
1668
+ bindings={{
1669
+ kv_namespaces: config.kv_namespaces?.map(
1670
+ ({ binding, preview_id, id: _id }) => {
1671
+ // In `dev`, we make folks use a separate kv namespace called
1672
+ // `preview_id` instead of `id` so that they don't
1673
+ // break production data. So here we check that a `preview_id`
1674
+ // has actually been configured.
1675
+ // This whole block of code will be obsoleted in the future
1676
+ // when we have copy-on-write for previews on edge workers.
1677
+ if (!preview_id) {
1678
+ // TODO: This error has to be a _lot_ better, ideally just asking
1679
+ // to create a preview namespace for the user automatically
1680
+ throw new Error(
1681
+ `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
1682
+ ); // Ugh, I really don't like this message very much
1683
+ }
1684
+ return {
1685
+ binding,
1686
+ id: preview_id,
1687
+ };
1688
+ }
1689
+ ),
1690
+ vars: config.vars,
1691
+ wasm_modules: config.wasm_modules,
1692
+ text_blobs: config.text_blobs,
1693
+ data_blobs: config.data_blobs,
1694
+ durable_objects: config.durable_objects,
1695
+ r2_buckets: config.r2_buckets?.map(
1696
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
1697
+ // same idea as kv namespace preview id,
1698
+ // same copy-on-write TODO
1699
+ if (!preview_bucket_name) {
1700
+ throw new Error(
1701
+ `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
1702
+ );
1703
+ }
1704
+ return {
1705
+ binding,
1706
+ bucket_name: preview_bucket_name,
1707
+ };
1708
+ }
1709
+ ),
1710
+ services: config.services,
1711
+ unsafe: config.unsafe?.bindings,
1712
+ }}
1713
+ crons={config.triggers.crons}
1714
+ inspectorPort={await getPort({ port: 9229 })}
1715
+ />
1716
+ );
1717
+ await waitUntilExit();
946
1718
  }
947
1719
  );
948
1720
 
949
- // route
1721
+ // [DEPRECATED] route
950
1722
  wrangler.command(
951
1723
  "route",
952
1724
  false, // I think we want to hide this command
@@ -955,35 +1727,39 @@ export async function main(argv: string[]): Promise<void> {
955
1727
  return routeYargs
956
1728
  .command(
957
1729
  "list",
958
- "List a route associated with a zone",
1730
+ "List the routes associated with a zone",
959
1731
  (yargs) => {
960
1732
  return yargs
961
1733
  .option("env", {
962
1734
  type: "string",
1735
+ requiresArg: true,
963
1736
  describe: "Perform on a specific environment",
964
1737
  })
965
1738
  .option("zone", {
966
1739
  type: "string",
967
- describe: "zone id",
1740
+ requiresArg: true,
1741
+ describe: "Zone id",
968
1742
  })
969
1743
  .positional("zone", {
970
- describe: "zone id",
1744
+ describe: "Zone id",
971
1745
  type: "string",
972
1746
  });
973
1747
  },
974
- async (args) => {
975
- console.log(":route list", args);
976
- // TODO: use environment (current wrangler doesn't do so?)
977
- const zone = args.zone || (args.config as Config).zone_id;
978
- if (!zone) {
979
- throw new Error("missing zone id");
980
- }
981
-
982
- console.log(await fetchResult(`/zones/${zone}/workers/routes`));
1748
+ () => {
1749
+ // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1750
+ const deprecationNotice =
1751
+ "`wrangler route list` has been deprecated.";
1752
+ const futureRoutes =
1753
+ "Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.";
1754
+ const presentRoutes =
1755
+ "Refer to the Cloudflare Dashboard to see the routes this worker is currently running on.";
1756
+ throw new DeprecationError(
1757
+ `${deprecationNotice}\n${futureRoutes}\n${presentRoutes}`
1758
+ );
983
1759
  }
984
1760
  )
985
1761
  .command(
986
- "delete <id>",
1762
+ "delete [id]",
987
1763
  "Delete a route associated with a zone",
988
1764
  (yargs) => {
989
1765
  return yargs
@@ -993,28 +1769,31 @@ export async function main(argv: string[]): Promise<void> {
993
1769
  })
994
1770
  .option("zone", {
995
1771
  type: "string",
1772
+ requiresArg: true,
996
1773
  describe: "zone id",
997
1774
  })
998
1775
  .option("env", {
999
1776
  type: "string",
1777
+ requiresArg: true,
1000
1778
  describe: "Perform on a specific environment",
1001
1779
  });
1002
1780
  },
1003
- async (args) => {
1004
- console.log(":route delete", args);
1005
- // TODO: use environment (current wrangler doesn't do so?)
1006
- const zone = args.zone || (args.config as Config).zone_id;
1007
- if (!zone) {
1008
- throw new Error("missing zone id");
1009
- }
1010
-
1011
- console.log(
1012
- await fetchResult(`/zones/${zone}/workers/routes/${args.id}`, {
1013
- method: "DELETE",
1014
- })
1015
- );
1781
+ () => {
1782
+ // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1783
+ const deprecationNotice =
1784
+ "`wrangler route delete` has been deprecated.";
1785
+ const shouldDo =
1786
+ "Remove the unwanted route(s) from wrangler.toml and run `wrangler publish` to remove your worker from those routes.";
1787
+ throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1016
1788
  }
1017
1789
  );
1790
+ },
1791
+ () => {
1792
+ // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1793
+ const deprecationNotice = "`wrangler route` has been deprecated.";
1794
+ const shouldDo =
1795
+ "Please use wrangler.toml and/or `wrangler publish --routes` to modify routes";
1796
+ throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1018
1797
  }
1019
1798
  );
1020
1799
 
@@ -1028,7 +1807,7 @@ export async function main(argv: string[]): Promise<void> {
1028
1807
  },
1029
1808
  () => {
1030
1809
  throw new DeprecationError(
1031
- "`wrangler subdomain` has been deprecated, please refer to TODO://some/path for alternatives"
1810
+ "`wrangler subdomain` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#subdomain for alternatives"
1032
1811
  );
1033
1812
  }
1034
1813
  );
@@ -1039,190 +1818,190 @@ export async function main(argv: string[]): Promise<void> {
1039
1818
  "🤫 Generate a secret that can be referenced in the worker script",
1040
1819
  (secretYargs) => {
1041
1820
  return secretYargs
1821
+ .command(subHelp)
1822
+ .option("legacy-env", {
1823
+ type: "boolean",
1824
+ describe: "Use legacy environments",
1825
+ hidden: true,
1826
+ })
1042
1827
  .command(
1043
1828
  "put <key>",
1044
1829
  "Create or update a secret variable for a script",
1045
1830
  (yargs) => {
1046
1831
  return yargs
1047
1832
  .positional("key", {
1048
- describe: "The variable name to be accessible in the script.",
1833
+ describe: "The variable name to be accessible in the script",
1049
1834
  type: "string",
1050
1835
  })
1051
1836
  .option("name", {
1052
- describe: "name of the script",
1837
+ describe: "Name of the worker",
1053
1838
  type: "string",
1839
+ requiresArg: true,
1054
1840
  })
1055
1841
  .option("env", {
1056
1842
  type: "string",
1843
+ requiresArg: true,
1057
1844
  describe:
1058
- "Binds the secret to the script of the specific environment.",
1845
+ "Binds the secret to the Worker of the specific environment",
1846
+ alias: "e",
1059
1847
  });
1060
1848
  },
1061
1849
  async (args) => {
1062
- const config = args.config as Config;
1850
+ await printWranglerBanner();
1851
+ const config = readConfig(args.config as ConfigPath, args);
1063
1852
 
1064
- // TODO: use environment (how does current wrangler do it?)
1065
- const scriptName = args.name || config.name;
1853
+ const scriptName = getLegacyScriptName(args, config);
1066
1854
  if (!scriptName) {
1067
1855
  throw new Error("Missing script name");
1068
1856
  }
1069
1857
 
1070
- if (args.local) {
1071
- console.warn("`wrangler secret put` is a no-op in --local mode");
1072
- }
1073
-
1074
- if (!args.local) {
1075
- // -- snip, extract --
1076
- const loggedIn = await loginOrRefreshIfRequired();
1077
- if (!loggedIn) {
1078
- // didn't login, let's just quit
1079
- console.log("Did not login, quitting...");
1080
- return;
1081
- }
1858
+ const accountId = await requireAuth(config);
1082
1859
 
1083
- if (!config.account_id) {
1084
- config.account_id = await getAccountId();
1085
- if (!config.account_id) {
1086
- throw new Error("No account id found, quitting...");
1087
- }
1088
- }
1089
- // -- snip, end --
1090
- }
1860
+ const isInteractive = process.stdin.isTTY;
1861
+ const secretValue = trimTrailingWhitespace(
1862
+ isInteractive
1863
+ ? await prompt("Enter a secret value:", "password")
1864
+ : await readFromStdin()
1865
+ );
1091
1866
 
1092
- const secretValue = await prompt(
1093
- "Enter a secret value:",
1094
- "password"
1867
+ logger.log(
1868
+ `🌀 Creating the secret for script ${scriptName} ${
1869
+ args.env && !isLegacyEnv(config) ? `(${args.env})` : ""
1870
+ }`
1095
1871
  );
1096
1872
 
1097
- if (args.local) {
1098
- return;
1873
+ async function submitSecret() {
1874
+ const url =
1875
+ !args.env || isLegacyEnv(config)
1876
+ ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1877
+ : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1878
+
1879
+ return await fetchResult(url, {
1880
+ method: "PUT",
1881
+ headers: { "Content-Type": "application/json" },
1882
+ body: JSON.stringify({
1883
+ name: args.key,
1884
+ text: secretValue,
1885
+ type: "secret_text",
1886
+ }),
1887
+ });
1099
1888
  }
1100
1889
 
1101
- console.log(`🌀 Creating the secret for script ${scriptName}`);
1102
-
1103
- async function submitSecret() {
1104
- return await fetchResult(
1105
- `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/`,
1890
+ const createDraftWorker = async () => {
1891
+ // TODO: log a warning
1892
+ await fetchResult(
1893
+ !isLegacyEnv(config) && args.env
1894
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}`
1895
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`,
1106
1896
  {
1107
1897
  method: "PUT",
1108
- headers: { "Content-Type": "application/json" },
1109
- body: JSON.stringify({
1110
- name: args.key,
1111
- text: secretValue,
1112
- type: "secret_text",
1898
+ body: createWorkerUploadForm({
1899
+ name: scriptName,
1900
+ main: {
1901
+ name: scriptName,
1902
+ content: `export default { fetch() {} }`,
1903
+ type: "esm",
1904
+ },
1905
+ bindings: {
1906
+ kv_namespaces: [],
1907
+ vars: {},
1908
+ durable_objects: { bindings: [] },
1909
+ r2_buckets: [],
1910
+ services: [],
1911
+ wasm_modules: {},
1912
+ text_blobs: {},
1913
+ data_blobs: {},
1914
+ unsafe: [],
1915
+ },
1916
+ modules: [],
1917
+ migrations: undefined,
1918
+ compatibility_date: undefined,
1919
+ compatibility_flags: undefined,
1920
+ usage_model: undefined,
1113
1921
  }),
1114
1922
  }
1115
1923
  );
1924
+ };
1925
+
1926
+ function isMissingWorkerError(e: unknown): e is { code: 10007 } {
1927
+ return (
1928
+ typeof e === "object" &&
1929
+ e !== null &&
1930
+ (e as { code: number }).code === 10007
1931
+ );
1116
1932
  }
1117
1933
 
1118
1934
  try {
1119
1935
  await submitSecret();
1120
1936
  } catch (e) {
1121
- if (e.code === 10007) {
1122
- // upload a draft worker
1123
- await fetchResult(
1124
- `/accounts/${config.account_id}/workers/scripts/${scriptName}`,
1125
- {
1126
- method: "PUT",
1127
- body: toFormData({
1128
- name: scriptName,
1129
- main: {
1130
- name: scriptName,
1131
- content: `export default { fetch() {} }`,
1132
- type: "esm",
1133
- },
1134
- bindings: {
1135
- kv_namespaces: [],
1136
- vars: {},
1137
- durable_objects: { bindings: [] },
1138
- },
1139
- modules: [],
1140
- migrations: undefined,
1141
- compatibility_date: undefined,
1142
- compatibility_flags: undefined,
1143
- usage_model: undefined,
1144
- }),
1145
- }
1146
- );
1147
-
1148
- // and then try again
1937
+ if (isMissingWorkerError(e)) {
1938
+ // create a draft worker and try again
1939
+ await createDraftWorker();
1149
1940
  await submitSecret();
1150
1941
  // TODO: delete the draft worker if this failed too?
1942
+ } else {
1943
+ throw e;
1151
1944
  }
1152
1945
  }
1153
- console.log(`✨ Success! Uploaded secret ${args.key}`);
1946
+
1947
+ logger.log(`✨ Success! Uploaded secret ${args.key}`);
1154
1948
  }
1155
1949
  )
1156
1950
  .command(
1157
1951
  "delete <key>",
1158
1952
  "Delete a secret variable from a script",
1159
- (yargs) => {
1953
+ async (yargs) => {
1954
+ await printWranglerBanner();
1160
1955
  return yargs
1161
1956
  .positional("key", {
1162
- describe: "The variable name to be accessible in the script.",
1957
+ describe: "The variable name to be accessible in the script",
1163
1958
  type: "string",
1164
1959
  })
1165
1960
  .option("name", {
1166
- describe: "name of the script",
1961
+ describe: "Name of the worker",
1167
1962
  type: "string",
1963
+ requiresArg: true,
1168
1964
  })
1169
1965
  .option("env", {
1170
1966
  type: "string",
1967
+ requiresArg: true,
1171
1968
  describe:
1172
- "Binds the secret to the script of the specific environment.",
1969
+ "Binds the secret to the Worker of the specific environment",
1970
+ alias: "e",
1173
1971
  });
1174
1972
  },
1175
1973
  async (args) => {
1176
- const config = args.config as Config;
1974
+ const config = readConfig(args.config as ConfigPath, args);
1177
1975
 
1178
- // TODO: use environment (how does current wrangler do it?)
1179
- const scriptName = args.name || config.name;
1976
+ const scriptName = getLegacyScriptName(args, config);
1180
1977
  if (!scriptName) {
1181
1978
  throw new Error("Missing script name");
1182
1979
  }
1183
1980
 
1184
- if (args.local) {
1185
- console.warn(
1186
- "`wrangler secret delete` is a no-op in --local mode"
1187
- );
1188
- }
1189
-
1190
- if (!args.local) {
1191
- // -- snip, extract --
1192
- const loggedIn = await loginOrRefreshIfRequired();
1193
- if (!loggedIn) {
1194
- // didn't login, let's just quit
1195
- console.log("Did not login, quitting...");
1196
- return;
1197
- }
1198
-
1199
- if (!config.account_id) {
1200
- config.account_id = await getAccountId();
1201
- if (!config.account_id) {
1202
- throw new Error("No account id found, quitting...");
1203
- }
1204
- }
1205
- // -- snip, end --
1206
- }
1981
+ const accountId = await requireAuth(config);
1207
1982
 
1208
1983
  if (
1209
1984
  await confirm(
1210
- `Are you sure you want to permanently delete the variable ${args.key} on the script ${scriptName}?`
1985
+ `Are you sure you want to permanently delete the variable ${
1986
+ args.key
1987
+ } on the script ${scriptName}${
1988
+ args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1989
+ }?`
1211
1990
  )
1212
1991
  ) {
1213
- console.log(
1214
- `🌀 Deleting the secret ${args.key} on script ${scriptName}.`
1992
+ logger.log(
1993
+ `🌀 Deleting the secret ${args.key} on script ${scriptName}${
1994
+ args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1995
+ }`
1215
1996
  );
1216
1997
 
1217
- if (args.local) {
1218
- return;
1219
- }
1998
+ const url =
1999
+ !args.env || isLegacyEnv(config)
2000
+ ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
2001
+ : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1220
2002
 
1221
- await fetchResult(
1222
- `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/${args.key}`,
1223
- { method: "DELETE" }
1224
- );
1225
- console.log(`✨ Success! Deleted secret ${args.key}`);
2003
+ await fetchResult(`${url}/${args.key}`, { method: "DELETE" });
2004
+ logger.log(`✨ Success! Deleted secret ${args.key}`);
1226
2005
  }
1227
2006
  }
1228
2007
  )
@@ -1232,59 +2011,34 @@ export async function main(argv: string[]): Promise<void> {
1232
2011
  (yargs) => {
1233
2012
  return yargs
1234
2013
  .option("name", {
1235
- describe: "name of the script",
2014
+ describe: "Name of the worker",
1236
2015
  type: "string",
2016
+ requiresArg: true,
1237
2017
  })
1238
2018
  .option("env", {
1239
2019
  type: "string",
2020
+ requiresArg: true,
1240
2021
  describe:
1241
- "Binds the secret to the script of the specific environment.",
2022
+ "Binds the secret to the Worker of the specific environment.",
2023
+ alias: "e",
1242
2024
  });
1243
2025
  },
1244
2026
  async (args) => {
1245
- const config = args.config as Config;
2027
+ const config = readConfig(args.config as ConfigPath, args);
1246
2028
 
1247
- // TODO: use environment (how does current wrangler do it?)
1248
- const scriptName = args.name || config.name;
2029
+ const scriptName = getLegacyScriptName(args, config);
1249
2030
  if (!scriptName) {
1250
2031
  throw new Error("Missing script name");
1251
2032
  }
1252
2033
 
1253
- if (args.local) {
1254
- console.warn("`wrangler secret list` is a no-op in --local mode");
1255
- }
1256
-
1257
- if (!args.local) {
1258
- // -- snip, extract --
1259
- const loggedIn = await loginOrRefreshIfRequired();
1260
- if (!loggedIn) {
1261
- // didn't login, let's just quit
1262
- console.log("Did not login, quitting...");
1263
- return;
1264
- }
1265
-
1266
- if (!config.account_id) {
1267
- config.account_id = await getAccountId();
1268
- if (!config.account_id) {
1269
- throw new Error("No account id found, quitting...");
1270
- }
1271
- }
1272
- // -- snip, end --
1273
- }
2034
+ const accountId = await requireAuth(config);
1274
2035
 
1275
- if (args.local) {
1276
- return;
1277
- }
2036
+ const url =
2037
+ !args.env || isLegacyEnv(config)
2038
+ ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
2039
+ : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1278
2040
 
1279
- console.log(
1280
- JSON.stringify(
1281
- await fetchResult(
1282
- `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets`
1283
- ),
1284
- null,
1285
- " "
1286
- )
1287
- );
2041
+ logger.log(JSON.stringify(await fetchResult(url), null, " "));
1288
2042
  }
1289
2043
  );
1290
2044
  }
@@ -1297,6 +2051,7 @@ export async function main(argv: string[]): Promise<void> {
1297
2051
  "🗂️ Interact with your Workers KV Namespaces",
1298
2052
  (namespaceYargs) => {
1299
2053
  return namespaceYargs
2054
+ .command(subHelp)
1300
2055
  .command(
1301
2056
  "create <namespace>",
1302
2057
  "Create a new namespace",
@@ -1309,7 +2064,9 @@ export async function main(argv: string[]): Promise<void> {
1309
2064
  })
1310
2065
  .option("env", {
1311
2066
  type: "string",
2067
+ requiresArg: true,
1312
2068
  describe: "Perform on a specific environment",
2069
+ alias: "e",
1313
2070
  })
1314
2071
  .option("preview", {
1315
2072
  type: "boolean",
@@ -1317,22 +2074,17 @@ export async function main(argv: string[]): Promise<void> {
1317
2074
  });
1318
2075
  },
1319
2076
  async (args) => {
1320
- if (args._.length > 2) {
1321
- const extraArgs = args._.slice(2).join(" ");
1322
- throw new CommandLineArgsError(
1323
- `Unexpected additional positional arguments "${extraArgs}".`
1324
- );
1325
- }
2077
+ await printWranglerBanner();
1326
2078
 
1327
- if (!isValidNamespaceBinding(args.namespace)) {
2079
+ if (!isValidKVNamespaceBinding(args.namespace)) {
1328
2080
  throw new CommandLineArgsError(
1329
2081
  `The namespace binding name "${args.namespace}" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.`
1330
2082
  );
1331
2083
  }
1332
2084
 
1333
- const config = args.config as Config;
2085
+ const config = readConfig(args.config as ConfigPath, args);
1334
2086
  if (!config.name) {
1335
- console.warn(
2087
+ logger.warn(
1336
2088
  "No configured name present, using `worker` as a prefix for the title"
1337
2089
  );
1338
2090
  }
@@ -1342,52 +2094,24 @@ export async function main(argv: string[]): Promise<void> {
1342
2094
  const preview = args.preview ? "_preview" : "";
1343
2095
  const title = `${name}${environment}-${args.namespace}${preview}`;
1344
2096
 
1345
- if (args.local) {
1346
- const { Miniflare } = await import("miniflare");
1347
- const mf = new Miniflare({
1348
- kvPersist: (args.kvPersist as string) || true,
1349
- // TODO: these options shouldn't be required
1350
- script: ` `, // has to be a string with at least one char
1351
- });
1352
- await mf.getKVNamespace(title); // this should "create" the namespace
1353
- console.log(`✨ Success! Created KV namespace ${title}`);
1354
- } else {
1355
- // -- snip, extract --
1356
- const loggedIn = await loginOrRefreshIfRequired();
1357
- if (!loggedIn) {
1358
- // didn't login, let's just quit
1359
- console.log("Did not login, quitting...");
1360
- return;
1361
- }
1362
-
1363
- if (!config.account_id) {
1364
- config.account_id = await getAccountId();
1365
- if (!config.account_id) {
1366
- throw new Error("No account id found, quitting...");
1367
- }
1368
- }
1369
- // -- snip, end --
2097
+ const accountId = await requireAuth(config);
1370
2098
 
1371
- // TODO: generate a binding name stripping non alphanumeric chars
2099
+ // TODO: generate a binding name stripping non alphanumeric chars
1372
2100
 
1373
- console.log(`🌀 Creating namespace with title "${title}"`);
1374
- const namespaceId = await createNamespace(
1375
- config.account_id,
1376
- title
1377
- );
2101
+ logger.log(`🌀 Creating namespace with title "${title}"`);
2102
+ const namespaceId = await createKVNamespace(accountId, title);
1378
2103
 
1379
- console.log("✨ Success!");
1380
- const envString = args.env ? ` under [env.${args.env}]` : "";
1381
- const previewString = args.preview ? "preview_" : "";
1382
- console.log(
1383
- `Add the following to your configuration file in your kv_namespaces array${envString}:`
1384
- );
1385
- console.log(
1386
- `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
1387
- );
2104
+ logger.log("✨ Success!");
2105
+ const envString = args.env ? ` under [env.${args.env}]` : "";
2106
+ const previewString = args.preview ? "preview_" : "";
2107
+ logger.log(
2108
+ `Add the following to your configuration file in your kv_namespaces array${envString}:`
2109
+ );
2110
+ logger.log(
2111
+ `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
2112
+ );
1388
2113
 
1389
- // TODO: automatically write this block to the wrangler.toml config file??
1390
- }
2114
+ // TODO: automatically write this block to the wrangler.toml config file??
1391
2115
  }
1392
2116
  )
1393
2117
  .command(
@@ -1395,39 +2119,15 @@ export async function main(argv: string[]): Promise<void> {
1395
2119
  "Outputs a list of all KV namespaces associated with your account id.",
1396
2120
  {},
1397
2121
  async (args) => {
1398
- const config = args.config as Config;
1399
-
1400
- if (args.local) {
1401
- throw new NotImplementedError(
1402
- `local mode is not yet supported for this command`
1403
- );
1404
- } else {
1405
- // -- snip, extract --
1406
- const loggedIn = await loginOrRefreshIfRequired();
1407
- if (!loggedIn) {
1408
- // didn't login, let's just quit
1409
- console.log("Did not login, quitting...");
1410
- return;
1411
- }
2122
+ const config = readConfig(args.config as ConfigPath, args);
1412
2123
 
1413
- if (!config.account_id) {
1414
- config.account_id = await getAccountId();
1415
- if (!config.account_id) {
1416
- throw new Error("No account id found, quitting...");
1417
- }
1418
- }
1419
- // -- snip, end --
2124
+ const accountId = await requireAuth(config);
1420
2125
 
1421
- // TODO: we should show bindings if they exist for given ids
2126
+ // TODO: we should show bindings if they exist for given ids
1422
2127
 
1423
- console.log(
1424
- JSON.stringify(
1425
- await listNamespaces(config.account_id),
1426
- null,
1427
- " "
1428
- )
1429
- );
1430
- }
2128
+ logger.log(
2129
+ JSON.stringify(await listKVNamespaces(accountId), null, " ")
2130
+ );
1431
2131
  }
1432
2132
  )
1433
2133
  .command(
@@ -1437,16 +2137,20 @@ export async function main(argv: string[]): Promise<void> {
1437
2137
  return yargs
1438
2138
  .option("binding", {
1439
2139
  type: "string",
2140
+ requiresArg: true,
1440
2141
  describe: "The name of the namespace to delete",
1441
2142
  })
1442
2143
  .option("namespace-id", {
1443
2144
  type: "string",
2145
+ requiresArg: true,
1444
2146
  describe: "The id of the namespace to delete",
1445
2147
  })
1446
2148
  .check(demandOneOfOption("binding", "namespace-id"))
1447
2149
  .option("env", {
1448
2150
  type: "string",
2151
+ requiresArg: true,
1449
2152
  describe: "Perform on a specific environment",
2153
+ alias: "e",
1450
2154
  })
1451
2155
  .option("preview", {
1452
2156
  type: "boolean",
@@ -1454,61 +2158,39 @@ export async function main(argv: string[]): Promise<void> {
1454
2158
  });
1455
2159
  },
1456
2160
  async (args) => {
1457
- const config = args.config as Config;
2161
+ await printWranglerBanner();
2162
+ const config = readConfig(args.config as ConfigPath, args);
1458
2163
 
1459
- if (args.local) {
1460
- throw new NotImplementedError(
1461
- `local mode is not yet supported for this command`
2164
+ let id;
2165
+ try {
2166
+ id = getKVNamespaceId(args, config);
2167
+ } catch (e) {
2168
+ throw new CommandLineArgsError(
2169
+ "Not able to delete namespace.\n" + ((e as Error).message ?? e)
1462
2170
  );
1463
- } else {
1464
- let id;
1465
- try {
1466
- id = getNamespaceId(args);
1467
- } catch (e) {
1468
- throw new CommandLineArgsError(
1469
- "Not able to delete namespace.\n" + e.message
1470
- );
1471
- }
1472
-
1473
- // -- snip, extract --
1474
- const loggedIn = await loginOrRefreshIfRequired();
1475
- if (!loggedIn) {
1476
- // didn't login, let's just quit
1477
- console.log("Did not login, quitting...");
1478
- return;
1479
- }
2171
+ }
1480
2172
 
1481
- if (!config.account_id) {
1482
- config.account_id = await getAccountId();
1483
- if (!config.account_id) {
1484
- throw new Error("No account id found, quitting...");
1485
- }
1486
- }
1487
- // -- snip, end --
2173
+ const accountId = await requireAuth(config);
1488
2174
 
1489
- await fetchResult<{ id: string }>(
1490
- `/accounts/${config.account_id}/storage/kv/namespaces/${id}`,
1491
- { method: "DELETE" }
1492
- );
2175
+ await deleteKVNamespace(accountId, id);
1493
2176
 
1494
- // TODO: recommend they remove it from wrangler.toml
2177
+ // TODO: recommend they remove it from wrangler.toml
1495
2178
 
1496
- // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1497
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1498
- // n
1499
- // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1500
- // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1501
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1502
- // y
1503
- // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1504
- // ✨ Success
1505
- // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
1506
- // ➜ test-mf
2179
+ // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
2180
+ // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
2181
+ // n
2182
+ // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
2183
+ // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
2184
+ // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
2185
+ // y
2186
+ // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
2187
+ // ✨ Success
2188
+ // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
2189
+ // ➜ test-mf
1507
2190
 
1508
- // TODO: do it automatically
2191
+ // TODO: do it automatically
1509
2192
 
1510
- // TODO: delete the preview namespace as well?
1511
- }
2193
+ // TODO: delete the preview namespace as well?
1512
2194
  }
1513
2195
  );
1514
2196
  }
@@ -1520,6 +2202,7 @@ export async function main(argv: string[]): Promise<void> {
1520
2202
  "🔑 Individually manage Workers KV key-value pairs",
1521
2203
  (kvKeyYargs) => {
1522
2204
  return kvKeyYargs
2205
+ .command(subHelp)
1523
2206
  .command(
1524
2207
  "put <key> [value]",
1525
2208
  "Writes a single key/value pair to the given namespace.",
@@ -1527,25 +2210,29 @@ export async function main(argv: string[]): Promise<void> {
1527
2210
  return yargs
1528
2211
  .positional("key", {
1529
2212
  type: "string",
1530
- describe: "The key to write to.",
2213
+ describe: "The key to write to",
1531
2214
  demandOption: true,
1532
2215
  })
1533
2216
  .positional("value", {
1534
2217
  type: "string",
1535
- describe: "The value to write.",
2218
+ describe: "The value to write",
1536
2219
  })
1537
2220
  .option("binding", {
1538
2221
  type: "string",
1539
- describe: "The binding of the namespace to write to.",
2222
+ requiresArg: true,
2223
+ describe: "The binding of the namespace to write to",
1540
2224
  })
1541
2225
  .option("namespace-id", {
1542
2226
  type: "string",
1543
- describe: "The id of the namespace to write to.",
2227
+ requiresArg: true,
2228
+ describe: "The id of the namespace to write to",
1544
2229
  })
1545
2230
  .check(demandOneOfOption("binding", "namespace-id"))
1546
2231
  .option("env", {
1547
2232
  type: "string",
2233
+ requiresArg: true,
1548
2234
  describe: "Perform on a specific environment",
2235
+ alias: "e",
1549
2236
  })
1550
2237
  .option("preview", {
1551
2238
  type: "boolean",
@@ -1553,7 +2240,7 @@ export async function main(argv: string[]): Promise<void> {
1553
2240
  })
1554
2241
  .option("ttl", {
1555
2242
  type: "number",
1556
- describe: "Time for which the entries should be visible.",
2243
+ describe: "Time for which the entries should be visible",
1557
2244
  })
1558
2245
  .option("expiration", {
1559
2246
  type: "number",
@@ -1562,60 +2249,39 @@ export async function main(argv: string[]): Promise<void> {
1562
2249
  })
1563
2250
  .option("path", {
1564
2251
  type: "string",
1565
- describe: "Read value from the file at a given path.",
2252
+ requiresArg: true,
2253
+ describe: "Read value from the file at a given path",
1566
2254
  })
1567
2255
  .check(demandOneOfOption("value", "path"));
1568
2256
  },
1569
2257
  async ({ key, ttl, expiration, ...args }) => {
1570
- const namespaceId = getNamespaceId(args);
2258
+ await printWranglerBanner();
2259
+ const config = readConfig(args.config as ConfigPath, args);
2260
+ const namespaceId = getKVNamespaceId(args, config);
1571
2261
  // One of `args.path` and `args.value` must be defined
1572
2262
  const value = args.path
1573
- ? await readFile(args.path, "utf-8")
2263
+ ? readFileSync(args.path)
1574
2264
  : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1575
2265
  args.value!;
1576
- const config = args.config as Config;
1577
2266
 
1578
2267
  if (args.path) {
1579
- console.log(
1580
- `writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}`
2268
+ logger.log(
2269
+ `Writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}.`
1581
2270
  );
1582
2271
  } else {
1583
- console.log(
1584
- `writing the value "${value}" to key "${key}" on namespace ${namespaceId}`
2272
+ logger.log(
2273
+ `Writing the value "${value}" to key "${key}" on namespace ${namespaceId}.`
1585
2274
  );
1586
2275
  }
1587
2276
 
1588
- if (args.local) {
1589
- const { Miniflare } = await import("miniflare");
1590
- const mf = new Miniflare({
1591
- kvPersist: (args.kvPersist as string) || true,
1592
- // TODO: these options shouldn't be required
1593
- script: ` `, // has to be a string with at least one char
1594
- });
1595
- const ns = await mf.getKVNamespace(namespaceId);
1596
- await ns.put(key, value, { expiration, expirationTtl: ttl });
1597
- } else {
1598
- // -- snip, extract --
1599
- const loggedIn = await loginOrRefreshIfRequired();
1600
- if (!loggedIn) {
1601
- // didn't login, let's just quit
1602
- console.log("Did not login, quitting...");
1603
- return;
1604
- }
1605
-
1606
- if (!config.account_id) {
1607
- config.account_id = await getAccountId();
1608
- if (!config.account_id) {
1609
- throw new Error("No account id found, quitting...");
1610
- }
1611
- }
1612
- // -- snip, end --
2277
+ const accountId = await requireAuth(config);
1613
2278
 
1614
- await putKeyValue(config.account_id, namespaceId, key, value, {
1615
- expiration,
1616
- expiration_ttl: ttl,
1617
- });
1618
- }
2279
+ await putKVKeyValue(accountId, namespaceId, {
2280
+ key,
2281
+ value,
2282
+ expiration,
2283
+ expiration_ttl: ttl,
2284
+ });
1619
2285
  }
1620
2286
  )
1621
2287
  .command(
@@ -1625,16 +2291,20 @@ export async function main(argv: string[]): Promise<void> {
1625
2291
  return yargs
1626
2292
  .option("binding", {
1627
2293
  type: "string",
2294
+ requiresArg: true,
1628
2295
  describe: "The name of the namespace to list",
1629
2296
  })
1630
2297
  .option("namespace-id", {
1631
2298
  type: "string",
2299
+ requiresArg: true,
1632
2300
  describe: "The id of the namespace to list",
1633
2301
  })
1634
2302
  .check(demandOneOfOption("binding", "namespace-id"))
1635
2303
  .option("env", {
1636
2304
  type: "string",
2305
+ requiresArg: true,
1637
2306
  describe: "Perform on a specific environment",
2307
+ alias: "e",
1638
2308
  })
1639
2309
  .option("preview", {
1640
2310
  type: "boolean",
@@ -1644,49 +2314,23 @@ export async function main(argv: string[]): Promise<void> {
1644
2314
  })
1645
2315
  .option("prefix", {
1646
2316
  type: "string",
2317
+ requiresArg: true,
1647
2318
  describe: "A prefix to filter listed keys",
1648
2319
  });
1649
2320
  },
1650
2321
  async ({ prefix, ...args }) => {
1651
2322
  // TODO: support for limit+cursor (pagination)
2323
+ const config = readConfig(args.config as ConfigPath, args);
2324
+ const namespaceId = getKVNamespaceId(args, config);
1652
2325
 
1653
- const namespaceId = getNamespaceId(args);
1654
- const config = args.config as Config;
1655
-
1656
- if (args.local) {
1657
- const { Miniflare } = await import("miniflare");
1658
- const mf = new Miniflare({
1659
- kvPersist: (args.kvPersist as string) || true,
1660
- // TODO: these options shouldn't be required
1661
- script: ` `, // has to be a string with at least one char
1662
- });
1663
- const ns = await mf.getKVNamespace(namespaceId);
1664
- const listResponse = await ns.list({ prefix });
1665
- console.log(JSON.stringify(listResponse.keys, null, " ")); // TODO: paginate, collate
1666
- } else {
1667
- // -- snip, extract --
1668
- const loggedIn = await loginOrRefreshIfRequired();
1669
- if (!loggedIn) {
1670
- // didn't login, let's just quit
1671
- console.log("Did not login, quitting...");
1672
- return;
1673
- }
1674
-
1675
- if (!config.account_id) {
1676
- config.account_id = await getAccountId();
1677
- if (!config.account_id) {
1678
- throw new Error("No account id found, quitting...");
1679
- }
1680
- }
1681
- // -- snip, end --
2326
+ const accountId = await requireAuth(config);
1682
2327
 
1683
- const results = await listNamespaceKeys(
1684
- config.account_id,
1685
- namespaceId,
1686
- prefix
1687
- );
1688
- console.log(JSON.stringify(results, undefined, 2));
1689
- }
2328
+ const results = await listKVNamespaceKeys(
2329
+ accountId,
2330
+ namespaceId,
2331
+ prefix
2332
+ );
2333
+ logger.log(JSON.stringify(results, undefined, 2));
1690
2334
  }
1691
2335
  )
1692
2336
  .command(
@@ -1701,16 +2345,20 @@ export async function main(argv: string[]): Promise<void> {
1701
2345
  })
1702
2346
  .option("binding", {
1703
2347
  type: "string",
2348
+ requiresArg: true,
1704
2349
  describe: "The name of the namespace to get from",
1705
2350
  })
1706
2351
  .option("namespace-id", {
1707
2352
  type: "string",
2353
+ requiresArg: true,
1708
2354
  describe: "The id of the namespace to get from",
1709
2355
  })
1710
2356
  .check(demandOneOfOption("binding", "namespace-id"))
1711
2357
  .option("env", {
1712
2358
  type: "string",
2359
+ requiresArg: true,
1713
2360
  describe: "Perform on a specific environment",
2361
+ alias: "e",
1714
2362
  })
1715
2363
  .option("preview", {
1716
2364
  type: "boolean",
@@ -1724,44 +2372,12 @@ export async function main(argv: string[]): Promise<void> {
1724
2372
  });
1725
2373
  },
1726
2374
  async ({ key, ...args }) => {
1727
- const namespaceId = getNamespaceId(args);
1728
- const config = args.config as Config;
1729
-
1730
- if (args.local) {
1731
- const { Miniflare } = await import("miniflare");
1732
- const mf = new Miniflare({
1733
- kvPersist: (args.kvPersist as string) || true,
1734
- // TODO: these options shouldn't be required
1735
- script: ` `, // has to be a string with at least one char
1736
- });
1737
- const ns = await mf.getKVNamespace(namespaceId);
1738
- console.log(await ns.get(key));
1739
- return;
1740
- }
2375
+ const config = readConfig(args.config as ConfigPath, args);
2376
+ const namespaceId = getKVNamespaceId(args, config);
1741
2377
 
1742
- if (!args.local) {
1743
- // -- snip, extract --
1744
- const loggedIn = await loginOrRefreshIfRequired();
1745
- if (!loggedIn) {
1746
- // didn't login, let's just quit
1747
- console.log("Did not login, quitting...");
1748
- return;
1749
- }
1750
-
1751
- if (!config.account_id) {
1752
- config.account_id = await getAccountId();
1753
- if (!config.account_id) {
1754
- throw new Error("No account id found, quitting...");
1755
- }
1756
- }
1757
- // -- snip, end --
1758
- }
2378
+ const accountId = await requireAuth(config);
1759
2379
 
1760
- console.log(
1761
- await fetchRaw(
1762
- `/accounts/${config.account_id}/storage/kv/namespaces/${namespaceId}/values/${key}`
1763
- )
1764
- );
2380
+ logger.log(await getKVKeyValue(accountId, namespaceId, key));
1765
2381
  }
1766
2382
  )
1767
2383
  .command(
@@ -1776,16 +2392,20 @@ export async function main(argv: string[]): Promise<void> {
1776
2392
  })
1777
2393
  .option("binding", {
1778
2394
  type: "string",
2395
+ requiresArg: true,
1779
2396
  describe: "The name of the namespace to delete from",
1780
2397
  })
1781
2398
  .option("namespace-id", {
1782
2399
  type: "string",
2400
+ requiresArg: true,
1783
2401
  describe: "The id of the namespace to delete from",
1784
2402
  })
1785
2403
  .check(demandOneOfOption("binding", "namespace-id"))
1786
2404
  .option("env", {
1787
2405
  type: "string",
2406
+ requiresArg: true,
1788
2407
  describe: "Perform on a specific environment",
2408
+ alias: "e",
1789
2409
  })
1790
2410
  .option("preview", {
1791
2411
  type: "boolean",
@@ -1793,48 +2413,17 @@ export async function main(argv: string[]): Promise<void> {
1793
2413
  });
1794
2414
  },
1795
2415
  async ({ key, ...args }) => {
1796
- const namespaceId = getNamespaceId(args);
2416
+ await printWranglerBanner();
2417
+ const config = readConfig(args.config as ConfigPath, args);
2418
+ const namespaceId = getKVNamespaceId(args, config);
1797
2419
 
1798
- console.log(
1799
- `deleting the key "${key}" on namespace ${namespaceId}`
2420
+ logger.log(
2421
+ `Deleting the key "${key}" on namespace ${namespaceId}.`
1800
2422
  );
1801
2423
 
1802
- if (args.local) {
1803
- const { Miniflare } = await import("miniflare");
1804
- const mf = new Miniflare({
1805
- kvPersist: (args.kvPersist as string) || true,
1806
- // TODO: these options shouldn't be required
1807
- script: ` `, // has to be a string with at least one char
1808
- });
1809
- const ns = await mf.getKVNamespace(namespaceId);
1810
- console.log(await ns.delete(key));
1811
- return;
1812
- }
1813
-
1814
- const config = args.config as Config;
1815
-
1816
- if (!args.local) {
1817
- // -- snip, extract --
1818
- const loggedIn = await loginOrRefreshIfRequired();
1819
- if (!loggedIn) {
1820
- // didn't login, let's just quit
1821
- console.log("Did not login, quitting...");
1822
- return;
1823
- }
1824
-
1825
- if (!config.account_id) {
1826
- config.account_id = await getAccountId();
1827
- if (!config.account_id) {
1828
- throw new Error("No account id found, quitting...");
1829
- }
1830
- }
1831
- // -- snip, end --
1832
- }
2424
+ const accountId = await requireAuth(config);
1833
2425
 
1834
- await fetchResult(
1835
- `/accounts/${config.account_id}/storage/kv/namespaces/${namespaceId}/values/${key}`,
1836
- { method: "DELETE" }
1837
- );
2426
+ await deleteKVKeyValue(accountId, namespaceId, key);
1838
2427
  }
1839
2428
  );
1840
2429
  }
@@ -1846,6 +2435,7 @@ export async function main(argv: string[]): Promise<void> {
1846
2435
  "💪 Interact with multiple Workers KV key-value pairs at once",
1847
2436
  (kvBulkYargs) => {
1848
2437
  return kvBulkYargs
2438
+ .command(subHelp)
1849
2439
  .command(
1850
2440
  "put <filename>",
1851
2441
  "Upload multiple key-value pairs to a namespace",
@@ -1858,16 +2448,20 @@ export async function main(argv: string[]): Promise<void> {
1858
2448
  })
1859
2449
  .option("binding", {
1860
2450
  type: "string",
1861
- describe: "The name of the namespace to put to",
2451
+ requiresArg: true,
2452
+ describe: "The name of the namespace to insert values into",
1862
2453
  })
1863
2454
  .option("namespace-id", {
1864
2455
  type: "string",
1865
- describe: "The id of the namespace to put to",
2456
+ requiresArg: true,
2457
+ describe: "The id of the namespace to insert values into",
1866
2458
  })
1867
2459
  .check(demandOneOfOption("binding", "namespace-id"))
1868
2460
  .option("env", {
1869
2461
  type: "string",
2462
+ requiresArg: true,
1870
2463
  describe: "Perform on a specific environment",
2464
+ alias: "e",
1871
2465
  })
1872
2466
  .option("preview", {
1873
2467
  type: "boolean",
@@ -1875,62 +2469,67 @@ export async function main(argv: string[]): Promise<void> {
1875
2469
  });
1876
2470
  },
1877
2471
  async ({ filename, ...args }) => {
2472
+ await printWranglerBanner();
1878
2473
  // The simplest implementation I could think of.
1879
2474
  // This could be made more efficient with a streaming parser/uploader
1880
2475
  // but we'll do that in the future if needed.
1881
2476
 
1882
- const namespaceId = getNamespaceId(args);
1883
- const config = args.config as Config;
1884
- const content = await readFile(filename, "utf-8");
1885
- let parsedContent;
1886
- try {
1887
- parsedContent = JSON.parse(content);
1888
- } catch (err) {
2477
+ const config = readConfig(args.config as ConfigPath, args);
2478
+ const namespaceId = getKVNamespaceId(args, config);
2479
+ const content = parseJSON(readFileSync(filename), filename);
2480
+
2481
+ if (!Array.isArray(content)) {
1889
2482
  throw new Error(
1890
- `Could not parse json from ${filename}.\n${err.message ?? err}`
2483
+ `Unexpected JSON input from "${filename}".\n` +
2484
+ `Expected an array of key-value objects but got type "${typeof content}".`
1891
2485
  );
1892
2486
  }
1893
2487
 
1894
- if (args.local) {
1895
- const { Miniflare } = await import("miniflare");
1896
- const mf = new Miniflare({
1897
- kvPersist: (args.kvPersist as string) || true,
1898
- // TODO: these options shouldn't be required
1899
- script: ` `, // has to be a string with at least one char
1900
- });
1901
- const ns = await mf.getKVNamespace(namespaceId);
1902
- for (const {
1903
- key,
1904
- value,
1905
- expiration,
1906
- expiration_ttl,
1907
- } of parsedContent) {
1908
- await ns.put(key, value, {
1909
- expiration,
1910
- expirationTtl: expiration_ttl,
1911
- });
1912
- }
1913
- } else {
1914
- // -- snip, extract --
1915
- const loggedIn = await loginOrRefreshIfRequired();
1916
- if (!loggedIn) {
1917
- // didn't login, let's just quit
1918
- console.log("Did not login, quitting...");
1919
- return;
1920
- }
1921
-
1922
- if (!config.account_id) {
1923
- config.account_id = await getAccountId();
1924
- if (!config.account_id) {
1925
- throw new Error("No account id found, quitting...");
2488
+ const errors: string[] = [];
2489
+ const warnings: string[] = [];
2490
+ for (let i = 0; i < content.length; i++) {
2491
+ const keyValue = content[i];
2492
+ if (!isKVKeyValue(keyValue)) {
2493
+ errors.push(
2494
+ `The item at index ${i} is ${JSON.stringify(keyValue)}`
2495
+ );
2496
+ } else {
2497
+ const props = unexpectedKVKeyValueProps(keyValue);
2498
+ if (props.length > 0) {
2499
+ warnings.push(
2500
+ `The item at index ${i} contains unexpected properties: ${JSON.stringify(
2501
+ props
2502
+ )}.`
2503
+ );
1926
2504
  }
1927
2505
  }
1928
- // -- snip, end --
1929
-
1930
- console.log(
1931
- await putBulkKeyValue(config.account_id, namespaceId, content)
2506
+ }
2507
+ if (warnings.length > 0) {
2508
+ logger.warn(
2509
+ `Unexpected key-value properties in "${filename}".\n` +
2510
+ warnings.join("\n")
2511
+ );
2512
+ }
2513
+ if (errors.length > 0) {
2514
+ throw new Error(
2515
+ `Unexpected JSON input from "${filename}".\n` +
2516
+ `Each item in the array should be an object that matches:\n\n` +
2517
+ `interface KeyValue {\n` +
2518
+ ` key: string;\n` +
2519
+ ` value: string;\n` +
2520
+ ` expiration?: number;\n` +
2521
+ ` expiration_ttl?: number;\n` +
2522
+ ` metadata?: object;\n` +
2523
+ ` base64?: boolean;\n` +
2524
+ `}\n\n` +
2525
+ errors.join("\n")
1932
2526
  );
1933
2527
  }
2528
+
2529
+ const accountId = await requireAuth(config);
2530
+ await putKVBulkKeyValue(accountId, namespaceId, content);
2531
+
2532
+ logger.log("Success!");
1934
2533
  }
1935
2534
  )
1936
2535
  .command(
@@ -1945,116 +2544,303 @@ export async function main(argv: string[]): Promise<void> {
1945
2544
  })
1946
2545
  .option("binding", {
1947
2546
  type: "string",
2547
+ requiresArg: true,
1948
2548
  describe: "The name of the namespace to delete from",
1949
2549
  })
1950
2550
  .option("namespace-id", {
1951
2551
  type: "string",
2552
+ requiresArg: true,
1952
2553
  describe: "The id of the namespace to delete from",
1953
2554
  })
1954
2555
  .check(demandOneOfOption("binding", "namespace-id"))
1955
2556
  .option("env", {
1956
2557
  type: "string",
2558
+ requiresArg: true,
1957
2559
  describe: "Perform on a specific environment",
2560
+ alias: "e",
1958
2561
  })
1959
2562
  .option("preview", {
1960
2563
  type: "boolean",
1961
2564
  describe: "Interact with a preview namespace",
2565
+ })
2566
+ .option("force", {
2567
+ type: "boolean",
2568
+ alias: "f",
2569
+ describe: "Do not ask for confirmation before deleting",
1962
2570
  });
1963
2571
  },
1964
2572
  async ({ filename, ...args }) => {
1965
- const namespaceId = getNamespaceId(args);
1966
- const config = args.config as Config;
1967
- const content = await readFile(filename, "utf-8");
1968
- let parsedContent;
1969
- try {
1970
- parsedContent = JSON.parse(content);
1971
- } catch (err) {
1972
- throw new Error(
1973
- `Could not parse json from ${filename}.\n${err.message ?? err}`
1974
- );
1975
- }
2573
+ await printWranglerBanner();
2574
+ const config = readConfig(args.config as ConfigPath, args);
2575
+ const namespaceId = getKVNamespaceId(args, config);
1976
2576
 
1977
- if (args.local) {
1978
- const { Miniflare } = await import("miniflare");
1979
- const mf = new Miniflare({
1980
- kvPersist: (args.kvPersist as string) || true,
1981
- // TODO: these options shouldn't be required
1982
- script: ` `, // has to be a string with at least one char
1983
- });
1984
- const ns = await mf.getKVNamespace(namespaceId);
1985
- for (const key of parsedContent) {
1986
- await ns.delete(key);
1987
- }
1988
- } else {
1989
- // -- snip, extract --
1990
- const loggedIn = await loginOrRefreshIfRequired();
1991
- if (!loggedIn) {
1992
- // didn't login, let's just quit
1993
- console.log("Did not login, quitting...");
2577
+ if (!args.force) {
2578
+ const result = await confirm(
2579
+ `Are you sure you want to delete all the keys read from "${filename}" from kv-namespace with id "${namespaceId}"?`
2580
+ );
2581
+ if (!result) {
2582
+ logger.log(`Not deleting keys read from "${filename}".`);
1994
2583
  return;
1995
2584
  }
2585
+ }
1996
2586
 
1997
- if (!config.account_id) {
1998
- config.account_id = await getAccountId();
1999
- if (!config.account_id) {
2000
- throw new Error("No account id found, quitting...");
2001
- }
2587
+ const content = parseJSON(
2588
+ readFileSync(filename),
2589
+ filename
2590
+ ) as string[];
2591
+
2592
+ if (!Array.isArray(content)) {
2593
+ throw new Error(
2594
+ `Unexpected JSON input from "${filename}".\n` +
2595
+ `Expected an array of strings but got:\n${content}`
2596
+ );
2597
+ }
2598
+
2599
+ const errors: string[] = [];
2600
+ for (let i = 0; i < content.length; i++) {
2601
+ const key = content[i];
2602
+ if (typeof key !== "string") {
2603
+ errors.push(
2604
+ `The item at index ${i} is type: "${typeof key}" - ${JSON.stringify(
2605
+ key
2606
+ )}`
2607
+ );
2002
2608
  }
2003
- // -- snip, end --
2004
-
2005
- console.log(
2006
- await deleteBulkKeyValue(
2007
- config.account_id,
2008
- namespaceId,
2009
- content
2010
- )
2609
+ }
2610
+ if (errors.length > 0) {
2611
+ throw new Error(
2612
+ `Unexpected JSON input from "${filename}".\n` +
2613
+ `Expected an array of strings.\n` +
2614
+ errors.join("\n")
2011
2615
  );
2012
2616
  }
2617
+
2618
+ const accountId = await requireAuth(config);
2619
+
2620
+ await deleteKVBulkKeyValue(accountId, namespaceId, content);
2621
+
2622
+ logger.log("Success!");
2013
2623
  }
2014
2624
  );
2015
2625
  }
2016
2626
  );
2017
2627
 
2018
- wrangler.command("pages", "⚡️ Configure Cloudflare Pages", pages);
2628
+ wrangler.command(
2629
+ "pages",
2630
+ "⚡️ Configure Cloudflare Pages",
2631
+ async (pagesYargs) => {
2632
+ await pages(pagesYargs.command(subHelp).epilogue(pagesBetaWarning));
2633
+ }
2634
+ );
2019
2635
 
2020
- wrangler
2021
- .option("config", {
2022
- alias: "c",
2023
- describe: "Path to .toml configuration file",
2024
- type: "string",
2025
- async coerce(arg) {
2026
- return await readConfig(arg);
2027
- },
2028
- })
2029
- .option("local", {
2030
- alias: "l",
2031
- describe: "Run on my machine",
2032
- type: "boolean",
2033
- default: false, // I bet this will a point of contention. We'll revisit it.
2034
- });
2636
+ wrangler.command("r2", "📦 Interact with an R2 store", (r2Yargs) => {
2637
+ return r2Yargs
2638
+ .command(subHelp)
2639
+ .command("bucket", "Manage R2 buckets", (r2BucketYargs) => {
2640
+ r2BucketYargs.command(
2641
+ "create <name>",
2642
+ "Create a new R2 bucket",
2643
+ (yargs) => {
2644
+ return yargs.positional("name", {
2645
+ describe: "The name of the new bucket",
2646
+ type: "string",
2647
+ demandOption: true,
2648
+ });
2649
+ },
2650
+ async (args) => {
2651
+ await printWranglerBanner();
2652
+
2653
+ const config = readConfig(args.config as ConfigPath, args);
2654
+
2655
+ const accountId = await requireAuth(config);
2656
+
2657
+ logger.log(`Creating bucket ${args.name}.`);
2658
+ await createR2Bucket(accountId, args.name);
2659
+ logger.log(`Created bucket ${args.name}.`);
2660
+ }
2661
+ );
2662
+
2663
+ r2BucketYargs.command("list", "List R2 buckets", {}, async (args) => {
2664
+ const config = readConfig(args.config as ConfigPath, args);
2665
+
2666
+ const accountId = await requireAuth(config);
2667
+
2668
+ logger.log(JSON.stringify(await listR2Buckets(accountId), null, 2));
2669
+ });
2670
+
2671
+ r2BucketYargs.command(
2672
+ "delete <name>",
2673
+ "Delete an R2 bucket",
2674
+ (yargs) => {
2675
+ return yargs.positional("name", {
2676
+ describe: "The name of the bucket to delete",
2677
+ type: "string",
2678
+ demandOption: true,
2679
+ });
2680
+ },
2681
+ async (args) => {
2682
+ await printWranglerBanner();
2683
+
2684
+ const config = readConfig(args.config as ConfigPath, args);
2685
+
2686
+ const accountId = await requireAuth(config);
2687
+
2688
+ logger.log(`Deleting bucket ${args.name}.`);
2689
+ await deleteR2Bucket(accountId, args.name);
2690
+ logger.log(`Deleted bucket ${args.name}.`);
2691
+ }
2692
+ );
2693
+ return r2BucketYargs;
2694
+ });
2695
+ });
2696
+
2697
+ /**
2698
+ * User Group: login, logout, and whoami
2699
+ * TODO: group commands into User group similar to .group() for flags in yargs
2700
+ */
2701
+ // login
2702
+ wrangler.command(
2703
+ // this needs scopes as an option?
2704
+ "login",
2705
+ "🔓 Login to Cloudflare",
2706
+ (yargs) => {
2707
+ // TODO: This needs some copy editing
2708
+ // I mean, this entire app does, but this too.
2709
+ return yargs
2710
+ .option("scopes-list", {
2711
+ describe: "List all the available OAuth scopes with descriptions",
2712
+ })
2713
+ .option("scopes", {
2714
+ describe: "Pick the set of applicable OAuth scopes when logging in",
2715
+ array: true,
2716
+ type: "string",
2717
+ requiresArg: true,
2718
+ });
2719
+
2720
+ // TODO: scopes
2721
+ },
2722
+ async (args) => {
2723
+ await printWranglerBanner();
2724
+ if (args["scopes-list"]) {
2725
+ listScopes();
2726
+ return;
2727
+ }
2728
+ if (args.scopes) {
2729
+ if (args.scopes.length === 0) {
2730
+ // don't allow no scopes to be passed, that would be weird
2731
+ listScopes();
2732
+ return;
2733
+ }
2734
+ if (!validateScopeKeys(args.scopes)) {
2735
+ throw new CommandLineArgsError(
2736
+ `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
2737
+ );
2738
+ }
2739
+ await login({ scopes: args.scopes });
2740
+ return;
2741
+ }
2742
+ await login();
2743
+
2744
+ // TODO: would be nice if it optionally saved login
2745
+ // credentials inside node_modules/.cache or something
2746
+ // this way you could have multiple users on a single machine
2747
+ }
2748
+ );
2749
+
2750
+ // logout
2751
+ wrangler.command(
2752
+ // this needs scopes as an option?
2753
+ "logout",
2754
+ "🚪 Logout from Cloudflare",
2755
+ () => {},
2756
+ async () => {
2757
+ await printWranglerBanner();
2758
+ await logout();
2759
+ }
2760
+ );
2761
+
2762
+ // whoami
2763
+ wrangler.command(
2764
+ "whoami",
2765
+ "🕵️ Retrieve your user info and test your auth config",
2766
+ () => {},
2767
+ async () => {
2768
+ await printWranglerBanner();
2769
+ await whoami();
2770
+ }
2771
+ );
2772
+
2773
+ wrangler.option("config", {
2774
+ alias: "c",
2775
+ describe: "Path to .toml configuration file",
2776
+ type: "string",
2777
+ requiresArg: true,
2778
+ });
2035
2779
 
2036
2780
  wrangler.group(["config", "help", "version"], "Flags:");
2037
2781
  wrangler.help().alias("h", "help");
2038
2782
  wrangler.version(wranglerVersion).alias("v", "version");
2039
2783
  wrangler.exitProcess(false);
2040
2784
 
2041
- await initialiseUserConfig();
2785
+ return wrangler;
2786
+ }
2042
2787
 
2788
+ export async function main(argv: string[]): Promise<void> {
2789
+ const wrangler = createCLIParser(argv);
2043
2790
  try {
2044
2791
  await wrangler.parse();
2045
2792
  } catch (e) {
2793
+ logger.log(""); // Just adds a bit of space
2046
2794
  if (e instanceof CommandLineArgsError) {
2047
- wrangler.showHelp("error");
2048
- console.error(""); // Just adds a bit of space
2049
- console.error(e.message);
2795
+ logger.error(e.message);
2796
+ // We are not able to ask the `wrangler` CLI parser to show help for a subcommand programmatically.
2797
+ // The workaround is to re-run the parsing with an additional `--help` flag, which will result in the correct help message being displayed.
2798
+ // The `wrangler` object is "frozen"; we cannot reuse that with different args, so we must create a new CLI parser to generate the help message.
2799
+ await createCLIParser([...argv, "--help"]).parse();
2800
+ } else if (e instanceof ParseError) {
2801
+ e.notes.push({
2802
+ text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/wrangler2/issues/new/choose",
2803
+ });
2804
+ logger.log(formatMessage(e));
2050
2805
  } else {
2051
- console.error(e.message);
2052
- console.error(""); // Just adds a bit of space
2053
- console.error(
2806
+ logger.error(e instanceof Error ? e.message : e);
2807
+ logger.log(
2054
2808
  `${fgGreenColor}%s${resetColor}`,
2055
- "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
2809
+ "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
2056
2810
  );
2057
2811
  }
2058
2812
  throw e;
2059
2813
  }
2060
2814
  }
2815
+
2816
+ function getDevCompatibilityDate(
2817
+ config: Config,
2818
+ compatibilityDate = config.compatibility_date
2819
+ ) {
2820
+ const currentDate = new Date().toISOString().substring(0, 10);
2821
+ if (config.configPath !== undefined && compatibilityDate === undefined) {
2822
+ logger.warn(
2823
+ `No compatibility_date was specified. Using today's date: ${currentDate}.\n` +
2824
+ "Add one to your wrangler.toml file:\n" +
2825
+ "```\n" +
2826
+ `compatibility_date = "${currentDate}"\n` +
2827
+ "```\n" +
2828
+ "or pass it in your terminal:\n" +
2829
+ "```\n" +
2830
+ `--compatibility-date=${currentDate}\n` +
2831
+ "```\n" +
2832
+ "See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
2833
+ );
2834
+ }
2835
+ return compatibilityDate ?? currentDate;
2836
+ }
2837
+
2838
+ /**
2839
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
2840
+ */
2841
+ function memoizeGetPort(defaultPort: number) {
2842
+ let portValue: number;
2843
+ return async () => {
2844
+ return portValue || (portValue = await getPort({ port: defaultPort }));
2845
+ };
2846
+ }