wrangler 0.0.0-e2b7352 → 0.0.0-e2f5756c2

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 (174) hide show
  1. package/README.md +44 -25
  2. package/bin/wrangler.js +90 -36
  3. package/config-schema.json +3324 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +139 -100
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +170 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  27. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  28. package/templates/modules-watch-stub.js +4 -0
  29. package/templates/new-worker-scheduled.js +17 -0
  30. package/templates/new-worker-scheduled.ts +32 -0
  31. package/templates/new-worker.js +3 -3
  32. package/templates/new-worker.ts +22 -4
  33. package/templates/no-op-worker.js +10 -0
  34. package/templates/pages-dev-pipeline.ts +32 -0
  35. package/templates/pages-dev-util.ts +55 -0
  36. package/templates/pages-shim.ts +9 -0
  37. package/templates/pages-template-plugin.ts +190 -0
  38. package/templates/pages-template-worker.ts +198 -0
  39. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  40. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  41. package/templates/tsconfig-sanity.ts +11 -0
  42. package/templates/tsconfig.init.json +22 -0
  43. package/templates/tsconfig.json +6 -103
  44. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  45. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  46. package/wrangler-dist/ProxyWorker.js +241 -0
  47. package/wrangler-dist/ProxyWorker.js.map +6 -0
  48. package/wrangler-dist/cli.d.ts +26702 -0
  49. package/wrangler-dist/cli.js +164220 -135144
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/miniflare-dist/index.mjs +0 -79
  55. package/miniflare-dist/index.mjs.map +0 -7
  56. package/pages/functions/buildWorker.ts +0 -62
  57. package/pages/functions/filepath-routing.test.ts +0 -223
  58. package/pages/functions/filepath-routing.ts +0 -181
  59. package/pages/functions/identifiers.ts +0 -78
  60. package/pages/functions/routes.ts +0 -151
  61. package/pages/functions/template-worker.ts +0 -130
  62. package/src/__tests__/configuration.test.ts +0 -2820
  63. package/src/__tests__/dev.test.tsx +0 -541
  64. package/src/__tests__/guess-worker-format.test.ts +0 -68
  65. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  66. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  67. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  68. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  69. package/src/__tests__/helpers/mock-bin.ts +0 -36
  70. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  71. package/src/__tests__/helpers/mock-console.ts +0 -70
  72. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  73. package/src/__tests__/helpers/mock-kv.ts +0 -33
  74. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  75. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  76. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  77. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  78. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  79. package/src/__tests__/https-options.test.ts +0 -127
  80. package/src/__tests__/index.test.ts +0 -983
  81. package/src/__tests__/jest.setup.ts +0 -69
  82. package/src/__tests__/kv.test.ts +0 -1380
  83. package/src/__tests__/logout.test.ts +0 -52
  84. package/src/__tests__/package-manager.test.ts +0 -206
  85. package/src/__tests__/pages.test.ts +0 -82
  86. package/src/__tests__/parse.test.ts +0 -322
  87. package/src/__tests__/publish.test.ts +0 -3509
  88. package/src/__tests__/r2.test.ts +0 -198
  89. package/src/__tests__/route.test.ts +0 -45
  90. package/src/__tests__/secret.test.ts +0 -425
  91. package/src/__tests__/sentry.test.ts +0 -146
  92. package/src/__tests__/tail.test.ts +0 -638
  93. package/src/__tests__/whoami.test.tsx +0 -100
  94. package/src/bundle.ts +0 -155
  95. package/src/cfetch/index.ts +0 -104
  96. package/src/cfetch/internal.ts +0 -139
  97. package/src/cli.ts +0 -19
  98. package/src/config/README.md +0 -107
  99. package/src/config/config.ts +0 -218
  100. package/src/config/diagnostics.ts +0 -80
  101. package/src/config/environment.ts +0 -371
  102. package/src/config/index.ts +0 -62
  103. package/src/config/validation-helpers.ts +0 -554
  104. package/src/config/validation.ts +0 -1232
  105. package/src/create-worker-preview.ts +0 -166
  106. package/src/create-worker-upload-form.ts +0 -217
  107. package/src/dev/dev.tsx +0 -392
  108. package/src/dev/local.tsx +0 -232
  109. package/src/dev/remote.tsx +0 -203
  110. package/src/dev/use-esbuild.ts +0 -104
  111. package/src/dialogs.tsx +0 -77
  112. package/src/entry.ts +0 -240
  113. package/src/environment-variables.ts +0 -33
  114. package/src/https-options.ts +0 -122
  115. package/src/index.tsx +0 -2389
  116. package/src/inspect.ts +0 -617
  117. package/src/intl-polyfill.d.ts +0 -139
  118. package/src/kv.ts +0 -319
  119. package/src/miniflare-cli/README.md +0 -30
  120. package/src/miniflare-cli/enum-keys.ts +0 -17
  121. package/src/miniflare-cli/index.ts +0 -37
  122. package/src/module-collection.ts +0 -258
  123. package/src/open-in-browser.ts +0 -25
  124. package/src/package-manager.ts +0 -126
  125. package/src/pages.tsx +0 -1061
  126. package/src/parse.ts +0 -183
  127. package/src/paths.ts +0 -26
  128. package/src/proxy.ts +0 -440
  129. package/src/publish.ts +0 -350
  130. package/src/r2.ts +0 -50
  131. package/src/reporting.ts +0 -131
  132. package/src/selfsigned.d.ts +0 -29
  133. package/src/sites.tsx +0 -280
  134. package/src/tail/filters.ts +0 -279
  135. package/src/tail/index.ts +0 -299
  136. package/src/tail/printing.ts +0 -62
  137. package/src/user.tsx +0 -1127
  138. package/src/whoami.tsx +0 -69
  139. package/src/worker.ts +0 -163
  140. package/templates/static-asset-facade.js +0 -47
  141. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  142. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  143. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  144. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  145. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  146. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  147. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  148. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  149. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  150. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  151. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  152. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  153. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  154. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  155. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  156. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  157. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  158. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  159. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  160. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  161. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  162. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  163. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  164. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  165. package/vendor/wrangler-mime/LICENSE +0 -21
  166. package/vendor/wrangler-mime/Mime.js +0 -97
  167. package/vendor/wrangler-mime/README.md +0 -187
  168. package/vendor/wrangler-mime/cli.js +0 -46
  169. package/vendor/wrangler-mime/index.js +0 -4
  170. package/vendor/wrangler-mime/lite.js +0 -4
  171. package/vendor/wrangler-mime/package.json +0 -52
  172. package/vendor/wrangler-mime/types/other.js +0 -1
  173. package/vendor/wrangler-mime/types/standard.js +0 -1
  174. package/wrangler-dist/cli.js.map +0 -7
package/src/dev/dev.tsx DELETED
@@ -1,392 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { watch } from "chokidar";
3
- import clipboardy from "clipboardy";
4
- import commandExists from "command-exists";
5
- import { Box, Text, useApp, useInput, useStdin } from "ink";
6
- import React, { useState, useEffect, useRef } from "react";
7
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
8
- import onExit from "signal-exit";
9
- import tmp from "tmp-promise";
10
- import { fetch } from "undici";
11
- import { runCustomBuild } from "../entry";
12
- import openInBrowser from "../open-in-browser";
13
- import { reportError } from "../reporting";
14
- import { getAPIToken } from "../user";
15
- import { Local } from "./local";
16
- import { Remote } from "./remote";
17
- import { useEsbuild } from "./use-esbuild";
18
- import type { Config } from "../config";
19
- import type { Entry } from "../entry";
20
- import type { AssetPaths } from "../sites";
21
- import type { CfWorkerInit } from "../worker";
22
- import type { EsbuildBundle } from "./use-esbuild";
23
-
24
- export type DevProps = {
25
- name?: string;
26
- entry: Entry;
27
- port: number;
28
- ip: string;
29
- inspectorPort: number;
30
- rules: Config["rules"];
31
- accountId: undefined | string;
32
- initialMode: "local" | "remote";
33
- jsxFactory: undefined | string;
34
- jsxFragment: undefined | string;
35
- tsconfig: string | undefined;
36
- upstreamProtocol: "https" | "http";
37
- localProtocol: "https" | "http";
38
- enableLocalPersistence: boolean;
39
- bindings: CfWorkerInit["bindings"];
40
- public: undefined | string;
41
- assetPaths: undefined | AssetPaths;
42
- compatibilityDate: undefined | string;
43
- compatibilityFlags: undefined | string[];
44
- usageModel: undefined | "bundled" | "unbound";
45
- build: {
46
- command?: undefined | string;
47
- cwd?: undefined | string;
48
- watch_dir?: undefined | string;
49
- };
50
- env: string | undefined;
51
- legacyEnv: boolean;
52
- zone:
53
- | {
54
- id: string;
55
- host: string;
56
- }
57
- | undefined;
58
- };
59
-
60
- export function DevImplementation(props: DevProps): JSX.Element {
61
- const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
62
- const directory = useTmpDir();
63
-
64
- useCustomBuild(props.entry, props.build);
65
-
66
- if (props.public && props.entry.format === "service-worker") {
67
- throw new Error(
68
- "You cannot use the service worker format with a `public` directory."
69
- );
70
- }
71
-
72
- if (props.bindings.wasm_modules && props.entry.format === "modules") {
73
- throw new Error(
74
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
75
- );
76
- }
77
-
78
- if (props.bindings.text_blobs && props.entry.format === "modules") {
79
- throw new Error(
80
- "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[build.upload.rules]` in your wrangler.toml"
81
- );
82
- }
83
-
84
- const bundle = useEsbuild({
85
- entry: props.entry,
86
- destination: directory,
87
- staticRoot: props.public,
88
- jsxFactory: props.jsxFactory,
89
- rules: props.rules,
90
- jsxFragment: props.jsxFragment,
91
- serveAssetsFromWorker: !!props.public,
92
- tsconfig: props.tsconfig,
93
- });
94
-
95
- // only load the UI if we're running in a supported environment
96
- const { isRawModeSupported } = useStdin();
97
- return isRawModeSupported ? (
98
- <InteractiveDevSession {...props} bundle={bundle} apiToken={apiToken} />
99
- ) : (
100
- <DevSession
101
- {...props}
102
- bundle={bundle}
103
- apiToken={apiToken}
104
- local={props.initialMode === "local"}
105
- />
106
- );
107
- }
108
-
109
- type InteractiveDevSessionProps = DevProps & {
110
- apiToken: string | undefined;
111
- bundle: EsbuildBundle | undefined;
112
- };
113
-
114
- function InteractiveDevSession(props: InteractiveDevSessionProps) {
115
- const toggles = useHotkeys(
116
- {
117
- local: props.initialMode === "local",
118
- tunnel: false,
119
- },
120
- props.port,
121
- props.ip,
122
- props.inspectorPort,
123
- props.localProtocol
124
- );
125
-
126
- useTunnel(toggles.tunnel);
127
-
128
- return (
129
- <>
130
- <DevSession {...props} local={toggles.local} />
131
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
132
- <Text>
133
- {`B to open a browser, D to open Devtools, L to ${
134
- toggles.local ? "turn off" : "turn on"
135
- } local mode, X to exit`}
136
- </Text>
137
- </Box>
138
- </>
139
- );
140
- }
141
-
142
- type DevSessionProps = InteractiveDevSessionProps & { local: boolean };
143
-
144
- function DevSession(props: DevSessionProps) {
145
- return props.local ? (
146
- <Local
147
- name={props.name}
148
- bundle={props.bundle}
149
- format={props.entry.format}
150
- compatibilityDate={props.compatibilityDate}
151
- compatibilityFlags={props.compatibilityFlags}
152
- bindings={props.bindings}
153
- assetPaths={props.assetPaths}
154
- public={props.public}
155
- port={props.port}
156
- ip={props.ip}
157
- rules={props.rules}
158
- inspectorPort={props.inspectorPort}
159
- enableLocalPersistence={props.enableLocalPersistence}
160
- />
161
- ) : (
162
- <Remote
163
- name={props.name}
164
- bundle={props.bundle}
165
- format={props.entry.format}
166
- accountId={props.accountId}
167
- apiToken={props.apiToken}
168
- bindings={props.bindings}
169
- assetPaths={props.assetPaths}
170
- public={props.public}
171
- port={props.port}
172
- ip={props.ip}
173
- localProtocol={props.localProtocol}
174
- inspectorPort={props.inspectorPort}
175
- compatibilityDate={props.compatibilityDate}
176
- compatibilityFlags={props.compatibilityFlags}
177
- usageModel={props.usageModel}
178
- env={props.env}
179
- legacyEnv={props.legacyEnv}
180
- zone={props.zone}
181
- />
182
- );
183
- }
184
-
185
- export interface DirectorySyncResult {
186
- name: string;
187
- removeCallback: () => void;
188
- }
189
-
190
- function useTmpDir(): string | undefined {
191
- const [directory, setDirectory] = useState<DirectorySyncResult>();
192
- const handleError = useErrorHandler();
193
- useEffect(() => {
194
- let dir: DirectorySyncResult | undefined;
195
- try {
196
- dir = tmp.dirSync({ unsafeCleanup: true });
197
- setDirectory(dir);
198
- return;
199
- } catch (err) {
200
- console.error("failed to create tmp dir");
201
- handleError(err);
202
- }
203
- return () => {
204
- dir?.removeCallback();
205
- };
206
- }, [handleError]);
207
- return directory?.name;
208
- }
209
-
210
- function useCustomBuild(
211
- expectedEntry: Entry,
212
- build: {
213
- command?: undefined | string;
214
- cwd?: undefined | string;
215
- watch_dir?: undefined | string;
216
- }
217
- ): void {
218
- useEffect(() => {
219
- if (!build.command) return;
220
- let watcher: ReturnType<typeof watch> | undefined;
221
- if (build.watch_dir) {
222
- watcher = watch(build.watch_dir, {
223
- persistent: true,
224
- ignoreInitial: true,
225
- }).on("all", (_event, filePath) => {
226
- //TODO: we should buffer requests to the proxy until this completes
227
- console.log(`The file ${filePath} changed, restarting build...`);
228
- runCustomBuild(expectedEntry.file, build).catch((err) => {
229
- console.error("Custom build failed:", err);
230
- });
231
- });
232
- }
233
-
234
- return () => {
235
- watcher?.close();
236
- };
237
- }, [build, expectedEntry.file]);
238
- }
239
-
240
- function sleep(period: number) {
241
- return new Promise((resolve) => setTimeout(resolve, period));
242
- }
243
- const SLEEP_DURATION = 2000;
244
- // really need a first class api for this
245
- const hostNameRegex = /userHostname="(.*)"/g;
246
- async function findTunnelHostname() {
247
- let hostName: string | undefined;
248
- while (!hostName) {
249
- try {
250
- const resp = await fetch("http://localhost:8789/metrics");
251
- const data = await resp.text();
252
- const matches = Array.from(data.matchAll(hostNameRegex));
253
- hostName = matches[0][1];
254
- } catch (err) {
255
- await sleep(SLEEP_DURATION);
256
- }
257
- }
258
- return hostName;
259
- }
260
-
261
- /**
262
- * Create a tunnel to the remote worker.
263
- * We've disabled this for now until we figure out a better user experience.
264
- */
265
- function useTunnel(toggle: boolean) {
266
- const tunnel = useRef<ReturnType<typeof spawn>>();
267
- const removeSignalExitListener = useRef<() => void>();
268
- // TODO: test if cloudflared is available, if not
269
- // point them to a url where they can get docs to install it
270
- useEffect(() => {
271
- async function startTunnel() {
272
- if (toggle) {
273
- try {
274
- await commandExists("cloudflared");
275
- } catch (e) {
276
- console.error(
277
- "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
278
- );
279
- return;
280
- }
281
- console.log("⎔ Starting a tunnel...");
282
- tunnel.current = spawn("cloudflared", [
283
- "tunnel",
284
- "--url",
285
- "http://localhost:8787",
286
- "--metrics",
287
- "localhost:8789",
288
- ]);
289
-
290
- tunnel.current.on("close", (code) => {
291
- if (code) {
292
- console.log(`Tunnel process exited with code ${code}`);
293
- }
294
- });
295
-
296
- removeSignalExitListener.current = onExit((_code, _signal) => {
297
- console.log("⎔ Shutting down local tunnel.");
298
- tunnel.current?.kill();
299
- tunnel.current = undefined;
300
- });
301
-
302
- const hostName = await findTunnelHostname();
303
- await clipboardy.write(hostName);
304
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
305
- }
306
- }
307
-
308
- startTunnel().catch(async (err) => {
309
- console.error("tunnel:", err);
310
- await reportError(err);
311
- });
312
-
313
- return () => {
314
- if (tunnel.current) {
315
- console.log("⎔ Shutting down tunnel.");
316
- tunnel.current?.kill();
317
- tunnel.current = undefined;
318
- removeSignalExitListener.current && removeSignalExitListener.current();
319
- removeSignalExitListener.current = undefined;
320
- }
321
- };
322
- }, [toggle]);
323
- }
324
-
325
- type useHotkeysInitialState = {
326
- local: boolean;
327
- tunnel: boolean;
328
- };
329
- function useHotkeys(
330
- initial: useHotkeysInitialState,
331
- port: number,
332
- ip: string,
333
- inspectorPort: number,
334
- localProtocol: "http" | "https"
335
- ) {
336
- // UGH, we should put port in context instead
337
- const [toggles, setToggles] = useState(initial);
338
- useInput(
339
- async (
340
- input,
341
- // eslint-disable-next-line unused-imports/no-unused-vars
342
- key
343
- ) => {
344
- switch (input.toLowerCase()) {
345
- // open browser
346
- case "b": {
347
- await openInBrowser(`${localProtocol}://${ip}:${port}`);
348
- break;
349
- }
350
- // toggle inspector
351
- case "d": {
352
- await openInBrowser(
353
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`,
354
- { forceChromium: true }
355
- );
356
- break;
357
- }
358
- // toggle local
359
- case "l":
360
- setToggles((previousToggles) => ({
361
- ...previousToggles,
362
- local: !previousToggles.local,
363
- }));
364
- break;
365
- // shut down
366
- case "q":
367
- case "x":
368
- process.exit(0);
369
- break;
370
- default:
371
- // nothing?
372
- break;
373
- }
374
- }
375
- );
376
- return toggles;
377
- }
378
-
379
- function ErrorFallback(props: { error: Error }) {
380
- const { exit } = useApp();
381
- useEffect(() => exit(props.error));
382
- return (
383
- <>
384
- <Text>Something went wrong:</Text>
385
- <Text>{props.error.stack}</Text>
386
- </>
387
- );
388
- }
389
-
390
- export default withErrorBoundary(DevImplementation, {
391
- FallbackComponent: ErrorFallback,
392
- });
package/src/dev/local.tsx DELETED
@@ -1,232 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { realpathSync } from "node:fs";
3
- import { writeFile } from "node:fs/promises";
4
- import path from "node:path";
5
- import { useState, useEffect, useRef } from "react";
6
- import onExit from "signal-exit";
7
- import useInspector from "../inspect";
8
- import { DEFAULT_MODULE_RULES } from "../module-collection";
9
- import { waitForPortToBeAvailable } from "../proxy";
10
- import type { Config } from "../config";
11
- import type { AssetPaths } from "../sites";
12
- import type { CfWorkerInit, CfScriptFormat } from "../worker";
13
- import type { EsbuildBundle } from "./use-esbuild";
14
- import type { MiniflareOptions } from "miniflare";
15
-
16
- interface LocalProps {
17
- name: undefined | string;
18
- bundle: EsbuildBundle | undefined;
19
- format: CfScriptFormat | undefined;
20
- compatibilityDate: string | undefined;
21
- compatibilityFlags: undefined | string[];
22
- bindings: CfWorkerInit["bindings"];
23
- assetPaths: undefined | AssetPaths;
24
- public: undefined | string;
25
- port: number;
26
- ip: string;
27
- rules: Config["rules"];
28
- inspectorPort: number;
29
- enableLocalPersistence: boolean;
30
- }
31
-
32
- export function Local(props: LocalProps) {
33
- const { inspectorUrl } = useLocalWorker(props);
34
- useInspector({
35
- inspectorUrl,
36
- port: props.inspectorPort,
37
- logToTerminal: false,
38
- });
39
- return null;
40
- }
41
-
42
- function useLocalWorker({
43
- name: workerName,
44
- bundle,
45
- format,
46
- compatibilityDate,
47
- compatibilityFlags,
48
- bindings,
49
- assetPaths,
50
- public: publicDirectory,
51
- port,
52
- rules,
53
- enableLocalPersistence,
54
- ip,
55
- }: LocalProps) {
56
- // TODO: pass vars via command line
57
- const local = useRef<ReturnType<typeof spawn>>();
58
- const removeSignalExitListener = useRef<() => void>();
59
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
60
- useEffect(() => {
61
- async function startLocalWorker() {
62
- if (!bundle || !format) return;
63
-
64
- // port for the worker
65
- await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
66
-
67
- if (publicDirectory) {
68
- throw new Error(
69
- '⎔ A "public" folder is not yet supported in local mode.'
70
- );
71
- }
72
-
73
- // In local mode, we want to copy all referenced modules into
74
- // the output bundle directory before starting up
75
- for (const module of bundle.modules) {
76
- await writeFile(
77
- path.join(path.dirname(bundle.path), module.name),
78
- module.content
79
- );
80
- }
81
-
82
- const scriptPath = realpathSync(bundle.path);
83
-
84
- const wasmBindings = { ...bindings.wasm_modules };
85
- if (format === "service-worker") {
86
- for (const { type, name } of bundle.modules) {
87
- if (type === "compiled-wasm") {
88
- // In service-worker format, .wasm modules are referenced by global identifiers,
89
- // so we convert it here.
90
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
91
- // characters with an underscore.
92
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
93
- wasmBindings[identifier] = name;
94
- }
95
- }
96
- }
97
-
98
- const options: MiniflareOptions = {
99
- name: workerName,
100
- port,
101
- scriptPath,
102
- host: ip,
103
- modules: format === "modules",
104
- modulesRules: (rules || [])
105
- .concat(DEFAULT_MODULE_RULES)
106
- .map(({ type, globs: include, fallthrough }) => ({
107
- type,
108
- include,
109
- fallthrough,
110
- })),
111
- compatibilityDate,
112
- compatibilityFlags,
113
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
114
- kvPersist: enableLocalPersistence,
115
- durableObjects: Object.fromEntries(
116
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
117
- (value) => [value.name, value.class_name]
118
- )
119
- ),
120
- durableObjectsPersist: enableLocalPersistence,
121
- cachePersist: enableLocalPersistence,
122
- sitePath: assetPaths?.assetDirectory
123
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
124
- : undefined,
125
- siteInclude: assetPaths?.includePatterns.length
126
- ? assetPaths?.includePatterns
127
- : undefined,
128
- siteExclude: assetPaths?.excludePatterns.length
129
- ? assetPaths.excludePatterns
130
- : undefined,
131
- bindings: bindings.vars,
132
- wasmBindings,
133
- sourceMap: true,
134
- logUnhandledRejections: true,
135
- };
136
-
137
- // The path to the Miniflare CLI assumes that this file is being run from
138
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
139
- // If either of those paths change this line needs updating.
140
- const miniflareCLIPath = path.resolve(
141
- __dirname,
142
- "../miniflare-dist/index.mjs"
143
- );
144
- const optionsArg = JSON.stringify(options, null);
145
-
146
- console.log("⎔ Starting a local server...");
147
- local.current = spawn(
148
- "node",
149
- [
150
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
151
- "--no-warnings", // hide annoying Node warnings
152
- "--inspect", // start Miniflare listening for a debugger to attach
153
- miniflareCLIPath,
154
- optionsArg,
155
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
156
- ],
157
- {
158
- cwd: path.dirname(scriptPath),
159
- }
160
- );
161
-
162
- local.current.on("close", (code) => {
163
- if (code) {
164
- console.log(`Miniflare process exited with code ${code}`);
165
- }
166
- });
167
-
168
- local.current.stdout?.on("data", (data: Buffer) => {
169
- console.log(`${data.toString()}`);
170
- });
171
-
172
- local.current.stderr?.on("data", (data: Buffer) => {
173
- console.error(`${data.toString()}`);
174
- const matches =
175
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
176
- data.toString()
177
- );
178
- if (matches) {
179
- setInspectorUrl(matches[1]);
180
- }
181
- });
182
-
183
- local.current.on("exit", (code) => {
184
- if (code) {
185
- console.error(`Miniflare process exited with code ${code}`);
186
- }
187
- });
188
-
189
- local.current.on("error", (error: Error) => {
190
- console.error(`Miniflare process failed to spawn`);
191
- console.error(error);
192
- });
193
-
194
- removeSignalExitListener.current = onExit((_code, _signal) => {
195
- console.log("⎔ Shutting down local server.");
196
- local.current?.kill();
197
- local.current = undefined;
198
- });
199
- }
200
-
201
- startLocalWorker().catch((err) => {
202
- console.error("local worker:", err);
203
- });
204
-
205
- return () => {
206
- if (local.current) {
207
- console.log("⎔ Shutting down local server.");
208
- local.current?.kill();
209
- local.current = undefined;
210
- removeSignalExitListener.current && removeSignalExitListener.current();
211
- removeSignalExitListener.current = undefined;
212
- }
213
- };
214
- }, [
215
- bundle,
216
- workerName,
217
- format,
218
- port,
219
- ip,
220
- bindings.durable_objects?.bindings,
221
- bindings.kv_namespaces,
222
- bindings.vars,
223
- compatibilityDate,
224
- compatibilityFlags,
225
- enableLocalPersistence,
226
- assetPaths,
227
- publicDirectory,
228
- rules,
229
- bindings.wasm_modules,
230
- ]);
231
- return { inspectorUrl };
232
- }