wrangler 0.0.0-e9307365 → 0.0.0-e94b46ff7

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 (199) hide show
  1. package/README.md +35 -49
  2. package/bin/wrangler.js +25 -100
  3. package/config-schema.json +2277 -0
  4. package/package.json +182 -172
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +2 -3
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +134 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  21. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  22. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +29 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +33 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +1 -1
  32. package/templates/pages-template-plugin.ts +53 -18
  33. package/templates/pages-template-worker.ts +49 -12
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +22 -0
  38. package/templates/tsconfig.json +12 -102
  39. package/templates/tsconfig.tsbuildinfo +1 -0
  40. package/wrangler-dist/InspectorProxyWorker.js +460 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +238 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26533 -167
  45. package/wrangler-dist/cli.js +146609 -141820
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -5416
  52. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  53. package/src/__tests__/config-cache.test.ts +0 -42
  54. package/src/__tests__/configuration.test.ts +0 -4022
  55. package/src/__tests__/dev.test.tsx +0 -1294
  56. package/src/__tests__/generate.test.ts +0 -93
  57. package/src/__tests__/guess-worker-format.test.ts +0 -85
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-bin.ts +0 -36
  62. package/src/__tests__/helpers/mock-cfetch.ts +0 -263
  63. package/src/__tests__/helpers/mock-console.ts +0 -97
  64. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  65. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  66. package/src/__tests__/helpers/mock-istty.ts +0 -74
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  69. package/src/__tests__/helpers/mock-process.ts +0 -39
  70. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  71. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  72. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  73. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  74. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  75. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  76. package/src/__tests__/https-options.test.ts +0 -163
  77. package/src/__tests__/index.test.ts +0 -245
  78. package/src/__tests__/init.test.ts +0 -1992
  79. package/src/__tests__/jest.setup.ts +0 -150
  80. package/src/__tests__/kv.test.ts +0 -1671
  81. package/src/__tests__/logger.test.ts +0 -141
  82. package/src/__tests__/metrics.test.ts +0 -450
  83. package/src/__tests__/package-manager.test.ts +0 -353
  84. package/src/__tests__/pages.test.ts +0 -1261
  85. package/src/__tests__/parse.test.ts +0 -330
  86. package/src/__tests__/publish.test.ts +0 -6914
  87. package/src/__tests__/pubsub.test.ts +0 -367
  88. package/src/__tests__/r2.test.ts +0 -317
  89. package/src/__tests__/route.test.ts +0 -45
  90. package/src/__tests__/secret.test.ts +0 -492
  91. package/src/__tests__/tail.test.ts +0 -698
  92. package/src/__tests__/test-old-node-version.js +0 -31
  93. package/src/__tests__/user.test.ts +0 -144
  94. package/src/__tests__/validate-dev-props.test.ts +0 -56
  95. package/src/__tests__/version.test.ts +0 -35
  96. package/src/__tests__/whoami.test.tsx +0 -289
  97. package/src/__tests__/worker-namespace.test.ts +0 -327
  98. package/src/abort.d.ts +0 -3
  99. package/src/api/dev.ts +0 -86
  100. package/src/api/index.ts +0 -1
  101. package/src/bundle-reporter.tsx +0 -29
  102. package/src/bundle.ts +0 -472
  103. package/src/cfetch/index.ts +0 -121
  104. package/src/cfetch/internal.ts +0 -181
  105. package/src/cli.ts +0 -27
  106. package/src/config/README.md +0 -107
  107. package/src/config/config.ts +0 -263
  108. package/src/config/diagnostics.ts +0 -80
  109. package/src/config/environment.ts +0 -485
  110. package/src/config/index.ts +0 -251
  111. package/src/config/validation-helpers.ts +0 -584
  112. package/src/config/validation.ts +0 -1856
  113. package/src/config-cache.ts +0 -84
  114. package/src/create-worker-preview.ts +0 -257
  115. package/src/create-worker-upload-form.ts +0 -288
  116. package/src/dev/dev-vars.ts +0 -36
  117. package/src/dev/dev.tsx +0 -531
  118. package/src/dev/local.tsx +0 -385
  119. package/src/dev/remote.tsx +0 -413
  120. package/src/dev/use-esbuild.ts +0 -175
  121. package/src/dev/validate-dev-props.ts +0 -31
  122. package/src/dev-registry.tsx +0 -157
  123. package/src/dev.tsx +0 -616
  124. package/src/dialogs.tsx +0 -135
  125. package/src/durable.ts +0 -102
  126. package/src/entry.ts +0 -328
  127. package/src/environment-variables.ts +0 -35
  128. package/src/errors.ts +0 -11
  129. package/src/faye-websocket.d.ts +0 -6
  130. package/src/generate.ts +0 -131
  131. package/src/git-client.ts +0 -42
  132. package/src/global-wrangler-config-path.ts +0 -26
  133. package/src/https-options.ts +0 -127
  134. package/src/index.tsx +0 -2184
  135. package/src/init.ts +0 -549
  136. package/src/inspect.ts +0 -750
  137. package/src/intl-polyfill.d.ts +0 -139
  138. package/src/is-interactive.ts +0 -12
  139. package/src/kv.ts +0 -430
  140. package/src/logger.ts +0 -73
  141. package/src/metrics/index.ts +0 -5
  142. package/src/metrics/is-ci.ts +0 -14
  143. package/src/metrics/metrics-config.ts +0 -239
  144. package/src/metrics/metrics-dispatcher.ts +0 -96
  145. package/src/metrics/metrics-usage-headers.ts +0 -24
  146. package/src/metrics/send-event.ts +0 -92
  147. package/src/miniflare-cli/README.md +0 -30
  148. package/src/miniflare-cli/assets.ts +0 -543
  149. package/src/miniflare-cli/enum-keys.ts +0 -17
  150. package/src/miniflare-cli/index.ts +0 -85
  151. package/src/miniflare-cli/request-context.ts +0 -40
  152. package/src/module-collection.ts +0 -258
  153. package/src/open-in-browser.ts +0 -17
  154. package/src/package-manager.ts +0 -219
  155. package/src/pages/build.tsx +0 -204
  156. package/src/pages/constants.ts +0 -8
  157. package/src/pages/deployments.tsx +0 -106
  158. package/src/pages/dev.tsx +0 -414
  159. package/src/pages/functions/buildPlugin.ts +0 -105
  160. package/src/pages/functions/buildWorker.ts +0 -151
  161. package/src/pages/functions/filepath-routing.test.ts +0 -234
  162. package/src/pages/functions/filepath-routing.ts +0 -189
  163. package/src/pages/functions/identifiers.ts +0 -78
  164. package/src/pages/functions/routes.ts +0 -151
  165. package/src/pages/index.tsx +0 -84
  166. package/src/pages/projects.tsx +0 -163
  167. package/src/pages/publish.tsx +0 -338
  168. package/src/pages/types.ts +0 -40
  169. package/src/pages/upload.tsx +0 -415
  170. package/src/pages/utils.ts +0 -12
  171. package/src/parse.ts +0 -286
  172. package/src/paths.ts +0 -26
  173. package/src/preview.ts +0 -31
  174. package/src/proxy.ts +0 -476
  175. package/src/publish.ts +0 -807
  176. package/src/pubsub/index.ts +0 -286
  177. package/src/pubsub/pubsub-commands.tsx +0 -623
  178. package/src/r2.ts +0 -118
  179. package/src/selfsigned.d.ts +0 -29
  180. package/src/sites.tsx +0 -372
  181. package/src/tail/filters.ts +0 -279
  182. package/src/tail/index.ts +0 -299
  183. package/src/tail/printing.ts +0 -67
  184. package/src/update-check.ts +0 -19
  185. package/src/user/choose-account.tsx +0 -69
  186. package/src/user/env-vars.ts +0 -46
  187. package/src/user/generate-auth-url.ts +0 -33
  188. package/src/user/generate-random-state.ts +0 -16
  189. package/src/user/index.ts +0 -3
  190. package/src/user/user.tsx +0 -1189
  191. package/src/whoami.tsx +0 -169
  192. package/src/worker-namespace.ts +0 -206
  193. package/src/worker.ts +0 -203
  194. package/src/zones.ts +0 -76
  195. package/templates/first-party-worker-module-facade.ts +0 -18
  196. package/templates/format-dev-errors.ts +0 -32
  197. package/templates/serve-static-assets.ts +0 -63
  198. package/templates/service-bindings-module-facade.js +0 -51
  199. package/templates/service-bindings-sw-facade.js +0 -39
package/src/index.tsx DELETED
@@ -1,2184 +0,0 @@
1
- import * as fs from "node:fs";
2
- import path from "node:path";
3
- import * as stream from "node:stream";
4
- import { StringDecoder } from "node:string_decoder";
5
- import { setTimeout } from "node:timers/promises";
6
- import TOML from "@iarna/toml";
7
- import chalk from "chalk";
8
- import onExit from "signal-exit";
9
- import supportsColor from "supports-color";
10
- import { setGlobalDispatcher, ProxyAgent } from "undici";
11
- import makeCLI from "yargs";
12
- import { version as wranglerVersion } from "../package.json";
13
- import { fetchResult } from "./cfetch";
14
- import { findWranglerToml, readConfig } from "./config";
15
- import { createWorkerUploadForm } from "./create-worker-upload-form";
16
- import { devHandler, devOptions } from "./dev";
17
- import { confirm, prompt } from "./dialogs";
18
- import { getEntry } from "./entry";
19
- import { DeprecationError } from "./errors";
20
- import { generateHandler, generateOptions } from "./generate";
21
- import { initOptions, initHandler } from "./init";
22
- import {
23
- getKVNamespaceId,
24
- listKVNamespaces,
25
- listKVNamespaceKeys,
26
- putKVKeyValue,
27
- putKVBulkKeyValue,
28
- deleteKVBulkKeyValue,
29
- createKVNamespace,
30
- isValidKVNamespaceBinding,
31
- getKVKeyValue,
32
- isKVKeyValue,
33
- unexpectedKVKeyValueProps,
34
- deleteKVNamespace,
35
- deleteKVKeyValue,
36
- } from "./kv";
37
- import { logger } from "./logger";
38
- import * as metrics from "./metrics";
39
- import { pages } from "./pages";
40
- import {
41
- formatMessage,
42
- ParseError,
43
- parseJSON,
44
- readFileSync,
45
- readFileSyncToBuffer,
46
- } from "./parse";
47
- import { previewHandler, previewOptions } from "./preview";
48
- import publish from "./publish";
49
- import { pubSubCommands } from "./pubsub/pubsub-commands";
50
- import {
51
- bucketAndKeyFromObjectPath,
52
- createR2Bucket,
53
- deleteR2Bucket,
54
- getR2Object,
55
- listR2Buckets,
56
- putR2Object,
57
- } from "./r2";
58
- import { getAssetPaths, getSiteAssetPaths } from "./sites";
59
- import {
60
- createTail,
61
- jsonPrintLogs,
62
- prettyPrintLogs,
63
- translateCLICommandToFilterMessage,
64
- } from "./tail";
65
- import { updateCheck } from "./update-check";
66
- import {
67
- login,
68
- logout,
69
- listScopes,
70
- validateScopeKeys,
71
- requireAuth,
72
- } from "./user";
73
- import { whoami } from "./whoami";
74
-
75
- import { workerNamespaceCommands } from "./worker-namespace";
76
- import type { Config } from "./config";
77
- import type { KeyValue } from "./kv";
78
- import type { TailCLIFilters } from "./tail";
79
- import type { Readable } from "node:stream";
80
- import type { RawData } from "ws";
81
- import type { CommandModule } from "yargs";
82
- import type Yargs from "yargs";
83
-
84
- export type ConfigPath = string | undefined;
85
-
86
- const resetColor = "\x1b[0m";
87
- const fgGreenColor = "\x1b[32m";
88
- export const DEFAULT_LOCAL_PORT = 8787;
89
- export const DEFAULT_INSPECTOR_PORT = 9229;
90
-
91
- const proxy =
92
- process.env.https_proxy ||
93
- process.env.HTTPS_PROXY ||
94
- process.env.http_proxy ||
95
- process.env.HTTP_PROXY ||
96
- undefined;
97
-
98
- if (proxy) {
99
- setGlobalDispatcher(new ProxyAgent(proxy));
100
- }
101
-
102
- export function getRules(config: Config): Config["rules"] {
103
- const rules = config.rules ?? config.build?.upload?.rules ?? [];
104
-
105
- if (config.rules && config.build?.upload?.rules) {
106
- throw new Error(
107
- `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
108
- );
109
- }
110
-
111
- if (config.build?.upload?.rules) {
112
- logger.warn(
113
- `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:
114
-
115
- ${TOML.stringify({ rules: config.build.upload.rules })}`
116
- );
117
- }
118
- return rules;
119
- }
120
-
121
- export async function printWranglerBanner() {
122
- // Let's not print this in tests
123
- if (typeof jest !== "undefined") {
124
- return;
125
- }
126
-
127
- const text = ` ⛅️ wrangler ${wranglerVersion} ${await updateCheck()}`;
128
-
129
- logger.log(
130
- text +
131
- "\n" +
132
- (supportsColor.stdout
133
- ? chalk.hex("#FF8800")("-".repeat(text.length))
134
- : "-".repeat(text.length))
135
- );
136
- }
137
-
138
- export function isLegacyEnv(config: Config): boolean {
139
- // We only read from config here, because we've already accounted for
140
- // args["legacy-env"] in https://github.com/cloudflare/wrangler2/blob/b24aeb5722370c2e04bce97a84a1fa1e55725d79/packages/wrangler/src/config/validation.ts#L94-L98
141
- return config.legacy_env;
142
- }
143
-
144
- export function getScriptName(
145
- args: { name: string | undefined; env: string | undefined },
146
- config: Config
147
- ): string | undefined {
148
- if (args.name && isLegacyEnv(config) && args.env) {
149
- throw new CommandLineArgsError(
150
- "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:" +
151
- `
152
- [env.${args.env}]
153
- name = "${args.name}"
154
- `
155
- );
156
- }
157
-
158
- return args.name ?? config.name;
159
- }
160
-
161
- /**
162
- * Alternative to the getScriptName() because special Legacy cases allowed "name", and "env" together in Wrangler1
163
- */
164
- function getLegacyScriptName(
165
- args: { name: string | undefined; env: string | undefined },
166
- config: Config
167
- ) {
168
- return args.name && args.env && isLegacyEnv(config)
169
- ? `${args.name}-${args.env}`
170
- : args.name ?? config.name;
171
- }
172
-
173
- /**
174
- * Get a promise to the streamed input from stdin.
175
- *
176
- * This function can be used to grab the incoming stream of data from, say,
177
- * piping the output of another process into the wrangler process.
178
- */
179
- function readFromStdin(): Promise<string> {
180
- return new Promise((resolve, reject) => {
181
- const stdin = process.stdin;
182
- const chunks: string[] = [];
183
-
184
- // When there is data ready to be read, the `readable` event will be triggered.
185
- // In the handler for `readable` we call `read()` over and over until all the available data has been read.
186
- stdin.on("readable", () => {
187
- let chunk;
188
- while (null !== (chunk = stdin.read())) {
189
- chunks.push(chunk);
190
- }
191
- });
192
-
193
- // When the streamed data is complete the `end` event will be triggered.
194
- // In the handler for `end` we join the chunks together and resolve the promise.
195
- stdin.on("end", () => {
196
- resolve(chunks.join(""));
197
- });
198
-
199
- // If there is an `error` event then the handler will reject the promise.
200
- stdin.on("error", (err) => {
201
- reject(err);
202
- });
203
- });
204
- }
205
-
206
- // a helper to demand one of a set of options
207
- // via https://github.com/yargs/yargs/issues/1093#issuecomment-491299261
208
- function demandOneOfOption(...options: string[]) {
209
- return function (argv: Yargs.Arguments) {
210
- const count = options.filter((option) => argv[option]).length;
211
- const lastOption = options.pop();
212
-
213
- if (count === 0) {
214
- throw new CommandLineArgsError(
215
- `Exactly one of the arguments ${options.join(
216
- ", "
217
- )} and ${lastOption} is required`
218
- );
219
- } else if (count > 1) {
220
- throw new CommandLineArgsError(
221
- `Arguments ${options.join(
222
- ", "
223
- )} and ${lastOption} are mutually exclusive`
224
- );
225
- }
226
-
227
- return true;
228
- };
229
- }
230
-
231
- /**
232
- * Remove trailing white space from inputs.
233
- * Matching Wrangler legacy behavior with handling inputs
234
- */
235
- function trimTrailingWhitespace(str: string) {
236
- return str.trimEnd();
237
- }
238
-
239
- export class CommandLineArgsError extends Error {}
240
-
241
- function createCLIParser(argv: string[]) {
242
- const wrangler = makeCLI(argv)
243
- .strict()
244
- // We handle errors ourselves in a try-catch around `yargs.parse`.
245
- // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
246
- // Otherwise we just log the error that was thrown without any "help info".
247
- .showHelpOnFail(false)
248
- .fail((msg, error) => {
249
- if (!error || error.name === "YError") {
250
- // If there is no error or the error is a "YError", then this came from yargs own validation
251
- // Wrap it in a `CommandLineArgsError` so that we can handle it appropriately further up.
252
- error = new CommandLineArgsError(msg);
253
- }
254
- throw error;
255
- })
256
- .scriptName("wrangler")
257
- .wrap(null);
258
-
259
- // Default help command that supports the subcommands
260
- const subHelp: CommandModule = {
261
- command: ["*"],
262
- handler: async (args) => {
263
- setImmediate(() =>
264
- wrangler.parse([...args._.map((a) => `${a}`), "--help"])
265
- );
266
- },
267
- };
268
- wrangler.command(
269
- ["*"],
270
- false,
271
- () => {},
272
- async (args) => {
273
- if (args._.length > 0) {
274
- throw new CommandLineArgsError(`Unknown command: ${args._}.`);
275
- } else {
276
- // args.v will exist and be true in the case that no command is called, and the -v
277
- // option is present. This is to allow for running asynchronous printWranglerBanner
278
- // in the version command.
279
- if (args.v) {
280
- if (process.stdout.isTTY) {
281
- await printWranglerBanner();
282
- } else {
283
- logger.log(wranglerVersion);
284
- }
285
- } else {
286
- wrangler.showHelp("log");
287
- }
288
- }
289
- }
290
- );
291
-
292
- // You will note that we use the form for all commands where we use the builder function
293
- // to define options and subcommands.
294
- // Further we return the result of this builder even though it's not completely necessary.
295
- // The reason is that it's required for type inference of the args in the handle function.
296
- // I wish we could enforce this pattern, but this comment will have to do for now.
297
- // (It's also annoying that choices[] doesn't get inferred as an enum. 🤷‍♂.)
298
-
299
- // [DEPRECATED] generate
300
- wrangler.command(
301
- // we definitely want to move away from us cloning github templates
302
- // we can do something better here, let's see
303
- "generate [name] [template]",
304
- false,
305
- generateOptions,
306
- generateHandler
307
- );
308
-
309
- // init
310
- wrangler.command(
311
- "init [name]",
312
- "📥 Create a wrangler.toml configuration file",
313
- initOptions,
314
- initHandler
315
- );
316
-
317
- // build
318
- wrangler.command(
319
- "build",
320
- false,
321
- (yargs) => {
322
- return yargs.option("env", {
323
- describe: "Perform on a specific environment",
324
- type: "string",
325
- });
326
- },
327
- async (buildArgs) => {
328
- // "[DEPRECATED] 🦀 Build your project (if applicable)",
329
-
330
- const envFlag = buildArgs.env ? ` --env=${buildArgs.env}` : "";
331
- logger.log(
332
- formatMessage({
333
- kind: "warning",
334
- text: "Deprecation: `wrangler build` has been deprecated.",
335
- notes: [
336
- {
337
- text: "Please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#build for more information.",
338
- },
339
- {
340
- text: `Attempting to run \`wrangler publish --dry-run --outdir=dist${envFlag}\` for you instead:`,
341
- },
342
- ],
343
- })
344
- );
345
-
346
- await createCLIParser([
347
- "publish",
348
- "--dry-run",
349
- "--outdir=dist",
350
- ...(buildArgs.env ? ["--env", buildArgs.env] : []),
351
- ]).parse();
352
- }
353
- );
354
-
355
- // config
356
- wrangler.command(
357
- "config",
358
- false,
359
- () => {},
360
- () => {
361
- // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
362
- throw new DeprecationError(
363
- "`wrangler config` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#config for alternatives"
364
- );
365
- }
366
- );
367
-
368
- // dev
369
- wrangler.command(
370
- "dev [script]",
371
- "👂 Start a local server for developing your worker",
372
- devOptions,
373
- devHandler
374
- );
375
-
376
- // publish
377
- wrangler.command(
378
- "publish [script]",
379
- "🆙 Publish your Worker to Cloudflare.",
380
- (yargs) => {
381
- return (
382
- yargs
383
- .option("env", {
384
- type: "string",
385
- requiresArg: true,
386
- describe: "Perform on a specific environment",
387
- alias: "e",
388
- })
389
- .positional("script", {
390
- describe: "The path to an entry point for your worker",
391
- type: "string",
392
- requiresArg: true,
393
- })
394
- .option("name", {
395
- describe: "Name of the worker",
396
- type: "string",
397
- requiresArg: true,
398
- })
399
- // We want to have a --no-bundle flag, but yargs requires that
400
- // we also have a --bundle flag (that it adds the --no to by itself)
401
- // So we make a --bundle flag, but hide it, and then add a --no-bundle flag
402
- // that's visible to the user but doesn't "do" anything.
403
- .option("bundle", {
404
- describe: "Run wrangler's compilation step before publishing",
405
- type: "boolean",
406
- hidden: true,
407
- })
408
- .option("no-bundle", {
409
- describe: "Skip internal build steps and directly publish Worker",
410
- type: "boolean",
411
- default: false,
412
- })
413
- .option("outdir", {
414
- describe: "Output directory for the bundled worker",
415
- type: "string",
416
- requiresArg: true,
417
- })
418
- .option("format", {
419
- choices: ["modules", "service-worker"] as const,
420
- describe: "Choose an entry type",
421
- deprecated: true,
422
- })
423
- .option("compatibility-date", {
424
- describe: "Date to use for compatibility checks",
425
- type: "string",
426
- requiresArg: true,
427
- })
428
- .option("compatibility-flags", {
429
- describe: "Flags to use for compatibility checks",
430
- alias: "compatibility-flag",
431
- type: "string",
432
- requiresArg: true,
433
- array: true,
434
- })
435
- .option("latest", {
436
- describe: "Use the latest version of the worker runtime",
437
- type: "boolean",
438
- default: false,
439
- })
440
- .option("experimental-public", {
441
- describe: "Static assets to be served",
442
- type: "string",
443
- requiresArg: true,
444
- deprecated: true,
445
- hidden: true,
446
- })
447
- .option("assets", {
448
- describe: "Static assets to be served",
449
- type: "string",
450
- requiresArg: true,
451
- })
452
- .option("site", {
453
- describe: "Root folder of static assets for Workers Sites",
454
- type: "string",
455
- requiresArg: true,
456
- })
457
- .option("site-include", {
458
- describe:
459
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
460
- type: "string",
461
- requiresArg: true,
462
- array: true,
463
- })
464
- .option("site-exclude", {
465
- describe:
466
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
467
- type: "string",
468
- requiresArg: true,
469
- array: true,
470
- })
471
- .option("triggers", {
472
- describe: "cron schedules to attach",
473
- alias: ["schedule", "schedules"],
474
- type: "string",
475
- requiresArg: true,
476
- array: true,
477
- })
478
- .option("routes", {
479
- describe: "Routes to upload",
480
- alias: "route",
481
- type: "string",
482
- requiresArg: true,
483
- array: true,
484
- })
485
- .option("jsx-factory", {
486
- describe: "The function that is called for each JSX element",
487
- type: "string",
488
- requiresArg: true,
489
- })
490
- .option("jsx-fragment", {
491
- describe: "The function that is called for each JSX fragment",
492
- type: "string",
493
- requiresArg: true,
494
- })
495
- .option("tsconfig", {
496
- describe: "Path to a custom tsconfig.json file",
497
- type: "string",
498
- requiresArg: true,
499
- })
500
- .option("minify", {
501
- describe: "Minify the Worker",
502
- type: "boolean",
503
- })
504
- .option("node-compat", {
505
- describe: "Enable node.js compatibility",
506
- type: "boolean",
507
- })
508
- .option("dry-run", {
509
- describe: "Don't actually publish",
510
- type: "boolean",
511
- })
512
- .option("legacy-env", {
513
- type: "boolean",
514
- describe: "Use legacy environments",
515
- hidden: true,
516
- })
517
- );
518
- },
519
- async (args) => {
520
- await printWranglerBanner();
521
-
522
- const configPath =
523
- (args.config as ConfigPath) ||
524
- (args.script && findWranglerToml(path.dirname(args.script)));
525
- const config = readConfig(configPath, args);
526
- const entry = await getEntry(args, config, "publish");
527
- await metrics.sendMetricsEvent(
528
- "deploy worker script",
529
- {
530
- usesTypeScript: /\.tsx?$/.test(entry.file),
531
- },
532
- {
533
- sendMetrics: config.send_metrics,
534
- }
535
- );
536
-
537
- if (args.public) {
538
- throw new Error("The --public field has been renamed to --assets");
539
- }
540
- if (args["experimental-public"]) {
541
- throw new Error(
542
- "The --experimental-public field has been renamed to --assets"
543
- );
544
- }
545
-
546
- if ((args.assets || config.assets) && (args.site || config.site)) {
547
- throw new Error(
548
- "Cannot use Assets and Workers Sites in the same Worker."
549
- );
550
- }
551
-
552
- if (args.assets) {
553
- logger.warn(
554
- "The --assets argument is experimental and may change or break at any time"
555
- );
556
- }
557
-
558
- if (args.latest) {
559
- logger.warn(
560
- "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"
561
- );
562
- }
563
-
564
- const accountId = args.dryRun ? undefined : await requireAuth(config);
565
-
566
- const assetPaths =
567
- args.assets || config.assets
568
- ? getAssetPaths(config, args.assets)
569
- : getSiteAssetPaths(
570
- config,
571
- args.site,
572
- args.siteInclude,
573
- args.siteExclude
574
- );
575
-
576
- await publish({
577
- config,
578
- accountId,
579
- name: getScriptName(args, config),
580
- rules: getRules(config),
581
- entry,
582
- env: args.env,
583
- compatibilityDate: args.latest
584
- ? new Date().toISOString().substring(0, 10)
585
- : args["compatibility-date"],
586
- compatibilityFlags: args["compatibility-flags"],
587
- triggers: args.triggers,
588
- jsxFactory: args["jsx-factory"],
589
- jsxFragment: args["jsx-fragment"],
590
- tsconfig: args.tsconfig,
591
- routes: args.routes,
592
- assetPaths,
593
- legacyEnv: isLegacyEnv(config),
594
- minify: args.minify,
595
- nodeCompat: args.nodeCompat,
596
- isWorkersSite: Boolean(args.site || config.site),
597
- outDir: args.outdir,
598
- dryRun: args.dryRun,
599
- noBundle: !(args.bundle ?? !config.no_bundle),
600
- });
601
- }
602
- );
603
-
604
- // tail
605
- wrangler.command(
606
- "tail [name]",
607
- "🦚 Starts a log tailing session for a published Worker.",
608
- (yargs) => {
609
- return yargs
610
- .positional("name", {
611
- describe: "Name of the worker",
612
- type: "string",
613
- })
614
- .option("format", {
615
- default: process.stdout.isTTY ? "pretty" : "json",
616
- choices: ["json", "pretty"],
617
- describe: "The format of log entries",
618
- })
619
- .option("status", {
620
- choices: ["ok", "error", "canceled"],
621
- describe: "Filter by invocation status",
622
- array: true,
623
- })
624
- .option("header", {
625
- type: "string",
626
- requiresArg: true,
627
- describe: "Filter by HTTP header",
628
- })
629
- .option("method", {
630
- type: "string",
631
- requiresArg: true,
632
- describe: "Filter by HTTP method",
633
- array: true,
634
- })
635
- .option("sampling-rate", {
636
- type: "number",
637
- describe: "Adds a percentage of requests to log sampling rate",
638
- })
639
- .option("search", {
640
- type: "string",
641
- requiresArg: true,
642
- describe: "Filter by a text match in console.log messages",
643
- })
644
- .option("ip", {
645
- type: "string",
646
- requiresArg: true,
647
- describe:
648
- 'Filter by the IP address the request originates from. Use "self" to filter for your own IP',
649
- array: true,
650
- })
651
- .option("env", {
652
- type: "string",
653
- requiresArg: true,
654
- describe: "Perform on a specific environment",
655
- alias: "e",
656
- })
657
- .option("debug", {
658
- type: "boolean",
659
- hidden: true,
660
- default: false,
661
- describe:
662
- "If a log would have been filtered out, send it through anyway alongside the filter which would have blocked it.",
663
- })
664
- .option("legacy-env", {
665
- type: "boolean",
666
- describe: "Use legacy environments",
667
- hidden: true,
668
- });
669
- },
670
- async (args) => {
671
- if (args.format === "pretty") {
672
- await printWranglerBanner();
673
- }
674
- const config = readConfig(args.config as ConfigPath, args);
675
- await metrics.sendMetricsEvent("begin log stream", {
676
- sendMetrics: config.send_metrics,
677
- });
678
-
679
- const scriptName = getLegacyScriptName(args, config);
680
-
681
- if (!scriptName) {
682
- throw new Error(
683
- "Required Worker name missing. Please specify the Worker name in wrangler.toml, or pass it as an argument with `wrangler tail <worker-name>`"
684
- );
685
- }
686
-
687
- const accountId = await requireAuth(config);
688
-
689
- const cliFilters: TailCLIFilters = {
690
- status: args.status as ("ok" | "error" | "canceled")[] | undefined,
691
- header: args.header,
692
- method: args.method,
693
- samplingRate: args["sampling-rate"],
694
- search: args.search,
695
- clientIp: args.ip,
696
- };
697
-
698
- const filters = translateCLICommandToFilterMessage(
699
- cliFilters,
700
- args.debug
701
- );
702
-
703
- const { tail, expiration, deleteTail } = await createTail(
704
- accountId,
705
- scriptName,
706
- filters,
707
- !isLegacyEnv(config) ? args.env : undefined
708
- );
709
-
710
- const scriptDisplayName = `${scriptName}${
711
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
712
- }`;
713
-
714
- if (args.format === "pretty") {
715
- logger.log(
716
- `Successfully created tail, expires at ${expiration.toLocaleString()}`
717
- );
718
- }
719
-
720
- onExit(async () => {
721
- tail.terminate();
722
- await deleteTail();
723
- await metrics.sendMetricsEvent("end log stream", {
724
- sendMetrics: config.send_metrics,
725
- });
726
- });
727
-
728
- const printLog: (data: RawData) => void =
729
- args.format === "pretty" ? prettyPrintLogs : jsonPrintLogs;
730
-
731
- tail.on("message", printLog);
732
-
733
- while (tail.readyState !== tail.OPEN) {
734
- switch (tail.readyState) {
735
- case tail.CONNECTING:
736
- await setTimeout(100);
737
- break;
738
- case tail.CLOSING:
739
- await setTimeout(100);
740
- break;
741
- case tail.CLOSED:
742
- await metrics.sendMetricsEvent("end log stream", {
743
- sendMetrics: config.send_metrics,
744
- });
745
- throw new Error(
746
- `Connection to ${scriptDisplayName} closed unexpectedly.`
747
- );
748
- }
749
- }
750
-
751
- if (args.format === "pretty") {
752
- logger.log(`Connected to ${scriptDisplayName}, waiting for logs...`);
753
- }
754
-
755
- tail.on("close", async () => {
756
- tail.terminate();
757
- await deleteTail();
758
- await metrics.sendMetricsEvent("end log stream", {
759
- sendMetrics: config.send_metrics,
760
- });
761
- });
762
- }
763
- );
764
-
765
- // preview
766
- wrangler.command(
767
- "preview [method] [body]",
768
- false,
769
- previewOptions,
770
- previewHandler
771
- );
772
-
773
- // [DEPRECATED] route
774
- wrangler.command(
775
- "route",
776
- false, // I think we want to hide this command
777
- // "➡️ List or delete worker routes",
778
- (routeYargs) => {
779
- return routeYargs
780
- .command(
781
- "list",
782
- "List the routes associated with a zone",
783
- (yargs) => {
784
- return yargs
785
- .option("env", {
786
- type: "string",
787
- requiresArg: true,
788
- describe: "Perform on a specific environment",
789
- })
790
- .option("zone", {
791
- type: "string",
792
- requiresArg: true,
793
- describe: "Zone id",
794
- })
795
- .positional("zone", {
796
- describe: "Zone id",
797
- type: "string",
798
- });
799
- },
800
- () => {
801
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
802
- const deprecationNotice =
803
- "`wrangler route list` has been deprecated.";
804
- const futureRoutes =
805
- "Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.";
806
- const presentRoutes =
807
- "Refer to the Cloudflare Dashboard to see the routes this worker is currently running on.";
808
- throw new DeprecationError(
809
- `${deprecationNotice}\n${futureRoutes}\n${presentRoutes}`
810
- );
811
- }
812
- )
813
- .command(
814
- "delete [id]",
815
- "Delete a route associated with a zone",
816
- (yargs) => {
817
- return yargs
818
- .positional("id", {
819
- describe: "The hash of the route ID to delete.",
820
- type: "string",
821
- })
822
- .option("zone", {
823
- type: "string",
824
- requiresArg: true,
825
- describe: "zone id",
826
- })
827
- .option("env", {
828
- type: "string",
829
- requiresArg: true,
830
- describe: "Perform on a specific environment",
831
- });
832
- },
833
- () => {
834
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
835
- const deprecationNotice =
836
- "`wrangler route delete` has been deprecated.";
837
- const shouldDo =
838
- "Remove the unwanted route(s) from wrangler.toml and run `wrangler publish` to remove your worker from those routes.";
839
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
840
- }
841
- );
842
- },
843
- () => {
844
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
845
- const deprecationNotice = "`wrangler route` has been deprecated.";
846
- const shouldDo =
847
- "Please use wrangler.toml and/or `wrangler publish --routes` to modify routes";
848
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
849
- }
850
- );
851
-
852
- // subdomain
853
- wrangler.command(
854
- "subdomain [name]",
855
- false,
856
- // "👷 Create or change your workers.dev subdomain.",
857
- (yargs) => {
858
- return yargs.positional("name", { type: "string" });
859
- },
860
- () => {
861
- throw new DeprecationError(
862
- "`wrangler subdomain` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#subdomain for alternatives"
863
- );
864
- }
865
- );
866
-
867
- // secret
868
- wrangler.command(
869
- "secret",
870
- "🤫 Generate a secret that can be referenced in a Worker",
871
- (secretYargs) => {
872
- return secretYargs
873
- .command(subHelp)
874
- .option("legacy-env", {
875
- type: "boolean",
876
- describe: "Use legacy environments",
877
- hidden: true,
878
- })
879
- .command(
880
- "put <key>",
881
- "Create or update a secret variable for a Worker",
882
- (yargs) => {
883
- return yargs
884
- .positional("key", {
885
- describe: "The variable name to be accessible in the Worker",
886
- type: "string",
887
- })
888
- .option("name", {
889
- describe: "Name of the Worker",
890
- type: "string",
891
- requiresArg: true,
892
- })
893
- .option("env", {
894
- type: "string",
895
- requiresArg: true,
896
- describe:
897
- "Binds the secret to the Worker of the specific environment",
898
- alias: "e",
899
- });
900
- },
901
- async (args) => {
902
- await printWranglerBanner();
903
- const config = readConfig(args.config as ConfigPath, args);
904
-
905
- const scriptName = getLegacyScriptName(args, config);
906
- if (!scriptName) {
907
- throw new Error(
908
- "Required Worker name missing. Please specify the Worker name in wrangler.toml, or pass it as an argument with `--name <worker-name>`"
909
- );
910
- }
911
-
912
- const accountId = await requireAuth(config);
913
-
914
- const isInteractive = process.stdin.isTTY;
915
- const secretValue = trimTrailingWhitespace(
916
- isInteractive
917
- ? await prompt("Enter a secret value:", "password")
918
- : await readFromStdin()
919
- );
920
-
921
- logger.log(
922
- `🌀 Creating the secret for the Worker "${scriptName}" ${
923
- args.env && !isLegacyEnv(config) ? `(${args.env})` : ""
924
- }`
925
- );
926
-
927
- async function submitSecret() {
928
- const url =
929
- !args.env || isLegacyEnv(config)
930
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
931
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
932
-
933
- return await fetchResult(url, {
934
- method: "PUT",
935
- headers: { "Content-Type": "application/json" },
936
- body: JSON.stringify({
937
- name: args.key,
938
- text: secretValue,
939
- type: "secret_text",
940
- }),
941
- });
942
- }
943
-
944
- const createDraftWorker = async () => {
945
- // TODO: log a warning
946
- await fetchResult(
947
- !isLegacyEnv(config) && args.env
948
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}`
949
- : `/accounts/${accountId}/workers/scripts/${scriptName}`,
950
- {
951
- method: "PUT",
952
- body: createWorkerUploadForm({
953
- name: scriptName,
954
- main: {
955
- name: scriptName,
956
- content: `export default { fetch() {} }`,
957
- type: "esm",
958
- },
959
- bindings: {
960
- kv_namespaces: [],
961
- vars: {},
962
- durable_objects: { bindings: [] },
963
- r2_buckets: [],
964
- services: [],
965
- wasm_modules: {},
966
- text_blobs: {},
967
- data_blobs: {},
968
- worker_namespaces: [],
969
- logfwdr: { schema: undefined, bindings: [] },
970
- unsafe: [],
971
- },
972
- modules: [],
973
- migrations: undefined,
974
- compatibility_date: undefined,
975
- compatibility_flags: undefined,
976
- usage_model: undefined,
977
- }),
978
- }
979
- );
980
- };
981
-
982
- function isMissingWorkerError(e: unknown): e is { code: 10007 } {
983
- return (
984
- typeof e === "object" &&
985
- e !== null &&
986
- (e as { code: number }).code === 10007
987
- );
988
- }
989
-
990
- try {
991
- await submitSecret();
992
- await metrics.sendMetricsEvent("create encrypted variable", {
993
- sendMetrics: config.send_metrics,
994
- });
995
- } catch (e) {
996
- if (isMissingWorkerError(e)) {
997
- // create a draft worker and try again
998
- await createDraftWorker();
999
- await submitSecret();
1000
- // TODO: delete the draft worker if this failed too?
1001
- } else {
1002
- throw e;
1003
- }
1004
- }
1005
-
1006
- logger.log(`✨ Success! Uploaded secret ${args.key}`);
1007
- }
1008
- )
1009
- .command(
1010
- "delete <key>",
1011
- "Delete a secret variable from a Worker",
1012
- async (yargs) => {
1013
- await printWranglerBanner();
1014
- return yargs
1015
- .positional("key", {
1016
- describe: "The variable name to be accessible in the Worker",
1017
- type: "string",
1018
- })
1019
- .option("name", {
1020
- describe: "Name of the Worker",
1021
- type: "string",
1022
- requiresArg: true,
1023
- })
1024
- .option("env", {
1025
- type: "string",
1026
- requiresArg: true,
1027
- describe:
1028
- "Binds the secret to the Worker of the specific environment",
1029
- alias: "e",
1030
- });
1031
- },
1032
- async (args) => {
1033
- const config = readConfig(args.config as ConfigPath, args);
1034
-
1035
- const scriptName = getLegacyScriptName(args, config);
1036
- if (!scriptName) {
1037
- throw new Error(
1038
- "Required Worker name missing. Please specify the Worker name in wrangler.toml, or pass it as an argument with `--name <worker-name>`"
1039
- );
1040
- }
1041
-
1042
- const accountId = await requireAuth(config);
1043
-
1044
- if (
1045
- await confirm(
1046
- `Are you sure you want to permanently delete the secret ${
1047
- args.key
1048
- } on the Worker ${scriptName}${
1049
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1050
- }?`
1051
- )
1052
- ) {
1053
- logger.log(
1054
- `🌀 Deleting the secret ${
1055
- args.key
1056
- } on the Worker ${scriptName}${
1057
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1058
- }`
1059
- );
1060
-
1061
- const url =
1062
- !args.env || isLegacyEnv(config)
1063
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1064
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1065
-
1066
- await fetchResult(`${url}/${args.key}`, { method: "DELETE" });
1067
- await metrics.sendMetricsEvent("delete encrypted variable", {
1068
- sendMetrics: config.send_metrics,
1069
- });
1070
- logger.log(`✨ Success! Deleted secret ${args.key}`);
1071
- }
1072
- }
1073
- )
1074
- .command(
1075
- "list",
1076
- "List all secrets for a Worker",
1077
- (yargs) => {
1078
- return yargs
1079
- .option("name", {
1080
- describe: "Name of the Worker",
1081
- type: "string",
1082
- requiresArg: true,
1083
- })
1084
- .option("env", {
1085
- type: "string",
1086
- requiresArg: true,
1087
- describe:
1088
- "Binds the secret to the Worker of the specific environment.",
1089
- alias: "e",
1090
- });
1091
- },
1092
- async (args) => {
1093
- const config = readConfig(args.config as ConfigPath, args);
1094
-
1095
- const scriptName = getLegacyScriptName(args, config);
1096
- if (!scriptName) {
1097
- throw new Error(
1098
- "Required Worker name missing. Please specify the Worker name in wrangler.toml, or pass it as an argument with `--name <worker-name>`"
1099
- );
1100
- }
1101
-
1102
- const accountId = await requireAuth(config);
1103
-
1104
- const url =
1105
- !args.env || isLegacyEnv(config)
1106
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1107
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1108
-
1109
- logger.log(JSON.stringify(await fetchResult(url), null, " "));
1110
- await metrics.sendMetricsEvent("list encrypted variables", {
1111
- sendMetrics: config.send_metrics,
1112
- });
1113
- }
1114
- );
1115
- }
1116
- );
1117
-
1118
- // kv
1119
- // :namespace
1120
- wrangler.command(
1121
- "kv:namespace",
1122
- "🗂️ Interact with your Workers KV Namespaces",
1123
- (namespaceYargs) => {
1124
- return namespaceYargs
1125
- .command(subHelp)
1126
- .command(
1127
- "create <namespace>",
1128
- "Create a new namespace",
1129
- (yargs) => {
1130
- return yargs
1131
- .positional("namespace", {
1132
- describe: "The name of the new namespace",
1133
- type: "string",
1134
- demandOption: true,
1135
- })
1136
- .option("env", {
1137
- type: "string",
1138
- requiresArg: true,
1139
- describe: "Perform on a specific environment",
1140
- alias: "e",
1141
- })
1142
- .option("preview", {
1143
- type: "boolean",
1144
- describe: "Interact with a preview namespace",
1145
- });
1146
- },
1147
- async (args) => {
1148
- await printWranglerBanner();
1149
-
1150
- if (!isValidKVNamespaceBinding(args.namespace)) {
1151
- throw new CommandLineArgsError(
1152
- `The namespace binding name "${args.namespace}" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.`
1153
- );
1154
- }
1155
-
1156
- const config = readConfig(args.config as ConfigPath, args);
1157
- if (!config.name) {
1158
- logger.warn(
1159
- "No configured name present, using `worker` as a prefix for the title"
1160
- );
1161
- }
1162
-
1163
- const name = config.name || "worker";
1164
- const environment = args.env ? `-${args.env}` : "";
1165
- const preview = args.preview ? "_preview" : "";
1166
- const title = `${name}${environment}-${args.namespace}${preview}`;
1167
-
1168
- const accountId = await requireAuth(config);
1169
-
1170
- // TODO: generate a binding name stripping non alphanumeric chars
1171
-
1172
- logger.log(`🌀 Creating namespace with title "${title}"`);
1173
- const namespaceId = await createKVNamespace(accountId, title);
1174
- await metrics.sendMetricsEvent("create kv namespace", {
1175
- sendMetrics: config.send_metrics,
1176
- });
1177
-
1178
- logger.log("✨ Success!");
1179
- const envString = args.env ? ` under [env.${args.env}]` : "";
1180
- const previewString = args.preview ? "preview_" : "";
1181
- logger.log(
1182
- `Add the following to your configuration file in your kv_namespaces array${envString}:`
1183
- );
1184
- logger.log(
1185
- `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
1186
- );
1187
-
1188
- // TODO: automatically write this block to the wrangler.toml config file??
1189
- }
1190
- )
1191
- .command(
1192
- "list",
1193
- "Outputs a list of all KV namespaces associated with your account id.",
1194
- {},
1195
- async (args) => {
1196
- const config = readConfig(args.config as ConfigPath, args);
1197
-
1198
- const accountId = await requireAuth(config);
1199
-
1200
- // TODO: we should show bindings if they exist for given ids
1201
-
1202
- logger.log(
1203
- JSON.stringify(await listKVNamespaces(accountId), null, " ")
1204
- );
1205
- await metrics.sendMetricsEvent("list kv namespaces", {
1206
- sendMetrics: config.send_metrics,
1207
- });
1208
- }
1209
- )
1210
- .command(
1211
- "delete",
1212
- "Deletes a given namespace.",
1213
- (yargs) => {
1214
- return yargs
1215
- .option("binding", {
1216
- type: "string",
1217
- requiresArg: true,
1218
- describe: "The name of the namespace to delete",
1219
- })
1220
- .option("namespace-id", {
1221
- type: "string",
1222
- requiresArg: true,
1223
- describe: "The id of the namespace to delete",
1224
- })
1225
- .check(demandOneOfOption("binding", "namespace-id"))
1226
- .option("env", {
1227
- type: "string",
1228
- requiresArg: true,
1229
- describe: "Perform on a specific environment",
1230
- alias: "e",
1231
- })
1232
- .option("preview", {
1233
- type: "boolean",
1234
- describe: "Interact with a preview namespace",
1235
- });
1236
- },
1237
- async (args) => {
1238
- await printWranglerBanner();
1239
- const config = readConfig(args.config as ConfigPath, args);
1240
-
1241
- let id;
1242
- try {
1243
- id = getKVNamespaceId(args, config);
1244
- } catch (e) {
1245
- throw new CommandLineArgsError(
1246
- "Not able to delete namespace.\n" + ((e as Error).message ?? e)
1247
- );
1248
- }
1249
-
1250
- const accountId = await requireAuth(config);
1251
-
1252
- logger.log(`Deleting KV namespace ${id}.`);
1253
- await deleteKVNamespace(accountId, id);
1254
- logger.log(`Deleted KV namespace ${id}.`);
1255
- await metrics.sendMetricsEvent("delete kv namespace", {
1256
- sendMetrics: config.send_metrics,
1257
- });
1258
-
1259
- // TODO: recommend they remove it from wrangler.toml
1260
-
1261
- // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1262
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1263
- // n
1264
- // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1265
- // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1266
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1267
- // y
1268
- // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1269
- // ✨ Success
1270
- // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
1271
- // ➜ test-mf
1272
-
1273
- // TODO: do it automatically
1274
-
1275
- // TODO: delete the preview namespace as well?
1276
- }
1277
- );
1278
- }
1279
- );
1280
-
1281
- // :key
1282
- wrangler.command(
1283
- "kv:key",
1284
- "🔑 Individually manage Workers KV key-value pairs",
1285
- (kvKeyYargs) => {
1286
- return kvKeyYargs
1287
- .command(subHelp)
1288
- .command(
1289
- "put <key> [value]",
1290
- "Writes a single key/value pair to the given namespace.",
1291
- (yargs) => {
1292
- return yargs
1293
- .positional("key", {
1294
- type: "string",
1295
- describe: "The key to write to",
1296
- demandOption: true,
1297
- })
1298
- .positional("value", {
1299
- type: "string",
1300
- describe: "The value to write",
1301
- })
1302
- .option("binding", {
1303
- type: "string",
1304
- requiresArg: true,
1305
- describe: "The binding of the namespace to write to",
1306
- })
1307
- .option("namespace-id", {
1308
- type: "string",
1309
- requiresArg: true,
1310
- describe: "The id of the namespace to write to",
1311
- })
1312
- .check(demandOneOfOption("binding", "namespace-id"))
1313
- .option("env", {
1314
- type: "string",
1315
- requiresArg: true,
1316
- describe: "Perform on a specific environment",
1317
- alias: "e",
1318
- })
1319
- .option("preview", {
1320
- type: "boolean",
1321
- describe: "Interact with a preview namespace",
1322
- })
1323
- .option("ttl", {
1324
- type: "number",
1325
- describe: "Time for which the entries should be visible",
1326
- })
1327
- .option("expiration", {
1328
- type: "number",
1329
- describe:
1330
- "Time since the UNIX epoch after which the entry expires",
1331
- })
1332
- .option("metadata", {
1333
- type: "string",
1334
- describe: "Arbitrary JSON that is associated with a key",
1335
- coerce: (jsonStr: string): KeyValue["metadata"] => {
1336
- try {
1337
- return JSON.parse(jsonStr);
1338
- } catch (_) {}
1339
- },
1340
- })
1341
- .option("path", {
1342
- type: "string",
1343
- requiresArg: true,
1344
- describe: "Read value from the file at a given path",
1345
- })
1346
- .check(demandOneOfOption("value", "path"));
1347
- },
1348
- async ({ key, ttl, expiration, metadata, ...args }) => {
1349
- await printWranglerBanner();
1350
- const config = readConfig(args.config as ConfigPath, args);
1351
- const namespaceId = getKVNamespaceId(args, config);
1352
- // One of `args.path` and `args.value` must be defined
1353
- const value = args.path
1354
- ? readFileSyncToBuffer(args.path)
1355
- : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1356
- args.value!;
1357
-
1358
- const metadataLog = metadata
1359
- ? ` with metadata "${JSON.stringify(metadata)}"`
1360
- : "";
1361
-
1362
- if (args.path) {
1363
- logger.log(
1364
- `Writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}${metadataLog}.`
1365
- );
1366
- } else {
1367
- logger.log(
1368
- `Writing the value "${value}" to key "${key}" on namespace ${namespaceId}${metadataLog}.`
1369
- );
1370
- }
1371
-
1372
- const accountId = await requireAuth(config);
1373
-
1374
- await putKVKeyValue(accountId, namespaceId, {
1375
- key,
1376
- value,
1377
- expiration,
1378
- expiration_ttl: ttl,
1379
- metadata: metadata as KeyValue["metadata"],
1380
- });
1381
- await metrics.sendMetricsEvent("write kv key-value", {
1382
- sendMetrics: config.send_metrics,
1383
- });
1384
- }
1385
- )
1386
- .command(
1387
- "list",
1388
- "Outputs a list of all keys in a given namespace.",
1389
- (yargs) => {
1390
- return yargs
1391
- .option("binding", {
1392
- type: "string",
1393
- requiresArg: true,
1394
- describe: "The name of the namespace to list",
1395
- })
1396
- .option("namespace-id", {
1397
- type: "string",
1398
- requiresArg: true,
1399
- describe: "The id of the namespace to list",
1400
- })
1401
- .check(demandOneOfOption("binding", "namespace-id"))
1402
- .option("env", {
1403
- type: "string",
1404
- requiresArg: true,
1405
- describe: "Perform on a specific environment",
1406
- alias: "e",
1407
- })
1408
- .option("preview", {
1409
- type: "boolean",
1410
- // In the case of listing keys we will default to non-preview mode
1411
- default: false,
1412
- describe: "Interact with a preview namespace",
1413
- })
1414
- .option("prefix", {
1415
- type: "string",
1416
- requiresArg: true,
1417
- describe: "A prefix to filter listed keys",
1418
- });
1419
- },
1420
- async ({ prefix, ...args }) => {
1421
- // TODO: support for limit+cursor (pagination)
1422
- const config = readConfig(args.config as ConfigPath, args);
1423
- const namespaceId = getKVNamespaceId(args, config);
1424
-
1425
- const accountId = await requireAuth(config);
1426
-
1427
- const results = await listKVNamespaceKeys(
1428
- accountId,
1429
- namespaceId,
1430
- prefix
1431
- );
1432
- logger.log(JSON.stringify(results, undefined, 2));
1433
- await metrics.sendMetricsEvent("list kv keys", {
1434
- sendMetrics: config.send_metrics,
1435
- });
1436
- }
1437
- )
1438
- .command(
1439
- "get <key>",
1440
- "Reads a single value by key from the given namespace.",
1441
- (yargs) => {
1442
- return yargs
1443
- .positional("key", {
1444
- describe: "The key value to get.",
1445
- type: "string",
1446
- demandOption: true,
1447
- })
1448
- .option("binding", {
1449
- type: "string",
1450
- requiresArg: true,
1451
- describe: "The name of the namespace to get from",
1452
- })
1453
- .option("namespace-id", {
1454
- type: "string",
1455
- requiresArg: true,
1456
- describe: "The id of the namespace to get from",
1457
- })
1458
- .check(demandOneOfOption("binding", "namespace-id"))
1459
- .option("env", {
1460
- type: "string",
1461
- requiresArg: true,
1462
- describe: "Perform on a specific environment",
1463
- alias: "e",
1464
- })
1465
- .option("preview", {
1466
- type: "boolean",
1467
- describe: "Interact with a preview namespace",
1468
- })
1469
- .option("preview", {
1470
- type: "boolean",
1471
- // In the case of getting key values we will default to non-preview mode
1472
- default: false,
1473
- describe: "Interact with a preview namespace",
1474
- })
1475
- .option("text", {
1476
- type: "boolean",
1477
- default: false,
1478
- describe: "Decode the returned value as a utf8 string",
1479
- });
1480
- },
1481
- async ({ key, ...args }) => {
1482
- const config = readConfig(args.config as ConfigPath, args);
1483
- const namespaceId = getKVNamespaceId(args, config);
1484
-
1485
- const accountId = await requireAuth(config);
1486
- const bufferKVValue = Buffer.from(
1487
- await getKVKeyValue(accountId, namespaceId, key)
1488
- );
1489
-
1490
- if (args.text) {
1491
- const decoder = new StringDecoder("utf8");
1492
- logger.log(decoder.write(bufferKVValue));
1493
- } else {
1494
- process.stdout.write(bufferKVValue);
1495
- }
1496
- await metrics.sendMetricsEvent("read kv value", {
1497
- sendMetrics: config.send_metrics,
1498
- });
1499
- }
1500
- )
1501
- .command(
1502
- "delete <key>",
1503
- "Removes a single key value pair from the given namespace.",
1504
- (yargs) => {
1505
- return yargs
1506
- .positional("key", {
1507
- describe: "The key value to delete",
1508
- type: "string",
1509
- demandOption: true,
1510
- })
1511
- .option("binding", {
1512
- type: "string",
1513
- requiresArg: true,
1514
- describe: "The name of the namespace to delete from",
1515
- })
1516
- .option("namespace-id", {
1517
- type: "string",
1518
- requiresArg: true,
1519
- describe: "The id of the namespace to delete from",
1520
- })
1521
- .check(demandOneOfOption("binding", "namespace-id"))
1522
- .option("env", {
1523
- type: "string",
1524
- requiresArg: true,
1525
- describe: "Perform on a specific environment",
1526
- alias: "e",
1527
- })
1528
- .option("preview", {
1529
- type: "boolean",
1530
- describe: "Interact with a preview namespace",
1531
- });
1532
- },
1533
- async ({ key, ...args }) => {
1534
- await printWranglerBanner();
1535
- const config = readConfig(args.config as ConfigPath, args);
1536
- const namespaceId = getKVNamespaceId(args, config);
1537
-
1538
- logger.log(
1539
- `Deleting the key "${key}" on namespace ${namespaceId}.`
1540
- );
1541
-
1542
- const accountId = await requireAuth(config);
1543
-
1544
- await deleteKVKeyValue(accountId, namespaceId, key);
1545
- await metrics.sendMetricsEvent("delete kv key-value", {
1546
- sendMetrics: config.send_metrics,
1547
- });
1548
- }
1549
- );
1550
- }
1551
- );
1552
-
1553
- // :bulk
1554
- wrangler.command(
1555
- "kv:bulk",
1556
- "💪 Interact with multiple Workers KV key-value pairs at once",
1557
- (kvBulkYargs) => {
1558
- return kvBulkYargs
1559
- .command(subHelp)
1560
- .command(
1561
- "put <filename>",
1562
- "Upload multiple key-value pairs to a namespace",
1563
- (yargs) => {
1564
- return yargs
1565
- .positional("filename", {
1566
- describe: `The JSON file of key-value pairs to upload, in form [{"key":..., "value":...}"...]`,
1567
- type: "string",
1568
- demandOption: true,
1569
- })
1570
- .option("binding", {
1571
- type: "string",
1572
- requiresArg: true,
1573
- describe: "The name of the namespace to insert values into",
1574
- })
1575
- .option("namespace-id", {
1576
- type: "string",
1577
- requiresArg: true,
1578
- describe: "The id of the namespace to insert values into",
1579
- })
1580
- .check(demandOneOfOption("binding", "namespace-id"))
1581
- .option("env", {
1582
- type: "string",
1583
- requiresArg: true,
1584
- describe: "Perform on a specific environment",
1585
- alias: "e",
1586
- })
1587
- .option("preview", {
1588
- type: "boolean",
1589
- describe: "Interact with a preview namespace",
1590
- });
1591
- },
1592
- async ({ filename, ...args }) => {
1593
- await printWranglerBanner();
1594
- // The simplest implementation I could think of.
1595
- // This could be made more efficient with a streaming parser/uploader
1596
- // but we'll do that in the future if needed.
1597
-
1598
- const config = readConfig(args.config as ConfigPath, args);
1599
- const namespaceId = getKVNamespaceId(args, config);
1600
- const content = parseJSON(readFileSync(filename), filename);
1601
-
1602
- if (!Array.isArray(content)) {
1603
- throw new Error(
1604
- `Unexpected JSON input from "${filename}".\n` +
1605
- `Expected an array of key-value objects but got type "${typeof content}".`
1606
- );
1607
- }
1608
-
1609
- const errors: string[] = [];
1610
- const warnings: string[] = [];
1611
- for (let i = 0; i < content.length; i++) {
1612
- const keyValue = content[i];
1613
- if (!isKVKeyValue(keyValue)) {
1614
- errors.push(
1615
- `The item at index ${i} is ${JSON.stringify(keyValue)}`
1616
- );
1617
- } else {
1618
- const props = unexpectedKVKeyValueProps(keyValue);
1619
- if (props.length > 0) {
1620
- warnings.push(
1621
- `The item at index ${i} contains unexpected properties: ${JSON.stringify(
1622
- props
1623
- )}.`
1624
- );
1625
- }
1626
- }
1627
- }
1628
- if (warnings.length > 0) {
1629
- logger.warn(
1630
- `Unexpected key-value properties in "${filename}".\n` +
1631
- warnings.join("\n")
1632
- );
1633
- }
1634
- if (errors.length > 0) {
1635
- throw new Error(
1636
- `Unexpected JSON input from "${filename}".\n` +
1637
- `Each item in the array should be an object that matches:\n\n` +
1638
- `interface KeyValue {\n` +
1639
- ` key: string;\n` +
1640
- ` value: string;\n` +
1641
- ` expiration?: number;\n` +
1642
- ` expiration_ttl?: number;\n` +
1643
- ` metadata?: object;\n` +
1644
- ` base64?: boolean;\n` +
1645
- `}\n\n` +
1646
- errors.join("\n")
1647
- );
1648
- }
1649
-
1650
- const accountId = await requireAuth(config);
1651
- await putKVBulkKeyValue(accountId, namespaceId, content);
1652
- await metrics.sendMetricsEvent("write kv key-values (bulk)", {
1653
- sendMetrics: config.send_metrics,
1654
- });
1655
-
1656
- logger.log("Success!");
1657
- }
1658
- )
1659
- .command(
1660
- "delete <filename>",
1661
- "Delete multiple key-value pairs from a namespace",
1662
- (yargs) => {
1663
- return yargs
1664
- .positional("filename", {
1665
- describe: `The JSON file of keys to delete, in the form ["key1", "key2", ...]`,
1666
- type: "string",
1667
- demandOption: true,
1668
- })
1669
- .option("binding", {
1670
- type: "string",
1671
- requiresArg: true,
1672
- describe: "The name of the namespace to delete from",
1673
- })
1674
- .option("namespace-id", {
1675
- type: "string",
1676
- requiresArg: true,
1677
- describe: "The id of the namespace to delete from",
1678
- })
1679
- .check(demandOneOfOption("binding", "namespace-id"))
1680
- .option("env", {
1681
- type: "string",
1682
- requiresArg: true,
1683
- describe: "Perform on a specific environment",
1684
- alias: "e",
1685
- })
1686
- .option("preview", {
1687
- type: "boolean",
1688
- describe: "Interact with a preview namespace",
1689
- })
1690
- .option("force", {
1691
- type: "boolean",
1692
- alias: "f",
1693
- describe: "Do not ask for confirmation before deleting",
1694
- });
1695
- },
1696
- async ({ filename, ...args }) => {
1697
- await printWranglerBanner();
1698
- const config = readConfig(args.config as ConfigPath, args);
1699
- const namespaceId = getKVNamespaceId(args, config);
1700
-
1701
- if (!args.force) {
1702
- const result = await confirm(
1703
- `Are you sure you want to delete all the keys read from "${filename}" from kv-namespace with id "${namespaceId}"?`
1704
- );
1705
- if (!result) {
1706
- logger.log(`Not deleting keys read from "${filename}".`);
1707
- return;
1708
- }
1709
- }
1710
-
1711
- const content = parseJSON(
1712
- readFileSync(filename),
1713
- filename
1714
- ) as string[];
1715
-
1716
- if (!Array.isArray(content)) {
1717
- throw new Error(
1718
- `Unexpected JSON input from "${filename}".\n` +
1719
- `Expected an array of strings but got:\n${content}`
1720
- );
1721
- }
1722
-
1723
- const errors: string[] = [];
1724
- for (let i = 0; i < content.length; i++) {
1725
- const key = content[i];
1726
- if (typeof key !== "string") {
1727
- errors.push(
1728
- `The item at index ${i} is type: "${typeof key}" - ${JSON.stringify(
1729
- key
1730
- )}`
1731
- );
1732
- }
1733
- }
1734
- if (errors.length > 0) {
1735
- throw new Error(
1736
- `Unexpected JSON input from "${filename}".\n` +
1737
- `Expected an array of strings.\n` +
1738
- errors.join("\n")
1739
- );
1740
- }
1741
-
1742
- const accountId = await requireAuth(config);
1743
-
1744
- await deleteKVBulkKeyValue(accountId, namespaceId, content);
1745
- await metrics.sendMetricsEvent("delete kv key-values (bulk)", {
1746
- sendMetrics: config.send_metrics,
1747
- });
1748
-
1749
- logger.log("Success!");
1750
- }
1751
- );
1752
- }
1753
- );
1754
-
1755
- wrangler.command(
1756
- "pages",
1757
- "⚡️ Configure Cloudflare Pages",
1758
- async (pagesYargs) => {
1759
- await pages(pagesYargs.command(subHelp));
1760
- }
1761
- );
1762
-
1763
- wrangler.command("r2", "📦 Interact with an R2 store", (r2Yargs) => {
1764
- return r2Yargs
1765
- .command(subHelp)
1766
- .command("object", "Manage R2 objects", (r2ObjectYargs) => {
1767
- return r2ObjectYargs
1768
- .command(
1769
- "get <objectPath>",
1770
- "Fetch an object from an R2 bucket",
1771
- (yargs) => {
1772
- return yargs
1773
- .positional("objectPath", {
1774
- describe:
1775
- "The source object path in the form of {bucket}/{key}",
1776
- type: "string",
1777
- })
1778
- .option("file", {
1779
- describe: "The destination file to create",
1780
- alias: "f",
1781
- conflicts: "pipe",
1782
- requiresArg: true,
1783
- type: "string",
1784
- })
1785
- .option("pipe", {
1786
- describe:
1787
- "Enables the file to be piped to a destination, rather than specified with the --file option",
1788
- alias: "p",
1789
- conflicts: "file",
1790
- type: "boolean",
1791
- });
1792
- },
1793
- async (args) => {
1794
- const config = readConfig(args.config as ConfigPath, args);
1795
- const accountId = await requireAuth(config);
1796
- const { objectPath, pipe } = args;
1797
- const { bucket, key } = bucketAndKeyFromObjectPath(objectPath);
1798
-
1799
- let file = args.file;
1800
- if (!file && !pipe) {
1801
- file = key;
1802
- }
1803
- if (!pipe) {
1804
- await printWranglerBanner();
1805
- logger.log(`Downloading "${key}" from "${bucket}".`);
1806
- }
1807
- const input = await getR2Object(accountId, bucket, key);
1808
- const output = file ? fs.createWriteStream(file) : process.stdout;
1809
- await new Promise<void>((resolve, reject) => {
1810
- stream.pipeline(input, output, (err: unknown) => {
1811
- err ? reject(err) : resolve();
1812
- });
1813
- });
1814
- if (!pipe) logger.log("Download complete.");
1815
- }
1816
- )
1817
- .command(
1818
- "put <objectPath>",
1819
- "Create an object in an R2 bucket",
1820
- (yargs) => {
1821
- return yargs
1822
- .positional("objectPath", {
1823
- describe:
1824
- "The destination object path in the form of {bucket}/{key}",
1825
- type: "string",
1826
- })
1827
- .option("file", {
1828
- describe: "The path of the file to upload",
1829
- alias: "f",
1830
- conflicts: "pipe",
1831
- requiresArg: true,
1832
- type: "string",
1833
- })
1834
- .option("pipe", {
1835
- describe:
1836
- "Enables the file to be piped in, rather than specified with the --file option",
1837
- alias: "p",
1838
- conflicts: "file",
1839
- type: "boolean",
1840
- })
1841
- .option("content-type", {
1842
- describe:
1843
- "A standard MIME type describing the format of the object data",
1844
- alias: "ct",
1845
- requiresArg: true,
1846
- type: "string",
1847
- })
1848
- .option("content-disposition", {
1849
- describe:
1850
- "Specifies presentational information for the object",
1851
- alias: "cd",
1852
- requiresArg: true,
1853
- type: "string",
1854
- })
1855
- .option("content-encoding", {
1856
- describe:
1857
- "Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field",
1858
- alias: "ce",
1859
- requiresArg: true,
1860
- type: "string",
1861
- })
1862
- .option("content-language", {
1863
- describe: "The language the content is in",
1864
- alias: "cl",
1865
- requiresArg: true,
1866
- type: "string",
1867
- })
1868
- .option("cache-control", {
1869
- describe:
1870
- "Specifies caching behavior along the request/reply chain",
1871
- alias: "cc",
1872
- requiresArg: true,
1873
- type: "string",
1874
- })
1875
- .option("expires", {
1876
- describe:
1877
- "The date and time at which the object is no longer cacheable",
1878
- alias: "e",
1879
- requiresArg: true,
1880
- type: "string",
1881
- });
1882
- },
1883
- async (args) => {
1884
- await printWranglerBanner();
1885
-
1886
- const config = readConfig(args.config as ConfigPath, args);
1887
- const accountId = await requireAuth(config);
1888
- const { objectPath, file, pipe, ...options } = args;
1889
- const { bucket, key } = bucketAndKeyFromObjectPath(objectPath);
1890
- if (!file && !pipe) {
1891
- throw new CommandLineArgsError(
1892
- "Either the --file or --pipe options are required."
1893
- );
1894
- }
1895
- let object: Readable | Buffer;
1896
- let objectSize: number;
1897
- if (file) {
1898
- object = fs.createReadStream(file);
1899
- const stats = fs.statSync(file);
1900
- objectSize = stats.size;
1901
- } else {
1902
- object = await new Promise<Buffer>((resolve, reject) => {
1903
- const stdin = process.stdin;
1904
- const chunks = Array<Buffer>();
1905
- stdin.on("data", (chunk) => chunks.push(chunk));
1906
- stdin.on("end", () => resolve(Buffer.concat(chunks)));
1907
- stdin.on("error", (err) =>
1908
- reject(
1909
- new CommandLineArgsError(
1910
- `Could not pipe. Reason: "${err.message}"`
1911
- )
1912
- )
1913
- );
1914
- });
1915
- objectSize = object.byteLength;
1916
- }
1917
-
1918
- logger.log(`Creating object "${key}" in bucket "${bucket}".`);
1919
- await putR2Object(accountId, bucket, key, object, {
1920
- ...options,
1921
- "content-length": `${objectSize}`,
1922
- });
1923
- logger.log("Upload complete.");
1924
- }
1925
- );
1926
- })
1927
- .command("bucket", "Manage R2 buckets", (r2BucketYargs) => {
1928
- r2BucketYargs.command(
1929
- "create <name>",
1930
- "Create a new R2 bucket",
1931
- (yargs) => {
1932
- return yargs.positional("name", {
1933
- describe: "The name of the new bucket",
1934
- type: "string",
1935
- demandOption: true,
1936
- });
1937
- },
1938
- async (args) => {
1939
- await printWranglerBanner();
1940
-
1941
- const config = readConfig(args.config as ConfigPath, args);
1942
-
1943
- const accountId = await requireAuth(config);
1944
-
1945
- logger.log(`Creating bucket ${args.name}.`);
1946
- await createR2Bucket(accountId, args.name);
1947
- logger.log(`Created bucket ${args.name}.`);
1948
- await metrics.sendMetricsEvent("create r2 bucket", {
1949
- sendMetrics: config.send_metrics,
1950
- });
1951
- }
1952
- );
1953
-
1954
- r2BucketYargs.command("list", "List R2 buckets", {}, async (args) => {
1955
- const config = readConfig(args.config as ConfigPath, args);
1956
-
1957
- const accountId = await requireAuth(config);
1958
-
1959
- logger.log(JSON.stringify(await listR2Buckets(accountId), null, 2));
1960
- await metrics.sendMetricsEvent("list r2 buckets", {
1961
- sendMetrics: config.send_metrics,
1962
- });
1963
- });
1964
-
1965
- r2BucketYargs.command(
1966
- "delete <name>",
1967
- "Delete an R2 bucket",
1968
- (yargs) => {
1969
- return yargs.positional("name", {
1970
- describe: "The name of the bucket to delete",
1971
- type: "string",
1972
- demandOption: true,
1973
- });
1974
- },
1975
- async (args) => {
1976
- await printWranglerBanner();
1977
-
1978
- const config = readConfig(args.config as ConfigPath, args);
1979
-
1980
- const accountId = await requireAuth(config);
1981
-
1982
- logger.log(`Deleting bucket ${args.name}.`);
1983
- await deleteR2Bucket(accountId, args.name);
1984
- logger.log(`Deleted bucket ${args.name}.`);
1985
- await metrics.sendMetricsEvent("delete r2 bucket", {
1986
- sendMetrics: config.send_metrics,
1987
- });
1988
- }
1989
- );
1990
- return r2BucketYargs;
1991
- });
1992
- });
1993
-
1994
- wrangler.command(
1995
- "worker-namespace",
1996
- "📦 Interact with a worker namespace",
1997
- (workerNamespaceYargs) => {
1998
- return workerNamespaceCommands(workerNamespaceYargs, subHelp);
1999
- }
2000
- );
2001
-
2002
- wrangler.command(
2003
- "pubsub",
2004
- "📮 Interact and manage Pub/Sub Brokers",
2005
- (pubsubYargs) => {
2006
- return pubSubCommands(pubsubYargs, subHelp);
2007
- }
2008
- );
2009
-
2010
- /**
2011
- * User Group: login, logout, and whoami
2012
- * TODO: group commands into User group similar to .group() for flags in yargs
2013
- */
2014
- // login
2015
- wrangler.command(
2016
- // this needs scopes as an option?
2017
- "login",
2018
- "🔓 Login to Cloudflare",
2019
- (yargs) => {
2020
- // TODO: This needs some copy editing
2021
- // I mean, this entire app does, but this too.
2022
- return yargs
2023
- .option("scopes-list", {
2024
- describe: "List all the available OAuth scopes with descriptions",
2025
- })
2026
- .option("scopes", {
2027
- describe: "Pick the set of applicable OAuth scopes when logging in",
2028
- array: true,
2029
- type: "string",
2030
- requiresArg: true,
2031
- });
2032
-
2033
- // TODO: scopes
2034
- },
2035
- async (args) => {
2036
- await printWranglerBanner();
2037
- if (args["scopes-list"]) {
2038
- listScopes();
2039
- return;
2040
- }
2041
- if (args.scopes) {
2042
- if (args.scopes.length === 0) {
2043
- // don't allow no scopes to be passed, that would be weird
2044
- listScopes();
2045
- return;
2046
- }
2047
- if (!validateScopeKeys(args.scopes)) {
2048
- throw new CommandLineArgsError(
2049
- `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
2050
- );
2051
- }
2052
- await login({ scopes: args.scopes });
2053
- return;
2054
- }
2055
- await login();
2056
- const config = readConfig(args.config as ConfigPath, args);
2057
- await metrics.sendMetricsEvent("login user", {
2058
- sendMetrics: config.send_metrics,
2059
- });
2060
-
2061
- // TODO: would be nice if it optionally saved login
2062
- // credentials inside node_modules/.cache or something
2063
- // this way you could have multiple users on a single machine
2064
- }
2065
- );
2066
-
2067
- // logout
2068
- wrangler.command(
2069
- // this needs scopes as an option?
2070
- "logout",
2071
- "🚪 Logout from Cloudflare",
2072
- () => {},
2073
- async () => {
2074
- await printWranglerBanner();
2075
- await logout();
2076
- const config = readConfig(undefined, {});
2077
- await metrics.sendMetricsEvent("logout user", {
2078
- sendMetrics: config.send_metrics,
2079
- });
2080
- }
2081
- );
2082
-
2083
- // whoami
2084
- wrangler.command(
2085
- "whoami",
2086
- "🕵️ Retrieve your user info and test your auth config",
2087
- () => {},
2088
- async () => {
2089
- await printWranglerBanner();
2090
- await whoami();
2091
- const config = readConfig(undefined, {});
2092
- await metrics.sendMetricsEvent("view accounts", {
2093
- sendMetrics: config.send_metrics,
2094
- });
2095
- }
2096
- );
2097
-
2098
- // This set to false to allow overwrite of default behaviour
2099
- wrangler.version(false);
2100
-
2101
- // version
2102
- wrangler.command(
2103
- "version",
2104
- false,
2105
- () => {},
2106
- async () => {
2107
- if (process.stdout.isTTY) {
2108
- await printWranglerBanner();
2109
- } else {
2110
- logger.log(wranglerVersion);
2111
- }
2112
- }
2113
- );
2114
-
2115
- wrangler.option("v", {
2116
- describe: "Show version number",
2117
- alias: "version",
2118
- type: "boolean",
2119
- });
2120
-
2121
- wrangler.option("config", {
2122
- alias: "c",
2123
- describe: "Path to .toml configuration file",
2124
- type: "string",
2125
- requiresArg: true,
2126
- });
2127
-
2128
- wrangler.group(["config", "help", "version"], "Flags:");
2129
- wrangler.help().alias("h", "help");
2130
-
2131
- wrangler.exitProcess(false);
2132
-
2133
- return wrangler;
2134
- }
2135
-
2136
- export async function main(argv: string[]): Promise<void> {
2137
- const wrangler = createCLIParser(argv);
2138
- try {
2139
- await wrangler.parse();
2140
- } catch (e) {
2141
- logger.log(""); // Just adds a bit of space
2142
- if (e instanceof CommandLineArgsError) {
2143
- logger.error(e.message);
2144
- // We are not able to ask the `wrangler` CLI parser to show help for a subcommand programmatically.
2145
- // The workaround is to re-run the parsing with an additional `--help` flag, which will result in the correct help message being displayed.
2146
- // 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.
2147
- await createCLIParser([...argv, "--help"]).parse();
2148
- } else if (e instanceof ParseError) {
2149
- e.notes.push({
2150
- text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/wrangler2/issues/new/choose",
2151
- });
2152
- logger.log(formatMessage(e));
2153
- } else {
2154
- logger.error(e instanceof Error ? e.message : e);
2155
- logger.log(
2156
- `${fgGreenColor}%s${resetColor}`,
2157
- "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
2158
- );
2159
- }
2160
- throw e;
2161
- }
2162
- }
2163
-
2164
- export function getDevCompatibilityDate(
2165
- config: Config,
2166
- compatibilityDate = config.compatibility_date
2167
- ) {
2168
- const currentDate = new Date().toISOString().substring(0, 10);
2169
- if (config.configPath !== undefined && compatibilityDate === undefined) {
2170
- logger.warn(
2171
- `No compatibility_date was specified. Using today's date: ${currentDate}.\n` +
2172
- "Add one to your wrangler.toml file:\n" +
2173
- "```\n" +
2174
- `compatibility_date = "${currentDate}"\n` +
2175
- "```\n" +
2176
- "or pass it in your terminal:\n" +
2177
- "```\n" +
2178
- `--compatibility-date=${currentDate}\n` +
2179
- "```\n" +
2180
- "See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
2181
- );
2182
- }
2183
- return compatibilityDate ?? currentDate;
2184
- }