wrangler 0.0.0-e4e9eaf → 0.0.0-e9a1820

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.
package/src/index.tsx ADDED
@@ -0,0 +1,1902 @@
1
+ import React from "react";
2
+ import { render } from "ink";
3
+ import Dev from "./dev";
4
+ import { readFile } from "node:fs/promises";
5
+ import makeCLI from "yargs";
6
+ import type Yargs from "yargs";
7
+ import { findUp } from "find-up";
8
+ import TOML from "@iarna/toml";
9
+ import type { Config } from "./config";
10
+ import { confirm, prompt } from "./dialogs";
11
+ import { version as wranglerVersion } from "../package.json";
12
+ import {
13
+ login,
14
+ logout,
15
+ listScopes,
16
+ initialise as initialiseUserConfig,
17
+ loginOrRefreshIfRequired,
18
+ getAccountId,
19
+ } from "./user";
20
+ import {
21
+ getNamespaceId,
22
+ listNamespaces,
23
+ listNamespaceKeys,
24
+ putKeyValue,
25
+ putBulkKeyValue,
26
+ deleteBulkKeyValue,
27
+ createNamespace,
28
+ isValidNamespaceBinding,
29
+ } from "./kv";
30
+
31
+ import { pages } from "./pages";
32
+
33
+ import cfetch from "./cfetch";
34
+
35
+ import publish from "./publish";
36
+ import path from "path/posix";
37
+ import { writeFile } from "node:fs/promises";
38
+ import { toFormData } from "./api/form_data";
39
+
40
+ import { createTail } from "./tail";
41
+ import onExit from "signal-exit";
42
+ import { setTimeout } from "node:timers/promises";
43
+ import * as fs from "node:fs";
44
+ import { execa } from "execa";
45
+
46
+ async function readConfig(configPath?: string): Promise<Config> {
47
+ const config: Config = {};
48
+ if (!configPath) {
49
+ configPath = await findUp("wrangler.toml");
50
+ // TODO - terminate this early instead of going all the way to the root
51
+ }
52
+
53
+ if (configPath) {
54
+ const tml: string = await readFile(configPath, "utf-8");
55
+ const parsed = TOML.parse(tml) as Config;
56
+ Object.assign(config, parsed);
57
+ }
58
+
59
+ const inheritedFields = [
60
+ "name",
61
+ "account_id",
62
+ "workers_dev",
63
+ "compatibility_date",
64
+ "compatibility_flags",
65
+ "zone_id",
66
+ "routes",
67
+ "route",
68
+ "jsx_factory",
69
+ "jsx_fragment",
70
+ "site",
71
+ "triggers",
72
+ "usage_model",
73
+ ];
74
+
75
+ Object.keys(config.env || {}).forEach((env) => {
76
+ inheritedFields.forEach((field) => {
77
+ if (config[field] !== undefined && config.env[env][field] === undefined) {
78
+ config.env[env][field] = config[field]; // TODO: - shallow copy?
79
+ }
80
+ });
81
+ });
82
+
83
+ const mirroredFields = [
84
+ "vars",
85
+ "kv_namespaces",
86
+ "durable_objects",
87
+ "experimental_services",
88
+ ];
89
+ Object.keys(config.env || {}).forEach((env) => {
90
+ mirroredFields.forEach((field) => {
91
+ // if it exists on top level, it should exist on env definitions
92
+ Object.keys(config[field] || {}).forEach((fieldKey) => {
93
+ if (!(fieldKey in config.env[env][field])) {
94
+ console.warn(
95
+ `In your configuration, "${field}.${fieldKey}" exists at a top level, but not on "env.${env}". This is not what you probably want, since the field "${field}" is not inherited by environments. Please add "${field}.${fieldKey}" to "env.${env}".`
96
+ );
97
+ }
98
+ });
99
+ });
100
+ });
101
+
102
+ if ("experimental_services" in config) {
103
+ console.warn(
104
+ "The experimental_services field is only for cloudflare internal usage right now, and is subject to change. Please do not use this on production projects"
105
+ );
106
+ }
107
+
108
+ // todo: validate, add defaults
109
+ // let's just do some basics for now
110
+
111
+ // @ts-expect-error we're being sneaky here for now
112
+ config.__path__ = configPath;
113
+
114
+ return config;
115
+ }
116
+
117
+ // a helper to demand one of a set of options
118
+ // via https://github.com/yargs/yargs/issues/1093#issuecomment-491299261
119
+ function demandOneOfOption(...options: string[]) {
120
+ return function (argv: Yargs.Arguments) {
121
+ const count = options.filter((option) => argv[option]).length;
122
+ const lastOption = options.pop();
123
+
124
+ if (count === 0) {
125
+ throw new CommandLineArgsError(
126
+ `Exactly one of the arguments ${options.join(
127
+ ", "
128
+ )} and ${lastOption} is required`
129
+ );
130
+ } else if (count > 1) {
131
+ throw new CommandLineArgsError(
132
+ `Arguments ${options.join(
133
+ ", "
134
+ )} and ${lastOption} are mutually exclusive`
135
+ );
136
+ }
137
+
138
+ return true;
139
+ };
140
+ }
141
+
142
+ class CommandLineArgsError extends Error {}
143
+ class DeprecationError extends Error {}
144
+ class NotImplementedError extends Error {}
145
+
146
+ export async function main(argv: string[]): Promise<void> {
147
+ const wrangler = makeCLI(argv)
148
+ // We handle errors ourselves in a try-catch around `yargs.parse`.
149
+ // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
150
+ // Otherwise we just log the error that was thrown without any "help info".
151
+ .showHelpOnFail(false)
152
+ .fail((msg, error) => {
153
+ if (!error) {
154
+ // If there is only a `msg` then this came from yargs own validation, so wrap in a `CommandLineArgsError`.
155
+ error = new CommandLineArgsError(msg);
156
+ }
157
+ throw error;
158
+ })
159
+ .scriptName("wrangler")
160
+ .wrap(null);
161
+
162
+ // the default is to simply print the help menu
163
+ wrangler.command(
164
+ ["*"],
165
+ false,
166
+ () => {},
167
+ (args) => {
168
+ if (args._.length > 0) {
169
+ throw new CommandLineArgsError(`Unknown command: ${args._}.`);
170
+ } else {
171
+ wrangler.showHelp("log");
172
+ }
173
+ }
174
+ );
175
+
176
+ // You will note that we use the form for all commands where we use the builder function
177
+ // to define options and subcommands.
178
+ // Further we return the result of this builder even though it's not completely necessary.
179
+ // The reason is that it's required for type inference of the args in the handle function.
180
+ // I wish we could enforce this pattern, but this comment will have to do for now.
181
+ // (It's also annoying that choices[] doesn't get inferred as an enum. 🤷‍♂.)
182
+
183
+ // [DEPRECATED] generate
184
+ wrangler.command(
185
+ // we definitely want to move away from us cloning github templates
186
+ // we can do something better here, let's see
187
+ "generate [name] [template]",
188
+ false,
189
+ (yargs) => {
190
+ return yargs
191
+ .positional("name", {
192
+ describe: "Name of the Workers project",
193
+ default: "worker",
194
+ })
195
+ .positional("template", {
196
+ describe: "a link to a GitHub template",
197
+ default: "https://github.com/cloudflare/worker-template",
198
+ });
199
+ },
200
+ () => {
201
+ // "👯 [DEPRECATED]. Scaffold a Cloudflare Workers project from a public GitHub repository.",
202
+ throw new DeprecationError(
203
+ "`wrangler generate` has been deprecated, please refer to TODO://some/path for alternatives"
204
+ );
205
+ }
206
+ );
207
+
208
+ // init
209
+ wrangler.command(
210
+ "init [name]",
211
+ "📥 Create a wrangler.toml configuration file",
212
+ (yargs) => {
213
+ return yargs.positional("name", {
214
+ describe: "The name of your worker.",
215
+ type: "string",
216
+ });
217
+ },
218
+ async (args) => {
219
+ if ("type" in args) {
220
+ let message = "The --type option is no longer supported.";
221
+ if (args.type === "webpack") {
222
+ message +=
223
+ "\nIf you wish to use webpack then you will need to create a custom build.";
224
+ // TODO: Add a link to docs
225
+ }
226
+ throw new CommandLineArgsError(message);
227
+ }
228
+
229
+ const destination = path.join(process.cwd(), "wrangler.toml");
230
+ if (fs.existsSync(destination)) {
231
+ console.warn(`${destination} file already exists!`);
232
+ const result = await confirm(
233
+ "Do you want to continue initializing this project?"
234
+ );
235
+ if (!result) {
236
+ return;
237
+ }
238
+ }
239
+
240
+ const compatibilityDate = new Date().toISOString().substring(0, 10);
241
+ try {
242
+ await writeFile(
243
+ destination,
244
+ `compatibility_date = "${compatibilityDate}"` + "\n"
245
+ );
246
+ console.log(`✨ Successfully created wrangler.toml`);
247
+ // TODO: suggest next steps?
248
+ } catch (err) {
249
+ throw new Error(
250
+ `Failed to create wrangler.toml.\n${err.message ?? err}`
251
+ );
252
+ }
253
+
254
+ // if no package.json, ask, and if yes, create one
255
+ let pathToPackageJson = await findUp("package.json");
256
+
257
+ if (!pathToPackageJson) {
258
+ if (
259
+ await confirm("No package.json found. Would you like to create one?")
260
+ ) {
261
+ await writeFile(
262
+ path.join(process.cwd(), "package.json"),
263
+ JSON.stringify(
264
+ {
265
+ name: "worker",
266
+ version: "0.0.1",
267
+ },
268
+ null,
269
+ " "
270
+ ) + "\n"
271
+ );
272
+ console.log(`✨ Created package.json`);
273
+ pathToPackageJson = path.join(process.cwd(), "package.json");
274
+ } else {
275
+ return;
276
+ }
277
+ }
278
+
279
+ // if workers-types doesn't exist as a dependency
280
+ // offer to install it
281
+ // and make a tsconfig?
282
+ let pathToTSConfig = await findUp("tsconfig.json");
283
+ if (!pathToTSConfig) {
284
+ if (await confirm("Would you like to use typescript?")) {
285
+ await writeFile(
286
+ path.join(process.cwd(), "tsconfig.json"),
287
+ JSON.stringify(
288
+ {
289
+ compilerOptions: {
290
+ target: "esnext",
291
+ module: "esnext",
292
+ moduleResolution: "node",
293
+ esModuleInterop: true,
294
+ allowJs: true,
295
+ allowSyntheticDefaultImports: true,
296
+ isolatedModules: true,
297
+ noEmit: true,
298
+ lib: ["esnext"],
299
+ jsx: "react",
300
+ resolveJsonModule: true,
301
+ types: ["@cloudflare/workers-types"],
302
+ },
303
+ },
304
+ null,
305
+ " "
306
+ ) + "\n"
307
+ );
308
+ await execa("npm", [
309
+ "install",
310
+ "@cloudflare/workers-types",
311
+ "--save-dev",
312
+ ]);
313
+ console.log(
314
+ `✨ Created tsconfig.json, installed @cloudflare/workers-types into devDependencies`
315
+ );
316
+ pathToTSConfig = path.join(process.cwd(), "tsconfig.json");
317
+ }
318
+ }
319
+ }
320
+ );
321
+
322
+ // build
323
+ wrangler.command(
324
+ "build",
325
+ false,
326
+ (yargs) => {
327
+ return yargs.option("env", {
328
+ describe: "Perform on a specific environment",
329
+ });
330
+ },
331
+ () => {
332
+ // "[DEPRECATED] 🦀 Build your project (if applicable)",
333
+ throw new DeprecationError(
334
+ "`wrangler build` has been deprecated, please refer to TODO://some/path for alternatives"
335
+ );
336
+ }
337
+ );
338
+
339
+ // login
340
+ wrangler.command(
341
+ // this needs scopes as an option?
342
+ "login",
343
+ false, // we don't need to show this in the menu
344
+ // "🔓 Login to Cloudflare",
345
+ (yargs) => {
346
+ // TODO: This needs some copy editing
347
+ // I mean, this entire app does, but this too.
348
+ return yargs
349
+ .option("scopes-list", {
350
+ describe: "list all the available OAuth scopes with descriptions.",
351
+ })
352
+ .option("scopes", {
353
+ describe: "allows to choose your set of OAuth scopes.",
354
+ array: true,
355
+ type: "string",
356
+ });
357
+
358
+ // TODO: scopes
359
+ },
360
+ async (args) => {
361
+ if (args["scopes-list"]) {
362
+ listScopes();
363
+ return;
364
+ }
365
+ if (args.scopes) {
366
+ if (args.scopes.length === 0) {
367
+ // don't allow no scopes to be passed, that would be weird
368
+ listScopes();
369
+ return;
370
+ }
371
+ await login({ scopes: args.scopes });
372
+ return;
373
+ }
374
+ await login();
375
+
376
+ // TODO: would be nice if it optionally saved login
377
+ // credentials inside node_modules/.cache or something
378
+ // this way you could have multiple users on a single machine
379
+ }
380
+ );
381
+
382
+ // logout
383
+ wrangler.command(
384
+ // this needs scopes as an option?
385
+ "logout",
386
+ false, // we don't need to show this in the menu
387
+ // "🚪 Logout from Cloudflare",
388
+ () => {},
389
+ async () => {
390
+ await logout();
391
+ }
392
+ );
393
+
394
+ // whoami
395
+ wrangler.command(
396
+ "whoami",
397
+ false, // we don't need to show this the menu
398
+ // "🕵️ Retrieve your user info and test your auth config",
399
+ () => {},
400
+ (args) => {
401
+ console.log(":whoami", args);
402
+ }
403
+ );
404
+
405
+ // config
406
+ wrangler.command(
407
+ "config",
408
+ false,
409
+ () => {},
410
+ () => {
411
+ // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
412
+ throw new DeprecationError(
413
+ "`wrangler config` has been deprecated, please refer to TODO://some/path for alternatives"
414
+ );
415
+ }
416
+ );
417
+
418
+ // dev
419
+ wrangler.command(
420
+ "dev <filename>",
421
+ "👂 Start a local server for developing your worker",
422
+ (yargs) => {
423
+ return yargs
424
+ .positional("filename", { describe: "entry point", type: "string" })
425
+ .option("name", {
426
+ describe: "name of the script",
427
+ type: "string",
428
+ })
429
+ .option("format", {
430
+ choices: ["modules", "service-worker"] as const,
431
+ describe: "Choose an entry type",
432
+ })
433
+ .option("env", {
434
+ describe: "Perform on a specific environment",
435
+ type: "string",
436
+ // TODO: get choices for the toml file?
437
+ })
438
+ .option("ip", {
439
+ describe: "IP address to listen on",
440
+ type: "string",
441
+ default: "127.0.0.1",
442
+ })
443
+ .option("port", {
444
+ describe: "Port to listen on, defaults to 8787",
445
+ type: "number",
446
+ default: 8787,
447
+ })
448
+ .option("host", {
449
+ type: "string",
450
+ describe:
451
+ "Host to forward requests to, defaults to the zone of project",
452
+ })
453
+ .option("local-protocol", {
454
+ default: "http",
455
+ describe: "Protocol to listen to requests on, defaults to http.",
456
+ choices: ["http", "https"],
457
+ })
458
+ .option("public", {
459
+ describe: "Static assets to be served",
460
+ type: "string",
461
+ })
462
+ .option("site", {
463
+ describe: "Root folder of static assets for Workers Sites",
464
+ type: "string",
465
+ })
466
+ .option("upstream-protocol", {
467
+ default: "https",
468
+ describe:
469
+ "Protocol to forward requests to host on, defaults to https.",
470
+ choices: ["http", "https"],
471
+ })
472
+ .option("jsx-factory", {
473
+ describe: "The function that is called for each JSX element",
474
+ type: "string",
475
+ })
476
+ .option("jsx-fragment", {
477
+ describe: "The function that is called for each JSX fragment",
478
+ type: "string",
479
+ });
480
+ },
481
+ async (args) => {
482
+ const { filename, format } = args;
483
+ const config = args.config as Config;
484
+
485
+ // -- snip, extract --
486
+
487
+ if (!args.local) {
488
+ const loggedIn = await loginOrRefreshIfRequired();
489
+ if (!loggedIn) {
490
+ // didn't login, let's just quit
491
+ console.log("Did not login, quitting...");
492
+ return;
493
+ }
494
+ if (!config.account_id) {
495
+ config.account_id = await getAccountId();
496
+ if (!config.account_id) {
497
+ throw new Error("No account id found, quitting...");
498
+ }
499
+ }
500
+ }
501
+
502
+ // -- snip, end --
503
+
504
+ const envRootObj = args.env ? config.env[args.env] || {} : config;
505
+
506
+ // TODO: this error shouldn't actually happen,
507
+ // but we haven't fixed it internally yet
508
+ if ("durable_objects" in envRootObj) {
509
+ if (!(args.name || config.name)) {
510
+ console.warn(
511
+ 'A worker with durable objects need to be named, or it may not work as expected. Add a "name" into wrangler.toml, or pass it in the command line with --name.'
512
+ );
513
+ }
514
+ // TODO: if not already published, publish a draft worker
515
+ }
516
+
517
+ render(
518
+ <Dev
519
+ name={args.name || config.name}
520
+ entry={path.relative(process.cwd(), filename)}
521
+ buildCommand={config.build || {}}
522
+ format={format}
523
+ initialMode={args.local ? "local" : "remote"}
524
+ jsxFactory={args["jsx-factory"] || envRootObj?.jsx_factory}
525
+ jsxFragment={args["jsx-fragment"] || envRootObj?.jsx_fragment}
526
+ accountId={config.account_id}
527
+ site={args.site || config.site?.bucket}
528
+ port={args.port || config.dev?.port}
529
+ public={args.public}
530
+ compatibilityDate={config.compatibility_date}
531
+ compatibilityFlags={config.compatibility_flags}
532
+ usageModel={config.usage_model}
533
+ bindings={{
534
+ kv_namespaces: envRootObj.kv_namespaces?.map(
535
+ ({ binding, preview_id, id: _id }) => {
536
+ // In `dev`, we make folks use a separate kv namespace called
537
+ // `preview_id` instead of `id` so that they don't
538
+ // break production data. So here we check that a `preview_id`
539
+ // has actually been configured.
540
+ // This whole block of code will be obsolted in the future
541
+ // when we have copy-on-write for previews on edge workers.
542
+ if (!preview_id) {
543
+ // TODO: This error has to be a _lot_ better, ideally just asking
544
+ // to create a preview namespace for the user automatically
545
+ throw new Error(
546
+ `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
547
+ ); // Ugh, I really don't like this message very much
548
+ }
549
+ return {
550
+ binding,
551
+ id: preview_id,
552
+ };
553
+ }
554
+ ),
555
+ vars: envRootObj.vars,
556
+ durable_objects: envRootObj.durable_objects,
557
+ services: envRootObj.experimental_services,
558
+ }}
559
+ />
560
+ );
561
+ }
562
+ );
563
+
564
+ // publish
565
+ wrangler.command(
566
+ "publish [script]",
567
+ "🆙 Publish your Worker to Cloudflare.",
568
+ (yargs) => {
569
+ return yargs
570
+ .option("env", {
571
+ type: "string",
572
+ describe: "Perform on a specific environment",
573
+ })
574
+ .positional("script", {
575
+ describe: "script to upload",
576
+ type: "string",
577
+ })
578
+ .option("name", {
579
+ describe: "name to use when uploading",
580
+ type: "string",
581
+ })
582
+ .option("public", {
583
+ describe: "Static assets to be served",
584
+ type: "string",
585
+ })
586
+ .option("site", {
587
+ describe: "Root folder of static assets for Workers Sites",
588
+ type: "string",
589
+ })
590
+ .option("triggers", {
591
+ describe: "cron schedules to attach",
592
+ alias: ["schedule", "schedules"],
593
+ type: "array",
594
+ })
595
+ .option("routes", {
596
+ describe: "routes to upload",
597
+ alias: "route",
598
+ type: "array",
599
+ })
600
+ .option("services", {
601
+ describe: "experimental support for services",
602
+ type: "boolean",
603
+ default: "false",
604
+ hidden: true,
605
+ })
606
+ .option("jsx-factory", {
607
+ describe: "The function that is called for each JSX element",
608
+ type: "string",
609
+ })
610
+ .option("jsx-fragment", {
611
+ describe: "The function that is called for each JSX fragment",
612
+ type: "string",
613
+ });
614
+ },
615
+ async (args) => {
616
+ if (args.local) {
617
+ throw new NotImplementedError(
618
+ "🚫 Local publishing is not yet supported"
619
+ );
620
+ }
621
+ const config = args.config as Config;
622
+
623
+ // -- snip, extract --
624
+ if (!args.local) {
625
+ const loggedIn = await loginOrRefreshIfRequired();
626
+ if (!loggedIn) {
627
+ // didn't login, let's just quit
628
+ console.log("Did not login, quitting...");
629
+ return;
630
+ }
631
+ if (!config.account_id) {
632
+ config.account_id = await getAccountId();
633
+ if (!config.account_id) {
634
+ throw new Error("No account id found, quitting...");
635
+ }
636
+ }
637
+ }
638
+
639
+ // -- snip, end --
640
+
641
+ await publish({
642
+ config: args.config as Config,
643
+ name: args.name,
644
+ script: args.script,
645
+ env: args.env,
646
+ triggers: args.triggers,
647
+ jsxFactory: args["jsx-factory"],
648
+ jsxFragment: args["jsx-fragment"],
649
+ routes: args.routes,
650
+ public: args.public,
651
+ site: args.site,
652
+ });
653
+ }
654
+ );
655
+
656
+ // tail
657
+ wrangler.command(
658
+ "tail [name]",
659
+ "🦚 Starts a log tailing session for a deployed Worker.",
660
+ (yargs) => {
661
+ return (
662
+ yargs
663
+ .positional("name", {
664
+ describe: "name of the worker",
665
+ type: "string",
666
+ })
667
+ // TODO: auto-detect if this should be json or pretty based on atty
668
+ .option("format", {
669
+ default: "json",
670
+ choices: ["json", "pretty"],
671
+ describe: "The format of log entries",
672
+ })
673
+ .option("status", {
674
+ choices: ["ok", "error", "canceled"],
675
+ describe: "Filter by invocation status",
676
+ })
677
+ .option("header", {
678
+ type: "string",
679
+ describe: "Filter by HTTP header",
680
+ })
681
+ .option("method", {
682
+ type: "string",
683
+ describe: "Filter by HTTP method",
684
+ })
685
+ .option("sampling-rate", {
686
+ type: "number",
687
+ describe: "Adds a percentage of requests to log sampling rate",
688
+ })
689
+ .option("search", {
690
+ type: "string",
691
+ describe: "Filter by a text match in console.log messages",
692
+ })
693
+ .option("env", {
694
+ type: "string",
695
+ describe: "Perform on a specific environment",
696
+ })
697
+ );
698
+ // TODO: filter by client ip, which can be 'self' or an ip address
699
+ },
700
+ async (args) => {
701
+ const config = args.config as Config;
702
+
703
+ if (!(args.name || config.name)) {
704
+ throw new Error("Missing script name");
705
+ }
706
+ const scriptName = `${args.name || config.name}${
707
+ args.env ? `-${args.env}` : ""
708
+ }`;
709
+
710
+ // -- snip, extract --
711
+
712
+ if (!args.local) {
713
+ const loggedIn = await loginOrRefreshIfRequired();
714
+ if (!loggedIn) {
715
+ // didn't login, let's just quit
716
+ console.log("Did not login, quitting...");
717
+ return;
718
+ }
719
+ if (!config.account_id) {
720
+ config.account_id = await getAccountId();
721
+ if (!config.account_id) {
722
+ throw new Error("No account id found, quitting...");
723
+ }
724
+ }
725
+ }
726
+
727
+ // -- snip, end --
728
+
729
+ const accountId = config.account_id;
730
+
731
+ const filters = {
732
+ status: args.status as "ok" | "error" | "canceled",
733
+ header: args.header,
734
+ method: args.method,
735
+ "sampling-rate": args["sampling-rate"],
736
+ search: args.search,
737
+ };
738
+
739
+ const { tail, expiration, /* sendHeartbeat, */ deleteTail } =
740
+ await createTail(accountId, scriptName, filters);
741
+
742
+ console.log(
743
+ `successfully created tail, expires at ${expiration.toLocaleString()}`
744
+ );
745
+
746
+ onExit(async () => {
747
+ tail.terminate();
748
+ await deleteTail();
749
+ });
750
+
751
+ tail.on("message", (data) => {
752
+ console.log(JSON.stringify(JSON.parse(data.toString()), null, " "));
753
+ });
754
+
755
+ while (tail.readyState !== tail.OPEN) {
756
+ switch (tail.readyState) {
757
+ case tail.CONNECTING:
758
+ await setTimeout(1000);
759
+ break;
760
+ case tail.CLOSING:
761
+ await setTimeout(1000);
762
+ break;
763
+ case tail.CLOSED:
764
+ process.exit(1);
765
+ }
766
+ }
767
+
768
+ console.log(`Connected to ${scriptName}, waiting for logs...`);
769
+ }
770
+ );
771
+
772
+ // preview
773
+ wrangler.command(
774
+ "preview [method] [body]",
775
+ false,
776
+ (yargs) => {
777
+ return yargs
778
+ .positional("method", {
779
+ describe: "Type of request to preview your worker",
780
+ choices: ["GET", "POST"],
781
+ default: ["GET"],
782
+ })
783
+ .positional("body", {
784
+ type: "string",
785
+ describe: "Body string to post to your preview worker request.",
786
+ default: "Null",
787
+ })
788
+ .option("env", {
789
+ type: "string",
790
+ describe: "Perform on a specific environment",
791
+ })
792
+ .option("watch", {
793
+ default: true,
794
+ describe: "Enable live preview",
795
+ type: "boolean",
796
+ });
797
+ },
798
+ () => {
799
+ // "🔬 [DEPRECATED] Preview your code temporarily on https://cloudflareworkers.com"
800
+ throw new DeprecationError(
801
+ "`wrangler preview` has been deprecated, please refer to TODO://some/path for alternatives"
802
+ );
803
+ }
804
+ );
805
+
806
+ // route
807
+ wrangler.command(
808
+ "route",
809
+ false, // I think we want to hide this command
810
+ // "➡️ List or delete worker routes",
811
+ (routeYargs) => {
812
+ return routeYargs
813
+ .command(
814
+ "list",
815
+ "List a route associated with a zone",
816
+ (yargs) => {
817
+ return yargs
818
+ .option("env", {
819
+ type: "string",
820
+ describe: "Perform on a specific environment",
821
+ })
822
+ .option("zone", {
823
+ type: "string",
824
+ describe: "zone id",
825
+ })
826
+ .positional("zone", {
827
+ describe: "zone id",
828
+ type: "string",
829
+ });
830
+ },
831
+ async (args) => {
832
+ console.log(":route list", args);
833
+ // TODO: use environment (current wrangler doesn't do so?)
834
+ const zone = args.zone || (args.config as Config).zone_id;
835
+ if (!zone) {
836
+ throw new Error("missing zone id");
837
+ }
838
+
839
+ console.log(await cfetch(`/zones/${zone}/workers/routes`));
840
+ }
841
+ )
842
+ .command(
843
+ "delete <id>",
844
+ "Delete a route associated with a zone",
845
+ (yargs) => {
846
+ return yargs
847
+ .positional("id", {
848
+ describe: "The hash of the route ID to delete.",
849
+ type: "string",
850
+ })
851
+ .option("zone", {
852
+ type: "string",
853
+ describe: "zone id",
854
+ })
855
+ .option("env", {
856
+ type: "string",
857
+ describe: "Perform on a specific environment",
858
+ });
859
+ },
860
+ async (args) => {
861
+ console.log(":route delete", args);
862
+ // TODO: use environment (current wrangler doesn't do so?)
863
+ const zone = args.zone || (args.config as Config).zone_id;
864
+ if (!zone) {
865
+ throw new Error("missing zone id");
866
+ }
867
+
868
+ console.log(
869
+ await cfetch(`/zones/${zone}/workers/routes/${args.id}`, {
870
+ method: "DELETE",
871
+ })
872
+ );
873
+ }
874
+ );
875
+ }
876
+ );
877
+
878
+ // subdomain
879
+ wrangler.command(
880
+ "subdomain [name]",
881
+ false,
882
+ // "👷 Create or change your workers.dev subdomain.",
883
+ (yargs) => {
884
+ return yargs.positional("name", { type: "string" });
885
+ },
886
+ () => {
887
+ throw new DeprecationError(
888
+ "`wrangler subdomain` has been deprecated, please refer to TODO://some/path for alternatives"
889
+ );
890
+ }
891
+ );
892
+
893
+ // secret
894
+ wrangler.command(
895
+ "secret",
896
+ "🤫 Generate a secret that can be referenced in the worker script",
897
+ (secretYargs) => {
898
+ return secretYargs
899
+ .command(
900
+ "put <key>",
901
+ "Create or update a secret variable for a script",
902
+ (yargs) => {
903
+ return yargs
904
+ .positional("key", {
905
+ describe: "The variable name to be accessible in the script.",
906
+ type: "string",
907
+ })
908
+ .option("name", {
909
+ describe: "name of the script",
910
+ type: "string",
911
+ })
912
+ .option("env", {
913
+ type: "string",
914
+ describe:
915
+ "Binds the secret to the script of the specific environment.",
916
+ });
917
+ },
918
+ async (args) => {
919
+ if (args.local) {
920
+ throw new NotImplementedError(
921
+ "--local not implemented for this command yet"
922
+ );
923
+ }
924
+ const config = args.config as Config;
925
+
926
+ // TODO: use environment (how does current wrangler do it?)
927
+ const scriptName = args.name || config.name;
928
+ if (!scriptName) {
929
+ throw new Error("Missing script name");
930
+ }
931
+
932
+ // -- snip, extract --
933
+
934
+ if (!args.local) {
935
+ const loggedIn = await loginOrRefreshIfRequired();
936
+ if (!loggedIn) {
937
+ // didn't login, let's just quit
938
+ console.log("Did not login, quitting...");
939
+ return;
940
+ }
941
+ if (!config.account_id) {
942
+ config.account_id = await getAccountId();
943
+ if (!config.account_id) {
944
+ throw new Error("No account id found, quitting...");
945
+ }
946
+ }
947
+ }
948
+
949
+ // -- snip, end --
950
+
951
+ const secretValue = await prompt(
952
+ "Enter a secret value:",
953
+ "password"
954
+ );
955
+ async function submitSecret() {
956
+ return await cfetch(
957
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/`,
958
+ {
959
+ method: "PUT",
960
+ headers: { "Content-Type": "application/json" },
961
+ body: JSON.stringify({
962
+ name: args.key,
963
+ text: secretValue,
964
+ type: "secret_text",
965
+ }),
966
+ }
967
+ );
968
+ }
969
+
970
+ try {
971
+ console.log(await submitSecret());
972
+ } catch (e) {
973
+ if (e.code === 10007) {
974
+ // upload a draft worker
975
+ await cfetch(
976
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}`,
977
+ {
978
+ method: "PUT",
979
+ // @ts-expect-error TODO: fix this error!
980
+ body: toFormData({
981
+ main: {
982
+ name: scriptName,
983
+ content: `export default { fetch() {} }`,
984
+ type: "esm",
985
+ },
986
+ bindings: {
987
+ kv_namespaces: [],
988
+ vars: {},
989
+ durable_objects: { bindings: [] },
990
+ },
991
+ modules: [],
992
+ }),
993
+ }
994
+ );
995
+
996
+ // and then try again
997
+ console.log(await submitSecret());
998
+ // TODO: delete the draft worker if this failed too?
999
+ }
1000
+ }
1001
+ }
1002
+ )
1003
+ .command(
1004
+ "delete <key>",
1005
+ "Delete a secret variable from a script",
1006
+ (yargs) => {
1007
+ return yargs
1008
+ .positional("key", {
1009
+ describe: "The variable name to be accessible in the script.",
1010
+ type: "string",
1011
+ })
1012
+ .option("name", {
1013
+ describe: "name of the script",
1014
+ type: "string",
1015
+ })
1016
+ .option("env", {
1017
+ type: "string",
1018
+ describe:
1019
+ "Binds the secret to the script of the specific environment.",
1020
+ });
1021
+ },
1022
+ async (args) => {
1023
+ if (args.local) {
1024
+ throw new NotImplementedError(
1025
+ "--local not implemented for this command yet"
1026
+ );
1027
+ }
1028
+ const config = args.config as Config;
1029
+
1030
+ // TODO: use environment (how does current wrangler do it?)
1031
+ const scriptName = args.name || config.name;
1032
+ if (!scriptName) {
1033
+ throw new Error("Missing script name");
1034
+ }
1035
+
1036
+ // -- snip, extract --
1037
+
1038
+ if (!args.local) {
1039
+ const loggedIn = await loginOrRefreshIfRequired();
1040
+ if (!loggedIn) {
1041
+ // didn't login, let's just quit
1042
+ console.log("Did not login, quitting...");
1043
+ return;
1044
+ }
1045
+ if (!config.account_id) {
1046
+ config.account_id = await getAccountId();
1047
+ if (!config.account_id) {
1048
+ throw new Error("No account id found, quitting...");
1049
+ }
1050
+ }
1051
+ }
1052
+
1053
+ // -- snip, end --
1054
+
1055
+ if (await confirm("Are you sure you want to delete this secret?")) {
1056
+ console.log(
1057
+ `Deleting the secret ${args.key} on script ${scriptName}.`
1058
+ );
1059
+
1060
+ console.log(
1061
+ await cfetch(
1062
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/${args.key}`,
1063
+ { method: "DELETE" }
1064
+ )
1065
+ );
1066
+ }
1067
+ }
1068
+ )
1069
+ .command(
1070
+ "list",
1071
+ "List all secrets for a script",
1072
+ (yargs) => {
1073
+ return yargs
1074
+ .option("name", {
1075
+ describe: "name of the script",
1076
+ type: "string",
1077
+ })
1078
+ .option("env", {
1079
+ type: "string",
1080
+ describe:
1081
+ "Binds the secret to the script of the specific environment.",
1082
+ });
1083
+ },
1084
+ async (args) => {
1085
+ if (args.local) {
1086
+ throw new NotImplementedError(
1087
+ "--local not implemented for this command yet"
1088
+ );
1089
+ }
1090
+ const config = args.config as Config;
1091
+
1092
+ // TODO: use environment (how does current wrangler do it?)
1093
+ const scriptName = args.name || config.name;
1094
+ if (!scriptName) {
1095
+ throw new Error("Missing script name");
1096
+ }
1097
+
1098
+ // -- snip, extract --
1099
+
1100
+ if (!args.local) {
1101
+ const loggedIn = await loginOrRefreshIfRequired();
1102
+ if (!loggedIn) {
1103
+ // didn't login, let's just quit
1104
+ console.log("Did not login, quitting...");
1105
+ return;
1106
+ }
1107
+ if (!config.account_id) {
1108
+ config.account_id = await getAccountId();
1109
+ if (!config.account_id) {
1110
+ throw new Error("No account id found, quitting...");
1111
+ }
1112
+ }
1113
+ }
1114
+
1115
+ // -- snip, end --
1116
+
1117
+ console.log(
1118
+ await cfetch(
1119
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets`
1120
+ )
1121
+ );
1122
+ }
1123
+ );
1124
+ }
1125
+ );
1126
+
1127
+ // kv
1128
+ // :namespace
1129
+ wrangler.command(
1130
+ "kv:namespace",
1131
+ "🗂️ Interact with your Workers KV Namespaces",
1132
+ (namespaceYargs) => {
1133
+ return namespaceYargs
1134
+ .command(
1135
+ "create <namespace>",
1136
+ "Create a new namespace",
1137
+ (yargs) => {
1138
+ return yargs
1139
+ .positional("namespace", {
1140
+ describe: "The name of the new namespace",
1141
+ type: "string",
1142
+ })
1143
+ .option("env", {
1144
+ type: "string",
1145
+ describe: "Perform on a specific environment",
1146
+ })
1147
+ .option("preview", {
1148
+ type: "boolean",
1149
+ describe: "Interact with a preview namespace",
1150
+ });
1151
+ },
1152
+ async (args) => {
1153
+ if (args._.length > 2) {
1154
+ const extraArgs = args._.slice(2).join(" ");
1155
+ throw new CommandLineArgsError(
1156
+ `Unexpected additional positional arguments "${extraArgs}".`
1157
+ );
1158
+ }
1159
+
1160
+ if (!isValidNamespaceBinding(args.namespace)) {
1161
+ throw new CommandLineArgsError(
1162
+ `The namespace binding name "${args.namespace}" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.`
1163
+ );
1164
+ }
1165
+
1166
+ const config = args.config as Config;
1167
+ if (!config.name) {
1168
+ console.warn(
1169
+ "No configured name present, using `worker` as a prefix for the title"
1170
+ );
1171
+ }
1172
+
1173
+ const name = config.name || "worker";
1174
+ const environment = args.env ? `-${args.env}` : "";
1175
+ const preview = args.preview ? "_preview" : "";
1176
+ const title = `${name}${environment}-${args.namespace}${preview}`;
1177
+
1178
+ if (args.local) {
1179
+ const { Miniflare } = await import("miniflare");
1180
+ const mf = new Miniflare({
1181
+ kvPersist: (args.kvPersist as string) || true,
1182
+ // TODO: these options shouldn't be required
1183
+ script: ` `, // has to be a string with at least one char
1184
+ });
1185
+ await mf.getKVNamespace(title); // this should "create" the namespace
1186
+ console.log(`✨ Success! Created KV namespace ${title}`);
1187
+ return;
1188
+ }
1189
+
1190
+ // -- snip, extract --
1191
+
1192
+ if (!args.local) {
1193
+ const loggedIn = await loginOrRefreshIfRequired();
1194
+ if (!loggedIn) {
1195
+ // didn't login, let's just quit
1196
+ console.log("Did not login, quitting...");
1197
+ return;
1198
+ }
1199
+ if (!config.account_id) {
1200
+ config.account_id = await getAccountId();
1201
+ if (!config.account_id) {
1202
+ throw new Error("No account id found, quitting...");
1203
+ }
1204
+ }
1205
+ }
1206
+
1207
+ // -- snip, end --
1208
+
1209
+ // TODO: generate a binding name stripping non alphanumeric chars
1210
+
1211
+ console.log(`🌀 Creating namespace with title "${title}"`);
1212
+ const namespaceId = await createNamespace(config.account_id, title);
1213
+
1214
+ console.log("✨ Success!");
1215
+ const envString = args.env ? ` under [env.${args.env}]` : "";
1216
+ const previewString = args.preview ? "preview_" : "";
1217
+ console.log(
1218
+ `Add the following to your configuration file in your kv_namespaces array${envString}:`
1219
+ );
1220
+ console.log(
1221
+ `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
1222
+ );
1223
+
1224
+ // TODO: automatically write this block to the wrangler.toml config file??
1225
+ }
1226
+ )
1227
+ .command(
1228
+ "list",
1229
+ "Outputs a list of all KV namespaces associated with your account id.",
1230
+ {},
1231
+ async (args) => {
1232
+ if (args.local) {
1233
+ throw new NotImplementedError(
1234
+ `local mode is not yet supported for this command`
1235
+ );
1236
+ }
1237
+
1238
+ const config = args.config as Config;
1239
+
1240
+ // -- snip, extract --
1241
+
1242
+ if (!args.local) {
1243
+ const loggedIn = await loginOrRefreshIfRequired();
1244
+ if (!loggedIn) {
1245
+ // didn't login, let's just quit
1246
+ console.log("Did not login, quitting...");
1247
+ return;
1248
+ }
1249
+ if (!config.account_id) {
1250
+ config.account_id = await getAccountId();
1251
+ if (!config.account_id) {
1252
+ throw new Error("No account id found, quitting...");
1253
+ }
1254
+ }
1255
+ }
1256
+
1257
+ // -- snip, end --
1258
+
1259
+ // TODO: we should show bindings if they exist for given ids
1260
+
1261
+ console.log(
1262
+ JSON.stringify(
1263
+ await listNamespaces(config.account_id),
1264
+ null,
1265
+ " "
1266
+ )
1267
+ );
1268
+ }
1269
+ )
1270
+ .command(
1271
+ "delete",
1272
+ "Deletes a given namespace.",
1273
+ (yargs) => {
1274
+ return yargs
1275
+ .option("binding", {
1276
+ type: "string",
1277
+ describe: "The name of the namespace to delete",
1278
+ })
1279
+ .option("namespace-id", {
1280
+ type: "string",
1281
+ describe: "The id of the namespace to delete",
1282
+ })
1283
+ .check(demandOneOfOption("binding", "namespace-id"))
1284
+ .option("env", {
1285
+ type: "string",
1286
+ describe: "Perform on a specific environment",
1287
+ })
1288
+ .option("preview", {
1289
+ type: "boolean",
1290
+ describe: "Interact with a preview namespace",
1291
+ });
1292
+ },
1293
+ async (args) => {
1294
+ if (args.local) {
1295
+ throw new NotImplementedError(
1296
+ `local mode is not yet supported for this command`
1297
+ );
1298
+ }
1299
+ const config = args.config as Config;
1300
+
1301
+ const id =
1302
+ args["namespace-id"] ||
1303
+ (args.env
1304
+ ? config.env[args.env] || {}
1305
+ : config
1306
+ ).kv_namespaces.find(
1307
+ (namespace) => namespace.binding === args.binding
1308
+ )?.[args.preview ? "preview_id" : "id"];
1309
+ if (!id) {
1310
+ throw new CommandLineArgsError(
1311
+ "Not able to delete namespace.\n" +
1312
+ `A namespace with binding name "${args.binding}" was not found in the configured "kv_namespaces".`
1313
+ );
1314
+ }
1315
+
1316
+ // -- snip, extract --
1317
+
1318
+ if (!args.local) {
1319
+ const loggedIn = await loginOrRefreshIfRequired();
1320
+ if (!loggedIn) {
1321
+ // didn't login, let's just quit
1322
+ console.log("Did not login, quitting...");
1323
+ return;
1324
+ }
1325
+
1326
+ if (!config.account_id) {
1327
+ config.account_id = await getAccountId();
1328
+ if (!config.account_id) {
1329
+ throw new Error("No account id found, quitting...");
1330
+ }
1331
+ }
1332
+ }
1333
+
1334
+ // -- snip, end --
1335
+
1336
+ await cfetch<{ id: string }>(
1337
+ `/accounts/${config.account_id}/storage/kv/namespaces/${id}`,
1338
+ { method: "DELETE" }
1339
+ );
1340
+
1341
+ // TODO: recommend they remove it from wrangler.toml
1342
+
1343
+ // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1344
+ // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1345
+ // n
1346
+ // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1347
+ // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1348
+ // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1349
+ // y
1350
+ // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1351
+ // ✨ Success
1352
+ // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
1353
+ // ➜ test-mf
1354
+
1355
+ // TODO: do it automatically
1356
+
1357
+ // TODO: delete the preview namespace as well?
1358
+ }
1359
+ );
1360
+ }
1361
+ );
1362
+
1363
+ // :key
1364
+ wrangler.command(
1365
+ "kv:key",
1366
+ "🔑 Individually manage Workers KV key-value pairs",
1367
+ (kvKeyYargs) => {
1368
+ return kvKeyYargs
1369
+ .command(
1370
+ "put <key> [value]",
1371
+ "Writes a single key/value pair to the given namespace.",
1372
+ (yargs) => {
1373
+ return yargs
1374
+ .positional("key", {
1375
+ type: "string",
1376
+ describe: "The key to write to.",
1377
+ })
1378
+ .positional("value", {
1379
+ type: "string",
1380
+ describe: "The value to write.",
1381
+ })
1382
+ .option("binding", {
1383
+ type: "string",
1384
+ describe: "The binding of the namespace to write to.",
1385
+ })
1386
+ .option("namespace-id", {
1387
+ type: "string",
1388
+ describe: "The id of the namespace to write to.",
1389
+ })
1390
+ .check(demandOneOfOption("binding", "namespace-id"))
1391
+ .option("env", {
1392
+ type: "string",
1393
+ describe: "Perform on a specific environment",
1394
+ })
1395
+ .option("preview", {
1396
+ type: "boolean",
1397
+ describe: "Interact with a preview namespace",
1398
+ })
1399
+ .option("ttl", {
1400
+ type: "number",
1401
+ describe: "Time for which the entries should be visible.",
1402
+ })
1403
+ .option("expiration", {
1404
+ type: "number",
1405
+ describe:
1406
+ "Time since the UNIX epoch after which the entry expires",
1407
+ })
1408
+ .option("path", {
1409
+ type: "string",
1410
+ describe: "Read value from the file at a given path.",
1411
+ })
1412
+ .check(demandOneOfOption("value", "path"));
1413
+ },
1414
+ async ({ key, ttl, expiration, ...args }) => {
1415
+ const namespaceId = getNamespaceId(args);
1416
+ const value = args.path
1417
+ ? await readFile(args.path, "utf-8")
1418
+ : args.value;
1419
+ const config = args.config as Config;
1420
+
1421
+ if (args.path) {
1422
+ console.log(
1423
+ `writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}`
1424
+ );
1425
+ } else {
1426
+ console.log(
1427
+ `writing the value "${value}" to key "${key}" on namespace ${namespaceId}`
1428
+ );
1429
+ }
1430
+
1431
+ if (args.local) {
1432
+ const { Miniflare } = await import("miniflare");
1433
+ const mf = new Miniflare({
1434
+ kvPersist: (args.kvPersist as string) || true,
1435
+ // TODO: these options shouldn't be required
1436
+ script: ` `, // has to be a string with at least one char
1437
+ });
1438
+ const ns = await mf.getKVNamespace(namespaceId);
1439
+ await ns.put(key, value, { expiration, expirationTtl: ttl });
1440
+ return;
1441
+ }
1442
+ // -- snip, extract --
1443
+
1444
+ if (!args.local) {
1445
+ const loggedIn = await loginOrRefreshIfRequired();
1446
+ if (!loggedIn) {
1447
+ // didn't login, let's just quit
1448
+ console.log("Did not login, quitting...");
1449
+ return;
1450
+ }
1451
+
1452
+ if (!config.account_id) {
1453
+ config.account_id = await getAccountId();
1454
+ if (!config.account_id) {
1455
+ throw new Error("No account id found, quitting...");
1456
+ }
1457
+ }
1458
+ }
1459
+
1460
+ // -- snip, end --
1461
+
1462
+ await putKeyValue(config.account_id, namespaceId, key, value, {
1463
+ expiration,
1464
+ expiration_ttl: ttl,
1465
+ });
1466
+ }
1467
+ )
1468
+ .command(
1469
+ "list",
1470
+ "Outputs a list of all keys in a given namespace.",
1471
+ (yargs) => {
1472
+ return yargs
1473
+ .option("binding", {
1474
+ type: "string",
1475
+ describe: "The name of the namespace to list",
1476
+ })
1477
+ .option("namespace-id", {
1478
+ type: "string",
1479
+ describe: "The id of the namespace to list",
1480
+ })
1481
+ .check(demandOneOfOption("binding", "namespace-id"))
1482
+ .option("env", {
1483
+ type: "string",
1484
+ describe: "Perform on a specific environment",
1485
+ })
1486
+ .option("prefix", {
1487
+ type: "string",
1488
+ describe: "A prefix to filter listed keys",
1489
+ });
1490
+ },
1491
+ async ({ prefix, ...args }) => {
1492
+ // TODO: support for limit+cursor (pagination)
1493
+
1494
+ const namespaceId = getNamespaceId(args);
1495
+ const config = args.config as Config;
1496
+
1497
+ if (args.local) {
1498
+ const { Miniflare } = await import("miniflare");
1499
+ const mf = new Miniflare({
1500
+ kvPersist: (args.kvPersist as string) || true,
1501
+ // TODO: these options shouldn't be required
1502
+ script: ` `, // has to be a string with at least one char
1503
+ });
1504
+ const ns = await mf.getKVNamespace(namespaceId);
1505
+ const listResponse = await ns.list({ prefix });
1506
+ console.log(JSON.stringify(listResponse.keys, null, " ")); // TODO: paginate, collate
1507
+ return;
1508
+ }
1509
+
1510
+ // -- snip, extract --
1511
+
1512
+ if (!args.local) {
1513
+ const loggedIn = await loginOrRefreshIfRequired();
1514
+ if (!loggedIn) {
1515
+ // didn't login, let's just quit
1516
+ console.log("Did not login, quitting...");
1517
+ return;
1518
+ }
1519
+
1520
+ if (!config.account_id) {
1521
+ config.account_id = await getAccountId();
1522
+ if (!config.account_id) {
1523
+ throw new Error("No account id found, quitting...");
1524
+ }
1525
+ }
1526
+ }
1527
+
1528
+ // -- snip, end --
1529
+
1530
+ console.log(
1531
+ await listNamespaceKeys(config.account_id, namespaceId, prefix)
1532
+ );
1533
+ }
1534
+ )
1535
+ .command(
1536
+ "get <key>",
1537
+ "Reads a single value by key from the given namespace.",
1538
+ (yargs) => {
1539
+ return yargs
1540
+ .positional("key", {
1541
+ describe: "The key value to get.",
1542
+ type: "string",
1543
+ })
1544
+ .option("binding", {
1545
+ type: "string",
1546
+ describe: "The name of the namespace to get from",
1547
+ })
1548
+ .option("namespace-id", {
1549
+ type: "string",
1550
+ describe: "The id of the namespace to get from",
1551
+ })
1552
+ .check(demandOneOfOption("binding", "namespace-id"))
1553
+ .option("env", {
1554
+ type: "string",
1555
+ describe: "Perform on a specific environment",
1556
+ })
1557
+ .option("preview", {
1558
+ type: "boolean",
1559
+ describe: "Interact with a preview namespace",
1560
+ });
1561
+ },
1562
+ async ({ key, ...args }) => {
1563
+ const namespaceId = getNamespaceId(args);
1564
+ const config = args.config as Config;
1565
+
1566
+ if (args.local) {
1567
+ const { Miniflare } = await import("miniflare");
1568
+ const mf = new Miniflare({
1569
+ kvPersist: (args.kvPersist as string) || true,
1570
+ // TODO: these options shouldn't be required
1571
+ script: ` `, // has to be a string with at least one char
1572
+ });
1573
+ const ns = await mf.getKVNamespace(namespaceId);
1574
+ console.log(await ns.get(key));
1575
+ return;
1576
+ }
1577
+
1578
+ // -- snip, extract --
1579
+
1580
+ if (!args.local) {
1581
+ const loggedIn = await loginOrRefreshIfRequired();
1582
+ if (!loggedIn) {
1583
+ // didn't login, let's just quit
1584
+ console.log("Did not login, quitting...");
1585
+ return;
1586
+ }
1587
+
1588
+ if (!config.account_id) {
1589
+ config.account_id = await getAccountId();
1590
+ if (!config.account_id) {
1591
+ throw new Error("No account id found, quitting...");
1592
+ }
1593
+ }
1594
+ }
1595
+
1596
+ // -- snip, end --
1597
+
1598
+ // annoyingly, the API for this one doesn't return the
1599
+ // data in the 'standard' format. goddammit.
1600
+ // That's why we have the fallthrough response in cfetch.
1601
+ // Oh well.
1602
+ console.log(
1603
+ await cfetch(
1604
+ `/accounts/${config.account_id}/storage/kv/namespaces/${namespaceId}/values/${key}`
1605
+ )
1606
+ );
1607
+ }
1608
+ )
1609
+ .command(
1610
+ "delete <key>",
1611
+ "Removes a single key value pair from the given namespace.",
1612
+ (yargs) => {
1613
+ return yargs
1614
+ .positional("key", {
1615
+ describe: "The key value to delete",
1616
+ type: "string",
1617
+ })
1618
+ .option("binding", {
1619
+ type: "string",
1620
+ describe: "The name of the namespace to delete from",
1621
+ })
1622
+ .option("namespace-id", {
1623
+ type: "string",
1624
+ describe: "The id of the namespace to delete from",
1625
+ })
1626
+ .check(demandOneOfOption("binding", "namespace-id"))
1627
+ .option("env", {
1628
+ type: "string",
1629
+ describe: "Perform on a specific environment",
1630
+ })
1631
+ .option("preview", {
1632
+ type: "boolean",
1633
+ describe: "Interact with a preview namespace",
1634
+ });
1635
+ },
1636
+ async ({ key, ...args }) => {
1637
+ const namespaceId = getNamespaceId(args);
1638
+
1639
+ console.log(
1640
+ `deleting the key "${key}" on namespace ${namespaceId}`
1641
+ );
1642
+
1643
+ if (args.local) {
1644
+ const { Miniflare } = await import("miniflare");
1645
+ const mf = new Miniflare({
1646
+ kvPersist: (args.kvPersist as string) || true,
1647
+ // TODO: these options shouldn't be required
1648
+ script: ` `, // has to be a string with at least one char
1649
+ });
1650
+ const ns = await mf.getKVNamespace(namespaceId);
1651
+ console.log(await ns.delete(key));
1652
+ return;
1653
+ }
1654
+
1655
+ const config = args.config as Config;
1656
+
1657
+ // -- snip, extract --
1658
+
1659
+ if (!args.local) {
1660
+ const loggedIn = await loginOrRefreshIfRequired();
1661
+ if (!loggedIn) {
1662
+ // didn't login, let's just quit
1663
+ console.log("Did not login, quitting...");
1664
+ return;
1665
+ }
1666
+
1667
+ if (!config.account_id) {
1668
+ config.account_id = await getAccountId();
1669
+ if (!config.account_id) {
1670
+ throw new Error("No account id found, quitting...");
1671
+ }
1672
+ }
1673
+ }
1674
+
1675
+ // -- snip, end --
1676
+
1677
+ await cfetch(
1678
+ `/accounts/${config.account_id}/storage/kv/namespaces/${namespaceId}/values/${key}`,
1679
+ { method: "DELETE" }
1680
+ );
1681
+ }
1682
+ );
1683
+ }
1684
+ );
1685
+
1686
+ // :bulk
1687
+ wrangler.command(
1688
+ "kv:bulk",
1689
+ "💪 Interact with multiple Workers KV key-value pairs at once",
1690
+ (kvBulkYargs) => {
1691
+ return kvBulkYargs
1692
+ .command(
1693
+ "put <filename>",
1694
+ "Upload multiple key-value pairs to a namespace",
1695
+ (yargs) => {
1696
+ return yargs
1697
+ .positional("filename", {
1698
+ describe: `The JSON file of key-value pairs to upload, in form [{"key":..., "value":...}"...]`,
1699
+ type: "string",
1700
+ })
1701
+ .option("binding", {
1702
+ type: "string",
1703
+ describe: "The name of the namespace to put to",
1704
+ })
1705
+ .option("namespace-id", {
1706
+ type: "string",
1707
+ describe: "The id of the namespace to put to",
1708
+ })
1709
+ .check(demandOneOfOption("binding", "namespace-id"))
1710
+ .option("env", {
1711
+ type: "string",
1712
+ describe: "Perform on a specific environment",
1713
+ })
1714
+ .option("preview", {
1715
+ type: "boolean",
1716
+ describe: "Interact with a preview namespace",
1717
+ });
1718
+ },
1719
+ async ({ filename, ...args }) => {
1720
+ // The simplest implementation I could think of.
1721
+ // This could be made more efficient with a streaming parser/uploader
1722
+ // but we'll do that in the future if needed.
1723
+
1724
+ const namespaceId = getNamespaceId(args);
1725
+ const config = args.config as Config;
1726
+ const content = await readFile(filename, "utf-8");
1727
+ let parsedContent;
1728
+ try {
1729
+ parsedContent = JSON.parse(content);
1730
+ } catch (err) {
1731
+ throw new Error(
1732
+ `Could not parse json from ${filename}.\n${err.message ?? err}`
1733
+ );
1734
+ }
1735
+
1736
+ if (args.local) {
1737
+ const { Miniflare } = await import("miniflare");
1738
+ const mf = new Miniflare({
1739
+ kvPersist: (args.kvPersist as string) || true,
1740
+ // TODO: these options shouldn't be required
1741
+ script: ` `, // has to be a string with at least one char
1742
+ });
1743
+ const ns = await mf.getKVNamespace(namespaceId);
1744
+ for (const {
1745
+ key,
1746
+ value,
1747
+ expiration,
1748
+ expiration_ttl,
1749
+ } of parsedContent) {
1750
+ await ns.put(key, value, {
1751
+ expiration,
1752
+ expirationTtl: expiration_ttl,
1753
+ });
1754
+ }
1755
+
1756
+ return;
1757
+ }
1758
+
1759
+ // -- snip, extract --
1760
+
1761
+ if (!args.local) {
1762
+ const loggedIn = await loginOrRefreshIfRequired();
1763
+ if (!loggedIn) {
1764
+ // didn't login, let's just quit
1765
+ console.log("Did not login, quitting...");
1766
+ return;
1767
+ }
1768
+
1769
+ if (!config.account_id) {
1770
+ config.account_id = await getAccountId();
1771
+ if (!config.account_id) {
1772
+ throw new Error("No account id found, quitting...");
1773
+ }
1774
+ }
1775
+ }
1776
+
1777
+ // -- snip, end --
1778
+
1779
+ console.log(
1780
+ await putBulkKeyValue(config.account_id, namespaceId, content)
1781
+ );
1782
+ }
1783
+ )
1784
+ .command(
1785
+ "delete <filename>",
1786
+ "Upload multiple key-value pairs to a namespace",
1787
+ (yargs) => {
1788
+ return yargs
1789
+ .positional("filename", {
1790
+ describe: `The JSON file of key-value pairs to upload, in form ["key1", "key2", ...]`,
1791
+ type: "string",
1792
+ })
1793
+ .option("binding", {
1794
+ type: "string",
1795
+ describe: "The name of the namespace to delete from",
1796
+ })
1797
+ .option("namespace-id", {
1798
+ type: "string",
1799
+ describe: "The id of the namespace to delete from",
1800
+ })
1801
+ .check(demandOneOfOption("binding", "namespace-id"))
1802
+ .option("env", {
1803
+ type: "string",
1804
+ describe: "Perform on a specific environment",
1805
+ })
1806
+ .option("preview", {
1807
+ type: "boolean",
1808
+ describe: "Interact with a preview namespace",
1809
+ });
1810
+ },
1811
+ async ({ filename, ...args }) => {
1812
+ const namespaceId = getNamespaceId(args);
1813
+ const config = args.config as Config;
1814
+ const content = await readFile(filename, "utf-8");
1815
+ let parsedContent;
1816
+ try {
1817
+ parsedContent = JSON.parse(content);
1818
+ } catch (err) {
1819
+ throw new Error(
1820
+ `Could not parse json from ${filename}.\n${err.message ?? err}`
1821
+ );
1822
+ }
1823
+
1824
+ if (args.local) {
1825
+ const { Miniflare } = await import("miniflare");
1826
+ const mf = new Miniflare({
1827
+ kvPersist: (args.kvPersist as string) || true,
1828
+ // TODO: these options shouldn't be required
1829
+ script: ` `, // has to be a string with at least one char
1830
+ });
1831
+ const ns = await mf.getKVNamespace(namespaceId);
1832
+ for (const key of parsedContent) {
1833
+ await ns.delete(key);
1834
+ }
1835
+
1836
+ return;
1837
+ }
1838
+
1839
+ // -- snip, extract --
1840
+
1841
+ if (!args.local) {
1842
+ const loggedIn = await loginOrRefreshIfRequired();
1843
+ if (!loggedIn) {
1844
+ // didn't login, let's just quit
1845
+ console.log("Did not login, quitting...");
1846
+ return;
1847
+ }
1848
+
1849
+ if (!config.account_id) {
1850
+ config.account_id = await getAccountId();
1851
+ if (!config.account_id) {
1852
+ throw new Error("No account id found, quitting...");
1853
+ }
1854
+ }
1855
+ }
1856
+
1857
+ // -- snip, end --
1858
+
1859
+ console.log(
1860
+ await deleteBulkKeyValue(config.account_id, namespaceId, content)
1861
+ );
1862
+ }
1863
+ );
1864
+ }
1865
+ );
1866
+
1867
+ wrangler.command("pages", "⚡️ Configure Cloudflare Pages", pages);
1868
+
1869
+ wrangler
1870
+ .option("config", {
1871
+ alias: "c",
1872
+ describe: "Path to .toml configuration file",
1873
+ type: "string",
1874
+ async coerce(arg) {
1875
+ return await readConfig(arg);
1876
+ },
1877
+ })
1878
+ .option("local", {
1879
+ alias: "l",
1880
+ describe: "Run on my machine",
1881
+ type: "boolean",
1882
+ default: false, // I bet this will a point of contention. We'll revisit it.
1883
+ });
1884
+
1885
+ wrangler.group(["config", "help", "version"], "Flags:");
1886
+ wrangler.help().alias("h", "help");
1887
+ wrangler.version(wranglerVersion).alias("v", "version");
1888
+ wrangler.exitProcess(false);
1889
+
1890
+ await initialiseUserConfig();
1891
+
1892
+ try {
1893
+ await wrangler.parse();
1894
+ } catch (e) {
1895
+ if (e instanceof CommandLineArgsError) {
1896
+ wrangler.showHelp("error");
1897
+ console.error(""); // Just adds a bit of space
1898
+ }
1899
+ console.error(e.message);
1900
+ throw e;
1901
+ }
1902
+ }