wrangler 0.0.0-e928f94 → 0.0.0-e9307365

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