wrangler 0.0.0-e64812e → 0.0.0-e6c71262

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