wrangler 0.0.0-e3a458e → 0.0.0-e3a57616

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