wrangler 0.0.0-e30d1013 → 0.0.0-e3136f935

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