wrangler 0.0.0-e60dc909 → 0.0.0-e61444cb

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