wrangler 0.0.0-e3e3243 → 0.0.0-e3efd68e3

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