wrangler 0.0.0-e64812e → 0.0.0-e7a0cd5b

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 (291) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +150 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1451 -21
  5. package/package.json +190 -152
  6. package/src/__tests__/access.test.ts +25 -0
  7. package/src/__tests__/api-dev.test.ts +209 -0
  8. package/src/__tests__/api-devregistry.test.js +57 -0
  9. package/src/__tests__/api.test.ts +80 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +4017 -3363
  13. package/src/__tests__/d1.test.ts +72 -0
  14. package/src/__tests__/delete.test.ts +230 -0
  15. package/src/__tests__/deployments.test.ts +95 -0
  16. package/src/__tests__/dev.test.tsx +1480 -951
  17. package/src/__tests__/dialogs.test.tsx +40 -0
  18. package/src/__tests__/generate.test.ts +235 -0
  19. package/src/__tests__/get-host-from-url.test.ts +16 -0
  20. package/src/__tests__/guess-worker-format.test.ts +68 -68
  21. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  22. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  23. package/src/__tests__/helpers/mock-bin.ts +20 -20
  24. package/src/__tests__/helpers/mock-cfetch.ts +216 -94
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  28. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  29. package/src/__tests__/helpers/mock-istty.ts +65 -18
  30. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  31. package/src/__tests__/helpers/mock-kv.ts +27 -27
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
  33. package/src/__tests__/helpers/mock-process.ts +39 -0
  34. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  35. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  36. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  37. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  38. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  39. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  40. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  41. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  42. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  43. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  44. package/src/__tests__/helpers/msw/index.ts +21 -0
  45. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  46. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  47. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  48. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  52. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  53. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  54. package/src/__tests__/https-options.test.ts +142 -109
  55. package/src/__tests__/index.test.ts +239 -233
  56. package/src/__tests__/init.test.ts +2869 -1603
  57. package/src/__tests__/jest.setup.ts +159 -34
  58. package/src/__tests__/kv.test.ts +1660 -1466
  59. package/src/__tests__/logger.test.ts +100 -74
  60. package/src/__tests__/metrics.test.ts +450 -0
  61. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  62. package/src/__tests__/middleware.test.ts +726 -0
  63. package/src/__tests__/package-manager.test.ts +303 -303
  64. package/src/__tests__/pages.test.ts +2204 -735
  65. package/src/__tests__/parse.test.ts +252 -252
  66. package/src/__tests__/paths.test.ts +39 -0
  67. package/src/__tests__/publish.test.ts +7543 -5351
  68. package/src/__tests__/pubsub.test.ts +370 -0
  69. package/src/__tests__/queues.test.ts +371 -0
  70. package/src/__tests__/r2.test.ts +371 -228
  71. package/src/__tests__/route.test.ts +18 -18
  72. package/src/__tests__/secret.test.ts +622 -459
  73. package/src/__tests__/tail.test.ts +677 -567
  74. package/src/__tests__/test-old-node-version.js +31 -0
  75. package/src/__tests__/type-generation.test.ts +217 -0
  76. package/src/__tests__/user.test.ts +140 -116
  77. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  78. package/src/__tests__/validate-dev-props.test.ts +56 -0
  79. package/src/__tests__/version.test.ts +35 -0
  80. package/src/__tests__/whoami.test.tsx +264 -91
  81. package/src/__tests__/worker-namespace.test.ts +326 -0
  82. package/src/abort.d.ts +1 -1
  83. package/src/api/dev.ts +208 -0
  84. package/src/api/index.ts +2 -0
  85. package/src/bundle-reporter.tsx +68 -0
  86. package/src/bundle.ts +746 -161
  87. package/src/cfetch/index.ts +120 -81
  88. package/src/cfetch/internal.ts +209 -91
  89. package/src/cli.ts +23 -8
  90. package/src/config/config.ts +236 -195
  91. package/src/config/diagnostics.ts +61 -61
  92. package/src/config/environment.ts +500 -357
  93. package/src/config/index.ts +310 -193
  94. package/src/config/validation-helpers.ts +379 -357
  95. package/src/config/validation.ts +1941 -1367
  96. package/src/config-cache.ts +81 -41
  97. package/src/create-worker-preview.ts +239 -142
  98. package/src/create-worker-upload-form.ts +305 -238
  99. package/src/d1/backups.tsx +218 -0
  100. package/src/d1/create.tsx +54 -0
  101. package/src/d1/delete.tsx +56 -0
  102. package/src/d1/execute.tsx +299 -0
  103. package/src/d1/formatTimeAgo.ts +14 -0
  104. package/src/d1/index.ts +76 -0
  105. package/src/d1/list.tsx +48 -0
  106. package/src/d1/options.ts +12 -0
  107. package/src/d1/types.tsx +14 -0
  108. package/src/d1/utils.ts +39 -0
  109. package/src/delete.ts +108 -0
  110. package/src/deployments.ts +74 -0
  111. package/src/deprecated/index.ts +438 -0
  112. package/src/dev/dev-vars.ts +20 -17
  113. package/src/dev/dev.tsx +520 -352
  114. package/src/dev/get-local-persistence-path.tsx +31 -0
  115. package/src/dev/local.tsx +697 -298
  116. package/src/dev/remote.tsx +591 -215
  117. package/src/dev/start-server.ts +513 -0
  118. package/src/dev/use-esbuild.ts +183 -97
  119. package/src/dev/validate-dev-props.ts +31 -0
  120. package/src/dev-registry.tsx +201 -0
  121. package/src/dev.tsx +869 -0
  122. package/src/dialogs.tsx +126 -98
  123. package/src/dispatch-namespace.ts +207 -0
  124. package/src/durable.ts +87 -87
  125. package/src/entry.ts +235 -228
  126. package/src/environment-variables.ts +38 -23
  127. package/src/errors.ts +6 -6
  128. package/src/git-client.ts +124 -0
  129. package/src/global-wrangler-config-path.ts +26 -0
  130. package/src/https-options.ts +84 -80
  131. package/src/index.tsx +627 -2807
  132. package/src/init.ts +970 -0
  133. package/src/inspect.ts +698 -593
  134. package/src/intl-polyfill.d.ts +123 -123
  135. package/src/is-ci.ts +14 -0
  136. package/src/is-interactive.ts +16 -0
  137. package/src/kv/helpers.ts +430 -0
  138. package/src/kv/index.ts +596 -0
  139. package/src/logger.ts +67 -41
  140. package/src/metrics/index.ts +5 -0
  141. package/src/metrics/metrics-config.ts +239 -0
  142. package/src/metrics/metrics-dispatcher.ts +96 -0
  143. package/src/metrics/metrics-usage-headers.ts +24 -0
  144. package/src/metrics/send-event.ts +94 -0
  145. package/src/miniflare-cli/assets.ts +215 -0
  146. package/src/miniflare-cli/index.ts +205 -33
  147. package/src/miniflare-cli/request-context.ts +18 -18
  148. package/src/module-collection.ts +221 -212
  149. package/src/open-in-browser.ts +4 -6
  150. package/src/package-manager.ts +173 -128
  151. package/src/pages/build.tsx +238 -0
  152. package/src/pages/constants.ts +18 -0
  153. package/src/pages/deployments.tsx +106 -0
  154. package/src/pages/dev.tsx +693 -0
  155. package/src/pages/errors.ts +66 -0
  156. package/src/pages/functions/buildPlugin.ts +110 -0
  157. package/src/pages/functions/buildWorker.ts +156 -0
  158. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  159. package/src/pages/functions/filepath-routing.ts +189 -0
  160. package/src/pages/functions/identifiers.ts +78 -0
  161. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  162. package/src/pages/functions/routes-consolidation.ts +73 -0
  163. package/src/pages/functions/routes-transformation.test.ts +282 -0
  164. package/src/pages/functions/routes-transformation.ts +115 -0
  165. package/src/pages/functions/routes-validation.test.ts +403 -0
  166. package/src/pages/functions/routes-validation.ts +202 -0
  167. package/src/pages/functions/routes.ts +151 -0
  168. package/src/pages/functions.tsx +82 -0
  169. package/src/pages/hash.tsx +13 -0
  170. package/src/pages/index.tsx +94 -0
  171. package/src/pages/projects.tsx +169 -0
  172. package/src/pages/publish.tsx +436 -0
  173. package/src/pages/types.ts +49 -0
  174. package/src/pages/upload.tsx +425 -0
  175. package/src/pages/utils.ts +12 -0
  176. package/src/parse.ts +209 -125
  177. package/src/paths.ts +53 -8
  178. package/src/proxy.ts +618 -394
  179. package/src/publish/index.ts +270 -0
  180. package/src/publish/publish.ts +1035 -0
  181. package/src/pubsub/index.ts +286 -0
  182. package/src/pubsub/pubsub-commands.tsx +624 -0
  183. package/src/queues/cli/commands/consumer/add.ts +71 -0
  184. package/src/queues/cli/commands/consumer/index.ts +22 -0
  185. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  186. package/src/queues/cli/commands/create.ts +25 -0
  187. package/src/queues/cli/commands/delete.ts +26 -0
  188. package/src/queues/cli/commands/index.ts +33 -0
  189. package/src/queues/cli/commands/list.ts +25 -0
  190. package/src/queues/client.ts +135 -0
  191. package/src/r2/helpers.ts +131 -0
  192. package/src/r2/index.ts +277 -0
  193. package/src/routes.ts +140 -0
  194. package/src/secret/index.ts +379 -0
  195. package/src/selfsigned.d.ts +23 -23
  196. package/src/sites.tsx +280 -203
  197. package/src/tail/createTail.ts +315 -0
  198. package/src/tail/filters.ts +108 -110
  199. package/src/tail/index.ts +211 -296
  200. package/src/tail/printing.ts +86 -46
  201. package/src/type-generation.ts +159 -0
  202. package/src/update-check.ts +11 -11
  203. package/src/user/access.ts +69 -0
  204. package/src/user/choose-account.tsx +69 -0
  205. package/src/user/env-vars.ts +46 -0
  206. package/src/user/generate-auth-url.ts +33 -0
  207. package/src/user/generate-random-state.ts +16 -0
  208. package/src/user/index.ts +3 -0
  209. package/src/user/user.tsx +1192 -0
  210. package/src/utils/collectKeyValues.ts +14 -0
  211. package/src/whoami.tsx +141 -42
  212. package/src/worker.ts +168 -106
  213. package/src/yargs-types.ts +20 -0
  214. package/src/zones.ts +191 -0
  215. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  216. package/templates/checked-fetch.js +17 -0
  217. package/templates/d1-beta-facade.js +174 -0
  218. package/templates/experimental-local-cache-stubs.js +27 -0
  219. package/templates/first-party-worker-module-facade.ts +18 -0
  220. package/templates/format-dev-errors.ts +32 -0
  221. package/templates/init-tests/test-jest-new-worker.js +25 -0
  222. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  223. package/templates/middleware/common.ts +62 -0
  224. package/templates/middleware/loader-modules.ts +84 -0
  225. package/templates/middleware/loader-sw.ts +213 -0
  226. package/templates/middleware/middleware-pretty-error.ts +40 -0
  227. package/templates/middleware/middleware-scheduled.ts +15 -0
  228. package/templates/new-worker-scheduled.js +3 -3
  229. package/templates/new-worker-scheduled.ts +15 -15
  230. package/templates/new-worker.js +3 -3
  231. package/templates/new-worker.ts +15 -15
  232. package/templates/no-op-worker.js +10 -0
  233. package/templates/pages-dev-pipeline.ts +28 -0
  234. package/templates/pages-dev-util.ts +52 -0
  235. package/templates/pages-shim.ts +9 -0
  236. package/templates/pages-template-plugin.ts +171 -0
  237. package/templates/pages-template-worker.ts +189 -0
  238. package/templates/serve-static-assets.ts +63 -0
  239. package/templates/service-bindings-module-facade.js +54 -0
  240. package/templates/service-bindings-sw-facade.js +42 -0
  241. package/templates/tsconfig.json +96 -95
  242. package/wrangler-dist/cli.d.ts +892 -0
  243. package/wrangler-dist/cli.js +145674 -108957
  244. package/pages/functions/buildPlugin.ts +0 -105
  245. package/pages/functions/buildWorker.ts +0 -151
  246. package/pages/functions/filepath-routing.ts +0 -189
  247. package/pages/functions/identifiers.ts +0 -78
  248. package/pages/functions/routes.ts +0 -156
  249. package/pages/functions/template-plugin.ts +0 -147
  250. package/pages/functions/template-worker.ts +0 -143
  251. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  252. package/src/kv.ts +0 -408
  253. package/src/miniflare-cli/enum-keys.ts +0 -17
  254. package/src/pages.tsx +0 -2038
  255. package/src/publish.ts +0 -583
  256. package/src/r2.ts +0 -50
  257. package/src/user.tsx +0 -1203
  258. package/templates/static-asset-facade.js +0 -47
  259. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  260. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  261. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  262. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  263. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  264. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  265. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  266. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  267. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  268. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  269. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  270. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  271. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  272. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  273. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  274. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  275. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  276. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  277. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  278. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  279. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  280. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  281. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  282. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  283. package/vendor/wrangler-mime/LICENSE +0 -21
  284. package/vendor/wrangler-mime/Mime.js +0 -97
  285. package/vendor/wrangler-mime/README.md +0 -187
  286. package/vendor/wrangler-mime/cli.js +0 -46
  287. package/vendor/wrangler-mime/index.js +0 -4
  288. package/vendor/wrangler-mime/lite.js +0 -4
  289. package/vendor/wrangler-mime/package.json +0 -52
  290. package/vendor/wrangler-mime/types/other.js +0 -1
  291. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/dev/local.tsx CHANGED
@@ -1,318 +1,717 @@
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 { registerWorker } from "../dev-registry";
7
11
  import useInspector from "../inspect";
8
12
  import { logger } from "../logger";
9
- import { DEFAULT_MODULE_RULES } from "../module-collection";
13
+ import {
14
+ DEFAULT_MODULE_RULES,
15
+ ModuleTypeToRuleType,
16
+ } from "../module-collection";
17
+ import { getBasePath } from "../paths";
10
18
  import { waitForPortToBeAvailable } from "../proxy";
11
19
  import type { Config } from "../config";
20
+ import type { WorkerRegistry } from "../dev-registry";
21
+ import type { EnablePagesAssetsServiceBindingOptions } from "../miniflare-cli";
12
22
  import type { AssetPaths } from "../sites";
13
- import type { CfWorkerInit, CfScriptFormat } from "../worker";
23
+ import type {
24
+ CfWorkerInit,
25
+ CfScriptFormat,
26
+ CfWasmModuleBindings,
27
+ CfTextBlobBindings,
28
+ CfDataBlobBindings,
29
+ CfDurableObject,
30
+ CfKvNamespace,
31
+ CfR2Bucket,
32
+ CfVars,
33
+ CfQueue,
34
+ CfD1Database,
35
+ } from "../worker";
14
36
  import type { EsbuildBundle } from "./use-esbuild";
37
+ import type {
38
+ Miniflare as Miniflare3Type,
39
+ MiniflareOptions as Miniflare3Options,
40
+ } from "@miniflare/tre";
15
41
  import type { MiniflareOptions } from "miniflare";
42
+ import type { ChildProcess } from "node:child_process";
16
43
 
17
- interface LocalProps {
18
- name: string | undefined;
19
- bundle: EsbuildBundle | undefined;
20
- format: CfScriptFormat | undefined;
21
- compatibilityDate: string;
22
- compatibilityFlags: string[] | undefined;
23
- bindings: CfWorkerInit["bindings"];
24
- assetPaths: AssetPaths | undefined;
25
- public: string | undefined;
26
- port: number;
27
- ip: string;
28
- rules: Config["rules"];
29
- inspectorPort: number;
30
- enableLocalPersistence: boolean;
31
- crons: Config["triggers"]["crons"];
44
+ export interface LocalProps {
45
+ name: string | undefined;
46
+ bundle: EsbuildBundle | undefined;
47
+ format: CfScriptFormat | undefined;
48
+ compatibilityDate: string;
49
+ compatibilityFlags: string[] | undefined;
50
+ usageModel: "bundled" | "unbound" | undefined;
51
+ bindings: CfWorkerInit["bindings"];
52
+ workerDefinitions: WorkerRegistry | undefined;
53
+ assetPaths: AssetPaths | undefined;
54
+ port: number;
55
+ ip: string;
56
+ rules: Config["rules"];
57
+ inspectorPort: number;
58
+ localPersistencePath: string | null;
59
+ liveReload: boolean;
60
+ crons: Config["triggers"]["crons"];
61
+ queueConsumers: Config["queues"]["consumers"];
62
+ localProtocol: "http" | "https";
63
+ localUpstream: string | undefined;
64
+ inspect: boolean;
65
+ onReady: ((ip: string, port: number) => void) | undefined;
66
+ logPrefix?: string;
67
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
68
+ testScheduled?: boolean;
69
+ experimentalLocal?: boolean;
32
70
  }
33
71
 
34
72
  export function Local(props: LocalProps) {
35
- const { inspectorUrl } = useLocalWorker(props);
36
- useInspector({
37
- inspectorUrl,
38
- port: props.inspectorPort,
39
- logToTerminal: false,
40
- });
41
- return null;
73
+ const { inspectorUrl } = useLocalWorker(props);
74
+ useInspector({
75
+ inspectorUrl,
76
+ port: props.inspectorPort,
77
+ logToTerminal: false,
78
+ });
79
+ return null;
42
80
  }
43
81
 
44
82
  function useLocalWorker({
45
- name: workerName,
46
- bundle,
47
- format,
48
- compatibilityDate,
49
- compatibilityFlags,
50
- bindings,
51
- assetPaths,
52
- public: publicDirectory,
53
- port,
54
- rules,
55
- enableLocalPersistence,
56
- ip,
57
- crons,
83
+ name: workerName,
84
+ bundle,
85
+ format,
86
+ compatibilityDate,
87
+ compatibilityFlags,
88
+ usageModel,
89
+ bindings,
90
+ workerDefinitions,
91
+ assetPaths,
92
+ port,
93
+ inspectorPort,
94
+ rules,
95
+ localPersistencePath,
96
+ liveReload,
97
+ ip,
98
+ crons,
99
+ queueConsumers,
100
+ localProtocol,
101
+ localUpstream,
102
+ inspect,
103
+ onReady,
104
+ logPrefix,
105
+ enablePagesAssetsServiceBinding,
106
+ experimentalLocal,
58
107
  }: LocalProps) {
59
- // TODO: pass vars via command line
60
- const local = useRef<ReturnType<typeof spawn>>();
61
- const removeSignalExitListener = useRef<() => void>();
62
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
63
- // if we're using local persistence for data, we should use the cwd
64
- // as an explicit path, or else it'll use the temp dir
65
- // which disappears when dev ends
66
- const localPersistencePath = enableLocalPersistence
67
- ? // Maybe we could make the path configurable as well?
68
- path.join(process.cwd(), "wrangler-local-state")
69
- : // We otherwise choose null, but choose true later
70
- // so that it's persisted in the temp dir across a dev session
71
- // even when we change source and reload
72
- null;
73
- useEffect(() => {
74
- const abortController = new AbortController();
75
- async function startLocalWorker() {
76
- if (!bundle || !format) return;
77
-
78
- // port for the worker
79
- await waitForPortToBeAvailable(port, {
80
- retryPeriod: 200,
81
- timeout: 2000,
82
- abortSignal: abortController.signal,
83
- });
84
-
85
- if (publicDirectory) {
86
- throw new Error(
87
- '⎔ A "public" folder is not yet supported in local mode.'
88
- );
89
- }
90
- if (bindings.services && bindings.services.length > 0) {
91
- throw new Error(
92
- "⎔ Service bindings are not yet supported in local mode."
93
- );
94
- }
95
-
96
- // In local mode, we want to copy all referenced modules into
97
- // the output bundle directory before starting up
98
- for (const module of bundle.modules) {
99
- await writeFile(
100
- path.join(path.dirname(bundle.path), module.name),
101
- module.content
102
- );
103
- }
104
-
105
- const scriptPath = realpathSync(bundle.path);
106
-
107
- // the wasm_modules/text_blobs/data_blobs bindings are
108
- // relative to process.cwd(), but the actual worker bundle
109
- // is in the temp output directory; so we rewrite the paths to be absolute,
110
- // letting miniflare resolve them correctly
111
-
112
- // wasm
113
- const wasmBindings: Record<string, string> = {};
114
- for (const [name, filePath] of Object.entries(
115
- bindings.wasm_modules || {}
116
- )) {
117
- wasmBindings[name] = path.join(process.cwd(), filePath);
118
- }
119
-
120
- // text
121
- const textBlobBindings: Record<string, string> = {};
122
- for (const [name, filePath] of Object.entries(
123
- bindings.text_blobs || {}
124
- )) {
125
- textBlobBindings[name] = path.join(process.cwd(), filePath);
126
- }
127
-
128
- // data
129
- const dataBlobBindings: Record<string, string> = {};
130
- for (const [name, filePath] of Object.entries(
131
- bindings.data_blobs || {}
132
- )) {
133
- dataBlobBindings[name] = path.join(process.cwd(), filePath);
134
- }
135
-
136
- if (format === "service-worker") {
137
- for (const { type, name } of bundle.modules) {
138
- if (type === "compiled-wasm") {
139
- // In service-worker format, .wasm modules are referenced by global identifiers,
140
- // so we convert it here.
141
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
142
- // characters with an underscore.
143
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
144
- wasmBindings[identifier] = name;
145
- } else if (type === "text") {
146
- // In service-worker format, text modules are referenced by global identifiers,
147
- // so we convert it here.
148
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
149
- // characters with an underscore.
150
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
151
- textBlobBindings[identifier] = name;
152
- } else if (type === "buffer") {
153
- // In service-worker format, data blobs are referenced by global identifiers,
154
- // so we convert it here.
155
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
156
- // characters with an underscore.
157
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
158
- dataBlobBindings[identifier] = name;
159
- }
160
- }
161
- }
162
-
163
- const options: MiniflareOptions = {
164
- name: workerName,
165
- port,
166
- scriptPath,
167
- host: ip,
168
- modules: format === "modules",
169
- modulesRules: (rules || [])
170
- .concat(DEFAULT_MODULE_RULES)
171
- .map(({ type, globs: include, fallthrough }) => ({
172
- type,
173
- include,
174
- fallthrough,
175
- })),
176
- compatibilityDate,
177
- compatibilityFlags,
178
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
179
- durableObjects: Object.fromEntries(
180
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
181
- (value) => [value.name, value.class_name]
182
- )
183
- ),
184
- ...(localPersistencePath
185
- ? {
186
- kvPersist: path.join(localPersistencePath, "kv"),
187
- durableObjectsPersist: path.join(localPersistencePath, "do"),
188
- cachePersist: path.join(localPersistencePath, "cache"),
189
- }
190
- : {
191
- // We mark these as true, so that they'll
192
- // persist in the temp directory.
193
- // This means they'll persist across a dev session,
194
- // even if we change source and reload,
195
- // and be deleted when the dev session ends
196
- durableObjectsPersist: true,
197
- cachePersist: true,
198
- kvPersist: true,
199
- }),
200
-
201
- sitePath: assetPaths?.assetDirectory
202
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
203
- : undefined,
204
- siteInclude: assetPaths?.includePatterns.length
205
- ? assetPaths?.includePatterns
206
- : undefined,
207
- siteExclude: assetPaths?.excludePatterns.length
208
- ? assetPaths.excludePatterns
209
- : undefined,
210
- bindings: bindings.vars,
211
- wasmBindings,
212
- textBlobBindings,
213
- dataBlobBindings,
214
- sourceMap: true,
215
- logUnhandledRejections: true,
216
- crons,
217
- };
218
-
219
- // The path to the Miniflare CLI assumes that this file is being run from
220
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
221
- // If either of those paths change this line needs updating.
222
- const miniflareCLIPath = path.resolve(
223
- __dirname,
224
- "../miniflare-dist/index.mjs"
225
- );
226
- const optionsArg = JSON.stringify(options, null);
227
-
228
- logger.log("⎔ Starting a local server...");
229
- local.current = spawn(
230
- "node",
231
- [
232
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
233
- "--no-warnings", // hide annoying Node warnings
234
- "--inspect", // start Miniflare listening for a debugger to attach
235
- miniflareCLIPath,
236
- optionsArg,
237
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
238
- ],
239
- {
240
- cwd: path.dirname(scriptPath),
241
- }
242
- );
243
-
244
- local.current.on("close", (code) => {
245
- if (code) {
246
- logger.log(`Miniflare process exited with code ${code}`);
247
- }
248
- });
249
-
250
- local.current.stdout?.on("data", (data: Buffer) => {
251
- process.stdout.write(data);
252
- });
253
-
254
- local.current.stderr?.on("data", (data: Buffer) => {
255
- const matches =
256
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
257
- data.toString()
258
- );
259
- if (matches) {
260
- setInspectorUrl(matches[1]);
261
- }
262
- });
263
-
264
- local.current.on("exit", (code) => {
265
- if (code) {
266
- logger.error(`Miniflare process exited with code ${code}`);
267
- }
268
- });
269
-
270
- local.current.on("error", (error: Error) => {
271
- logger.error(`Miniflare process failed to spawn`);
272
- logger.error(error);
273
- });
274
-
275
- removeSignalExitListener.current = onExit((_code, _signal) => {
276
- logger.log("⎔ Shutting down local server.");
277
- local.current?.kill();
278
- local.current = undefined;
279
- });
280
- }
281
-
282
- startLocalWorker().catch((err) => {
283
- logger.error("local worker:", err);
284
- });
285
-
286
- return () => {
287
- abortController.abort();
288
- if (local.current) {
289
- logger.log("⎔ Shutting down local server.");
290
- local.current?.kill();
291
- local.current = undefined;
292
- removeSignalExitListener.current && removeSignalExitListener.current();
293
- removeSignalExitListener.current = undefined;
294
- }
295
- };
296
- }, [
297
- bundle,
298
- workerName,
299
- format,
300
- port,
301
- ip,
302
- bindings.durable_objects?.bindings,
303
- bindings.kv_namespaces,
304
- bindings.vars,
305
- bindings.services,
306
- compatibilityDate,
307
- compatibilityFlags,
308
- localPersistencePath,
309
- assetPaths,
310
- publicDirectory,
311
- rules,
312
- bindings.wasm_modules,
313
- bindings.text_blobs,
314
- bindings.data_blobs,
315
- crons,
316
- ]);
317
- return { inspectorUrl };
108
+ // TODO: pass vars via command line
109
+ const local = useRef<ChildProcess>();
110
+ const experimentalLocalRef = useRef<Miniflare3Type>();
111
+ const removeSignalExitListener = useRef<() => void>();
112
+ const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
113
+
114
+ useEffect(() => {
115
+ if (bindings.services && bindings.services.length > 0) {
116
+ logger.warn(
117
+ "⎔ Support for service bindings in local mode is experimental and may change."
118
+ );
119
+ }
120
+ }, [bindings.services]);
121
+
122
+ useEffect(() => {
123
+ const externalDurableObjects = (
124
+ bindings.durable_objects?.bindings || []
125
+ ).filter((binding) => binding.script_name);
126
+
127
+ if (externalDurableObjects.length > 0) {
128
+ logger.warn(
129
+ "⎔ Support for external Durable Objects in local mode is experimental and may change."
130
+ );
131
+ }
132
+ }, [bindings.durable_objects?.bindings]);
133
+
134
+ useEffect(() => {
135
+ const abortController = new AbortController();
136
+ async function startLocalWorker() {
137
+ if (!bundle || !format) return;
138
+
139
+ // port for the worker
140
+ await waitForPortToBeAvailable(port, {
141
+ retryPeriod: 200,
142
+ timeout: 2000,
143
+ abortSignal: abortController.signal,
144
+ });
145
+
146
+ // In local mode, we want to copy all referenced modules into
147
+ // the output bundle directory before starting up
148
+ for (const module of bundle.modules) {
149
+ await writeFile(
150
+ path.join(path.dirname(bundle.path), module.name),
151
+ module.content
152
+ );
153
+ }
154
+
155
+ const scriptPath = realpathSync(bundle.path);
156
+
157
+ const upstream =
158
+ typeof localUpstream === "string"
159
+ ? `${localProtocol}://${localUpstream}`
160
+ : undefined;
161
+
162
+ const {
163
+ externalDurableObjects,
164
+ internalDurableObjects,
165
+ wasmBindings,
166
+ textBlobBindings,
167
+ dataBlobBindings,
168
+ } = setupBindings({
169
+ wasm_modules: bindings.wasm_modules,
170
+ text_blobs: bindings.text_blobs,
171
+ data_blobs: bindings.data_blobs,
172
+ durable_objects: bindings.durable_objects,
173
+ format,
174
+ bundle,
175
+ });
176
+
177
+ const { forkOptions, miniflareCLIPath } = setupMiniflareOptions({
178
+ workerName,
179
+ port,
180
+ scriptPath,
181
+ localProtocol,
182
+ ip,
183
+ format,
184
+ rules,
185
+ compatibilityDate,
186
+ compatibilityFlags,
187
+ usageModel,
188
+ kv_namespaces: bindings?.kv_namespaces,
189
+ r2_buckets: bindings?.r2_buckets,
190
+ queueBindings: bindings?.queues,
191
+ queueConsumers: queueConsumers,
192
+ d1_databases: bindings?.d1_databases,
193
+ internalDurableObjects,
194
+ externalDurableObjects,
195
+ localPersistencePath,
196
+ liveReload,
197
+ assetPaths,
198
+ vars: bindings?.vars,
199
+ wasmBindings,
200
+ textBlobBindings,
201
+ dataBlobBindings,
202
+ crons,
203
+ upstream,
204
+ logPrefix,
205
+ workerDefinitions,
206
+ enablePagesAssetsServiceBinding,
207
+ });
208
+
209
+ if (experimentalLocal) {
210
+ // TODO: refactor setupMiniflareOptions so we don't need to parse here
211
+ const mf2Options: MiniflareOptions = JSON.parse(forkOptions[0]);
212
+ const mf = await setupExperimentalLocal(mf2Options, format, bundle);
213
+ await mf.ready;
214
+ experimentalLocalRef.current = mf;
215
+ removeSignalExitListener.current = onExit(() => {
216
+ logger.log("⎔ Shutting down experimental local server.");
217
+ mf.dispose();
218
+ experimentalLocalRef.current = undefined;
219
+ });
220
+ return;
221
+ }
222
+
223
+ const nodeOptions = setupNodeOptions({ inspect, ip, inspectorPort });
224
+ logger.log("⎔ Starting a local server...");
225
+
226
+ const child = (local.current = fork(miniflareCLIPath, forkOptions, {
227
+ cwd: path.dirname(scriptPath),
228
+ execArgv: nodeOptions,
229
+ stdio: "pipe",
230
+ env: {
231
+ ...process.env,
232
+ FORCE_COLOR: chalk.supportsColor.hasBasic ? "1" : undefined,
233
+ },
234
+ }));
235
+
236
+ child.on("message", async (messageString) => {
237
+ const message = JSON.parse(messageString as string);
238
+ if (message.ready) {
239
+ // Let's register our presence in the dev registry
240
+ if (workerName) {
241
+ await registerWorker(workerName, {
242
+ protocol: localProtocol,
243
+ mode: "local",
244
+ port,
245
+ host: ip,
246
+ durableObjects: internalDurableObjects.map((binding) => ({
247
+ name: binding.name,
248
+ className: binding.class_name,
249
+ })),
250
+ ...(message.durableObjectsPort
251
+ ? {
252
+ durableObjectsHost: ip,
253
+ durableObjectsPort: message.durableObjectsPort,
254
+ }
255
+ : {}),
256
+ });
257
+ }
258
+ onReady?.(ip, message.mfPort);
259
+ }
260
+ });
261
+
262
+ child.on("close", (code) => {
263
+ if (code) {
264
+ logger.log(`Miniflare process exited with code ${code}`);
265
+ }
266
+ });
267
+
268
+ child.stdout?.on("data", (data: Buffer) => {
269
+ process.stdout.write(data);
270
+ });
271
+
272
+ // parse the node inspector url (which may be received in chunks) from stderr
273
+ let stderrData = "";
274
+ let inspectorUrlFound = false;
275
+ child.stderr?.on("data", (data: Buffer) => {
276
+ if (!inspectorUrlFound) {
277
+ stderrData += data.toString();
278
+ const matches =
279
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)[\r|\n]/.exec(
280
+ stderrData
281
+ );
282
+ if (matches) {
283
+ inspectorUrlFound = true;
284
+ setInspectorUrl(matches[1]);
285
+ }
286
+ }
287
+
288
+ process.stderr.write(data);
289
+ });
290
+
291
+ child.on("exit", (code) => {
292
+ if (code) {
293
+ logger.error(`Miniflare process exited with code ${code}`);
294
+ }
295
+ });
296
+
297
+ child.on("error", (error: Error) => {
298
+ logger.error(`Miniflare process failed to spawn`);
299
+ logger.error(error);
300
+ });
301
+
302
+ removeSignalExitListener.current = onExit((_code, _signal) => {
303
+ logger.log("⎔ Shutting down local server.");
304
+ child.kill();
305
+ local.current = undefined;
306
+ });
307
+ }
308
+
309
+ startLocalWorker().catch((err) => {
310
+ logger.error("local worker:", err);
311
+ });
312
+
313
+ return () => {
314
+ abortController.abort();
315
+ if (local.current) {
316
+ logger.log("⎔ Shutting down local server.");
317
+ local.current?.kill();
318
+ local.current = undefined;
319
+ }
320
+ if (experimentalLocalRef.current) {
321
+ logger.log("⎔ Shutting down experimental local server.");
322
+ // Initialisation errors are also thrown asynchronously by dispose().
323
+ // The catch() above should've caught them though.
324
+ experimentalLocalRef.current?.dispose().catch(() => {});
325
+ experimentalLocalRef.current = undefined;
326
+ }
327
+ removeSignalExitListener.current?.();
328
+ removeSignalExitListener.current = undefined;
329
+ };
330
+ }, [
331
+ bundle,
332
+ workerName,
333
+ format,
334
+ port,
335
+ inspectorPort,
336
+ ip,
337
+ queueConsumers,
338
+ bindings.queues,
339
+ bindings.durable_objects,
340
+ bindings.kv_namespaces,
341
+ bindings.r2_buckets,
342
+ bindings.d1_databases,
343
+ bindings.vars,
344
+ bindings.services,
345
+ workerDefinitions,
346
+ compatibilityDate,
347
+ compatibilityFlags,
348
+ usageModel,
349
+ localPersistencePath,
350
+ liveReload,
351
+ assetPaths,
352
+ rules,
353
+ bindings.wasm_modules,
354
+ bindings.text_blobs,
355
+ bindings.data_blobs,
356
+ crons,
357
+ localProtocol,
358
+ localUpstream,
359
+ inspect,
360
+ logPrefix,
361
+ onReady,
362
+ enablePagesAssetsServiceBinding,
363
+ experimentalLocal,
364
+ ]);
365
+ return { inspectorUrl };
366
+ }
367
+
368
+ interface SetupBindingsProps {
369
+ wasm_modules: CfWasmModuleBindings | undefined;
370
+ text_blobs: CfTextBlobBindings | undefined;
371
+ data_blobs: CfDataBlobBindings | undefined;
372
+ durable_objects: { bindings: CfDurableObject[] } | undefined;
373
+ bundle: EsbuildBundle;
374
+ format: CfScriptFormat;
375
+ }
376
+
377
+ export function setupBindings({
378
+ wasm_modules,
379
+ text_blobs,
380
+ data_blobs,
381
+ durable_objects,
382
+ format,
383
+ bundle,
384
+ }: SetupBindingsProps) {
385
+ // the wasm_modules/text_blobs/data_blobs bindings are
386
+ // relative to process.cwd(), but the actual worker bundle
387
+ // is in the temp output directory; so we rewrite the paths to be absolute,
388
+ // letting miniflare resolve them correctly
389
+
390
+ // wasm
391
+ const wasmBindings: Record<string, string> = {};
392
+ for (const [name, filePath] of Object.entries(wasm_modules || {})) {
393
+ wasmBindings[name] = path.join(process.cwd(), filePath);
394
+ }
395
+
396
+ // text
397
+ const textBlobBindings: Record<string, string> = {};
398
+ for (const [name, filePath] of Object.entries(text_blobs || {})) {
399
+ textBlobBindings[name] = path.join(process.cwd(), filePath);
400
+ }
401
+
402
+ // data
403
+ const dataBlobBindings: Record<string, string> = {};
404
+ for (const [name, filePath] of Object.entries(data_blobs || {})) {
405
+ dataBlobBindings[name] = path.join(process.cwd(), filePath);
406
+ }
407
+
408
+ if (format === "service-worker") {
409
+ for (const { type, name } of bundle.modules) {
410
+ if (type === "compiled-wasm") {
411
+ // In service-worker format, .wasm modules are referenced by global identifiers,
412
+ // so we convert it here.
413
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
414
+ // characters with an underscore.
415
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
416
+ wasmBindings[identifier] = name;
417
+ } else if (type === "text") {
418
+ // In service-worker format, text modules are referenced by global identifiers,
419
+ // so we convert it here.
420
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
421
+ // characters with an underscore.
422
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
423
+ textBlobBindings[identifier] = name;
424
+ } else if (type === "buffer") {
425
+ // In service-worker format, data blobs are referenced by global identifiers,
426
+ // so we convert it here.
427
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
428
+ // characters with an underscore.
429
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
430
+ dataBlobBindings[identifier] = name;
431
+ }
432
+ }
433
+ }
434
+
435
+ const internalDurableObjects = (durable_objects?.bindings || []).filter(
436
+ (binding) => !binding.script_name
437
+ );
438
+ const externalDurableObjects = (durable_objects?.bindings || []).filter(
439
+ (binding) => binding.script_name
440
+ );
441
+ return {
442
+ internalDurableObjects,
443
+ externalDurableObjects,
444
+ wasmBindings,
445
+ textBlobBindings,
446
+ dataBlobBindings,
447
+ };
448
+ }
449
+
450
+ interface SetupMiniflareOptionsProps {
451
+ workerName: string | undefined;
452
+ port: number;
453
+ scriptPath: string;
454
+ localProtocol: "http" | "https";
455
+ ip: string;
456
+ format: CfScriptFormat;
457
+ rules: Config["rules"];
458
+ compatibilityDate: string;
459
+ compatibilityFlags: string[] | undefined;
460
+ usageModel: "bundled" | "unbound" | undefined;
461
+ kv_namespaces: CfKvNamespace[] | undefined;
462
+ queueBindings: CfQueue[] | undefined;
463
+ queueConsumers: Config["queues"]["consumers"];
464
+ r2_buckets: CfR2Bucket[] | undefined;
465
+ d1_databases: CfD1Database[] | undefined;
466
+ internalDurableObjects: CfDurableObject[];
467
+ externalDurableObjects: CfDurableObject[];
468
+ localPersistencePath: string | null;
469
+ liveReload: boolean;
470
+ assetPaths: AssetPaths | undefined;
471
+ vars: CfVars | undefined;
472
+ wasmBindings: Record<string, string>;
473
+ textBlobBindings: Record<string, string>;
474
+ dataBlobBindings: Record<string, string>;
475
+ crons: Config["triggers"]["crons"];
476
+ upstream: string | undefined;
477
+ logPrefix: string | undefined;
478
+ workerDefinitions: WorkerRegistry | undefined;
479
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
480
+ }
481
+
482
+ export function setupMiniflareOptions({
483
+ workerName,
484
+ port,
485
+ scriptPath,
486
+ localProtocol,
487
+ ip,
488
+ format,
489
+ rules,
490
+ compatibilityDate,
491
+ compatibilityFlags,
492
+ usageModel,
493
+ kv_namespaces,
494
+ queueBindings,
495
+ queueConsumers,
496
+ r2_buckets,
497
+ d1_databases,
498
+ internalDurableObjects,
499
+ externalDurableObjects,
500
+ localPersistencePath,
501
+ liveReload,
502
+ assetPaths,
503
+ vars,
504
+ wasmBindings,
505
+ textBlobBindings,
506
+ dataBlobBindings,
507
+ crons,
508
+ upstream,
509
+ logPrefix,
510
+ workerDefinitions,
511
+ enablePagesAssetsServiceBinding,
512
+ }: SetupMiniflareOptionsProps): {
513
+ miniflareCLIPath: string;
514
+ forkOptions: string[];
515
+ } {
516
+ // It's now getting _really_ messy now with Pages ASSETS binding outside and the external Durable Objects inside.
517
+ const options = {
518
+ name: workerName,
519
+ port,
520
+ scriptPath,
521
+ https: localProtocol === "https",
522
+ host: ip,
523
+ modules: format === "modules",
524
+ modulesRules: (rules || [])
525
+ .concat(DEFAULT_MODULE_RULES)
526
+ .map(({ type, globs: include, fallthrough }) => ({
527
+ type,
528
+ include,
529
+ fallthrough,
530
+ })),
531
+ compatibilityDate,
532
+ compatibilityFlags,
533
+ usageModel,
534
+ kvNamespaces: kv_namespaces?.map((kv) => kv.binding),
535
+ queueBindings: queueBindings?.map((queue) => {
536
+ return { name: queue.binding, queueName: queue.queue_name };
537
+ }),
538
+ queueConsumers: queueConsumers?.map((consumer) => {
539
+ const waitMs = consumer.max_batch_timeout
540
+ ? 1000 * consumer.max_batch_timeout
541
+ : undefined;
542
+ return {
543
+ queueName: consumer.queue,
544
+ maxBatchSize: consumer.max_batch_size,
545
+ maxWaitMs: waitMs,
546
+ maxRetries: consumer.max_retries,
547
+ deadLetterQueue: consumer.dead_letter_queue,
548
+ };
549
+ }),
550
+ r2Buckets: r2_buckets?.map((r2) => r2.binding),
551
+ durableObjects: Object.fromEntries(
552
+ internalDurableObjects.map((binding) => [
553
+ binding.name,
554
+ binding.class_name,
555
+ ])
556
+ ),
557
+ externalDurableObjects: Object.fromEntries(
558
+ externalDurableObjects
559
+ .map((binding) => {
560
+ const service =
561
+ workerDefinitions &&
562
+ workerDefinitions[binding.script_name as string];
563
+ if (!service) return [binding.name, undefined];
564
+
565
+ const name = service.durableObjects.find(
566
+ (durableObject) => durableObject.className === binding.class_name
567
+ )?.name;
568
+ if (!name) return [binding.name, undefined];
569
+
570
+ return [
571
+ binding.name,
572
+ {
573
+ name,
574
+ host: service.durableObjectsHost,
575
+ port: service.durableObjectsPort,
576
+ },
577
+ ];
578
+ })
579
+ .filter(([_, details]) => !!details)
580
+ ),
581
+ d1Databases: d1_databases?.map((db) => db.binding),
582
+ ...(localPersistencePath
583
+ ? {
584
+ cachePersist: path.join(localPersistencePath, "cache"),
585
+ durableObjectsPersist: path.join(localPersistencePath, "do"),
586
+ kvPersist: path.join(localPersistencePath, "kv"),
587
+ r2Persist: path.join(localPersistencePath, "r2"),
588
+ d1Persist: path.join(localPersistencePath, "d1"),
589
+ }
590
+ : {
591
+ // We mark these as true, so that they'll
592
+ // persist in the temp directory.
593
+ // This means they'll persist across a dev session,
594
+ // even if we change source and reload,
595
+ // and be deleted when the dev session ends
596
+ cachePersist: true,
597
+ durableObjectsPersist: true,
598
+ kvPersist: true,
599
+ r2Persist: true,
600
+ }),
601
+
602
+ liveReload,
603
+ sitePath: assetPaths?.assetDirectory
604
+ ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
605
+ : undefined,
606
+ siteInclude: assetPaths?.includePatterns.length
607
+ ? assetPaths?.includePatterns
608
+ : undefined,
609
+ siteExclude: assetPaths?.excludePatterns.length
610
+ ? assetPaths.excludePatterns
611
+ : undefined,
612
+ bindings: vars,
613
+ wasmBindings,
614
+ textBlobBindings,
615
+ dataBlobBindings,
616
+ sourceMap: true,
617
+ logUnhandledRejections: true,
618
+ crons,
619
+ upstream,
620
+ logLevel: logger.loggerLevel,
621
+ logOptions: logPrefix ? { prefix: logPrefix } : undefined,
622
+ enablePagesAssetsServiceBinding,
623
+ };
624
+ // The path to the Miniflare CLI assumes that this file is being run from
625
+ // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
626
+ // If either of those paths change this line needs updating.
627
+ const miniflareCLIPath = path.resolve(
628
+ getBasePath(),
629
+ "miniflare-dist/index.mjs"
630
+ );
631
+ const miniflareOptions = JSON.stringify(options, null);
632
+ const forkOptions = [miniflareOptions];
633
+ if (enablePagesAssetsServiceBinding) {
634
+ forkOptions.push(JSON.stringify(enablePagesAssetsServiceBinding));
635
+ }
636
+ return { miniflareCLIPath, forkOptions };
637
+ }
638
+
639
+ export function setupNodeOptions({
640
+ inspect,
641
+ ip,
642
+ inspectorPort,
643
+ }: {
644
+ inspect: boolean;
645
+ ip: string;
646
+ inspectorPort: number;
647
+ }) {
648
+ const nodeOptions = [
649
+ "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
650
+ "--no-warnings", // hide annoying Node warnings
651
+ // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
652
+ ];
653
+ if (inspect) {
654
+ nodeOptions.push("--inspect=" + `${ip}:${inspectorPort}`); // start Miniflare listening for a debugger to attach
655
+ }
656
+ return nodeOptions;
657
+ }
658
+
659
+ // Caching of the `npx-import`ed `@miniflare/tre` package
660
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
661
+ let Miniflare: typeof import("@miniflare/tre").Miniflare;
662
+
663
+ function arrayToObject(values: string[] = []): Record<string, string> {
664
+ return Object.fromEntries(values.map((value) => [value, value]));
665
+ }
666
+
667
+ export async function setupExperimentalLocal(
668
+ mf2Options: MiniflareOptions,
669
+ format: CfScriptFormat,
670
+ bundle: EsbuildBundle
671
+ ): Promise<Miniflare3Type> {
672
+ const options: Miniflare3Options = {
673
+ ...mf2Options,
674
+ // Miniflare 3 distinguishes between binding name and namespace/bucket IDs.
675
+ // For now, just use the same value as we did in Miniflare 2.
676
+ // TODO: use defined KV preview ID if any
677
+ kvNamespaces: arrayToObject(mf2Options.kvNamespaces),
678
+ r2Buckets: arrayToObject(mf2Options.r2Buckets),
679
+ };
680
+
681
+ if (format === "modules") {
682
+ // Manually specify all modules from the bundle. If we didn't do this,
683
+ // Miniflare 3 would try collect them automatically again itself.
684
+
685
+ // Resolve entrypoint relative to the temporary directory, ensuring
686
+ // path doesn't start with `..`, which causes issues in `workerd`.
687
+ // Also ensures other modules with relative names can be resolved.
688
+ const root = path.dirname(bundle.path);
689
+
690
+ assert.strictEqual(bundle.type, "esm");
691
+ options.modules = [
692
+ // Entrypoint
693
+ {
694
+ type: "ESModule",
695
+ path: path.relative(root, bundle.path),
696
+ contents: await readFile(bundle.path, "utf-8"),
697
+ },
698
+ // Misc (WebAssembly, etc, ...)
699
+ ...bundle.modules.map((module) => ({
700
+ type: ModuleTypeToRuleType[module.type ?? "esm"],
701
+ path: module.name,
702
+ contents: module.content,
703
+ })),
704
+ ];
705
+ }
706
+
707
+ logger.log("⎔ Starting an experimental local server...");
708
+
709
+ if (Miniflare === undefined) {
710
+ ({ Miniflare } = await npxImport<
711
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
712
+ typeof import("@miniflare/tre")
713
+ >("@miniflare/tre@next"));
714
+ }
715
+
716
+ return new Miniflare(options);
318
717
  }