wrangler 0.0.0-e452a35 → 0.0.0-e4ca780f

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