wrangler 0.0.0-e64812e → 0.0.0-e6c9c5c0

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 (338) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +170 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1499 -21
  5. package/package.json +193 -152
  6. package/src/__tests__/access.test.ts +25 -0
  7. package/src/__tests__/api-dev.test.ts +238 -0
  8. package/src/__tests__/api-devregistry.test.js +64 -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 +4152 -3363
  13. package/src/__tests__/d1/d1.test.ts +127 -0
  14. package/src/__tests__/d1/splitter.test.ts +255 -0
  15. package/src/__tests__/delete.test.ts +266 -0
  16. package/src/__tests__/deployments.test.ts +105 -0
  17. package/src/__tests__/dev.test.tsx +1558 -952
  18. package/src/__tests__/generate.test.ts +238 -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-auth-domain.ts +20 -0
  24. package/src/__tests__/helpers/mock-bin.ts +20 -20
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +88 -79
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +11 -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 +12 -0
  31. package/src/__tests__/helpers/mock-kv.ts +41 -28
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +241 -233
  33. package/src/__tests__/helpers/mock-process.ts +34 -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/blob-worker.cjs +19 -0
  37. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  38. package/src/__tests__/helpers/msw/handlers/deployments.ts +69 -0
  39. package/src/__tests__/helpers/msw/handlers/namespaces.ts +81 -0
  40. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  41. package/src/__tests__/helpers/msw/handlers/r2.ts +60 -0
  42. package/src/__tests__/helpers/msw/handlers/script.ts +56 -0
  43. package/src/__tests__/helpers/msw/handlers/user.ts +52 -0
  44. package/src/__tests__/helpers/msw/handlers/zones.ts +20 -0
  45. package/src/__tests__/helpers/msw/index.ts +50 -0
  46. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  47. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  48. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  49. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  51. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  52. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  53. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  54. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  55. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  56. package/src/__tests__/https-options.test.ts +142 -109
  57. package/src/__tests__/index.test.ts +245 -233
  58. package/src/__tests__/init.test.ts +3135 -1605
  59. package/src/__tests__/jest.setup.ts +148 -50
  60. package/src/__tests__/kv.test.ts +1778 -1471
  61. package/src/__tests__/logger.test.ts +100 -74
  62. package/src/__tests__/logout.test.ts +47 -0
  63. package/src/__tests__/metrics.test.ts +493 -0
  64. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  65. package/src/__tests__/middleware.test.ts +750 -0
  66. package/src/__tests__/package-manager.test.ts +303 -303
  67. package/src/__tests__/pages-deployment-tail.test.ts +955 -0
  68. package/src/__tests__/pages.test.ts +2887 -743
  69. package/src/__tests__/parse.test.ts +252 -252
  70. package/src/__tests__/paths.test.ts +39 -0
  71. package/src/__tests__/publish.test.ts +8004 -5355
  72. package/src/__tests__/pubsub.test.ts +490 -0
  73. package/src/__tests__/queues.test.ts +522 -0
  74. package/src/__tests__/r2.test.ts +364 -228
  75. package/src/__tests__/route.test.ts +18 -18
  76. package/src/__tests__/secret.test.ts +681 -469
  77. package/src/__tests__/tail.test.ts +835 -567
  78. package/src/__tests__/test-old-node-version.js +31 -0
  79. package/src/__tests__/tsconfig-sanity.ts +12 -0
  80. package/src/__tests__/tsconfig.json +8 -0
  81. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  82. package/src/__tests__/type-generation.test.ts +233 -0
  83. package/src/__tests__/user.test.ts +107 -120
  84. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  85. package/src/__tests__/validate-dev-props.test.ts +56 -0
  86. package/src/__tests__/version.test.ts +35 -0
  87. package/src/__tests__/whoami.test.tsx +165 -98
  88. package/src/__tests__/worker-namespace.test.ts +334 -0
  89. package/src/abort.d.ts +1 -1
  90. package/src/api/dev.ts +259 -0
  91. package/src/api/index.ts +3 -0
  92. package/src/api/pages/index.ts +5 -0
  93. package/src/api/pages/publish.tsx +321 -0
  94. package/src/bundle-reporter.ts +68 -0
  95. package/src/bundle.ts +838 -163
  96. package/src/cfetch/index.ts +120 -83
  97. package/src/cfetch/internal.ts +210 -97
  98. package/src/cli.ts +23 -8
  99. package/src/config/config.ts +236 -195
  100. package/src/config/diagnostics.ts +61 -61
  101. package/src/config/environment.ts +516 -357
  102. package/src/config/index.ts +326 -193
  103. package/src/config/validation-helpers.ts +379 -357
  104. package/src/config/validation.ts +1979 -1367
  105. package/src/config-cache.ts +81 -41
  106. package/src/create-worker-preview.ts +239 -142
  107. package/src/create-worker-upload-form.ts +309 -238
  108. package/src/d1/backups.tsx +219 -0
  109. package/src/d1/constants.ts +2 -0
  110. package/src/d1/create.tsx +63 -0
  111. package/src/d1/delete.ts +56 -0
  112. package/src/d1/execute.tsx +323 -0
  113. package/src/d1/formatTimeAgo.ts +14 -0
  114. package/src/d1/index.ts +101 -0
  115. package/src/d1/list.tsx +48 -0
  116. package/src/d1/migrations/apply.tsx +197 -0
  117. package/src/d1/migrations/create.tsx +77 -0
  118. package/src/d1/migrations/helpers.ts +147 -0
  119. package/src/d1/migrations/index.ts +3 -0
  120. package/src/d1/migrations/list.tsx +79 -0
  121. package/src/d1/migrations/options.ts +18 -0
  122. package/src/d1/options.ts +22 -0
  123. package/src/d1/splitter.ts +161 -0
  124. package/src/d1/types.ts +24 -0
  125. package/src/d1/utils.ts +48 -0
  126. package/src/delete.ts +103 -0
  127. package/src/deployments.ts +93 -0
  128. package/src/deprecated/index.ts +145 -0
  129. package/src/dev/dev-vars.ts +20 -17
  130. package/src/dev/dev.tsx +547 -352
  131. package/src/dev/get-local-persistence-path.ts +31 -0
  132. package/src/dev/local.tsx +903 -298
  133. package/src/dev/remote.tsx +620 -215
  134. package/src/dev/start-server.ts +538 -0
  135. package/src/dev/use-esbuild.ts +184 -97
  136. package/src/dev/validate-dev-props.ts +31 -0
  137. package/src/dev-registry.ts +201 -0
  138. package/src/dev.tsx +949 -0
  139. package/src/dialogs.ts +136 -0
  140. package/src/dispatch-namespace.ts +207 -0
  141. package/src/docs/index.ts +98 -0
  142. package/src/durable.ts +87 -87
  143. package/src/entry.ts +236 -230
  144. package/src/environment-variables/factory.ts +88 -0
  145. package/src/environment-variables/misc-variables.ts +30 -0
  146. package/src/errors.ts +6 -6
  147. package/src/generate/index.ts +300 -0
  148. package/src/git-client.ts +135 -0
  149. package/src/global-wrangler-config-path.ts +26 -0
  150. package/src/https-options.ts +84 -80
  151. package/src/index.ts +694 -0
  152. package/src/init.ts +1024 -0
  153. package/src/inspect.ts +698 -593
  154. package/src/intl-polyfill.d.ts +123 -123
  155. package/src/is-ci.ts +14 -0
  156. package/src/is-interactive.ts +16 -0
  157. package/src/jest.d.ts +4 -0
  158. package/src/kv/helpers.ts +430 -0
  159. package/src/kv/index.ts +596 -0
  160. package/src/logger.ts +80 -42
  161. package/src/metrics/index.ts +5 -0
  162. package/src/metrics/metrics-config.ts +239 -0
  163. package/src/metrics/metrics-dispatcher.ts +96 -0
  164. package/src/metrics/metrics-usage-headers.ts +24 -0
  165. package/src/metrics/send-event.ts +98 -0
  166. package/src/miniflare-cli/assets.ts +250 -0
  167. package/src/miniflare-cli/index.ts +202 -33
  168. package/src/miniflare-cli/request-context.ts +18 -18
  169. package/src/miniflare-cli/tsconfig.json +9 -0
  170. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  171. package/src/miniflare-cli/types.ts +11 -0
  172. package/src/module-collection.ts +221 -212
  173. package/src/open-in-browser.ts +4 -6
  174. package/src/package-manager.ts +173 -128
  175. package/src/pages/build.ts +150 -0
  176. package/src/pages/buildFunctions.ts +129 -0
  177. package/src/pages/constants.ts +18 -0
  178. package/src/pages/deployment-tails.ts +284 -0
  179. package/src/pages/deployments.tsx +84 -0
  180. package/src/pages/dev.ts +716 -0
  181. package/src/pages/errors.ts +66 -0
  182. package/src/pages/functions/buildPlugin.ts +90 -0
  183. package/src/pages/functions/buildWorker.ts +288 -0
  184. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  185. package/src/pages/functions/filepath-routing.ts +189 -0
  186. package/src/pages/functions/identifiers.ts +78 -0
  187. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  188. package/src/pages/functions/routes-consolidation.ts +73 -0
  189. package/src/pages/functions/routes-transformation.test.ts +282 -0
  190. package/src/pages/functions/routes-transformation.ts +115 -0
  191. package/src/pages/functions/routes-validation.test.ts +403 -0
  192. package/src/pages/functions/routes-validation.ts +202 -0
  193. package/src/pages/functions/routes.ts +151 -0
  194. package/src/pages/functions/tsconfig.json +8 -0
  195. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  196. package/src/pages/functions.ts +82 -0
  197. package/src/pages/hash.ts +13 -0
  198. package/src/pages/index.ts +102 -0
  199. package/src/pages/projects.tsx +167 -0
  200. package/src/pages/prompt-select-project.tsx +31 -0
  201. package/src/pages/publish.tsx +263 -0
  202. package/src/pages/types.ts +41 -0
  203. package/src/pages/upload.tsx +447 -0
  204. package/src/pages/utils.ts +23 -0
  205. package/src/parse.ts +209 -125
  206. package/src/paths.ts +53 -8
  207. package/src/proxy.ts +623 -394
  208. package/src/publish/index.ts +270 -0
  209. package/src/publish/publish.ts +1064 -0
  210. package/src/pubsub/index.ts +286 -0
  211. package/src/pubsub/pubsub-commands.ts +624 -0
  212. package/src/queues/cli/commands/consumer/add.ts +71 -0
  213. package/src/queues/cli/commands/consumer/index.ts +22 -0
  214. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  215. package/src/queues/cli/commands/create.ts +25 -0
  216. package/src/queues/cli/commands/delete.ts +26 -0
  217. package/src/queues/cli/commands/index.ts +36 -0
  218. package/src/queues/cli/commands/list.ts +25 -0
  219. package/src/queues/client.ts +135 -0
  220. package/src/queues/utils.ts +18 -0
  221. package/src/r2/constants.ts +4 -0
  222. package/src/r2/helpers.ts +131 -0
  223. package/src/r2/index.ts +289 -0
  224. package/src/routes.ts +140 -0
  225. package/src/secret/index.ts +379 -0
  226. package/src/selfsigned.d.ts +23 -23
  227. package/src/sites.ts +372 -0
  228. package/src/tail/createTail.ts +406 -0
  229. package/src/tail/filters.ts +108 -110
  230. package/src/tail/index.ts +210 -296
  231. package/src/tail/printing.ts +101 -46
  232. package/src/tsconfig-sanity.ts +16 -0
  233. package/src/type-generation.ts +181 -0
  234. package/src/update-check.ts +11 -11
  235. package/src/user/access.ts +68 -0
  236. package/src/user/auth-variables.ts +113 -0
  237. package/src/user/choose-account.tsx +39 -0
  238. package/src/user/generate-auth-url.ts +33 -0
  239. package/src/user/generate-random-state.ts +16 -0
  240. package/src/user/index.ts +2 -0
  241. package/src/user/user.ts +1232 -0
  242. package/src/utils/collectKeyValues.ts +14 -0
  243. package/src/whoami.ts +135 -0
  244. package/src/worker.ts +177 -106
  245. package/src/yargs-types.ts +24 -0
  246. package/src/zones.ts +191 -0
  247. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  248. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  249. package/templates/__tests__/tsconfig.json +8 -0
  250. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  251. package/templates/checked-fetch.js +15 -0
  252. package/templates/d1-beta-facade.js +241 -0
  253. package/templates/facade.d.ts +14 -0
  254. package/templates/first-party-worker-module-facade.ts +19 -0
  255. package/templates/format-dev-errors.ts +33 -0
  256. package/templates/init-tests/test-jest-new-worker.js +23 -0
  257. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  258. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  259. package/templates/middleware/common.ts +62 -0
  260. package/templates/middleware/loader-modules.ts +84 -0
  261. package/templates/middleware/loader-sw.ts +233 -0
  262. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  263. package/templates/middleware/middleware-pretty-error.ts +40 -0
  264. package/templates/middleware/middleware-scheduled.ts +15 -0
  265. package/templates/new-worker-scheduled.js +3 -3
  266. package/templates/new-worker-scheduled.ts +15 -15
  267. package/templates/new-worker.js +3 -3
  268. package/templates/new-worker.ts +15 -15
  269. package/templates/no-op-worker.js +10 -0
  270. package/templates/pages-dev-pipeline.ts +31 -0
  271. package/templates/pages-dev-util.ts +52 -0
  272. package/templates/pages-shim.ts +12 -0
  273. package/templates/pages-template-plugin.ts +176 -0
  274. package/templates/pages-template-worker.ts +189 -0
  275. package/templates/serve-static-assets.ts +65 -0
  276. package/templates/service-bindings-module-facade.js +54 -0
  277. package/templates/service-bindings-sw-facade.js +42 -0
  278. package/templates/tsconfig-sanity.ts +11 -0
  279. package/templates/tsconfig.init.json +106 -0
  280. package/templates/tsconfig.json +6 -103
  281. package/templates/tsconfig.tsbuildinfo +1 -0
  282. package/wrangler-dist/cli.d.ts +1028 -0
  283. package/wrangler-dist/cli.js +129259 -110922
  284. package/wrangler-dist/wasm-sync.wasm +0 -0
  285. package/pages/functions/buildPlugin.ts +0 -105
  286. package/pages/functions/buildWorker.ts +0 -151
  287. package/pages/functions/filepath-routing.ts +0 -189
  288. package/pages/functions/identifiers.ts +0 -78
  289. package/pages/functions/routes.ts +0 -156
  290. package/pages/functions/template-plugin.ts +0 -147
  291. package/pages/functions/template-worker.ts +0 -143
  292. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  293. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  294. package/src/dialogs.tsx +0 -135
  295. package/src/environment-variables.ts +0 -35
  296. package/src/index.tsx +0 -2864
  297. package/src/kv.ts +0 -408
  298. package/src/miniflare-cli/enum-keys.ts +0 -17
  299. package/src/pages.tsx +0 -2038
  300. package/src/publish.ts +0 -583
  301. package/src/r2.ts +0 -50
  302. package/src/sites.tsx +0 -295
  303. package/src/user.tsx +0 -1203
  304. package/src/whoami.tsx +0 -70
  305. package/templates/static-asset-facade.js +0 -47
  306. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  307. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  308. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  309. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  310. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  311. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  312. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  313. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  314. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  315. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  316. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  317. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  318. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  319. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  320. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  321. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  322. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  323. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  324. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  325. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  326. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  327. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  328. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  329. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  330. package/vendor/wrangler-mime/LICENSE +0 -21
  331. package/vendor/wrangler-mime/Mime.js +0 -97
  332. package/vendor/wrangler-mime/README.md +0 -187
  333. package/vendor/wrangler-mime/cli.js +0 -46
  334. package/vendor/wrangler-mime/index.js +0 -4
  335. package/vendor/wrangler-mime/lite.js +0 -4
  336. package/vendor/wrangler-mime/package.json +0 -52
  337. package/vendor/wrangler-mime/types/other.js +0 -1
  338. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/init.ts ADDED
@@ -0,0 +1,1024 @@
1
+ import * as fs from "node:fs";
2
+ import { writeFile, mkdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import TOML from "@iarna/toml";
5
+ import { findUp } from "find-up";
6
+ import { version as wranglerVersion } from "../package.json";
7
+
8
+ import { fetchResult } from "./cfetch";
9
+ import { fetchDashboardScript } from "./cfetch/internal";
10
+ import { readConfig } from "./config";
11
+ import { confirm, select } from "./dialogs";
12
+ import { initializeGit, getGitVersioon, isInsideGitRepo } from "./git-client";
13
+ import { logger } from "./logger";
14
+ import { getPackageManager } from "./package-manager";
15
+ import { parsePackageJSON, parseTOML, readFileSync } from "./parse";
16
+ import { getBasePath } from "./paths";
17
+ import { requireAuth } from "./user";
18
+ import { CommandLineArgsError, printWranglerBanner } from "./index";
19
+
20
+ import type { RawConfig } from "./config";
21
+ import type { Route, SimpleRoute } from "./config/environment";
22
+ import type { WorkerMetadata } from "./create-worker-upload-form";
23
+ import type { ConfigPath } from "./index";
24
+ import type { PackageManager } from "./package-manager";
25
+ import type { PackageJSON } from "./parse";
26
+ import type {
27
+ CommonYargsOptions,
28
+ YargsOptionsToInterface,
29
+ } from "./yargs-types";
30
+ import type { Argv } from "yargs";
31
+
32
+ export function initOptions(yargs: Argv<CommonYargsOptions>) {
33
+ return yargs
34
+ .positional("name", {
35
+ describe: "The name of your worker",
36
+ type: "string",
37
+ })
38
+ .option("type", {
39
+ describe: "The type of worker to create",
40
+ type: "string",
41
+ choices: ["rust", "javascript", "webpack"],
42
+ hidden: true,
43
+ deprecated: true,
44
+ })
45
+ .option("site", {
46
+ hidden: true,
47
+ type: "boolean",
48
+ deprecated: true,
49
+ })
50
+ .option("yes", {
51
+ describe: 'Answer "yes" to any prompts for new projects',
52
+ type: "boolean",
53
+ alias: "y",
54
+ })
55
+ .option("from-dash", {
56
+ describe:
57
+ "The name of the Worker you wish to download from the Cloudflare dashboard for local development.",
58
+ type: "string",
59
+ requiresArg: true,
60
+ });
61
+ }
62
+
63
+ type InitArgs = YargsOptionsToInterface<typeof initOptions>;
64
+
65
+ export type ServiceMetadataRes = {
66
+ id: string;
67
+ default_environment: {
68
+ environment: string;
69
+ created_on: string;
70
+ modified_on: string;
71
+ script: {
72
+ id: string;
73
+ tag: string;
74
+ etag: string;
75
+ handlers: string[];
76
+ modified_on: string;
77
+ created_on: string;
78
+ migration_tag: string;
79
+ usage_model: "bundled" | "unbound";
80
+ compatibility_date: string;
81
+ last_deployed_from?: "wrangler" | "dash" | "api";
82
+ };
83
+ };
84
+ created_on: string;
85
+ modified_on: string;
86
+ usage_model: "bundled" | "unbound";
87
+ environments: [
88
+ {
89
+ environment: string;
90
+ created_on: string;
91
+ modified_on: string;
92
+ }
93
+ ];
94
+ };
95
+
96
+ export type RawSimpleRoute = { pattern: string };
97
+ export type RawRoutes = (RawSimpleRoute | Exclude<Route, SimpleRoute>) & {
98
+ id: string;
99
+ };
100
+ export type RoutesRes = RawRoutes[];
101
+
102
+ export type CronTriggersRes = {
103
+ schedules: [
104
+ {
105
+ cron: string;
106
+ created_on: Date;
107
+ modified_on: Date;
108
+ }
109
+ ];
110
+ };
111
+
112
+ export async function initHandler(args: InitArgs) {
113
+ await printWranglerBanner();
114
+ if (args.type) {
115
+ let message = "The --type option is no longer supported.";
116
+ if (args.type === "webpack") {
117
+ message +=
118
+ "\nIf you wish to use webpack then you will need to create a custom build.";
119
+ // TODO: Add a link to docs
120
+ }
121
+ throw new CommandLineArgsError(message);
122
+ }
123
+
124
+ const devDepsToInstall: string[] = [];
125
+ const instructions: string[] = [];
126
+ let shouldRunPackageManagerInstall = false;
127
+ const fromDashScriptName = args.fromDash;
128
+ const creationDirectory = path.resolve(
129
+ process.cwd(),
130
+ (args.name ? args.name : fromDashScriptName) ?? ""
131
+ );
132
+
133
+ if (args.site) {
134
+ const gitDirectory =
135
+ creationDirectory !== process.cwd()
136
+ ? path.basename(creationDirectory)
137
+ : "my-site";
138
+ const message =
139
+ "The --site option is no longer supported.\n" +
140
+ "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
141
+ "```\n" +
142
+ `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
143
+ `cd ${gitDirectory}\n` +
144
+ "```\n\n" +
145
+ "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
146
+ "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
147
+ throw new CommandLineArgsError(message);
148
+ }
149
+
150
+ // TODO: make sure args.name is a valid identifier for a worker name
151
+ const workerName = path
152
+ .basename(creationDirectory)
153
+ .toLowerCase()
154
+ .replaceAll(/[^a-z0-9\-_]/gm, "-");
155
+
156
+ const packageManager = await getPackageManager(creationDirectory);
157
+
158
+ // TODO: ask which directory to make the worker in (defaults to args.name)
159
+ // TODO: if args.name isn't provided, ask what to name the worker
160
+ // Note: `--from-dash` will be a fallback creationDir/Worker name if none is provided.
161
+
162
+ const wranglerTomlDestination = path.join(
163
+ creationDirectory,
164
+ "./wrangler.toml"
165
+ );
166
+ let justCreatedWranglerToml = false;
167
+
168
+ let accountId = "";
169
+ let serviceMetadata: undefined | ServiceMetadataRes;
170
+
171
+ // If --from-dash, check that script actually exists
172
+ if (fromDashScriptName) {
173
+ const config = readConfig(args.config as ConfigPath, args);
174
+ accountId = await requireAuth(config);
175
+ try {
176
+ serviceMetadata = await fetchResult<ServiceMetadataRes>(
177
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}`
178
+ );
179
+ } catch (err) {
180
+ if ((err as { code?: number }).code === 10090) {
181
+ throw new Error(
182
+ "wrangler couldn't find a Worker script with that name in your account.\nRun `wrangler whoami` to confirm you're logged into the correct account."
183
+ );
184
+ }
185
+ throw err;
186
+ }
187
+ }
188
+
189
+ if (fs.existsSync(wranglerTomlDestination)) {
190
+ let shouldContinue = false;
191
+ logger.warn(
192
+ `${path.relative(process.cwd(), wranglerTomlDestination)} already exists!`
193
+ );
194
+ if (!fromDashScriptName) {
195
+ shouldContinue = await confirm(
196
+ "Do you want to continue initializing this project?"
197
+ );
198
+ }
199
+ if (!shouldContinue) {
200
+ return;
201
+ }
202
+ } else {
203
+ await mkdir(creationDirectory, { recursive: true });
204
+ const compatibilityDate = new Date().toISOString().substring(0, 10);
205
+
206
+ try {
207
+ await writeFile(
208
+ wranglerTomlDestination,
209
+ TOML.stringify({
210
+ name: workerName,
211
+ compatibility_date: compatibilityDate,
212
+ }) + "\n"
213
+ );
214
+
215
+ logger.log(
216
+ `✨ Created ${path.relative(process.cwd(), wranglerTomlDestination)}`
217
+ );
218
+ justCreatedWranglerToml = true;
219
+ } catch (err) {
220
+ throw new Error(
221
+ `Failed to create ${path.relative(
222
+ process.cwd(),
223
+ wranglerTomlDestination
224
+ )}.\n${(err as Error).message ?? err}`
225
+ );
226
+ }
227
+ }
228
+
229
+ const yesFlag = args.yes ?? false;
230
+
231
+ if (!(await isInsideGitRepo(creationDirectory)) && (await getGitVersioon())) {
232
+ const shouldInitGit =
233
+ yesFlag ||
234
+ (await confirm("Would you like to use git to manage this Worker?"));
235
+ if (shouldInitGit) {
236
+ await initializeGit(creationDirectory);
237
+ await writeFile(
238
+ path.join(creationDirectory, ".gitignore"),
239
+ readFileSync(path.join(getBasePath(), "templates/gitignore"))
240
+ );
241
+ logger.log(
242
+ args.name && args.name !== "."
243
+ ? `✨ Initialized git repository at ${path.relative(
244
+ process.cwd(),
245
+ creationDirectory
246
+ )}`
247
+ : `✨ Initialized git repository`
248
+ );
249
+ }
250
+ }
251
+
252
+ const isolatedInit = !!args.name;
253
+ let pathToPackageJson = await findPath(
254
+ isolatedInit,
255
+ creationDirectory,
256
+ "package.json"
257
+ );
258
+ let shouldCreatePackageJson = false;
259
+ let shouldCreateTests = false;
260
+ let newWorkerTestType: "jest" | "vitest" = "jest";
261
+
262
+ if (!pathToPackageJson) {
263
+ // If no package.json exists, ask to create one
264
+ shouldCreatePackageJson =
265
+ yesFlag ||
266
+ (await confirm("No package.json found. Would you like to create one?"));
267
+
268
+ if (shouldCreatePackageJson) {
269
+ await writeFile(
270
+ path.join(creationDirectory, "./package.json"),
271
+ JSON.stringify(
272
+ {
273
+ name: workerName,
274
+ version: "0.0.0",
275
+ devDependencies: {
276
+ wrangler: wranglerVersion,
277
+ },
278
+ private: true,
279
+ },
280
+ null,
281
+ " "
282
+ ) + "\n"
283
+ );
284
+
285
+ shouldRunPackageManagerInstall = true;
286
+ pathToPackageJson = path.join(creationDirectory, "package.json");
287
+ logger.log(
288
+ `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
289
+ );
290
+ } else {
291
+ return;
292
+ }
293
+ } else {
294
+ // If package.json exists and wrangler isn't installed,
295
+ // then ask to add wrangler to devDependencies
296
+ const packageJson = parsePackageJSON(
297
+ readFileSync(pathToPackageJson),
298
+ pathToPackageJson
299
+ );
300
+ if (
301
+ !(
302
+ packageJson.devDependencies?.wrangler ||
303
+ packageJson.dependencies?.wrangler
304
+ )
305
+ ) {
306
+ const shouldInstall =
307
+ yesFlag ||
308
+ (await confirm(
309
+ `Would you like to install wrangler into ${path.relative(
310
+ process.cwd(),
311
+ pathToPackageJson
312
+ )}?`
313
+ ));
314
+ if (shouldInstall) {
315
+ devDepsToInstall.push(`wrangler@${wranglerVersion}`);
316
+ }
317
+ }
318
+ }
319
+
320
+ let isTypescriptProject = false;
321
+ let pathToTSConfig = await findPath(
322
+ isolatedInit,
323
+ creationDirectory,
324
+ "tsconfig.json"
325
+ );
326
+ if (!pathToTSConfig) {
327
+ // If there's no tsconfig, offer to create one
328
+ // and install @cloudflare/workers-types
329
+ if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
330
+ isTypescriptProject = true;
331
+ await writeFile(
332
+ path.join(creationDirectory, "./tsconfig.json"),
333
+ readFileSync(path.join(getBasePath(), "templates/tsconfig.init.json"))
334
+ );
335
+ devDepsToInstall.push("@cloudflare/workers-types");
336
+ devDepsToInstall.push("typescript");
337
+ pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
338
+ logger.log(`✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`);
339
+ }
340
+ } else {
341
+ isTypescriptProject = true;
342
+ // If there's a tsconfig, check if @cloudflare/workers-types
343
+ // is already installed, and offer to install it if not
344
+ const packageJson = parsePackageJSON(
345
+ readFileSync(pathToPackageJson),
346
+ pathToPackageJson
347
+ );
348
+ if (
349
+ !(
350
+ packageJson.devDependencies?.["@cloudflare/workers-types"] ||
351
+ packageJson.dependencies?.["@cloudflare/workers-types"]
352
+ )
353
+ ) {
354
+ const shouldInstall = await confirm(
355
+ "Would you like to install the type definitions for Workers into your package.json?"
356
+ );
357
+ if (shouldInstall) {
358
+ devDepsToInstall.push("@cloudflare/workers-types");
359
+ // We don't update the tsconfig.json because
360
+ // it could be complicated in existing projects
361
+ // and we don't want to break them. Instead, we simply
362
+ // tell the user that they need to update their tsconfig.json
363
+ instructions.push(
364
+ `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
365
+ process.cwd(),
366
+ pathToTSConfig
367
+ )}`
368
+ );
369
+ }
370
+ }
371
+ }
372
+
373
+ const packageJsonContent = parsePackageJSON(
374
+ readFileSync(pathToPackageJson),
375
+ pathToPackageJson
376
+ );
377
+ const shouldWritePackageJsonScripts =
378
+ !packageJsonContent.scripts?.start &&
379
+ !packageJsonContent.scripts?.publish &&
380
+ shouldCreatePackageJson;
381
+
382
+ async function writePackageJsonScriptsAndUpdateWranglerToml({
383
+ isWritingScripts,
384
+ isAddingTests,
385
+ testRunner,
386
+ isCreatingWranglerToml,
387
+ packagePath,
388
+ scriptPath,
389
+ extraToml,
390
+ }: {
391
+ isWritingScripts: boolean;
392
+ isAddingTests?: boolean;
393
+ testRunner?: "jest" | "vitest";
394
+ isCreatingWranglerToml: boolean;
395
+ packagePath: string;
396
+ scriptPath: string;
397
+ extraToml: TOML.JsonMap;
398
+ }) {
399
+ if (isAddingTests && !testRunner) {
400
+ logger.error("testRunner is required if isAddingTests");
401
+ }
402
+ if (isCreatingWranglerToml) {
403
+ // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
404
+ const parsedWranglerToml = parseTOML(
405
+ readFileSync(wranglerTomlDestination)
406
+ );
407
+ const newToml = {
408
+ name: parsedWranglerToml.name,
409
+ main: scriptPath,
410
+ compatibility_date: parsedWranglerToml.compatibility_date,
411
+ ...extraToml,
412
+ };
413
+ fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
414
+ }
415
+ const isNamedWorker =
416
+ isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
417
+ const isAddingTestScripts =
418
+ isAddingTests && !packageJsonContent.scripts?.test;
419
+ if (isWritingScripts) {
420
+ await writeFile(
421
+ packagePath,
422
+ JSON.stringify(
423
+ {
424
+ ...packageJsonContent,
425
+ scripts: {
426
+ ...packageJsonContent.scripts,
427
+ start: isCreatingWranglerToml
428
+ ? `wrangler dev`
429
+ : `wrangler dev ${scriptPath}`,
430
+ deploy: isCreatingWranglerToml
431
+ ? `wrangler publish`
432
+ : `wrangler publish ${scriptPath}`,
433
+ ...(isAddingTestScripts && { test: testRunner }),
434
+ },
435
+ } as PackageJSON,
436
+ null,
437
+ 2
438
+ ) + "\n"
439
+ );
440
+ instructions.push(
441
+ `\nTo start developing your Worker, run \`${
442
+ isNamedWorker ? `cd ${args.name || fromDashScriptName} && ` : ""
443
+ }npm start\``
444
+ );
445
+ if (isAddingTestScripts) {
446
+ instructions.push(`To start testing your Worker, run \`npm test\``);
447
+ }
448
+ instructions.push(
449
+ `To publish your Worker to the Internet, run \`npm run deploy\``
450
+ );
451
+ } else {
452
+ instructions.push(
453
+ `\nTo start developing your Worker, run \`npx wrangler dev\`${
454
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
455
+ }`
456
+ );
457
+ instructions.push(
458
+ `To publish your Worker to the Internet, run \`npx wrangler publish\`${
459
+ isCreatingWranglerToml ? "" : ` ${scriptPath}`
460
+ }`
461
+ );
462
+ }
463
+ }
464
+
465
+ if (isTypescriptProject) {
466
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
467
+ const newWorkerFilename = path.relative(
468
+ process.cwd(),
469
+ path.join(creationDirectory, "./src/index.ts")
470
+ );
471
+ if (fromDashScriptName) {
472
+ logger.warn(
473
+ "After running `wrangler init --from-dash`, modifying your worker via the Cloudflare dashboard is discouraged.\nEdits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish."
474
+ );
475
+
476
+ await mkdir(path.join(creationDirectory, "./src"), {
477
+ recursive: true,
478
+ });
479
+
480
+ const defaultEnvironment =
481
+ serviceMetadata?.default_environment.environment;
482
+ // I want the default environment, assuming it's the most up to date code.
483
+ const dashScript = await fetchDashboardScript(
484
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
485
+ );
486
+
487
+ await writeFile(
488
+ path.join(creationDirectory, "./src/index.ts"),
489
+ dashScript
490
+ );
491
+
492
+ await writePackageJsonScriptsAndUpdateWranglerToml({
493
+ isWritingScripts: shouldWritePackageJsonScripts,
494
+ isCreatingWranglerToml: justCreatedWranglerToml,
495
+ packagePath: pathToPackageJson,
496
+ scriptPath: "src/index.ts",
497
+ extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
498
+ defaultEnvironment,
499
+ environments: serviceMetadata?.environments,
500
+ })) as TOML.JsonMap,
501
+ });
502
+ } else {
503
+ const newWorkerType = yesFlag
504
+ ? "fetch"
505
+ : await getNewWorkerType(newWorkerFilename);
506
+
507
+ if (newWorkerType !== "none") {
508
+ const template = getNewWorkerTemplate("ts", newWorkerType);
509
+
510
+ await mkdir(path.join(creationDirectory, "./src"), {
511
+ recursive: true,
512
+ });
513
+
514
+ await writeFile(
515
+ path.join(creationDirectory, "./src/index.ts"),
516
+ readFileSync(path.join(getBasePath(), `templates/${template}`))
517
+ );
518
+
519
+ logger.log(
520
+ `✨ Created ${path.relative(
521
+ process.cwd(),
522
+ path.join(creationDirectory, "./src/index.ts")
523
+ )}`
524
+ );
525
+
526
+ shouldCreateTests =
527
+ yesFlag ||
528
+ (await confirm(
529
+ "Would you like us to write your first test with Vitest?"
530
+ ));
531
+
532
+ if (shouldCreateTests) {
533
+ if (yesFlag) {
534
+ logger.info("Your project will use Vitest to run your tests.");
535
+ }
536
+
537
+ newWorkerTestType = "vitest";
538
+ devDepsToInstall.push(newWorkerTestType);
539
+
540
+ await writeFile(
541
+ path.join(creationDirectory, "./src/index.test.ts"),
542
+ readFileSync(
543
+ path.join(
544
+ getBasePath(),
545
+ `templates/init-tests/test-${newWorkerTestType}-new-worker.ts`
546
+ )
547
+ )
548
+ );
549
+ logger.log(
550
+ `✨ Created ${path.relative(
551
+ process.cwd(),
552
+ path.join(creationDirectory, "./src/index.test.ts")
553
+ )}`
554
+ );
555
+ }
556
+
557
+ await writePackageJsonScriptsAndUpdateWranglerToml({
558
+ isWritingScripts: shouldWritePackageJsonScripts,
559
+ isAddingTests: shouldCreateTests,
560
+ isCreatingWranglerToml: justCreatedWranglerToml,
561
+ packagePath: pathToPackageJson,
562
+ testRunner: newWorkerTestType,
563
+ scriptPath: "src/index.ts",
564
+ extraToml: getNewWorkerToml(newWorkerType),
565
+ });
566
+ }
567
+ }
568
+ }
569
+ } else {
570
+ if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
571
+ const newWorkerFilename = path.relative(
572
+ process.cwd(),
573
+ path.join(creationDirectory, "./src/index.js")
574
+ );
575
+
576
+ if (fromDashScriptName) {
577
+ logger.warn(
578
+ "After running `wrangler init --from-dash`, modifying your worker via the Cloudflare dashboard is discouraged.\nEdits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish."
579
+ );
580
+
581
+ await mkdir(path.join(creationDirectory, "./src"), {
582
+ recursive: true,
583
+ });
584
+
585
+ const defaultEnvironment =
586
+ serviceMetadata?.default_environment.environment;
587
+
588
+ // I want the default environment, assuming it's the most up to date code.
589
+ const dashScript = await fetchDashboardScript(
590
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
591
+ );
592
+
593
+ await writeFile(
594
+ path.join(creationDirectory, "./src/index.js"),
595
+ dashScript
596
+ );
597
+
598
+ await writePackageJsonScriptsAndUpdateWranglerToml({
599
+ isWritingScripts: shouldWritePackageJsonScripts,
600
+ isCreatingWranglerToml: justCreatedWranglerToml,
601
+ packagePath: pathToPackageJson,
602
+ scriptPath: "src/index.js",
603
+ //? Should we have Environment argument for `wrangler init --from-dash` - Jacob
604
+ extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
605
+ defaultEnvironment,
606
+ environments: serviceMetadata?.environments,
607
+ })) as TOML.JsonMap,
608
+ });
609
+ } else {
610
+ const newWorkerType = yesFlag
611
+ ? "fetch"
612
+ : await getNewWorkerType(newWorkerFilename);
613
+
614
+ if (newWorkerType !== "none") {
615
+ const template = getNewWorkerTemplate("js", newWorkerType);
616
+
617
+ await mkdir(path.join(creationDirectory, "./src"), {
618
+ recursive: true,
619
+ });
620
+ await writeFile(
621
+ path.join(creationDirectory, "./src/index.js"),
622
+ readFileSync(path.join(getBasePath(), `templates/${template}`))
623
+ );
624
+
625
+ logger.log(
626
+ `✨ Created ${path.relative(
627
+ process.cwd(),
628
+ path.join(creationDirectory, "./src/index.js")
629
+ )}`
630
+ );
631
+
632
+ shouldCreateTests =
633
+ yesFlag ||
634
+ (await confirm("Would you like us to write your first test?"));
635
+
636
+ if (shouldCreateTests) {
637
+ newWorkerTestType = await getNewWorkerTestType(yesFlag);
638
+ devDepsToInstall.push(newWorkerTestType);
639
+ await writeFile(
640
+ path.join(creationDirectory, "./src/index.test.js"),
641
+ readFileSync(
642
+ path.join(
643
+ getBasePath(),
644
+ `templates/init-tests/test-${newWorkerTestType}-new-worker.js`
645
+ )
646
+ )
647
+ );
648
+ logger.log(
649
+ `✨ Created ${path.relative(
650
+ process.cwd(),
651
+ path.join(creationDirectory, "./src/index.test.js")
652
+ )}`
653
+ );
654
+ }
655
+
656
+ await writePackageJsonScriptsAndUpdateWranglerToml({
657
+ isWritingScripts: shouldWritePackageJsonScripts,
658
+ isAddingTests: shouldCreateTests,
659
+ testRunner: newWorkerTestType,
660
+ isCreatingWranglerToml: justCreatedWranglerToml,
661
+ packagePath: pathToPackageJson,
662
+ scriptPath: "src/index.js",
663
+ extraToml: getNewWorkerToml(newWorkerType),
664
+ });
665
+ }
666
+ }
667
+ }
668
+ }
669
+ // install packages as the final step of init
670
+ try {
671
+ await installPackages(
672
+ shouldRunPackageManagerInstall,
673
+ devDepsToInstall,
674
+ packageManager
675
+ );
676
+ } catch (e) {
677
+ // fetching packages could fail due to loss of internet, etc
678
+ // we should let folks know we failed to fetch, but their
679
+ // workers project is still ready to go
680
+ logger.error(e instanceof Error ? e.message : e);
681
+ instructions.push(
682
+ "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
683
+ );
684
+ }
685
+
686
+ // let users know what to do now
687
+ instructions.forEach((instruction) => logger.log(instruction));
688
+ }
689
+
690
+ /*
691
+ * Passes the array of accumulated devDeps to install through to
692
+ * the package manager. Also generates a human-readable list
693
+ * of packages it installed.
694
+ * If there are no devDeps to install, optionally runs
695
+ * the package manager's install command.
696
+ */
697
+ async function installPackages(
698
+ shouldRunInstall: boolean,
699
+ depsToInstall: string[],
700
+ packageManager: PackageManager
701
+ ) {
702
+ //lets install the devDeps they asked for
703
+ //and run their package manager's install command if needed
704
+ if (depsToInstall.length > 0) {
705
+ const formatter = new Intl.ListFormat("en", {
706
+ style: "long",
707
+ type: "conjunction",
708
+ });
709
+ await packageManager.addDevDeps(...depsToInstall);
710
+ const versionlessPackages = depsToInstall.map((dep) =>
711
+ dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
712
+ );
713
+
714
+ logger.log(
715
+ `✨ Installed ${formatter.format(
716
+ versionlessPackages
717
+ )} into devDependencies`
718
+ );
719
+ } else {
720
+ if (shouldRunInstall) {
721
+ await packageManager.install();
722
+ }
723
+ }
724
+ }
725
+
726
+ async function getNewWorkerType(newWorkerFilename: string) {
727
+ return select(`Would you like to create a Worker at ${newWorkerFilename}?`, {
728
+ choices: [
729
+ {
730
+ value: "none",
731
+ title: "None",
732
+ },
733
+ {
734
+ value: "fetch",
735
+ title: "Fetch handler",
736
+ },
737
+ {
738
+ value: "scheduled",
739
+ title: "Scheduled handler",
740
+ },
741
+ ],
742
+ defaultOption: 1,
743
+ });
744
+ }
745
+
746
+ async function getNewWorkerTestType(yesFlag?: boolean) {
747
+ return yesFlag
748
+ ? "jest"
749
+ : select(`Which test runner would you like to use?`, {
750
+ choices: [
751
+ {
752
+ value: "vitest",
753
+ title: "Vitest",
754
+ },
755
+ {
756
+ value: "jest",
757
+ title: "Jest",
758
+ },
759
+ ],
760
+ defaultOption: 1,
761
+ });
762
+ }
763
+
764
+ function getNewWorkerTemplate(
765
+ lang: "js" | "ts",
766
+ workerType: "fetch" | "scheduled"
767
+ ) {
768
+ const templates = {
769
+ "js-fetch": "new-worker.js",
770
+ "js-scheduled": "new-worker-scheduled.js",
771
+ "ts-fetch": "new-worker.ts",
772
+ "ts-scheduled": "new-worker-scheduled.ts",
773
+ };
774
+
775
+ return templates[`${lang}-${workerType}`];
776
+ }
777
+
778
+ function getNewWorkerToml(workerType: "fetch" | "scheduled"): TOML.JsonMap {
779
+ if (workerType === "scheduled") {
780
+ return {
781
+ triggers: {
782
+ crons: ["1 * * * *"],
783
+ },
784
+ };
785
+ }
786
+
787
+ return {};
788
+ }
789
+
790
+ /**
791
+ * Find the path to the given `basename` file from the `cwd`.
792
+ *
793
+ * If `isolatedInit` is true then we only look in the `cwd` directory for the file.
794
+ * Otherwise we also search up the tree.
795
+ */
796
+ async function findPath(
797
+ isolatedInit: boolean,
798
+ cwd: string,
799
+ basename: string
800
+ ): Promise<string | undefined> {
801
+ if (isolatedInit) {
802
+ return fs.existsSync(path.resolve(cwd, basename))
803
+ ? path.resolve(cwd, basename)
804
+ : undefined;
805
+ } else {
806
+ return await findUp(basename, {
807
+ cwd: cwd,
808
+ });
809
+ }
810
+ }
811
+
812
+ async function getWorkerConfig(
813
+ accountId: string,
814
+ fromDashScriptName: string,
815
+ {
816
+ defaultEnvironment,
817
+ environments,
818
+ }: {
819
+ defaultEnvironment: string | undefined;
820
+ environments: ServiceMetadataRes["environments"] | undefined;
821
+ }
822
+ ): Promise<RawConfig> {
823
+ const [bindings, routes, serviceEnvMetadata, cronTriggers] =
824
+ await Promise.all([
825
+ fetchResult<WorkerMetadata["bindings"]>(
826
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/bindings`
827
+ ),
828
+ fetchResult<RoutesRes>(
829
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/routes`
830
+ ),
831
+ fetchResult<ServiceMetadataRes["default_environment"]>(
832
+ `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}`
833
+ ),
834
+ fetchResult<CronTriggersRes>(
835
+ `/accounts/${accountId}/workers/scripts/${fromDashScriptName}/schedules`
836
+ ),
837
+ ]).catch((e) => {
838
+ throw new Error(
839
+ `Error Occurred ${e}: Unable to fetch bindings, routes, or services metadata from the dashboard. Please try again later.`
840
+ );
841
+ });
842
+
843
+ const mappedBindings = bindings
844
+ .filter((binding) => (binding.type as string) !== "secret_text")
845
+ // Combine the same types into {[type]: [binding]}
846
+ .reduce((configObj, binding) => {
847
+ // Some types have different names in wrangler.toml
848
+ // I want the type safety of the binding being destructured after the case narrowing the union but type is unused
849
+
850
+ switch (binding.type) {
851
+ case "plain_text":
852
+ {
853
+ configObj.vars = {
854
+ ...(configObj.vars ?? {}),
855
+ [binding.name]: binding.text,
856
+ };
857
+ }
858
+ break;
859
+ case "json":
860
+ {
861
+ configObj.vars = {
862
+ ...(configObj.vars ?? {}),
863
+ name: binding.name,
864
+ json: binding.json,
865
+ };
866
+ }
867
+ break;
868
+ case "kv_namespace":
869
+ {
870
+ configObj.kv_namespaces = [
871
+ ...(configObj.kv_namespaces ?? []),
872
+ { id: binding.namespace_id, binding: binding.name },
873
+ ];
874
+ }
875
+ break;
876
+ case "durable_object_namespace":
877
+ {
878
+ configObj.durable_objects = {
879
+ bindings: [
880
+ ...(configObj.durable_objects?.bindings ?? []),
881
+ {
882
+ name: binding.name,
883
+ class_name: binding.class_name,
884
+ script_name: binding.script_name,
885
+ environment: binding.environment,
886
+ },
887
+ ],
888
+ };
889
+ }
890
+ break;
891
+ case "r2_bucket":
892
+ {
893
+ configObj.r2_buckets = [
894
+ ...(configObj.r2_buckets ?? []),
895
+ { binding: binding.name, bucket_name: binding.bucket_name },
896
+ ];
897
+ }
898
+ break;
899
+ case "service":
900
+ {
901
+ configObj.services = [
902
+ ...(configObj.services ?? []),
903
+ {
904
+ binding: binding.name,
905
+ service: binding.service,
906
+ environment: binding.environment,
907
+ },
908
+ ];
909
+ }
910
+ break;
911
+ case "analytics_engine":
912
+ {
913
+ configObj.analytics_engine_datasets = [
914
+ ...(configObj.analytics_engine_datasets ?? []),
915
+ { binding: binding.name, dataset: binding.dataset },
916
+ ];
917
+ }
918
+ break;
919
+ case "dispatch_namespace":
920
+ {
921
+ configObj.dispatch_namespaces = [
922
+ ...(configObj.dispatch_namespaces ?? []),
923
+ { binding: binding.name, namespace: binding.namespace },
924
+ ];
925
+ }
926
+ break;
927
+ case "logfwdr":
928
+ {
929
+ configObj.logfwdr = {
930
+ // TODO: Messaging about adding schema file path
931
+ schema: "",
932
+ bindings: [
933
+ ...(configObj.logfwdr?.bindings ?? []),
934
+ { name: binding.name, destination: binding.destination },
935
+ ],
936
+ };
937
+ }
938
+ break;
939
+ case "wasm_module":
940
+ {
941
+ configObj.wasm_modules = {
942
+ ...(configObj.wasm_modules ?? {}),
943
+ [binding.name]: binding.part,
944
+ };
945
+ }
946
+ break;
947
+ case "text_blob":
948
+ {
949
+ configObj.text_blobs = {
950
+ ...(configObj.text_blobs ?? {}),
951
+ [binding.name]: binding.part,
952
+ };
953
+ }
954
+ break;
955
+ case "data_blob":
956
+ {
957
+ configObj.data_blobs = {
958
+ ...(configObj.data_blobs ?? {}),
959
+ [binding.name]: binding.part,
960
+ };
961
+ }
962
+ break;
963
+ default: {
964
+ // If we don't know what the type is, its an unsafe binding
965
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
966
+ if (!(binding as any)?.type) break;
967
+ configObj.unsafe = {
968
+ bindings: [...(configObj.unsafe?.bindings ?? []), binding],
969
+ };
970
+ }
971
+ }
972
+
973
+ return configObj;
974
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
975
+ }, {} as RawConfig);
976
+
977
+ const durableObjectClassNames = bindings
978
+ .filter((binding) => binding.type === "durable_object_namespace")
979
+ .map(
980
+ (durableObject) => (durableObject as { class_name: string }).class_name
981
+ );
982
+
983
+ const routeOrRoutes = routes.map((rawRoute) => {
984
+ const { id: _id, ...route } = rawRoute;
985
+ if (Object.keys(route).length === 1) {
986
+ return route.pattern;
987
+ } else {
988
+ return route as Route;
989
+ }
990
+ });
991
+ const routeOrRoutesToConfig =
992
+ routeOrRoutes.length > 1
993
+ ? { routes: routeOrRoutes }
994
+ : { route: routeOrRoutes[0] };
995
+
996
+ return {
997
+ compatibility_date:
998
+ serviceEnvMetadata.script.compatibility_date ??
999
+ new Date().toISOString().substring(0, 10),
1000
+ ...routeOrRoutesToConfig,
1001
+ usage_model: serviceEnvMetadata.script.usage_model,
1002
+ ...(durableObjectClassNames.length
1003
+ ? {
1004
+ migrations: [
1005
+ {
1006
+ tag: serviceEnvMetadata.script.migration_tag,
1007
+ new_classes: durableObjectClassNames,
1008
+ },
1009
+ ],
1010
+ }
1011
+ : {}),
1012
+ triggers: {
1013
+ crons: cronTriggers.schedules.map((scheduled) => scheduled.cron),
1014
+ },
1015
+ env: environments
1016
+ ?.filter((env) => env.environment !== "production")
1017
+ // `env` can have multiple Environments, with different configs.
1018
+ .reduce((envObj, { environment }) => {
1019
+ return { ...envObj, [environment]: {} };
1020
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1021
+ }, {} as RawConfig["env"]),
1022
+ ...mappedBindings,
1023
+ };
1024
+ }