wrangler 0.0.0-e61907d → 0.0.0-e9ab55a

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 (42) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +36 -2
  3. package/import_meta_url.js +3 -0
  4. package/package.json +62 -19
  5. package/pages/functions/buildWorker.ts +62 -0
  6. package/pages/functions/filepath-routing.test.ts +39 -0
  7. package/pages/functions/filepath-routing.ts +228 -0
  8. package/pages/functions/identifiers.ts +78 -0
  9. package/pages/functions/routes.ts +158 -0
  10. package/pages/functions/template-worker.ts +136 -0
  11. package/src/__tests__/clipboardy-mock.js +4 -0
  12. package/src/__tests__/dev.test.tsx +67 -0
  13. package/src/__tests__/index.test.ts +287 -0
  14. package/src/__tests__/jest.setup.ts +22 -0
  15. package/src/__tests__/kv.test.ts +1126 -0
  16. package/src/__tests__/mock-cfetch.ts +171 -0
  17. package/src/__tests__/mock-dialogs.ts +65 -0
  18. package/src/__tests__/publish.test.ts +102 -0
  19. package/src/__tests__/run-in-tmp.ts +19 -0
  20. package/src/__tests__/run-wrangler.ts +32 -0
  21. package/src/api/form_data.ts +131 -0
  22. package/src/api/preview.ts +128 -0
  23. package/src/api/worker.ts +155 -0
  24. package/src/cfetch/index.ts +102 -0
  25. package/src/cfetch/internal.ts +69 -0
  26. package/src/cli.ts +9 -0
  27. package/src/config.ts +646 -0
  28. package/src/dev.tsx +784 -0
  29. package/src/dialogs.tsx +77 -0
  30. package/src/index.tsx +1928 -0
  31. package/src/inspect.ts +543 -0
  32. package/src/kv.tsx +276 -0
  33. package/src/module-collection.ts +64 -0
  34. package/src/pages.tsx +1040 -0
  35. package/src/proxy.ts +302 -0
  36. package/src/publish.ts +382 -0
  37. package/src/sites.tsx +118 -0
  38. package/src/tail.tsx +73 -0
  39. package/src/user.tsx +1027 -0
  40. package/wrangler-dist/{index_node.js → cli.js} +57871 -35979
  41. package/wrangler-dist/cli.js.map +7 -0
  42. package/wrangler-dist/index_node.js.map +0 -7
package/src/dev.tsx ADDED
@@ -0,0 +1,784 @@
1
+ import esbuild from "esbuild";
2
+ import assert from "node:assert";
3
+ import { spawn } from "node:child_process";
4
+ import { readFile } from "node:fs/promises";
5
+ import { existsSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { Box, Text, useApp, useInput } from "ink";
8
+ import { watch } from "chokidar";
9
+ import clipboardy from "clipboardy";
10
+ import commandExists from "command-exists";
11
+ import { execa } from "execa";
12
+ import fetch from "node-fetch";
13
+ import open from "open";
14
+ import React, { useState, useEffect, useRef } from "react";
15
+ import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
16
+ import onExit from "signal-exit";
17
+ import tmp from "tmp-promise";
18
+ import type { DirectoryResult } from "tmp-promise";
19
+
20
+ import type { CfPreviewToken } from "./api/preview";
21
+ import type { CfModule } from "./api/worker";
22
+ import { createWorker } from "./api/worker";
23
+ import type { CfWorkerInit } from "./api/worker";
24
+
25
+ import useInspector from "./inspect";
26
+ import makeModuleCollector from "./module-collection";
27
+ import { usePreviewServer } from "./proxy";
28
+ import { syncAssets } from "./sites";
29
+ import { getAPIToken } from "./user";
30
+
31
+ type CfScriptFormat = undefined | "modules" | "service-worker";
32
+
33
+ export type DevProps = {
34
+ name?: string;
35
+ entry: string;
36
+ port?: number;
37
+ format: CfScriptFormat;
38
+ accountId: undefined | string;
39
+ initialMode: "local" | "remote";
40
+ jsxFactory: undefined | string;
41
+ jsxFragment: undefined | string;
42
+ bindings: CfWorkerInit["bindings"];
43
+ public: undefined | string;
44
+ site: undefined | string;
45
+ compatibilityDate: undefined | string;
46
+ compatibilityFlags: undefined | string[];
47
+ usageModel: undefined | "bundled" | "unbound";
48
+ buildCommand: {
49
+ command?: undefined | string;
50
+ cwd?: undefined | string;
51
+ watch_dir?: undefined | string;
52
+ };
53
+ };
54
+
55
+ function Dev(props: DevProps): JSX.Element {
56
+ if (props.public && props.format === "service-worker") {
57
+ throw new Error(
58
+ "You cannot use the service worker format with a `public` directory."
59
+ );
60
+ }
61
+ const port = props.port ?? 8787;
62
+ const apiToken = getAPIToken();
63
+ const directory = useTmpDir();
64
+
65
+ // if there isn't a build command, we just return the entry immediately
66
+ // ideally there would be a conditional here, but the rules of hooks
67
+ // kinda forbid that, so we thread the entry through useCustomBuild
68
+ const entry = useCustomBuild(props.entry, props.buildCommand);
69
+
70
+ const bundle = useEsbuild({
71
+ entry,
72
+ destination: directory,
73
+ staticRoot: props.public,
74
+ jsxFactory: props.jsxFactory,
75
+ jsxFragment: props.jsxFragment,
76
+ });
77
+ if (bundle && bundle.type === "commonjs" && !props.format && props.public) {
78
+ throw new Error(
79
+ "You cannot use the service worker format with a `public` directory."
80
+ );
81
+ }
82
+
83
+ const toggles = useHotkeys(
84
+ {
85
+ local: props.initialMode === "local",
86
+ tunnel: false,
87
+ },
88
+ port
89
+ );
90
+
91
+ useTunnel(toggles.tunnel);
92
+
93
+ return (
94
+ <>
95
+ {toggles.local ? (
96
+ <Local
97
+ name={props.name}
98
+ bundle={bundle}
99
+ format={props.format}
100
+ bindings={props.bindings}
101
+ site={props.site}
102
+ public={props.public}
103
+ port={port}
104
+ />
105
+ ) : (
106
+ <Remote
107
+ name={props.name}
108
+ bundle={bundle}
109
+ format={props.format}
110
+ accountId={props.accountId}
111
+ apiToken={apiToken}
112
+ bindings={props.bindings}
113
+ site={props.site}
114
+ public={props.public}
115
+ port={port}
116
+ compatibilityDate={props.compatibilityDate}
117
+ compatibilityFlags={props.compatibilityFlags}
118
+ usageModel={props.usageModel}
119
+ />
120
+ )}
121
+ <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
122
+ <Text>
123
+ {`B to open a browser, D to open Devtools, S to ${
124
+ toggles.tunnel ? "turn off" : "turn on"
125
+ } (experimental) sharing, L to ${
126
+ toggles.local ? "turn off" : "turn on"
127
+ } local mode, X to exit`}
128
+ </Text>
129
+ </Box>
130
+ </>
131
+ );
132
+ }
133
+
134
+ function Remote(props: {
135
+ name: undefined | string;
136
+ bundle: EsbuildBundle | undefined;
137
+ format: CfScriptFormat;
138
+ public: undefined | string;
139
+ site: undefined | string;
140
+ port: number;
141
+ accountId: undefined | string;
142
+ apiToken: undefined | string;
143
+ bindings: CfWorkerInit["bindings"];
144
+ compatibilityDate: string | undefined;
145
+ compatibilityFlags: undefined | string[];
146
+ usageModel: undefined | "bundled" | "unbound";
147
+ }) {
148
+ assert(props.accountId, "accountId is required");
149
+ assert(props.apiToken, "apiToken is required");
150
+ const previewToken = useWorker({
151
+ name: props.name,
152
+ bundle: props.bundle,
153
+ format: props.format,
154
+ modules: props.bundle ? props.bundle.modules : [],
155
+ accountId: props.accountId,
156
+ apiToken: props.apiToken,
157
+ bindings: props.bindings,
158
+ sitesFolder: props.site,
159
+ port: props.port,
160
+ compatibilityDate: props.compatibilityDate,
161
+ compatibilityFlags: props.compatibilityFlags,
162
+ usageModel: props.usageModel,
163
+ });
164
+
165
+ usePreviewServer({
166
+ previewToken,
167
+ publicRoot: props.public,
168
+ port: props.port,
169
+ });
170
+
171
+ useInspector({
172
+ inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
173
+ port: 9229,
174
+ logToTerminal: true,
175
+ });
176
+ return null;
177
+ }
178
+ function Local(props: {
179
+ name: undefined | string;
180
+ bundle: EsbuildBundle | undefined;
181
+ format: CfScriptFormat;
182
+ bindings: CfWorkerInit["bindings"];
183
+ public: undefined | string;
184
+ site: undefined | string;
185
+ port: number;
186
+ }) {
187
+ const { inspectorUrl } = useLocalWorker({
188
+ name: props.name,
189
+ bundle: props.bundle,
190
+ format: props.format,
191
+ bindings: props.bindings,
192
+ port: props.port,
193
+ });
194
+ useInspector({ inspectorUrl, port: 9229, logToTerminal: false });
195
+ return null;
196
+ }
197
+
198
+ function useLocalWorker(props: {
199
+ name: undefined | string;
200
+ bundle: EsbuildBundle | undefined;
201
+ format: CfScriptFormat;
202
+ bindings: CfWorkerInit["bindings"];
203
+ port: number;
204
+ }) {
205
+ // TODO: pass vars via command line
206
+ const { bundle, format, bindings, port } = props;
207
+ const local = useRef<ReturnType<typeof spawn>>();
208
+ const removeSignalExitListener = useRef<() => void>();
209
+ const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
210
+ useEffect(() => {
211
+ async function startLocalWorker() {
212
+ if (!bundle) return;
213
+ if (format === "modules" && bundle.type === "commonjs") {
214
+ console.error("⎔ Cannot use modules with a commonjs bundle.");
215
+ // TODO: a much better error message here, with what to do next
216
+ return;
217
+ }
218
+ if (format === "service-worker" && bundle.type !== "esm") {
219
+ console.error("⎔ Cannot use service-worker with a esm bundle.");
220
+ // TODO: a much better error message here, with what to do next
221
+ return;
222
+ }
223
+
224
+ console.log("⎔ Starting a local server...");
225
+ // TODO: just use execa for this
226
+ local.current = spawn("node", [
227
+ "--experimental-vm-modules",
228
+ "--inspect",
229
+ require.resolve("miniflare/cli"),
230
+ bundle.path,
231
+ "--watch",
232
+ "--wrangler-config",
233
+ path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
234
+ "--env",
235
+ path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
236
+ "--package",
237
+ path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
238
+ "--port",
239
+ port.toString(),
240
+ "--kv-persist",
241
+ "--cache-persist",
242
+ "--do-persist",
243
+ ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
244
+ return ["--binding", `${key}=${value}`];
245
+ }),
246
+ ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
247
+ return ["--kv", binding];
248
+ }),
249
+ ...(bindings.durable_objects?.bindings || []).flatMap(
250
+ ({ name, class_name }) => {
251
+ return ["--do", `${name}=${class_name}`];
252
+ }
253
+ ),
254
+ "--modules",
255
+ format ||
256
+ (bundle.type === "esm" ? "modules" : "service-worker") === "modules"
257
+ ? "true"
258
+ : "false",
259
+ ]);
260
+ console.log(`⬣ Listening at http://localhost:${port}`);
261
+
262
+ local.current.on("close", (code) => {
263
+ if (code !== null) {
264
+ console.log(`miniflare process exited with code ${code}`);
265
+ }
266
+ });
267
+
268
+ local.current.stdout?.on("data", (data: Buffer) => {
269
+ console.log(`${data.toString()}`);
270
+ });
271
+
272
+ local.current.stderr?.on("data", (data: Buffer) => {
273
+ console.error(`${data.toString()}`);
274
+ const matches =
275
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:9229\/[A-Za-z0-9-]+)/.exec(
276
+ data.toString()
277
+ );
278
+ if (matches) {
279
+ setInspectorUrl(matches[1]);
280
+ }
281
+ });
282
+
283
+ local.current.on("exit", (code) => {
284
+ if (code !== 0) {
285
+ console.error(`miniflare process exited with code ${code}`);
286
+ }
287
+ });
288
+
289
+ local.current.on("error", (error: Error) => {
290
+ console.error(`miniflare process failed to spawn`);
291
+ console.error(error);
292
+ });
293
+
294
+ removeSignalExitListener.current = onExit((_code, _signal) => {
295
+ console.log("⎔ Shutting down local server.");
296
+ local.current?.kill();
297
+ local.current = undefined;
298
+ });
299
+ }
300
+
301
+ startLocalWorker().catch((err) => {
302
+ console.error("local worker:", err);
303
+ });
304
+
305
+ return () => {
306
+ if (local.current) {
307
+ console.log("⎔ Shutting down local server.");
308
+ local.current?.kill();
309
+ local.current = undefined;
310
+ removeSignalExitListener.current && removeSignalExitListener.current();
311
+ removeSignalExitListener.current = undefined;
312
+ }
313
+ };
314
+ }, [
315
+ bundle,
316
+ format,
317
+ port,
318
+ bindings.durable_objects?.bindings,
319
+ bindings.kv_namespaces,
320
+ bindings.vars,
321
+ ]);
322
+ return { inspectorUrl };
323
+ }
324
+
325
+ function useTmpDir(): string | undefined {
326
+ const [directory, setDirectory] = useState<DirectoryResult>();
327
+ const handleError = useErrorHandler();
328
+ useEffect(() => {
329
+ let dir: DirectoryResult;
330
+ async function create() {
331
+ try {
332
+ dir = await tmp.dir({ unsafeCleanup: true });
333
+ setDirectory(dir);
334
+ return;
335
+ } catch (err) {
336
+ console.error("failed to create tmp dir");
337
+ throw err;
338
+ }
339
+ }
340
+ create().catch((err) => {
341
+ // we want to break here
342
+ // we can't do much without a temp dir anyway
343
+ handleError(err);
344
+ });
345
+ return () => {
346
+ dir.cleanup().catch(() => {
347
+ // extremely unlikely,
348
+ // but it's 2021 after all
349
+ console.error("failed to cleanup tmp dir");
350
+ });
351
+ };
352
+ }, [handleError]);
353
+ return directory?.path;
354
+ }
355
+
356
+ function useCustomBuild(
357
+ expectedEntry: string,
358
+ props: {
359
+ command?: undefined | string;
360
+ cwd?: undefined | string;
361
+ watch_dir?: undefined | string;
362
+ }
363
+ ): undefined | string {
364
+ const [entry, setEntry] = useState<string | undefined>(
365
+ // if there's no build command, just return the expected entry
366
+ props.command || expectedEntry
367
+ );
368
+ const { command, cwd, watch_dir } = props;
369
+ useEffect(() => {
370
+ if (!command) return;
371
+ let cmd, interval;
372
+ console.log("running:", command);
373
+ const commandPieces = command.split(" ");
374
+ cmd = execa(commandPieces[0], commandPieces.slice(1), {
375
+ ...(cwd && { cwd }),
376
+ stderr: "inherit",
377
+ stdout: "inherit",
378
+ });
379
+ if (watch_dir) {
380
+ watch(watch_dir, { persistent: true, ignoreInitial: true }).on(
381
+ "all",
382
+ (_event, _path) => {
383
+ console.log(`The file ${path} changed, restarting build...`);
384
+ cmd.kill();
385
+ cmd = execa(commandPieces[0], commandPieces.slice(1), {
386
+ ...(cwd && { cwd }),
387
+ stderr: "inherit",
388
+ stdout: "inherit",
389
+ });
390
+ }
391
+ );
392
+ }
393
+
394
+ // check every so often whether `expectedEntry` exists
395
+ // if it does, we're done
396
+ const startedAt = Date.now();
397
+ interval = setInterval(() => {
398
+ if (existsSync(expectedEntry)) {
399
+ clearInterval(interval);
400
+ setEntry(expectedEntry);
401
+ } else {
402
+ const elapsed = Date.now() - startedAt;
403
+ // timeout after 30 seconds of waiting
404
+ if (elapsed > 1000 * 60 * 30) {
405
+ console.error("⎔ Build timed out.");
406
+ clearInterval(interval);
407
+ cmd.kill();
408
+ }
409
+ }
410
+ }, 200);
411
+ // TODO: we could probably timeout here after a while
412
+
413
+ return () => {
414
+ if (cmd) {
415
+ cmd.kill();
416
+ cmd = undefined;
417
+ }
418
+ clearInterval(interval);
419
+ interval = undefined;
420
+ };
421
+ }, [command, cwd, expectedEntry, watch_dir]);
422
+ return entry;
423
+ }
424
+
425
+ type EsbuildBundle = {
426
+ id: number;
427
+ path: string;
428
+ entry: string;
429
+ type: "esm" | "commonjs";
430
+ exports: string[];
431
+ modules: CfModule[];
432
+ };
433
+
434
+ function useEsbuild(props: {
435
+ entry: undefined | string;
436
+ destination: string | undefined;
437
+ staticRoot: undefined | string;
438
+ jsxFactory: string | undefined;
439
+ jsxFragment: string | undefined;
440
+ }): EsbuildBundle | undefined {
441
+ const { entry, destination, staticRoot, jsxFactory, jsxFragment } = props;
442
+ const [bundle, setBundle] = useState<EsbuildBundle>();
443
+ useEffect(() => {
444
+ let result: esbuild.BuildResult | undefined;
445
+ async function build() {
446
+ if (!destination || !entry) return;
447
+ const moduleCollector = makeModuleCollector();
448
+ result = await esbuild.build({
449
+ entryPoints: [entry],
450
+ bundle: true,
451
+ outdir: destination,
452
+ metafile: true,
453
+ format: "esm",
454
+ sourcemap: true,
455
+ loader: {
456
+ ".js": "jsx",
457
+ },
458
+ ...(jsxFactory && { jsxFactory }),
459
+ ...(jsxFragment && { jsxFragment }),
460
+ external: ["__STATIC_CONTENT_MANIFEST"],
461
+ conditions: ["worker", "browser"],
462
+ plugins: [moduleCollector.plugin],
463
+ // TODO: import.meta.url
464
+ watch: {
465
+ async onRebuild(error) {
466
+ if (error) console.error("watch build failed:", error);
467
+ else {
468
+ // nothing really changes here, so let's increment the id
469
+ // to change the return object's identity
470
+ setBundle((previousBundle) => {
471
+ if (previousBundle === undefined) {
472
+ assert.fail(
473
+ "Rebuild triggered with no previous build available"
474
+ );
475
+ }
476
+ return { ...previousBundle, id: previousBundle.id + 1 };
477
+ });
478
+ }
479
+ },
480
+ },
481
+ });
482
+
483
+ // result.metafile is defined because of the `metafile: true` option above.
484
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
485
+ const metafile = result.metafile!;
486
+ const outputEntry = Object.entries(metafile.outputs).find(
487
+ ([_path, { entryPoint }]) => entryPoint === entry
488
+ ); // assumedly only one entry point
489
+
490
+ if (outputEntry === undefined) {
491
+ throw new Error(
492
+ `Cannot find entry-point "${entry}" in generated bundle.`
493
+ );
494
+ }
495
+ setBundle({
496
+ id: 0,
497
+ entry,
498
+ path: outputEntry[0],
499
+ type: outputEntry[1].exports.length > 0 ? "esm" : "commonjs",
500
+ exports: outputEntry[1].exports,
501
+ modules: moduleCollector.modules,
502
+ });
503
+ }
504
+ build().catch((_err) => {
505
+ // esbuild already logs errors to stderr
506
+ // and we don't want to end the process
507
+ // on build errors anyway
508
+ // so this is a no-op error handler
509
+ });
510
+ return () => {
511
+ result?.stop?.();
512
+ };
513
+ }, [entry, destination, staticRoot, jsxFactory, jsxFragment]);
514
+ return bundle;
515
+ }
516
+
517
+ function useWorker(props: {
518
+ name: undefined | string;
519
+ bundle: EsbuildBundle | undefined;
520
+ format: CfScriptFormat;
521
+ modules: CfModule[];
522
+ accountId: string;
523
+ apiToken: string;
524
+ bindings: CfWorkerInit["bindings"];
525
+ sitesFolder: undefined | string;
526
+ port: number;
527
+ compatibilityDate: string | undefined;
528
+ compatibilityFlags: string[] | undefined;
529
+ usageModel: undefined | "bundled" | "unbound";
530
+ }): CfPreviewToken | undefined {
531
+ const {
532
+ name,
533
+ bundle,
534
+ format,
535
+ modules,
536
+ accountId,
537
+ apiToken,
538
+ bindings,
539
+ sitesFolder,
540
+ compatibilityDate,
541
+ compatibilityFlags,
542
+ usageModel,
543
+ port,
544
+ } = props;
545
+ const [token, setToken] = useState<CfPreviewToken | undefined>();
546
+
547
+ // This is the most reliable way to detect whether
548
+ // something's "happened" in our system; We make a ref and
549
+ // mark it once we log our initial message. Refs are vars!
550
+ const startedRef = useRef(false);
551
+
552
+ useEffect(() => {
553
+ async function start() {
554
+ setToken(undefined); // reset token in case we're re-running
555
+
556
+ if (!bundle) return;
557
+ if (format === "modules" && bundle.type === "commonjs") {
558
+ console.error("⎔ Cannot use modules with a commonjs bundle.");
559
+ // TODO: a much better error message here, with what to do next
560
+ return;
561
+ }
562
+ if (format === "service-worker" && bundle.type !== "esm") {
563
+ console.error("⎔ Cannot use service-worker with a esm bundle.");
564
+ // TODO: a much better error message here, with what to do next
565
+ return;
566
+ }
567
+
568
+ if (!startedRef.current) {
569
+ startedRef.current = true;
570
+ } else {
571
+ console.log("⎔ Detected changes, restarting server...");
572
+ }
573
+
574
+ const assets = sitesFolder
575
+ ? await syncAssets(
576
+ accountId,
577
+ path.basename(bundle.path),
578
+ sitesFolder,
579
+ true,
580
+ undefined // TODO: env
581
+ )
582
+ : {
583
+ manifest: undefined,
584
+ namespace: undefined,
585
+ }; // TODO: cancellable?
586
+
587
+ const content = await readFile(bundle.path, "utf-8");
588
+ const init: CfWorkerInit = {
589
+ name,
590
+ main: {
591
+ name: path.basename(bundle.path),
592
+ type: format || bundle.type === "esm" ? "esm" : "commonjs",
593
+ content,
594
+ },
595
+ modules: modules.concat(
596
+ assets.manifest
597
+ ? {
598
+ name: "__STATIC_CONTENT_MANIFEST",
599
+ content: JSON.stringify(assets.manifest),
600
+ type: "text",
601
+ }
602
+ : []
603
+ ),
604
+ bindings: {
605
+ ...bindings,
606
+ kv_namespaces: (bindings.kv_namespaces || []).concat(
607
+ assets.namespace
608
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
609
+ : []
610
+ ),
611
+ },
612
+ migrations: undefined, // no migrations in dev
613
+ compatibility_date: compatibilityDate,
614
+ compatibility_flags: compatibilityFlags,
615
+ usage_model: usageModel,
616
+ };
617
+ setToken(
618
+ await createWorker(init, {
619
+ accountId,
620
+ apiToken,
621
+ })
622
+ );
623
+ }
624
+ start().catch((err) => {
625
+ // we want to log the error, but not end the process
626
+ // since it could recover after the developer fixes whatever's wrong
627
+ console.error("remote worker:", err);
628
+ });
629
+ }, [
630
+ name,
631
+ bundle,
632
+ format,
633
+ accountId,
634
+ apiToken,
635
+ port,
636
+ sitesFolder,
637
+ compatibilityDate,
638
+ compatibilityFlags,
639
+ usageModel,
640
+ bindings,
641
+ modules,
642
+ ]);
643
+ return token;
644
+ }
645
+
646
+ function sleep(period: number) {
647
+ return new Promise((resolve) => setTimeout(resolve, period));
648
+ }
649
+ const SLEEP_DURATION = 2000;
650
+ // really need a first class api for this
651
+ const hostNameRegex = /userHostname="(.*)"/g;
652
+ async function findTunnelHostname() {
653
+ let hostName: string | undefined;
654
+ while (!hostName) {
655
+ try {
656
+ const resp = await fetch("http://localhost:8789/metrics");
657
+ const data = await resp.text();
658
+ const matches = Array.from(data.matchAll(hostNameRegex));
659
+ hostName = matches[0][1];
660
+ } catch (err) {
661
+ await sleep(SLEEP_DURATION);
662
+ }
663
+ }
664
+ return hostName;
665
+ }
666
+
667
+ function useTunnel(toggle: boolean) {
668
+ const tunnel = useRef<ReturnType<typeof spawn>>();
669
+ const removeSignalExitListener = useRef<() => void>();
670
+ // TODO: test if cloudflared is available, if not
671
+ // point them to a url where they can get docs to install it
672
+ useEffect(() => {
673
+ async function startTunnel() {
674
+ if (toggle) {
675
+ try {
676
+ await commandExists("cloudflared");
677
+ } catch (e) {
678
+ console.error(
679
+ "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
680
+ );
681
+ return;
682
+ }
683
+ console.log("⎔ Starting a tunnel...");
684
+ tunnel.current = spawn("cloudflared", [
685
+ "tunnel",
686
+ "--url",
687
+ "http://localhost:8787",
688
+ "--metrics",
689
+ "localhost:8789",
690
+ ]);
691
+
692
+ tunnel.current.on("close", (code) => {
693
+ if (code !== 0) {
694
+ console.log(`Tunnel process exited with code ${code}`);
695
+ }
696
+ });
697
+
698
+ removeSignalExitListener.current = onExit((_code, _signal) => {
699
+ console.log("⎔ Shutting down local tunnel.");
700
+ tunnel.current?.kill();
701
+ tunnel.current = undefined;
702
+ });
703
+
704
+ const hostName = await findTunnelHostname();
705
+ await clipboardy.write(hostName);
706
+ console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
707
+ }
708
+ }
709
+
710
+ startTunnel().catch((err) => {
711
+ console.error("tunnel:", err);
712
+ });
713
+
714
+ return () => {
715
+ if (tunnel.current) {
716
+ console.log("⎔ Shutting down tunnel.");
717
+ tunnel.current?.kill();
718
+ tunnel.current = undefined;
719
+ removeSignalExitListener.current && removeSignalExitListener.current();
720
+ removeSignalExitListener.current = undefined;
721
+ }
722
+ };
723
+ }, [toggle]);
724
+ }
725
+
726
+ type useHotkeysInitialState = {
727
+ local: boolean;
728
+ tunnel: boolean;
729
+ };
730
+ function useHotkeys(initial: useHotkeysInitialState, port: number) {
731
+ // UGH, we should put port in context instead
732
+ const [toggles, setToggles] = useState(initial);
733
+ useInput(
734
+ async (
735
+ input,
736
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
737
+ key
738
+ ) => {
739
+ switch (input) {
740
+ case "b": // open browser
741
+ await open(`http://localhost:${port}/`);
742
+ break;
743
+ case "d": // toggle inspector
744
+ await open(
745
+ `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
746
+ );
747
+ break;
748
+ case "s": // toggle tunnel
749
+ setToggles((previousToggles) => ({
750
+ ...previousToggles,
751
+ tunnel: !previousToggles.tunnel,
752
+ }));
753
+ break;
754
+ case "l": // toggle local
755
+ setToggles((previousToggles) => ({
756
+ ...previousToggles,
757
+ local: !previousToggles.local,
758
+ }));
759
+ break;
760
+ case "q": // shut down
761
+ case "x": // shut down
762
+ process.exit(0);
763
+ break;
764
+ default:
765
+ // nothing?
766
+ break;
767
+ }
768
+ }
769
+ );
770
+ return toggles;
771
+ }
772
+
773
+ function ErrorFallback(props: { error: Error }) {
774
+ const { exit } = useApp();
775
+ useEffect(() => exit(new Error()));
776
+ return (
777
+ <>
778
+ <Text>Something went wrong:</Text>
779
+ <Text>{props.error.stack}</Text>
780
+ </>
781
+ );
782
+ }
783
+
784
+ export default withErrorBoundary(Dev, { FallbackComponent: ErrorFallback });