wrangler 0.0.0-e2b7352 → 0.0.0-e305903a

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