wrangler 0.0.0-afdb7e49 → 0.0.0-b032bf2e

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