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