wrangler 0.0.0-e978986 → 0.0.0-e98613f8

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