wrangler 0.0.0-e978986 → 0.0.0-e98613f8

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 (304) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +162 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1456 -21
  5. package/package.json +191 -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 +56 -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 +3970 -3363
  13. package/src/__tests__/d1.test.ts +80 -0
  14. package/src/__tests__/delete.test.ts +263 -0
  15. package/src/__tests__/deployments.test.ts +91 -0
  16. package/src/__tests__/dev.test.tsx +1524 -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 +229 -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 +31 -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 +241 -233
  56. package/src/__tests__/init.test.ts +2884 -1536
  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__/logout.test.ts +47 -0
  61. package/src/__tests__/metrics.test.ts +450 -0
  62. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  63. package/src/__tests__/middleware.test.ts +726 -0
  64. package/src/__tests__/package-manager.test.ts +303 -303
  65. package/src/__tests__/pages-deployment-tail.test.ts +820 -0
  66. package/src/__tests__/pages.test.ts +2423 -638
  67. package/src/__tests__/parse.test.ts +252 -252
  68. package/src/__tests__/paths.test.ts +39 -0
  69. package/src/__tests__/publish.test.ts +7516 -5351
  70. package/src/__tests__/pubsub.test.ts +370 -0
  71. package/src/__tests__/queues.test.ts +522 -0
  72. package/src/__tests__/r2.test.ts +388 -228
  73. package/src/__tests__/route.test.ts +18 -18
  74. package/src/__tests__/secret.test.ts +622 -459
  75. package/src/__tests__/tail.test.ts +776 -567
  76. package/src/__tests__/test-old-node-version.js +31 -0
  77. package/src/__tests__/type-generation.test.ts +226 -0
  78. package/src/__tests__/user.test.ts +117 -119
  79. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  80. package/src/__tests__/validate-dev-props.test.ts +56 -0
  81. package/src/__tests__/version.test.ts +35 -0
  82. package/src/__tests__/whoami.test.tsx +264 -91
  83. package/src/__tests__/worker-namespace.test.ts +326 -0
  84. package/src/abort.d.ts +1 -1
  85. package/src/api/dev.ts +210 -0
  86. package/src/api/index.ts +2 -0
  87. package/src/bundle-reporter.tsx +68 -0
  88. package/src/bundle.ts +785 -162
  89. package/src/cfetch/index.ts +120 -81
  90. package/src/cfetch/internal.ts +209 -91
  91. package/src/cli.ts +23 -8
  92. package/src/config/config.ts +236 -195
  93. package/src/config/diagnostics.ts +61 -61
  94. package/src/config/environment.ts +498 -357
  95. package/src/config/index.ts +302 -193
  96. package/src/config/validation-helpers.ts +379 -357
  97. package/src/config/validation.ts +1931 -1367
  98. package/src/config-cache.ts +81 -41
  99. package/src/create-worker-preview.ts +239 -142
  100. package/src/create-worker-upload-form.ts +300 -238
  101. package/src/d1/backups.tsx +223 -0
  102. package/src/d1/constants.ts +2 -0
  103. package/src/d1/create.tsx +63 -0
  104. package/src/d1/delete.tsx +56 -0
  105. package/src/d1/execute.tsx +352 -0
  106. package/src/d1/formatTimeAgo.ts +14 -0
  107. package/src/d1/index.ts +101 -0
  108. package/src/d1/list.tsx +48 -0
  109. package/src/d1/migrations/apply.tsx +184 -0
  110. package/src/d1/migrations/create.tsx +77 -0
  111. package/src/d1/migrations/helpers.ts +147 -0
  112. package/src/d1/migrations/index.tsx +3 -0
  113. package/src/d1/migrations/list.tsx +79 -0
  114. package/src/d1/migrations/options.ts +18 -0
  115. package/src/d1/options.ts +22 -0
  116. package/src/d1/types.tsx +24 -0
  117. package/src/d1/utils.ts +48 -0
  118. package/src/delete.ts +108 -0
  119. package/src/deployments.ts +77 -0
  120. package/src/deprecated/index.ts +438 -0
  121. package/src/dev/dev-vars.ts +20 -17
  122. package/src/dev/dev.tsx +547 -352
  123. package/src/dev/get-local-persistence-path.tsx +31 -0
  124. package/src/dev/local.tsx +870 -298
  125. package/src/dev/remote.tsx +591 -215
  126. package/src/dev/start-server.ts +539 -0
  127. package/src/dev/use-esbuild.ts +183 -97
  128. package/src/dev/validate-dev-props.ts +31 -0
  129. package/src/dev-registry.tsx +201 -0
  130. package/src/dev.tsx +913 -0
  131. package/src/dialogs.tsx +132 -99
  132. package/src/dispatch-namespace.ts +207 -0
  133. package/src/durable.ts +87 -87
  134. package/src/entry.ts +235 -228
  135. package/src/environment-variables.ts +38 -23
  136. package/src/errors.ts +6 -6
  137. package/src/git-client.ts +135 -0
  138. package/src/global-wrangler-config-path.ts +26 -0
  139. package/src/https-options.ts +84 -80
  140. package/src/index.tsx +630 -2791
  141. package/src/init.ts +970 -0
  142. package/src/inspect.ts +698 -593
  143. package/src/intl-polyfill.d.ts +123 -123
  144. package/src/is-ci.ts +14 -0
  145. package/src/is-interactive.ts +16 -0
  146. package/src/kv/helpers.ts +430 -0
  147. package/src/kv/index.ts +596 -0
  148. package/src/logger.ts +67 -41
  149. package/src/metrics/index.ts +5 -0
  150. package/src/metrics/metrics-config.ts +239 -0
  151. package/src/metrics/metrics-dispatcher.ts +96 -0
  152. package/src/metrics/metrics-usage-headers.ts +24 -0
  153. package/src/metrics/send-event.ts +96 -0
  154. package/src/miniflare-cli/assets.ts +220 -0
  155. package/src/miniflare-cli/index.ts +205 -33
  156. package/src/miniflare-cli/request-context.ts +18 -18
  157. package/src/module-collection.ts +221 -212
  158. package/src/open-in-browser.ts +4 -6
  159. package/src/package-manager.ts +173 -128
  160. package/src/pages/build.tsx +270 -0
  161. package/src/pages/constants.ts +18 -0
  162. package/src/pages/deployment-tails.tsx +284 -0
  163. package/src/pages/deployments.tsx +84 -0
  164. package/src/pages/dev.tsx +706 -0
  165. package/src/pages/errors.ts +66 -0
  166. package/src/pages/functions/buildPlugin.ts +107 -0
  167. package/src/pages/functions/buildWorker.ts +166 -0
  168. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  169. package/src/pages/functions/filepath-routing.ts +189 -0
  170. package/src/pages/functions/identifiers.ts +78 -0
  171. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  172. package/src/pages/functions/routes-consolidation.ts +73 -0
  173. package/src/pages/functions/routes-transformation.test.ts +282 -0
  174. package/src/pages/functions/routes-transformation.ts +115 -0
  175. package/src/pages/functions/routes-validation.test.ts +403 -0
  176. package/src/pages/functions/routes-validation.ts +202 -0
  177. package/src/pages/functions/routes.ts +151 -0
  178. package/src/pages/functions.tsx +82 -0
  179. package/src/pages/hash.tsx +13 -0
  180. package/src/pages/index.tsx +102 -0
  181. package/src/pages/projects.tsx +169 -0
  182. package/src/pages/prompt-select-project.tsx +31 -0
  183. package/src/pages/publish.tsx +451 -0
  184. package/src/pages/types.ts +41 -0
  185. package/src/pages/upload.tsx +426 -0
  186. package/src/pages/utils.ts +23 -0
  187. package/src/parse.ts +209 -125
  188. package/src/paths.ts +53 -8
  189. package/src/proxy.ts +623 -394
  190. package/src/publish/index.ts +270 -0
  191. package/src/publish/publish.ts +1035 -0
  192. package/src/pubsub/index.ts +286 -0
  193. package/src/pubsub/pubsub-commands.tsx +624 -0
  194. package/src/queues/cli/commands/consumer/add.ts +71 -0
  195. package/src/queues/cli/commands/consumer/index.ts +22 -0
  196. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  197. package/src/queues/cli/commands/create.ts +25 -0
  198. package/src/queues/cli/commands/delete.ts +26 -0
  199. package/src/queues/cli/commands/index.ts +36 -0
  200. package/src/queues/cli/commands/list.ts +25 -0
  201. package/src/queues/client.ts +135 -0
  202. package/src/queues/utils.ts +18 -0
  203. package/src/r2/constants.ts +4 -0
  204. package/src/r2/helpers.ts +131 -0
  205. package/src/r2/index.ts +289 -0
  206. package/src/routes.ts +140 -0
  207. package/src/secret/index.ts +378 -0
  208. package/src/selfsigned.d.ts +23 -23
  209. package/src/sites.tsx +280 -203
  210. package/src/tail/createTail.ts +379 -0
  211. package/src/tail/filters.ts +108 -110
  212. package/src/tail/index.ts +211 -296
  213. package/src/tail/printing.ts +86 -46
  214. package/src/type-generation.ts +173 -0
  215. package/src/update-check.ts +11 -11
  216. package/src/user/access.ts +69 -0
  217. package/src/user/choose-account.tsx +69 -0
  218. package/src/user/env-vars.ts +46 -0
  219. package/src/user/generate-auth-url.ts +33 -0
  220. package/src/user/generate-random-state.ts +16 -0
  221. package/src/user/index.ts +3 -0
  222. package/src/user/user.tsx +1198 -0
  223. package/src/utils/collectKeyValues.ts +14 -0
  224. package/src/whoami.tsx +141 -42
  225. package/src/worker.ts +171 -106
  226. package/src/yargs-types.ts +24 -0
  227. package/src/zones.ts +191 -0
  228. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  229. package/templates/checked-fetch.js +17 -0
  230. package/templates/d1-beta-facade.js +205 -0
  231. package/templates/first-party-worker-module-facade.ts +18 -0
  232. package/templates/format-dev-errors.ts +32 -0
  233. package/templates/init-tests/test-jest-new-worker.js +25 -0
  234. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  235. package/templates/middleware/common.ts +62 -0
  236. package/templates/middleware/loader-modules.ts +84 -0
  237. package/templates/middleware/loader-sw.ts +227 -0
  238. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  239. package/templates/middleware/middleware-pretty-error.ts +40 -0
  240. package/templates/middleware/middleware-scheduled.ts +15 -0
  241. package/templates/new-worker-scheduled.js +4 -4
  242. package/templates/new-worker-scheduled.ts +16 -16
  243. package/templates/new-worker.js +3 -3
  244. package/templates/new-worker.ts +15 -15
  245. package/templates/no-op-worker.js +10 -0
  246. package/templates/pages-dev-pipeline.ts +28 -0
  247. package/templates/pages-dev-util.ts +52 -0
  248. package/templates/pages-shim.ts +9 -0
  249. package/templates/pages-template-plugin.ts +171 -0
  250. package/templates/pages-template-worker.ts +189 -0
  251. package/templates/serve-static-assets.ts +63 -0
  252. package/templates/service-bindings-module-facade.js +54 -0
  253. package/templates/service-bindings-sw-facade.js +42 -0
  254. package/templates/tsconfig.json +96 -95
  255. package/wrangler-dist/cli.d.ts +893 -0
  256. package/wrangler-dist/cli.js +146463 -108710
  257. package/pages/functions/buildPlugin.ts +0 -105
  258. package/pages/functions/buildWorker.ts +0 -151
  259. package/pages/functions/filepath-routing.ts +0 -189
  260. package/pages/functions/identifiers.ts +0 -78
  261. package/pages/functions/routes.ts +0 -156
  262. package/pages/functions/template-plugin.ts +0 -147
  263. package/pages/functions/template-worker.ts +0 -143
  264. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  265. package/src/kv.ts +0 -408
  266. package/src/miniflare-cli/enum-keys.ts +0 -17
  267. package/src/pages.tsx +0 -2027
  268. package/src/publish.ts +0 -583
  269. package/src/r2.ts +0 -50
  270. package/src/user.tsx +0 -1203
  271. package/templates/static-asset-facade.js +0 -47
  272. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  273. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  274. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  275. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  276. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  277. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  278. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  279. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  280. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  281. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  282. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  283. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  284. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  285. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  286. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  287. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  288. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  289. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  290. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  291. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  292. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  293. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  294. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  295. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  296. package/vendor/wrangler-mime/LICENSE +0 -21
  297. package/vendor/wrangler-mime/Mime.js +0 -97
  298. package/vendor/wrangler-mime/README.md +0 -187
  299. package/vendor/wrangler-mime/cli.js +0 -46
  300. package/vendor/wrangler-mime/index.js +0 -4
  301. package/vendor/wrangler-mime/lite.js +0 -4
  302. package/vendor/wrangler-mime/package.json +0 -52
  303. package/vendor/wrangler-mime/types/other.js +0 -1
  304. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/dev/local.tsx CHANGED
@@ -1,318 +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
13
  import { logger } from "../logger";
9
- import { DEFAULT_MODULE_RULES } from "../module-collection";
14
+ import {
15
+ DEFAULT_MODULE_RULES,
16
+ ModuleTypeToRuleType,
17
+ } from "../module-collection";
18
+ import { getBasePath } from "../paths";
10
19
  import { waitForPortToBeAvailable } from "../proxy";
20
+ import { requireAuth } from "../user";
11
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";
12
25
  import type { AssetPaths } from "../sites";
13
- 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";
14
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";
15
46
  import type { MiniflareOptions } from "miniflare";
47
+ import type { ChildProcess } from "node:child_process";
48
+ import type { RequestInit } from "undici";
16
49
 
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"];
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;
32
78
  }
33
79
 
80
+ type InspectorJSON = {
81
+ id: string;
82
+ title: string;
83
+ type: "node";
84
+ description: string;
85
+ webSocketDebuggerUrl: string;
86
+ devtoolsFrontendUrl: string;
87
+ devtoolsFrontendUrlCompat: string;
88
+ faviconUrl: string;
89
+ url: string;
90
+ }[];
91
+
34
92
  export function Local(props: LocalProps) {
35
- const { inspectorUrl } = useLocalWorker(props);
36
- useInspector({
37
- inspectorUrl,
38
- port: props.inspectorPort,
39
- logToTerminal: false,
40
- });
41
- return null;
93
+ const { inspectorUrl } = useLocalWorker(props);
94
+ useInspector({
95
+ inspectorUrl,
96
+ port: props.inspectorPort,
97
+ logToTerminal: props.experimentalLocal ?? false,
98
+ });
99
+ return null;
42
100
  }
43
101
 
44
102
  function useLocalWorker({
45
- name: workerName,
46
- bundle,
47
- format,
48
- compatibilityDate,
49
- compatibilityFlags,
50
- bindings,
51
- assetPaths,
52
- public: publicDirectory,
53
- port,
54
- rules,
55
- enableLocalPersistence,
56
- ip,
57
- crons,
103
+ name: workerName,
104
+ bundle,
105
+ format,
106
+ compatibilityDate,
107
+ compatibilityFlags,
108
+ usageModel,
109
+ bindings,
110
+ workerDefinitions,
111
+ assetPaths,
112
+ initialPort,
113
+ 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,
58
129
  }: 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 };
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"));
318
890
  }