wrangler 0.0.0-e7a0cd5b → 0.0.0-e81b1611

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