vde-open 0.1.14 → 0.1.16

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 CHANGED
@@ -28,7 +28,7 @@ To install from a clone of this repository (Node.js 24.22.1 is pinned in `mise.t
28
28
  pnpm install --frozen-lockfile
29
29
  pnpm build
30
30
  pnpm test:pack # builds artifacts/vde-open-<version>.tgz and verifies an install in a separate directory
31
- bun add -g "$PWD/artifacts/vde-open-0.1.14.tgz" # bun add -g needs an absolute path
31
+ bun add -g "$PWD/artifacts/vde-open-0.1.16.tgz" # bun add -g needs an absolute path
32
32
  ```
33
33
 
34
34
  ## `vde-open` and `vo`
@@ -53,7 +53,7 @@ vo close docs/design.md # remove from the list (the file is not
53
53
  vo daemon stop # stop the daemon
54
54
  ```
55
55
 
56
- The management UI does not require authentication. The URL printed by `vo ui --print-url` can be copied to another browser or tab on the same machine while the daemon is running. URLs that select a document work directly too. Both listeners bind to `127.0.0.1`; viewing from another machine is not supported.
56
+ The management UI does not require authentication. Its URL is `http://127.0.0.1:43180/` by default and stays the same across daemon restarts, so it can be bookmarked; an open tab reconnects after `vo daemon restart` and shows the same document again (HTML returns to the static view until scripts are allowed again). The URL printed by `vo ui --print-url` can be copied to another browser or tab on the same machine. URLs that select a document work directly too. All listeners bind to `127.0.0.1`. To read on your phone, see [Reading on your phone over Tailscale](#reading-on-your-phone-over-tailscale).
57
57
 
58
58
  For how agents search, read, and ask questions, see [docs/agent-usage.md](docs/agent-usage.md).
59
59
 
@@ -77,9 +77,10 @@ ln -s ~/.bun/install/global/node_modules/vde-open/skills/vde-open ~/.codex/skill
77
77
 
78
78
  ## HTML display limits
79
79
 
80
- - By default (static), scripts do not run. Scripts, event attributes, iframe/object/embed, base, automatic navigation (meta refresh), form targets, and external images, CSS, and fonts are removed. Links cannot be clicked inside the view; open them from "Links in this document".
80
+ - By default (Static), the view removes the document's scripts, event attributes, iframe/object/embed, base, automatic navigation (meta refresh), form targets, and external images, CSS, and fonts.
81
+ - In Static and Interactive, select a local document link in the preview to switch to an open document or confirm opening a new one. Heading links jump within the preview. Open external links from "Links in this document".
81
82
  - Only files that the document references, inside the assets root (by default the document's directory), can be loaded. Files whose names start with "." such as `.env` and `.git` are never loaded. Set the scope with `--assets-root` and individual files with `--asset`.
82
- - Scripts run only in HTML opened with `--html-mode interactive`. Use it only with HTML that you or the agent prepared and trust: scripts can load only registered files and cannot reach the management UI, the management API, or other files, but this does not block every outbound request (navigation inside the view, for example). After the daemon restarts, the HTML is static until you allow scripts again in the management UI.
83
+ - Document scripts run only in Interactive HTML. You can enable it with `--html-mode interactive` or allow scripts in the management UI. Use it only with HTML that you or the agent prepared and trust: scripts can load only registered files and cannot reach the management UI, the management API, or other files, but this does not block every outbound request (navigation inside the view, for example). After the daemon restarts, the HTML is static until you allow scripts again in the management UI.
83
84
  - "Differences" in the management UI lists what the view changed, why, and what to do.
84
85
 
85
86
  ## Markdown display
@@ -130,8 +131,38 @@ Images are searchable by title and path (`vo search diagram --mode path`). Text
130
131
  - Linux: `$XDG_STATE_HOME/vde-open` (or `~/.local/state/vde-open` if unset)
131
132
  - Windows: `%LOCALAPPDATA%\vde-open`
132
133
  - Stop the daemon with `vo daemon stop`, and check it with `vo daemon status`.
134
+ - The listen ports are read from an optional `listeners.json` in the state directory when the daemon starts (`{"managementPort": 43180, "previewPort": 43181}`; both are the defaults). Changes apply on the next start. `vo serve --port <n> --preview-port <n>` overrides them for that run only and does not change the file. If a port is in use, starting fails with `E_DAEMON_START_FAILED`, naming the listener and the port.
133
135
  - Management UI preferences such as the color theme and the view mode are stored in the browser.
134
136
 
137
+ ## Reading on your phone over Tailscale
138
+
139
+ The documents open on this machine can be read on your own phone, and HTML demos that you allowed on the PC can be tapped and dragged there. The phone gets a list and a reader only: it cannot open, close, reorder, or focus documents, answer questions, or allow scripts. Choosing a document on the phone never changes what the PC shows.
140
+
141
+ ```bash
142
+ vo mobile enable # set up and print the URL to bookmark on your phone
143
+ vo mobile status # settings, the daemon's state, and the Serve forwards
144
+ vo mobile disable # remove the settings and the reader's forwards
145
+ ```
146
+
147
+ `vo mobile enable` reads this machine's Tailscale name and your Tailscale login from `tailscale status`, writes them to `listeners.json` in the state directory (other settings are kept), restarts the daemon, and adds the two Tailscale Serve forwards (`https://<host>:43182` and `:43183` to the same ports on `127.0.0.1`). It never changes another Serve setting: if either port is used for something else, it stops without changing anything. `--no-serve` leaves Serve to you. Serve's CLI cannot make a change conditional, so each forward is checked right before it is added or removed; one made by another program in that instant could still be replaced. Then open the printed `https://<host>:43182/` on your phone (signed in to the same tailnet) and bookmark it; it stays the same across daemon restarts.
148
+
149
+ To set it up by hand instead, add this to `listeners.json` and restart the daemon, then add the forwards with `tailscale serve --bg --https=43182 http://127.0.0.1:43182` and the same for 43183:
150
+
151
+ ```json
152
+ {
153
+ "mobile": {
154
+ "host": "example-mac.example-tailnet.ts.net",
155
+ "login": "person@example.com",
156
+ "uiPort": 43182,
157
+ "previewPort": 43183
158
+ }
159
+ }
160
+ ```
161
+
162
+ `uiPort` and `previewPort` default to 43182 and 43183, must differ from each other and from the PC ports, and cannot be 443. `vo daemon status` shows `phone reader: ready <URL>`, or `error` with the reason (the PC keeps working either way).
163
+
164
+ Every request on both ports must carry the `Host` you configured and exactly one `Tailscale-User-Login` equal to `login`, which Serve adds for the signed-in person; anything else is refused. If your Tailscale login changes, run `vo mobile enable` again. Restrict which devices may reach the two ports with your tailnet access rules as well. HTML runs scripts on the phone only while the PC allows them (`vo open --html-mode interactive demo.html`, with `--asset` for files it loads); allowing again after a restart, revoking, closing, or saving the document replaces or removes the phone's view. The Serve forwards stay while the daemon is stopped; before giving the ports another use, run `vo mobile disable` (or `tailscale serve --https=43182 off` and the same for 43183). `vo mobile disable` removes every forward that has exactly the reader's shape (`/` on that HTTPS port to the same port on `127.0.0.1`), including one you made by hand; to keep Serve as it is, use `vo mobile disable --no-serve`.
165
+
135
166
  ## Asking a person and getting answers
136
167
 
137
168
  ```bash
package/dist/cli.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { C as decodeStateFile, D as daemonEntryPath, E as resolveStateRoot, O as referencedBlobs, S as renameWithRetry, T as resolveRuntimeLocation, a as DAEMON_LOCK_NAME, b as proofMatches, c as readIpcKey, d as inspectOwner, f as readCurrentLock, g as encodeFrame, h as FrameDecoder, i as requirePrivateDirectoryIfExists, k as version, l as readPointer, m as systemProcessProbe, n as ensurePrivateDirectory, o as POINTER_FILE, p as releaseLock, r as inspectPrivateDirectory, s as START_LOCK_NAME, t as startDaemon, u as acquireLock, v as computeProof, w as currentPathEnvironment, x as removeWithRetry, y as createNonce } from "./main-ChphixE8.js";
3
- import { A as successEnvelope, C as VdeError, D as ExitCode, E as isVdeError, O as envelopeSchema, T as isErrorCode, Y as LIMITS, k as errorEnvelope, w as exitCodeForError } from "./search-index-B-hHn9RV.js";
2
+ import { A as resolveRuntimeLocation, C as computeProof, D as renameWithRetry, E as removeWithRetry, M as daemonEntryPath, N as referencedBlobs, O as decodeStateFile, P as version, T as proofMatches, _ as readCurrentLock, a as DAEMON_LOCK_NAME, b as FrameDecoder, c as readIpcKey, d as LISTENER_CONFIG_FILE, f as readListenerConfig, g as inspectOwner, h as acquireLock, i as requirePrivateDirectoryIfExists, j as resolveStateRoot, k as currentPathEnvironment, l as readPointer, m as resolvePcPorts, n as ensurePrivateDirectory, o as POINTER_FILE, p as resolveMobileConfig, r as inspectPrivateDirectory, s as START_LOCK_NAME, t as startDaemon, u as DEFAULT_PORTS, v as releaseLock, w as createNonce, x as encodeFrame, y as systemProcessProbe } from "./main-D-ZX3nEP.js";
3
+ import { A as isErrorCode, F as successEnvelope, M as ExitCode, N as envelopeSchema, O as VdeError, P as errorEnvelope, j as isVdeError, k as exitCodeForError, tt as LIMITS } from "./search-index-B0xpVDwG.js";
4
4
  import fs, { fstatSync } from "node:fs";
5
- import { lstat, readFile, readdir, stat as stat$1, writeFile } from "node:fs/promises";
6
- import path, { dirname, join, resolve } from "node:path";
5
+ import { lstat, readFile, readdir, rename, rm, stat as stat$1, writeFile } from "node:fs/promises";
6
+ import path, { dirname, isAbsolute, join, resolve } from "node:path";
7
7
  import { EventEmitter } from "node:events";
8
- import childProcess, { spawn } from "node:child_process";
8
+ import childProcess, { execFile, spawn } from "node:child_process";
9
9
  import process$1 from "node:process";
10
10
  import { stripVTControlCharacters } from "node:util";
11
- import { randomUUID } from "node:crypto";
11
+ import { randomBytes, randomUUID } from "node:crypto";
12
12
  import { connect } from "node:net";
13
13
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
14
14
  //#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
@@ -3552,7 +3552,8 @@ function createDaemonControl(environment) {
3552
3552
  stateRoot,
3553
3553
  openDocuments: null,
3554
3554
  catalogVersion: null,
3555
- uiUrl: null
3555
+ uiUrl: null,
3556
+ mobile: null
3556
3557
  });
3557
3558
  return {
3558
3559
  stateRoot,
@@ -3564,6 +3565,261 @@ function createDaemonControl(environment) {
3564
3565
  };
3565
3566
  }
3566
3567
  //#endregion
3568
+ //#region src/cli/mobile-setup.ts
3569
+ const TAILSCALE_TIMEOUT_MS = 15e3;
3570
+ const MAC_APP_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale";
3571
+ function execute(command, args, env) {
3572
+ return new Promise((resolve, reject) => {
3573
+ execFile(command, args, {
3574
+ env,
3575
+ timeout: TAILSCALE_TIMEOUT_MS,
3576
+ maxBuffer: 8388608
3577
+ }, (error, stdout, stderr) => {
3578
+ if (!error) {
3579
+ resolve(stdout);
3580
+ return;
3581
+ }
3582
+ if (error.code === "ENOENT") {
3583
+ reject(new VdeError("E_TAILSCALE_UNAVAILABLE", "The tailscale command was not found."));
3584
+ return;
3585
+ }
3586
+ const reason = stderr.split("\n").map((line) => line.trim()).find((line) => line !== "" && !line.startsWith("Warning:")) ?? "failed";
3587
+ reject(new VdeError("E_TAILSCALE_FAILED", `tailscale ${args.join(" ")} failed: ${reason}`, { reason }));
3588
+ });
3589
+ });
3590
+ }
3591
+ function createTailscale(env) {
3592
+ const explicit = env["VDE_OPEN_TAILSCALE"];
3593
+ if (explicit !== void 0 && explicit !== "" && !isAbsolute(explicit)) throw new VdeError("E_INVALID_ARGUMENT", "VDE_OPEN_TAILSCALE must be an absolute path.");
3594
+ const candidates = explicit ? [explicit] : ["tailscale", MAC_APP_CLI];
3595
+ return { async run(args) {
3596
+ let last = null;
3597
+ for (const command of candidates) try {
3598
+ return await execute(command, args, env);
3599
+ } catch (error) {
3600
+ last = error;
3601
+ if (!(error instanceof VdeError && error.code === "E_TAILSCALE_UNAVAILABLE")) throw error;
3602
+ }
3603
+ throw last;
3604
+ } };
3605
+ }
3606
+ async function detectIdentity(tailscale) {
3607
+ const status = JSON.parse(await tailscale.run(["status", "--json"]));
3608
+ if (status.BackendState !== "Running") throw new VdeError("E_TAILSCALE_FAILED", "Tailscale is not running or not signed in on this machine.", { reason: status.BackendState ?? "unknown" });
3609
+ if ((status.Self?.Tags ?? []).length > 0) throw new VdeError("E_TAILSCALE_FAILED", "This machine is a tagged device; Tailscale Serve sends no login for it, so the phone reader cannot be used.", { reason: "tagged" });
3610
+ const host = (status.Self?.DNSName ?? "").replace(/\.$/, "").toLowerCase();
3611
+ const login = status.User?.[String(status.Self?.UserID)]?.LoginName ?? "";
3612
+ if (host === "" || login === "") throw new VdeError("E_TAILSCALE_FAILED", "Tailscale did not report this machine’s name or login.", { reason: "incomplete-status" });
3613
+ return {
3614
+ host,
3615
+ login
3616
+ };
3617
+ }
3618
+ function forwardState(serve, host, port) {
3619
+ const key = `${host}:${String(port)}`;
3620
+ const web = Object.entries(serve.Web ?? {}).filter(([name]) => name.endsWith(`:${String(port)}`));
3621
+ const handlers = serve.Web?.[key]?.Handlers ?? {};
3622
+ if (web.length === 1 && web[0]?.[0] === key && Object.keys(handlers).length === 1 && handlers["/"]?.Proxy === `http://127.0.0.1:${String(port)}` && serve.AllowFunnel?.[key] !== true) return "ours";
3623
+ return web.length === 0 && serve.TCP?.[String(port)] === void 0 ? "free" : "other";
3624
+ }
3625
+ async function serveStatus(tailscale) {
3626
+ const text = (await tailscale.run([
3627
+ "serve",
3628
+ "status",
3629
+ "--json"
3630
+ ])).trim();
3631
+ return text === "" ? {} : JSON.parse(text);
3632
+ }
3633
+ async function readConfig(path) {
3634
+ let text;
3635
+ try {
3636
+ text = await readFile(path, "utf8");
3637
+ } catch (error) {
3638
+ if (error.code === "ENOENT") return {};
3639
+ throw error;
3640
+ }
3641
+ let value;
3642
+ try {
3643
+ value = JSON.parse(text);
3644
+ } catch {
3645
+ value = null;
3646
+ }
3647
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new VdeError("E_INVALID_ARGUMENT", `${LISTENER_CONFIG_FILE} is not a JSON object. Fix or remove it first.`, { path });
3648
+ return value;
3649
+ }
3650
+ async function writeConfig(path, config) {
3651
+ if (Object.keys(config).length === 0) {
3652
+ await rm(path, { force: true });
3653
+ return;
3654
+ }
3655
+ const temporary = `${path}.${randomBytes(6).toString("hex")}.tmp`;
3656
+ await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, {
3657
+ mode: 384,
3658
+ flag: "wx"
3659
+ });
3660
+ await rename(temporary, path);
3661
+ }
3662
+ function hasReaderForward(serve, host, port) {
3663
+ return serve.Web?.[`${host}:${String(port)}`]?.Handlers?.["/"]?.Proxy === `http://127.0.0.1:${String(port)}`;
3664
+ }
3665
+ async function takeBack(tailscale, host, ports) {
3666
+ const left = [];
3667
+ for (const port of ports) {
3668
+ let status;
3669
+ try {
3670
+ status = await serveStatus(tailscale);
3671
+ } catch {
3672
+ left.push(port);
3673
+ continue;
3674
+ }
3675
+ if (forwardState(status, host, port) !== "ours") {
3676
+ if (hasReaderForward(status, host, port)) left.push(port);
3677
+ continue;
3678
+ }
3679
+ try {
3680
+ await tailscale.run([
3681
+ "serve",
3682
+ `--https=${String(port)}`,
3683
+ "off"
3684
+ ]);
3685
+ } catch {
3686
+ left.push(port);
3687
+ }
3688
+ }
3689
+ return left;
3690
+ }
3691
+ async function enableMobile(context, options) {
3692
+ const stateRoot = resolveStateRoot(context.environment);
3693
+ const path = join(stateRoot, LISTENER_CONFIG_FILE);
3694
+ const { host, login } = await detectIdentity(context.tailscale);
3695
+ const pc = resolvePcPorts({}, await readListenerConfig(stateRoot), false);
3696
+ const config = await readConfig(path);
3697
+ const previous = config["mobile"] ?? {};
3698
+ const portOr = (value, fallback) => typeof value === "number" ? value : fallback;
3699
+ const mobile = {
3700
+ host,
3701
+ login,
3702
+ uiPort: portOr(previous.uiPort, DEFAULT_PORTS.mobileUi),
3703
+ previewPort: portOr(previous.previewPort, DEFAULT_PORTS.mobilePreview)
3704
+ };
3705
+ const checked = resolveMobileConfig(mobile, pc);
3706
+ if (checked.state !== "enabled") throw new VdeError("E_INVALID_ARGUMENT", `The phone reader settings are invalid (${checked.state === "error" ? checked.reason : "disabled"}).`);
3707
+ const ports = [mobile.uiPort, mobile.previewPort];
3708
+ let before = {};
3709
+ if (options.serve) {
3710
+ before = await serveStatus(context.tailscale);
3711
+ const taken = ports.filter((port) => forwardState(before, host, port) === "other");
3712
+ if (taken.length > 0) throw new VdeError("E_SERVE_CONFLICT", `Tailscale Serve already uses HTTPS port ${taken.join(" and ")} for something else. Nothing was changed; free the port or choose other ports in ${LISTENER_CONFIG_FILE}.`, { ports: taken });
3713
+ }
3714
+ await ensurePrivateDirectory(stateRoot, {
3715
+ uid: context.environment.uid,
3716
+ platform: context.environment.platform
3717
+ });
3718
+ await writeConfig(path, {
3719
+ ...config,
3720
+ mobile
3721
+ });
3722
+ const status = await context.restartDaemon();
3723
+ if (status.mobile?.state !== "ready") {
3724
+ const reason = status.mobile?.state === "error" ? `${status.mobile.reason}` : "not started";
3725
+ throw new VdeError("E_DAEMON_START_FAILED", `The settings were saved, but the phone reader did not start (${reason}). Serve was not changed.`, { mobile: status.mobile });
3726
+ }
3727
+ const serve = {};
3728
+ const attempted = [];
3729
+ try {
3730
+ for (const port of ports) {
3731
+ if (!options.serve) {
3732
+ serve[String(port)] = "skipped";
3733
+ continue;
3734
+ }
3735
+ const now = forwardState(await serveStatus(context.tailscale), host, port);
3736
+ if (now === "ours") {
3737
+ serve[String(port)] = "present";
3738
+ continue;
3739
+ }
3740
+ if (now === "other") throw new VdeError("E_SERVE_CONFLICT", `Tailscale Serve started using HTTPS port ${String(port)} for something else meanwhile.`, { ports: [port] });
3741
+ attempted.push(port);
3742
+ await context.tailscale.run([
3743
+ "serve",
3744
+ "--bg",
3745
+ `--https=${String(port)}`,
3746
+ `http://127.0.0.1:${String(port)}`
3747
+ ]);
3748
+ serve[String(port)] = "added";
3749
+ }
3750
+ if (attempted.length > 0) {
3751
+ const after = await serveStatus(context.tailscale);
3752
+ const missing = attempted.filter((port) => forwardState(after, host, port) !== "ours");
3753
+ if (missing.length > 0) throw new VdeError("E_TAILSCALE_FAILED", `Serve does not show the forward for port ${missing.join(" and ")}.`, { reason: "not-applied" });
3754
+ }
3755
+ } catch (error) {
3756
+ const left = await takeBack(context.tailscale, host, attempted);
3757
+ throw new VdeError(error instanceof VdeError ? error.code : "E_TAILSCALE_FAILED", `${error instanceof Error ? error.message : "Serve could not be changed."} The settings were saved in ${path}${left.length > 0 ? `; Serve may still forward port ${left.join(" and ")} (check with vo mobile status).` : "; the forwards this run tried to add are no longer in Serve."}`, {
3758
+ ...error instanceof VdeError ? error.details : {},
3759
+ settingsSaved: path,
3760
+ possiblyLeft: left
3761
+ });
3762
+ }
3763
+ return {
3764
+ uiUrl: status.mobile.uiUrl,
3765
+ host,
3766
+ login,
3767
+ serve
3768
+ };
3769
+ }
3770
+ async function disableMobile(context, options) {
3771
+ const path = join(resolveStateRoot(context.environment), LISTENER_CONFIG_FILE);
3772
+ const config = await readConfig(path);
3773
+ const mobile = config["mobile"];
3774
+ if (mobile === void 0) return {
3775
+ wasEnabled: false,
3776
+ serve: {}
3777
+ };
3778
+ const serve = {};
3779
+ const ports = [mobile.uiPort ?? DEFAULT_PORTS.mobileUi, mobile.previewPort ?? DEFAULT_PORTS.mobilePreview];
3780
+ if (options.serve && typeof mobile.host === "string") for (const port of ports) {
3781
+ const state = forwardState(await serveStatus(context.tailscale), mobile.host, port);
3782
+ if (state === "ours") {
3783
+ await context.tailscale.run([
3784
+ "serve",
3785
+ `--https=${String(port)}`,
3786
+ "off"
3787
+ ]);
3788
+ serve[String(port)] = "removed";
3789
+ } else serve[String(port)] = state === "free" ? "absent" : "kept";
3790
+ }
3791
+ else for (const port of ports) serve[String(port)] = "skipped";
3792
+ const { mobile: _removed, ...rest } = config;
3793
+ await writeConfig(path, rest);
3794
+ if (await context.daemonRunning()) await context.restartDaemon();
3795
+ return {
3796
+ wasEnabled: true,
3797
+ serve
3798
+ };
3799
+ }
3800
+ async function mobileStatus(context) {
3801
+ const mobile = (await readConfig(join(resolveStateRoot(context.environment), LISTENER_CONFIG_FILE)))["mobile"];
3802
+ const configured = mobile && typeof mobile.host === "string" && typeof mobile.login === "string" ? {
3803
+ host: mobile.host,
3804
+ login: mobile.login,
3805
+ uiPort: mobile.uiPort ?? DEFAULT_PORTS.mobileUi,
3806
+ previewPort: mobile.previewPort ?? DEFAULT_PORTS.mobilePreview
3807
+ } : null;
3808
+ let serve = null;
3809
+ if (configured) {
3810
+ const status = await serveStatus(context.tailscale).catch(() => null);
3811
+ if (status) serve = {
3812
+ [String(configured.uiPort)]: forwardState(status, configured.host, configured.uiPort),
3813
+ [String(configured.previewPort)]: forwardState(status, configured.host, configured.previewPort)
3814
+ };
3815
+ }
3816
+ return {
3817
+ configured,
3818
+ daemon: (await context.daemonStatus()).mobile,
3819
+ serve
3820
+ };
3821
+ }
3822
+ //#endregion
3567
3823
  //#region src/cli/output.ts
3568
3824
  function codeUnitEscape(character) {
3569
3825
  return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
@@ -4054,7 +4310,12 @@ async function runCli(rawArgv, context) {
4054
4310
  program.command("ui").description("Open the management UI in the browser").option("--print-url", "Print the UI URL instead of opening the browser", false).option("--json", "Output the result as JSON", false).action(async (options) => {
4055
4311
  await execute("ui", options.json, () => showUi(options.printUrl, options.json), () => "");
4056
4312
  });
4057
- const renderStatus = (status) => status.state === "running" ? `running pid=${String(status.pid)} open documents: ${String(status.openDocuments)} ${status.uiUrl ?? ""}` : "stopped";
4313
+ const renderMobile = (mobile) => {
4314
+ if (mobile === null || mobile.state === "disabled") return "";
4315
+ if (mobile.state === "ready") return `\nphone reader: ready ${mobile.uiUrl}`;
4316
+ return `\nphone reader: error${mobile.listener === null ? "" : ` (${mobile.listener} port ${String(mobile.port)})`}: ${escapeForTerminal(mobile.reason)}`;
4317
+ };
4318
+ const renderStatus = (status) => status.state === "running" ? `running pid=${String(status.pid)} open documents: ${String(status.openDocuments)} ${status.uiUrl ?? ""}${renderMobile(status.mobile)}` : "stopped";
4058
4319
  const daemon = program.command("daemon").description("Start, inspect, and stop the daemon");
4059
4320
  daemon.command("status").description("Show the daemon status. Does not start a new daemon when stopped").option("--json", "Output the result as JSON", false).action(async (options) => {
4060
4321
  await execute("daemon.status", options.json, async () => {
@@ -4082,7 +4343,56 @@ async function runCli(rawArgv, context) {
4082
4343
  return viaDaemon("daemon.status", {});
4083
4344
  }, renderStatus);
4084
4345
  });
4085
- program.command("serve").description("Run the daemon in the foreground. Press Ctrl+C to stop").option("--port <n>", "Port for the management UI. Defaults to a free port", parseInteger("--port", 1, 65535)).option("--preview-port <n>", "Port for the listener that shows documents. Defaults to a free port", parseInteger("--preview-port", 1, 65535)).action(async (options) => {
4346
+ const mobile = program.command("mobile").description("Set up reading open documents on your phone over Tailscale");
4347
+ const restartDaemon = async () => {
4348
+ await control.stop();
4349
+ return (await viaDaemon("daemon.status", {})).data;
4350
+ };
4351
+ const renderServe = (serve) => Object.entries(serve).map(([port, state]) => `${port} ${state}`).join(", ");
4352
+ mobile.command("enable").description("Read this machine's Tailscale name and your login into listeners.json, restart the daemon, and add the two Tailscale Serve forwards").option("--no-serve", "Do not change Tailscale Serve (add the forwards yourself)").option("--json", "Output the result as JSON", false).action(async (options) => {
4353
+ await execute("mobile.enable", options.json, async () => ({ data: await enableMobile({
4354
+ environment: context.environment,
4355
+ tailscale: createTailscale(context.environment.env),
4356
+ restartDaemon
4357
+ }, { serve: options.serve }) }), (data) => [
4358
+ `phone reader: ${data.uiUrl}`,
4359
+ `login: ${escapeForTerminal(data.login)}`,
4360
+ `serve: ${renderServe(data.serve)}`,
4361
+ options.serve ? "Open the URL on your phone (signed in to the same tailnet) and bookmark it." : `Add the forwards: tailscale serve --bg --https=<port> http://127.0.0.1:<port> (for ${Object.keys(data.serve).join(" and ")})`
4362
+ ].join("\n"));
4363
+ });
4364
+ mobile.command("disable").description("Remove the phone reader settings and only its own Tailscale Serve forwards, then restart the daemon").option("--no-serve", "Do not change Tailscale Serve").option("--json", "Output the result as JSON", false).action(async (options) => {
4365
+ await execute("mobile.disable", options.json, async () => ({ data: await disableMobile({
4366
+ environment: context.environment,
4367
+ tailscale: createTailscale(context.environment.env),
4368
+ restartDaemon,
4369
+ daemonRunning: async () => {
4370
+ const connection = await control.connectExisting();
4371
+ connection?.close();
4372
+ return connection !== null;
4373
+ }
4374
+ }, { serve: options.serve }) }), (data) => data.wasEnabled ? `phone reader: disabled\nserve: ${renderServe(data.serve)}` : "phone reader: was not enabled");
4375
+ });
4376
+ mobile.command("status").description("Show the phone reader settings, its state in the daemon, and the Tailscale Serve forwards").option("--json", "Output the result as JSON", false).action(async (options) => {
4377
+ await execute("mobile.status", options.json, async () => ({ data: await mobileStatus({
4378
+ environment: context.environment,
4379
+ tailscale: createTailscale(context.environment.env),
4380
+ daemonStatus: async () => {
4381
+ const connection = await control.connectExisting();
4382
+ if (!connection) return control.stoppedStatus();
4383
+ try {
4384
+ return unwrap(await connection.request("daemon.status", {})).data;
4385
+ } finally {
4386
+ connection.close();
4387
+ }
4388
+ }
4389
+ }) }), (data) => [
4390
+ data.configured === null ? "settings: none (vo mobile enable)" : `settings: https://${data.configured.host}:${String(data.configured.uiPort)}/ login: ${escapeForTerminal(data.configured.login)}`,
4391
+ `daemon: ${data.daemon === null ? "stopped" : data.daemon.state === "error" ? `error (${escapeForTerminal(data.daemon.reason)})` : data.daemon.state === "ready" ? `ready ${data.daemon.uiUrl}` : data.daemon.state}`,
4392
+ ...data.configured === null ? [] : [`serve: ${data.serve === null ? "unknown (tailscale not available)" : renderServe(data.serve)}`]
4393
+ ].join("\n"));
4394
+ });
4395
+ program.command("serve").description("Run the daemon in the foreground. Press Ctrl+C to stop").option("--port <n>", "Port for the management UI for this run only. Defaults to listeners.json, then 43180", parseInteger("--port", 1, 65535)).option("--preview-port <n>", "Port for the listener that shows documents for this run only. Defaults to listeners.json, then 43181", parseInteger("--preview-port", 1, 65535)).action(async (options) => {
4086
4396
  try {
4087
4397
  const handle = await startDaemon({
4088
4398
  environment: context.environment,
package/dist/daemon.js CHANGED
@@ -1,5 +1,5 @@
1
- import { k as version, t as startDaemon, w as currentPathEnvironment } from "./main-ChphixE8.js";
2
- import { E as isVdeError } from "./search-index-B-hHn9RV.js";
1
+ import { P as version, k as currentPathEnvironment, t as startDaemon } from "./main-D-ZX3nEP.js";
2
+ import { j as isVdeError } from "./search-index-B0xpVDwG.js";
3
3
  //#region src/daemon.ts
4
4
  function notifyParent(message) {
5
5
  if (!process.send) return;
@@ -8752,6 +8752,30 @@ function analyzeDocument(source, format) {
8752
8752
  return format === "markdown" ? analyzeMarkdown(source) : analyzeHtml(source);
8753
8753
  }
8754
8754
  //#endregion
8755
+ //#region ../../packages/document/src/html-link-relay.ts
8756
+ const HTML_LINK_ATTRIBUTE = "data-vde-document-link";
8757
+ const HTML_LINK_RELAY = `(() => {
8758
+ if (parent === window) return;
8759
+ const channel = new MessageChannel();
8760
+ const send = channel.port1.postMessage.bind(channel.port1);
8761
+ const closest = Function.call.bind(Element.prototype.closest);
8762
+ const attribute = Function.call.bind(Element.prototype.getAttribute);
8763
+ const targetOf = Function.call.bind(Object.getOwnPropertyDescriptor(Event.prototype, 'target').get);
8764
+ const preventDefault = Function.call.bind(Event.prototype.preventDefault);
8765
+ const ElementType = Element;
8766
+ const Anchor = HTMLAnchorElement;
8767
+ const Area = HTMLAreaElement;
8768
+ window.addEventListener('click', (event) => {
8769
+ const target = targetOf(event);
8770
+ if (!(target instanceof ElementType)) return;
8771
+ const link = closest(target, 'a[href="#"][${HTML_LINK_ATTRIBUTE}], area[href="#"][${HTML_LINK_ATTRIBUTE}]');
8772
+ if (!(link instanceof Anchor || link instanceof Area)) return;
8773
+ preventDefault(event);
8774
+ if (event.isTrusted) send(attribute(link, '${HTML_LINK_ATTRIBUTE}'));
8775
+ }, true);
8776
+ parent.postMessage('vde-open:document-links', '*', [channel.port2]);
8777
+ })();`;
8778
+ //#endregion
8755
8779
  //#region ../../packages/document/src/rendering-rules.ts
8756
8780
  function renderedLinkOf(href) {
8757
8781
  if (href === void 0 || href === "") return "text";
@@ -14527,6 +14551,7 @@ function rewriteElement(element, policy) {
14527
14551
  for (const attribute of element.attrs) {
14528
14552
  const name = attribute.name;
14529
14553
  if (!ATTRIBUTE_NAME.test(name)) continue;
14554
+ if (policy.relayDocumentLinks && name === "data-vde-document-link") continue;
14530
14555
  if (name.startsWith("on")) {
14531
14556
  if (policy.interactive) kept.push(attribute);
14532
14557
  else handlers += 1;
@@ -14547,8 +14572,19 @@ function rewriteElement(element, policy) {
14547
14572
  if (name === "href") {
14548
14573
  if (tag === "link") kept.push(attribute);
14549
14574
  else if (isAnchor) {
14550
- if (classifyLink(attribute.value).kind === "fragment") kept.push(attribute);
14551
- else policy.link(attribute.value, textOf(element));
14575
+ const { kind } = classifyLink(attribute.value);
14576
+ if (kind === "fragment") kept.push(attribute);
14577
+ else {
14578
+ const linkId = policy.link(attribute.value, textOf(element), kind);
14579
+ if (linkId === null) policy.note("link-disabled", null);
14580
+ else kept.push({
14581
+ ...attribute,
14582
+ value: "#"
14583
+ }, {
14584
+ name: HTML_LINK_ATTRIBUTE,
14585
+ value: linkId
14586
+ });
14587
+ }
14552
14588
  }
14553
14589
  continue;
14554
14590
  }
@@ -14630,7 +14666,7 @@ function rewriteTree(root, policy) {
14630
14666
  if (child.tagName === "style") {
14631
14667
  child.childNodes = [{
14632
14668
  nodeName: "#text",
14633
- value: rewriteCss(textOfStyle(child), "stylesheet", policy),
14669
+ value: rewriteCss(rawTextOf(child), "stylesheet", policy),
14634
14670
  parentNode: child
14635
14671
  }];
14636
14672
  kept.push(child);
@@ -14644,17 +14680,20 @@ function rewriteTree(root, policy) {
14644
14680
  for (const child of kept) child.parentNode = parent;
14645
14681
  }
14646
14682
  }
14647
- function textOfStyle(element) {
14683
+ function rawTextOf(element) {
14648
14684
  let text = "";
14649
14685
  for (const child of element.childNodes) if (child.nodeName === "#text" && "value" in child) text += child.value;
14650
14686
  return text;
14651
14687
  }
14652
- function assertOutput(html, interactive) {
14653
- const stack = [parse$50(html, { scriptingEnabled: false })];
14688
+ function assertOutput(html, interactive, withLinkRelay) {
14689
+ const document = parse$50(html, { scriptingEnabled: false });
14690
+ const relay = withLinkRelay ? headOf(document).childNodes[0] : void 0;
14691
+ if (withLinkRelay && (!relay || !isElement(relay) || relay.tagName !== "script" || relay.attrs.length !== 0 || rawTextOf(relay) !== HTML_LINK_RELAY)) throw new Error("unsafe output: document link relay");
14692
+ const stack = [document];
14654
14693
  while (stack.length > 0) {
14655
14694
  const node = stack.pop();
14656
14695
  if (isElement(node)) {
14657
- if (node.namespaceURI !== HTML_NAMESPACE || REMOVED_ELEMENTS[node.tagName] !== void 0 && !(interactive && node.tagName === "script") || interactive && node.tagName === "noscript" || node.attrs.some((attribute) => attribute.name.startsWith("on") && !interactive || REMOVED_ATTRIBUTES.has(attribute.name))) throw new Error(`unsafe output: ${node.tagName}`);
14696
+ if (node.namespaceURI !== HTML_NAMESPACE || node !== relay && REMOVED_ELEMENTS[node.tagName] !== void 0 && !(interactive && node.tagName === "script") || interactive && node.tagName === "noscript" || node.attrs.some((attribute) => attribute.name.startsWith("on") && !interactive || REMOVED_ATTRIBUTES.has(attribute.name))) throw new Error(`unsafe output: ${node.tagName}`);
14658
14697
  if (node.tagName === "template" && "content" in node) stack.push(node.content);
14659
14698
  }
14660
14699
  if (isParent(node)) for (const child of node.childNodes) stack.push(child);
@@ -14716,29 +14755,32 @@ function resolveAssetUrl(url, context, baseDir, assets, log, options = {}) {
14716
14755
  function transformStaticHtml(input, log = new DiagnosticLog()) {
14717
14756
  const baseDir = dirnameOfLogicalPath(input.documentLogicalPath);
14718
14757
  const links = [];
14719
- const linkIds = /* @__PURE__ */ new Set();
14758
+ const linksByHref = /* @__PURE__ */ new Map();
14720
14759
  const interactive = input.interactive === true;
14760
+ const relayDocumentLinks = input.relayDocumentLinks === true;
14721
14761
  const policy = {
14722
14762
  interactive,
14763
+ relayDocumentLinks,
14723
14764
  note: (code, target) => log.note(code, target),
14724
14765
  asset: (url, context) => resolveAssetUrl(url, context, baseDir, input.assets, log, {
14725
14766
  scripts: interactive,
14726
14767
  ...input.assetUrls === void 0 ? {} : { assetUrls: input.assetUrls }
14727
14768
  }),
14728
- link(href, text) {
14729
- log.note("link-disabled", null);
14730
- const target = classifyLink(href);
14731
- if (target.kind === "fragment" || links.length >= MAX_LINKS) return;
14769
+ link(href, text, kind) {
14732
14770
  const shown = href.trim().slice(0, 2e3);
14733
- if (linkIds.has(shown)) return;
14734
- linkIds.add(shown);
14735
- const linkId = `lnk_${String(links.length + 1).padStart(4, "0")}`;
14736
- links.push({
14737
- linkId,
14738
- href: shown,
14739
- text,
14740
- kind: target.kind
14741
- });
14771
+ let link = linksByHref.get(shown);
14772
+ if (link === void 0) {
14773
+ if (links.length >= MAX_LINKS) return null;
14774
+ link = {
14775
+ linkId: `lnk_${String(links.length + 1).padStart(4, "0")}`,
14776
+ href: shown,
14777
+ text,
14778
+ kind
14779
+ };
14780
+ linksByHref.set(shown, link);
14781
+ links.push(link);
14782
+ }
14783
+ return relayDocumentLinks && kind === "document" && link.kind === "document" ? link.linkId : null;
14742
14784
  }
14743
14785
  };
14744
14786
  const document = parse$50(input.source, { scriptingEnabled: false });
@@ -14746,8 +14788,10 @@ function transformStaticHtml(input, log = new DiagnosticLog()) {
14746
14788
  for (const heading of headings) setId(heading.element, heading.anchor);
14747
14789
  rewriteTree(document, policy);
14748
14790
  if (interactive && input.sdkScript !== void 0) insertFirstScript(document, input.sdkScript);
14791
+ const withLinkRelay = relayDocumentLinks && links.some((link) => link.kind === "document");
14792
+ if (withLinkRelay) insertFirstScript(document, HTML_LINK_RELAY);
14749
14793
  const html = serialize(document);
14750
- assertOutput(html, interactive);
14794
+ assertOutput(html, interactive, withLinkRelay);
14751
14795
  return {
14752
14796
  html,
14753
14797
  links,
@@ -14788,10 +14832,14 @@ function reachable(document, headings) {
14788
14832
  anchor
14789
14833
  }));
14790
14834
  }
14791
- function insertFirstScript(document, source) {
14792
- if (source.toLowerCase().includes("<\/script")) throw new Error("script text must not close itself");
14835
+ function headOf(document) {
14793
14836
  const head = document.childNodes.find((node) => isElement(node) && node.tagName === "html")?.childNodes.find((node) => isElement(node) && node.tagName === "head");
14794
14837
  if (!head) throw new Error("document has no head");
14838
+ return head;
14839
+ }
14840
+ function insertFirstScript(document, source) {
14841
+ if (source.toLowerCase().includes("<\/script")) throw new Error("script text must not close itself");
14842
+ const head = headOf(document);
14795
14843
  const script = {
14796
14844
  nodeName: "script",
14797
14845
  tagName: "script",
@@ -14819,10 +14867,10 @@ function scanHtmlReferences(source) {
14819
14867
  });
14820
14868
  return url;
14821
14869
  },
14822
- link: () => void 0,
14870
+ link: () => null,
14823
14871
  note: () => void 0
14824
14872
  });
14825
14873
  return references;
14826
14874
  }
14827
14875
  //#endregion
14828
- export { escapeAttr as A, roleAllowed as C, defaultTreeAdapter as D, serialize as E, footnoteReferenceId as M, __commonJSMin as N, NS as O, __toESM as P, isValidLogicalPath as S, parseFragment as T, classifyLink as _, scanCssReferences as a, encodeLogicalPath as b, renderedLinkOf as c, analyzeDocument as d, assertWithinLimits as f, assetTypeOf as g, parseMarkdownDocument as h, transformStaticHtml as i, escapeHtml as j, parseMarkdown as k, MARKDOWN_PARSE_OPTIONS as l, markdownUrlTransform as m, resolveAssetUrl as n, transformCss as o, inlineText as p, scanHtmlReferences as r, localImagePath as s, DiagnosticLog as t, ParseLimitError as u, classifyReference as v, parse$50 as w, hasHiddenSegment as x, dirnameOfLogicalPath as y };
14876
+ export { parseMarkdown as A, isValidLogicalPath as C, serialize as D, parseFragment as E, __toESM as F, escapeHtml as M, footnoteReferenceId as N, defaultTreeAdapter as O, __commonJSMin as P, hasHiddenSegment as S, parse$50 as T, assetTypeOf as _, scanCssReferences as a, dirnameOfLogicalPath as b, renderedLinkOf as c, ParseLimitError as d, analyzeDocument as f, parseMarkdownDocument as g, markdownUrlTransform as h, transformStaticHtml as i, escapeAttr as j, NS as k, HTML_LINK_RELAY as l, inlineText as m, resolveAssetUrl as n, transformCss as o, assertWithinLimits as p, scanHtmlReferences as r, localImagePath as s, DiagnosticLog as t, MARKDOWN_PARSE_OPTIONS as u, classifyLink as v, roleAllowed as w, encodeLogicalPath as x, classifyReference as y };