wrangler 0.0.0-e928f94 → 0.0.0-e93063e9

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