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