wrangler 0.0.0-e3e3243 → 0.0.0-e4047cab

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