wrangler 0.0.0-eab9542 → 0.0.0-eaf71b86c

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