wrangler 0.0.0-e1b8ac4 → 0.0.0-e1c2f5b9

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 (295) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +170 -62
  3. package/miniflare-dist/index.mjs +1499 -21
  4. package/package.json +193 -156
  5. package/src/__tests__/access.test.ts +25 -0
  6. package/src/__tests__/api-dev.test.ts +238 -0
  7. package/src/__tests__/api-devregistry.test.js +64 -0
  8. package/src/__tests__/api.test.ts +80 -0
  9. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  10. package/src/__tests__/config-cache.test.ts +30 -24
  11. package/src/__tests__/configuration.test.ts +4152 -3537
  12. package/src/__tests__/d1.test.ts +123 -0
  13. package/src/__tests__/delete.test.ts +263 -0
  14. package/src/__tests__/deployments.test.ts +105 -0
  15. package/src/__tests__/dev.test.tsx +1559 -1028
  16. package/src/__tests__/dialogs.test.tsx +40 -0
  17. package/src/__tests__/generate.test.ts +235 -0
  18. package/src/__tests__/get-host-from-url.test.ts +16 -0
  19. package/src/__tests__/guess-worker-format.test.ts +68 -68
  20. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  21. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  22. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  23. package/src/__tests__/helpers/mock-bin.ts +20 -20
  24. package/src/__tests__/helpers/mock-cfetch.ts +165 -99
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +94 -94
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  28. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  29. package/src/__tests__/helpers/mock-istty.ts +65 -18
  30. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  31. package/src/__tests__/helpers/mock-kv.ts +27 -27
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +244 -228
  33. package/src/__tests__/helpers/mock-process.ts +23 -13
  34. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  35. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  36. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  37. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  38. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  39. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  40. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  41. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  42. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  43. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  44. package/src/__tests__/helpers/msw/index.ts +21 -0
  45. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  46. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  47. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  48. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  52. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  53. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  54. package/src/__tests__/https-options.test.ts +142 -109
  55. package/src/__tests__/index.test.ts +245 -234
  56. package/src/__tests__/init.test.ts +3027 -1925
  57. package/src/__tests__/jest.setup.ts +157 -61
  58. package/src/__tests__/kv.test.ts +1773 -1507
  59. package/src/__tests__/logger.test.ts +96 -96
  60. package/src/__tests__/logout.test.ts +47 -0
  61. package/src/__tests__/metrics.test.ts +495 -0
  62. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  63. package/src/__tests__/middleware.test.ts +750 -0
  64. package/src/__tests__/package-manager.test.ts +303 -303
  65. package/src/__tests__/pages-deployment-tail.test.ts +884 -0
  66. package/src/__tests__/pages.test.ts +2424 -735
  67. package/src/__tests__/parse.test.ts +252 -252
  68. package/src/__tests__/paths.test.ts +39 -0
  69. package/src/__tests__/publish.test.ts +7621 -5798
  70. package/src/__tests__/pubsub.test.ts +490 -0
  71. package/src/__tests__/queues.test.ts +522 -0
  72. package/src/__tests__/r2.test.ts +388 -228
  73. package/src/__tests__/route.test.ts +18 -18
  74. package/src/__tests__/secret.test.ts +673 -460
  75. package/src/__tests__/tail.test.ts +776 -567
  76. package/src/__tests__/test-old-node-version.js +31 -0
  77. package/src/__tests__/tsconfig-sanity.ts +12 -0
  78. package/src/__tests__/tsconfig.json +8 -0
  79. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  80. package/src/__tests__/type-generation.test.ts +233 -0
  81. package/src/__tests__/user.test.ts +117 -120
  82. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  83. package/src/__tests__/validate-dev-props.test.ts +56 -0
  84. package/src/__tests__/version.test.ts +35 -0
  85. package/src/__tests__/whoami.test.tsx +264 -125
  86. package/src/__tests__/worker-namespace.test.ts +326 -0
  87. package/src/abort.d.ts +1 -1
  88. package/src/api/dev.ts +218 -0
  89. package/src/api/index.ts +2 -0
  90. package/src/bundle-reporter.tsx +68 -0
  91. package/src/bundle.ts +785 -166
  92. package/src/cfetch/index.ts +120 -83
  93. package/src/cfetch/internal.ts +211 -92
  94. package/src/cli.ts +23 -8
  95. package/src/config/config.ts +236 -204
  96. package/src/config/diagnostics.ts +61 -61
  97. package/src/config/environment.ts +514 -357
  98. package/src/config/index.ts +326 -193
  99. package/src/config/validation-helpers.ts +379 -366
  100. package/src/config/validation.ts +1973 -1402
  101. package/src/config-cache.ts +81 -41
  102. package/src/create-worker-preview.ts +239 -142
  103. package/src/create-worker-upload-form.ts +309 -238
  104. package/src/d1/backups.tsx +223 -0
  105. package/src/d1/constants.ts +2 -0
  106. package/src/d1/create.tsx +63 -0
  107. package/src/d1/delete.tsx +56 -0
  108. package/src/d1/execute.tsx +352 -0
  109. package/src/d1/formatTimeAgo.ts +14 -0
  110. package/src/d1/index.ts +101 -0
  111. package/src/d1/list.tsx +48 -0
  112. package/src/d1/migrations/apply.tsx +196 -0
  113. package/src/d1/migrations/create.tsx +77 -0
  114. package/src/d1/migrations/helpers.ts +147 -0
  115. package/src/d1/migrations/index.tsx +3 -0
  116. package/src/d1/migrations/list.tsx +79 -0
  117. package/src/d1/migrations/options.ts +18 -0
  118. package/src/d1/options.ts +22 -0
  119. package/src/d1/types.tsx +24 -0
  120. package/src/d1/utils.ts +48 -0
  121. package/src/delete.ts +108 -0
  122. package/src/deployments.ts +83 -0
  123. package/src/deprecated/index.ts +145 -0
  124. package/src/dev/dev-vars.ts +20 -17
  125. package/src/dev/dev.tsx +544 -329
  126. package/src/dev/get-local-persistence-path.tsx +31 -0
  127. package/src/dev/local.tsx +912 -301
  128. package/src/dev/remote.tsx +591 -230
  129. package/src/dev/start-server.ts +543 -0
  130. package/src/dev/use-esbuild.ts +183 -91
  131. package/src/dev/validate-dev-props.ts +31 -0
  132. package/src/dev-registry.tsx +201 -0
  133. package/src/dev.tsx +949 -0
  134. package/src/dialogs.tsx +132 -99
  135. package/src/dispatch-namespace.ts +207 -0
  136. package/src/docs/index.ts +97 -0
  137. package/src/durable.ts +87 -87
  138. package/src/entry.ts +235 -228
  139. package/src/environment-variables/factory.ts +88 -0
  140. package/src/environment-variables/misc-variables.ts +30 -0
  141. package/src/errors.ts +6 -6
  142. package/src/generate/index.ts +300 -0
  143. package/src/git-client.ts +135 -0
  144. package/src/global-wrangler-config-path.ts +26 -0
  145. package/src/https-options.ts +84 -80
  146. package/src/index.tsx +637 -2850
  147. package/src/init.ts +1025 -0
  148. package/src/inspect.ts +698 -593
  149. package/src/intl-polyfill.d.ts +123 -123
  150. package/src/is-ci.ts +14 -0
  151. package/src/is-interactive.ts +16 -0
  152. package/src/jest.d.ts +4 -0
  153. package/src/kv/helpers.ts +430 -0
  154. package/src/kv/index.ts +596 -0
  155. package/src/logger.ts +64 -45
  156. package/src/metrics/index.ts +5 -0
  157. package/src/metrics/metrics-config.ts +239 -0
  158. package/src/metrics/metrics-dispatcher.ts +96 -0
  159. package/src/metrics/metrics-usage-headers.ts +24 -0
  160. package/src/metrics/send-event.ts +97 -0
  161. package/src/miniflare-cli/assets.ts +250 -0
  162. package/src/miniflare-cli/index.ts +202 -33
  163. package/src/miniflare-cli/request-context.ts +18 -18
  164. package/src/miniflare-cli/tsconfig.json +9 -0
  165. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  166. package/src/miniflare-cli/types.ts +11 -0
  167. package/src/module-collection.ts +221 -212
  168. package/src/open-in-browser.ts +4 -4
  169. package/src/package-manager.ts +173 -128
  170. package/src/pages/build.tsx +270 -0
  171. package/src/pages/constants.ts +18 -0
  172. package/src/pages/deployment-tails.tsx +284 -0
  173. package/src/pages/deployments.tsx +84 -0
  174. package/src/pages/dev.tsx +710 -0
  175. package/src/pages/errors.ts +66 -0
  176. package/src/pages/functions/buildPlugin.ts +107 -0
  177. package/src/pages/functions/buildWorker.ts +166 -0
  178. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  179. package/src/pages/functions/filepath-routing.ts +189 -0
  180. package/src/pages/functions/identifiers.ts +78 -0
  181. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  182. package/src/pages/functions/routes-consolidation.ts +73 -0
  183. package/src/pages/functions/routes-transformation.test.ts +282 -0
  184. package/src/pages/functions/routes-transformation.ts +115 -0
  185. package/src/pages/functions/routes-validation.test.ts +403 -0
  186. package/src/pages/functions/routes-validation.ts +202 -0
  187. package/src/pages/functions/routes.ts +151 -0
  188. package/src/pages/functions/tsconfig.json +8 -0
  189. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  190. package/src/pages/functions.tsx +82 -0
  191. package/src/pages/hash.tsx +13 -0
  192. package/src/pages/index.tsx +102 -0
  193. package/src/pages/projects.tsx +169 -0
  194. package/src/pages/prompt-select-project.tsx +31 -0
  195. package/src/pages/publish.tsx +461 -0
  196. package/src/pages/types.ts +41 -0
  197. package/src/pages/upload.tsx +447 -0
  198. package/src/pages/utils.ts +23 -0
  199. package/src/parse.ts +202 -138
  200. package/src/paths.ts +53 -8
  201. package/src/proxy.ts +623 -405
  202. package/src/publish/index.ts +270 -0
  203. package/src/publish/publish.ts +1036 -0
  204. package/src/pubsub/index.ts +286 -0
  205. package/src/pubsub/pubsub-commands.tsx +624 -0
  206. package/src/queues/cli/commands/consumer/add.ts +71 -0
  207. package/src/queues/cli/commands/consumer/index.ts +22 -0
  208. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  209. package/src/queues/cli/commands/create.ts +25 -0
  210. package/src/queues/cli/commands/delete.ts +26 -0
  211. package/src/queues/cli/commands/index.ts +36 -0
  212. package/src/queues/cli/commands/list.ts +25 -0
  213. package/src/queues/client.ts +135 -0
  214. package/src/queues/utils.ts +18 -0
  215. package/src/r2/constants.ts +4 -0
  216. package/src/r2/helpers.ts +131 -0
  217. package/src/r2/index.ts +289 -0
  218. package/src/routes.ts +140 -0
  219. package/src/secret/index.ts +379 -0
  220. package/src/selfsigned.d.ts +23 -23
  221. package/src/sites.tsx +258 -254
  222. package/src/tail/createTail.ts +379 -0
  223. package/src/tail/filters.ts +108 -110
  224. package/src/tail/index.ts +211 -296
  225. package/src/tail/printing.ts +86 -46
  226. package/src/tsconfig-sanity.ts +16 -0
  227. package/src/type-generation.ts +181 -0
  228. package/src/update-check.ts +11 -11
  229. package/src/user/access.ts +68 -0
  230. package/src/user/auth-variables.ts +113 -0
  231. package/src/user/choose-account.tsx +69 -0
  232. package/src/user/generate-auth-url.ts +33 -0
  233. package/src/user/generate-random-state.ts +16 -0
  234. package/src/user/index.ts +2 -0
  235. package/src/user/user.tsx +1238 -0
  236. package/src/utils/collectKeyValues.ts +14 -0
  237. package/src/whoami.tsx +141 -43
  238. package/src/worker.ts +177 -107
  239. package/src/yargs-types.ts +24 -0
  240. package/src/zones.ts +158 -40
  241. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  242. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  243. package/templates/__tests__/tsconfig.json +8 -0
  244. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  245. package/templates/checked-fetch.js +17 -0
  246. package/templates/d1-beta-facade.js +205 -0
  247. package/templates/facade.d.ts +14 -0
  248. package/templates/first-party-worker-module-facade.ts +19 -0
  249. package/templates/format-dev-errors.ts +33 -0
  250. package/templates/init-tests/test-jest-new-worker.js +23 -0
  251. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  252. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  253. package/templates/middleware/common.ts +62 -0
  254. package/templates/middleware/loader-modules.ts +82 -0
  255. package/templates/middleware/loader-sw.ts +233 -0
  256. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  257. package/templates/middleware/middleware-pretty-error.ts +40 -0
  258. package/templates/middleware/middleware-scheduled.ts +15 -0
  259. package/templates/new-worker-scheduled.js +3 -3
  260. package/templates/new-worker-scheduled.ts +15 -15
  261. package/templates/new-worker.js +3 -3
  262. package/templates/new-worker.ts +15 -15
  263. package/templates/no-op-worker.js +10 -0
  264. package/templates/pages-dev-pipeline.ts +31 -0
  265. package/templates/pages-dev-util.ts +52 -0
  266. package/templates/pages-shim.ts +12 -0
  267. package/templates/pages-template-plugin.ts +171 -0
  268. package/templates/pages-template-worker.ts +189 -0
  269. package/templates/serve-static-assets.ts +65 -0
  270. package/templates/service-bindings-module-facade.js +54 -0
  271. package/templates/service-bindings-sw-facade.js +42 -0
  272. package/templates/tsconfig-sanity.ts +11 -0
  273. package/templates/tsconfig.init.json +106 -0
  274. package/templates/tsconfig.json +6 -103
  275. package/templates/tsconfig.tsbuildinfo +1 -0
  276. package/wrangler-dist/cli.d.ts +906 -0
  277. package/wrangler-dist/cli.js +147920 -108883
  278. package/pages/functions/buildPlugin.ts +0 -105
  279. package/pages/functions/buildWorker.ts +0 -151
  280. package/pages/functions/filepath-routing.ts +0 -189
  281. package/pages/functions/identifiers.ts +0 -78
  282. package/pages/functions/routes.ts +0 -156
  283. package/pages/functions/template-plugin.ts +0 -147
  284. package/pages/functions/template-worker.ts +0 -143
  285. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  286. package/src/environment-variables.ts +0 -35
  287. package/src/generate-auth-url.ts +0 -33
  288. package/src/generate-random-state.ts +0 -16
  289. package/src/kv.ts +0 -408
  290. package/src/miniflare-cli/enum-keys.ts +0 -17
  291. package/src/pages.tsx +0 -2093
  292. package/src/publish.ts +0 -726
  293. package/src/r2.ts +0 -50
  294. package/src/user.tsx +0 -1202
  295. package/templates/static-asset-facade.js +0 -43
package/src/index.tsx CHANGED
@@ -1,2907 +1,694 @@
1
- import * as fs from "node:fs";
2
- import { writeFile, mkdir } from "node:fs/promises";
3
- import path from "node:path";
4
- import { setTimeout } from "node:timers/promises";
1
+ import os from "node:os";
5
2
  import TOML from "@iarna/toml";
6
3
  import chalk from "chalk";
7
- import { watch } from "chokidar";
8
- import { execa } from "execa";
9
- import { findUp } from "find-up";
10
- import getPort from "get-port";
11
- import { render } from "ink";
12
- import React from "react";
13
- import onExit from "signal-exit";
14
4
  import supportsColor from "supports-color";
15
- import { setGlobalDispatcher, ProxyAgent } from "undici";
5
+ import { ProxyAgent, setGlobalDispatcher } from "undici";
16
6
  import makeCLI from "yargs";
17
7
  import { version as wranglerVersion } from "../package.json";
18
- import { fetchResult } from "./cfetch";
19
- import { findWranglerToml, printBindings, readConfig } from "./config";
20
- import { createWorkerUploadForm } from "./create-worker-upload-form";
21
- import Dev from "./dev/dev";
22
- import { getVarsForDev } from "./dev/dev-vars";
23
- import { confirm, prompt, select } from "./dialogs";
24
- import { getEntry } from "./entry";
25
- import { DeprecationError } from "./errors";
8
+ import { isBuildFailure } from "./bundle";
9
+ import { loadDotEnv, readConfig } from "./config";
10
+ import { d1 } from "./d1";
11
+ import { deleteHandler, deleteOptions } from "./delete";
12
+ import { deployments } from "./deployments";
26
13
  import {
27
- getKVNamespaceId,
28
- listKVNamespaces,
29
- listKVNamespaceKeys,
30
- putKVKeyValue,
31
- putKVBulkKeyValue,
32
- deleteKVBulkKeyValue,
33
- createKVNamespace,
34
- isValidKVNamespaceBinding,
35
- getKVKeyValue,
36
- isKVKeyValue,
37
- unexpectedKVKeyValueProps,
38
- deleteKVNamespace,
39
- deleteKVKeyValue,
40
- } from "./kv";
41
- import { logger } from "./logger";
42
- import { getPackageManager } from "./package-manager";
43
- import { pages, pagesBetaWarning } from "./pages";
44
- import {
45
- formatMessage,
46
- ParseError,
47
- parseJSON,
48
- parsePackageJSON,
49
- parseTOML,
50
- readFileSync,
51
- readFileSyncToBuffer,
52
- } from "./parse";
53
- import publish from "./publish";
54
- import { createR2Bucket, deleteR2Bucket, listR2Buckets } from "./r2";
55
- import { getAssetPaths, getSiteAssetPaths } from "./sites";
56
- import {
57
- createTail,
58
- jsonPrintLogs,
59
- prettyPrintLogs,
60
- translateCLICommandToFilterMessage,
61
- } from "./tail";
14
+ buildHandler,
15
+ buildOptions,
16
+ configHandler,
17
+ noOpOptions,
18
+ previewHandler,
19
+ previewOptions,
20
+ route,
21
+ routeHandler,
22
+ subdomainHandler,
23
+ subdomainOptions,
24
+ } from "./deprecated";
25
+ import { devHandler, devOptions } from "./dev";
26
+ import { workerNamespaceCommands } from "./dispatch-namespace";
27
+ import { docsHandler, docsOptions } from "./docs";
28
+ import { generateHandler, generateOptions } from "./generate";
29
+ import { initHandler, initOptions } from "./init";
30
+ import { kvNamespace, kvKey, kvBulk } from "./kv";
31
+ import { logBuildFailure, logger } from "./logger";
32
+ import * as metrics from "./metrics";
33
+ import { pages } from "./pages";
34
+ import { formatMessage, ParseError } from "./parse";
35
+ import { publishOptions, publishHandler } from "./publish";
36
+ import { pubSubCommands } from "./pubsub/pubsub-commands";
37
+ import { queues } from "./queues/cli/commands";
38
+ import { r2 } from "./r2";
39
+ import { secret, secretBulkHandler, secretBulkOptions } from "./secret";
40
+ import { tailOptions, tailHandler } from "./tail";
41
+ import { generateTypes } from "./type-generation";
62
42
  import { updateCheck } from "./update-check";
63
43
  import {
64
- login,
65
- logout,
66
- listScopes,
67
- validateScopeKeys,
68
- requireAuth,
44
+ listScopes,
45
+ login,
46
+ logout,
47
+ requireAuth,
48
+ validateScopeKeys,
69
49
  } from "./user";
70
50
  import { whoami } from "./whoami";
71
- import { getZoneIdFromHost, getZoneForRoute } from "./zones";
72
51
 
73
52
  import type { Config } from "./config";
74
- import type { TailCLIFilters } from "./tail";
75
- import type { RawData } from "ws";
76
- import type { CommandModule } from "yargs";
53
+ import type { CommonYargsOptions } from "./yargs-types";
54
+ import type { ArgumentsCamelCase } from "yargs";
77
55
  import type Yargs from "yargs";
78
56
 
79
- type ConfigPath = string | undefined;
57
+ export type ConfigPath = string | undefined;
80
58
 
81
59
  const resetColor = "\x1b[0m";
82
60
  const fgGreenColor = "\x1b[32m";
83
- const DEFAULT_LOCAL_PORT = 8787;
61
+ export const DEFAULT_LOCAL_PORT = 8787;
62
+ export const DEFAULT_INSPECTOR_PORT = 9229;
84
63
 
85
64
  const proxy =
86
- process.env.https_proxy ||
87
- process.env.HTTPS_PROXY ||
88
- process.env.http_proxy ||
89
- process.env.HTTP_PROXY ||
90
- undefined;
65
+ process.env.https_proxy ||
66
+ process.env.HTTPS_PROXY ||
67
+ process.env.http_proxy ||
68
+ process.env.HTTP_PROXY ||
69
+ undefined;
91
70
 
92
71
  if (proxy) {
93
- setGlobalDispatcher(new ProxyAgent(proxy));
72
+ setGlobalDispatcher(new ProxyAgent(proxy));
73
+ logger.log(
74
+ `Proxy environment variables detected. We'll use your proxy for fetch requests.`
75
+ );
94
76
  }
95
77
 
96
- function getRules(config: Config): Config["rules"] {
97
- const rules = config.rules ?? config.build?.upload?.rules ?? [];
78
+ export function getRules(config: Config): Config["rules"] {
79
+ const rules = config.rules ?? config.build?.upload?.rules ?? [];
98
80
 
99
- if (config.rules && config.build?.upload?.rules) {
100
- throw new Error(
101
- `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
102
- );
103
- }
81
+ if (config.rules && config.build?.upload?.rules) {
82
+ throw new Error(
83
+ `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
84
+ );
85
+ }
104
86
 
105
- if (config.build?.upload?.rules) {
106
- logger.warn(
107
- `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:
87
+ if (config.build?.upload?.rules) {
88
+ logger.warn(
89
+ `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:
108
90
 
109
91
  ${TOML.stringify({ rules: config.build.upload.rules })}`
110
- );
111
- }
112
- return rules;
92
+ );
93
+ }
94
+ return rules;
113
95
  }
114
96
 
115
- async function printWranglerBanner() {
116
- // Let's not print this in tests
117
- if (typeof jest !== "undefined") {
118
- return;
119
- }
120
-
121
- const text = ` ⛅️ wrangler ${wranglerVersion} ${await updateCheck()}`;
122
-
123
- logger.log(
124
- text +
125
- "\n" +
126
- (supportsColor.stdout
127
- ? chalk.hex("#FF8800")("-".repeat(text.length))
128
- : "-".repeat(text.length))
129
- );
97
+ export async function printWranglerBanner() {
98
+ // Let's not print this in tests
99
+ if (typeof jest !== "undefined") {
100
+ return;
101
+ }
102
+
103
+ const text = ` ⛅️ wrangler ${wranglerVersion} ${await updateCheck()}`;
104
+
105
+ logger.log(
106
+ text +
107
+ "\n" +
108
+ (supportsColor.stdout
109
+ ? chalk.hex("#FF8800")("-".repeat(text.length))
110
+ : "-".repeat(text.length))
111
+ );
130
112
  }
131
113
 
132
- function isLegacyEnv(config: Config): boolean {
133
- // We only read from config here, because we've already accounted for
134
- // args["legacy-env"] in https://github.com/cloudflare/wrangler2/blob/b24aeb5722370c2e04bce97a84a1fa1e55725d79/packages/wrangler/src/config/validation.ts#L94-L98
135
- return config.legacy_env;
114
+ export function isLegacyEnv(config: Config): boolean {
115
+ // We only read from config here, because we've already accounted for
116
+ // args["legacy-env"] in https://github.com/cloudflare/wrangler2/blob/b24aeb5722370c2e04bce97a84a1fa1e55725d79/packages/wrangler/src/config/validation.ts#L94-L98
117
+ return config.legacy_env;
136
118
  }
137
119
 
138
- function getScriptName(
139
- args: { name: string | undefined; env: string | undefined },
140
- config: Config
120
+ export function getScriptName(
121
+ args: { name: string | undefined; env: string | undefined },
122
+ config: Config
141
123
  ): string | undefined {
142
- if (args.name && isLegacyEnv(config) && args.env) {
143
- throw new CommandLineArgsError(
144
- "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:" +
145
- `
124
+ if (args.name && isLegacyEnv(config) && args.env) {
125
+ throw new CommandLineArgsError(
126
+ "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:" +
127
+ `
146
128
  [env.${args.env}]
147
129
  name = "${args.name}"
148
130
  `
149
- );
150
- }
131
+ );
132
+ }
151
133
 
152
- return args.name ?? config.name;
134
+ return args.name ?? config.name;
153
135
  }
154
136
 
155
137
  /**
156
138
  * Alternative to the getScriptName() because special Legacy cases allowed "name", and "env" together in Wrangler1
157
139
  */
158
- function getLegacyScriptName(
159
- args: { name: string | undefined; env: string | undefined },
160
- config: Config
140
+ export function getLegacyScriptName(
141
+ args: { name: string | undefined; env: string | undefined },
142
+ config: Config
161
143
  ) {
162
- return args.name && args.env && isLegacyEnv(config)
163
- ? `${args.name}-${args.env}`
164
- : args.name ?? config.name;
165
- }
166
-
167
- /**
168
- * Get a promise to the streamed input from stdin.
169
- *
170
- * This function can be used to grab the incoming stream of data from, say,
171
- * piping the output of another process into the wrangler process.
172
- */
173
- function readFromStdin(): Promise<string> {
174
- return new Promise((resolve, reject) => {
175
- const stdin = process.stdin;
176
- const chunks: string[] = [];
177
-
178
- // When there is data ready to be read, the `readable` event will be triggered.
179
- // In the handler for `readable` we call `read()` over and over until all the available data has been read.
180
- stdin.on("readable", () => {
181
- let chunk;
182
- while (null !== (chunk = stdin.read())) {
183
- chunks.push(chunk);
184
- }
185
- });
186
-
187
- // When the streamed data is complete the `end` event will be triggered.
188
- // In the handler for `end` we join the chunks together and resolve the promise.
189
- stdin.on("end", () => {
190
- resolve(chunks.join(""));
191
- });
192
-
193
- // If there is an `error` event then the handler will reject the promise.
194
- stdin.on("error", (err) => {
195
- reject(err);
196
- });
197
- });
144
+ return args.name && args.env && isLegacyEnv(config)
145
+ ? `${args.name}-${args.env}`
146
+ : args.name ?? config.name;
198
147
  }
199
148
 
200
149
  // a helper to demand one of a set of options
201
150
  // via https://github.com/yargs/yargs/issues/1093#issuecomment-491299261
202
- function demandOneOfOption(...options: string[]) {
203
- return function (argv: Yargs.Arguments) {
204
- const count = options.filter((option) => argv[option]).length;
205
- const lastOption = options.pop();
206
-
207
- if (count === 0) {
208
- throw new CommandLineArgsError(
209
- `Exactly one of the arguments ${options.join(
210
- ", "
211
- )} and ${lastOption} is required`
212
- );
213
- } else if (count > 1) {
214
- throw new CommandLineArgsError(
215
- `Arguments ${options.join(
216
- ", "
217
- )} and ${lastOption} are mutually exclusive`
218
- );
219
- }
220
-
221
- return true;
222
- };
223
- }
224
-
225
- /**
226
- * Remove trailing white space from inputs.
227
- * Matching Wrangler legacy behavior with handling inputs
228
- */
229
- function trimTrailingWhitespace(str: string) {
230
- return str.trimEnd();
151
+ export function demandOneOfOption(...options: string[]) {
152
+ return function (argv: Yargs.Arguments) {
153
+ const count = options.filter((option) => argv[option]).length;
154
+ const lastOption = options.pop();
155
+
156
+ if (count === 0) {
157
+ throw new CommandLineArgsError(
158
+ `Exactly one of the arguments ${options.join(
159
+ ", "
160
+ )} and ${lastOption} is required`
161
+ );
162
+ } else if (count > 1) {
163
+ throw new CommandLineArgsError(
164
+ `Arguments ${options.join(
165
+ ", "
166
+ )} and ${lastOption} are mutually exclusive`
167
+ );
168
+ }
169
+
170
+ return true;
171
+ };
231
172
  }
232
173
 
233
- class CommandLineArgsError extends Error {}
234
-
235
- function createCLIParser(argv: string[]) {
236
- const wrangler = makeCLI(argv)
237
- .strict()
238
- // We handle errors ourselves in a try-catch around `yargs.parse`.
239
- // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
240
- // Otherwise we just log the error that was thrown without any "help info".
241
- .showHelpOnFail(false)
242
- .fail((msg, error) => {
243
- if (!error || error.name === "YError") {
244
- // If there is no error or the error is a "YError", then this came from yargs own validation
245
- // Wrap it in a `CommandLineArgsError` so that we can handle it appropriately further up.
246
- error = new CommandLineArgsError(msg);
247
- }
248
- throw error;
249
- })
250
- .scriptName("wrangler")
251
- .wrap(null);
252
-
253
- // Default help command that supports the subcommands
254
- const subHelp: CommandModule = {
255
- command: ["*"],
256
- handler: async (args) => {
257
- setImmediate(() =>
258
- wrangler.parse([...args._.map((a) => `${a}`), "--help"])
259
- );
260
- },
261
- };
262
- wrangler.command(
263
- ["*"],
264
- false,
265
- () => {},
266
- (args) => {
267
- if (args._.length > 0) {
268
- throw new CommandLineArgsError(`Unknown command: ${args._}.`);
269
- } else {
270
- wrangler.showHelp("log");
271
- }
272
- }
273
- );
274
-
275
- // You will note that we use the form for all commands where we use the builder function
276
- // to define options and subcommands.
277
- // Further we return the result of this builder even though it's not completely necessary.
278
- // The reason is that it's required for type inference of the args in the handle function.
279
- // I wish we could enforce this pattern, but this comment will have to do for now.
280
- // (It's also annoying that choices[] doesn't get inferred as an enum. 🤷‍♂.)
281
-
282
- // [DEPRECATED] generate
283
- wrangler.command(
284
- // we definitely want to move away from us cloning github templates
285
- // we can do something better here, let's see
286
- "generate [name] [template]",
287
- false,
288
- (yargs) => {
289
- return yargs
290
- .positional("name", {
291
- describe: "Name of the Workers project",
292
- default: "worker",
293
- })
294
- .positional("template", {
295
- describe: "The URL of a GitHub template",
296
- default: "https://github.com/cloudflare/worker-template",
297
- });
298
- },
299
- (generateArgs) => {
300
- // "👯 [DEPRECATED]. Scaffold a Cloudflare Workers project from a public GitHub repository.",
301
- throw new DeprecationError(
302
- "`wrangler generate` has been deprecated.\n" +
303
- "Try running `wrangler init` to generate a basic Worker, or cloning the template repository instead:\n\n" +
304
- "```\n" +
305
- `git clone ${generateArgs.template}\n` +
306
- "```\n\n" +
307
- "Please refer to https://developers.cloudflare.com/workers/wrangler/deprecations/#generate for more information."
308
- );
309
- }
310
- );
311
-
312
- // init
313
- wrangler.command(
314
- "init [name]",
315
- "📥 Create a wrangler.toml configuration file",
316
- (yargs) => {
317
- return yargs
318
- .positional("name", {
319
- describe: "The name of your worker",
320
- type: "string",
321
- })
322
- .option("type", {
323
- describe: "The type of worker to create",
324
- type: "string",
325
- choices: ["rust", "javascript", "webpack"],
326
- hidden: true,
327
- deprecated: true,
328
- })
329
- .option("site", {
330
- hidden: true,
331
- type: "boolean",
332
- deprecated: true,
333
- })
334
- .option("yes", {
335
- describe: 'Answer "yes" to any prompts for new projects',
336
- type: "boolean",
337
- alias: "y",
338
- });
339
- },
340
- async (args) => {
341
- await printWranglerBanner();
342
- if (args.type) {
343
- let message = "The --type option is no longer supported.";
344
- if (args.type === "webpack") {
345
- message +=
346
- "\nIf you wish to use webpack then you will need to create a custom build.";
347
- // TODO: Add a link to docs
348
- }
349
- throw new CommandLineArgsError(message);
350
- }
351
-
352
- const devDepsToInstall: string[] = [];
353
- const instructions: string[] = [];
354
- let shouldRunPackageManagerInstall = false;
355
- const creationDirectory = path.resolve(process.cwd(), args.name ?? "");
356
-
357
- if (args.site) {
358
- const gitDirectory =
359
- creationDirectory !== process.cwd()
360
- ? path.basename(creationDirectory)
361
- : "my-site";
362
- const message =
363
- "The --site option is no longer supported.\n" +
364
- "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
365
- "```\n" +
366
- `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
367
- `cd ${gitDirectory}\n` +
368
- "```\n\n" +
369
- "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
370
- "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
371
- throw new CommandLineArgsError(message);
372
- }
373
-
374
- // TODO: make sure args.name is a valid identifier for a worker name
375
- const workerName = path
376
- .basename(creationDirectory)
377
- .toLowerCase()
378
- .replaceAll(/[^a-z0-9\-_]/gm, "-");
379
-
380
- const packageManager = await getPackageManager(creationDirectory);
381
-
382
- // TODO: ask which directory to make the worker in (defaults to args.name)
383
- // TODO: if args.name isn't provided, ask what to name the worker
384
-
385
- const wranglerTomlDestination = path.join(
386
- creationDirectory,
387
- "./wrangler.toml"
388
- );
389
- let justCreatedWranglerToml = false;
390
-
391
- if (fs.existsSync(wranglerTomlDestination)) {
392
- logger.warn(
393
- `${path.relative(
394
- process.cwd(),
395
- wranglerTomlDestination
396
- )} already exists!`
397
- );
398
- const shouldContinue = await confirm(
399
- "Do you want to continue initializing this project?"
400
- );
401
- if (!shouldContinue) {
402
- return;
403
- }
404
- } else {
405
- await mkdir(creationDirectory, { recursive: true });
406
- const compatibilityDate = new Date().toISOString().substring(0, 10);
407
-
408
- try {
409
- await writeFile(
410
- wranglerTomlDestination,
411
- TOML.stringify({
412
- name: workerName,
413
- compatibility_date: compatibilityDate,
414
- }) + "\n"
415
- );
416
-
417
- logger.log(
418
- `✨ Created ${path.relative(
419
- process.cwd(),
420
- wranglerTomlDestination
421
- )}`
422
- );
423
- justCreatedWranglerToml = true;
424
- } catch (err) {
425
- throw new Error(
426
- `Failed to create ${path.relative(
427
- process.cwd(),
428
- wranglerTomlDestination
429
- )}.\n${(err as Error).message ?? err}`
430
- );
431
- }
432
- }
433
-
434
- const yesFlag = args.yes ?? false;
435
-
436
- const isInsideGitProject = Boolean(
437
- await findUp(".git", { cwd: creationDirectory, type: "directory" })
438
- );
439
- let isGitInstalled;
440
- try {
441
- isGitInstalled = (await execa("git", ["--version"])).exitCode === 0;
442
- } catch (err) {
443
- isGitInstalled = false;
444
- }
445
- if (!isInsideGitProject && isGitInstalled) {
446
- const shouldInitGit =
447
- yesFlag ||
448
- (await confirm("Would you like to use git to manage this Worker?"));
449
- if (shouldInitGit) {
450
- await execa("git", ["init"], {
451
- cwd: creationDirectory,
452
- });
453
- await execa("git", ["branch", "-m", "main"], {
454
- cwd: creationDirectory,
455
- });
456
- await writeFile(
457
- path.join(creationDirectory, ".gitignore"),
458
- readFileSync(path.join(__dirname, "../templates/gitignore"))
459
- );
460
- logger.log(
461
- args.name && args.name !== "."
462
- ? `✨ Initialized git repository at ${path.relative(
463
- process.cwd(),
464
- creationDirectory
465
- )}`
466
- : `✨ Initialized git repository`
467
- );
468
- }
469
- }
470
-
471
- const isolatedInit = !!args.name;
472
- let pathToPackageJson = await findPath(
473
- isolatedInit,
474
- creationDirectory,
475
- "package.json"
476
- );
477
- let shouldCreatePackageJson = false;
478
-
479
- if (!pathToPackageJson) {
480
- // If no package.json exists, ask to create one
481
- shouldCreatePackageJson =
482
- yesFlag ||
483
- (await confirm(
484
- "No package.json found. Would you like to create one?"
485
- ));
486
-
487
- if (shouldCreatePackageJson) {
488
- await writeFile(
489
- path.join(creationDirectory, "./package.json"),
490
- JSON.stringify(
491
- {
492
- name: workerName,
493
- version: "0.0.0",
494
- devDependencies: {
495
- wrangler: wranglerVersion,
496
- },
497
- private: true,
498
- },
499
- null,
500
- " "
501
- ) + "\n"
502
- );
503
-
504
- shouldRunPackageManagerInstall = true;
505
- pathToPackageJson = path.join(creationDirectory, "package.json");
506
- logger.log(
507
- `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
508
- );
509
- } else {
510
- return;
511
- }
512
- } else {
513
- // If package.json exists and wrangler isn't installed,
514
- // then ask to add wrangler to devDependencies
515
- const packageJson = parsePackageJSON(
516
- readFileSync(pathToPackageJson),
517
- pathToPackageJson
518
- );
519
- if (
520
- !(
521
- packageJson.devDependencies?.wrangler ||
522
- packageJson.dependencies?.wrangler
523
- )
524
- ) {
525
- const shouldInstall =
526
- yesFlag ||
527
- (await confirm(
528
- `Would you like to install wrangler into ${path.relative(
529
- process.cwd(),
530
- pathToPackageJson
531
- )}?`
532
- ));
533
- if (shouldInstall) {
534
- devDepsToInstall.push(`wrangler@${wranglerVersion}`);
535
- }
536
- }
537
- }
538
-
539
- let isTypescriptProject = false;
540
- let pathToTSConfig = await findPath(
541
- isolatedInit,
542
- creationDirectory,
543
- "tsconfig.json"
544
- );
545
- if (!pathToTSConfig) {
546
- // If there's no tsconfig, offer to create one
547
- // and install @cloudflare/workers-types
548
- if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
549
- isTypescriptProject = true;
550
- await writeFile(
551
- path.join(creationDirectory, "./tsconfig.json"),
552
- readFileSync(path.join(__dirname, "../templates/tsconfig.json"))
553
- );
554
- devDepsToInstall.push("@cloudflare/workers-types");
555
- devDepsToInstall.push("typescript");
556
- pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
557
- logger.log(
558
- `✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`
559
- );
560
- }
561
- } else {
562
- isTypescriptProject = true;
563
- // If there's a tsconfig, check if @cloudflare/workers-types
564
- // is already installed, and offer to install it if not
565
- const packageJson = parsePackageJSON(
566
- readFileSync(pathToPackageJson),
567
- pathToPackageJson
568
- );
569
- if (
570
- !(
571
- packageJson.devDependencies?.["@cloudflare/workers-types"] ||
572
- packageJson.dependencies?.["@cloudflare/workers-types"]
573
- )
574
- ) {
575
- const shouldInstall = await confirm(
576
- "Would you like to install the type definitions for Workers into your package.json?"
577
- );
578
- if (shouldInstall) {
579
- devDepsToInstall.push("@cloudflare/workers-types");
580
- // We don't update the tsconfig.json because
581
- // it could be complicated in existing projects
582
- // and we don't want to break them. Instead, we simply
583
- // tell the user that they need to update their tsconfig.json
584
- instructions.push(
585
- `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
586
- process.cwd(),
587
- pathToTSConfig
588
- )}`
589
- );
590
- }
591
- }
592
- }
593
-
594
- const packageJsonContent = parsePackageJSON(
595
- readFileSync(pathToPackageJson),
596
- pathToPackageJson
597
- );
598
- const shouldWritePackageJsonScripts =
599
- !packageJsonContent.scripts?.start &&
600
- !packageJsonContent.scripts?.publish &&
601
- shouldCreatePackageJson;
602
-
603
- /*
604
- * Passes the array of accumulated devDeps to install through to
605
- * the package manager. Also generates a human-readable list
606
- * of packages it installed.
607
- * If there are no devDeps to install, optionally runs
608
- * the package manager's install command.
609
- */
610
- async function installPackages(
611
- shouldRunInstall: boolean,
612
- depsToInstall: string[]
613
- ) {
614
- //lets install the devDeps they asked for
615
- //and run their package manager's install command if needed
616
- if (depsToInstall.length > 0) {
617
- const formatter = new Intl.ListFormat("en", {
618
- style: "long",
619
- type: "conjunction",
620
- });
621
- await packageManager.addDevDeps(...depsToInstall);
622
- const versionlessPackages = depsToInstall.map((dep) =>
623
- dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
624
- );
625
-
626
- logger.log(
627
- `✨ Installed ${formatter.format(
628
- versionlessPackages
629
- )} into devDependencies`
630
- );
631
- } else {
632
- if (shouldRunInstall) {
633
- await packageManager.install();
634
- }
635
- }
636
- }
637
-
638
- async function writePackageJsonScriptsAndUpdateWranglerToml(
639
- isWritingScripts: boolean,
640
- isCreatingWranglerToml: boolean,
641
- packagePath: string,
642
- scriptPath: string,
643
- extraToml: TOML.JsonMap
644
- ) {
645
- if (isCreatingWranglerToml) {
646
- // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
647
- const parsedWranglerToml = parseTOML(
648
- readFileSync(wranglerTomlDestination)
649
- );
650
- const newToml = {
651
- name: parsedWranglerToml.name,
652
- main: scriptPath,
653
- compatibility_date: parsedWranglerToml.compatibility_date,
654
- ...extraToml,
655
- };
656
- fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
657
- }
658
- const isNamedWorker =
659
- isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
660
-
661
- if (isWritingScripts) {
662
- await writeFile(
663
- packagePath,
664
- JSON.stringify(
665
- {
666
- ...packageJsonContent,
667
- scripts: {
668
- ...packageJsonContent.scripts,
669
- start: isCreatingWranglerToml
670
- ? `wrangler dev`
671
- : `wrangler dev ${scriptPath}`,
672
- deploy: isCreatingWranglerToml
673
- ? `wrangler publish`
674
- : `wrangler publish ${scriptPath}`,
675
- },
676
- },
677
- null,
678
- 2
679
- ) + "\n"
680
- );
681
- instructions.push(
682
- `\nTo start developing your Worker, run \`${
683
- isNamedWorker ? `cd ${args.name} && ` : ""
684
- }npm start\``
685
- );
686
- instructions.push(
687
- `To publish your Worker to the Internet, run \`npm run deploy\``
688
- );
689
- } else {
690
- instructions.push(
691
- `\nTo start developing your Worker, run \`npx wrangler dev\`${
692
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
693
- }`
694
- );
695
- instructions.push(
696
- `To publish your Worker to the Internet, run \`npx wrangler publish\`${
697
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
698
- }`
699
- );
700
- }
701
- }
702
-
703
- async function getNewWorkerType(newWorkerFilename: string) {
704
- return select(
705
- `Would you like to create a Worker at ${newWorkerFilename}?`,
706
- [
707
- {
708
- value: "none",
709
- label: "None",
710
- },
711
- {
712
- value: "fetch",
713
- label: "Fetch handler",
714
- },
715
- {
716
- value: "scheduled",
717
- label: "Scheduled handler",
718
- },
719
- ],
720
- 1
721
- ) as Promise<"none" | "fetch" | "scheduled">;
722
- }
723
-
724
- function getNewWorkerTemplate(
725
- lang: "js" | "ts",
726
- workerType: "fetch" | "scheduled"
727
- ) {
728
- const templates = {
729
- "js-fetch": "new-worker.js",
730
- "js-scheduled": "new-worker-scheduled.js",
731
- "ts-fetch": "new-worker.ts",
732
- "ts-scheduled": "new-worker-scheduled.ts",
733
- };
734
-
735
- return templates[`${lang}-${workerType}`];
736
- }
737
-
738
- function getNewWorkerToml(
739
- workerType: "fetch" | "scheduled"
740
- ): TOML.JsonMap {
741
- if (workerType === "scheduled") {
742
- return {
743
- triggers: {
744
- crons: ["1 * * * *"],
745
- },
746
- };
747
- }
748
-
749
- return {};
750
- }
751
-
752
- if (isTypescriptProject) {
753
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
754
- const newWorkerFilename = path.relative(
755
- process.cwd(),
756
- path.join(creationDirectory, "./src/index.ts")
757
- );
758
-
759
- const newWorkerType = yesFlag
760
- ? "fetch"
761
- : await getNewWorkerType(newWorkerFilename);
762
-
763
- if (newWorkerType !== "none") {
764
- const template = getNewWorkerTemplate("ts", newWorkerType);
765
-
766
- await mkdir(path.join(creationDirectory, "./src"), {
767
- recursive: true,
768
- });
769
- await writeFile(
770
- path.join(creationDirectory, "./src/index.ts"),
771
- readFileSync(path.join(__dirname, `../templates/${template}`))
772
- );
773
-
774
- logger.log(
775
- `✨ Created ${path.relative(
776
- process.cwd(),
777
- path.join(creationDirectory, "./src/index.ts")
778
- )}`
779
- );
780
-
781
- await writePackageJsonScriptsAndUpdateWranglerToml(
782
- shouldWritePackageJsonScripts,
783
- justCreatedWranglerToml,
784
- pathToPackageJson,
785
- "src/index.ts",
786
- getNewWorkerToml(newWorkerType)
787
- );
788
- }
789
- }
790
- } else {
791
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
792
- const newWorkerFilename = path.relative(
793
- process.cwd(),
794
- path.join(creationDirectory, "./src/index.js")
795
- );
796
-
797
- const newWorkerType = yesFlag
798
- ? "fetch"
799
- : await getNewWorkerType(newWorkerFilename);
800
-
801
- if (newWorkerType !== "none") {
802
- const template = getNewWorkerTemplate("js", newWorkerType);
803
-
804
- await mkdir(path.join(creationDirectory, "./src"), {
805
- recursive: true,
806
- });
807
- await writeFile(
808
- path.join(creationDirectory, "./src/index.js"),
809
- readFileSync(path.join(__dirname, `../templates/${template}`))
810
- );
811
-
812
- logger.log(
813
- `✨ Created ${path.relative(
814
- process.cwd(),
815
- path.join(creationDirectory, "./src/index.js")
816
- )}`
817
- );
818
-
819
- await writePackageJsonScriptsAndUpdateWranglerToml(
820
- shouldWritePackageJsonScripts,
821
- justCreatedWranglerToml,
822
- pathToPackageJson,
823
- "src/index.js",
824
- getNewWorkerToml(newWorkerType)
825
- );
826
- }
827
- }
828
- }
829
- // install packages as the final step of init
830
- try {
831
- await installPackages(shouldRunPackageManagerInstall, devDepsToInstall);
832
- } catch (e) {
833
- // fetching packages could fail due to loss of internet, etc
834
- // we should let folks know we failed to fetch, but their
835
- // workers project is still ready to go
836
- logger.error(e instanceof Error ? e.message : e);
837
- instructions.push(
838
- "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
839
- );
840
- }
841
-
842
- // let users know what to do now
843
- instructions.forEach((instruction) => logger.log(instruction));
844
- }
845
- );
846
-
847
- // build
848
- wrangler.command(
849
- "build",
850
- false,
851
- (yargs) => {
852
- return yargs.option("env", {
853
- describe: "Perform on a specific environment",
854
- type: "string",
855
- });
856
- },
857
- async (buildArgs) => {
858
- // "[DEPRECATED] 🦀 Build your project (if applicable)",
859
-
860
- const envFlag = buildArgs.env ? ` --env=${buildArgs.env}` : "";
861
- logger.log(
862
- formatMessage({
863
- kind: "warning",
864
- text: "Deprecation: `wrangler build` has been deprecated.",
865
- notes: [
866
- {
867
- text: "Please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#build for more information.",
868
- },
869
- {
870
- text: `Attempting to run \`wrangler publish --dry-run --outdir=dist${envFlag}\` for you instead:`,
871
- },
872
- ],
873
- })
874
- );
875
-
876
- await createCLIParser([
877
- "publish",
878
- "--dry-run",
879
- "--outdir=dist",
880
- ...(buildArgs.env ? ["--env", buildArgs.env] : []),
881
- ]).parse();
882
- }
883
- );
884
-
885
- // config
886
- wrangler.command(
887
- "config",
888
- false,
889
- () => {},
890
- () => {
891
- // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
892
- throw new DeprecationError(
893
- "`wrangler config` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#config for alternatives"
894
- );
895
- }
896
- );
897
-
898
- // dev
899
- wrangler.command(
900
- "dev [script]",
901
- "👂 Start a local server for developing your worker",
902
- (yargs) => {
903
- return yargs
904
- .positional("script", {
905
- describe: "The path to an entry point for your worker",
906
- type: "string",
907
- })
908
- .option("name", {
909
- describe: "Name of the worker",
910
- type: "string",
911
- requiresArg: true,
912
- })
913
- .option("format", {
914
- choices: ["modules", "service-worker"] as const,
915
- describe: "Choose an entry type",
916
- deprecated: true,
917
- })
918
- .option("env", {
919
- describe: "Perform on a specific environment",
920
- type: "string",
921
- requiresArg: true,
922
- alias: "e",
923
- })
924
- .option("compatibility-date", {
925
- describe: "Date to use for compatibility checks",
926
- type: "string",
927
- requiresArg: true,
928
- })
929
- .option("compatibility-flags", {
930
- describe: "Flags to use for compatibility checks",
931
- alias: "compatibility-flag",
932
- type: "string",
933
- requiresArg: true,
934
- array: true,
935
- })
936
- .option("latest", {
937
- describe: "Use the latest version of the worker runtime",
938
- type: "boolean",
939
- default: true,
940
- })
941
- .option("ip", {
942
- describe: "IP address to listen on, defaults to `localhost`",
943
- type: "string",
944
- requiresArg: true,
945
- })
946
- .option("port", {
947
- describe: "Port to listen on",
948
- type: "number",
949
- })
950
- .option("inspector-port", {
951
- describe: "Port for devtools to connect to",
952
- type: "number",
953
- })
954
- .option("routes", {
955
- describe: "Routes to upload",
956
- alias: "route",
957
- type: "string",
958
- requiresArg: true,
959
- array: true,
960
- })
961
- .option("host", {
962
- type: "string",
963
- requiresArg: true,
964
- describe:
965
- "Host to forward requests to, defaults to the zone of project",
966
- })
967
- .option("local-protocol", {
968
- describe: "Protocol to listen to requests on, defaults to http.",
969
- choices: ["http", "https"] as const,
970
- })
971
- .option("experimental-public", {
972
- describe: "Static assets to be served",
973
- type: "string",
974
- requiresArg: true,
975
- deprecated: true,
976
- hidden: true,
977
- })
978
- .option("assets", {
979
- describe: "Static assets to be served",
980
- type: "string",
981
- requiresArg: true,
982
- })
983
- .option("site", {
984
- describe: "Root folder of static assets for Workers Sites",
985
- type: "string",
986
- requiresArg: true,
987
- })
988
- .option("site-include", {
989
- describe:
990
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
991
- type: "string",
992
- requiresArg: true,
993
- array: true,
994
- })
995
- .option("site-exclude", {
996
- describe:
997
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
998
- type: "string",
999
- requiresArg: true,
1000
- array: true,
1001
- })
1002
- .option("upstream-protocol", {
1003
- describe:
1004
- "Protocol to forward requests to host on, defaults to https.",
1005
- choices: ["http", "https"] as const,
1006
- })
1007
- .option("jsx-factory", {
1008
- describe: "The function that is called for each JSX element",
1009
- type: "string",
1010
- requiresArg: true,
1011
- })
1012
- .option("jsx-fragment", {
1013
- describe: "The function that is called for each JSX fragment",
1014
- type: "string",
1015
- requiresArg: true,
1016
- })
1017
- .option("tsconfig", {
1018
- describe: "Path to a custom tsconfig.json file",
1019
- type: "string",
1020
- requiresArg: true,
1021
- })
1022
- .option("local", {
1023
- alias: "l",
1024
- describe: "Run on my machine",
1025
- type: "boolean",
1026
- default: false, // I bet this will a point of contention. We'll revisit it.
1027
- })
1028
- .option("minify", {
1029
- describe: "Minify the script",
1030
- type: "boolean",
1031
- })
1032
- .option("node-compat", {
1033
- describe: "Enable node.js compatibility",
1034
- type: "boolean",
1035
- })
1036
- .option("experimental-enable-local-persistence", {
1037
- describe: "Enable persistence for this session (only for local mode)",
1038
- type: "boolean",
1039
- })
1040
- .option("inspect", {
1041
- describe: "Enable dev tools",
1042
- type: "boolean",
1043
- deprecated: true,
1044
- })
1045
- .option("legacy-env", {
1046
- type: "boolean",
1047
- describe: "Use legacy environments",
1048
- hidden: true,
1049
- });
1050
- },
1051
- async (args) => {
1052
- let watcher: ReturnType<typeof watch> | undefined;
1053
- try {
1054
- await printWranglerBanner();
1055
- const configPath =
1056
- (args.config as ConfigPath) ||
1057
- ((args.script &&
1058
- findWranglerToml(path.dirname(args.script))) as ConfigPath);
1059
- let config = readConfig(configPath, args);
1060
-
1061
- if (config.configPath) {
1062
- watcher = watch(config.configPath, {
1063
- persistent: true,
1064
- }).on("change", async (_event) => {
1065
- // TODO: Do we need to handle different `_event` types differently?
1066
- // e.g. what if the file is deleted, or added?
1067
- config = readConfig(configPath, args);
1068
- if (config.configPath) {
1069
- logger.log(`${path.basename(config.configPath)} changed...`);
1070
- rerender(await getDevReactElement(config));
1071
- }
1072
- });
1073
- }
1074
-
1075
- const entry = await getEntry(args, config, "dev");
1076
-
1077
- if (config.services && config.services.length > 0) {
1078
- logger.warn(
1079
- `This worker is bound to live services: ${config.services
1080
- .map(
1081
- (service) =>
1082
- `${service.binding} (${service.service}${
1083
- service.environment ? `@${service.environment}` : ""
1084
- })`
1085
- )
1086
- .join(", ")}`
1087
- );
1088
- }
1089
-
1090
- if (args.inspect) {
1091
- logger.warn(
1092
- "Passing --inspect is unnecessary, now you can always connect to devtools."
1093
- );
1094
- }
1095
-
1096
- if (args["experimental-public"]) {
1097
- throw new Error(
1098
- "The --experimental-public field has been renamed to --assets"
1099
- );
1100
- }
1101
-
1102
- if (args.public) {
1103
- throw new Error("The --public field has been renamed to --assets");
1104
- }
1105
-
1106
- if ((args.assets || config.assets) && (args.site || config.site)) {
1107
- throw new Error(
1108
- "Cannot use Assets and Workers Sites in the same Worker."
1109
- );
1110
- }
1111
-
1112
- const upstreamProtocol =
1113
- args["upstream-protocol"] || config.dev.upstream_protocol;
1114
- if (upstreamProtocol === "http") {
1115
- logger.warn(
1116
- "Setting upstream-protocol to http is not currently implemented.\n" +
1117
- "If this is required in your project, please add your use case to the following issue:\n" +
1118
- "https://github.com/cloudflare/wrangler2/issues/583."
1119
- );
1120
- }
1121
-
1122
- // TODO: if worker_dev = false and no routes, then error (only for dev)
1123
-
1124
- // Compute zone info from the `host` and `route` args and config;
1125
- let host = args.host || config.dev.host;
1126
- let zoneId: string | undefined;
1127
-
1128
- if (!args.local) {
1129
- if (host) {
1130
- zoneId = await getZoneIdFromHost(host);
1131
- }
1132
- const routes = args.routes || config.route || config.routes;
1133
- if (!zoneId && routes) {
1134
- const firstRoute = Array.isArray(routes) ? routes[0] : routes;
1135
- const zone = await getZoneForRoute(firstRoute);
1136
- if (zone) {
1137
- zoneId = zone.id;
1138
- host = zone.host;
1139
- }
1140
- }
1141
- }
1142
-
1143
- const nodeCompat = args.nodeCompat ?? config.node_compat;
1144
- if (nodeCompat) {
1145
- logger.warn(
1146
- "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
1147
- );
1148
- }
1149
-
1150
- // eslint-disable-next-line no-inner-declarations
1151
- async function getBindings(configParam: Config) {
1152
- return {
1153
- kv_namespaces: configParam.kv_namespaces?.map(
1154
- ({ binding, preview_id, id: _id }) => {
1155
- // In `dev`, we make folks use a separate kv namespace called
1156
- // `preview_id` instead of `id` so that they don't
1157
- // break production data. So here we check that a `preview_id`
1158
- // has actually been configured.
1159
- // This whole block of code will be obsoleted in the future
1160
- // when we have copy-on-write for previews on edge workers.
1161
- if (!preview_id) {
1162
- // TODO: This error has to be a _lot_ better, ideally just asking
1163
- // to create a preview namespace for the user automatically
1164
- throw new Error(
1165
- `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`
1166
- ); // Ugh, I really don't like this message very much
1167
- }
1168
- return {
1169
- binding,
1170
- id: preview_id,
1171
- };
1172
- }
1173
- ),
1174
- // Use a copy of combinedVars since we're modifying it later
1175
- vars: getVarsForDev(configParam),
1176
- wasm_modules: configParam.wasm_modules,
1177
- text_blobs: configParam.text_blobs,
1178
- data_blobs: configParam.data_blobs,
1179
- durable_objects: configParam.durable_objects,
1180
- r2_buckets: configParam.r2_buckets?.map(
1181
- ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
1182
- // same idea as kv namespace preview id,
1183
- // same copy-on-write TODO
1184
- if (!preview_bucket_name) {
1185
- throw new Error(
1186
- `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
1187
- );
1188
- }
1189
- return {
1190
- binding,
1191
- bucket_name: preview_bucket_name,
1192
- };
1193
- }
1194
- ),
1195
- services: configParam.services,
1196
- unsafe: configParam.unsafe?.bindings,
1197
- };
1198
- }
1199
-
1200
- const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
1201
- const getInspectorPort = memoizeGetPort(9229);
1202
-
1203
- // eslint-disable-next-line no-inner-declarations
1204
- async function getDevReactElement(configParam: Config) {
1205
- // now log all available bindings into the terminal
1206
- const bindings = await getBindings(configParam);
1207
- // mask anything that was overridden in .dev.vars
1208
- // so that we don't log potential secrets into the terminal
1209
- const maskedVars = { ...bindings.vars };
1210
- for (const key of Object.keys(maskedVars)) {
1211
- if (maskedVars[key] !== configParam.vars[key]) {
1212
- // This means it was overridden in .dev.vars
1213
- // so let's mask it
1214
- maskedVars[key] = "(hidden)";
1215
- }
1216
- }
1217
-
1218
- printBindings({
1219
- ...bindings,
1220
- vars: maskedVars,
1221
- });
1222
-
1223
- const assetPaths =
1224
- args.assets || config.assets
1225
- ? getAssetPaths(config, args.assets)
1226
- : getSiteAssetPaths(
1227
- config,
1228
- args.site,
1229
- args.siteInclude,
1230
- args.siteExclude
1231
- );
1232
-
1233
- return (
1234
- <Dev
1235
- name={getScriptName(args, config)}
1236
- entry={entry}
1237
- env={args.env}
1238
- zone={zoneId}
1239
- host={host}
1240
- rules={getRules(config)}
1241
- legacyEnv={isLegacyEnv(config)}
1242
- minify={args.minify ?? config.minify}
1243
- nodeCompat={nodeCompat}
1244
- build={config.build || {}}
1245
- initialMode={args.local ? "local" : "remote"}
1246
- jsxFactory={args["jsx-factory"] || config.jsx_factory}
1247
- jsxFragment={args["jsx-fragment"] || config.jsx_fragment}
1248
- tsconfig={args.tsconfig ?? config.tsconfig}
1249
- upstreamProtocol={upstreamProtocol}
1250
- localProtocol={
1251
- args["local-protocol"] || config.dev.local_protocol
1252
- }
1253
- enableLocalPersistence={
1254
- args["experimental-enable-local-persistence"] || false
1255
- }
1256
- accountId={config.account_id}
1257
- assetPaths={assetPaths}
1258
- port={args.port || config.dev.port || (await getLocalPort())}
1259
- ip={args.ip || config.dev.ip}
1260
- inspectorPort={
1261
- args["inspector-port"] ?? (await getInspectorPort())
1262
- }
1263
- isWorkersSite={Boolean(args.site || config.site)}
1264
- compatibilityDate={getDevCompatibilityDate(
1265
- config,
1266
- args["compatibility-date"]
1267
- )}
1268
- compatibilityFlags={
1269
- args["compatibility-flags"] || config.compatibility_flags
1270
- }
1271
- usageModel={config.usage_model}
1272
- bindings={bindings}
1273
- crons={config.triggers.crons}
1274
- />
1275
- );
1276
- }
1277
- const { waitUntilExit, rerender } = render(
1278
- await getDevReactElement(config)
1279
- );
1280
- await waitUntilExit();
1281
- } finally {
1282
- await watcher?.close();
1283
- }
1284
- }
1285
- );
1286
-
1287
- // publish
1288
- wrangler.command(
1289
- "publish [script]",
1290
- "🆙 Publish your Worker to Cloudflare.",
1291
- (yargs) => {
1292
- return yargs
1293
- .option("env", {
1294
- type: "string",
1295
- requiresArg: true,
1296
- describe: "Perform on a specific environment",
1297
- alias: "e",
1298
- })
1299
- .positional("script", {
1300
- describe: "The path to an entry point for your worker",
1301
- type: "string",
1302
- requiresArg: true,
1303
- })
1304
- .option("name", {
1305
- describe: "Name of the worker",
1306
- type: "string",
1307
- requiresArg: true,
1308
- })
1309
- .option("outdir", {
1310
- describe: "Output directory for the bundled worker",
1311
- type: "string",
1312
- requiresArg: true,
1313
- })
1314
- .option("format", {
1315
- choices: ["modules", "service-worker"] as const,
1316
- describe: "Choose an entry type",
1317
- deprecated: true,
1318
- })
1319
- .option("compatibility-date", {
1320
- describe: "Date to use for compatibility checks",
1321
- type: "string",
1322
- requiresArg: true,
1323
- })
1324
- .option("compatibility-flags", {
1325
- describe: "Flags to use for compatibility checks",
1326
- alias: "compatibility-flag",
1327
- type: "string",
1328
- requiresArg: true,
1329
- array: true,
1330
- })
1331
- .option("latest", {
1332
- describe: "Use the latest version of the worker runtime",
1333
- type: "boolean",
1334
- default: false,
1335
- })
1336
- .option("experimental-public", {
1337
- describe: "Static assets to be served",
1338
- type: "string",
1339
- requiresArg: true,
1340
- deprecated: true,
1341
- hidden: true,
1342
- })
1343
- .option("assets", {
1344
- describe: "Static assets to be served",
1345
- type: "string",
1346
- requiresArg: true,
1347
- })
1348
- .option("site", {
1349
- describe: "Root folder of static assets for Workers Sites",
1350
- type: "string",
1351
- requiresArg: true,
1352
- })
1353
- .option("site-include", {
1354
- describe:
1355
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
1356
- type: "string",
1357
- requiresArg: true,
1358
- array: true,
1359
- })
1360
- .option("site-exclude", {
1361
- describe:
1362
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
1363
- type: "string",
1364
- requiresArg: true,
1365
- array: true,
1366
- })
1367
- .option("triggers", {
1368
- describe: "cron schedules to attach",
1369
- alias: ["schedule", "schedules"],
1370
- type: "string",
1371
- requiresArg: true,
1372
- array: true,
1373
- })
1374
- .option("routes", {
1375
- describe: "Routes to upload",
1376
- alias: "route",
1377
- type: "string",
1378
- requiresArg: true,
1379
- array: true,
1380
- })
1381
- .option("jsx-factory", {
1382
- describe: "The function that is called for each JSX element",
1383
- type: "string",
1384
- requiresArg: true,
1385
- })
1386
- .option("jsx-fragment", {
1387
- describe: "The function that is called for each JSX fragment",
1388
- type: "string",
1389
- requiresArg: true,
1390
- })
1391
- .option("tsconfig", {
1392
- describe: "Path to a custom tsconfig.json file",
1393
- type: "string",
1394
- requiresArg: true,
1395
- })
1396
- .option("minify", {
1397
- describe: "Minify the script",
1398
- type: "boolean",
1399
- })
1400
- .option("node-compat", {
1401
- describe: "Enable node.js compatibility",
1402
- type: "boolean",
1403
- })
1404
- .option("dry-run", {
1405
- describe: "Don't actually publish",
1406
- type: "boolean",
1407
- })
1408
- .option("legacy-env", {
1409
- type: "boolean",
1410
- describe: "Use legacy environments",
1411
- hidden: true,
1412
- });
1413
- },
1414
- async (args) => {
1415
- await printWranglerBanner();
1416
-
1417
- const configPath =
1418
- (args.config as ConfigPath) ||
1419
- (args.script && findWranglerToml(path.dirname(args.script)));
1420
- const config = readConfig(configPath, args);
1421
- const entry = await getEntry(args, config, "publish");
1422
-
1423
- if (args.public) {
1424
- throw new Error("The --public field has been renamed to --assets");
1425
- }
1426
- if (args["experimental-public"]) {
1427
- throw new Error(
1428
- "The --experimental-public field has been renamed to --assets"
1429
- );
1430
- }
1431
-
1432
- if ((args.assets || config.assets) && (args.site || config.site)) {
1433
- throw new Error(
1434
- "Cannot use Assets and Workers Sites in the same Worker."
1435
- );
1436
- }
1437
-
1438
- if (args.latest) {
1439
- logger.warn(
1440
- "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"
1441
- );
1442
- }
1443
-
1444
- const accountId = args.dryRun ? undefined : await requireAuth(config);
1445
-
1446
- const assetPaths =
1447
- args.assets || config.assets
1448
- ? getAssetPaths(config, args.assets)
1449
- : getSiteAssetPaths(
1450
- config,
1451
- args.site,
1452
- args.siteInclude,
1453
- args.siteExclude
1454
- );
1455
-
1456
- await publish({
1457
- config,
1458
- accountId,
1459
- name: getScriptName(args, config),
1460
- rules: getRules(config),
1461
- entry,
1462
- env: args.env,
1463
- compatibilityDate: args.latest
1464
- ? new Date().toISOString().substring(0, 10)
1465
- : args["compatibility-date"],
1466
- compatibilityFlags: args["compatibility-flags"],
1467
- triggers: args.triggers,
1468
- jsxFactory: args["jsx-factory"],
1469
- jsxFragment: args["jsx-fragment"],
1470
- tsconfig: args.tsconfig,
1471
- routes: args.routes,
1472
- assetPaths,
1473
- legacyEnv: isLegacyEnv(config),
1474
- minify: args.minify,
1475
- nodeCompat: args.nodeCompat,
1476
- isWorkersSite: Boolean(args.site || config.site),
1477
- outDir: args.outdir,
1478
- dryRun: args.dryRun,
1479
- });
1480
- }
1481
- );
1482
-
1483
- // tail
1484
- wrangler.command(
1485
- "tail [name]",
1486
- "🦚 Starts a log tailing session for a published Worker.",
1487
- (yargs) => {
1488
- return yargs
1489
- .positional("name", {
1490
- describe: "Name of the worker",
1491
- type: "string",
1492
- })
1493
- .option("format", {
1494
- default: process.stdout.isTTY ? "pretty" : "json",
1495
- choices: ["json", "pretty"],
1496
- describe: "The format of log entries",
1497
- })
1498
- .option("status", {
1499
- choices: ["ok", "error", "canceled"],
1500
- describe: "Filter by invocation status",
1501
- array: true,
1502
- })
1503
- .option("header", {
1504
- type: "string",
1505
- requiresArg: true,
1506
- describe: "Filter by HTTP header",
1507
- })
1508
- .option("method", {
1509
- type: "string",
1510
- requiresArg: true,
1511
- describe: "Filter by HTTP method",
1512
- array: true,
1513
- })
1514
- .option("sampling-rate", {
1515
- type: "number",
1516
- describe: "Adds a percentage of requests to log sampling rate",
1517
- })
1518
- .option("search", {
1519
- type: "string",
1520
- requiresArg: true,
1521
- describe: "Filter by a text match in console.log messages",
1522
- })
1523
- .option("ip", {
1524
- type: "string",
1525
- requiresArg: true,
1526
- describe:
1527
- 'Filter by the IP address the request originates from. Use "self" to filter for your own IP',
1528
- array: true,
1529
- })
1530
- .option("env", {
1531
- type: "string",
1532
- requiresArg: true,
1533
- describe: "Perform on a specific environment",
1534
- alias: "e",
1535
- })
1536
- .option("debug", {
1537
- type: "boolean",
1538
- hidden: true,
1539
- default: false,
1540
- describe:
1541
- "If a log would have been filtered out, send it through anyway alongside the filter which would have blocked it.",
1542
- })
1543
- .option("legacy-env", {
1544
- type: "boolean",
1545
- describe: "Use legacy environments",
1546
- hidden: true,
1547
- });
1548
- },
1549
- async (args) => {
1550
- if (args.format === "pretty") {
1551
- await printWranglerBanner();
1552
- }
1553
- const config = readConfig(args.config as ConfigPath, args);
1554
-
1555
- const scriptName = getLegacyScriptName(args, config);
1556
-
1557
- if (!scriptName) {
1558
- throw new Error("Missing script name");
1559
- }
1560
-
1561
- const accountId = await requireAuth(config);
1562
-
1563
- const cliFilters: TailCLIFilters = {
1564
- status: args.status as ("ok" | "error" | "canceled")[] | undefined,
1565
- header: args.header,
1566
- method: args.method,
1567
- samplingRate: args["sampling-rate"],
1568
- search: args.search,
1569
- clientIp: args.ip,
1570
- };
1571
-
1572
- const filters = translateCLICommandToFilterMessage(
1573
- cliFilters,
1574
- args.debug
1575
- );
1576
-
1577
- const { tail, expiration, deleteTail } = await createTail(
1578
- accountId,
1579
- scriptName,
1580
- filters,
1581
- !isLegacyEnv(config) ? args.env : undefined
1582
- );
1583
-
1584
- const scriptDisplayName = `${scriptName}${
1585
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1586
- }`;
1587
-
1588
- if (args.format === "pretty") {
1589
- logger.log(
1590
- `Successfully created tail, expires at ${expiration.toLocaleString()}`
1591
- );
1592
- }
1593
-
1594
- onExit(async () => {
1595
- tail.terminate();
1596
- await deleteTail();
1597
- });
1598
-
1599
- const printLog: (data: RawData) => void =
1600
- args.format === "pretty" ? prettyPrintLogs : jsonPrintLogs;
1601
-
1602
- tail.on("message", printLog);
1603
-
1604
- while (tail.readyState !== tail.OPEN) {
1605
- switch (tail.readyState) {
1606
- case tail.CONNECTING:
1607
- await setTimeout(100);
1608
- break;
1609
- case tail.CLOSING:
1610
- await setTimeout(100);
1611
- break;
1612
- case tail.CLOSED:
1613
- throw new Error(
1614
- `Connection to ${scriptDisplayName} closed unexpectedly.`
1615
- );
1616
- }
1617
- }
1618
-
1619
- if (args.format === "pretty") {
1620
- logger.log(`Connected to ${scriptDisplayName}, waiting for logs...`);
1621
- }
1622
-
1623
- tail.on("close", async () => {
1624
- tail.terminate();
1625
- await deleteTail();
1626
- });
1627
- }
1628
- );
1629
-
1630
- // preview
1631
- wrangler.command(
1632
- "preview [method] [body]",
1633
- false,
1634
- (yargs) => {
1635
- return yargs
1636
- .positional("method", {
1637
- type: "string",
1638
- describe: "Type of request to preview your worker",
1639
- })
1640
- .positional("body", {
1641
- type: "string",
1642
- describe: "Body string to post to your preview worker request.",
1643
- })
1644
- .option("env", {
1645
- type: "string",
1646
- requiresArg: true,
1647
- describe: "Perform on a specific environment",
1648
- })
1649
- .option("watch", {
1650
- default: true,
1651
- describe: "Enable live preview",
1652
- type: "boolean",
1653
- });
1654
- },
1655
- async (args) => {
1656
- if (args.method || args.body) {
1657
- throw new DeprecationError(
1658
- "The `wrangler preview` command has been deprecated.\n" +
1659
- "Try using `wrangler dev` to to try out a worker during development.\n"
1660
- );
1661
- }
1662
-
1663
- // Delegate to `wrangler dev`
1664
- logger.warn(
1665
- "***************************************************\n" +
1666
- "The `wrangler preview` command has been deprecated.\n" +
1667
- "Attempting to run `wrangler dev` instead.\n" +
1668
- "***************************************************\n"
1669
- );
1670
-
1671
- const config = readConfig(args.config as ConfigPath, args);
1672
- const entry = await getEntry({}, config, "dev");
1673
-
1674
- const accountId = await requireAuth(config);
1675
-
1676
- const { waitUntilExit } = render(
1677
- <Dev
1678
- name={config.name}
1679
- entry={entry}
1680
- rules={getRules(config)}
1681
- env={args.env}
1682
- zone={undefined}
1683
- host={undefined}
1684
- legacyEnv={isLegacyEnv(config)}
1685
- build={config.build || {}}
1686
- minify={undefined}
1687
- nodeCompat={config.node_compat}
1688
- initialMode={args.local ? "local" : "remote"}
1689
- jsxFactory={config.jsx_factory}
1690
- jsxFragment={config.jsx_fragment}
1691
- tsconfig={config.tsconfig}
1692
- upstreamProtocol={config.dev.upstream_protocol}
1693
- localProtocol={config.dev.local_protocol}
1694
- enableLocalPersistence={false}
1695
- accountId={accountId}
1696
- assetPaths={undefined}
1697
- port={
1698
- config.dev.port || (await getPort({ port: DEFAULT_LOCAL_PORT }))
1699
- }
1700
- ip={config.dev.ip}
1701
- isWorkersSite={false}
1702
- compatibilityDate={getDevCompatibilityDate(config)}
1703
- compatibilityFlags={config.compatibility_flags}
1704
- usageModel={config.usage_model}
1705
- bindings={{
1706
- kv_namespaces: config.kv_namespaces?.map(
1707
- ({ binding, preview_id, id: _id }) => {
1708
- // In `dev`, we make folks use a separate kv namespace called
1709
- // `preview_id` instead of `id` so that they don't
1710
- // break production data. So here we check that a `preview_id`
1711
- // has actually been configured.
1712
- // This whole block of code will be obsoleted in the future
1713
- // when we have copy-on-write for previews on edge workers.
1714
- if (!preview_id) {
1715
- // TODO: This error has to be a _lot_ better, ideally just asking
1716
- // to create a preview namespace for the user automatically
1717
- throw new Error(
1718
- `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`
1719
- ); // Ugh, I really don't like this message very much
1720
- }
1721
- return {
1722
- binding,
1723
- id: preview_id,
1724
- };
1725
- }
1726
- ),
1727
- vars: config.vars,
1728
- wasm_modules: config.wasm_modules,
1729
- text_blobs: config.text_blobs,
1730
- data_blobs: config.data_blobs,
1731
- durable_objects: config.durable_objects,
1732
- r2_buckets: config.r2_buckets?.map(
1733
- ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
1734
- // same idea as kv namespace preview id,
1735
- // same copy-on-write TODO
1736
- if (!preview_bucket_name) {
1737
- throw new Error(
1738
- `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
1739
- );
1740
- }
1741
- return {
1742
- binding,
1743
- bucket_name: preview_bucket_name,
1744
- };
1745
- }
1746
- ),
1747
- services: config.services,
1748
- unsafe: config.unsafe?.bindings,
1749
- }}
1750
- crons={config.triggers.crons}
1751
- inspectorPort={await getPort({ port: 9229 })}
1752
- />
1753
- );
1754
- await waitUntilExit();
1755
- }
1756
- );
1757
-
1758
- // [DEPRECATED] route
1759
- wrangler.command(
1760
- "route",
1761
- false, // I think we want to hide this command
1762
- // "➡️ List or delete worker routes",
1763
- (routeYargs) => {
1764
- return routeYargs
1765
- .command(
1766
- "list",
1767
- "List the routes associated with a zone",
1768
- (yargs) => {
1769
- return yargs
1770
- .option("env", {
1771
- type: "string",
1772
- requiresArg: true,
1773
- describe: "Perform on a specific environment",
1774
- })
1775
- .option("zone", {
1776
- type: "string",
1777
- requiresArg: true,
1778
- describe: "Zone id",
1779
- })
1780
- .positional("zone", {
1781
- describe: "Zone id",
1782
- type: "string",
1783
- });
1784
- },
1785
- () => {
1786
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1787
- const deprecationNotice =
1788
- "`wrangler route list` has been deprecated.";
1789
- const futureRoutes =
1790
- "Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.";
1791
- const presentRoutes =
1792
- "Refer to the Cloudflare Dashboard to see the routes this worker is currently running on.";
1793
- throw new DeprecationError(
1794
- `${deprecationNotice}\n${futureRoutes}\n${presentRoutes}`
1795
- );
1796
- }
1797
- )
1798
- .command(
1799
- "delete [id]",
1800
- "Delete a route associated with a zone",
1801
- (yargs) => {
1802
- return yargs
1803
- .positional("id", {
1804
- describe: "The hash of the route ID to delete.",
1805
- type: "string",
1806
- })
1807
- .option("zone", {
1808
- type: "string",
1809
- requiresArg: true,
1810
- describe: "zone id",
1811
- })
1812
- .option("env", {
1813
- type: "string",
1814
- requiresArg: true,
1815
- describe: "Perform on a specific environment",
1816
- });
1817
- },
1818
- () => {
1819
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1820
- const deprecationNotice =
1821
- "`wrangler route delete` has been deprecated.";
1822
- const shouldDo =
1823
- "Remove the unwanted route(s) from wrangler.toml and run `wrangler publish` to remove your worker from those routes.";
1824
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1825
- }
1826
- );
1827
- },
1828
- () => {
1829
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1830
- const deprecationNotice = "`wrangler route` has been deprecated.";
1831
- const shouldDo =
1832
- "Please use wrangler.toml and/or `wrangler publish --routes` to modify routes";
1833
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1834
- }
1835
- );
1836
-
1837
- // subdomain
1838
- wrangler.command(
1839
- "subdomain [name]",
1840
- false,
1841
- // "👷 Create or change your workers.dev subdomain.",
1842
- (yargs) => {
1843
- return yargs.positional("name", { type: "string" });
1844
- },
1845
- () => {
1846
- throw new DeprecationError(
1847
- "`wrangler subdomain` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#subdomain for alternatives"
1848
- );
1849
- }
1850
- );
1851
-
1852
- // secret
1853
- wrangler.command(
1854
- "secret",
1855
- "🤫 Generate a secret that can be referenced in the worker script",
1856
- (secretYargs) => {
1857
- return secretYargs
1858
- .command(subHelp)
1859
- .option("legacy-env", {
1860
- type: "boolean",
1861
- describe: "Use legacy environments",
1862
- hidden: true,
1863
- })
1864
- .command(
1865
- "put <key>",
1866
- "Create or update a secret variable for a script",
1867
- (yargs) => {
1868
- return yargs
1869
- .positional("key", {
1870
- describe: "The variable name to be accessible in the script",
1871
- type: "string",
1872
- })
1873
- .option("name", {
1874
- describe: "Name of the worker",
1875
- type: "string",
1876
- requiresArg: true,
1877
- })
1878
- .option("env", {
1879
- type: "string",
1880
- requiresArg: true,
1881
- describe:
1882
- "Binds the secret to the Worker of the specific environment",
1883
- alias: "e",
1884
- });
1885
- },
1886
- async (args) => {
1887
- await printWranglerBanner();
1888
- const config = readConfig(args.config as ConfigPath, args);
1889
-
1890
- const scriptName = getLegacyScriptName(args, config);
1891
- if (!scriptName) {
1892
- throw new Error("Missing script name");
1893
- }
1894
-
1895
- const accountId = await requireAuth(config);
1896
-
1897
- const isInteractive = process.stdin.isTTY;
1898
- const secretValue = trimTrailingWhitespace(
1899
- isInteractive
1900
- ? await prompt("Enter a secret value:", "password")
1901
- : await readFromStdin()
1902
- );
1903
-
1904
- logger.log(
1905
- `🌀 Creating the secret for script ${scriptName} ${
1906
- args.env && !isLegacyEnv(config) ? `(${args.env})` : ""
1907
- }`
1908
- );
1909
-
1910
- async function submitSecret() {
1911
- const url =
1912
- !args.env || isLegacyEnv(config)
1913
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1914
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1915
-
1916
- return await fetchResult(url, {
1917
- method: "PUT",
1918
- headers: { "Content-Type": "application/json" },
1919
- body: JSON.stringify({
1920
- name: args.key,
1921
- text: secretValue,
1922
- type: "secret_text",
1923
- }),
1924
- });
1925
- }
1926
-
1927
- const createDraftWorker = async () => {
1928
- // TODO: log a warning
1929
- await fetchResult(
1930
- !isLegacyEnv(config) && args.env
1931
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}`
1932
- : `/accounts/${accountId}/workers/scripts/${scriptName}`,
1933
- {
1934
- method: "PUT",
1935
- body: createWorkerUploadForm({
1936
- name: scriptName,
1937
- main: {
1938
- name: scriptName,
1939
- content: `export default { fetch() {} }`,
1940
- type: "esm",
1941
- },
1942
- bindings: {
1943
- kv_namespaces: [],
1944
- vars: {},
1945
- durable_objects: { bindings: [] },
1946
- r2_buckets: [],
1947
- services: [],
1948
- wasm_modules: {},
1949
- text_blobs: {},
1950
- data_blobs: {},
1951
- unsafe: [],
1952
- },
1953
- modules: [],
1954
- migrations: undefined,
1955
- compatibility_date: undefined,
1956
- compatibility_flags: undefined,
1957
- usage_model: undefined,
1958
- }),
1959
- }
1960
- );
1961
- };
1962
-
1963
- function isMissingWorkerError(e: unknown): e is { code: 10007 } {
1964
- return (
1965
- typeof e === "object" &&
1966
- e !== null &&
1967
- (e as { code: number }).code === 10007
1968
- );
1969
- }
1970
-
1971
- try {
1972
- await submitSecret();
1973
- } catch (e) {
1974
- if (isMissingWorkerError(e)) {
1975
- // create a draft worker and try again
1976
- await createDraftWorker();
1977
- await submitSecret();
1978
- // TODO: delete the draft worker if this failed too?
1979
- } else {
1980
- throw e;
1981
- }
1982
- }
1983
-
1984
- logger.log(`✨ Success! Uploaded secret ${args.key}`);
1985
- }
1986
- )
1987
- .command(
1988
- "delete <key>",
1989
- "Delete a secret variable from a script",
1990
- async (yargs) => {
1991
- await printWranglerBanner();
1992
- return yargs
1993
- .positional("key", {
1994
- describe: "The variable name to be accessible in the script",
1995
- type: "string",
1996
- })
1997
- .option("name", {
1998
- describe: "Name of the worker",
1999
- type: "string",
2000
- requiresArg: true,
2001
- })
2002
- .option("env", {
2003
- type: "string",
2004
- requiresArg: true,
2005
- describe:
2006
- "Binds the secret to the Worker of the specific environment",
2007
- alias: "e",
2008
- });
2009
- },
2010
- async (args) => {
2011
- const config = readConfig(args.config as ConfigPath, args);
2012
-
2013
- const scriptName = getLegacyScriptName(args, config);
2014
- if (!scriptName) {
2015
- throw new Error("Missing script name");
2016
- }
2017
-
2018
- const accountId = await requireAuth(config);
2019
-
2020
- if (
2021
- await confirm(
2022
- `Are you sure you want to permanently delete the variable ${
2023
- args.key
2024
- } on the script ${scriptName}${
2025
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
2026
- }?`
2027
- )
2028
- ) {
2029
- logger.log(
2030
- `🌀 Deleting the secret ${args.key} on script ${scriptName}${
2031
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
2032
- }`
2033
- );
2034
-
2035
- const url =
2036
- !args.env || isLegacyEnv(config)
2037
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
2038
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
2039
-
2040
- await fetchResult(`${url}/${args.key}`, { method: "DELETE" });
2041
- logger.log(`✨ Success! Deleted secret ${args.key}`);
2042
- }
2043
- }
2044
- )
2045
- .command(
2046
- "list",
2047
- "List all secrets for a script",
2048
- (yargs) => {
2049
- return yargs
2050
- .option("name", {
2051
- describe: "Name of the worker",
2052
- type: "string",
2053
- requiresArg: true,
2054
- })
2055
- .option("env", {
2056
- type: "string",
2057
- requiresArg: true,
2058
- describe:
2059
- "Binds the secret to the Worker of the specific environment.",
2060
- alias: "e",
2061
- });
2062
- },
2063
- async (args) => {
2064
- const config = readConfig(args.config as ConfigPath, args);
2065
-
2066
- const scriptName = getLegacyScriptName(args, config);
2067
- if (!scriptName) {
2068
- throw new Error("Missing script name");
2069
- }
2070
-
2071
- const accountId = await requireAuth(config);
2072
-
2073
- const url =
2074
- !args.env || isLegacyEnv(config)
2075
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
2076
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
2077
-
2078
- logger.log(JSON.stringify(await fetchResult(url), null, " "));
2079
- }
2080
- );
2081
- }
2082
- );
2083
-
2084
- // kv
2085
- // :namespace
2086
- wrangler.command(
2087
- "kv:namespace",
2088
- "🗂️ Interact with your Workers KV Namespaces",
2089
- (namespaceYargs) => {
2090
- return namespaceYargs
2091
- .command(subHelp)
2092
- .command(
2093
- "create <namespace>",
2094
- "Create a new namespace",
2095
- (yargs) => {
2096
- return yargs
2097
- .positional("namespace", {
2098
- describe: "The name of the new namespace",
2099
- type: "string",
2100
- demandOption: true,
2101
- })
2102
- .option("env", {
2103
- type: "string",
2104
- requiresArg: true,
2105
- describe: "Perform on a specific environment",
2106
- alias: "e",
2107
- })
2108
- .option("preview", {
2109
- type: "boolean",
2110
- describe: "Interact with a preview namespace",
2111
- });
2112
- },
2113
- async (args) => {
2114
- await printWranglerBanner();
2115
-
2116
- if (!isValidKVNamespaceBinding(args.namespace)) {
2117
- throw new CommandLineArgsError(
2118
- `The namespace binding name "${args.namespace}" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.`
2119
- );
2120
- }
2121
-
2122
- const config = readConfig(args.config as ConfigPath, args);
2123
- if (!config.name) {
2124
- logger.warn(
2125
- "No configured name present, using `worker` as a prefix for the title"
2126
- );
2127
- }
2128
-
2129
- const name = config.name || "worker";
2130
- const environment = args.env ? `-${args.env}` : "";
2131
- const preview = args.preview ? "_preview" : "";
2132
- const title = `${name}${environment}-${args.namespace}${preview}`;
2133
-
2134
- const accountId = await requireAuth(config);
2135
-
2136
- // TODO: generate a binding name stripping non alphanumeric chars
2137
-
2138
- logger.log(`🌀 Creating namespace with title "${title}"`);
2139
- const namespaceId = await createKVNamespace(accountId, title);
2140
-
2141
- logger.log("✨ Success!");
2142
- const envString = args.env ? ` under [env.${args.env}]` : "";
2143
- const previewString = args.preview ? "preview_" : "";
2144
- logger.log(
2145
- `Add the following to your configuration file in your kv_namespaces array${envString}:`
2146
- );
2147
- logger.log(
2148
- `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
2149
- );
2150
-
2151
- // TODO: automatically write this block to the wrangler.toml config file??
2152
- }
2153
- )
2154
- .command(
2155
- "list",
2156
- "Outputs a list of all KV namespaces associated with your account id.",
2157
- {},
2158
- async (args) => {
2159
- const config = readConfig(args.config as ConfigPath, args);
2160
-
2161
- const accountId = await requireAuth(config);
2162
-
2163
- // TODO: we should show bindings if they exist for given ids
2164
-
2165
- logger.log(
2166
- JSON.stringify(await listKVNamespaces(accountId), null, " ")
2167
- );
2168
- }
2169
- )
2170
- .command(
2171
- "delete",
2172
- "Deletes a given namespace.",
2173
- (yargs) => {
2174
- return yargs
2175
- .option("binding", {
2176
- type: "string",
2177
- requiresArg: true,
2178
- describe: "The name of the namespace to delete",
2179
- })
2180
- .option("namespace-id", {
2181
- type: "string",
2182
- requiresArg: true,
2183
- describe: "The id of the namespace to delete",
2184
- })
2185
- .check(demandOneOfOption("binding", "namespace-id"))
2186
- .option("env", {
2187
- type: "string",
2188
- requiresArg: true,
2189
- describe: "Perform on a specific environment",
2190
- alias: "e",
2191
- })
2192
- .option("preview", {
2193
- type: "boolean",
2194
- describe: "Interact with a preview namespace",
2195
- });
2196
- },
2197
- async (args) => {
2198
- await printWranglerBanner();
2199
- const config = readConfig(args.config as ConfigPath, args);
2200
-
2201
- let id;
2202
- try {
2203
- id = getKVNamespaceId(args, config);
2204
- } catch (e) {
2205
- throw new CommandLineArgsError(
2206
- "Not able to delete namespace.\n" + ((e as Error).message ?? e)
2207
- );
2208
- }
2209
-
2210
- const accountId = await requireAuth(config);
2211
-
2212
- await deleteKVNamespace(accountId, id);
2213
-
2214
- // TODO: recommend they remove it from wrangler.toml
2215
-
2216
- // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
2217
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
2218
- // n
2219
- // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
2220
- // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
2221
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
2222
- // y
2223
- // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
2224
- // ✨ Success
2225
- // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
2226
- // ➜ test-mf
2227
-
2228
- // TODO: do it automatically
2229
-
2230
- // TODO: delete the preview namespace as well?
2231
- }
2232
- );
2233
- }
2234
- );
2235
-
2236
- // :key
2237
- wrangler.command(
2238
- "kv:key",
2239
- "🔑 Individually manage Workers KV key-value pairs",
2240
- (kvKeyYargs) => {
2241
- return kvKeyYargs
2242
- .command(subHelp)
2243
- .command(
2244
- "put <key> [value]",
2245
- "Writes a single key/value pair to the given namespace.",
2246
- (yargs) => {
2247
- return yargs
2248
- .positional("key", {
2249
- type: "string",
2250
- describe: "The key to write to",
2251
- demandOption: true,
2252
- })
2253
- .positional("value", {
2254
- type: "string",
2255
- describe: "The value to write",
2256
- })
2257
- .option("binding", {
2258
- type: "string",
2259
- requiresArg: true,
2260
- describe: "The binding of the namespace to write to",
2261
- })
2262
- .option("namespace-id", {
2263
- type: "string",
2264
- requiresArg: true,
2265
- describe: "The id of the namespace to write to",
2266
- })
2267
- .check(demandOneOfOption("binding", "namespace-id"))
2268
- .option("env", {
2269
- type: "string",
2270
- requiresArg: true,
2271
- describe: "Perform on a specific environment",
2272
- alias: "e",
2273
- })
2274
- .option("preview", {
2275
- type: "boolean",
2276
- describe: "Interact with a preview namespace",
2277
- })
2278
- .option("ttl", {
2279
- type: "number",
2280
- describe: "Time for which the entries should be visible",
2281
- })
2282
- .option("expiration", {
2283
- type: "number",
2284
- describe:
2285
- "Time since the UNIX epoch after which the entry expires",
2286
- })
2287
- .option("path", {
2288
- type: "string",
2289
- requiresArg: true,
2290
- describe: "Read value from the file at a given path",
2291
- })
2292
- .check(demandOneOfOption("value", "path"));
2293
- },
2294
- async ({ key, ttl, expiration, ...args }) => {
2295
- await printWranglerBanner();
2296
- const config = readConfig(args.config as ConfigPath, args);
2297
- const namespaceId = getKVNamespaceId(args, config);
2298
- // One of `args.path` and `args.value` must be defined
2299
- const value = args.path
2300
- ? readFileSyncToBuffer(args.path)
2301
- : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2302
- args.value!;
2303
-
2304
- if (args.path) {
2305
- logger.log(
2306
- `Writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}.`
2307
- );
2308
- } else {
2309
- logger.log(
2310
- `Writing the value "${value}" to key "${key}" on namespace ${namespaceId}.`
2311
- );
2312
- }
2313
-
2314
- const accountId = await requireAuth(config);
2315
-
2316
- await putKVKeyValue(accountId, namespaceId, {
2317
- key,
2318
- value,
2319
- expiration,
2320
- expiration_ttl: ttl,
2321
- });
2322
- }
2323
- )
2324
- .command(
2325
- "list",
2326
- "Outputs a list of all keys in a given namespace.",
2327
- (yargs) => {
2328
- return yargs
2329
- .option("binding", {
2330
- type: "string",
2331
- requiresArg: true,
2332
- describe: "The name of the namespace to list",
2333
- })
2334
- .option("namespace-id", {
2335
- type: "string",
2336
- requiresArg: true,
2337
- describe: "The id of the namespace to list",
2338
- })
2339
- .check(demandOneOfOption("binding", "namespace-id"))
2340
- .option("env", {
2341
- type: "string",
2342
- requiresArg: true,
2343
- describe: "Perform on a specific environment",
2344
- alias: "e",
2345
- })
2346
- .option("preview", {
2347
- type: "boolean",
2348
- // In the case of listing keys we will default to non-preview mode
2349
- default: false,
2350
- describe: "Interact with a preview namespace",
2351
- })
2352
- .option("prefix", {
2353
- type: "string",
2354
- requiresArg: true,
2355
- describe: "A prefix to filter listed keys",
2356
- });
2357
- },
2358
- async ({ prefix, ...args }) => {
2359
- // TODO: support for limit+cursor (pagination)
2360
- const config = readConfig(args.config as ConfigPath, args);
2361
- const namespaceId = getKVNamespaceId(args, config);
2362
-
2363
- const accountId = await requireAuth(config);
2364
-
2365
- const results = await listKVNamespaceKeys(
2366
- accountId,
2367
- namespaceId,
2368
- prefix
2369
- );
2370
- logger.log(JSON.stringify(results, undefined, 2));
2371
- }
2372
- )
2373
- .command(
2374
- "get <key>",
2375
- "Reads a single value by key from the given namespace.",
2376
- (yargs) => {
2377
- return yargs
2378
- .positional("key", {
2379
- describe: "The key value to get.",
2380
- type: "string",
2381
- demandOption: true,
2382
- })
2383
- .option("binding", {
2384
- type: "string",
2385
- requiresArg: true,
2386
- describe: "The name of the namespace to get from",
2387
- })
2388
- .option("namespace-id", {
2389
- type: "string",
2390
- requiresArg: true,
2391
- describe: "The id of the namespace to get from",
2392
- })
2393
- .check(demandOneOfOption("binding", "namespace-id"))
2394
- .option("env", {
2395
- type: "string",
2396
- requiresArg: true,
2397
- describe: "Perform on a specific environment",
2398
- alias: "e",
2399
- })
2400
- .option("preview", {
2401
- type: "boolean",
2402
- describe: "Interact with a preview namespace",
2403
- })
2404
- .option("preview", {
2405
- type: "boolean",
2406
- // In the case of getting key values we will default to non-preview mode
2407
- default: false,
2408
- describe: "Interact with a preview namespace",
2409
- });
2410
- },
2411
- async ({ key, ...args }) => {
2412
- const config = readConfig(args.config as ConfigPath, args);
2413
- const namespaceId = getKVNamespaceId(args, config);
2414
-
2415
- const accountId = await requireAuth(config);
2416
-
2417
- process.stdout.write(
2418
- Buffer.from(await getKVKeyValue(accountId, namespaceId, key))
2419
- );
2420
- }
2421
- )
2422
- .command(
2423
- "delete <key>",
2424
- "Removes a single key value pair from the given namespace.",
2425
- (yargs) => {
2426
- return yargs
2427
- .positional("key", {
2428
- describe: "The key value to delete",
2429
- type: "string",
2430
- demandOption: true,
2431
- })
2432
- .option("binding", {
2433
- type: "string",
2434
- requiresArg: true,
2435
- describe: "The name of the namespace to delete from",
2436
- })
2437
- .option("namespace-id", {
2438
- type: "string",
2439
- requiresArg: true,
2440
- describe: "The id of the namespace to delete from",
2441
- })
2442
- .check(demandOneOfOption("binding", "namespace-id"))
2443
- .option("env", {
2444
- type: "string",
2445
- requiresArg: true,
2446
- describe: "Perform on a specific environment",
2447
- alias: "e",
2448
- })
2449
- .option("preview", {
2450
- type: "boolean",
2451
- describe: "Interact with a preview namespace",
2452
- });
2453
- },
2454
- async ({ key, ...args }) => {
2455
- await printWranglerBanner();
2456
- const config = readConfig(args.config as ConfigPath, args);
2457
- const namespaceId = getKVNamespaceId(args, config);
2458
-
2459
- logger.log(
2460
- `Deleting the key "${key}" on namespace ${namespaceId}.`
2461
- );
2462
-
2463
- const accountId = await requireAuth(config);
2464
-
2465
- await deleteKVKeyValue(accountId, namespaceId, key);
2466
- }
2467
- );
2468
- }
2469
- );
2470
-
2471
- // :bulk
2472
- wrangler.command(
2473
- "kv:bulk",
2474
- "💪 Interact with multiple Workers KV key-value pairs at once",
2475
- (kvBulkYargs) => {
2476
- return kvBulkYargs
2477
- .command(subHelp)
2478
- .command(
2479
- "put <filename>",
2480
- "Upload multiple key-value pairs to a namespace",
2481
- (yargs) => {
2482
- return yargs
2483
- .positional("filename", {
2484
- describe: `The JSON file of key-value pairs to upload, in form [{"key":..., "value":...}"...]`,
2485
- type: "string",
2486
- demandOption: true,
2487
- })
2488
- .option("binding", {
2489
- type: "string",
2490
- requiresArg: true,
2491
- describe: "The name of the namespace to insert values into",
2492
- })
2493
- .option("namespace-id", {
2494
- type: "string",
2495
- requiresArg: true,
2496
- describe: "The id of the namespace to insert values into",
2497
- })
2498
- .check(demandOneOfOption("binding", "namespace-id"))
2499
- .option("env", {
2500
- type: "string",
2501
- requiresArg: true,
2502
- describe: "Perform on a specific environment",
2503
- alias: "e",
2504
- })
2505
- .option("preview", {
2506
- type: "boolean",
2507
- describe: "Interact with a preview namespace",
2508
- });
2509
- },
2510
- async ({ filename, ...args }) => {
2511
- await printWranglerBanner();
2512
- // The simplest implementation I could think of.
2513
- // This could be made more efficient with a streaming parser/uploader
2514
- // but we'll do that in the future if needed.
2515
-
2516
- const config = readConfig(args.config as ConfigPath, args);
2517
- const namespaceId = getKVNamespaceId(args, config);
2518
- const content = parseJSON(readFileSync(filename), filename);
2519
-
2520
- if (!Array.isArray(content)) {
2521
- throw new Error(
2522
- `Unexpected JSON input from "${filename}".\n` +
2523
- `Expected an array of key-value objects but got type "${typeof content}".`
2524
- );
2525
- }
2526
-
2527
- const errors: string[] = [];
2528
- const warnings: string[] = [];
2529
- for (let i = 0; i < content.length; i++) {
2530
- const keyValue = content[i];
2531
- if (!isKVKeyValue(keyValue)) {
2532
- errors.push(
2533
- `The item at index ${i} is ${JSON.stringify(keyValue)}`
2534
- );
2535
- } else {
2536
- const props = unexpectedKVKeyValueProps(keyValue);
2537
- if (props.length > 0) {
2538
- warnings.push(
2539
- `The item at index ${i} contains unexpected properties: ${JSON.stringify(
2540
- props
2541
- )}.`
2542
- );
2543
- }
2544
- }
2545
- }
2546
- if (warnings.length > 0) {
2547
- logger.warn(
2548
- `Unexpected key-value properties in "${filename}".\n` +
2549
- warnings.join("\n")
2550
- );
2551
- }
2552
- if (errors.length > 0) {
2553
- throw new Error(
2554
- `Unexpected JSON input from "${filename}".\n` +
2555
- `Each item in the array should be an object that matches:\n\n` +
2556
- `interface KeyValue {\n` +
2557
- ` key: string;\n` +
2558
- ` value: string;\n` +
2559
- ` expiration?: number;\n` +
2560
- ` expiration_ttl?: number;\n` +
2561
- ` metadata?: object;\n` +
2562
- ` base64?: boolean;\n` +
2563
- `}\n\n` +
2564
- errors.join("\n")
2565
- );
2566
- }
2567
-
2568
- const accountId = await requireAuth(config);
2569
- await putKVBulkKeyValue(accountId, namespaceId, content);
2570
-
2571
- logger.log("Success!");
2572
- }
2573
- )
2574
- .command(
2575
- "delete <filename>",
2576
- "Delete multiple key-value pairs from a namespace",
2577
- (yargs) => {
2578
- return yargs
2579
- .positional("filename", {
2580
- describe: `The JSON file of keys to delete, in the form ["key1", "key2", ...]`,
2581
- type: "string",
2582
- demandOption: true,
2583
- })
2584
- .option("binding", {
2585
- type: "string",
2586
- requiresArg: true,
2587
- describe: "The name of the namespace to delete from",
2588
- })
2589
- .option("namespace-id", {
2590
- type: "string",
2591
- requiresArg: true,
2592
- describe: "The id of the namespace to delete from",
2593
- })
2594
- .check(demandOneOfOption("binding", "namespace-id"))
2595
- .option("env", {
2596
- type: "string",
2597
- requiresArg: true,
2598
- describe: "Perform on a specific environment",
2599
- alias: "e",
2600
- })
2601
- .option("preview", {
2602
- type: "boolean",
2603
- describe: "Interact with a preview namespace",
2604
- })
2605
- .option("force", {
2606
- type: "boolean",
2607
- alias: "f",
2608
- describe: "Do not ask for confirmation before deleting",
2609
- });
2610
- },
2611
- async ({ filename, ...args }) => {
2612
- await printWranglerBanner();
2613
- const config = readConfig(args.config as ConfigPath, args);
2614
- const namespaceId = getKVNamespaceId(args, config);
2615
-
2616
- if (!args.force) {
2617
- const result = await confirm(
2618
- `Are you sure you want to delete all the keys read from "${filename}" from kv-namespace with id "${namespaceId}"?`
2619
- );
2620
- if (!result) {
2621
- logger.log(`Not deleting keys read from "${filename}".`);
2622
- return;
2623
- }
2624
- }
2625
-
2626
- const content = parseJSON(
2627
- readFileSync(filename),
2628
- filename
2629
- ) as string[];
2630
-
2631
- if (!Array.isArray(content)) {
2632
- throw new Error(
2633
- `Unexpected JSON input from "${filename}".\n` +
2634
- `Expected an array of strings but got:\n${content}`
2635
- );
2636
- }
2637
-
2638
- const errors: string[] = [];
2639
- for (let i = 0; i < content.length; i++) {
2640
- const key = content[i];
2641
- if (typeof key !== "string") {
2642
- errors.push(
2643
- `The item at index ${i} is type: "${typeof key}" - ${JSON.stringify(
2644
- key
2645
- )}`
2646
- );
2647
- }
2648
- }
2649
- if (errors.length > 0) {
2650
- throw new Error(
2651
- `Unexpected JSON input from "${filename}".\n` +
2652
- `Expected an array of strings.\n` +
2653
- errors.join("\n")
2654
- );
2655
- }
2656
-
2657
- const accountId = await requireAuth(config);
2658
-
2659
- await deleteKVBulkKeyValue(accountId, namespaceId, content);
2660
-
2661
- logger.log("Success!");
2662
- }
2663
- );
2664
- }
2665
- );
2666
-
2667
- wrangler.command(
2668
- "pages",
2669
- "⚡️ Configure Cloudflare Pages",
2670
- async (pagesYargs) => {
2671
- await pages(pagesYargs.command(subHelp).epilogue(pagesBetaWarning));
2672
- }
2673
- );
2674
-
2675
- wrangler.command("r2", "📦 Interact with an R2 store", (r2Yargs) => {
2676
- return r2Yargs
2677
- .command(subHelp)
2678
- .command("bucket", "Manage R2 buckets", (r2BucketYargs) => {
2679
- r2BucketYargs.command(
2680
- "create <name>",
2681
- "Create a new R2 bucket",
2682
- (yargs) => {
2683
- return yargs.positional("name", {
2684
- describe: "The name of the new bucket",
2685
- type: "string",
2686
- demandOption: true,
2687
- });
2688
- },
2689
- async (args) => {
2690
- await printWranglerBanner();
2691
-
2692
- const config = readConfig(args.config as ConfigPath, args);
2693
-
2694
- const accountId = await requireAuth(config);
2695
-
2696
- logger.log(`Creating bucket ${args.name}.`);
2697
- await createR2Bucket(accountId, args.name);
2698
- logger.log(`Created bucket ${args.name}.`);
2699
- }
2700
- );
2701
-
2702
- r2BucketYargs.command("list", "List R2 buckets", {}, async (args) => {
2703
- const config = readConfig(args.config as ConfigPath, args);
2704
-
2705
- const accountId = await requireAuth(config);
2706
-
2707
- logger.log(JSON.stringify(await listR2Buckets(accountId), null, 2));
2708
- });
2709
-
2710
- r2BucketYargs.command(
2711
- "delete <name>",
2712
- "Delete an R2 bucket",
2713
- (yargs) => {
2714
- return yargs.positional("name", {
2715
- describe: "The name of the bucket to delete",
2716
- type: "string",
2717
- demandOption: true,
2718
- });
2719
- },
2720
- async (args) => {
2721
- await printWranglerBanner();
2722
-
2723
- const config = readConfig(args.config as ConfigPath, args);
2724
-
2725
- const accountId = await requireAuth(config);
2726
-
2727
- logger.log(`Deleting bucket ${args.name}.`);
2728
- await deleteR2Bucket(accountId, args.name);
2729
- logger.log(`Deleted bucket ${args.name}.`);
2730
- }
2731
- );
2732
- return r2BucketYargs;
2733
- });
2734
- });
2735
-
2736
- /**
2737
- * User Group: login, logout, and whoami
2738
- * TODO: group commands into User group similar to .group() for flags in yargs
2739
- */
2740
- // login
2741
- wrangler.command(
2742
- // this needs scopes as an option?
2743
- "login",
2744
- "🔓 Login to Cloudflare",
2745
- (yargs) => {
2746
- // TODO: This needs some copy editing
2747
- // I mean, this entire app does, but this too.
2748
- return yargs
2749
- .option("scopes-list", {
2750
- describe: "List all the available OAuth scopes with descriptions",
2751
- })
2752
- .option("scopes", {
2753
- describe: "Pick the set of applicable OAuth scopes when logging in",
2754
- array: true,
2755
- type: "string",
2756
- requiresArg: true,
2757
- });
2758
-
2759
- // TODO: scopes
2760
- },
2761
- async (args) => {
2762
- await printWranglerBanner();
2763
- if (args["scopes-list"]) {
2764
- listScopes();
2765
- return;
2766
- }
2767
- if (args.scopes) {
2768
- if (args.scopes.length === 0) {
2769
- // don't allow no scopes to be passed, that would be weird
2770
- listScopes();
2771
- return;
2772
- }
2773
- if (!validateScopeKeys(args.scopes)) {
2774
- throw new CommandLineArgsError(
2775
- `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
2776
- );
2777
- }
2778
- await login({ scopes: args.scopes });
2779
- return;
2780
- }
2781
- await login();
2782
-
2783
- // TODO: would be nice if it optionally saved login
2784
- // credentials inside node_modules/.cache or something
2785
- // this way you could have multiple users on a single machine
2786
- }
2787
- );
2788
-
2789
- // logout
2790
- wrangler.command(
2791
- // this needs scopes as an option?
2792
- "logout",
2793
- "🚪 Logout from Cloudflare",
2794
- () => {},
2795
- async () => {
2796
- await printWranglerBanner();
2797
- await logout();
2798
- }
2799
- );
2800
-
2801
- // whoami
2802
- wrangler.command(
2803
- "whoami",
2804
- "🕵️ Retrieve your user info and test your auth config",
2805
- () => {},
2806
- async () => {
2807
- await printWranglerBanner();
2808
- await whoami();
2809
- }
2810
- );
2811
-
2812
- wrangler.option("config", {
2813
- alias: "c",
2814
- describe: "Path to .toml configuration file",
2815
- type: "string",
2816
- requiresArg: true,
2817
- });
2818
-
2819
- wrangler.group(["config", "help", "version"], "Flags:");
2820
- wrangler.help().alias("h", "help");
2821
- wrangler.version(wranglerVersion).alias("v", "version");
2822
- wrangler.exitProcess(false);
2823
-
2824
- return wrangler;
174
+ export class CommandLineArgsError extends Error {}
175
+
176
+ export function createCLIParser(argv: string[]) {
177
+ // Type check result against CommonYargsOptions to make sure we've included
178
+ // all common options
179
+ const wrangler: Yargs.Argv<CommonYargsOptions> = makeCLI(argv)
180
+ .strict()
181
+ // We handle errors ourselves in a try-catch around `yargs.parse`.
182
+ // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
183
+ // Otherwise we just log the error that was thrown without any "help info".
184
+ .showHelpOnFail(false)
185
+ .fail((msg, error) => {
186
+ if (!error || error.name === "YError") {
187
+ // If there is no error or the error is a "YError", then this came from yargs own validation
188
+ // Wrap it in a `CommandLineArgsError` so that we can handle it appropriately further up.
189
+ error = new CommandLineArgsError(msg);
190
+ }
191
+ throw error;
192
+ })
193
+ .scriptName("wrangler")
194
+ .wrap(null)
195
+ // Define global options here, so they get included in the `Argv` type of
196
+ // the `wrangler` variable
197
+ .version(false)
198
+ .option("v", {
199
+ describe: "Show version number",
200
+ alias: "version",
201
+ type: "boolean",
202
+ })
203
+ .option("config", {
204
+ alias: "c",
205
+ describe: "Path to .toml configuration file",
206
+ type: "string",
207
+ requiresArg: true,
208
+ })
209
+ .option("env", {
210
+ alias: "e",
211
+ describe: "Environment to use for operations and .env files",
212
+ type: "string",
213
+ requiresArg: true,
214
+ })
215
+ .check((args) => {
216
+ // Grab locally specified env params from `.env` file
217
+ const loaded = loadDotEnv(".env", args.env);
218
+ for (const [key, value] of Object.entries(loaded?.parsed ?? {})) {
219
+ if (!(key in process.env)) process.env[key] = value;
220
+ }
221
+ return true;
222
+ });
223
+
224
+ wrangler.group(["config", "env", "help", "version"], "Flags:");
225
+ wrangler.help().alias("h", "help");
226
+
227
+ // Default help command that supports the subcommands
228
+ const subHelp: Yargs.CommandModule<CommonYargsOptions, CommonYargsOptions> = {
229
+ command: ["*"],
230
+ handler: async (args) => {
231
+ setImmediate(() =>
232
+ wrangler.parse([...args._.map((a) => `${a}`), "--help"])
233
+ );
234
+ },
235
+ };
236
+ wrangler.command(
237
+ ["*"],
238
+ false,
239
+ () => {},
240
+ async (args) => {
241
+ if (args._.length > 0) {
242
+ throw new CommandLineArgsError(`Unknown command: ${args._}.`);
243
+ } else {
244
+ // args.v will exist and be true in the case that no command is called, and the -v
245
+ // option is present. This is to allow for running asynchronous printWranglerBanner
246
+ // in the version command.
247
+ if (args.v) {
248
+ if (process.stdout.isTTY) {
249
+ await printWranglerBanner();
250
+ } else {
251
+ logger.log(wranglerVersion);
252
+ }
253
+ } else {
254
+ wrangler.showHelp("log");
255
+ }
256
+ }
257
+ }
258
+ );
259
+
260
+ // You will note that we use the form for all commands where we use the builder function
261
+ // to define options and subcommands.
262
+ // Further we return the result of this builder even though it's not completely necessary.
263
+ // The reason is that it's required for type inference of the args in the handle function.
264
+ // I wish we could enforce this pattern, but this comment will have to do for now.
265
+ // (It's also annoying that choices[] doesn't get inferred as an enum. 🤷‍♂.)
266
+
267
+ // docs
268
+ wrangler.command(
269
+ "docs [command]",
270
+ "📚 Open wrangler's docs in your browser",
271
+ docsOptions,
272
+ docsHandler
273
+ );
274
+
275
+ // init
276
+ wrangler.command(
277
+ "init [name]",
278
+ "📥 Initialize a basic Worker project, including a wrangler.toml file",
279
+ initOptions,
280
+ initHandler
281
+ );
282
+
283
+ // generate
284
+ wrangler.command(
285
+ "generate [name] [template]",
286
+ "✨ Generate a new Worker project from an existing Worker template. See https://github.com/cloudflare/templates",
287
+ generateOptions,
288
+ generateHandler
289
+ );
290
+
291
+ // [DEPRECATED] build
292
+ wrangler.command("build", false, buildOptions, buildHandler);
293
+
294
+ // [DEPRECATED] config
295
+ wrangler.command("config", false, noOpOptions, configHandler);
296
+
297
+ // dev
298
+ wrangler.command(
299
+ "dev [script]",
300
+ "👂 Start a local server for developing your worker",
301
+ devOptions,
302
+ devHandler
303
+ );
304
+
305
+ // publish
306
+ wrangler.command(
307
+ "publish [script]",
308
+ "🆙 Publish your Worker to Cloudflare.",
309
+ publishOptions,
310
+ publishHandler
311
+ );
312
+
313
+ // delete
314
+ wrangler.command(
315
+ "delete [script]",
316
+ "🗑 Delete your Worker from Cloudflare.",
317
+ deleteOptions,
318
+ deleteHandler
319
+ );
320
+
321
+ // tail
322
+ wrangler.command(
323
+ "tail [worker]",
324
+ "🦚 Starts a log tailing session for a published Worker.",
325
+ tailOptions,
326
+ tailHandler
327
+ );
328
+
329
+ // [DEPRECATED] preview
330
+ wrangler.command(
331
+ "preview [method] [body]",
332
+ false,
333
+ previewOptions,
334
+ previewHandler
335
+ );
336
+
337
+ // [DEPRECATED] route
338
+ wrangler.command(
339
+ "route",
340
+ false, // I think we want to hide this command
341
+ // "➡️ List or delete worker routes",
342
+ (routeYargs) => {
343
+ return route(routeYargs);
344
+ },
345
+ routeHandler
346
+ );
347
+
348
+ // [DEPRECATED] subdomain
349
+ wrangler.command(
350
+ "subdomain [name]",
351
+ false,
352
+ // "👷 Create or change your workers.dev subdomain.",
353
+ subdomainOptions,
354
+ subdomainHandler
355
+ );
356
+
357
+ // secret
358
+ wrangler.command(
359
+ "secret",
360
+ "🤫 Generate a secret that can be referenced in a Worker",
361
+ (secretYargs) => {
362
+ return secret(secretYargs.command(subHelp));
363
+ }
364
+ );
365
+
366
+ wrangler.command(
367
+ "secret:bulk <json>",
368
+ "🗄️ Bulk upload secrets for a Worker",
369
+ secretBulkOptions,
370
+ secretBulkHandler
371
+ );
372
+
373
+ // kv namespace
374
+ wrangler.command(
375
+ "kv:namespace",
376
+ "🗂️ Interact with your Workers KV Namespaces",
377
+ (namespaceYargs) => {
378
+ return kvNamespace(namespaceYargs.command(subHelp));
379
+ }
380
+ );
381
+
382
+ // kv key
383
+ wrangler.command(
384
+ "kv:key",
385
+ "🔑 Individually manage Workers KV key-value pairs",
386
+ (keyYargs) => {
387
+ return kvKey(keyYargs.command(subHelp));
388
+ }
389
+ );
390
+
391
+ // kv bulk
392
+ wrangler.command(
393
+ "kv:bulk",
394
+ "💪 Interact with multiple Workers KV key-value pairs at once",
395
+ (bulkYargs) => {
396
+ return kvBulk(bulkYargs.command(subHelp));
397
+ }
398
+ );
399
+
400
+ // pages
401
+ wrangler.command("pages", "⚡️ Configure Cloudflare Pages", (pagesYargs) => {
402
+ return pages(pagesYargs.command(subHelp));
403
+ });
404
+
405
+ // queues
406
+ wrangler.command("queues", "🇶 Configure Workers Queues", (queuesYargs) => {
407
+ return queues(queuesYargs.command(subHelp));
408
+ });
409
+
410
+ // r2
411
+ wrangler.command("r2", "📦 Interact with an R2 store", (r2Yargs) => {
412
+ return r2(r2Yargs.command(subHelp));
413
+ });
414
+
415
+ // dispatch-namespace
416
+ wrangler.command(
417
+ "dispatch-namespace",
418
+ "📦 Interact with a dispatch namespace",
419
+ (workerNamespaceYargs) => {
420
+ return workerNamespaceCommands(workerNamespaceYargs, subHelp);
421
+ }
422
+ );
423
+
424
+ // d1
425
+ wrangler.command("d1", "🗄 Interact with a D1 database", (d1Yargs) => {
426
+ return d1(d1Yargs.command(subHelp));
427
+ });
428
+
429
+ // pubsub
430
+ wrangler.command(
431
+ "pubsub",
432
+ "📮 Interact and manage Pub/Sub Brokers",
433
+ (pubsubYargs) => {
434
+ return pubSubCommands(pubsubYargs, subHelp);
435
+ }
436
+ );
437
+
438
+ /**
439
+ * User Group: login, logout, and whoami
440
+ * TODO: group commands into User group similar to .group() for flags in yargs
441
+ */
442
+ // login
443
+ wrangler.command(
444
+ // this needs scopes as an option?
445
+ "login",
446
+ "🔓 Login to Cloudflare",
447
+ (yargs) => {
448
+ // TODO: This needs some copy editing
449
+ // I mean, this entire app does, but this too.
450
+ return yargs
451
+ .option("scopes-list", {
452
+ describe: "List all the available OAuth scopes with descriptions",
453
+ })
454
+ .option("browser", {
455
+ default: true,
456
+ type: "boolean",
457
+ describe: "Automatically open the OAuth link in a browser",
458
+ })
459
+ .option("scopes", {
460
+ describe: "Pick the set of applicable OAuth scopes when logging in",
461
+ array: true,
462
+ type: "string",
463
+ requiresArg: true,
464
+ });
465
+
466
+ // TODO: scopes
467
+ },
468
+ async (args) => {
469
+ await printWranglerBanner();
470
+ if (args["scopes-list"]) {
471
+ listScopes();
472
+ return;
473
+ }
474
+ if (args.scopes) {
475
+ if (args.scopes.length === 0) {
476
+ // don't allow no scopes to be passed, that would be weird
477
+ listScopes();
478
+ return;
479
+ }
480
+ if (!validateScopeKeys(args.scopes)) {
481
+ throw new CommandLineArgsError(
482
+ `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
483
+ );
484
+ }
485
+ await login({ scopes: args.scopes, browser: args.browser });
486
+ return;
487
+ }
488
+ await login({ browser: args.browser });
489
+ const config = readConfig(args.config as ConfigPath, args);
490
+ await metrics.sendMetricsEvent("login user", {
491
+ sendMetrics: config.send_metrics,
492
+ });
493
+
494
+ // TODO: would be nice if it optionally saved login
495
+ // credentials inside node_modules/.cache or something
496
+ // this way you could have multiple users on a single machine
497
+ }
498
+ );
499
+
500
+ // logout
501
+ wrangler.command(
502
+ // this needs scopes as an option?
503
+ "logout",
504
+ "🚪 Logout from Cloudflare",
505
+ () => {},
506
+ async () => {
507
+ await printWranglerBanner();
508
+ await logout();
509
+ const config = readConfig(undefined, {});
510
+ await metrics.sendMetricsEvent("logout user", {
511
+ sendMetrics: config.send_metrics,
512
+ });
513
+ }
514
+ );
515
+
516
+ // whoami
517
+ wrangler.command(
518
+ "whoami",
519
+ "🕵️ Retrieve your user info and test your auth config",
520
+ () => {},
521
+ async () => {
522
+ await printWranglerBanner();
523
+ await whoami();
524
+ const config = readConfig(undefined, {});
525
+ await metrics.sendMetricsEvent("view accounts", {
526
+ sendMetrics: config.send_metrics,
527
+ });
528
+ }
529
+ );
530
+
531
+ // type generation
532
+ wrangler.command(
533
+ "types",
534
+ "📝 Generate types from bindings & module rules in config",
535
+ () => {},
536
+ async () => {
537
+ await printWranglerBanner();
538
+ const config = readConfig(undefined, {});
539
+
540
+ const configBindings: Partial<Config> = {
541
+ kv_namespaces: config.kv_namespaces ?? [],
542
+ vars: { ...config.vars },
543
+ wasm_modules: config.wasm_modules,
544
+ text_blobs: {
545
+ ...config.text_blobs,
546
+ },
547
+ data_blobs: config.data_blobs,
548
+ durable_objects: config.durable_objects,
549
+ r2_buckets: config.r2_buckets,
550
+ d1_databases: config.d1_databases,
551
+ services: config.services,
552
+ analytics_engine_datasets: config.analytics_engine_datasets,
553
+ dispatch_namespaces: config.dispatch_namespaces,
554
+ logfwdr: config.logfwdr,
555
+ unsafe: { bindings: config.unsafe?.bindings },
556
+ rules: config.rules,
557
+ queues: config.queues,
558
+ };
559
+
560
+ await generateTypes(configBindings, config);
561
+ }
562
+ );
563
+
564
+ //deployments
565
+ const deploymentsWarning =
566
+ "🚧`wrangler deployments` is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
567
+ wrangler.command(
568
+ "deployments",
569
+ "🚢 Displays the 10 most recent deployments for a worker",
570
+ (yargs) => {
571
+ yargs
572
+ .option("name", {
573
+ describe: "The name of your worker",
574
+ type: "string",
575
+ })
576
+ .epilogue(deploymentsWarning);
577
+ },
578
+ async (deploymentsYargs: ArgumentsCamelCase<{ name: string }>) => {
579
+ await printWranglerBanner();
580
+ const config = readConfig(
581
+ deploymentsYargs.config as ConfigPath,
582
+ deploymentsYargs
583
+ );
584
+ const accountId = await requireAuth(config);
585
+ const scriptName = getScriptName(
586
+ { name: deploymentsYargs.name, env: undefined },
587
+ config
588
+ );
589
+
590
+ logger.log(`${deploymentsWarning}\n`);
591
+ await deployments(accountId, scriptName);
592
+ }
593
+ );
594
+
595
+ // This set to false to allow overwrite of default behaviour
596
+ wrangler.version(false);
597
+
598
+ // version
599
+ wrangler.command(
600
+ "version",
601
+ false,
602
+ () => {},
603
+ async () => {
604
+ if (process.stdout.isTTY) {
605
+ await printWranglerBanner();
606
+ } else {
607
+ logger.log(wranglerVersion);
608
+ }
609
+ }
610
+ );
611
+
612
+ wrangler.exitProcess(false);
613
+
614
+ return wrangler;
2825
615
  }
2826
616
 
2827
617
  export async function main(argv: string[]): Promise<void> {
2828
- const wrangler = createCLIParser(argv);
2829
- try {
2830
- await wrangler.parse();
2831
- } catch (e) {
2832
- logger.log(""); // Just adds a bit of space
2833
- if (e instanceof CommandLineArgsError) {
2834
- logger.error(e.message);
2835
- // We are not able to ask the `wrangler` CLI parser to show help for a subcommand programmatically.
2836
- // The workaround is to re-run the parsing with an additional `--help` flag, which will result in the correct help message being displayed.
2837
- // 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.
2838
- await createCLIParser([...argv, "--help"]).parse();
2839
- } else if (e instanceof ParseError) {
2840
- e.notes.push({
2841
- text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/wrangler2/issues/new/choose",
2842
- });
2843
- logger.log(formatMessage(e));
2844
- } else {
2845
- logger.error(e instanceof Error ? e.message : e);
2846
- logger.log(
2847
- `${fgGreenColor}%s${resetColor}`,
2848
- "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
2849
- );
2850
- }
2851
- throw e;
2852
- }
618
+ const wrangler = createCLIParser(argv);
619
+ try {
620
+ await wrangler.parse();
621
+ } catch (e) {
622
+ logger.log(""); // Just adds a bit of space
623
+ if (e instanceof CommandLineArgsError) {
624
+ logger.error(e.message);
625
+ // We are not able to ask the `wrangler` CLI parser to show help for a subcommand programmatically.
626
+ // The workaround is to re-run the parsing with an additional `--help` flag, which will result in the correct help message being displayed.
627
+ // 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.
628
+ await createCLIParser([...argv, "--help"]).parse();
629
+ } else if (e instanceof ParseError) {
630
+ e.notes.push({
631
+ text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/wrangler2/issues/new/choose",
632
+ });
633
+ logger.log(formatMessage(e));
634
+ } else if (
635
+ e instanceof Error &&
636
+ e.message.includes("Raw mode is not supported on")
637
+ ) {
638
+ // the current terminal doesn't support raw mode, which Ink needs to render
639
+ // Ink doesn't throw a typed error or subclass or anything, so we just check the message content.
640
+ // https://github.com/vadimdemedes/ink/blob/546fe16541fd05ad4e638d6842ca4cbe88b4092b/src/components/App.tsx#L138-L148
641
+
642
+ const currentPlatform = os.platform();
643
+
644
+ const thisTerminalIsUnsupported =
645
+ "This terminal doesn't support raw mode.";
646
+ const soWranglerWontWork =
647
+ "Wrangler uses raw mode to read user input and write output to the terminal, and won't function correctly without it.";
648
+ const tryRunningItIn =
649
+ "Try running your previous command in a terminal that supports raw mode";
650
+ const oneOfThese =
651
+ currentPlatform === "win32"
652
+ ? ", such as Command Prompt or Powershell."
653
+ : currentPlatform === "darwin"
654
+ ? ", such as Terminal.app or iTerm."
655
+ : "."; // linux user detected, hand holding disengaged.
656
+
657
+ logger.error(
658
+ `${thisTerminalIsUnsupported}\n${soWranglerWontWork}\n${tryRunningItIn}${oneOfThese}`
659
+ );
660
+ } else if (isBuildFailure(e)) {
661
+ logBuildFailure(e);
662
+ logger.error(e.message);
663
+ } else {
664
+ logger.error(e instanceof Error ? e.message : e);
665
+ logger.log(
666
+ `${fgGreenColor}%s${resetColor}`,
667
+ "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
668
+ );
669
+ }
670
+ throw e;
671
+ }
2853
672
  }
2854
673
 
2855
- function getDevCompatibilityDate(
2856
- config: Config,
2857
- compatibilityDate = config.compatibility_date
674
+ export function getDevCompatibilityDate(
675
+ config: Config,
676
+ compatibilityDate = config.compatibility_date
2858
677
  ) {
2859
- const currentDate = new Date().toISOString().substring(0, 10);
2860
- if (config.configPath !== undefined && compatibilityDate === undefined) {
2861
- logger.warn(
2862
- `No compatibility_date was specified. Using today's date: ${currentDate}.\n` +
2863
- "Add one to your wrangler.toml file:\n" +
2864
- "```\n" +
2865
- `compatibility_date = "${currentDate}"\n` +
2866
- "```\n" +
2867
- "or pass it in your terminal:\n" +
2868
- "```\n" +
2869
- `--compatibility-date=${currentDate}\n` +
2870
- "```\n" +
2871
- "See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
2872
- );
2873
- }
2874
- return compatibilityDate ?? currentDate;
2875
- }
2876
-
2877
- /**
2878
- * Avoiding calling `getPort()` multiple times by memoizing the first result.
2879
- */
2880
- function memoizeGetPort(defaultPort: number) {
2881
- let portValue: number;
2882
- return async () => {
2883
- return portValue || (portValue = await getPort({ port: defaultPort }));
2884
- };
2885
- }
2886
-
2887
- /**
2888
- * Find the path to the given `basename` file from the `cwd`.
2889
- *
2890
- * If `isolatedInit` is true then we only look in the `cwd` directory for the file.
2891
- * Otherwise we also search up the tree.
2892
- */
2893
- async function findPath(
2894
- isolatedInit: boolean,
2895
- cwd: string,
2896
- basename: string
2897
- ): Promise<string | undefined> {
2898
- if (isolatedInit) {
2899
- return fs.existsSync(path.resolve(cwd, basename))
2900
- ? path.resolve(cwd, basename)
2901
- : undefined;
2902
- } else {
2903
- return await findUp(basename, {
2904
- cwd: cwd,
2905
- });
2906
- }
678
+ const currentDate = new Date().toISOString().substring(0, 10);
679
+ if (config.configPath !== undefined && compatibilityDate === undefined) {
680
+ logger.warn(
681
+ `No compatibility_date was specified. Using today's date: ${currentDate}.\n` +
682
+ "Add one to your wrangler.toml file:\n" +
683
+ "```\n" +
684
+ `compatibility_date = "${currentDate}"\n` +
685
+ "```\n" +
686
+ "or pass it in your terminal:\n" +
687
+ "```\n" +
688
+ `--compatibility-date=${currentDate}\n` +
689
+ "```\n" +
690
+ "See https://developers.cloudflare.com/workers/platform/compatibility-dates/ for more information."
691
+ );
692
+ }
693
+ return compatibilityDate ?? currentDate;
2907
694
  }