wrangler 0.0.0-e6733a3 → 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 (380) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -14
  3. package/bin/wrangler.js +180 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +6442 -0
  6. package/package.json +198 -124
  7. package/src/__tests__/access.test.ts +25 -0
  8. package/src/__tests__/api-dev.test.ts +238 -0
  9. package/src/__tests__/api-devregistry.test.ts +121 -0
  10. package/src/__tests__/api.test.ts +102 -0
  11. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  12. package/src/__tests__/config-cache.test.ts +42 -0
  13. package/src/__tests__/configuration.test.ts +4671 -0
  14. package/src/__tests__/constellation.test.ts +371 -0
  15. package/src/__tests__/d1/d1.test.ts +82 -0
  16. package/src/__tests__/d1/execute.test.ts +66 -0
  17. package/src/__tests__/d1/migrate.test.ts +257 -0
  18. package/src/__tests__/d1/splitter.test.ts +255 -0
  19. package/src/__tests__/delete.test.ts +272 -0
  20. package/src/__tests__/deployments.test.ts +369 -0
  21. package/src/__tests__/dev.test.tsx +1613 -62
  22. package/src/__tests__/generate.test.ts +254 -0
  23. package/src/__tests__/get-host-from-url.test.ts +16 -0
  24. package/src/__tests__/guess-worker-format.test.ts +120 -0
  25. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  26. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  27. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  28. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  29. package/src/__tests__/helpers/mock-bin.ts +36 -0
  30. package/src/__tests__/helpers/mock-console.ts +112 -0
  31. package/src/__tests__/helpers/mock-dialogs.ts +139 -0
  32. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  33. package/src/__tests__/helpers/mock-get-zone-from-host.ts +11 -0
  34. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  35. package/src/__tests__/helpers/mock-istty.ts +74 -0
  36. package/src/__tests__/helpers/mock-known-routes.ts +12 -0
  37. package/src/__tests__/helpers/mock-kv.ts +46 -0
  38. package/src/__tests__/helpers/mock-oauth-flow.ts +263 -0
  39. package/src/__tests__/helpers/mock-process.ts +34 -0
  40. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  41. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  42. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  43. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  44. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  45. package/src/__tests__/helpers/msw/handlers/deployments.ts +160 -0
  46. package/src/__tests__/helpers/msw/handlers/namespaces.ts +81 -0
  47. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  48. package/src/__tests__/helpers/msw/handlers/r2.ts +60 -0
  49. package/src/__tests__/helpers/msw/handlers/script.ts +56 -0
  50. package/src/__tests__/helpers/msw/handlers/user.ts +52 -0
  51. package/src/__tests__/helpers/msw/handlers/zones.ts +20 -0
  52. package/src/__tests__/helpers/msw/index.ts +52 -0
  53. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  54. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  55. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  56. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  57. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  58. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  59. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  60. package/src/__tests__/helpers/worker-scripts/parent-worker.js +11 -0
  61. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  62. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  63. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  64. package/src/__tests__/https-options.test.ts +163 -0
  65. package/src/__tests__/index.test.ts +279 -284
  66. package/src/__tests__/init.test.ts +3419 -0
  67. package/src/__tests__/jest.setup.ts +173 -16
  68. package/src/__tests__/kv.test.ts +1794 -1093
  69. package/src/__tests__/logger.test.ts +207 -0
  70. package/src/__tests__/logout.test.ts +47 -0
  71. package/src/__tests__/metrics.test.ts +493 -0
  72. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  73. package/src/__tests__/middleware.test.ts +816 -0
  74. package/src/__tests__/mtls-certificates.test.ts +589 -0
  75. package/src/__tests__/package-manager.test.ts +353 -0
  76. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  77. package/src/__tests__/pages/functions-build.test.ts +528 -0
  78. package/src/__tests__/pages/pages.test.ts +81 -0
  79. package/src/__tests__/pages/project-create.test.ts +63 -0
  80. package/src/__tests__/pages/project-list.test.ts +110 -0
  81. package/src/__tests__/pages/project-upload.test.ts +500 -0
  82. package/src/__tests__/pages/publish.test.ts +2864 -0
  83. package/src/__tests__/pages-deployment-tail.test.ts +957 -0
  84. package/src/__tests__/parse.test.ts +436 -0
  85. package/src/__tests__/paths.test.ts +39 -0
  86. package/src/__tests__/publish.test.ts +8849 -0
  87. package/src/__tests__/pubsub.test.ts +496 -0
  88. package/src/__tests__/queues.test.ts +532 -0
  89. package/src/__tests__/r2.test.ts +374 -0
  90. package/src/__tests__/route.test.ts +45 -0
  91. package/src/__tests__/secret.test.ts +693 -0
  92. package/src/__tests__/tail.test.ts +989 -0
  93. package/src/__tests__/test-old-node-version.js +31 -0
  94. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  95. package/src/__tests__/tsconfig-sanity.ts +12 -0
  96. package/src/__tests__/tsconfig.json +8 -0
  97. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  98. package/src/__tests__/type-generation.test.ts +234 -0
  99. package/src/__tests__/unstableDev.test.ts +61 -0
  100. package/src/__tests__/user.test.ts +118 -0
  101. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  102. package/src/__tests__/validate-dev-props.test.ts +56 -0
  103. package/src/__tests__/version.test.ts +35 -0
  104. package/src/__tests__/whoami.test.tsx +172 -0
  105. package/src/__tests__/worker-namespace.test.ts +340 -0
  106. package/src/abort.d.ts +3 -0
  107. package/src/api/dev.ts +321 -0
  108. package/src/api/index.ts +11 -0
  109. package/src/api/mtls-certificate.ts +148 -0
  110. package/src/api/pages/create-worker-bundle-contents.ts +79 -0
  111. package/src/api/pages/index.ts +5 -0
  112. package/src/api/pages/publish.tsx +371 -0
  113. package/src/bundle-reporter.ts +68 -0
  114. package/src/bundle.ts +929 -0
  115. package/src/cfetch/index.ts +127 -71
  116. package/src/cfetch/internal.ts +240 -46
  117. package/src/cli.ts +25 -6
  118. package/src/config/README.md +107 -0
  119. package/src/config/config.ts +282 -0
  120. package/src/config/diagnostics.ts +80 -0
  121. package/src/config/environment.ts +650 -0
  122. package/src/config/index.ts +424 -0
  123. package/src/config/validation-helpers.ts +597 -0
  124. package/src/config/validation.ts +2457 -0
  125. package/src/config-cache.ts +85 -0
  126. package/src/constellation/createProject.tsx +51 -0
  127. package/src/constellation/deleteProject.ts +51 -0
  128. package/src/constellation/deleteProjectModel.ts +76 -0
  129. package/src/constellation/index.ts +75 -0
  130. package/src/constellation/listCatalog.tsx +35 -0
  131. package/src/constellation/listModel.tsx +49 -0
  132. package/src/constellation/listProject.tsx +28 -0
  133. package/src/constellation/listRuntime.tsx +28 -0
  134. package/src/constellation/options.ts +17 -0
  135. package/src/constellation/types.ts +17 -0
  136. package/src/constellation/uploadModel.tsx +84 -0
  137. package/src/constellation/utils.ts +90 -0
  138. package/src/create-worker-preview.ts +293 -0
  139. package/src/create-worker-upload-form.ts +380 -0
  140. package/src/d1/backups.tsx +219 -0
  141. package/src/d1/constants.ts +5 -0
  142. package/src/d1/create.tsx +102 -0
  143. package/src/d1/delete.ts +53 -0
  144. package/src/d1/execute.tsx +371 -0
  145. package/src/d1/formatTimeAgo.ts +14 -0
  146. package/src/d1/index.ts +100 -0
  147. package/src/d1/list.tsx +62 -0
  148. package/src/d1/migrations/apply.tsx +235 -0
  149. package/src/d1/migrations/create.tsx +79 -0
  150. package/src/d1/migrations/helpers.ts +171 -0
  151. package/src/d1/migrations/index.ts +3 -0
  152. package/src/d1/migrations/list.tsx +95 -0
  153. package/src/d1/migrations/options.ts +23 -0
  154. package/src/d1/options.ts +22 -0
  155. package/src/d1/splitter.ts +161 -0
  156. package/src/d1/types.ts +32 -0
  157. package/src/d1/utils.ts +49 -0
  158. package/src/delete.ts +100 -0
  159. package/src/deployments.ts +368 -0
  160. package/src/deprecated/index.ts +144 -0
  161. package/src/dev/dev-vars.ts +39 -0
  162. package/src/dev/dev.tsx +605 -0
  163. package/src/dev/get-local-persistence-path.ts +31 -0
  164. package/src/dev/local.tsx +952 -0
  165. package/src/dev/remote.tsx +635 -0
  166. package/src/dev/start-server.ts +545 -0
  167. package/src/dev/use-esbuild.ts +215 -0
  168. package/src/dev/validate-dev-props.ts +40 -0
  169. package/src/dev-registry.ts +213 -0
  170. package/src/dev.tsx +918 -752
  171. package/src/dialogs.ts +136 -0
  172. package/src/dispatch-namespace.ts +211 -0
  173. package/src/docs/helpers.ts +50 -0
  174. package/src/docs/index.ts +54 -0
  175. package/src/durable.ts +102 -0
  176. package/src/entry.ts +344 -0
  177. package/src/environment-variables/factory.ts +89 -0
  178. package/src/environment-variables/misc-variables.ts +30 -0
  179. package/src/errors.ts +11 -0
  180. package/src/generate/index.ts +304 -0
  181. package/src/git-client.ts +135 -0
  182. package/src/global-wrangler-config-path.ts +26 -0
  183. package/src/https-options.ts +127 -0
  184. package/src/index.ts +769 -0
  185. package/src/init.ts +1123 -0
  186. package/src/inspect.ts +836 -477
  187. package/src/intl-polyfill.d.ts +139 -0
  188. package/src/is-ci.ts +14 -0
  189. package/src/is-interactive.ts +16 -0
  190. package/src/jest.d.ts +4 -0
  191. package/src/kv/helpers.ts +433 -0
  192. package/src/kv/index.ts +594 -0
  193. package/src/logger.ts +123 -0
  194. package/src/metrics/index.ts +5 -0
  195. package/src/metrics/metrics-config.ts +239 -0
  196. package/src/metrics/metrics-dispatcher.ts +96 -0
  197. package/src/metrics/metrics-usage-headers.ts +24 -0
  198. package/src/metrics/send-event.ts +99 -0
  199. package/src/miniflare-cli/README.md +30 -0
  200. package/src/miniflare-cli/assets.ts +251 -0
  201. package/src/miniflare-cli/index.ts +210 -0
  202. package/src/miniflare-cli/request-context.ts +40 -0
  203. package/src/miniflare-cli/tsconfig.json +9 -0
  204. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  205. package/src/miniflare-cli/types.ts +11 -0
  206. package/src/module-collection.ts +322 -53
  207. package/src/mtls-certificate/cli.ts +155 -0
  208. package/src/open-in-browser.ts +17 -0
  209. package/src/package-manager.ts +219 -0
  210. package/src/pages/build.ts +423 -0
  211. package/src/pages/buildFunctions.ts +140 -0
  212. package/src/pages/constants.ts +18 -0
  213. package/src/pages/deployment-tails.ts +281 -0
  214. package/src/pages/deployments.tsx +84 -0
  215. package/src/pages/dev.ts +734 -0
  216. package/src/pages/errors.ts +67 -0
  217. package/src/pages/functions/buildPlugin.ts +114 -0
  218. package/src/pages/functions/buildWorker.ts +350 -0
  219. package/src/pages/functions/filepath-routing.test.ts +234 -0
  220. package/src/pages/functions/filepath-routing.ts +189 -0
  221. package/src/pages/functions/identifiers.ts +78 -0
  222. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  223. package/src/pages/functions/routes-consolidation.ts +73 -0
  224. package/src/pages/functions/routes-transformation.test.ts +282 -0
  225. package/src/pages/functions/routes-transformation.ts +115 -0
  226. package/src/pages/functions/routes-validation.test.ts +403 -0
  227. package/src/pages/functions/routes-validation.ts +202 -0
  228. package/src/pages/functions/routes.ts +151 -0
  229. package/src/pages/functions/tsconfig.json +8 -0
  230. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  231. package/src/pages/functions.ts +86 -0
  232. package/src/pages/hash.ts +13 -0
  233. package/src/pages/index.ts +102 -0
  234. package/src/pages/projects.tsx +159 -0
  235. package/src/pages/prompt-select-project.tsx +31 -0
  236. package/src/pages/publish.tsx +267 -0
  237. package/src/pages/types.ts +46 -0
  238. package/src/pages/upload.tsx +469 -0
  239. package/src/pages/utils.ts +23 -0
  240. package/src/parse.ts +308 -0
  241. package/src/paths.ts +71 -0
  242. package/src/proxy.ts +652 -252
  243. package/src/publish/index.ts +274 -0
  244. package/src/publish/publish.ts +1067 -0
  245. package/src/pubsub/index.ts +286 -0
  246. package/src/pubsub/pubsub-commands.ts +623 -0
  247. package/src/queues/cli/commands/consumer/add.ts +71 -0
  248. package/src/queues/cli/commands/consumer/index.ts +19 -0
  249. package/src/queues/cli/commands/consumer/remove.ts +31 -0
  250. package/src/queues/cli/commands/create.ts +25 -0
  251. package/src/queues/cli/commands/delete.ts +26 -0
  252. package/src/queues/cli/commands/index.ts +35 -0
  253. package/src/queues/cli/commands/list.ts +25 -0
  254. package/src/queues/client.ts +136 -0
  255. package/src/queues/utils.ts +18 -0
  256. package/src/r2/constants.ts +4 -0
  257. package/src/r2/helpers.ts +132 -0
  258. package/src/r2/index.ts +289 -0
  259. package/src/routes.ts +140 -0
  260. package/src/secret/index.ts +379 -0
  261. package/src/selfsigned.d.ts +29 -0
  262. package/src/sites.ts +484 -0
  263. package/src/tail/createTail.ts +415 -0
  264. package/src/tail/filters.ts +277 -0
  265. package/src/tail/index.ts +211 -0
  266. package/src/tail/printing.ts +132 -0
  267. package/src/traverse-module-graph.ts +54 -0
  268. package/src/tsconfig-sanity.ts +16 -0
  269. package/src/type-generation.ts +187 -0
  270. package/src/update-check.ts +19 -0
  271. package/src/user/access.ts +68 -0
  272. package/src/user/auth-variables.ts +113 -0
  273. package/src/user/choose-account.tsx +39 -0
  274. package/src/user/generate-auth-url.ts +33 -0
  275. package/src/user/generate-random-state.ts +16 -0
  276. package/src/user/index.ts +2 -0
  277. package/src/user/user.ts +1234 -0
  278. package/src/utils/collectKeyValues.ts +14 -0
  279. package/src/utils/render.ts +93 -0
  280. package/src/whoami.ts +135 -0
  281. package/src/worker.ts +294 -0
  282. package/src/yargs-types.ts +37 -0
  283. package/src/zones.ts +191 -0
  284. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  285. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  286. package/templates/__tests__/tsconfig.json +8 -0
  287. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  288. package/templates/checked-fetch.js +23 -0
  289. package/templates/d1-beta-facade.js +244 -0
  290. package/templates/facade.d.ts +14 -0
  291. package/templates/first-party-worker-module-facade.ts +19 -0
  292. package/templates/format-dev-errors.ts +34 -0
  293. package/templates/gitignore +172 -0
  294. package/templates/init-tests/test-jest-new-worker.js +23 -0
  295. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  296. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  297. package/templates/middleware/common.ts +62 -0
  298. package/templates/middleware/loader-modules.ts +84 -0
  299. package/templates/middleware/loader-sw.ts +233 -0
  300. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  301. package/templates/middleware/middleware-pretty-error.ts +40 -0
  302. package/templates/middleware/middleware-scheduled.ts +15 -0
  303. package/templates/new-worker-scheduled.js +17 -0
  304. package/templates/new-worker-scheduled.ts +32 -0
  305. package/templates/new-worker.js +15 -0
  306. package/templates/new-worker.ts +33 -0
  307. package/templates/no-op-worker.js +10 -0
  308. package/templates/pages-dev-pipeline.ts +31 -0
  309. package/templates/pages-dev-util.ts +55 -0
  310. package/templates/pages-shim.ts +12 -0
  311. package/templates/pages-template-plugin.ts +180 -0
  312. package/templates/pages-template-worker.ts +189 -0
  313. package/templates/serve-static-assets.ts +66 -0
  314. package/templates/service-bindings-module-facade.js +55 -0
  315. package/templates/service-bindings-sw-facade.js +42 -0
  316. package/templates/tsconfig-sanity.ts +11 -0
  317. package/templates/tsconfig.init.json +105 -0
  318. package/templates/tsconfig.json +8 -0
  319. package/templates/tsconfig.tsbuildinfo +1 -0
  320. package/wrangler-dist/cli.d.ts +1673 -0
  321. package/wrangler-dist/cli.js +144054 -113972
  322. package/wrangler-dist/wasm-sync.wasm +0 -0
  323. package/pages/functions/buildWorker.ts +0 -62
  324. package/pages/functions/filepath-routing.test.ts +0 -39
  325. package/pages/functions/filepath-routing.ts +0 -221
  326. package/pages/functions/identifiers.ts +0 -78
  327. package/pages/functions/routes.ts +0 -158
  328. package/pages/functions/template-worker.ts +0 -144
  329. package/src/__tests__/mock-cfetch.ts +0 -171
  330. package/src/__tests__/mock-dialogs.ts +0 -65
  331. package/src/__tests__/run-in-tmp.ts +0 -19
  332. package/src/__tests__/run-wrangler.ts +0 -32
  333. package/src/api/form_data.ts +0 -131
  334. package/src/api/preview.ts +0 -128
  335. package/src/api/worker.ts +0 -155
  336. package/src/config.ts +0 -487
  337. package/src/dialogs.tsx +0 -77
  338. package/src/index.tsx +0 -1974
  339. package/src/kv.tsx +0 -267
  340. package/src/pages.tsx +0 -1031
  341. package/src/publish.ts +0 -358
  342. package/src/sites.tsx +0 -114
  343. package/src/tail.tsx +0 -73
  344. package/src/user.tsx +0 -1025
  345. package/static-asset-facade.js +0 -47
  346. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  347. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  348. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  349. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  350. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  351. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  352. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  353. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  354. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  355. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  356. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  357. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  358. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  359. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  360. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  361. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  362. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  363. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  364. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  365. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  366. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  367. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  368. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  369. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  370. package/vendor/wrangler-mime/LICENSE +0 -21
  371. package/vendor/wrangler-mime/Mime.js +0 -97
  372. package/vendor/wrangler-mime/README.md +0 -187
  373. package/vendor/wrangler-mime/cli.js +0 -46
  374. package/vendor/wrangler-mime/index.js +0 -4
  375. package/vendor/wrangler-mime/lite.js +0 -4
  376. package/vendor/wrangler-mime/package.json +0 -52
  377. package/vendor/wrangler-mime/types/other.js +0 -1
  378. package/vendor/wrangler-mime/types/standard.js +0 -1
  379. package/wrangler-dist/cli.js.map +0 -7
  380. /package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
package/src/dev.tsx CHANGED
@@ -1,771 +1,937 @@
1
- import esbuild from "esbuild";
2
- import { readFile } from "fs/promises";
3
- import { existsSync } from "fs";
4
- import type { DirectoryResult } from "tmp-promise";
5
- import tmp from "tmp-promise";
6
- import type { CfPreviewToken } from "./api/preview";
7
- import { Box, Text, useApp, useInput } from "ink";
8
- import React, { useState, useEffect, useRef } from "react";
9
- import path from "path";
10
- import open from "open";
11
- import useInspector from "./inspect";
12
- import type { CfModule } from "./api/worker";
13
- import { createWorker } from "./api/worker";
14
- import type { CfWorkerInit } from "./api/worker";
15
- import { spawn } from "child_process";
16
- import onExit from "signal-exit";
17
- import { syncAssets } from "./sites";
18
- import clipboardy from "clipboardy";
19
- import commandExists from "command-exists";
20
- import assert from "assert";
21
- import { getAPIToken } from "./user";
22
- import fetch from "node-fetch";
23
- import makeModuleCollector from "./module-collection";
24
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
25
- import { usePreviewServer } from "./proxy";
26
- import { execa } from "execa";
1
+ import path from "node:path";
2
+ import chalk from "chalk";
27
3
  import { watch } from "chokidar";
28
-
29
- type CfScriptFormat = undefined | "modules" | "service-worker";
30
-
31
- export type DevProps = {
32
- name?: string;
33
- entry: string;
34
- port?: number;
35
- format: CfScriptFormat;
36
- accountId: undefined | string;
37
- initialMode: "local" | "remote";
38
- jsxFactory: undefined | string;
39
- jsxFragment: undefined | string;
40
- bindings: CfWorkerInit["bindings"];
41
- public: undefined | string;
42
- site: undefined | string;
43
- compatibilityDate: undefined | string;
44
- compatibilityFlags: undefined | string[];
45
- usageModel: undefined | "bundled" | "unbound";
46
- buildCommand: {
47
- command?: undefined | string;
48
- cwd?: undefined | string;
49
- watch_dir?: undefined | string;
50
- };
51
- };
52
-
53
- function Dev(props: DevProps): JSX.Element {
54
- if (props.public && props.format === "service-worker") {
55
- throw new Error(
56
- "You cannot use the service worker format with a `public` directory."
57
- );
58
- }
59
- const port = props.port || 8787;
60
- const apiToken = getAPIToken();
61
- const directory = useTmpDir();
62
-
63
- // if there isn't a build command, we just return the entry immediately
64
- // ideally there would be a conditional here, but the rules of hooks
65
- // kinda forbid that, so we thread the entry through useCustomBuild
66
- const entry = useCustomBuild(props.entry, props.buildCommand);
67
-
68
- const bundle = useEsbuild({
69
- entry,
70
- destination: directory,
71
- staticRoot: props.public,
72
- jsxFactory: props.jsxFactory,
73
- jsxFragment: props.jsxFragment,
74
- });
75
- if (bundle && bundle.type === "commonjs" && !props.format && props.public) {
76
- throw new Error(
77
- "You cannot use the service worker format with a `public` directory."
78
- );
79
- }
80
-
81
- const toggles = useHotkeys(
82
- {
83
- local: props.initialMode === "local",
84
- tunnel: false,
85
- },
86
- port
87
- );
88
-
89
- useTunnel(toggles.tunnel);
90
-
91
- return (
92
- <>
93
- {toggles.local ? (
94
- <Local
95
- name={props.name}
96
- bundle={bundle}
97
- format={props.format}
98
- bindings={props.bindings}
99
- site={props.site}
100
- public={props.public}
101
- port={props.port}
102
- />
103
- ) : (
104
- <Remote
105
- name={props.name}
106
- bundle={bundle}
107
- format={props.format}
108
- accountId={props.accountId}
109
- apiToken={apiToken}
110
- bindings={props.bindings}
111
- site={props.site}
112
- public={props.public}
113
- port={props.port}
114
- compatibilityDate={props.compatibilityDate}
115
- compatibilityFlags={props.compatibilityFlags}
116
- usageModel={props.usageModel}
117
- />
118
- )}
119
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
120
- <Text>
121
- {`B to open a browser, D to open Devtools, S to ${
122
- toggles.tunnel ? "turn off" : "turn on"
123
- } (experimental) sharing, L to ${
124
- toggles.local ? "turn off" : "turn on"
125
- } local mode, X to exit`}
126
- </Text>
127
- </Box>
128
- </>
129
- );
4
+ import getPort from "get-port";
5
+ import { render } from "ink";
6
+ import React from "react";
7
+ import { findWranglerToml, printBindings, readConfig } from "./config";
8
+ import Dev from "./dev/dev";
9
+ import { getVarsForDev } from "./dev/dev-vars";
10
+ import { getLocalPersistencePath } from "./dev/get-local-persistence-path";
11
+
12
+ import { startDevServer } from "./dev/start-server";
13
+ import { getEntry } from "./entry";
14
+ import { logger } from "./logger";
15
+ import * as metrics from "./metrics";
16
+ import { getAssetPaths, getSiteAssetPaths } from "./sites";
17
+ import { getAccountFromCache, loginOrRefreshIfRequired } from "./user";
18
+ import { collectKeyValues } from "./utils/collectKeyValues";
19
+ import { identifyD1BindingsAsBeta } from "./worker";
20
+ import { getHostFromRoute, getZoneForRoute, getZoneIdFromHost } from "./zones";
21
+ import {
22
+ DEFAULT_INSPECTOR_PORT,
23
+ DEFAULT_LOCAL_PORT,
24
+ getDevCompatibilityDate,
25
+ getRules,
26
+ getScriptName,
27
+ isLegacyEnv,
28
+ printWranglerBanner,
29
+ } from "./index";
30
+ import type { Config, Environment } from "./config";
31
+ import type { Route, Rule } from "./config/environment";
32
+ import type { LoggerLevel } from "./logger";
33
+ import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli/types";
34
+ import type { CfWorkerInit } from "./worker";
35
+ import type {
36
+ CommonYargsArgv,
37
+ StrictYargsOptionsToInterface,
38
+ } from "./yargs-types";
39
+
40
+ export function devOptions(yargs: CommonYargsArgv) {
41
+ return (
42
+ yargs
43
+ .positional("script", {
44
+ describe: "The path to an entry point for your worker",
45
+ type: "string",
46
+ })
47
+ .option("name", {
48
+ describe: "Name of the worker",
49
+ type: "string",
50
+ requiresArg: true,
51
+ })
52
+ // We want to have a --no-bundle flag, but yargs requires that
53
+ // we also have a --bundle flag (that it adds the --no to by itself)
54
+ // So we make a --bundle flag, but hide it, and then add a --no-bundle flag
55
+ // that's visible to the user but doesn't "do" anything.
56
+ .option("bundle", {
57
+ describe: "Run wrangler's compilation step before publishing",
58
+ type: "boolean",
59
+ hidden: true,
60
+ })
61
+ .option("no-bundle", {
62
+ describe: "Skip internal build steps and directly publish script",
63
+ type: "boolean",
64
+ default: false,
65
+ })
66
+ .option("format", {
67
+ choices: ["modules", "service-worker"] as const,
68
+ describe: "Choose an entry type",
69
+ hidden: true,
70
+ deprecated: true,
71
+ })
72
+ .option("compatibility-date", {
73
+ describe: "Date to use for compatibility checks",
74
+ type: "string",
75
+ requiresArg: true,
76
+ })
77
+ .option("compatibility-flags", {
78
+ describe: "Flags to use for compatibility checks",
79
+ alias: "compatibility-flag",
80
+ type: "string",
81
+ requiresArg: true,
82
+ array: true,
83
+ })
84
+ .option("latest", {
85
+ describe: "Use the latest version of the worker runtime",
86
+ type: "boolean",
87
+ default: true,
88
+ })
89
+ .option("ip", {
90
+ describe: "IP address to listen on",
91
+ type: "string",
92
+ })
93
+ .option("port", {
94
+ describe: "Port to listen on",
95
+ type: "number",
96
+ })
97
+ .option("inspector-port", {
98
+ describe: "Port for devtools to connect to",
99
+ type: "number",
100
+ })
101
+ .option("routes", {
102
+ describe: "Routes to upload",
103
+ alias: "route",
104
+ type: "string",
105
+ requiresArg: true,
106
+ array: true,
107
+ })
108
+ .option("host", {
109
+ type: "string",
110
+ requiresArg: true,
111
+ describe:
112
+ "Host to forward requests to, defaults to the zone of project",
113
+ })
114
+ .option("local-protocol", {
115
+ describe: "Protocol to listen to requests on, defaults to http.",
116
+ choices: ["http", "https"] as const,
117
+ })
118
+ .options("local-upstream", {
119
+ type: "string",
120
+ describe:
121
+ "Host to act as origin in local mode, defaults to dev.host or route",
122
+ })
123
+ .option("experimental-public", {
124
+ describe: "Static assets to be served",
125
+ type: "string",
126
+ requiresArg: true,
127
+ deprecated: true,
128
+ hidden: true,
129
+ })
130
+ .option("assets", {
131
+ describe: "Static assets to be served",
132
+ type: "string",
133
+ requiresArg: true,
134
+ })
135
+ .option("public", {
136
+ describe: "(Deprecated) Static assets to be served",
137
+ type: "string",
138
+ requiresArg: true,
139
+ deprecated: true,
140
+ hidden: true,
141
+ })
142
+ .option("site", {
143
+ describe: "Root folder of static assets for Workers Sites",
144
+ type: "string",
145
+ requiresArg: true,
146
+ })
147
+ .option("site-include", {
148
+ describe:
149
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
150
+ type: "string",
151
+ requiresArg: true,
152
+ array: true,
153
+ })
154
+ .option("site-exclude", {
155
+ describe:
156
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
157
+ type: "string",
158
+ requiresArg: true,
159
+ array: true,
160
+ })
161
+ .option("upstream-protocol", {
162
+ describe: "Protocol to forward requests to host on, defaults to https.",
163
+ choices: ["http", "https"] as const,
164
+ })
165
+ .option("var", {
166
+ describe:
167
+ "A key-value pair to be injected into the script as a variable",
168
+ type: "string",
169
+ requiresArg: true,
170
+ array: true,
171
+ })
172
+ .option("define", {
173
+ describe: "A key-value pair to be substituted in the script",
174
+ type: "string",
175
+ requiresArg: true,
176
+ array: true,
177
+ })
178
+ .option("jsx-factory", {
179
+ describe: "The function that is called for each JSX element",
180
+ type: "string",
181
+ requiresArg: true,
182
+ })
183
+ .option("jsx-fragment", {
184
+ describe: "The function that is called for each JSX fragment",
185
+ type: "string",
186
+ requiresArg: true,
187
+ })
188
+ .option("tsconfig", {
189
+ describe: "Path to a custom tsconfig.json file",
190
+ type: "string",
191
+ requiresArg: true,
192
+ })
193
+ .option("local", {
194
+ alias: "l",
195
+ describe: "Run on my machine",
196
+ type: "boolean",
197
+ default: false, // I bet this will a point of contention. We'll revisit it.
198
+ })
199
+ .option("experimental-local", {
200
+ describe: "Run on my machine using the Cloudflare Workers runtime",
201
+ type: "boolean",
202
+ default: false,
203
+ })
204
+ .option("experimental-local-remote-kv", {
205
+ describe:
206
+ "Read/write KV data from/to real namespaces on the Cloudflare network",
207
+ type: "boolean",
208
+ default: false,
209
+ })
210
+ .check((argv) => {
211
+ if (argv.local && argv["experimental-local"]) {
212
+ throw new Error(
213
+ "--local and --experimental-local are mutually exclusive. " +
214
+ "Please enable one or the other."
215
+ );
216
+ }
217
+ if (
218
+ argv["experimental-local-remote-kv"] &&
219
+ !argv["experimental-local"]
220
+ ) {
221
+ throw new Error(
222
+ "--experimental-local-remote-kv requires --experimental-local to be enabled."
223
+ );
224
+ }
225
+ return true;
226
+ })
227
+ .option("minify", {
228
+ describe: "Minify the script",
229
+ type: "boolean",
230
+ })
231
+ .option("node-compat", {
232
+ describe: "Enable Node.js compatibility",
233
+ type: "boolean",
234
+ })
235
+ .option("experimental-enable-local-persistence", {
236
+ describe:
237
+ "Enable persistence for local mode (deprecated, use --persist)",
238
+ type: "boolean",
239
+ deprecated: true,
240
+ hidden: true,
241
+ })
242
+ .option("persist", {
243
+ describe:
244
+ "Enable persistence for local mode, using default path: .wrangler/state",
245
+ type: "boolean",
246
+ })
247
+ .option("persist-to", {
248
+ describe:
249
+ "Specify directory to use for local persistence (implies --persist)",
250
+ type: "string",
251
+ requiresArg: true,
252
+ })
253
+ .option("live-reload", {
254
+ describe:
255
+ "Auto reload HTML pages when change is detected in local mode",
256
+ type: "boolean",
257
+ })
258
+ .check((argv) => {
259
+ const local = argv["local"] || argv["experimental-local"];
260
+ if (argv["live-reload"] && !local) {
261
+ throw new Error(
262
+ "--live-reload is only supported in local mode. " +
263
+ "Please enable either --local or --experimental-local."
264
+ );
265
+ }
266
+ return true;
267
+ })
268
+ .option("inspect", {
269
+ describe: "Enable dev tools",
270
+ type: "boolean",
271
+ deprecated: true,
272
+ hidden: true,
273
+ })
274
+ .option("legacy-env", {
275
+ type: "boolean",
276
+ describe: "Use legacy environments",
277
+ hidden: true,
278
+ })
279
+ .option("test-scheduled", {
280
+ describe: "Test scheduled events by visiting /__scheduled in browser",
281
+ type: "boolean",
282
+ default: false,
283
+ })
284
+ .option("log-level", {
285
+ choices: ["debug", "info", "log", "warn", "error", "none"] as const,
286
+ describe: "Specify logging level",
287
+ // Yargs requires this to type log-level properly
288
+ default: "log" as LoggerLevel,
289
+ })
290
+ );
130
291
  }
131
292
 
132
- function Remote(props: {
133
- name: undefined | string;
134
- bundle: EsbuildBundle | undefined;
135
- format: CfScriptFormat;
136
- public: undefined | string;
137
- site: undefined | string;
138
- port: number;
139
- accountId: undefined | string;
140
- apiToken: undefined | string;
141
- bindings: CfWorkerInit["bindings"];
142
- compatibilityDate: string | undefined;
143
- compatibilityFlags: undefined | string[];
144
- usageModel: undefined | "bundled" | "unbound";
145
- }) {
146
- assert(props.accountId, "accountId is required");
147
- assert(props.apiToken, "apiToken is required");
148
- const previewToken = useWorker({
149
- name: props.name,
150
- bundle: props.bundle,
151
- format: props.format,
152
- modules: props.bundle ? props.bundle.modules : [],
153
- accountId: props.accountId,
154
- apiToken: props.apiToken,
155
- bindings: props.bindings,
156
- sitesFolder: props.site,
157
- port: props.port,
158
- compatibilityDate: props.compatibilityDate,
159
- compatibilityFlags: props.compatibilityFlags,
160
- usageModel: props.usageModel,
161
- });
162
-
163
- usePreviewServer({
164
- previewToken,
165
- publicRoot: props.public,
166
- port: props.port,
167
- });
168
-
169
- useInspector({
170
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
171
- port: 9229,
172
- logToTerminal: true,
173
- });
174
- return null;
175
- }
176
- function Local(props: {
177
- name: undefined | string;
178
- bundle: EsbuildBundle | undefined;
179
- format: CfScriptFormat;
180
- bindings: CfWorkerInit["bindings"];
181
- public: undefined | string;
182
- site: undefined | string;
183
- port: number;
184
- }) {
185
- const { inspectorUrl } = useLocalWorker({
186
- name: props.name,
187
- bundle: props.bundle,
188
- format: props.format,
189
- bindings: props.bindings,
190
- port: props.port,
191
- });
192
- useInspector({ inspectorUrl, port: 9229, logToTerminal: false });
193
- return null;
293
+ type DevArguments = StrictYargsOptionsToInterface<typeof devOptions>;
294
+
295
+ export async function devHandler(args: DevArguments) {
296
+ if (!(args.local || args.experimentalLocal)) {
297
+ const isLoggedIn = await loginOrRefreshIfRequired();
298
+ if (!isLoggedIn) {
299
+ throw new Error(
300
+ "You must be logged in to use wrangler dev in remote mode. Try logging in, or run wrangler dev --local."
301
+ );
302
+ }
303
+ }
304
+
305
+ let watcher;
306
+ try {
307
+ const devInstance = await startDev(args);
308
+ watcher = devInstance.watcher;
309
+ const { waitUntilExit } = devInstance.devReactElement;
310
+ await waitUntilExit();
311
+ } finally {
312
+ await watcher?.close();
313
+ }
194
314
  }
195
315
 
196
- function useLocalWorker(props: {
197
- name: undefined | string;
198
- bundle: EsbuildBundle | undefined;
199
- format: CfScriptFormat;
200
- bindings: CfWorkerInit["bindings"];
201
- port: number;
202
- }) {
203
- // TODO: pass vars via command line
204
- const { bundle, format, bindings, port } = props;
205
- const local = useRef<ReturnType<typeof spawn>>();
206
- const removeSignalExitListener = useRef<() => void>();
207
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
208
- useEffect(() => {
209
- async function startLocalWorker() {
210
- if (!bundle) return;
211
- if (format === "modules" && bundle.type === "commonjs") {
212
- console.error("āŽ” Cannot use modules with a commonjs bundle.");
213
- // TODO: a much better error message here, with what to do next
214
- return;
215
- }
216
- if (format === "service-worker" && bundle.type !== "esm") {
217
- console.error("āŽ” Cannot use service-worker with a esm bundle.");
218
- // TODO: a much better error message here, with what to do next
219
- return;
220
- }
221
-
222
- console.log("āŽ” Starting a local server...");
223
- // TODO: just use execa for this
224
- local.current = spawn("node", [
225
- "--experimental-vm-modules",
226
- "--inspect",
227
- require.resolve("miniflare/cli"),
228
- bundle.path,
229
- "--watch",
230
- "--wrangler-config",
231
- path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
232
- "--env",
233
- path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
234
- "--package",
235
- path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
236
- "--port",
237
- port.toString(),
238
- "--kv-persist",
239
- "--cache-persist",
240
- "--do-persist",
241
- ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
242
- return ["--binding", `${key}=${value}`];
243
- }),
244
- ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
245
- return ["--kv", binding];
246
- }),
247
- ...(bindings.durable_objects?.bindings || []).flatMap(
248
- ({ name, class_name }) => {
249
- return ["--do", `${name}=${class_name}`];
250
- }
251
- ),
252
- "--modules",
253
- format ||
254
- (bundle.type === "esm" ? "modules" : "service-worker") === "modules"
255
- ? "true"
256
- : "false",
257
- ]);
258
- console.log(`⬣ Listening at http://localhost:${port}`);
259
-
260
- local.current.on("close", (code) => {
261
- if (code !== null) {
262
- console.log(`miniflare process exited with code ${code}`);
263
- }
264
- });
265
-
266
- local.current.stdout.on("data", (data: Buffer) => {
267
- console.log(`${data.toString()}`);
268
- });
269
-
270
- local.current.stderr.on("data", (data: Buffer) => {
271
- console.error(`${data.toString()}`);
272
- const matches =
273
- /Debugger listening on (ws:\/\/127\.0\.0\.1:9229\/[A-Za-z0-9-]+)/.exec(
274
- data.toString()
275
- );
276
- if (matches) {
277
- setInspectorUrl(matches[1]);
278
- }
279
- });
280
-
281
- local.current.on("exit", (code) => {
282
- if (code !== 0) {
283
- console.error(`miniflare process exited with code ${code}`);
284
- }
285
- });
286
-
287
- local.current.on("error", (error: Error) => {
288
- console.error(`miniflare process failed to spawn`);
289
- console.error(error);
290
- });
291
-
292
- removeSignalExitListener.current = onExit((_code, _signal) => {
293
- console.log("āŽ” Shutting down local server.");
294
- local.current?.kill();
295
- local.current = undefined;
296
- });
297
- }
298
-
299
- startLocalWorker().catch((err) => {
300
- console.error("local worker:", err);
301
- });
302
-
303
- return () => {
304
- if (local.current) {
305
- console.log("āŽ” Shutting down local server.");
306
- local.current?.kill();
307
- local.current = undefined;
308
- removeSignalExitListener.current && removeSignalExitListener.current();
309
- removeSignalExitListener.current = undefined;
310
- }
311
- };
312
- }, [
313
- bundle,
314
- format,
315
- port,
316
- bindings.durable_objects?.bindings,
317
- bindings.kv_namespaces,
318
- bindings.vars,
319
- ]);
320
- return { inspectorUrl };
321
- }
322
-
323
- function useTmpDir(): string | undefined {
324
- const [directory, setDirectory] = useState<DirectoryResult>();
325
- const handleError = useErrorHandler();
326
- useEffect(() => {
327
- let dir: DirectoryResult;
328
- async function create() {
329
- try {
330
- dir = await tmp.dir({ unsafeCleanup: true });
331
- setDirectory(dir);
332
- return;
333
- } catch (err) {
334
- console.error("failed to create tmp dir");
335
- throw err;
336
- }
337
- }
338
- create().catch((err) => {
339
- // we want to break here
340
- // we can't do much without a temp dir anyway
341
- handleError(err);
342
- });
343
- return () => {
344
- dir.cleanup().catch(() => {
345
- // extremely unlikely,
346
- // but it's 2021 after all
347
- console.error("failed to cleanup tmp dir");
348
- });
349
- };
350
- }, [handleError]);
351
- return directory?.path;
352
- }
353
-
354
- function useCustomBuild(
355
- expectedEntry: string,
356
- props: {
357
- command?: undefined | string;
358
- cwd?: undefined | string;
359
- watch_dir?: undefined | string;
360
- }
361
- ): undefined | string {
362
- const [entry, setEntry] = useState<string | undefined>(
363
- // if there's no build command, just return the expected entry
364
- props.command ? null : expectedEntry
365
- );
366
- const { command, cwd, watch_dir } = props;
367
- useEffect(() => {
368
- if (!command) return;
369
- let cmd, interval;
370
- console.log("running:", command);
371
- const commandPieces = command.split(" ");
372
- cmd = execa(commandPieces[0], commandPieces.slice(1), {
373
- ...(cwd && { cwd }),
374
- stderr: "inherit",
375
- stdout: "inherit",
376
- });
377
- if (watch_dir) {
378
- watch(watch_dir, { persistent: true, ignoreInitial: true }).on(
379
- "all",
380
- (_event, _path) => {
381
- console.log(`The file ${path} changed, restarting build...`);
382
- cmd.kill();
383
- cmd = execa(commandPieces[0], commandPieces.slice(1), {
384
- ...(cwd && { cwd }),
385
- stderr: "inherit",
386
- stdout: "inherit",
387
- });
388
- }
389
- );
390
- }
391
-
392
- // check every so often whether `expectedEntry` exists
393
- // if it does, we're done
394
- const startedAt = Date.now();
395
- interval = setInterval(() => {
396
- if (existsSync(expectedEntry)) {
397
- clearInterval(interval);
398
- setEntry(expectedEntry);
399
- } else {
400
- const elapsed = Date.now() - startedAt;
401
- // timeout after 30 seconds of waiting
402
- if (elapsed > 1000 * 60 * 30) {
403
- console.error("āŽ” Build timed out.");
404
- clearInterval(interval);
405
- cmd.kill();
406
- }
407
- }
408
- }, 200);
409
- // TODO: we could probably timeout here after a while
410
-
411
- return () => {
412
- if (cmd) {
413
- cmd.kill();
414
- cmd = undefined;
415
- }
416
- clearInterval(interval);
417
- interval = undefined;
418
- };
419
- }, [command, cwd, expectedEntry, watch_dir]);
420
- return entry;
421
- }
422
-
423
- type EsbuildBundle = {
424
- id: number;
425
- path: string;
426
- entry: string;
427
- type: "esm" | "commonjs";
428
- exports: string[];
429
- modules: CfModule[];
316
+ export type AdditionalDevProps = {
317
+ vars?: {
318
+ [key: string]: unknown;
319
+ };
320
+ kv?: {
321
+ binding: string;
322
+ id: string;
323
+ preview_id?: string;
324
+ }[];
325
+ durableObjects?: {
326
+ name: string;
327
+ class_name: string;
328
+ script_name?: string | undefined;
329
+ environment?: string | undefined;
330
+ }[];
331
+ r2?: {
332
+ binding: string;
333
+ bucket_name: string;
334
+ preview_bucket_name?: string;
335
+ }[];
336
+ d1Databases?: Environment["d1_databases"];
337
+ processEntrypoint?: boolean;
338
+ moduleRoot?: string;
339
+ rules?: Rule[];
340
+ constellation?: Environment["constellation"];
430
341
  };
431
342
 
432
- function useEsbuild(props: {
433
- entry: undefined | string;
434
- destination: string | undefined;
435
- staticRoot: undefined | string;
436
- jsxFactory: string | undefined;
437
- jsxFragment: string | undefined;
438
- }): EsbuildBundle | undefined {
439
- const { entry, destination, staticRoot, jsxFactory, jsxFragment } = props;
440
- const [bundle, setBundle] = useState<EsbuildBundle>();
441
- useEffect(() => {
442
- let result: esbuild.BuildResult;
443
- async function build() {
444
- if (!destination || !entry) return;
445
- const moduleCollector = makeModuleCollector();
446
- result = await esbuild.build({
447
- entryPoints: [entry],
448
- bundle: true,
449
- outdir: destination,
450
- metafile: true,
451
- format: "esm",
452
- sourcemap: true,
453
- loader: {
454
- ".js": "jsx",
455
- },
456
- ...(jsxFactory && { jsxFactory }),
457
- ...(jsxFragment && { jsxFragment }),
458
- external: ["__STATIC_CONTENT_MANIFEST"],
459
- conditions: ["worker", "browser"],
460
- plugins: [moduleCollector.plugin],
461
- // TODO: import.meta.url
462
- watch: {
463
- async onRebuild(error) {
464
- if (error) console.error("watch build failed:", error);
465
- else {
466
- // nothing really changes here, so let's increment the id
467
- // to change the return object's identity
468
- setBundle((previousBundle) => ({
469
- ...previousBundle,
470
- id: previousBundle.id + 1,
471
- }));
472
- }
473
- },
474
- },
475
- });
476
-
477
- const chunks = Object.entries(result.metafile.outputs).find(
478
- ([_path, { entryPoint }]) =>
479
- entryPoint === Object.keys(result.metafile.inputs)[0]
480
- ); // assumedly only one entry point
481
-
482
- setBundle({
483
- id: 0,
484
- entry,
485
- path: chunks[0],
486
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
487
- exports: chunks[1].exports,
488
- modules: moduleCollector.modules,
489
- });
490
- }
491
- build().catch((_err) => {
492
- // esbuild already logs errors to stderr
493
- // and we don't want to end the process
494
- // on build errors anyway
495
- // so this is a no-op error handler
496
- });
497
- return () => {
498
- result?.stop();
499
- };
500
- }, [entry, destination, staticRoot, jsxFactory, jsxFragment]);
501
- return bundle;
343
+ type StartDevOptions = DevArguments &
344
+ // These options can be passed in directly when called with the `wrangler.dev()` API.
345
+ // They aren't exposed as CLI arguments.
346
+ AdditionalDevProps & {
347
+ forceLocal?: boolean;
348
+ disableDevRegistry?: boolean;
349
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
350
+ onReady?: (ip: string, port: number) => void;
351
+ showInteractiveDevSession?: boolean;
352
+ };
353
+
354
+ export async function startDev(args: StartDevOptions) {
355
+ let watcher: ReturnType<typeof watch> | undefined;
356
+ let rerender: (node: React.ReactNode) => void | undefined;
357
+ try {
358
+ if (args.logLevel) {
359
+ logger.loggerLevel = args.logLevel;
360
+ }
361
+ await printWranglerBanner();
362
+
363
+ if (args.local && process.platform !== "win32") {
364
+ logger.info(
365
+ chalk.magenta(
366
+ `Want to try out the next version of local mode using the open-source Workers runtime?\nSwitch out --local for ${chalk.bold(
367
+ "--experimental-local"
368
+ )} and let us know what you think at https://discord.gg/cloudflaredev !`
369
+ )
370
+ );
371
+ }
372
+
373
+ const configPath =
374
+ args.config ||
375
+ (args.script && findWranglerToml(path.dirname(args.script)));
376
+ let config = readConfig(configPath, args);
377
+
378
+ if (config.configPath) {
379
+ watcher = watch(config.configPath, {
380
+ persistent: true,
381
+ }).on("change", async (_event) => {
382
+ // TODO: Do we need to handle different `_event` types differently?
383
+ // e.g. what if the file is deleted, or added?
384
+ config = readConfig(configPath, args);
385
+ if (config.configPath) {
386
+ logger.log(`${path.basename(config.configPath)} changed...`);
387
+ rerender(await getDevReactElement(config));
388
+ }
389
+ });
390
+ }
391
+
392
+ const {
393
+ entry,
394
+ legacyNodeCompat,
395
+ nodejsCompat,
396
+ upstreamProtocol,
397
+ zoneId,
398
+ host,
399
+ routes,
400
+ getLocalPort,
401
+ getInspectorPort,
402
+ cliDefines,
403
+ localPersistencePath,
404
+ } = await validateDevServerSettings(args, config);
405
+
406
+ await metrics.sendMetricsEvent(
407
+ "run dev",
408
+ {
409
+ local: args.local,
410
+ usesTypeScript: /\.tsx?$/.test(entry.file),
411
+ },
412
+ { sendMetrics: config.send_metrics, offline: args.local }
413
+ );
414
+
415
+ // eslint-disable-next-line no-inner-declarations
416
+ async function getDevReactElement(configParam: Config) {
417
+ const { assetPaths, bindings } = getBindingsAndAssetPaths(
418
+ args,
419
+ configParam
420
+ );
421
+
422
+ return (
423
+ <Dev
424
+ name={getScriptName({ name: args.name, env: args.env }, configParam)}
425
+ noBundle={!(args.bundle ?? !configParam.no_bundle)}
426
+ entry={entry}
427
+ env={args.env}
428
+ zone={zoneId}
429
+ host={host}
430
+ routes={routes}
431
+ processEntrypoint={!!args.processEntrypoint}
432
+ rules={args.rules ?? getRules(configParam)}
433
+ legacyEnv={isLegacyEnv(configParam)}
434
+ minify={args.minify ?? configParam.minify}
435
+ legacyNodeCompat={legacyNodeCompat}
436
+ nodejsCompat={nodejsCompat}
437
+ build={configParam.build || {}}
438
+ define={{ ...configParam.define, ...cliDefines }}
439
+ initialMode={
440
+ args.local || args.experimentalLocal ? "local" : "remote"
441
+ }
442
+ jsxFactory={args.jsxFactory || configParam.jsx_factory}
443
+ jsxFragment={args.jsxFragment || configParam.jsx_fragment}
444
+ tsconfig={args.tsconfig ?? configParam.tsconfig}
445
+ upstreamProtocol={upstreamProtocol}
446
+ localProtocol={args.localProtocol || configParam.dev.local_protocol}
447
+ localUpstream={args.localUpstream ?? host}
448
+ localPersistencePath={localPersistencePath}
449
+ liveReload={args.liveReload || false}
450
+ accountId={configParam.account_id || getAccountFromCache()?.id}
451
+ assetPaths={assetPaths}
452
+ assetsConfig={configParam.assets}
453
+ initialPort={
454
+ args.port ?? configParam.dev.port ?? (await getLocalPort())
455
+ }
456
+ initialIp={args.ip || configParam.dev.ip}
457
+ inspectorPort={
458
+ args.inspectorPort ??
459
+ configParam.dev.inspector_port ??
460
+ (await getInspectorPort())
461
+ }
462
+ isWorkersSite={Boolean(args.site || configParam.site)}
463
+ compatibilityDate={getDevCompatibilityDate(
464
+ configParam,
465
+ args.compatibilityDate
466
+ )}
467
+ compatibilityFlags={
468
+ args.compatibilityFlags || configParam.compatibility_flags
469
+ }
470
+ usageModel={configParam.usage_model}
471
+ bindings={bindings}
472
+ crons={configParam.triggers.crons}
473
+ queueConsumers={configParam.queues.consumers}
474
+ onReady={args.onReady}
475
+ inspect={args.inspect ?? true}
476
+ showInteractiveDevSession={args.showInteractiveDevSession}
477
+ forceLocal={args.forceLocal}
478
+ enablePagesAssetsServiceBinding={args.enablePagesAssetsServiceBinding}
479
+ firstPartyWorker={configParam.first_party_worker}
480
+ sendMetrics={configParam.send_metrics}
481
+ testScheduled={args.testScheduled}
482
+ experimentalLocal={args.experimentalLocal}
483
+ experimentalLocalRemoteKv={args.experimentalLocalRemoteKv}
484
+ />
485
+ );
486
+ }
487
+ const devReactElement = render(await getDevReactElement(config));
488
+
489
+ // In the bootstrapper script `bin/wrangler.js`, we open an IPC channel, so
490
+ // IPC messages from this process are propagated through the bootstrapper.
491
+ // Normally, Node's SIGINT handler would close this for us, but interactive
492
+ // mode enables raw mode on stdin which disables the built-in handler. The
493
+ // following line disconnects from the IPC channel when we press `x` or
494
+ // CTRL-C in interactive mode, ensuring no open handles, and allowing for a
495
+ // clean exit. Note, if we called `stop()` using the dev API, we don't want
496
+ // to disconnect here, as the user may still need IPC. We also don't want
497
+ // to disconnect if this file was imported in Jest (not the case with E2E
498
+ // tests), as that would stop communication with the test runner.
499
+ let apiStopped = false;
500
+ void devReactElement.waitUntilExit().then(() => {
501
+ if (!apiStopped && typeof jest === "undefined") process.disconnect?.();
502
+ });
503
+
504
+ rerender = devReactElement.rerender;
505
+ return {
506
+ devReactElement,
507
+ watcher,
508
+ stop: async () => {
509
+ apiStopped = true;
510
+ devReactElement.unmount();
511
+ await watcher?.close();
512
+ },
513
+ };
514
+ } finally {
515
+ await watcher?.close();
516
+ }
502
517
  }
503
518
 
504
- function useWorker(props: {
505
- name: undefined | string;
506
- bundle: EsbuildBundle | undefined;
507
- format: CfScriptFormat;
508
- modules: CfModule[];
509
- accountId: string;
510
- apiToken: string;
511
- bindings: CfWorkerInit["bindings"];
512
- sitesFolder: undefined | string;
513
- port: number;
514
- compatibilityDate: string | undefined;
515
- compatibilityFlags: string[] | undefined;
516
- usageModel: undefined | "bundled" | "unbound";
517
- }): CfPreviewToken | undefined {
518
- const {
519
- name,
520
- bundle,
521
- format,
522
- modules,
523
- accountId,
524
- apiToken,
525
- bindings,
526
- sitesFolder,
527
- compatibilityDate,
528
- compatibilityFlags,
529
- usageModel,
530
- port,
531
- } = props;
532
- const [token, setToken] = useState<CfPreviewToken | undefined>();
533
-
534
- // This is the most reliable way to detect whether
535
- // something's "happened" in our system; We make a ref and
536
- // mark it once we log our initial message. Refs are vars!
537
- const startedRef = useRef(false);
538
-
539
- useEffect(() => {
540
- async function start() {
541
- setToken(undefined); // reset token in case we're re-running
542
-
543
- if (!bundle) return;
544
- if (format === "modules" && bundle.type === "commonjs") {
545
- console.error("āŽ” Cannot use modules with a commonjs bundle.");
546
- // TODO: a much better error message here, with what to do next
547
- return;
548
- }
549
- if (format === "service-worker" && bundle.type !== "esm") {
550
- console.error("āŽ” Cannot use service-worker with a esm bundle.");
551
- // TODO: a much better error message here, with what to do next
552
- return;
553
- }
554
-
555
- if (!startedRef.current) {
556
- startedRef.current = true;
557
- } else {
558
- console.log("āŽ” Detected changes, restarting server...");
559
- }
560
-
561
- const assets = sitesFolder
562
- ? await syncAssets(
563
- accountId,
564
- path.basename(bundle.path),
565
- sitesFolder,
566
- true,
567
- undefined // TODO: env
568
- )
569
- : {
570
- manifest: undefined,
571
- namespace: undefined,
572
- }; // TODO: cancellable?
573
-
574
- const content = await readFile(bundle.path, "utf-8");
575
- const init: CfWorkerInit = {
576
- name,
577
- main: {
578
- name: path.basename(bundle.path),
579
- type: format || bundle.type === "esm" ? "esm" : "commonjs",
580
- content,
581
- },
582
- modules: modules.concat(
583
- assets.manifest
584
- ? {
585
- name: "__STATIC_CONTENT_MANIFEST",
586
- content: JSON.stringify(assets.manifest),
587
- type: "text",
588
- }
589
- : []
590
- ),
591
- bindings: {
592
- ...bindings,
593
- kv_namespaces: (bindings.kv_namespaces || []).concat(
594
- assets.namespace
595
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
596
- : []
597
- ),
598
- },
599
- migrations: undefined, // no migrations in dev
600
- compatibility_date: compatibilityDate,
601
- compatibility_flags: compatibilityFlags,
602
- usage_model: usageModel,
603
- };
604
- setToken(
605
- await createWorker(init, {
606
- accountId,
607
- apiToken,
608
- })
609
- );
610
- }
611
- start().catch((err) => {
612
- // we want to log the error, but not end the process
613
- // since it could recover after the developer fixes whatever's wrong
614
- console.error("remote worker:", err);
615
- });
616
- }, [
617
- name,
618
- bundle,
619
- format,
620
- accountId,
621
- apiToken,
622
- port,
623
- sitesFolder,
624
- compatibilityDate,
625
- compatibilityFlags,
626
- usageModel,
627
- bindings,
628
- modules,
629
- ]);
630
- return token;
519
+ export async function startApiDev(args: StartDevOptions) {
520
+ if (args.logLevel) {
521
+ logger.loggerLevel = args.logLevel;
522
+ }
523
+ await printWranglerBanner();
524
+
525
+ const configPath =
526
+ args.config || (args.script && findWranglerToml(path.dirname(args.script)));
527
+ const config = readConfig(configPath, args);
528
+
529
+ const {
530
+ entry,
531
+ legacyNodeCompat,
532
+ nodejsCompat,
533
+ upstreamProtocol,
534
+ zoneId,
535
+ host,
536
+ routes,
537
+ getLocalPort,
538
+ getInspectorPort,
539
+ cliDefines,
540
+ localPersistencePath,
541
+ } = await validateDevServerSettings(args, config);
542
+
543
+ await metrics.sendMetricsEvent(
544
+ "run dev (api)",
545
+ { local: args.local },
546
+ { sendMetrics: config.send_metrics, offline: args.local }
547
+ );
548
+
549
+ // eslint-disable-next-line no-inner-declarations
550
+ async function getDevServer(configParam: Config) {
551
+ const { assetPaths, bindings } = getBindingsAndAssetPaths(
552
+ args,
553
+ configParam
554
+ );
555
+
556
+ //if args.bundle is on, don't disable bundling
557
+ //if there's no args.bundle, and configParam.no_bundle is on, disable bundling
558
+ //otherwise, enable bundling
559
+ const enableBundling = args.bundle ?? !configParam.no_bundle;
560
+ return await startDevServer({
561
+ name: getScriptName({ name: args.name, env: args.env }, configParam),
562
+ noBundle: !enableBundling,
563
+ entry: entry,
564
+ env: args.env,
565
+ zone: zoneId,
566
+ host: host,
567
+ routes: routes,
568
+ processEntrypoint: !!args.processEntrypoint,
569
+ rules: args.rules ?? getRules(configParam),
570
+ legacyEnv: isLegacyEnv(configParam),
571
+ minify: args.minify ?? configParam.minify,
572
+ legacyNodeCompat,
573
+ nodejsCompat,
574
+ build: configParam.build || {},
575
+ define: { ...config.define, ...cliDefines },
576
+ initialMode: args.local ? "local" : "remote",
577
+ jsxFactory: args.jsxFactory ?? configParam.jsx_factory,
578
+ jsxFragment: args.jsxFragment ?? configParam.jsx_fragment,
579
+ tsconfig: args.tsconfig ?? configParam.tsconfig,
580
+ upstreamProtocol: upstreamProtocol,
581
+ localProtocol: args.localProtocol ?? configParam.dev.local_protocol,
582
+ localUpstream: args.localUpstream ?? host,
583
+ localPersistencePath,
584
+ liveReload: args.liveReload ?? false,
585
+ accountId: configParam.account_id ?? getAccountFromCache()?.id,
586
+ assetPaths: assetPaths,
587
+ assetsConfig: configParam.assets,
588
+ //port can be 0, which means to use a random port
589
+ initialPort: args.port ?? configParam.dev.port ?? (await getLocalPort()),
590
+ initialIp: args.ip ?? configParam.dev.ip,
591
+ inspectorPort:
592
+ args.inspectorPort ??
593
+ configParam.dev.inspector_port ??
594
+ (await getInspectorPort()),
595
+ isWorkersSite: Boolean(args.site || configParam.site),
596
+ compatibilityDate: getDevCompatibilityDate(
597
+ config,
598
+ // Only `compatibilityDate` will be set when using `unstable_dev`
599
+ args.compatibilityDate
600
+ ),
601
+ compatibilityFlags:
602
+ args.compatibilityFlags ?? configParam.compatibility_flags,
603
+ usageModel: configParam.usage_model,
604
+ bindings: bindings,
605
+ crons: configParam.triggers.crons,
606
+ queueConsumers: configParam.queues.consumers,
607
+ onReady: args.onReady,
608
+ inspect: args.inspect ?? true,
609
+ showInteractiveDevSession: args.showInteractiveDevSession,
610
+ forceLocal: args.forceLocal,
611
+ enablePagesAssetsServiceBinding: args.enablePagesAssetsServiceBinding,
612
+ local: args.local ?? true,
613
+ firstPartyWorker: configParam.first_party_worker,
614
+ sendMetrics: configParam.send_metrics,
615
+ testScheduled: args.testScheduled,
616
+ experimentalLocal: args.experimentalLocal,
617
+ experimentalLocalRemoteKv: args.experimentalLocalRemoteKv,
618
+ disableDevRegistry: args.disableDevRegistry ?? false,
619
+ });
620
+ }
621
+
622
+ const devServer = await getDevServer(config);
623
+ if (!devServer) {
624
+ throw logger.error("Failed to start dev server.");
625
+ }
626
+
627
+ return {
628
+ stop: async () => {
629
+ await devServer.stop();
630
+ },
631
+ };
631
632
  }
632
-
633
- function sleep(period: number) {
634
- return new Promise((resolve) => setTimeout(resolve, period));
633
+ /**
634
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
635
+ */
636
+ function memoizeGetPort(defaultPort: number) {
637
+ let portValue: number;
638
+ return async () => {
639
+ return portValue || (portValue = await getPort({ port: defaultPort }));
640
+ };
635
641
  }
636
- const SLEEP_DURATION = 2000;
637
- // really need a first class api for this
638
- const hostNameRegex = /userHostname="(.*)"/g;
639
- async function findTunnelHostname() {
640
- let hostName: string | undefined;
641
- while (!hostName) {
642
- try {
643
- const resp = await fetch("http://localhost:8789/metrics");
644
- const data = await resp.text();
645
- const matches = Array.from(data.matchAll(hostNameRegex));
646
- hostName = matches[0][1];
647
- } catch (err) {
648
- await sleep(SLEEP_DURATION);
649
- }
650
- }
651
- return hostName;
642
+ /**
643
+ * mask anything that was overridden in .dev.vars
644
+ * so that we don't log potential secrets into the terminal
645
+ */
646
+ function maskVars(bindings: CfWorkerInit["bindings"], configParam: Config) {
647
+ const maskedVars = { ...bindings.vars };
648
+ for (const key of Object.keys(maskedVars)) {
649
+ if (maskedVars[key] !== configParam.vars[key]) {
650
+ // This means it was overridden in .dev.vars
651
+ // so let's mask it
652
+ maskedVars[key] = "(hidden)";
653
+ }
654
+ }
655
+ return maskedVars;
652
656
  }
653
657
 
654
- function useTunnel(toggle: boolean) {
655
- const tunnel = useRef<ReturnType<typeof spawn>>();
656
- const removeSignalExitListener = useRef<() => void>();
657
- // TODO: test if cloudflared is available, if not
658
- // point them to a url where they can get docs to install it
659
- useEffect(() => {
660
- async function startTunnel() {
661
- if (toggle) {
662
- try {
663
- await commandExists("cloudflared");
664
- } catch (e) {
665
- console.error(
666
- "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
667
- );
668
- return;
669
- }
670
- console.log("āŽ” Starting a tunnel...");
671
- tunnel.current = spawn("cloudflared", [
672
- "tunnel",
673
- "--url",
674
- "http://localhost:8787",
675
- "--metrics",
676
- "localhost:8789",
677
- ]);
678
-
679
- tunnel.current.on("close", (code) => {
680
- if (code !== 0) {
681
- console.log(`Tunnel process exited with code ${code}`);
682
- }
683
- });
684
-
685
- removeSignalExitListener.current = onExit((_code, _signal) => {
686
- console.log("āŽ” Shutting down local tunnel.");
687
- tunnel.current?.kill();
688
- tunnel.current = undefined;
689
- });
690
-
691
- const hostName = await findTunnelHostname();
692
- await clipboardy.write(hostName);
693
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
694
- }
695
- }
696
-
697
- startTunnel().catch((err) => {
698
- console.error("tunnel:", err);
699
- });
700
-
701
- return () => {
702
- if (tunnel.current) {
703
- console.log("āŽ” Shutting down tunnel.");
704
- tunnel.current?.kill();
705
- tunnel.current = undefined;
706
- removeSignalExitListener.current && removeSignalExitListener.current();
707
- removeSignalExitListener.current = undefined;
708
- }
709
- };
710
- }, [toggle]);
658
+ async function getZoneIdHostAndRoutes(args: StartDevOptions, config: Config) {
659
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
660
+ // Compute zone info from the `host` and `route` args and config;
661
+ let host = args.host || config.dev.host;
662
+ let zoneId: string | undefined;
663
+ const routes: Route[] | undefined =
664
+ args.routes || (config.route && [config.route]) || config.routes;
665
+
666
+ if (args.forceLocal) {
667
+ args.local = true;
668
+ }
669
+
670
+ if (!args.local && !args.experimentalLocal) {
671
+ if (host) {
672
+ zoneId = await getZoneIdFromHost(host);
673
+ }
674
+ if (!zoneId && routes) {
675
+ const firstRoute = routes[0];
676
+ const zone = await getZoneForRoute(firstRoute);
677
+ if (zone) {
678
+ zoneId = zone.id;
679
+ host = zone.host;
680
+ }
681
+ }
682
+ } else if (!host) {
683
+ if (routes) {
684
+ const firstRoute = routes[0];
685
+ host = getHostFromRoute(firstRoute);
686
+ }
687
+ }
688
+ return { host, routes, zoneId };
711
689
  }
712
690
 
713
- type useHotkeysInitialState = {
714
- local: boolean;
715
- tunnel: boolean;
716
- };
717
- function useHotkeys(initial: useHotkeysInitialState, port: number) {
718
- // UGH, we should put port in context instead
719
- const [toggles, setToggles] = useState(initial);
720
- useInput(
721
- async (
722
- input,
723
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
724
- key
725
- ) => {
726
- switch (input) {
727
- case "b": // open browser
728
- await open(`http://localhost:${port}/`);
729
- break;
730
- case "d": // toggle inspector
731
- await open(
732
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
733
- );
734
- break;
735
- case "s": // toggle tunnel
736
- setToggles((previousToggles) => ({
737
- ...previousToggles,
738
- tunnel: !previousToggles.tunnel,
739
- }));
740
- break;
741
- case "l": // toggle local
742
- setToggles((previousToggles) => ({
743
- ...previousToggles,
744
- local: !previousToggles.local,
745
- }));
746
- break;
747
- case "q": // shut down
748
- case "x": // shut down
749
- process.exit(0);
750
- break;
751
- default:
752
- // nothing?
753
- break;
754
- }
755
- }
756
- );
757
- return toggles;
691
+ async function validateDevServerSettings(
692
+ args: StartDevOptions,
693
+ config: Config
694
+ ) {
695
+ const entry = await getEntry(
696
+ { assets: args.assets, script: args.script, moduleRoot: args.moduleRoot },
697
+ config,
698
+ "dev"
699
+ );
700
+
701
+ const { zoneId, host, routes } = await getZoneIdHostAndRoutes(args, config);
702
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
703
+ const getInspectorPort = memoizeGetPort(DEFAULT_INSPECTOR_PORT);
704
+
705
+ if (config.services && config.services.length > 0) {
706
+ logger.warn(
707
+ `This worker is bound to live services: ${config.services
708
+ .map(
709
+ (service) =>
710
+ `${service.binding} (${service.service}${
711
+ service.environment ? `@${service.environment}` : ""
712
+ })`
713
+ )
714
+ .join(", ")}`
715
+ );
716
+ }
717
+
718
+ if (args.inspect) {
719
+ //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
720
+ logger.warn(
721
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
722
+ );
723
+ }
724
+ if (args.experimentalPublic) {
725
+ throw new Error(
726
+ "The --experimental-public field has been renamed to --assets"
727
+ );
728
+ }
729
+
730
+ if (args.public) {
731
+ throw new Error("The --public field has been renamed to --assets");
732
+ }
733
+
734
+ if ((args.assets ?? config.assets) && (args.site ?? config.site)) {
735
+ throw new Error("Cannot use Assets and Workers Sites in the same Worker.");
736
+ }
737
+
738
+ if (args.assets) {
739
+ logger.warn(
740
+ "The --assets argument is experimental and may change or break at any time"
741
+ );
742
+ }
743
+ const upstreamProtocol =
744
+ args.upstreamProtocol ?? config.dev.upstream_protocol;
745
+ if (upstreamProtocol === "http") {
746
+ logger.warn(
747
+ "Setting upstream-protocol to http is not currently implemented.\n" +
748
+ "If this is required in your project, please add your use case to the following issue:\n" +
749
+ "https://github.com/cloudflare/workers-sdk/issues/583."
750
+ );
751
+ }
752
+ const legacyNodeCompat = args.nodeCompat ?? config.node_compat;
753
+ if (legacyNodeCompat) {
754
+ logger.warn(
755
+ "Enabling Node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
756
+ );
757
+ }
758
+
759
+ const compatibilityFlags =
760
+ args.compatibilityFlags ?? config.compatibility_flags;
761
+ const nodejsCompat = compatibilityFlags?.includes("nodejs_compat");
762
+ if (legacyNodeCompat && nodejsCompat) {
763
+ throw new Error(
764
+ "The `nodejs_compat` compatibility flag cannot be used in conjunction with the legacy `--node-compat` flag. If you want to use the Workers runtime Node.js compatibility features, please remove the `--node-compat` argument from your CLI command or `node_compat = true` from your config file."
765
+ );
766
+ }
767
+
768
+ if (args.experimentalEnableLocalPersistence) {
769
+ logger.warn(
770
+ `--experimental-enable-local-persistence is deprecated.\n` +
771
+ `Move any existing data to .wrangler/state and use --persist, or\n` +
772
+ `use --persist-to=./wrangler-local-state to keep using the old path.`
773
+ );
774
+ }
775
+
776
+ const localPersistencePath = getLocalPersistencePath(
777
+ args.persistTo,
778
+ Boolean(args.persist),
779
+ config.configPath
780
+ );
781
+
782
+ const cliDefines = collectKeyValues(args.define);
783
+
784
+ return {
785
+ entry,
786
+ upstreamProtocol,
787
+ legacyNodeCompat,
788
+ nodejsCompat,
789
+ getLocalPort,
790
+ getInspectorPort,
791
+ zoneId,
792
+ host,
793
+ routes,
794
+ cliDefines,
795
+ localPersistencePath,
796
+ };
758
797
  }
759
798
 
760
- function ErrorFallback(props: { error: Error }) {
761
- const { exit } = useApp();
762
- useEffect(() => exit(new Error()));
763
- return (
764
- <>
765
- <Text>Something went wrong:</Text>
766
- <Text>{props.error.message}</Text>
767
- </>
768
- );
799
+ function getBindingsAndAssetPaths(args: StartDevOptions, configParam: Config) {
800
+ const cliVars = collectKeyValues(args.var);
801
+
802
+ // now log all available bindings into the terminal
803
+ const bindings = getBindings(configParam, args.env, args.local ?? false, {
804
+ kv: args.kv,
805
+ vars: { ...args.vars, ...cliVars },
806
+ durableObjects: args.durableObjects,
807
+ r2: args.r2,
808
+ d1Databases: args.d1Databases,
809
+ });
810
+
811
+ const maskedVars = maskVars(bindings, configParam);
812
+
813
+ printBindings({
814
+ ...bindings,
815
+ vars: maskedVars,
816
+ });
817
+
818
+ const assetPaths =
819
+ args.assets || configParam.assets
820
+ ? getAssetPaths(configParam, args.assets)
821
+ : getSiteAssetPaths(
822
+ configParam,
823
+ args.site,
824
+ args.siteInclude,
825
+ args.siteExclude
826
+ );
827
+ return { assetPaths, bindings };
769
828
  }
770
829
 
771
- export default withErrorBoundary(Dev, { FallbackComponent: ErrorFallback });
830
+ function getBindings(
831
+ configParam: Config,
832
+ env: string | undefined,
833
+ local: boolean,
834
+ args: AdditionalDevProps
835
+ ): CfWorkerInit["bindings"] {
836
+ const bindings = {
837
+ kv_namespaces: [
838
+ ...(configParam.kv_namespaces || []).map(
839
+ ({ binding, preview_id, id: _id }) => {
840
+ // In `dev`, we make folks use a separate kv namespace called
841
+ // `preview_id` instead of `id` so that they don't
842
+ // break production data. So here we check that a `preview_id`
843
+ // has actually been configured.
844
+ // This whole block of code will be obsoleted in the future
845
+ // when we have copy-on-write for previews on edge workers.
846
+ if (!preview_id) {
847
+ // TODO: This error has to be a _lot_ better, ideally just asking
848
+ // to create a preview namespace for the user automatically
849
+ throw new Error(
850
+ `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
851
+ ); // Ugh, I really don't like this message very much
852
+ }
853
+ return {
854
+ binding,
855
+ id: preview_id,
856
+ };
857
+ }
858
+ ),
859
+ ...(args.kv || []),
860
+ ],
861
+ send_email: configParam.send_email,
862
+ // Use a copy of combinedVars since we're modifying it later
863
+ vars: {
864
+ ...getVarsForDev(configParam, env),
865
+ ...args.vars,
866
+ },
867
+ wasm_modules: configParam.wasm_modules,
868
+ text_blobs: configParam.text_blobs,
869
+ browser: configParam.browser,
870
+ data_blobs: configParam.data_blobs,
871
+ durable_objects: {
872
+ bindings: [
873
+ ...(configParam.durable_objects || { bindings: [] }).bindings,
874
+ ...(args.durableObjects || []),
875
+ ],
876
+ },
877
+ queues: [
878
+ ...(configParam.queues.producers || []).map((queue) => {
879
+ return { binding: queue.binding, queue_name: queue.queue };
880
+ }),
881
+ ],
882
+ r2_buckets: [
883
+ ...(configParam.r2_buckets?.map(
884
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
885
+ // same idea as kv namespace preview id,
886
+ // same copy-on-write TODO
887
+ if (!preview_bucket_name) {
888
+ throw new Error(
889
+ `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
890
+ );
891
+ }
892
+ return {
893
+ binding,
894
+ bucket_name: preview_bucket_name,
895
+ };
896
+ }
897
+ ) || []),
898
+ ...(args.r2 || []),
899
+ ],
900
+ dispatch_namespaces: configParam.dispatch_namespaces,
901
+ mtls_certificates: configParam.mtls_certificates,
902
+ services: configParam.services,
903
+ analytics_engine_datasets: configParam.analytics_engine_datasets,
904
+ unsafe: {
905
+ bindings: configParam.unsafe.bindings,
906
+ metadata: configParam.unsafe.metadata,
907
+ },
908
+ logfwdr: configParam.logfwdr,
909
+ d1_databases: identifyD1BindingsAsBeta([
910
+ ...(configParam.d1_databases ?? []).map((d1Db) => {
911
+ //in local dev, bindings don't matter
912
+ if (local) {
913
+ return {
914
+ ...d1Db,
915
+ database_id: "local",
916
+ };
917
+ }
918
+ // if you have a preview_database_id, we'll use it, but we shouldn't force people to use it.
919
+ if (!d1Db.preview_database_id && !process.env.NO_D1_WARNING) {
920
+ logger.log(
921
+ `--------------------\nšŸ’” Recommendation: for development, use a preview D1 database rather than the one you'd use in production.\nšŸ’” Create a new D1 database with "wrangler d1 create <name>" and add its id as preview_database_id to the d1_database "${d1Db.binding}" in your wrangler.toml\n--------------------\n`
922
+ );
923
+ }
924
+ return {
925
+ ...d1Db,
926
+ database_id: d1Db.preview_database_id
927
+ ? d1Db.preview_database_id
928
+ : d1Db.database_id,
929
+ };
930
+ }),
931
+ ...(args.d1Databases || []),
932
+ ]),
933
+ constellation: configParam.constellation,
934
+ };
935
+
936
+ return bindings;
937
+ }