wrangler 0.0.0-e452a35 → 0.0.0-e4ca780f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/README.md +24 -4
  2. package/bin/wrangler.js +170 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1590 -81
  5. package/package.json +198 -152
  6. package/src/__tests__/access.test.ts +25 -0
  7. package/src/__tests__/api-dev.test.ts +238 -0
  8. package/src/__tests__/api-devregistry.test.ts +121 -0
  9. package/src/__tests__/api.test.ts +102 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +4498 -3321
  13. package/src/__tests__/d1/d1.test.ts +82 -0
  14. package/src/__tests__/d1/execute.test.ts +66 -0
  15. package/src/__tests__/d1/migrate.test.ts +157 -0
  16. package/src/__tests__/d1/splitter.test.ts +255 -0
  17. package/src/__tests__/delete.test.ts +272 -0
  18. package/src/__tests__/deployments.test.ts +369 -0
  19. package/src/__tests__/dev.test.tsx +1592 -874
  20. package/src/__tests__/generate.test.ts +237 -0
  21. package/src/__tests__/get-host-from-url.test.ts +16 -0
  22. package/src/__tests__/guess-worker-format.test.ts +103 -68
  23. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  24. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  25. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  26. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  27. package/src/__tests__/helpers/mock-bin.ts +20 -20
  28. package/src/__tests__/helpers/mock-console.ts +64 -39
  29. package/src/__tests__/helpers/mock-dialogs.ts +104 -55
  30. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  31. package/src/__tests__/helpers/mock-get-zone-from-host.ts +11 -0
  32. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  33. package/src/__tests__/helpers/mock-istty.ts +65 -18
  34. package/src/__tests__/helpers/mock-known-routes.ts +12 -0
  35. package/src/__tests__/helpers/mock-kv.ts +41 -28
  36. package/src/__tests__/helpers/mock-oauth-flow.ts +241 -233
  37. package/src/__tests__/helpers/mock-process.ts +34 -0
  38. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  39. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  40. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  41. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  42. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  43. package/src/__tests__/helpers/msw/handlers/deployments.ts +160 -0
  44. package/src/__tests__/helpers/msw/handlers/namespaces.ts +81 -0
  45. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  46. package/src/__tests__/helpers/msw/handlers/r2.ts +60 -0
  47. package/src/__tests__/helpers/msw/handlers/script.ts +56 -0
  48. package/src/__tests__/helpers/msw/handlers/user.ts +52 -0
  49. package/src/__tests__/helpers/msw/handlers/zones.ts +20 -0
  50. package/src/__tests__/helpers/msw/index.ts +52 -0
  51. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  52. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  53. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  54. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  55. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  56. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  57. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  58. package/src/__tests__/helpers/worker-scripts/parent-worker.js +11 -0
  59. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  60. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  61. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  62. package/src/__tests__/https-options.test.ts +142 -109
  63. package/src/__tests__/index.test.ts +260 -236
  64. package/src/__tests__/init.test.ts +3167 -1528
  65. package/src/__tests__/jest.setup.ts +152 -50
  66. package/src/__tests__/kv.test.ts +1789 -1471
  67. package/src/__tests__/logger.test.ts +167 -75
  68. package/src/__tests__/logout.test.ts +47 -0
  69. package/src/__tests__/metrics.test.ts +493 -0
  70. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  71. package/src/__tests__/middleware.test.ts +816 -0
  72. package/src/__tests__/mtls-certificates.test.ts +588 -0
  73. package/src/__tests__/package-manager.test.ts +312 -165
  74. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  75. package/src/__tests__/pages/functions-build.test.ts +452 -0
  76. package/src/__tests__/pages/pages.test.ts +81 -0
  77. package/src/__tests__/pages/project-create.test.ts +63 -0
  78. package/src/__tests__/pages/project-list.test.ts +110 -0
  79. package/src/__tests__/pages/project-upload.test.ts +500 -0
  80. package/src/__tests__/pages/publish.test.ts +2864 -0
  81. package/src/__tests__/pages-deployment-tail.test.ts +955 -0
  82. package/src/__tests__/parse.test.ts +358 -252
  83. package/src/__tests__/paths.test.ts +39 -0
  84. package/src/__tests__/publish.test.ts +8310 -5355
  85. package/src/__tests__/pubsub.test.ts +496 -0
  86. package/src/__tests__/queues.test.ts +532 -0
  87. package/src/__tests__/r2.test.ts +369 -228
  88. package/src/__tests__/route.test.ts +18 -18
  89. package/src/__tests__/secret.test.ts +681 -469
  90. package/src/__tests__/tail.test.ts +835 -567
  91. package/src/__tests__/test-old-node-version.js +31 -0
  92. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  93. package/src/__tests__/tsconfig-sanity.ts +12 -0
  94. package/src/__tests__/tsconfig.json +8 -0
  95. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  96. package/src/__tests__/type-generation.test.ts +234 -0
  97. package/src/__tests__/user.test.ts +107 -120
  98. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  99. package/src/__tests__/validate-dev-props.test.ts +56 -0
  100. package/src/__tests__/version.test.ts +35 -0
  101. package/src/__tests__/whoami.test.tsx +165 -98
  102. package/src/__tests__/worker-namespace.test.ts +340 -0
  103. package/src/abort.d.ts +1 -1
  104. package/src/api/dev.ts +316 -0
  105. package/src/api/index.ts +11 -0
  106. package/src/api/mtls-certificate.ts +148 -0
  107. package/src/api/pages/create-worker-bundle-contents.ts +76 -0
  108. package/src/api/pages/index.ts +5 -0
  109. package/src/api/pages/publish.tsx +355 -0
  110. package/src/bundle-reporter.ts +68 -0
  111. package/src/bundle.ts +869 -161
  112. package/src/cfetch/index.ts +120 -83
  113. package/src/cfetch/internal.ts +214 -95
  114. package/src/cli.ts +23 -8
  115. package/src/config/config.ts +244 -196
  116. package/src/config/diagnostics.ts +61 -61
  117. package/src/config/environment.ts +555 -357
  118. package/src/config/index.ts +374 -196
  119. package/src/config/validation-helpers.ts +379 -357
  120. package/src/config/validation.ts +2170 -1358
  121. package/src/config-cache.ts +81 -41
  122. package/src/create-worker-preview.ts +250 -142
  123. package/src/create-worker-upload-form.ts +343 -238
  124. package/src/d1/backups.tsx +219 -0
  125. package/src/d1/constants.ts +2 -0
  126. package/src/d1/create.tsx +68 -0
  127. package/src/d1/delete.ts +53 -0
  128. package/src/d1/execute.tsx +357 -0
  129. package/src/d1/formatTimeAgo.ts +14 -0
  130. package/src/d1/index.ts +100 -0
  131. package/src/d1/list.tsx +60 -0
  132. package/src/d1/migrations/apply.tsx +212 -0
  133. package/src/d1/migrations/create.tsx +79 -0
  134. package/src/d1/migrations/helpers.ts +172 -0
  135. package/src/d1/migrations/index.ts +3 -0
  136. package/src/d1/migrations/list.tsx +95 -0
  137. package/src/d1/migrations/options.ts +23 -0
  138. package/src/d1/options.ts +22 -0
  139. package/src/d1/splitter.ts +161 -0
  140. package/src/d1/types.ts +25 -0
  141. package/src/d1/utils.ts +49 -0
  142. package/src/delete.ts +100 -0
  143. package/src/deployments.ts +368 -0
  144. package/src/deprecated/index.ts +144 -0
  145. package/src/dev/dev-vars.ts +20 -17
  146. package/src/dev/dev.tsx +533 -355
  147. package/src/dev/get-local-persistence-path.ts +31 -0
  148. package/src/dev/local.tsx +900 -298
  149. package/src/dev/remote.tsx +620 -215
  150. package/src/dev/start-server.ts +534 -0
  151. package/src/dev/use-esbuild.ts +182 -97
  152. package/src/dev/validate-dev-props.ts +40 -0
  153. package/src/dev-registry.ts +202 -0
  154. package/src/dev.tsx +929 -0
  155. package/src/dialogs.ts +136 -0
  156. package/src/dispatch-namespace.ts +211 -0
  157. package/src/docs/index.ts +97 -0
  158. package/src/durable.ts +87 -87
  159. package/src/entry.ts +246 -231
  160. package/src/environment-variables/factory.ts +88 -0
  161. package/src/environment-variables/misc-variables.ts +30 -0
  162. package/src/errors.ts +6 -6
  163. package/src/generate/index.ts +298 -0
  164. package/src/git-client.ts +135 -0
  165. package/src/global-wrangler-config-path.ts +26 -0
  166. package/src/https-options.ts +84 -80
  167. package/src/index.ts +758 -0
  168. package/src/init.ts +1032 -0
  169. package/src/inspect.ts +713 -593
  170. package/src/intl-polyfill.d.ts +123 -123
  171. package/src/is-ci.ts +14 -0
  172. package/src/is-interactive.ts +16 -0
  173. package/src/jest.d.ts +4 -0
  174. package/src/kv/helpers.ts +430 -0
  175. package/src/kv/index.ts +594 -0
  176. package/src/logger.ts +96 -43
  177. package/src/metrics/index.ts +5 -0
  178. package/src/metrics/metrics-config.ts +239 -0
  179. package/src/metrics/metrics-dispatcher.ts +96 -0
  180. package/src/metrics/metrics-usage-headers.ts +24 -0
  181. package/src/metrics/send-event.ts +99 -0
  182. package/src/miniflare-cli/assets.ts +251 -0
  183. package/src/miniflare-cli/index.ts +202 -33
  184. package/src/miniflare-cli/request-context.ts +18 -18
  185. package/src/miniflare-cli/tsconfig.json +9 -0
  186. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  187. package/src/miniflare-cli/types.ts +11 -0
  188. package/src/module-collection.ts +290 -215
  189. package/src/mtls-certificate/cli.ts +155 -0
  190. package/src/open-in-browser.ts +4 -6
  191. package/src/package-manager.ts +182 -90
  192. package/src/pages/build.ts +410 -0
  193. package/src/pages/buildFunctions.ts +140 -0
  194. package/src/pages/constants.ts +18 -0
  195. package/src/pages/deployment-tails.ts +281 -0
  196. package/src/pages/deployments.tsx +84 -0
  197. package/src/pages/dev.ts +716 -0
  198. package/src/pages/errors.ts +67 -0
  199. package/src/pages/functions/buildPlugin.ts +113 -0
  200. package/src/pages/functions/buildWorker.ts +291 -0
  201. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  202. package/src/pages/functions/filepath-routing.ts +189 -0
  203. package/src/pages/functions/identifiers.ts +78 -0
  204. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  205. package/src/pages/functions/routes-consolidation.ts +73 -0
  206. package/src/pages/functions/routes-transformation.test.ts +282 -0
  207. package/src/pages/functions/routes-transformation.ts +115 -0
  208. package/src/pages/functions/routes-validation.test.ts +403 -0
  209. package/src/pages/functions/routes-validation.ts +202 -0
  210. package/src/pages/functions/routes.ts +151 -0
  211. package/src/pages/functions/tsconfig.json +8 -0
  212. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  213. package/src/pages/functions.ts +86 -0
  214. package/src/pages/hash.ts +13 -0
  215. package/src/pages/index.ts +102 -0
  216. package/src/pages/projects.tsx +159 -0
  217. package/src/pages/prompt-select-project.tsx +31 -0
  218. package/src/pages/publish.tsx +267 -0
  219. package/src/pages/types.ts +46 -0
  220. package/src/pages/upload.tsx +469 -0
  221. package/src/pages/utils.ts +23 -0
  222. package/src/parse.ts +232 -126
  223. package/src/paths.ts +53 -8
  224. package/src/proxy.ts +623 -394
  225. package/src/publish/index.ts +274 -0
  226. package/src/publish/publish.ts +1060 -0
  227. package/src/pubsub/index.ts +286 -0
  228. package/src/pubsub/pubsub-commands.ts +623 -0
  229. package/src/queues/cli/commands/consumer/add.ts +71 -0
  230. package/src/queues/cli/commands/consumer/index.ts +19 -0
  231. package/src/queues/cli/commands/consumer/remove.ts +31 -0
  232. package/src/queues/cli/commands/create.ts +25 -0
  233. package/src/queues/cli/commands/delete.ts +26 -0
  234. package/src/queues/cli/commands/index.ts +35 -0
  235. package/src/queues/cli/commands/list.ts +25 -0
  236. package/src/queues/client.ts +136 -0
  237. package/src/queues/utils.ts +18 -0
  238. package/src/r2/constants.ts +4 -0
  239. package/src/r2/helpers.ts +132 -0
  240. package/src/r2/index.ts +289 -0
  241. package/src/routes.ts +140 -0
  242. package/src/secret/index.ts +376 -0
  243. package/src/selfsigned.d.ts +23 -23
  244. package/src/sites.ts +372 -0
  245. package/src/tail/createTail.ts +406 -0
  246. package/src/tail/filters.ts +109 -111
  247. package/src/tail/index.ts +208 -296
  248. package/src/tail/printing.ts +101 -46
  249. package/src/traverse-module-graph.ts +53 -0
  250. package/src/tsconfig-sanity.ts +16 -0
  251. package/src/type-generation.ts +181 -0
  252. package/src/update-check.ts +11 -11
  253. package/src/user/access.ts +68 -0
  254. package/src/user/auth-variables.ts +113 -0
  255. package/src/user/choose-account.tsx +39 -0
  256. package/src/user/generate-auth-url.ts +33 -0
  257. package/src/user/generate-random-state.ts +16 -0
  258. package/src/user/index.ts +2 -0
  259. package/src/user/user.ts +1233 -0
  260. package/src/utils/collectKeyValues.ts +14 -0
  261. package/src/utils/render.ts +93 -0
  262. package/src/whoami.ts +135 -0
  263. package/src/worker.ts +200 -106
  264. package/src/yargs-types.ts +37 -0
  265. package/src/zones.ts +191 -0
  266. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  267. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  268. package/templates/__tests__/tsconfig.json +8 -0
  269. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  270. package/templates/checked-fetch.js +23 -0
  271. package/templates/d1-beta-facade.js +244 -0
  272. package/templates/facade.d.ts +14 -0
  273. package/templates/first-party-worker-module-facade.ts +19 -0
  274. package/templates/format-dev-errors.ts +34 -0
  275. package/templates/gitignore +1 -0
  276. package/templates/init-tests/test-jest-new-worker.js +23 -0
  277. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  278. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  279. package/templates/middleware/common.ts +62 -0
  280. package/templates/middleware/loader-modules.ts +84 -0
  281. package/templates/middleware/loader-sw.ts +233 -0
  282. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  283. package/templates/middleware/middleware-pretty-error.ts +40 -0
  284. package/templates/middleware/middleware-scheduled.ts +15 -0
  285. package/templates/new-worker-scheduled.js +17 -0
  286. package/templates/new-worker-scheduled.ts +32 -0
  287. package/templates/new-worker.js +3 -3
  288. package/templates/new-worker.ts +18 -15
  289. package/templates/no-op-worker.js +10 -0
  290. package/templates/pages-dev-pipeline.ts +31 -0
  291. package/templates/pages-dev-util.ts +52 -0
  292. package/templates/pages-shim.ts +12 -0
  293. package/templates/pages-template-plugin.ts +180 -0
  294. package/templates/pages-template-worker.ts +189 -0
  295. package/templates/serve-static-assets.ts +66 -0
  296. package/templates/service-bindings-module-facade.js +55 -0
  297. package/templates/service-bindings-sw-facade.js +42 -0
  298. package/templates/tsconfig-sanity.ts +11 -0
  299. package/templates/tsconfig.init.json +105 -0
  300. package/templates/tsconfig.json +6 -103
  301. package/templates/tsconfig.tsbuildinfo +1 -0
  302. package/wrangler-dist/cli.d.ts +1641 -0
  303. package/wrangler-dist/cli.js +138434 -111674
  304. package/wrangler-dist/wasm-sync.wasm +0 -0
  305. package/pages/functions/buildPlugin.ts +0 -105
  306. package/pages/functions/buildWorker.ts +0 -151
  307. package/pages/functions/filepath-routing.ts +0 -189
  308. package/pages/functions/identifiers.ts +0 -78
  309. package/pages/functions/routes.ts +0 -156
  310. package/pages/functions/template-plugin.ts +0 -147
  311. package/pages/functions/template-worker.ts +0 -143
  312. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  313. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  314. package/src/__tests__/pages.test.ts +0 -657
  315. package/src/dialogs.tsx +0 -87
  316. package/src/environment-variables.ts +0 -35
  317. package/src/index.tsx +0 -2789
  318. package/src/kv.ts +0 -408
  319. package/src/miniflare-cli/enum-keys.ts +0 -17
  320. package/src/pages.tsx +0 -2027
  321. package/src/publish.ts +0 -583
  322. package/src/r2.ts +0 -50
  323. package/src/sites.tsx +0 -295
  324. package/src/user.tsx +0 -1203
  325. package/src/whoami.tsx +0 -70
  326. package/templates/static-asset-facade.js +0 -47
  327. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  328. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  329. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  330. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  331. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  332. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  333. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  334. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  335. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  336. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  337. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  338. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  339. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  340. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  341. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  342. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  343. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  344. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  345. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  346. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  347. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  348. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  349. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  350. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  351. package/vendor/wrangler-mime/LICENSE +0 -21
  352. package/vendor/wrangler-mime/Mime.js +0 -97
  353. package/vendor/wrangler-mime/README.md +0 -187
  354. package/vendor/wrangler-mime/cli.js +0 -46
  355. package/vendor/wrangler-mime/index.js +0 -4
  356. package/vendor/wrangler-mime/lite.js +0 -4
  357. package/vendor/wrangler-mime/package.json +0 -52
  358. package/vendor/wrangler-mime/types/other.js +0 -1
  359. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/dev/local.tsx CHANGED
@@ -1,318 +1,920 @@
1
- import { spawn } from "node:child_process";
1
+ import assert from "node:assert";
2
+ import { fork } from "node:child_process";
2
3
  import { realpathSync } from "node:fs";
3
- import { writeFile } from "node:fs/promises";
4
+ import { readFile } from "node:fs/promises";
4
5
  import path from "node:path";
6
+ import chalk from "chalk";
7
+ import getPort from "get-port";
8
+ import { npxImport } from "npx-import";
5
9
  import { useState, useEffect, useRef } from "react";
6
10
  import onExit from "signal-exit";
11
+ import { fetch } from "undici";
12
+ import { performApiFetch } from "../cfetch/internal";
13
+ import { registerWorker } from "../dev-registry";
7
14
  import useInspector from "../inspect";
8
15
  import { logger } from "../logger";
9
- import { DEFAULT_MODULE_RULES } from "../module-collection";
16
+ import {
17
+ DEFAULT_MODULE_RULES,
18
+ ModuleTypeToRuleType,
19
+ } from "../module-collection";
20
+ import { getBasePath } from "../paths";
10
21
  import { waitForPortToBeAvailable } from "../proxy";
22
+ import { requireAuth } from "../user";
11
23
  import type { Config } from "../config";
24
+ import type { WorkerRegistry } from "../dev-registry";
25
+ import type { LoggerLevel } from "../logger";
26
+ import type { EnablePagesAssetsServiceBindingOptions } from "../miniflare-cli/types";
12
27
  import type { AssetPaths } from "../sites";
13
- import type { CfWorkerInit, CfScriptFormat } from "../worker";
28
+ import type {
29
+ CfWorkerInit,
30
+ CfScriptFormat,
31
+ CfWasmModuleBindings,
32
+ CfTextBlobBindings,
33
+ CfDataBlobBindings,
34
+ CfDurableObject,
35
+ CfKvNamespace,
36
+ CfR2Bucket,
37
+ CfVars,
38
+ CfQueue,
39
+ CfD1Database,
40
+ } from "../worker";
14
41
  import type { EsbuildBundle } from "./use-esbuild";
42
+ import type {
43
+ Miniflare as Miniflare3Type,
44
+ MiniflareOptions as Miniflare3Options,
45
+ Log as Miniflare3LogType,
46
+ CloudflareFetch,
47
+ } from "@miniflare/tre";
15
48
  import type { MiniflareOptions } from "miniflare";
49
+ import type { ChildProcess } from "node:child_process";
16
50
 
17
- interface LocalProps {
18
- name: string | undefined;
19
- bundle: EsbuildBundle | undefined;
20
- format: CfScriptFormat | undefined;
21
- compatibilityDate: string;
22
- compatibilityFlags: string[] | undefined;
23
- bindings: CfWorkerInit["bindings"];
24
- assetPaths: AssetPaths | undefined;
25
- public: string | undefined;
26
- port: number;
27
- ip: string;
28
- rules: Config["rules"];
29
- inspectorPort: number;
30
- enableLocalPersistence: boolean;
31
- crons: Config["triggers"]["crons"];
51
+ export interface LocalProps {
52
+ name: string | undefined;
53
+ bundle: EsbuildBundle | undefined;
54
+ format: CfScriptFormat | undefined;
55
+ compatibilityDate: string;
56
+ compatibilityFlags: string[] | undefined;
57
+ usageModel: "bundled" | "unbound" | undefined;
58
+ bindings: CfWorkerInit["bindings"];
59
+ workerDefinitions: WorkerRegistry | undefined;
60
+ assetPaths: AssetPaths | undefined;
61
+ initialPort: number;
62
+ initialIp: string;
63
+ rules: Config["rules"];
64
+ inspectorPort: number;
65
+ localPersistencePath: string | null;
66
+ liveReload: boolean;
67
+ crons: Config["triggers"]["crons"];
68
+ queueConsumers: Config["queues"]["consumers"];
69
+ localProtocol: "http" | "https";
70
+ localUpstream: string | undefined;
71
+ inspect: boolean;
72
+ onReady: ((ip: string, port: number) => void) | undefined;
73
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
74
+ testScheduled?: boolean;
75
+ experimentalLocal: boolean | undefined;
76
+ accountId: string | undefined; // Account ID? In local mode??? :exploding_head:
77
+ experimentalLocalRemoteKv: boolean | undefined;
32
78
  }
33
79
 
80
+ type InspectorJSON = {
81
+ id: string;
82
+ title: string;
83
+ type: "node";
84
+ description: string;
85
+ webSocketDebuggerUrl: string;
86
+ devtoolsFrontendUrl: string;
87
+ devtoolsFrontendUrlCompat: string;
88
+ faviconUrl: string;
89
+ url: string;
90
+ }[];
91
+
34
92
  export function Local(props: LocalProps) {
35
- const { inspectorUrl } = useLocalWorker(props);
36
- useInspector({
37
- inspectorUrl,
38
- port: props.inspectorPort,
39
- logToTerminal: false,
40
- });
41
- return null;
93
+ const { inspectorUrl } = useLocalWorker(props);
94
+ useInspector({
95
+ inspectorUrl,
96
+ port: props.inspectorPort,
97
+ logToTerminal: props.experimentalLocal ?? false,
98
+ });
99
+ return null;
42
100
  }
43
101
 
44
102
  function useLocalWorker({
45
- name: workerName,
46
- bundle,
47
- format,
48
- compatibilityDate,
49
- compatibilityFlags,
50
- bindings,
51
- assetPaths,
52
- public: publicDirectory,
53
- port,
54
- rules,
55
- enableLocalPersistence,
56
- ip,
57
- crons,
103
+ name: workerName,
104
+ bundle,
105
+ format,
106
+ compatibilityDate,
107
+ compatibilityFlags,
108
+ usageModel,
109
+ bindings,
110
+ workerDefinitions,
111
+ assetPaths,
112
+ initialPort,
113
+ rules,
114
+ localPersistencePath,
115
+ liveReload,
116
+ initialIp,
117
+ crons,
118
+ queueConsumers,
119
+ localProtocol,
120
+ localUpstream,
121
+ inspect,
122
+ onReady,
123
+ enablePagesAssetsServiceBinding,
124
+ experimentalLocal,
125
+ accountId,
126
+ experimentalLocalRemoteKv,
58
127
  }: LocalProps) {
59
- // TODO: pass vars via command line
60
- const local = useRef<ReturnType<typeof spawn>>();
61
- const removeSignalExitListener = useRef<() => void>();
62
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
63
- // if we're using local persistence for data, we should use the cwd
64
- // as an explicit path, or else it'll use the temp dir
65
- // which disappears when dev ends
66
- const localPersistencePath = enableLocalPersistence
67
- ? // Maybe we could make the path configurable as well?
68
- path.join(process.cwd(), "wrangler-local-state")
69
- : // We otherwise choose null, but choose true later
70
- // so that it's persisted in the temp dir across a dev session
71
- // even when we change source and reload
72
- null;
73
- useEffect(() => {
74
- const abortController = new AbortController();
75
- async function startLocalWorker() {
76
- if (!bundle || !format) return;
77
-
78
- // port for the worker
79
- await waitForPortToBeAvailable(port, {
80
- retryPeriod: 200,
81
- timeout: 2000,
82
- abortSignal: abortController.signal,
83
- });
84
-
85
- if (publicDirectory) {
86
- throw new Error(
87
- '⎔ A "public" folder is not yet supported in local mode.'
88
- );
89
- }
90
- if (bindings.services && bindings.services.length > 0) {
91
- throw new Error(
92
- "⎔ Service bindings are not yet supported in local mode."
93
- );
94
- }
95
-
96
- // In local mode, we want to copy all referenced modules into
97
- // the output bundle directory before starting up
98
- for (const module of bundle.modules) {
99
- await writeFile(
100
- path.join(path.dirname(bundle.path), module.name),
101
- module.content
102
- );
103
- }
104
-
105
- const scriptPath = realpathSync(bundle.path);
106
-
107
- // the wasm_modules/text_blobs/data_blobs bindings are
108
- // relative to process.cwd(), but the actual worker bundle
109
- // is in the temp output directory; so we rewrite the paths to be absolute,
110
- // letting miniflare resolve them correctly
111
-
112
- // wasm
113
- const wasmBindings: Record<string, string> = {};
114
- for (const [name, filePath] of Object.entries(
115
- bindings.wasm_modules || {}
116
- )) {
117
- wasmBindings[name] = path.join(process.cwd(), filePath);
118
- }
119
-
120
- // text
121
- const textBlobBindings: Record<string, string> = {};
122
- for (const [name, filePath] of Object.entries(
123
- bindings.text_blobs || {}
124
- )) {
125
- textBlobBindings[name] = path.join(process.cwd(), filePath);
126
- }
127
-
128
- // data
129
- const dataBlobBindings: Record<string, string> = {};
130
- for (const [name, filePath] of Object.entries(
131
- bindings.data_blobs || {}
132
- )) {
133
- dataBlobBindings[name] = path.join(process.cwd(), filePath);
134
- }
135
-
136
- if (format === "service-worker") {
137
- for (const { type, name } of bundle.modules) {
138
- if (type === "compiled-wasm") {
139
- // In service-worker format, .wasm modules are referenced by global identifiers,
140
- // so we convert it here.
141
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
142
- // characters with an underscore.
143
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
144
- wasmBindings[identifier] = name;
145
- } else if (type === "text") {
146
- // In service-worker format, text modules are referenced by global identifiers,
147
- // so we convert it here.
148
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
149
- // characters with an underscore.
150
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
151
- textBlobBindings[identifier] = name;
152
- } else if (type === "buffer") {
153
- // In service-worker format, data blobs are referenced by global identifiers,
154
- // so we convert it here.
155
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
156
- // characters with an underscore.
157
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
158
- dataBlobBindings[identifier] = name;
159
- }
160
- }
161
- }
162
-
163
- const options: MiniflareOptions = {
164
- name: workerName,
165
- port,
166
- scriptPath,
167
- host: ip,
168
- modules: format === "modules",
169
- modulesRules: (rules || [])
170
- .concat(DEFAULT_MODULE_RULES)
171
- .map(({ type, globs: include, fallthrough }) => ({
172
- type,
173
- include,
174
- fallthrough,
175
- })),
176
- compatibilityDate,
177
- compatibilityFlags,
178
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
179
- durableObjects: Object.fromEntries(
180
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
181
- (value) => [value.name, value.class_name]
182
- )
183
- ),
184
- ...(localPersistencePath
185
- ? {
186
- kvPersist: path.join(localPersistencePath, "kv"),
187
- durableObjectsPersist: path.join(localPersistencePath, "do"),
188
- cachePersist: path.join(localPersistencePath, "cache"),
189
- }
190
- : {
191
- // We mark these as true, so that they'll
192
- // persist in the temp directory.
193
- // This means they'll persist across a dev session,
194
- // even if we change source and reload,
195
- // and be deleted when the dev session ends
196
- durableObjectsPersist: true,
197
- cachePersist: true,
198
- kvPersist: true,
199
- }),
200
-
201
- sitePath: assetPaths?.assetDirectory
202
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
203
- : undefined,
204
- siteInclude: assetPaths?.includePatterns.length
205
- ? assetPaths?.includePatterns
206
- : undefined,
207
- siteExclude: assetPaths?.excludePatterns.length
208
- ? assetPaths.excludePatterns
209
- : undefined,
210
- bindings: bindings.vars,
211
- wasmBindings,
212
- textBlobBindings,
213
- dataBlobBindings,
214
- sourceMap: true,
215
- logUnhandledRejections: true,
216
- crons,
217
- };
218
-
219
- // The path to the Miniflare CLI assumes that this file is being run from
220
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
221
- // If either of those paths change this line needs updating.
222
- const miniflareCLIPath = path.resolve(
223
- __dirname,
224
- "../miniflare-dist/index.mjs"
225
- );
226
- const optionsArg = JSON.stringify(options, null);
227
-
228
- logger.log("⎔ Starting a local server...");
229
- local.current = spawn(
230
- "node",
231
- [
232
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
233
- "--no-warnings", // hide annoying Node warnings
234
- "--inspect", // start Miniflare listening for a debugger to attach
235
- miniflareCLIPath,
236
- optionsArg,
237
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
238
- ],
239
- {
240
- cwd: path.dirname(scriptPath),
241
- }
242
- );
243
-
244
- local.current.on("close", (code) => {
245
- if (code) {
246
- logger.log(`Miniflare process exited with code ${code}`);
247
- }
248
- });
249
-
250
- local.current.stdout?.on("data", (data: Buffer) => {
251
- process.stdout.write(data);
252
- });
253
-
254
- local.current.stderr?.on("data", (data: Buffer) => {
255
- const matches =
256
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
257
- data.toString()
258
- );
259
- if (matches) {
260
- setInspectorUrl(matches[1]);
261
- }
262
- });
263
-
264
- local.current.on("exit", (code) => {
265
- if (code) {
266
- logger.error(`Miniflare process exited with code ${code}`);
267
- }
268
- });
269
-
270
- local.current.on("error", (error: Error) => {
271
- logger.error(`Miniflare process failed to spawn`);
272
- logger.error(error);
273
- });
274
-
275
- removeSignalExitListener.current = onExit((_code, _signal) => {
276
- logger.log("⎔ Shutting down local server.");
277
- local.current?.kill();
278
- local.current = undefined;
279
- });
280
- }
281
-
282
- startLocalWorker().catch((err) => {
283
- logger.error("local worker:", err);
284
- });
285
-
286
- return () => {
287
- abortController.abort();
288
- if (local.current) {
289
- logger.log("⎔ Shutting down local server.");
290
- local.current?.kill();
291
- local.current = undefined;
292
- removeSignalExitListener.current && removeSignalExitListener.current();
293
- removeSignalExitListener.current = undefined;
294
- }
295
- };
296
- }, [
297
- bundle,
298
- workerName,
299
- format,
300
- port,
301
- ip,
302
- bindings.durable_objects?.bindings,
303
- bindings.kv_namespaces,
304
- bindings.vars,
305
- bindings.services,
306
- compatibilityDate,
307
- compatibilityFlags,
308
- localPersistencePath,
309
- assetPaths,
310
- publicDirectory,
311
- rules,
312
- bindings.wasm_modules,
313
- bindings.text_blobs,
314
- bindings.data_blobs,
315
- crons,
316
- ]);
317
- return { inspectorUrl };
128
+ // TODO: pass vars via command line
129
+ const local = useRef<ChildProcess>();
130
+ const experimentalLocalRef = useRef<Miniflare3Type>();
131
+ const removeSignalExitListener = useRef<() => void>();
132
+ const removeExperimentalLocalSignalExitListener = useRef<() => void>();
133
+ const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
134
+
135
+ // Our inspector proxy server will be binding to `LocalProps`'s `inspectorPort`.
136
+ // If we attempted to bind Node.js/workerd to the same inspector port, we'd get a port already in use error.
137
+ // Therefore, generate a new random port for our runtime's to bind their inspector service to.
138
+ const runtimeInspectorPortRef = useRef<number>();
139
+
140
+ useEffect(() => {
141
+ if (bindings.services && bindings.services.length > 0) {
142
+ logger.warn(
143
+ "⎔ Support for service bindings in local mode is experimental and may change."
144
+ );
145
+ }
146
+ }, [bindings.services]);
147
+
148
+ useEffect(() => {
149
+ const externalDurableObjects = (
150
+ bindings.durable_objects?.bindings || []
151
+ ).filter((binding) => binding.script_name);
152
+
153
+ if (externalDurableObjects.length > 0) {
154
+ logger.warn(
155
+ "⎔ Support for external Durable Objects in local mode is experimental and may change."
156
+ );
157
+ }
158
+ }, [bindings.durable_objects?.bindings]);
159
+
160
+ useEffect(() => {
161
+ const abortController = new AbortController();
162
+ async function startLocalWorker() {
163
+ if (!bundle || !format) return;
164
+
165
+ const scriptPath = realpathSync(bundle.path);
166
+
167
+ const upstream =
168
+ typeof localUpstream === "string"
169
+ ? `${localProtocol}://${localUpstream}`
170
+ : undefined;
171
+
172
+ const {
173
+ externalDurableObjects,
174
+ internalDurableObjects,
175
+ wasmBindings,
176
+ textBlobBindings,
177
+ dataBlobBindings,
178
+ } = setupBindings({
179
+ wasm_modules: bindings.wasm_modules,
180
+ text_blobs: bindings.text_blobs,
181
+ data_blobs: bindings.data_blobs,
182
+ durable_objects: bindings.durable_objects,
183
+ format,
184
+ bundle,
185
+ });
186
+
187
+ runtimeInspectorPortRef.current ??= await getPort();
188
+ const runtimeInspectorPort = runtimeInspectorPortRef.current;
189
+
190
+ const { forkOptions, miniflareCLIPath, options } = setupMiniflareOptions({
191
+ workerName,
192
+ port: initialPort,
193
+ scriptPath,
194
+ localProtocol,
195
+ ip: initialIp,
196
+ format,
197
+ rules,
198
+ compatibilityDate,
199
+ compatibilityFlags,
200
+ usageModel,
201
+ kv_namespaces: bindings?.kv_namespaces,
202
+ r2_buckets: bindings?.r2_buckets,
203
+ queueBindings: bindings?.queues,
204
+ queueConsumers: queueConsumers,
205
+ d1_databases: bindings?.d1_databases,
206
+ internalDurableObjects,
207
+ externalDurableObjects,
208
+ localPersistencePath,
209
+ liveReload,
210
+ assetPaths,
211
+ vars: bindings?.vars,
212
+ wasmBindings,
213
+ textBlobBindings,
214
+ dataBlobBindings,
215
+ crons,
216
+ upstream,
217
+ workerDefinitions,
218
+ enablePagesAssetsServiceBinding,
219
+ });
220
+
221
+ if (experimentalLocal) {
222
+ const log = await buildMiniflare3Logger();
223
+ const mf3Options = await transformMf2OptionsToMf3Options({
224
+ miniflare2Options: options,
225
+ format,
226
+ bundle,
227
+ log,
228
+ enablePagesAssetsServiceBinding,
229
+ kvNamespaces: bindings?.kv_namespaces,
230
+ r2Buckets: bindings?.r2_buckets,
231
+ d1Databases: bindings?.d1_databases,
232
+ authenticatedAccountId: accountId,
233
+ kvRemote: experimentalLocalRemoteKv,
234
+ inspectorPort: runtimeInspectorPort,
235
+ });
236
+
237
+ const current = experimentalLocalRef.current;
238
+
239
+ if (current === undefined) {
240
+ // If we don't have an active Miniflare instance, create a new one
241
+ const { Miniflare } = await getMiniflare3();
242
+ if (abortController.signal.aborted) return;
243
+ const mf = new Miniflare(mf3Options);
244
+ experimentalLocalRef.current = mf;
245
+ removeExperimentalLocalSignalExitListener.current = onExit(() => {
246
+ logger.log("⎔ Shutting down experimental local server.");
247
+ void mf.dispose();
248
+ experimentalLocalRef.current = undefined;
249
+ });
250
+ await mf.ready;
251
+ } else {
252
+ // Otherwise, reuse the existing instance with its loopback server
253
+ // and just update the options
254
+ if (abortController.signal.aborted) return;
255
+ logger.log("⎔ Reloading experimental local server.");
256
+ await current.setOptions(mf3Options);
257
+ }
258
+
259
+ try {
260
+ // fetch the inspector JSON response from the DevTools Inspector protocol
261
+ const inspectorJSONArr = (await (
262
+ await fetch(`http://127.0.0.1:${runtimeInspectorPort}/json`)
263
+ ).json()) as InspectorJSON;
264
+
265
+ const foundInspectorURL = inspectorJSONArr?.find((inspectorJSON) =>
266
+ inspectorJSON.id.startsWith("core:user")
267
+ )?.webSocketDebuggerUrl;
268
+ if (foundInspectorURL === undefined) {
269
+ setInspectorUrl(undefined);
270
+ } else {
271
+ const url = new URL(foundInspectorURL);
272
+ // Force inspector URL to be different on each reload so `useEffect`
273
+ // in `useInspector` is re-run to connect to newly restarted
274
+ // `workerd` server when updating options. Can't use a query param
275
+ // here as that seems to cause an infinite connection loop, can't
276
+ // use a hash as those are forbidden by `ws`, so username it is.
277
+ url.username = `${Date.now()}-${Math.floor(
278
+ Math.random() * Number.MAX_SAFE_INTEGER
279
+ )}`;
280
+ setInspectorUrl(url.toString());
281
+ }
282
+ } catch (error: unknown) {
283
+ logger.error("Error attempting to retrieve Debugger URL:", error);
284
+ }
285
+
286
+ return;
287
+ }
288
+
289
+ // Wait for the Worker port to be available. We don't want to do this in experimental local
290
+ // mode, as we only `dispose()` the Miniflare 3 instance, and shutdown the server when
291
+ // unmounting the component, not when props change. If we did, we'd just timeout every time.
292
+ await waitForPortToBeAvailable(initialPort, {
293
+ retryPeriod: 200,
294
+ timeout: 2000,
295
+ abortSignal: abortController.signal,
296
+ });
297
+
298
+ const nodeOptions = setupNodeOptions({
299
+ inspect,
300
+ inspectorPort: runtimeInspectorPort,
301
+ });
302
+ logger.log("⎔ Starting a local server...");
303
+
304
+ const hasColourSupport =
305
+ chalk.supportsColor.hasBasic && process.env.FORCE_COLOR !== "0";
306
+ const child = (local.current = fork(miniflareCLIPath, forkOptions, {
307
+ cwd: path.dirname(scriptPath),
308
+ execArgv: nodeOptions,
309
+ stdio: "pipe",
310
+ env: {
311
+ ...process.env,
312
+ FORCE_COLOR: hasColourSupport ? "1" : undefined,
313
+ },
314
+ }));
315
+
316
+ child.on("message", async (messageString) => {
317
+ const message = JSON.parse(messageString as string);
318
+ if (message.ready) {
319
+ // Let's register our presence in the dev registry
320
+ if (workerName) {
321
+ await registerWorker(workerName, {
322
+ protocol: localProtocol,
323
+ mode: "local",
324
+ port: message.port,
325
+ host: initialIp,
326
+ durableObjects: internalDurableObjects.map((binding) => ({
327
+ name: binding.name,
328
+ className: binding.class_name,
329
+ })),
330
+ ...(message.durableObjectsPort
331
+ ? {
332
+ durableObjectsHost: initialIp,
333
+ durableObjectsPort: message.durableObjectsPort,
334
+ }
335
+ : {}),
336
+ });
337
+ }
338
+ onReady?.(initialIp, message.port);
339
+ }
340
+ });
341
+
342
+ child.on("close", (code) => {
343
+ if (code) {
344
+ logger.log(`Miniflare process exited with code ${code}`);
345
+ }
346
+ });
347
+
348
+ child.stdout?.on("data", (data: Buffer) => {
349
+ process.stdout.write(data);
350
+ });
351
+
352
+ // parse the node inspector url (which may be received in chunks) from stderr
353
+ let stderrData = "";
354
+ let inspectorUrlFound = false;
355
+ child.stderr?.on("data", (data: Buffer) => {
356
+ if (!inspectorUrlFound) {
357
+ stderrData += data.toString();
358
+ const matches =
359
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)[\r|\n]/.exec(
360
+ stderrData
361
+ );
362
+ if (matches) {
363
+ inspectorUrlFound = true;
364
+ setInspectorUrl(matches[1]);
365
+ }
366
+ }
367
+
368
+ process.stderr.write(data);
369
+ });
370
+
371
+ child.on("exit", (code) => {
372
+ if (code) {
373
+ logger.error(`Miniflare process exited with code ${code}`);
374
+ }
375
+ });
376
+
377
+ child.on("error", (error: Error) => {
378
+ logger.error(`Miniflare process failed to spawn`);
379
+ logger.error(error);
380
+ });
381
+
382
+ removeSignalExitListener.current = onExit((_code, _signal) => {
383
+ logger.log("⎔ Shutting down local server.");
384
+ child.kill();
385
+ local.current = undefined;
386
+ });
387
+ }
388
+
389
+ startLocalWorker().catch((err) => {
390
+ if (err.code === "ERR_RUNTIME_FAILURE") {
391
+ // Don't log a full verbose stack-trace when Miniflare 3's workerd instance fails to start.
392
+ // workerd will log its own errors, and our stack trace won't have any useful information.
393
+ logger.error(err.message);
394
+ } else {
395
+ logger.error("local worker:", err);
396
+ }
397
+ });
398
+
399
+ return () => {
400
+ abortController.abort();
401
+ if (local.current) {
402
+ logger.log("⎔ Shutting down local server.");
403
+ local.current?.kill();
404
+ local.current = undefined;
405
+ }
406
+ removeSignalExitListener.current?.();
407
+ removeSignalExitListener.current = undefined;
408
+ };
409
+ }, [
410
+ bundle,
411
+ workerName,
412
+ format,
413
+ initialPort,
414
+ initialIp,
415
+ queueConsumers,
416
+ bindings.queues,
417
+ bindings.durable_objects,
418
+ bindings.kv_namespaces,
419
+ bindings.r2_buckets,
420
+ bindings.d1_databases,
421
+ bindings.vars,
422
+ bindings.services,
423
+ workerDefinitions,
424
+ compatibilityDate,
425
+ compatibilityFlags,
426
+ usageModel,
427
+ localPersistencePath,
428
+ liveReload,
429
+ assetPaths,
430
+ rules,
431
+ bindings.wasm_modules,
432
+ bindings.text_blobs,
433
+ bindings.data_blobs,
434
+ crons,
435
+ localProtocol,
436
+ localUpstream,
437
+ inspect,
438
+ onReady,
439
+ enablePagesAssetsServiceBinding,
440
+ experimentalLocal,
441
+ accountId,
442
+ experimentalLocalRemoteKv,
443
+ ]);
444
+
445
+ // Rather than disposing the Miniflare instance on every reload, only dispose
446
+ // it if local mode is disabled and the `Local` component is unmounted. This
447
+ // allows us to use the more efficient `Miniflare#setOptions` on reload which
448
+ // retains internal state (e.g. the Miniflare loopback server).
449
+ useEffect(
450
+ () => () => {
451
+ if (experimentalLocalRef.current) {
452
+ logger.log("⎔ Shutting down experimental local server.");
453
+ // Initialisation errors are also thrown asynchronously by dispose().
454
+ // The catch() above should've caught them though.
455
+ experimentalLocalRef.current?.dispose().catch(() => {});
456
+ experimentalLocalRef.current = undefined;
457
+ }
458
+ removeExperimentalLocalSignalExitListener.current?.();
459
+ removeExperimentalLocalSignalExitListener.current = undefined;
460
+ },
461
+ []
462
+ );
463
+
464
+ return { inspectorUrl };
465
+ }
466
+
467
+ interface SetupBindingsProps {
468
+ wasm_modules: CfWasmModuleBindings | undefined;
469
+ text_blobs: CfTextBlobBindings | undefined;
470
+ data_blobs: CfDataBlobBindings | undefined;
471
+ durable_objects: { bindings: CfDurableObject[] } | undefined;
472
+ bundle: EsbuildBundle;
473
+ format: CfScriptFormat;
474
+ }
475
+
476
+ export function setupBindings({
477
+ wasm_modules,
478
+ text_blobs,
479
+ data_blobs,
480
+ durable_objects,
481
+ format,
482
+ bundle,
483
+ }: SetupBindingsProps) {
484
+ // the wasm_modules/text_blobs/data_blobs bindings are
485
+ // relative to process.cwd(), but the actual worker bundle
486
+ // is in the temp output directory; so we rewrite the paths to be absolute,
487
+ // letting miniflare resolve them correctly
488
+
489
+ // wasm
490
+ const wasmBindings: Record<string, string> = {};
491
+ for (const [name, filePath] of Object.entries(wasm_modules || {})) {
492
+ wasmBindings[name] = path.join(process.cwd(), filePath);
493
+ }
494
+
495
+ // text
496
+ const textBlobBindings: Record<string, string> = {};
497
+ for (const [name, filePath] of Object.entries(text_blobs || {})) {
498
+ textBlobBindings[name] = path.join(process.cwd(), filePath);
499
+ }
500
+
501
+ // data
502
+ const dataBlobBindings: Record<string, string> = {};
503
+ for (const [name, filePath] of Object.entries(data_blobs || {})) {
504
+ dataBlobBindings[name] = path.join(process.cwd(), filePath);
505
+ }
506
+
507
+ if (format === "service-worker") {
508
+ for (const { type, name } of bundle.modules) {
509
+ if (type === "compiled-wasm") {
510
+ // In service-worker format, .wasm modules are referenced by global identifiers,
511
+ // so we convert it here.
512
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
513
+ // characters with an underscore.
514
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
515
+ wasmBindings[identifier] = name;
516
+ } else if (type === "text") {
517
+ // In service-worker format, text modules are referenced by global identifiers,
518
+ // so we convert it here.
519
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
520
+ // characters with an underscore.
521
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
522
+ textBlobBindings[identifier] = name;
523
+ } else if (type === "buffer") {
524
+ // In service-worker format, data blobs are referenced by global identifiers,
525
+ // so we convert it here.
526
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
527
+ // characters with an underscore.
528
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
529
+ dataBlobBindings[identifier] = name;
530
+ }
531
+ }
532
+ }
533
+
534
+ const internalDurableObjects = (durable_objects?.bindings || []).filter(
535
+ (binding) => !binding.script_name
536
+ );
537
+ const externalDurableObjects = (durable_objects?.bindings || []).filter(
538
+ (binding) => binding.script_name
539
+ );
540
+ return {
541
+ internalDurableObjects,
542
+ externalDurableObjects,
543
+ wasmBindings,
544
+ textBlobBindings,
545
+ dataBlobBindings,
546
+ };
547
+ }
548
+
549
+ interface SetupMiniflareOptionsProps {
550
+ workerName: string | undefined;
551
+ port: number;
552
+ scriptPath: string;
553
+ localProtocol: "http" | "https";
554
+ ip: string;
555
+ format: CfScriptFormat;
556
+ rules: Config["rules"];
557
+ compatibilityDate: string;
558
+ compatibilityFlags: string[] | undefined;
559
+ usageModel: "bundled" | "unbound" | undefined;
560
+ kv_namespaces: CfKvNamespace[] | undefined;
561
+ queueBindings: CfQueue[] | undefined;
562
+ queueConsumers: Config["queues"]["consumers"];
563
+ r2_buckets: CfR2Bucket[] | undefined;
564
+ d1_databases: CfD1Database[] | undefined;
565
+ internalDurableObjects: CfDurableObject[];
566
+ externalDurableObjects: CfDurableObject[];
567
+ localPersistencePath: string | null;
568
+ liveReload: boolean;
569
+ assetPaths: AssetPaths | undefined;
570
+ vars: CfVars | undefined;
571
+ wasmBindings: Record<string, string>;
572
+ textBlobBindings: Record<string, string>;
573
+ dataBlobBindings: Record<string, string>;
574
+ crons: Config["triggers"]["crons"];
575
+ upstream: string | undefined;
576
+ workerDefinitions: WorkerRegistry | undefined;
577
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
578
+ }
579
+
580
+ export function setupMiniflareOptions({
581
+ workerName,
582
+ port,
583
+ scriptPath,
584
+ localProtocol,
585
+ ip,
586
+ format,
587
+ rules,
588
+ compatibilityDate,
589
+ compatibilityFlags,
590
+ usageModel,
591
+ kv_namespaces,
592
+ queueBindings,
593
+ queueConsumers,
594
+ r2_buckets,
595
+ d1_databases,
596
+ internalDurableObjects,
597
+ externalDurableObjects,
598
+ localPersistencePath,
599
+ liveReload,
600
+ assetPaths,
601
+ vars,
602
+ wasmBindings,
603
+ textBlobBindings,
604
+ dataBlobBindings,
605
+ crons,
606
+ upstream,
607
+ workerDefinitions,
608
+ enablePagesAssetsServiceBinding,
609
+ }: SetupMiniflareOptionsProps): {
610
+ miniflareCLIPath: string;
611
+ forkOptions: string[];
612
+ options: MiniflareOptions;
613
+ } {
614
+ // It's now getting _really_ messy now with Pages ASSETS binding outside and the external Durable Objects inside.
615
+ const options: MiniflareOptions = {
616
+ name: workerName,
617
+ port,
618
+ scriptPath,
619
+ https: localProtocol === "https",
620
+ host: ip,
621
+ modules: format === "modules",
622
+ modulesRules: (rules || [])
623
+ .concat(DEFAULT_MODULE_RULES)
624
+ .map(({ type, globs: include, fallthrough }) => ({
625
+ type,
626
+ include,
627
+ fallthrough,
628
+ })),
629
+ compatibilityDate,
630
+ compatibilityFlags,
631
+ usageModel,
632
+ kvNamespaces: kv_namespaces?.map((kv) => kv.binding),
633
+ queueBindings: queueBindings?.map((queue) => {
634
+ return { name: queue.binding, queueName: queue.queue_name };
635
+ }),
636
+ queueConsumers: queueConsumers?.map((consumer) => {
637
+ const waitMs = consumer.max_batch_timeout
638
+ ? 1000 * consumer.max_batch_timeout
639
+ : undefined;
640
+ return {
641
+ queueName: consumer.queue,
642
+ maxBatchSize: consumer.max_batch_size,
643
+ maxWaitMs: waitMs,
644
+ maxRetries: consumer.max_retries,
645
+ deadLetterQueue: consumer.dead_letter_queue,
646
+ };
647
+ }),
648
+ r2Buckets: r2_buckets?.map((r2) => r2.binding),
649
+ durableObjects: Object.fromEntries(
650
+ internalDurableObjects.map((binding) => [
651
+ binding.name,
652
+ binding.class_name,
653
+ ])
654
+ ),
655
+ externalDurableObjects: Object.fromEntries(
656
+ externalDurableObjects
657
+ .map((binding) => {
658
+ const service =
659
+ workerDefinitions &&
660
+ workerDefinitions[binding.script_name as string];
661
+ if (!service) return [binding.name, undefined];
662
+
663
+ const name = service.durableObjects.find(
664
+ (durableObject) => durableObject.className === binding.class_name
665
+ )?.name;
666
+ if (!name) return [binding.name, undefined];
667
+
668
+ return [
669
+ binding.name,
670
+ {
671
+ name,
672
+ host: service.durableObjectsHost,
673
+ port: service.durableObjectsPort,
674
+ },
675
+ ];
676
+ })
677
+ .filter(([_, details]) => !!details)
678
+ ),
679
+ d1Databases: d1_databases?.map((db) => db.binding),
680
+ ...(localPersistencePath
681
+ ? {
682
+ cachePersist: path.join(localPersistencePath, "cache"),
683
+ durableObjectsPersist: path.join(localPersistencePath, "do"),
684
+ kvPersist: path.join(localPersistencePath, "kv"),
685
+ r2Persist: path.join(localPersistencePath, "r2"),
686
+ d1Persist: path.join(localPersistencePath, "d1"),
687
+ }
688
+ : {
689
+ // We mark these as true, so that they'll
690
+ // persist in the temp directory.
691
+ // This means they'll persist across a dev session,
692
+ // even if we change source and reload,
693
+ // and be deleted when the dev session ends
694
+ cachePersist: true,
695
+ durableObjectsPersist: true,
696
+ kvPersist: true,
697
+ r2Persist: true,
698
+ }),
699
+
700
+ liveReload,
701
+ sitePath: assetPaths?.assetDirectory
702
+ ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
703
+ : undefined,
704
+ siteInclude: assetPaths?.includePatterns.length
705
+ ? assetPaths?.includePatterns
706
+ : undefined,
707
+ siteExclude: assetPaths?.excludePatterns.length
708
+ ? assetPaths.excludePatterns
709
+ : undefined,
710
+ bindings: vars,
711
+ wasmBindings,
712
+ textBlobBindings,
713
+ dataBlobBindings,
714
+ sourceMap: true,
715
+ logUnhandledRejections: true,
716
+ crons,
717
+ upstream,
718
+ logLevel: logger.loggerLevel,
719
+ enablePagesAssetsServiceBinding,
720
+ };
721
+ // The path to the Miniflare CLI assumes that this file is being run from
722
+ // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
723
+ // If either of those paths change this line needs updating.
724
+ const miniflareCLIPath = path.resolve(
725
+ getBasePath(),
726
+ "miniflare-dist/index.mjs"
727
+ );
728
+ const miniflareOptions = JSON.stringify(options, null);
729
+ const forkOptions = [miniflareOptions];
730
+ if (enablePagesAssetsServiceBinding) {
731
+ forkOptions.push(JSON.stringify(enablePagesAssetsServiceBinding));
732
+ }
733
+ return { miniflareCLIPath, forkOptions, options };
734
+ }
735
+
736
+ export function setupNodeOptions({
737
+ inspect,
738
+ inspectorPort,
739
+ }: {
740
+ inspect: boolean;
741
+ inspectorPort: number;
742
+ }) {
743
+ const nodeOptions = [
744
+ "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
745
+ "--no-warnings", // hide annoying Node warnings
746
+ // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
747
+ ];
748
+ if (inspect) {
749
+ nodeOptions.push("--inspect=" + `127.0.0.1:${inspectorPort}`); // start Miniflare listening for a debugger to attach
750
+ }
751
+ return nodeOptions;
752
+ }
753
+
754
+ export interface SetupMiniflare3Options {
755
+ // Regular Miniflare 2 options to transform
756
+ miniflare2Options: MiniflareOptions;
757
+ // Miniflare 3 requires all modules to be manually specified
758
+ format: CfScriptFormat;
759
+ bundle: EsbuildBundle;
760
+
761
+ // Miniflare's logger
762
+ log: Miniflare3LogType;
763
+
764
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
765
+
766
+ // Miniflare 3 accepts namespace/bucket names in addition to binding names.
767
+ // This means multiple workers persisting to the same location can have
768
+ // different binding names for the same namespace/bucket. Therefore, we need
769
+ // the full KV/R2 arrays. This is also required for remote KV storage, as
770
+ // we need actual namespace IDs to connect to.
771
+ kvNamespaces: CfKvNamespace[] | undefined;
772
+ r2Buckets: CfR2Bucket[] | undefined;
773
+ d1Databases: CfD1Database[] | undefined;
774
+
775
+ // Account ID to use for authenticated Cloudflare fetch. If true, prompt
776
+ // user for ID if multiple available.
777
+ authenticatedAccountId: string | true | undefined;
778
+ // Whether to read/write from/to real KV namespaces
779
+ kvRemote: boolean | undefined;
780
+
781
+ // Port to start DevTools inspector server on
782
+ inspectorPort: number;
783
+ }
784
+
785
+ export async function buildMiniflare3Logger(): Promise<Miniflare3LogType> {
786
+ const { Log, NoOpLog, LogLevel } = await getMiniflare3();
787
+
788
+ let level = logger.loggerLevel.toUpperCase() as Uppercase<LoggerLevel>;
789
+ if (level === "LOG") level = "INFO";
790
+ const logLevel = LogLevel[level];
791
+
792
+ return logLevel === LogLevel.NONE ? new NoOpLog() : new Log(logLevel);
793
+ }
794
+
795
+ export async function transformMf2OptionsToMf3Options({
796
+ miniflare2Options,
797
+ format,
798
+ bundle,
799
+ log,
800
+ enablePagesAssetsServiceBinding,
801
+ kvNamespaces,
802
+ r2Buckets,
803
+ d1Databases,
804
+ authenticatedAccountId,
805
+ kvRemote,
806
+ inspectorPort,
807
+ }: SetupMiniflare3Options): Promise<Miniflare3Options> {
808
+ // Build authenticated Cloudflare API fetch function if required
809
+ let cloudflareFetch: CloudflareFetch | undefined;
810
+ if (kvRemote && authenticatedAccountId !== undefined) {
811
+ const { Response: Miniflare3Response } = await getMiniflare3();
812
+ const preferredAccountId =
813
+ authenticatedAccountId === true ? undefined : authenticatedAccountId;
814
+ const accountId = await requireAuth({ account_id: preferredAccountId });
815
+ cloudflareFetch = async (resource, searchParams, init) => {
816
+ resource = `/accounts/${accountId}/${resource}`;
817
+ const response = await performApiFetch(resource, init, searchParams);
818
+ return new Miniflare3Response(response.body, response);
819
+ };
820
+ }
821
+
822
+ const options: Miniflare3Options = {
823
+ ...miniflare2Options,
824
+ // Miniflare 3 distinguishes between binding name and namespace/bucket IDs.
825
+ kvNamespaces: Object.fromEntries(
826
+ kvNamespaces?.map(({ binding, id }) => [binding, id]) ?? []
827
+ ),
828
+ r2Buckets: Object.fromEntries(
829
+ r2Buckets?.map(({ binding, bucket_name }) => [binding, bucket_name]) ?? []
830
+ ),
831
+ d1Databases: Object.fromEntries(
832
+ d1Databases?.map(({ binding, database_id, preview_database_id }) => [
833
+ binding,
834
+ preview_database_id ?? database_id,
835
+ ]) ?? []
836
+ ),
837
+ inspectorPort,
838
+ verbose: true,
839
+ cloudflareFetch,
840
+ log,
841
+ };
842
+
843
+ if (enablePagesAssetsServiceBinding !== undefined) {
844
+ // `../miniflare-cli/assets` dynamically imports`@cloudflare/pages-shared/environment-polyfills`.
845
+ // `@cloudflare/pages-shared/environment-polyfills/types.ts` defines `global`
846
+ // augmentations that pollute the `import`-site's typing environment.
847
+ //
848
+ // We `require` instead of `import`ing here to avoid polluting the main
849
+ // `wrangler` TypeScript project with the `global` augmentations. This
850
+ // relies on the fact that `require` is untyped.
851
+ //
852
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
853
+ const generateASSETSBinding = require("../miniflare-cli/assets").default;
854
+ options.serviceBindings = {
855
+ ...options.serviceBindings,
856
+ ASSETS: (await generateASSETSBinding({
857
+ log,
858
+ ...enablePagesAssetsServiceBinding,
859
+ tre: true,
860
+ // We can get rid of this `any` easily once we do experimental-local/tre by default
861
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
862
+ })) as any,
863
+ };
864
+ }
865
+
866
+ if (format === "modules") {
867
+ // Manually specify all modules from the bundle. If we didn't do this,
868
+ // Miniflare 3 would try collect them automatically again itself.
869
+
870
+ // Resolve entrypoint relative to the temporary directory, ensuring
871
+ // path doesn't start with `..`, which causes issues in `workerd`.
872
+ // Also ensures other modules with relative names can be resolved.
873
+ const root = path.dirname(bundle.path);
874
+
875
+ assert.strictEqual(bundle.type, "esm");
876
+ // Required for source mapped paths to resolve correctly
877
+ options.modulesRoot = root;
878
+ options.modules = [
879
+ // Entrypoint
880
+ {
881
+ type: "ESModule",
882
+ path: bundle.path,
883
+ contents: await readFile(bundle.path, "utf-8"),
884
+ },
885
+ // Misc (WebAssembly, etc, ...)
886
+ ...bundle.modules.map((module) => ({
887
+ type: ModuleTypeToRuleType[module.type ?? "esm"],
888
+ path: path.resolve(root, module.name),
889
+ contents: module.content,
890
+ })),
891
+ ];
892
+ }
893
+
894
+ if (kvRemote) {
895
+ // `kvPersist` is always assigned a truthy value in `setupMiniflareOptions`
896
+ assert(options.kvPersist);
897
+ const kvRemoteCache =
898
+ options.kvPersist === true
899
+ ? // If storing in temporary directory, find this path from the bundle
900
+ // output path
901
+ path.join(path.dirname(bundle.path), ".mf", "kv-remote")
902
+ : // Otherwise, `kvPersist` looks like `.../kv`, so rewrite it to
903
+ // `kv-remote` since the expected metadata format for remote storage
904
+ // is different to local
905
+ path.join(path.dirname(options.kvPersist), "kv-remote");
906
+ options.kvPersist = `remote:?cache=${encodeURIComponent(kvRemoteCache)}`;
907
+ }
908
+
909
+ return options;
910
+ }
911
+
912
+ // Caching of the `npx-import`ed `@miniflare/tre` package
913
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
914
+ let miniflare3Module: typeof import("@miniflare/tre");
915
+ export async function getMiniflare3(): Promise<
916
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
917
+ typeof import("@miniflare/tre")
918
+ > {
919
+ return (miniflare3Module ??= await npxImport("@miniflare/tre@3.0.0-next.12"));
318
920
  }