fascicle 0.16.2 → 0.16.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.16.3 — 2026-10-19
4
+
5
+ ### Fixed
6
+
7
+ - **`fascicle-viewer` follows a file whose directory doesn't exist yet, or moves away mid-run.** The viewer waited for a missing file through a watch on the file's directory, so a path whose directory didn't exist yet failed that watch with an io error, and the canvas never filled, even after the file appeared. A file watch follows the file rather than the path, so when the file's directory was moved away with the file inside, nothing reported it, and the viewer never saw a new file made at the old path. Volley's `.volley/trajectory.jsonl` does both, since its directory appears when a run starts, and a harness that keeps each run's record moves it away when the run ends. The viewer now watches the closest directory above the path that exists and moves down a level each time the next directory appears, and while it follows the file it keeps a watch on the file's directory, which reports that directory moving or going away. A file made at the path afterwards is read from its first line, as a rotated file is. A file that stands where a directory on the path should be is a wait as well, not an io error.
8
+
3
9
  ## v0.16.2 — 2026-10-19
4
10
 
5
11
  ### Added
package/dist/viewer.d.ts CHANGED
@@ -121,9 +121,9 @@ type Tail = {
121
121
  *
122
122
  * Watches the file with `fs.watch` and re-reads from the last known offset
123
123
  * on every change, buffering an incomplete trailing line until the rest
124
- * arrives. A missing file is waited for through a watch on its directory,
125
- * and a new file at the path (a different inode) is read from its first
126
- * line. Overlapping change events are coalesced: a read already in flight
124
+ * arrives. A missing file is waited for through a watch on the closest
125
+ * directory above it that exists, and a new file at the path (a different
126
+ * inode) is read from its first line. Overlapping change events are coalesced: a read already in flight
127
127
  * absorbs any events that fire while it runs instead of starting a second
128
128
  * concurrent read.
129
129
  */
package/dist/viewer.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import "./core-CErsxGF6.js";
2
2
  import { l as parse_trajectory_event } from "./trajectory-DeURWIhj.js";
3
3
  import { open, stat } from "node:fs/promises";
4
- import { basename, dirname, extname, resolve, sep } from "node:path";
4
+ import { basename, dirname, extname, relative, resolve, sep } from "node:path";
5
5
  import { createReadStream, existsSync, statSync, watch } from "node:fs";
6
6
  import { spawn } from "node:child_process";
7
7
  import { pipeline } from "node:stream";
@@ -593,10 +593,12 @@ function handle_ingest(req, res, broadcaster, on_parse_error) {
593
593
  * complete line. Handles these pathological cases:
594
594
  *
595
595
  * - A file that doesn't exist yet: a missing file is a wait, not an
596
- * error. The tail reads it from its first line once it appears.
596
+ * error. The tail reads it from its first line once it appears, and the
597
+ * directories above it can be missing too.
597
598
  * - Rotation: a file renamed away and recreated under the same name is a
598
599
  * new inode, so the tail starts the new file from its first line rather
599
- * than at the old file's offset.
600
+ * than at the old file's offset. A file whose directory is moved away,
601
+ * and a new directory made in its place, rotates the same way.
600
602
  * - Truncation: a stat shorter than the current offset means the file
601
603
  * shrank in place. Reset offset to 0 and re-stream.
602
604
  * - Partial last line: if the trailing chunk has no `\n`, buffer it and
@@ -606,14 +608,17 @@ function handle_ingest(req, res, broadcaster, on_parse_error) {
606
608
  *
607
609
  * Two fs.watch watchers drive the reads. A watch on the file itself carries
608
610
  * every append, but it follows the file's inode, so it can't see a file
609
- * appear and after a rename it reports on the old one. So while the file is
610
- * missing, and from the moment that watch reports a rename, a second watch
611
- * on the parent directory waits for the file's name, and the first pass that
612
- * finds a file there moves the file watch onto it and drops the directory
613
- * watch. Appends never ride the directory watch, because macOS serves a
614
- * directory through FSEvents, whose stream starts asynchronously and drops
615
- * what happens before it is live, while a file watch is kqueue's and holds
616
- * from the moment it is made. Reads are serialized, and change events that arrive mid-read are coalesced
611
+ * appear, after a rename it reports on the old one, and it reports nothing
612
+ * when the file's directory moves away with the file inside. A second watch,
613
+ * on a directory, covers those. While the file is missing, it sits on the
614
+ * closest directory above the path that exists and waits for the next name
615
+ * down, so it moves down a level each time a directory on the path appears.
616
+ * Once a pass finds the file, the file watch moves onto it, and the directory
617
+ * watch stays on the file's own directory, where it reports that directory
618
+ * moving or going away. Appends never depend on the directory watch, because
619
+ * macOS serves a directory through FSEvents, whose stream starts
620
+ * asynchronously and drops what happens before it is live, while a file watch
621
+ * is kqueue's and holds from the moment it is made. Reads are serialized, and change events that arrive mid-read are coalesced
617
622
  * into one extra pass rather than dropped, so a burst of appends never starts
618
623
  * overlapping reads. Each pass re-stats and re-reads from the saved offset,
619
624
  * which also covers platforms where fs.watch misses some append
@@ -621,26 +626,73 @@ function handle_ingest(req, res, broadcaster, on_parse_error) {
621
626
  * regardless.
622
627
  */
623
628
  /**
624
- * True for the error a stat or an open throws when nothing is at the path,
629
+ * True for the errors a stat or an open throws when no file is at the path,
625
630
  * which the tail reads as waiting for the file rather than as a failure.
631
+ *
632
+ * Nothing at the path is one (ENOENT), and a file where a directory on the
633
+ * path should be is the other (ENOTDIR), since the file can appear once a
634
+ * directory takes that file's place.
626
635
  */
627
636
  function is_missing(err) {
628
- return Reflect.get(Object(err), "code") === "ENOENT";
637
+ const code = Reflect.get(Object(err), "code");
638
+ return code === "ENOENT" || code === "ENOTDIR";
639
+ }
640
+ /**
641
+ * The inode of the directory at `dir`, or null when no directory is there.
642
+ *
643
+ * An entry that isn't a directory counts as none, since a watch on it could
644
+ * never report the next name down the path.
645
+ */
646
+ function dir_inode(dir) {
647
+ try {
648
+ const st = statSync(dir);
649
+ return st.isDirectory() ? st.ino : null;
650
+ } catch {
651
+ return null;
652
+ }
653
+ }
654
+ /**
655
+ * The closest directory at or above `dir` that exists, with its inode.
656
+ *
657
+ * Every walk up ends at a root, which exists, so this comes back empty only
658
+ * when even a root can't be read.
659
+ */
660
+ function nearest_dir(dir) {
661
+ let at = dir;
662
+ let ino = dir_inode(at);
663
+ while (ino === null) {
664
+ const up = dirname(at);
665
+ if (up === at) return null;
666
+ at = up;
667
+ ino = dir_inode(at);
668
+ }
669
+ return {
670
+ path: at,
671
+ ino
672
+ };
673
+ }
674
+ /**
675
+ * The first name on the way down from `dir` to `path`: the next directory
676
+ * that has to appear, or the file's own name when `dir` holds the file.
677
+ */
678
+ function next_name(dir, path) {
679
+ const rest = relative(dir, path);
680
+ const cut = rest.indexOf(sep);
681
+ return cut === -1 ? rest : rest.slice(0, cut);
629
682
  }
630
683
  /**
631
684
  * Starts tailing `path` and returns a handle to stop or drain it.
632
685
  *
633
686
  * Watches the file with `fs.watch` and re-reads from the last known offset
634
687
  * on every change, buffering an incomplete trailing line until the rest
635
- * arrives. A missing file is waited for through a watch on its directory,
636
- * and a new file at the path (a different inode) is read from its first
637
- * line. Overlapping change events are coalesced: a read already in flight
688
+ * arrives. A missing file is waited for through a watch on the closest
689
+ * directory above it that exists, and a new file at the path (a different
690
+ * inode) is read from its first line. Overlapping change events are coalesced: a read already in flight
638
691
  * absorbs any events that fire while it runs instead of starting a second
639
692
  * concurrent read.
640
693
  */
641
694
  function start_tail(config) {
642
695
  const { path, on_event, on_parse_error, on_io_error } = config;
643
- const name = basename(path);
644
696
  let inode = null;
645
697
  let offset = 0;
646
698
  let buffer = "";
@@ -649,6 +701,8 @@ function start_tail(config) {
649
701
  let closed = false;
650
702
  let file_watcher = null;
651
703
  let dir_watcher = null;
704
+ let watched_dir = null;
705
+ let watched_ino = null;
652
706
  let last_drain = Promise.resolve();
653
707
  const report = (err) => {
654
708
  if (on_io_error && !is_missing(err)) on_io_error(err);
@@ -678,24 +732,32 @@ function start_tail(config) {
678
732
  return null;
679
733
  }
680
734
  };
681
- const await_file = () => {
682
- if (dir_watcher !== null) return;
683
- dir_watcher = watch$1(dirname(path), (_event, filename) => {
684
- if (filename === null || filename === name) schedule();
735
+ const watch_dir = (dir, ino) => {
736
+ if (dir_watcher !== null && watched_dir === dir && watched_ino === ino) return false;
737
+ dir_watcher?.close();
738
+ watched_dir = dir;
739
+ watched_ino = ino;
740
+ const next = next_name(dir, path);
741
+ const own = basename(dir);
742
+ dir_watcher = watch$1(dir, (_event, filename) => {
743
+ if (filename === null || filename === next || filename === own) schedule();
685
744
  });
686
- if (dir_watcher !== null) schedule();
745
+ return dir_watcher !== null;
746
+ };
747
+ const watch_nearest = () => {
748
+ const dir = nearest_dir(dirname(path));
749
+ return dir !== null && watch_dir(dir.path, dir.ino);
750
+ };
751
+ const await_file = () => {
752
+ if (watch_nearest()) schedule();
687
753
  };
688
754
  const adopt = (ino) => {
689
755
  inode = ino;
690
756
  offset = 0;
691
757
  buffer = "";
692
758
  file_watcher?.close();
693
- file_watcher = watch$1(path, (event) => {
694
- if (event === "rename") await_file();
695
- schedule();
696
- });
697
- dir_watcher?.close();
698
- dir_watcher = null;
759
+ file_watcher = watch$1(path, schedule);
760
+ watch_nearest();
699
761
  };
700
762
  const locate = async () => {
701
763
  let st;
@@ -1 +1 @@
1
- {"version":3,"file":"viewer.js","names":["watch","fs_watch"],"sources":["../src/viewer/broadcast.ts","../src/viewer/server.ts","../src/viewer/tail.ts","../src/viewer/start_viewer.ts","../src/viewer/cli.ts"],"sourcesContent":["/**\n * In-process pub/sub for trajectory events.\n *\n * One ring buffer of the last N events plus a Set of subscriber callbacks.\n * Both producers (file tail and HTTP ingest) push into the same broadcaster;\n * SSE writers fan out via `subscribe`.\n */\n\nimport type { ParsedTrajectoryEvent } from '#core'\n\nexport type BroadcastEvent = {\n readonly id: number\n readonly event: ParsedTrajectoryEvent\n}\n\nexport type Subscriber = (entry: BroadcastEvent) => void\n\nexport type Broadcaster = {\n readonly emit: (event: ParsedTrajectoryEvent) => BroadcastEvent\n readonly subscribe: (fn: Subscriber) => () => void\n readonly snapshot: () => readonly BroadcastEvent[]\n readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[]\n readonly size: () => number\n}\n\nexport type BroadcasterConfig = {\n readonly buffer: number\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\n/**\n * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.\n *\n * Each event gets a monotonic `id` so SSE clients can replay from a known\n * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so\n * slow-client backpressure is the subscriber's responsibility. A subscriber\n * that throws is unsubscribed, and the `on_subscriber_error` callback fires\n * once with the captured error so the server can log it.\n */\nexport function create_broadcaster(config: BroadcasterConfig): Broadcaster {\n // `| 0` truncates fractional sizes; clamp so the ring keeps at least one\n // event.\n const max = Math.max(1, config.buffer | 0)\n const ring: BroadcastEvent[] = []\n const subscribers = new Set<Subscriber>()\n let next_id = 1\n\n const emit = (event: ParsedTrajectoryEvent): BroadcastEvent => {\n const entry: BroadcastEvent = { id: next_id++, event }\n ring.push(entry)\n if (ring.length > max) ring.splice(0, ring.length - max)\n // Iterate a copy so deleting a throwing subscriber (or an unsubscribe\n // triggered from inside a callback) cannot upset the live Set.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(entry)\n } catch (err) {\n subscribers.delete(fn)\n if (config.on_subscriber_error) config.on_subscriber_error(err)\n }\n }\n return entry\n }\n\n const subscribe = (fn: Subscriber): (() => void) => {\n subscribers.add(fn)\n return () => { subscribers.delete(fn) }\n }\n\n const snapshot = (): readonly BroadcastEvent[] => [...ring]\n\n const snapshot_after = (last_id: number): readonly BroadcastEvent[] =>\n ring.filter((e) => e.id > last_id)\n\n const size = (): number => ring.length\n\n return { emit, subscribe, snapshot, snapshot_after, size }\n}\n","/**\n * Tiny HTTP server: 5 API routes, SSE fan-out, NDJSON ingest, plus the\n * compiled run canvas served as static files.\n *\n * GET /api/events -> text/event-stream, replaying past the client cursor\n * GET /api/trajectory -> the full run history as NDJSON (file, or ring)\n * GET /api/snapshot -> JSON dump of the ring buffer\n * POST /api/ingest -> newline-delimited trajectory events (http_logger)\n * GET /api/health -> { ok: true }\n * GET /<anything> -> a file from the compiled app, `/` being index.html\n *\n * The server owns nothing but the socket. The broadcaster owns the recent\n * event ring; the tailed file owns the full history; the canvas is a vite build\n * on disk. A client folds `/api/trajectory` for the whole run and then follows\n * `/api/events`, which replays anything past the cursor it names and streams\n * new events live. The ring is bounded memory by design, so history older than\n * it is served from the file the tail already reads.\n *\n * A server bound to a loopback name answers only requests whose `Host` names\n * loopback too, so a web page can't reach it by rebinding a domain of its own\n * to 127.0.0.1. Ingest is mounted unless the config turns it off, reads only\n * `application/x-ndjson`, and refuses a body past 8 MB.\n */\n\nimport { createReadStream, statSync, type Stats } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { isIPv6 } from 'node:net'\nimport { dirname, extname, resolve, sep } from 'node:path'\nimport { pipeline } from 'node:stream'\nimport { fileURLToPath } from 'node:url'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\nimport type { Broadcaster } from './broadcast.js'\n\nconst SSE_HEARTBEAT_MS = 15_000\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/**\n * The header `/api/trajectory` stamps with the broadcaster's newest id: the\n * seam the client resumes SSE from after folding the history dump. The client\n * carries the same literal (`app/history.ts`); the two ends cannot share a\n * module because the browser bundle must not pull in node builtins.\n */\nconst CURSOR_HEADER = 'x-fascicle-cursor'\n\n/**\n * Content types for everything the compiled app ships. Anything outside the\n * map is served as an opaque download rather than guessed at, which keeps a\n * stray file from being executed as script by a browser.\n */\nconst CONTENT_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css; charset=utf-8',\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.woff2': 'font/woff2',\n}\n\nconst FALLBACK_CONTENT_TYPE = 'application/octet-stream'\n\n/**\n * The names that keep the viewer on this machine. A server bound to one of\n * them answers only a request whose `Host` names one of them as well.\n */\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '::1'])\n\n/** The one content type `/api/ingest` reads, which is what `http_logger` sends. */\nconst NDJSON = 'application/x-ndjson'\n\n/**\n * The most bytes one ingest body may carry. `http_logger` posts a single\n * event per request, so only a runaway or hostile client comes near it.\n */\nconst INGEST_LIMIT_BYTES = 8_000_000\n\nexport type ServerConfig = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\n /**\n * Where the compiled canvas lives, defaulting to the bundled\n * `dist/viewer-app`. The tests point it at a fixture directory so the suite\n * never depends on a build having run.\n */\n readonly app_dir?: string\n /**\n * The trajectory file `/api/trajectory` streams as full history. Absent when\n * the server is ingest-fed only, where that route falls back to the ring.\n * Threaded from the tailed `path` by `start_viewer`.\n */\n readonly trajectory_path?: string\n /**\n * Whether `POST /api/ingest` is mounted; default true. Off, the route is a\n * 404 like any path the API doesn't claim, which is how the CLI keeps a\n * viewer that only tails a file from taking posts.\n */\n readonly ingest?: boolean | undefined\n readonly on_parse_error?: (err: unknown, line: string) => void\n}\n\nexport type ViewerServer = {\n readonly url: string\n /** The port the socket bound, which differs from the requested one for `port: 0`. */\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the HTTP server and resolves once it is listening.\n *\n * Wires the five API routes (health, snapshot, trajectory, SSE, ingest) plus\n * the compiled app's static files to a single request handler, and resolves\n * with the bound URL and port and a `close` that shuts the socket down. The\n * `Host` check runs before anything else, then the API routes are matched\n * first and exactly, so no file the canvas ships can ever shadow one.\n */\nexport function start_server(config: ServerConfig): Promise<ViewerServer> {\n const { broadcaster, host, port, app_dir, trajectory_path, ingest = true, on_parse_error } = config\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n if (!host_allowed(host, req.headers.host)) {\n send_forbidden_host(res, host)\n return\n }\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /api/health') {\n send_json(res, 200, { ok: true })\n return\n }\n if (route === 'GET /api/snapshot') {\n send_json(res, 200, { events: broadcaster.snapshot() })\n return\n }\n if (route === 'GET /api/trajectory') {\n serve_trajectory(res, broadcaster, trajectory_path)\n return\n }\n if (route === 'GET /api/events') {\n handle_sse(req, res, broadcaster)\n return\n }\n if (ingest && route === 'POST /api/ingest') {\n handle_ingest(req, res, broadcaster, on_parse_error)\n return\n }\n if (route.startsWith('GET /')) {\n serve_app_asset(res, route, app_dir)\n return\n }\n send_not_found(res, route)\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n // `listen` can fail (for example, port already in use); reject instead of\n // leaving the returned promise pending forever.\n http_server.once('error', res_err)\n http_server.listen(port, host, () => {\n http_server.removeListener('error', res_err)\n const bound_port = bound_port_of(http_server.address(), port)\n res_ok({\n url: `http://${format_authority(host, bound_port)}`,\n port: bound_port,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Resolves the port a listening server actually bound to.\n *\n * `address()` is only an `AddressInfo` for a TCP listen; it is a path string\n * for a unix socket and `null` before listening, so the fallback covers both.\n * The bound port differs from the requested one only when the caller passed 0\n * and asked the OS to pick a free port.\n */\nexport function bound_port_of(addr: ReturnType<Server['address']>, fallback: number): number {\n return addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : fallback\n}\n\n/**\n * Joins a host and port into a URL authority, bracketing an IPv6 literal.\n *\n * `http://::1:4242` is not a URL; `http://[::1]:4242` is. A hostname or IPv4\n * address passes through untouched.\n */\nfunction format_authority(host: string, port: number): string {\n return `${isIPv6(host) ? `[${host}]` : host}:${port}`\n}\n\n/**\n * Whether `host` is a loopback name, which keeps a server bound to it on this\n * machine.\n */\nexport function is_loopback_host(host: string): boolean {\n return LOOPBACK_HOSTS.has(host)\n}\n\n/**\n * The hostname a `Host` header names, lowercased, with an IPv6 literal's\n * brackets and any port taken off.\n */\nfunction host_name(header: string): string {\n const host = header.toLowerCase()\n if (host.startsWith('[')) return host.slice(1, host.indexOf(']'))\n const colon = host.indexOf(':')\n return colon === -1 ? host : host.slice(0, colon)\n}\n\n/**\n * Whether a server bound to `bound` answers a request whose `Host` header is\n * `header`.\n *\n * Bound to a loopback name, it answers only a `Host` that names loopback too,\n * whatever the port, because a page that rebinds a domain of its own to\n * 127.0.0.1 still sends that domain, and would otherwise read every prompt and\n * output in the trajectory. A request with no `Host` is refused as well. Bound\n * anywhere else, it checks nothing: whoever can reach it can read it, which\n * is what the CLI warns about before it binds.\n */\nfunction host_allowed(bound: string, header: string | undefined): boolean {\n if (!is_loopback_host(bound)) return true\n return header !== undefined && is_loopback_host(host_name(header))\n}\n\n/**\n * Writes the 403 for a request whose `Host` a loopback-bound server won't\n * answer, naming the names it will.\n */\nfunction send_forbidden_host(res: ServerResponse, bound: string): void {\n send_json(res, 403, {\n error: 'forbidden_host',\n message: `this viewer is bound to ${bound} and answers only a Host of localhost, 127.0.0.1, or ::1; open it by one of those names`,\n })\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Resolves the path against the client's `Host` header when it parses, and\n * against the server's own `host`/`port` otherwise. A header can be present yet\n * malformed (`'in valid'`), which `??` cannot catch because it is neither null\n * nor undefined; fed to `new URL` it throws. Trying the header inside a\n * try/catch and falling back to the server's authority keeps route resolution\n * total for any header a client sends.\n */\nexport function resolve_route(\n req: {\n url?: string | undefined\n method?: string | undefined\n headers: { host?: string | undefined }\n },\n host: string,\n port: number,\n): string {\n const method = req.method ?? 'GET'\n const path = req.url ?? '/'\n const header = req.headers.host\n if (header !== undefined) {\n try {\n return `${method} ${new URL(path, `http://${header}`).pathname}`\n } catch {\n // A malformed Host header falls through to the server's own authority.\n }\n }\n return `${method} ${new URL(path, `http://${format_authority(host, port)}`).pathname}`\n}\n\n/**\n * Closes the HTTP server and resolves once every connection is torn down.\n */\nfunction close_server(server: Server): Promise<void> {\n return new Promise((res_ok, res_err) => {\n server.close((err) => {\n if (err) res_err(err)\n else res_ok()\n })\n // `close` alone only stops new connections and waits for existing ones\n // (including open SSE streams) to end on their own, which can hang\n // indefinitely. Force them closed so shutdown actually completes.\n // `closeAllConnections` has existed since node 18.2 and `engines.node` is\n // `>=24`, so the call is unconditional.\n server.closeAllConnections()\n })\n}\n\n/**\n * Writes a JSON response with the given status code.\n */\nfunction send_json(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify(body))\n}\n\n/**\n * Writes the JSON 404 that names the route that missed.\n */\nfunction send_not_found(res: ServerResponse, route: string): void {\n send_json(res, 404, { error: 'not_found', route })\n}\n\n/**\n * Handles `GET /api/trajectory` by streaming the whole run history as NDJSON,\n * one event per line, so the client folds the full run before it follows the\n * live tail.\n *\n * The tailed file is the source of truth: its bytes stream straight through,\n * which keeps memory bounded no matter how long the run grew, and a finished\n * `.jsonl` opened with no live producer becomes the same client path as live.\n * An ingest-fed server has no file, so it falls back to the ring buffer, the\n * only history it holds. Either way the response is stamped with the\n * broadcaster's newest id, the seam the client resumes SSE from; the client\n * still takes the larger of that and its own folded count, so a file that ran\n * ahead of the broadcaster is not re-folded.\n */\nfunction serve_trajectory(\n res: ServerResponse,\n broadcaster: Broadcaster,\n trajectory_path: string | undefined,\n): void {\n const ring = broadcaster.snapshot()\n res.statusCode = 200\n res.setHeader('content-type', 'application/x-ndjson; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader(CURSOR_HEADER, String(ring.at(-1)?.id ?? 0))\n\n // The two guards are nested rather than joined with `&&` on purpose: only a\n // present file reaches `createReadStream`, so a path that is undefined (ingest\n // mode) or set-but-uncreated (a run not yet started) falls through to the\n // ring, the only history such a server holds. `stat_file` returns null\n // for a missing path either way, which keeps the fallthrough total.\n if (trajectory_path !== undefined) {\n if (stat_file(trajectory_path) !== null) {\n stream_file(res, trajectory_path)\n return\n }\n }\n res.end(ring.map((entry) => `${JSON.stringify(entry.event)}\\n`).join(''))\n}\n\n/**\n * Where the compiled canvas can be, relative to this module.\n *\n * Published, `viewer.js` sits in `dist/` beside `dist/viewer-app/`. Running\n * from source, this module is `src/viewer/server.ts` and the same build output\n * is two levels up in the repo's `dist/`. The two candidates never both exist\n * for the same install, so probing them in order is unambiguous.\n */\nfunction app_dir_candidates(here: string): readonly string[] {\n return [resolve(here, 'viewer-app'), resolve(here, '..', '..', 'dist', 'viewer-app')]\n}\n\n/**\n * The compiled app directory, or `null` when the canvas has not been built.\n *\n * A directory only counts once its `index.html` is really there, so a\n * half-written build reads as absent rather than as a directory that 404s\n * every asset.\n */\nfunction resolve_app_dir(override: string | undefined): string | null {\n const candidates = override === undefined ? app_dir_candidates(HERE) : [override]\n return candidates.find((dir) => stat_file(resolve(dir, 'index.html')) !== null) ?? null\n}\n\n/**\n * The stats of an existing regular file, or `null` for anything else.\n *\n * One syscall answers both questions the asset route asks: whether to serve\n * the path at all, and what `content-length` to declare. Reading the stats\n * before the stream opens is what keeps a missing file a clean 404 rather\n * than a stream error raised after the headers have gone out.\n */\nfunction stat_file(path: string): Stats | null {\n try {\n const stats = statSync(path)\n return stats.isFile() ? stats : null\n } catch {\n return null\n }\n}\n\n/**\n * Resolves a URL path inside the compiled app directory, or `null` when it\n * escapes it.\n *\n * The server is bound to localhost by default, but a browser will happily\n * send `/../../etc/passwd`, so containment is checked on the resolved path\n * rather than trusted from the URL text.\n */\nfunction resolve_app_file(dir: string, url_path: string): string | null {\n const file = resolve(dir, `.${url_path}`)\n if (file !== dir && !file.startsWith(dir + sep)) return null\n return file === dir ? resolve(dir, 'index.html') : file\n}\n\n/**\n * Streams one file of the compiled canvas as the response body.\n *\n * A missing app directory is a 500 naming the build step, because the server\n * is fine and the operator forgot to compile; a missing file inside a present\n * app is an ordinary 404.\n */\nfunction serve_app_asset(res: ServerResponse, route: string, override: string | undefined): void {\n const dir = resolve_app_dir(override)\n if (dir === null) {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer app not built; run `pnpm build`')\n return\n }\n\n // The route key is `\"<METHOD> <path>\"`; splitting on the space keeps the\n // path independent of which method got here, so the GET guard above stays\n // the only thing deciding whether a non-GET reaches the filesystem.\n const file = resolve_app_file(dir, route.slice(route.indexOf(' ') + 1))\n const stats = file === null ? null : stat_file(file)\n if (file === null || stats === null) {\n send_not_found(res, route)\n return\n }\n\n res.statusCode = 200\n res.setHeader('content-type', CONTENT_TYPES[extname(file)] ?? FALLBACK_CONTENT_TYPE)\n // A localhost dev tool is rebuilt while its tab is open, so nothing it\n // serves may be cached: a stale bundle would look like a broken canvas.\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(stats.size))\n stream_file(res, file)\n}\n\n/**\n * Streams a file as the response body, dropping the connection if the read\n * fails.\n *\n * A file can pass `stat_file` and still refuse to open (mode 000 answers\n * EACCES), and a bare `pipe` leaves that stream error unhandled, which ends the\n * process. `pipeline` handles it by destroying both ends, so the client sees a\n * dropped connection and the server keeps serving. It also closes the file when\n * a client leaves mid-stream.\n */\nfunction stream_file(res: ServerResponse, path: string): void {\n pipeline(createReadStream(path), res, () => {\n // Both streams are already destroyed on failure; nothing is left to undo.\n })\n}\n\n/**\n * Handles `GET /api/events` by turning the connection into an SSE stream.\n *\n * Replays whatever the client missed since its cursor, subscribes it to the\n * broadcaster for new events, and keeps the connection alive with a periodic\n * heartbeat comment. The cursor is the furthest the client can name: the\n * `Last-Event-ID` a reconnecting browser sends, or the `?since=` a fresh load\n * sets after folding `/api/trajectory`, because native `EventSource` cannot set\n * the header on a first connect. That same cursor guards the live subscription,\n * so an event the history dump already carried is never delivered twice when\n * the file ran ahead of the broadcaster at dump time.\n */\nfunction handle_sse(req: IncomingMessage, res: ServerResponse, broadcaster: Broadcaster): void {\n res.statusCode = 200\n res.setHeader('content-type', 'text/event-stream')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('connection', 'keep-alive')\n // Disables response buffering in nginx so SSE frames reach the client as\n // soon as they are written instead of sitting in a proxy buffer.\n res.setHeader('x-accel-buffering', 'no')\n\n // Node holds the response head back until something is written, so a stream\n // that opens on an empty ring buffer would sit headerless until the first\n // heartbeat 15 seconds later, and `EventSource` would not raise `open` until\n // then. One comment frame flushes the head immediately and is ignored by\n // every SSE client.\n res.write(': connected\\n\\n')\n\n // Replay everything after the client's cursor before subscribing. Both\n // calls run synchronously back to back, so there is no window in which\n // an event could land between the replay and the live subscription.\n const cursor = Math.max(\n parse_last_event_id(req.headers['last-event-id']),\n parse_since(req.url),\n )\n for (const entry of broadcaster.snapshot_after(cursor)) {\n write_event(res, entry.id, entry.event)\n }\n\n // Comment frames keep the connection alive through idle proxies and\n // load balancers that would otherwise time out a quiet SSE stream.\n const heartbeat = setInterval(() => {\n res.write(': heartbeat\\n\\n')\n }, SSE_HEARTBEAT_MS)\n\n // The live guard matters only when the cursor sits ahead of the ring: a fresh\n // load that folded a file the broadcaster had not caught up to. In the common\n // reconnect case every live id is already past the cursor, so nothing drops.\n const unsubscribe = broadcaster.subscribe((entry) => {\n if (entry.id > cursor) write_event(res, entry.id, entry.event)\n })\n\n const close = (): void => {\n clearInterval(heartbeat)\n unsubscribe()\n if (!res.writableEnded) {\n res.write('event: close\\ndata: {}\\n\\n')\n res.end()\n }\n }\n\n // A clean disconnect and a socket error both need the same cleanup.\n req.on('close', close)\n req.on('error', close)\n}\n\n/**\n * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.\n *\n * Treats a missing header or a non-numeric or non-positive value as \"no\n * cursor\", which makes `handle_sse` replay the full ring buffer.\n */\nfunction parse_last_event_id(value: string | string[] | undefined): number {\n if (typeof value !== 'string') return 0\n const n = Number.parseInt(value, 10)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n/**\n * Parses the `?since=` cursor off a request URL, defaulting to 0.\n *\n * A fresh load sets it after folding `/api/trajectory`, since native\n * `EventSource` cannot send a `Last-Event-ID` header on a first connect. The\n * value reuses `parse_last_event_id`'s number rule, so a missing, absent, or\n * unusable `since` reads as \"no cursor\" exactly as the header does.\n */\nfunction parse_since(url: string | undefined): number {\n if (typeof url !== 'string') return 0\n const query = url.indexOf('?')\n if (query === -1) return 0\n return parse_last_event_id(new URLSearchParams(url.slice(query + 1)).get('since') ?? undefined)\n}\n\n/**\n * Writes one SSE `trajectory` event frame to the response stream.\n */\nfunction write_event(res: ServerResponse, id: number, event: ParsedTrajectoryEvent): void {\n res.write(`id: ${id}\\nevent: trajectory\\ndata: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Whether a `content-type` header names NDJSON, whatever its case and its\n * parameters, so `application/x-ndjson; charset=utf-8` counts.\n */\nfunction is_ndjson(header: string | undefined): boolean {\n if (header === undefined) return false\n const semicolon = header.indexOf(';')\n const type = semicolon === -1 ? header : header.slice(0, semicolon)\n return type.trim().toLowerCase() === NDJSON\n}\n\n/**\n * Writes the 413 for an ingest body past the limit, closing the connection so\n * the rest of the body is never read.\n */\nfunction send_too_large(res: ServerResponse): void {\n res.setHeader('connection', 'close')\n send_json(res, 413, {\n error: 'payload_too_large',\n message: `an ingest body holds at most ${INGEST_LIMIT_BYTES} bytes; post the events in smaller batches`,\n })\n}\n\n/**\n * Answers an ingest request that won't be read, before any of its body is:\n * a 415 for a body that isn't NDJSON, and a 413 for one whose declared length\n * runs past the limit. Returns whether it answered.\n *\n * Requiring the content type is what keeps a web page out: a page can post a\n * `text/plain` body to any origin without a preflight, but not an NDJSON one.\n */\nfunction refuse_ingest(req: IncomingMessage, res: ServerResponse): boolean {\n if (!is_ndjson(req.headers['content-type'])) {\n send_json(res, 415, {\n error: 'unsupported_media_type',\n message: `post trajectory events as ${NDJSON}, one JSON event to a line`,\n })\n return true\n }\n if (Number(req.headers['content-length']) > INGEST_LIMIT_BYTES) {\n send_too_large(res)\n return true\n }\n return false\n}\n\n/**\n * Handles `POST /api/ingest`: parses newline-delimited trajectory events\n * from the request body and feeds valid ones into the broadcaster.\n *\n * Reports how many lines were accepted vs rejected in the response body;\n * a malformed line is skipped and reported via `on_parse_error`, not\n * treated as a fatal request error. A body sent without a length is counted\n * as it streams, and one that runs past the limit gets its 413 there, after\n * the lines before that point have gone out. Once a request is answered,\n * nothing more it sends is read or reported.\n */\nfunction handle_ingest(\n req: IncomingMessage,\n res: ServerResponse,\n broadcaster: Broadcaster,\n on_parse_error?: (err: unknown, line: string) => void,\n): void {\n if (refuse_ingest(req, res)) return\n let buf = ''\n let received = 0\n let accepted = 0\n let rejected = 0\n\n const consume_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n rejected++\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n rejected++\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n broadcaster.emit(result.data)\n accepted++\n }\n\n req.setEncoding('utf8')\n req.on('data', (chunk: string) => {\n if (res.writableEnded) return\n received += Buffer.byteLength(chunk)\n if (received > INGEST_LIMIT_BYTES) {\n send_too_large(res)\n return\n }\n buf += chunk\n // Consume every complete line in the buffer so far; a trailing partial\n // line (no `\\n` yet) stays in `buf` until a later chunk completes it.\n let nl = buf.indexOf('\\n')\n while (nl !== -1) {\n consume_line(buf.slice(0, nl))\n buf = buf.slice(nl + 1)\n nl = buf.indexOf('\\n')\n }\n })\n req.on('end', () => {\n if (res.writableEnded) return\n // Flush a final line that arrived without a trailing newline.\n if (buf.length > 0) consume_line(buf)\n send_json(res, 200, { accepted, rejected })\n })\n req.on('error', (err: unknown) => {\n if (res.writableEnded) return\n if (on_parse_error) on_parse_error(err, '')\n send_json(res, 400, { error: 'bad_request' })\n })\n}\n\nexport const internals_for_test = {\n SSE_HEARTBEAT_MS,\n CURSOR_HEADER,\n INGEST_LIMIT_BYTES,\n host_allowed,\n app_dir_candidates,\n resolve_app_dir,\n resolve_app_file,\n parse_last_event_id,\n parse_since,\n serve_trajectory,\n handle_sse,\n handle_ingest,\n}\n","/**\n * JSONL file tailer.\n *\n * Follows a path for appends and emits one parsed trajectory event per\n * complete line. Handles these pathological cases:\n *\n * - A file that doesn't exist yet: a missing file is a wait, not an\n * error. The tail reads it from its first line once it appears.\n * - Rotation: a file renamed away and recreated under the same name is a\n * new inode, so the tail starts the new file from its first line rather\n * than at the old file's offset.\n * - Truncation: a stat shorter than the current offset means the file\n * shrank in place. Reset offset to 0 and re-stream.\n * - Partial last line: if the trailing chunk has no `\\n`, buffer it and\n * wait. Never parse a half-written line.\n * - Schema failures: a line that fails `parse_trajectory_event` is\n * dropped and surfaced to `on_parse_error`. The stream keeps going.\n *\n * Two fs.watch watchers drive the reads. A watch on the file itself carries\n * every append, but it follows the file's inode, so it can't see a file\n * appear and after a rename it reports on the old one. So while the file is\n * missing, and from the moment that watch reports a rename, a second watch\n * on the parent directory waits for the file's name, and the first pass that\n * finds a file there moves the file watch onto it and drops the directory\n * watch. Appends never ride the directory watch, because macOS serves a\n * directory through FSEvents, whose stream starts asynchronously and drops\n * what happens before it is live, while a file watch is kqueue's and holds\n * from the moment it is made. Reads are serialized, and change events that arrive mid-read are coalesced\n * into one extra pass rather than dropped, so a burst of appends never starts\n * overlapping reads. Each pass re-stats and re-reads from the saved offset,\n * which also covers platforms where fs.watch misses some append\n * notifications: the next successful change event catches the file up\n * regardless.\n */\n\nimport { type FSWatcher, type WatchListener, watch as fs_watch } from 'node:fs'\nimport { open, stat } from 'node:fs/promises'\nimport { basename, dirname } from 'node:path'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\n\nexport type TailConfig = {\n readonly path: string\n readonly on_event: (event: ParsedTrajectoryEvent) => void\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n}\n\nexport type Tail = {\n readonly stop: () => void\n readonly drain: () => Promise<void>\n}\n\n/**\n * True for the error a stat or an open throws when nothing is at the path,\n * which the tail reads as waiting for the file rather than as a failure.\n */\nfunction is_missing(err: unknown): boolean {\n return Reflect.get(Object(err), 'code') === 'ENOENT'\n}\n\n/**\n * Starts tailing `path` and returns a handle to stop or drain it.\n *\n * Watches the file with `fs.watch` and re-reads from the last known offset\n * on every change, buffering an incomplete trailing line until the rest\n * arrives. A missing file is waited for through a watch on its directory,\n * and a new file at the path (a different inode) is read from its first\n * line. Overlapping change events are coalesced: a read already in flight\n * absorbs any events that fire while it runs instead of starting a second\n * concurrent read.\n */\nexport function start_tail(config: TailConfig): Tail {\n const { path, on_event, on_parse_error, on_io_error } = config\n const name = basename(path)\n let inode: number | null = null\n let offset = 0\n let buffer = ''\n let busy = false\n let pending = false\n let closed = false\n let file_watcher: FSWatcher | null = null\n let dir_watcher: FSWatcher | null = null\n let last_drain: Promise<void> = Promise.resolve()\n\n // A stat or open that finds nothing at the path is the wait for the file,\n // which the CLI has already warned about, so only other failures report.\n const report = (err: unknown): void => {\n if (on_io_error && !is_missing(err)) on_io_error(err)\n }\n\n const handle_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n on_event(result.data)\n }\n\n // Starts a watch, reporting one that can't start (a directory that doesn't\n // exist, say) rather than throwing out of a read pass. A pass that was in\n // flight when the tail stopped starts nothing, so stop() leaves no watch\n // holding the process open.\n const watch = (target: string, listener: WatchListener<string>): FSWatcher | null => {\n if (closed) return null\n try {\n return fs_watch(target, { persistent: true }, listener)\n } catch (err) {\n if (on_io_error) on_io_error(err)\n return null\n }\n }\n\n // Waits on the directory for the file's name. Arming the watch schedules\n // one more pass, which catches a file that appeared between the last stat\n // and the watch. A watch that fails to arm (its directory is missing too)\n // schedules nothing, or every pass would retry it and spin. A platform\n // that can't name the file in an event passes null, which schedules a pass\n // rather than risk missing one.\n const await_file = (): void => {\n if (dir_watcher !== null) return\n dir_watcher = watch(dirname(path), (_event, filename) => {\n if (filename === null || filename === name) schedule()\n })\n if (dir_watcher !== null) schedule()\n }\n\n // Follows the file now at the path from its first line. The file watch\n // moves onto it, and a rename it reports (the file moved away or was\n // deleted) sends the tail back to waiting on the directory.\n const adopt = (ino: number): void => {\n inode = ino\n offset = 0\n buffer = ''\n file_watcher?.close()\n file_watcher = watch(path, (event) => {\n if (event === 'rename') await_file()\n schedule()\n })\n dir_watcher?.close()\n dir_watcher = null\n }\n\n // Stats the path and returns the size to read up to, or null when nothing\n // is there. A missing file forgets its inode, so whatever appears next is\n // read from the top even if the filesystem reuses the number. A new inode\n // (the first sighting, or a file recreated after a rotation) is adopted,\n // and a file shorter than the offset was truncated in place, so both start\n // over at offset 0, since the saved offset means nothing in either.\n const locate = async (): Promise<number | null> => {\n let st\n try {\n st = await stat(path)\n } catch (err) {\n if (is_missing(err)) {\n inode = null\n await_file()\n }\n report(err)\n return null\n }\n if (st.ino !== inode) {\n adopt(st.ino)\n } else if (st.size < offset) {\n offset = 0\n buffer = ''\n }\n return st.size\n }\n\n const read_more = async (): Promise<void> => {\n const size = await locate()\n if (size === null || size === offset) return\n\n const fh = await open(path, 'r').catch((err: unknown) => {\n report(err)\n return null\n })\n if (!fh) return\n try {\n const length = size - offset\n const buf = Buffer.alloc(length)\n const { bytesRead } = await fh.read(buf, 0, length, offset)\n offset += bytesRead\n buffer += buf.subarray(0, bytesRead).toString('utf8')\n } catch (err) {\n // A path that stats and opens can still refuse a read (a directory\n // answers EISDIR). The watcher starts read passes without awaiting\n // them, so the error is reported here rather than left to reject one.\n report(err)\n return\n } finally {\n await fh.close()\n }\n\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n const line = buffer.slice(0, nl)\n buffer = buffer.slice(nl + 1)\n handle_line(line)\n nl = buffer.indexOf('\\n')\n }\n // Anything left in `buffer` has no trailing newline yet; keep it for\n // the next read instead of parsing a half-written line.\n }\n\n // Coalesces watcher bursts: if `schedule` fires while a read is already\n // running, it just flags `pending` and returns. The running loop below\n // checks `pending` after each pass and does one more pass if it was set,\n // so a burst of change events never starts overlapping reads.\n const schedule = (): void => {\n if (closed) return\n if (busy) {\n pending = true\n return\n }\n busy = true\n last_drain = (async (): Promise<void> => {\n try {\n let keep_going = true\n while (keep_going) {\n pending = false\n await read_more()\n keep_going = pending && !closed\n }\n } finally {\n busy = false\n }\n })()\n }\n\n schedule()\n\n const stop = (): void => {\n closed = true\n file_watcher?.close()\n file_watcher = null\n dir_watcher?.close()\n dir_watcher = null\n }\n\n const drain = async (): Promise<void> => {\n schedule()\n await last_drain\n }\n\n return { stop, drain }\n}\n","/**\n * `start_viewer` programmatic embed implementation.\n *\n * Spin up the server, optionally start tailing a JSONL file, and return a\n * handle that can stop both. `start_viewer` only depends on core's wire-format\n * schema; it never reaches into the engine, composites, or any provider.\n */\n\nimport { create_broadcaster } from './broadcast.js'\nimport { start_server, type ViewerServer } from './server.js'\nimport { start_tail, type Tail } from './tail.js'\n\nexport type StartViewerOptions = {\n readonly path?: string\n readonly host?: string\n readonly port?: number\n readonly buffer?: number\n /** Whether the server takes `POST /api/ingest`, which `http_logger` posts to; default true. */\n readonly ingest?: boolean\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport type ViewerHandle = {\n readonly url: string\n readonly host: string\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`\n * is set, a file tail that feeds the same broadcaster.\n *\n * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. SSE is always\n * available, HTTP ingest is on unless `ingest` is false, and tailing is opt-in\n * via `path`.\n */\nexport async function start_viewer(options: StartViewerOptions = {}): Promise<ViewerHandle> {\n const host = options.host ?? '127.0.0.1'\n const port = options.port ?? 4242\n const buffer = options.buffer ?? 1000\n const broadcaster = create_broadcaster({\n buffer,\n ...(options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}),\n })\n const server = await start_server({\n broadcaster,\n host,\n port,\n ingest: options.ingest,\n // The tailed file is `/api/trajectory`'s full-history source; an\n // ingest-only viewer leaves it unset and that route serves the ring.\n ...(options.path !== undefined ? { trajectory_path: options.path } : {}),\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n })\n\n let tail: Tail | null = null\n if (options.path !== undefined) {\n tail = start_tail({\n path: options.path,\n on_event: (event) => { broadcaster.emit(event) },\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n ...(options.on_io_error ? { on_io_error: options.on_io_error } : {}),\n })\n }\n\n return wrap_handle(server, tail, host)\n}\n\n/**\n * Combines the server and optional tail into a single `ViewerHandle`.\n *\n * `close` stops the tail first, then closes the server, mirroring the\n * startup order (server first, tail second) in reverse. The port is the one\n * the server reports binding rather than the requested `port` option, since\n * a caller that passes `0` gets whatever port the OS actually bound.\n */\nfunction wrap_handle(server: ViewerServer, tail: Tail | null, host: string): ViewerHandle {\n return {\n url: server.url,\n host,\n port: server.port,\n close: async () => {\n if (tail) tail.stop()\n await server.close()\n },\n }\n}\n","#!/usr/bin/env tsx\n/**\n * fascicle-viewer CLI.\n *\n * fascicle-viewer <path> # tail a JSONL file (primary)\n * fascicle-viewer --listen # accept HTTP push only\n * fascicle-viewer <path> --listen # both producers feed the same broadcaster\n *\n * Flags: --port <n> --host <h> --buffer <n> --no-open --help\n *\n * `POST /api/ingest` is mounted only under `--listen`, so a viewer that only\n * tails a file takes no posts from anything.\n *\n * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT\n * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`\n * so the `fascicle-viewer` bin shim can drive it from the bundled\n * `dist/viewer.js`.\n */\n\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { parseArgs } from 'node:util'\nimport { fileURLToPath } from 'node:url'\nimport { is_loopback_host } from './server.js'\nimport { start_viewer } from './start_viewer.js'\n\ntype CliArgs = {\n readonly path?: string\n readonly host: string\n readonly port: number\n readonly buffer: number\n readonly listen: boolean\n readonly open: boolean\n}\n\nconst HELP = `\\\nfascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.\n\nUsage:\n fascicle-viewer <path> tail a JSONL file\n fascicle-viewer --listen accept HTTP push only\n fascicle-viewer <path> --listen both producers feed the same broadcaster\n\nOptions:\n --listen accept HTTP push on /api/ingest (off unless set)\n --port <n> port (default 4242)\n --host <h> bind host (default 127.0.0.1; a non-loopback host warns)\n --buffer <n> ring-buffer size (default 1000)\n --no-open do not open the browser\n --help show this message\n`\n\n/**\n * Parses CLI argv into a validated `CliArgs`, exiting on bad input.\n *\n * `--help` prints usage and exits 0. Invalid numeric flags, or a missing\n * <path> without `--listen`, write to stderr and exit 2.\n */\nexport function parse(argv: readonly string[]): CliArgs {\n const { values, positionals } = parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n port: { type: 'string', default: '4242' },\n host: { type: 'string', default: '127.0.0.1' },\n buffer: { type: 'string', default: '1000' },\n listen: { type: 'boolean', default: false },\n open: { type: 'boolean', default: true },\n 'no-open': { type: 'boolean', default: false },\n help: { type: 'boolean', default: false },\n },\n })\n if (values.help) {\n process.stdout.write(HELP)\n process.exit(0)\n }\n const port_raw = values.port\n const buffer_raw = values.buffer\n const port = Number.parseInt(port_raw, 10)\n const buffer = Number.parseInt(buffer_raw, 10)\n if (!Number.isFinite(port) || port <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --port '${port_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --buffer '${buffer_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n const path = positionals[0]\n const listen = values.listen\n if (path === undefined && !listen) {\n process.stderr.write('fascicle-viewer: a <path> is required unless --listen is set\\n')\n process.stderr.write(HELP)\n process.exit(2)\n }\n return {\n ...(path !== undefined ? { path } : {}),\n host: values.host,\n port,\n buffer,\n listen,\n open: !values['no-open'] && values.open,\n }\n}\n\n/**\n * Opens `url` in the platform's default browser, best-effort.\n *\n * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)\n * detached and swallows failures; the CLI prints the URL either way.\n */\nexport function open_browser(url: string): void {\n const platform = process.platform\n const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'\n const args = platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url]\n try {\n const child = spawn(cmd, args, { stdio: 'ignore', detached: true })\n child.on('error', () => {})\n child.unref()\n } catch {\n // Best-effort. The CLI logs the URL anyway.\n }\n}\n\n/**\n * CLI entry point: parses argv, starts the viewer, and wires shutdown.\n *\n * Warns but proceeds when the tailed path does not exist yet or when the\n * bind host is not loopback (the dashboard has no auth). Optionally opens the\n * browser, then installs SIGINT/SIGTERM handlers that close the viewer\n * before exiting.\n */\nexport async function run_viewer_cli(argv: readonly string[]): Promise<void> {\n const args = parse(argv)\n\n if (args.path !== undefined && !existsSync(args.path)) {\n process.stderr.write(\n `fascicle-viewer: warning: ${args.path} does not exist yet, so the viewer will read it from its first line once it is created\\n`,\n )\n }\n if (!is_loopback_host(args.host)) {\n process.stderr.write(\n `fascicle-viewer: warning: binding ${args.host} reaches beyond this machine, and the dashboard has no auth, so anyone who can reach it reads your trajectory stream; pass --host 127.0.0.1 to keep it local\\n`,\n )\n }\n\n const handle = await start_viewer({\n ...(args.path !== undefined ? { path: args.path } : {}),\n host: args.host,\n port: args.port,\n buffer: args.buffer,\n ingest: args.listen,\n on_parse_error: (err, line) => {\n const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line\n process.stderr.write(\n `fascicle-viewer: skipped malformed line: ${preview}\\n ${describe_error(err)}\\n`,\n )\n },\n on_io_error: (err) => {\n process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\\n`)\n },\n })\n\n if (args.path !== undefined) process.stderr.write(`fascicle-viewer: watching ${args.path}\\n`)\n if (args.listen) process.stderr.write(`fascicle-viewer: listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`fascicle-viewer: viewer at ${handle.url}\\n`)\n\n if (args.open) open_browser(handle.url)\n\n const shutdown = async (): Promise<void> => {\n process.stderr.write('\\nfascicle-viewer: shutting down\\n')\n await handle.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\n/**\n * Renders an unknown thrown value as a human-readable message.\n */\nfunction describe_error(err: unknown): string {\n if (err instanceof Error) return err.message\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n}\n\n// ESM main-module detection. The bundler inlines this file into dist/viewer.js,\n// so a fragile suffix check (`endsWith('/cli.js')`) would fire whenever a\n// consumer's own entry script happened to be named cli.js, see\n// https://nodejs.org/api/esm.html#importmetaurl. Compare the resolved path of\n// this module against argv[1] so the auto-execute only fires when the file is\n// run directly (for example, `tsx src/viewer/cli.ts`), not when imported.\nconst invoked_directly =\n process.argv[1] !== undefined &&\n process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) {\n void run_viewer_cli(process.argv.slice(2)).catch((err: unknown) => {\n process.stderr.write(`fascicle-viewer: ${describe_error(err)}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,mBAAmB,QAAwC;CAGzE,MAAM,MAAM,KAAK,IAAI,GAAG,OAAO,SAAS,CAAC;CACzC,MAAM,OAAyB,CAAC;CAChC,MAAM,8BAAc,IAAI,IAAgB;CACxC,IAAI,UAAU;CAEd,MAAM,QAAQ,UAAiD;EAC7D,MAAM,QAAwB;GAAE,IAAI;GAAW;EAAM;EACrD,KAAK,KAAK,KAAK;EACf,IAAI,KAAK,SAAS,KAAK,KAAK,OAAO,GAAG,KAAK,SAAS,GAAG;EAGvD,KAAK,MAAM,MAAM,MAAM,KAAK,WAAW,GACrC,IAAI;GACF,GAAG,KAAK;EACV,SAAS,KAAK;GACZ,YAAY,OAAO,EAAE;GACrB,IAAI,OAAO,qBAAqB,OAAO,oBAAoB,GAAG;EAChE;EAEF,OAAO;CACT;CAEA,MAAM,aAAa,OAAiC;EAClD,YAAY,IAAI,EAAE;EAClB,aAAa;GAAE,YAAY,OAAO,EAAE;EAAE;CACxC;CAEA,MAAM,iBAA4C,CAAC,GAAG,IAAI;CAE1D,MAAM,kBAAkB,YACtB,KAAK,QAAQ,MAAM,EAAE,KAAK,OAAO;CAEnC,MAAM,aAAqB,KAAK;CAEhC,OAAO;EAAE;EAAM;EAAW;EAAU;EAAgB;CAAK;AAC3D;;;;;;;;;;;;;;;;;;;;;;;;;;AC5CA,MAAM,mBAAmB;AACzB,MAAM,OAAO,QAAQ,cAAc,YAAY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AAG,iBAAiB;EAAE,SAAc;CAAE,CAAC;AACjD;;;;AAKA,SAAS,eAAe,KAAsB;CAC5C,IAAI,eAAe,OAAO,OAAO,IAAI;CACrC,IAAI;EACF,OAAO,KAAK,UAAU,GAAG;CAC3B,QAAQ;EACN,OAAO,OAAO,GAAG;CACnB;AACF;AAYA,IAHE,QAAQ,KAAK,OAAO,KAAA,KACpB,QAAQ,KAAK,OAAO,cAAc,YAAY,GAAG,GAGjD,eAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,QAAiB;CACjE,QAAQ,OAAO,MAAM,oBAAoB,eAAe,GAAG,EAAE,GAAG;CAChE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"viewer.js","names":["watch","fs_watch"],"sources":["../src/viewer/broadcast.ts","../src/viewer/server.ts","../src/viewer/tail.ts","../src/viewer/start_viewer.ts","../src/viewer/cli.ts"],"sourcesContent":["/**\n * In-process pub/sub for trajectory events.\n *\n * One ring buffer of the last N events plus a Set of subscriber callbacks.\n * Both producers (file tail and HTTP ingest) push into the same broadcaster;\n * SSE writers fan out via `subscribe`.\n */\n\nimport type { ParsedTrajectoryEvent } from '#core'\n\nexport type BroadcastEvent = {\n readonly id: number\n readonly event: ParsedTrajectoryEvent\n}\n\nexport type Subscriber = (entry: BroadcastEvent) => void\n\nexport type Broadcaster = {\n readonly emit: (event: ParsedTrajectoryEvent) => BroadcastEvent\n readonly subscribe: (fn: Subscriber) => () => void\n readonly snapshot: () => readonly BroadcastEvent[]\n readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[]\n readonly size: () => number\n}\n\nexport type BroadcasterConfig = {\n readonly buffer: number\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\n/**\n * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.\n *\n * Each event gets a monotonic `id` so SSE clients can replay from a known\n * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so\n * slow-client backpressure is the subscriber's responsibility. A subscriber\n * that throws is unsubscribed, and the `on_subscriber_error` callback fires\n * once with the captured error so the server can log it.\n */\nexport function create_broadcaster(config: BroadcasterConfig): Broadcaster {\n // `| 0` truncates fractional sizes; clamp so the ring keeps at least one\n // event.\n const max = Math.max(1, config.buffer | 0)\n const ring: BroadcastEvent[] = []\n const subscribers = new Set<Subscriber>()\n let next_id = 1\n\n const emit = (event: ParsedTrajectoryEvent): BroadcastEvent => {\n const entry: BroadcastEvent = { id: next_id++, event }\n ring.push(entry)\n if (ring.length > max) ring.splice(0, ring.length - max)\n // Iterate a copy so deleting a throwing subscriber (or an unsubscribe\n // triggered from inside a callback) cannot upset the live Set.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(entry)\n } catch (err) {\n subscribers.delete(fn)\n if (config.on_subscriber_error) config.on_subscriber_error(err)\n }\n }\n return entry\n }\n\n const subscribe = (fn: Subscriber): (() => void) => {\n subscribers.add(fn)\n return () => { subscribers.delete(fn) }\n }\n\n const snapshot = (): readonly BroadcastEvent[] => [...ring]\n\n const snapshot_after = (last_id: number): readonly BroadcastEvent[] =>\n ring.filter((e) => e.id > last_id)\n\n const size = (): number => ring.length\n\n return { emit, subscribe, snapshot, snapshot_after, size }\n}\n","/**\n * Tiny HTTP server: 5 API routes, SSE fan-out, NDJSON ingest, plus the\n * compiled run canvas served as static files.\n *\n * GET /api/events -> text/event-stream, replaying past the client cursor\n * GET /api/trajectory -> the full run history as NDJSON (file, or ring)\n * GET /api/snapshot -> JSON dump of the ring buffer\n * POST /api/ingest -> newline-delimited trajectory events (http_logger)\n * GET /api/health -> { ok: true }\n * GET /<anything> -> a file from the compiled app, `/` being index.html\n *\n * The server owns nothing but the socket. The broadcaster owns the recent\n * event ring; the tailed file owns the full history; the canvas is a vite build\n * on disk. A client folds `/api/trajectory` for the whole run and then follows\n * `/api/events`, which replays anything past the cursor it names and streams\n * new events live. The ring is bounded memory by design, so history older than\n * it is served from the file the tail already reads.\n *\n * A server bound to a loopback name answers only requests whose `Host` names\n * loopback too, so a web page can't reach it by rebinding a domain of its own\n * to 127.0.0.1. Ingest is mounted unless the config turns it off, reads only\n * `application/x-ndjson`, and refuses a body past 8 MB.\n */\n\nimport { createReadStream, statSync, type Stats } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { isIPv6 } from 'node:net'\nimport { dirname, extname, resolve, sep } from 'node:path'\nimport { pipeline } from 'node:stream'\nimport { fileURLToPath } from 'node:url'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\nimport type { Broadcaster } from './broadcast.js'\n\nconst SSE_HEARTBEAT_MS = 15_000\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/**\n * The header `/api/trajectory` stamps with the broadcaster's newest id: the\n * seam the client resumes SSE from after folding the history dump. The client\n * carries the same literal (`app/history.ts`); the two ends cannot share a\n * module because the browser bundle must not pull in node builtins.\n */\nconst CURSOR_HEADER = 'x-fascicle-cursor'\n\n/**\n * Content types for everything the compiled app ships. Anything outside the\n * map is served as an opaque download rather than guessed at, which keeps a\n * stray file from being executed as script by a browser.\n */\nconst CONTENT_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css; charset=utf-8',\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.woff2': 'font/woff2',\n}\n\nconst FALLBACK_CONTENT_TYPE = 'application/octet-stream'\n\n/**\n * The names that keep the viewer on this machine. A server bound to one of\n * them answers only a request whose `Host` names one of them as well.\n */\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '::1'])\n\n/** The one content type `/api/ingest` reads, which is what `http_logger` sends. */\nconst NDJSON = 'application/x-ndjson'\n\n/**\n * The most bytes one ingest body may carry. `http_logger` posts a single\n * event per request, so only a runaway or hostile client comes near it.\n */\nconst INGEST_LIMIT_BYTES = 8_000_000\n\nexport type ServerConfig = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\n /**\n * Where the compiled canvas lives, defaulting to the bundled\n * `dist/viewer-app`. The tests point it at a fixture directory so the suite\n * never depends on a build having run.\n */\n readonly app_dir?: string\n /**\n * The trajectory file `/api/trajectory` streams as full history. Absent when\n * the server is ingest-fed only, where that route falls back to the ring.\n * Threaded from the tailed `path` by `start_viewer`.\n */\n readonly trajectory_path?: string\n /**\n * Whether `POST /api/ingest` is mounted; default true. Off, the route is a\n * 404 like any path the API doesn't claim, which is how the CLI keeps a\n * viewer that only tails a file from taking posts.\n */\n readonly ingest?: boolean | undefined\n readonly on_parse_error?: (err: unknown, line: string) => void\n}\n\nexport type ViewerServer = {\n readonly url: string\n /** The port the socket bound, which differs from the requested one for `port: 0`. */\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the HTTP server and resolves once it is listening.\n *\n * Wires the five API routes (health, snapshot, trajectory, SSE, ingest) plus\n * the compiled app's static files to a single request handler, and resolves\n * with the bound URL and port and a `close` that shuts the socket down. The\n * `Host` check runs before anything else, then the API routes are matched\n * first and exactly, so no file the canvas ships can ever shadow one.\n */\nexport function start_server(config: ServerConfig): Promise<ViewerServer> {\n const { broadcaster, host, port, app_dir, trajectory_path, ingest = true, on_parse_error } = config\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n if (!host_allowed(host, req.headers.host)) {\n send_forbidden_host(res, host)\n return\n }\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /api/health') {\n send_json(res, 200, { ok: true })\n return\n }\n if (route === 'GET /api/snapshot') {\n send_json(res, 200, { events: broadcaster.snapshot() })\n return\n }\n if (route === 'GET /api/trajectory') {\n serve_trajectory(res, broadcaster, trajectory_path)\n return\n }\n if (route === 'GET /api/events') {\n handle_sse(req, res, broadcaster)\n return\n }\n if (ingest && route === 'POST /api/ingest') {\n handle_ingest(req, res, broadcaster, on_parse_error)\n return\n }\n if (route.startsWith('GET /')) {\n serve_app_asset(res, route, app_dir)\n return\n }\n send_not_found(res, route)\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n // `listen` can fail (for example, port already in use); reject instead of\n // leaving the returned promise pending forever.\n http_server.once('error', res_err)\n http_server.listen(port, host, () => {\n http_server.removeListener('error', res_err)\n const bound_port = bound_port_of(http_server.address(), port)\n res_ok({\n url: `http://${format_authority(host, bound_port)}`,\n port: bound_port,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Resolves the port a listening server actually bound to.\n *\n * `address()` is only an `AddressInfo` for a TCP listen; it is a path string\n * for a unix socket and `null` before listening, so the fallback covers both.\n * The bound port differs from the requested one only when the caller passed 0\n * and asked the OS to pick a free port.\n */\nexport function bound_port_of(addr: ReturnType<Server['address']>, fallback: number): number {\n return addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : fallback\n}\n\n/**\n * Joins a host and port into a URL authority, bracketing an IPv6 literal.\n *\n * `http://::1:4242` is not a URL; `http://[::1]:4242` is. A hostname or IPv4\n * address passes through untouched.\n */\nfunction format_authority(host: string, port: number): string {\n return `${isIPv6(host) ? `[${host}]` : host}:${port}`\n}\n\n/**\n * Whether `host` is a loopback name, which keeps a server bound to it on this\n * machine.\n */\nexport function is_loopback_host(host: string): boolean {\n return LOOPBACK_HOSTS.has(host)\n}\n\n/**\n * The hostname a `Host` header names, lowercased, with an IPv6 literal's\n * brackets and any port taken off.\n */\nfunction host_name(header: string): string {\n const host = header.toLowerCase()\n if (host.startsWith('[')) return host.slice(1, host.indexOf(']'))\n const colon = host.indexOf(':')\n return colon === -1 ? host : host.slice(0, colon)\n}\n\n/**\n * Whether a server bound to `bound` answers a request whose `Host` header is\n * `header`.\n *\n * Bound to a loopback name, it answers only a `Host` that names loopback too,\n * whatever the port, because a page that rebinds a domain of its own to\n * 127.0.0.1 still sends that domain, and would otherwise read every prompt and\n * output in the trajectory. A request with no `Host` is refused as well. Bound\n * anywhere else, it checks nothing: whoever can reach it can read it, which\n * is what the CLI warns about before it binds.\n */\nfunction host_allowed(bound: string, header: string | undefined): boolean {\n if (!is_loopback_host(bound)) return true\n return header !== undefined && is_loopback_host(host_name(header))\n}\n\n/**\n * Writes the 403 for a request whose `Host` a loopback-bound server won't\n * answer, naming the names it will.\n */\nfunction send_forbidden_host(res: ServerResponse, bound: string): void {\n send_json(res, 403, {\n error: 'forbidden_host',\n message: `this viewer is bound to ${bound} and answers only a Host of localhost, 127.0.0.1, or ::1; open it by one of those names`,\n })\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Resolves the path against the client's `Host` header when it parses, and\n * against the server's own `host`/`port` otherwise. A header can be present yet\n * malformed (`'in valid'`), which `??` cannot catch because it is neither null\n * nor undefined; fed to `new URL` it throws. Trying the header inside a\n * try/catch and falling back to the server's authority keeps route resolution\n * total for any header a client sends.\n */\nexport function resolve_route(\n req: {\n url?: string | undefined\n method?: string | undefined\n headers: { host?: string | undefined }\n },\n host: string,\n port: number,\n): string {\n const method = req.method ?? 'GET'\n const path = req.url ?? '/'\n const header = req.headers.host\n if (header !== undefined) {\n try {\n return `${method} ${new URL(path, `http://${header}`).pathname}`\n } catch {\n // A malformed Host header falls through to the server's own authority.\n }\n }\n return `${method} ${new URL(path, `http://${format_authority(host, port)}`).pathname}`\n}\n\n/**\n * Closes the HTTP server and resolves once every connection is torn down.\n */\nfunction close_server(server: Server): Promise<void> {\n return new Promise((res_ok, res_err) => {\n server.close((err) => {\n if (err) res_err(err)\n else res_ok()\n })\n // `close` alone only stops new connections and waits for existing ones\n // (including open SSE streams) to end on their own, which can hang\n // indefinitely. Force them closed so shutdown actually completes.\n // `closeAllConnections` has existed since node 18.2 and `engines.node` is\n // `>=24`, so the call is unconditional.\n server.closeAllConnections()\n })\n}\n\n/**\n * Writes a JSON response with the given status code.\n */\nfunction send_json(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify(body))\n}\n\n/**\n * Writes the JSON 404 that names the route that missed.\n */\nfunction send_not_found(res: ServerResponse, route: string): void {\n send_json(res, 404, { error: 'not_found', route })\n}\n\n/**\n * Handles `GET /api/trajectory` by streaming the whole run history as NDJSON,\n * one event per line, so the client folds the full run before it follows the\n * live tail.\n *\n * The tailed file is the source of truth: its bytes stream straight through,\n * which keeps memory bounded no matter how long the run grew, and a finished\n * `.jsonl` opened with no live producer becomes the same client path as live.\n * An ingest-fed server has no file, so it falls back to the ring buffer, the\n * only history it holds. Either way the response is stamped with the\n * broadcaster's newest id, the seam the client resumes SSE from; the client\n * still takes the larger of that and its own folded count, so a file that ran\n * ahead of the broadcaster is not re-folded.\n */\nfunction serve_trajectory(\n res: ServerResponse,\n broadcaster: Broadcaster,\n trajectory_path: string | undefined,\n): void {\n const ring = broadcaster.snapshot()\n res.statusCode = 200\n res.setHeader('content-type', 'application/x-ndjson; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader(CURSOR_HEADER, String(ring.at(-1)?.id ?? 0))\n\n // The two guards are nested rather than joined with `&&` on purpose: only a\n // present file reaches `createReadStream`, so a path that is undefined (ingest\n // mode) or set-but-uncreated (a run not yet started) falls through to the\n // ring, the only history such a server holds. `stat_file` returns null\n // for a missing path either way, which keeps the fallthrough total.\n if (trajectory_path !== undefined) {\n if (stat_file(trajectory_path) !== null) {\n stream_file(res, trajectory_path)\n return\n }\n }\n res.end(ring.map((entry) => `${JSON.stringify(entry.event)}\\n`).join(''))\n}\n\n/**\n * Where the compiled canvas can be, relative to this module.\n *\n * Published, `viewer.js` sits in `dist/` beside `dist/viewer-app/`. Running\n * from source, this module is `src/viewer/server.ts` and the same build output\n * is two levels up in the repo's `dist/`. The two candidates never both exist\n * for the same install, so probing them in order is unambiguous.\n */\nfunction app_dir_candidates(here: string): readonly string[] {\n return [resolve(here, 'viewer-app'), resolve(here, '..', '..', 'dist', 'viewer-app')]\n}\n\n/**\n * The compiled app directory, or `null` when the canvas has not been built.\n *\n * A directory only counts once its `index.html` is really there, so a\n * half-written build reads as absent rather than as a directory that 404s\n * every asset.\n */\nfunction resolve_app_dir(override: string | undefined): string | null {\n const candidates = override === undefined ? app_dir_candidates(HERE) : [override]\n return candidates.find((dir) => stat_file(resolve(dir, 'index.html')) !== null) ?? null\n}\n\n/**\n * The stats of an existing regular file, or `null` for anything else.\n *\n * One syscall answers both questions the asset route asks: whether to serve\n * the path at all, and what `content-length` to declare. Reading the stats\n * before the stream opens is what keeps a missing file a clean 404 rather\n * than a stream error raised after the headers have gone out.\n */\nfunction stat_file(path: string): Stats | null {\n try {\n const stats = statSync(path)\n return stats.isFile() ? stats : null\n } catch {\n return null\n }\n}\n\n/**\n * Resolves a URL path inside the compiled app directory, or `null` when it\n * escapes it.\n *\n * The server is bound to localhost by default, but a browser will happily\n * send `/../../etc/passwd`, so containment is checked on the resolved path\n * rather than trusted from the URL text.\n */\nfunction resolve_app_file(dir: string, url_path: string): string | null {\n const file = resolve(dir, `.${url_path}`)\n if (file !== dir && !file.startsWith(dir + sep)) return null\n return file === dir ? resolve(dir, 'index.html') : file\n}\n\n/**\n * Streams one file of the compiled canvas as the response body.\n *\n * A missing app directory is a 500 naming the build step, because the server\n * is fine and the operator forgot to compile; a missing file inside a present\n * app is an ordinary 404.\n */\nfunction serve_app_asset(res: ServerResponse, route: string, override: string | undefined): void {\n const dir = resolve_app_dir(override)\n if (dir === null) {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer app not built; run `pnpm build`')\n return\n }\n\n // The route key is `\"<METHOD> <path>\"`; splitting on the space keeps the\n // path independent of which method got here, so the GET guard above stays\n // the only thing deciding whether a non-GET reaches the filesystem.\n const file = resolve_app_file(dir, route.slice(route.indexOf(' ') + 1))\n const stats = file === null ? null : stat_file(file)\n if (file === null || stats === null) {\n send_not_found(res, route)\n return\n }\n\n res.statusCode = 200\n res.setHeader('content-type', CONTENT_TYPES[extname(file)] ?? FALLBACK_CONTENT_TYPE)\n // A localhost dev tool is rebuilt while its tab is open, so nothing it\n // serves may be cached: a stale bundle would look like a broken canvas.\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(stats.size))\n stream_file(res, file)\n}\n\n/**\n * Streams a file as the response body, dropping the connection if the read\n * fails.\n *\n * A file can pass `stat_file` and still refuse to open (mode 000 answers\n * EACCES), and a bare `pipe` leaves that stream error unhandled, which ends the\n * process. `pipeline` handles it by destroying both ends, so the client sees a\n * dropped connection and the server keeps serving. It also closes the file when\n * a client leaves mid-stream.\n */\nfunction stream_file(res: ServerResponse, path: string): void {\n pipeline(createReadStream(path), res, () => {\n // Both streams are already destroyed on failure; nothing is left to undo.\n })\n}\n\n/**\n * Handles `GET /api/events` by turning the connection into an SSE stream.\n *\n * Replays whatever the client missed since its cursor, subscribes it to the\n * broadcaster for new events, and keeps the connection alive with a periodic\n * heartbeat comment. The cursor is the furthest the client can name: the\n * `Last-Event-ID` a reconnecting browser sends, or the `?since=` a fresh load\n * sets after folding `/api/trajectory`, because native `EventSource` cannot set\n * the header on a first connect. That same cursor guards the live subscription,\n * so an event the history dump already carried is never delivered twice when\n * the file ran ahead of the broadcaster at dump time.\n */\nfunction handle_sse(req: IncomingMessage, res: ServerResponse, broadcaster: Broadcaster): void {\n res.statusCode = 200\n res.setHeader('content-type', 'text/event-stream')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('connection', 'keep-alive')\n // Disables response buffering in nginx so SSE frames reach the client as\n // soon as they are written instead of sitting in a proxy buffer.\n res.setHeader('x-accel-buffering', 'no')\n\n // Node holds the response head back until something is written, so a stream\n // that opens on an empty ring buffer would sit headerless until the first\n // heartbeat 15 seconds later, and `EventSource` would not raise `open` until\n // then. One comment frame flushes the head immediately and is ignored by\n // every SSE client.\n res.write(': connected\\n\\n')\n\n // Replay everything after the client's cursor before subscribing. Both\n // calls run synchronously back to back, so there is no window in which\n // an event could land between the replay and the live subscription.\n const cursor = Math.max(\n parse_last_event_id(req.headers['last-event-id']),\n parse_since(req.url),\n )\n for (const entry of broadcaster.snapshot_after(cursor)) {\n write_event(res, entry.id, entry.event)\n }\n\n // Comment frames keep the connection alive through idle proxies and\n // load balancers that would otherwise time out a quiet SSE stream.\n const heartbeat = setInterval(() => {\n res.write(': heartbeat\\n\\n')\n }, SSE_HEARTBEAT_MS)\n\n // The live guard matters only when the cursor sits ahead of the ring: a fresh\n // load that folded a file the broadcaster had not caught up to. In the common\n // reconnect case every live id is already past the cursor, so nothing drops.\n const unsubscribe = broadcaster.subscribe((entry) => {\n if (entry.id > cursor) write_event(res, entry.id, entry.event)\n })\n\n const close = (): void => {\n clearInterval(heartbeat)\n unsubscribe()\n if (!res.writableEnded) {\n res.write('event: close\\ndata: {}\\n\\n')\n res.end()\n }\n }\n\n // A clean disconnect and a socket error both need the same cleanup.\n req.on('close', close)\n req.on('error', close)\n}\n\n/**\n * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.\n *\n * Treats a missing header or a non-numeric or non-positive value as \"no\n * cursor\", which makes `handle_sse` replay the full ring buffer.\n */\nfunction parse_last_event_id(value: string | string[] | undefined): number {\n if (typeof value !== 'string') return 0\n const n = Number.parseInt(value, 10)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n/**\n * Parses the `?since=` cursor off a request URL, defaulting to 0.\n *\n * A fresh load sets it after folding `/api/trajectory`, since native\n * `EventSource` cannot send a `Last-Event-ID` header on a first connect. The\n * value reuses `parse_last_event_id`'s number rule, so a missing, absent, or\n * unusable `since` reads as \"no cursor\" exactly as the header does.\n */\nfunction parse_since(url: string | undefined): number {\n if (typeof url !== 'string') return 0\n const query = url.indexOf('?')\n if (query === -1) return 0\n return parse_last_event_id(new URLSearchParams(url.slice(query + 1)).get('since') ?? undefined)\n}\n\n/**\n * Writes one SSE `trajectory` event frame to the response stream.\n */\nfunction write_event(res: ServerResponse, id: number, event: ParsedTrajectoryEvent): void {\n res.write(`id: ${id}\\nevent: trajectory\\ndata: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Whether a `content-type` header names NDJSON, whatever its case and its\n * parameters, so `application/x-ndjson; charset=utf-8` counts.\n */\nfunction is_ndjson(header: string | undefined): boolean {\n if (header === undefined) return false\n const semicolon = header.indexOf(';')\n const type = semicolon === -1 ? header : header.slice(0, semicolon)\n return type.trim().toLowerCase() === NDJSON\n}\n\n/**\n * Writes the 413 for an ingest body past the limit, closing the connection so\n * the rest of the body is never read.\n */\nfunction send_too_large(res: ServerResponse): void {\n res.setHeader('connection', 'close')\n send_json(res, 413, {\n error: 'payload_too_large',\n message: `an ingest body holds at most ${INGEST_LIMIT_BYTES} bytes; post the events in smaller batches`,\n })\n}\n\n/**\n * Answers an ingest request that won't be read, before any of its body is:\n * a 415 for a body that isn't NDJSON, and a 413 for one whose declared length\n * runs past the limit. Returns whether it answered.\n *\n * Requiring the content type is what keeps a web page out: a page can post a\n * `text/plain` body to any origin without a preflight, but not an NDJSON one.\n */\nfunction refuse_ingest(req: IncomingMessage, res: ServerResponse): boolean {\n if (!is_ndjson(req.headers['content-type'])) {\n send_json(res, 415, {\n error: 'unsupported_media_type',\n message: `post trajectory events as ${NDJSON}, one JSON event to a line`,\n })\n return true\n }\n if (Number(req.headers['content-length']) > INGEST_LIMIT_BYTES) {\n send_too_large(res)\n return true\n }\n return false\n}\n\n/**\n * Handles `POST /api/ingest`: parses newline-delimited trajectory events\n * from the request body and feeds valid ones into the broadcaster.\n *\n * Reports how many lines were accepted vs rejected in the response body;\n * a malformed line is skipped and reported via `on_parse_error`, not\n * treated as a fatal request error. A body sent without a length is counted\n * as it streams, and one that runs past the limit gets its 413 there, after\n * the lines before that point have gone out. Once a request is answered,\n * nothing more it sends is read or reported.\n */\nfunction handle_ingest(\n req: IncomingMessage,\n res: ServerResponse,\n broadcaster: Broadcaster,\n on_parse_error?: (err: unknown, line: string) => void,\n): void {\n if (refuse_ingest(req, res)) return\n let buf = ''\n let received = 0\n let accepted = 0\n let rejected = 0\n\n const consume_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n rejected++\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n rejected++\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n broadcaster.emit(result.data)\n accepted++\n }\n\n req.setEncoding('utf8')\n req.on('data', (chunk: string) => {\n if (res.writableEnded) return\n received += Buffer.byteLength(chunk)\n if (received > INGEST_LIMIT_BYTES) {\n send_too_large(res)\n return\n }\n buf += chunk\n // Consume every complete line in the buffer so far; a trailing partial\n // line (no `\\n` yet) stays in `buf` until a later chunk completes it.\n let nl = buf.indexOf('\\n')\n while (nl !== -1) {\n consume_line(buf.slice(0, nl))\n buf = buf.slice(nl + 1)\n nl = buf.indexOf('\\n')\n }\n })\n req.on('end', () => {\n if (res.writableEnded) return\n // Flush a final line that arrived without a trailing newline.\n if (buf.length > 0) consume_line(buf)\n send_json(res, 200, { accepted, rejected })\n })\n req.on('error', (err: unknown) => {\n if (res.writableEnded) return\n if (on_parse_error) on_parse_error(err, '')\n send_json(res, 400, { error: 'bad_request' })\n })\n}\n\nexport const internals_for_test = {\n SSE_HEARTBEAT_MS,\n CURSOR_HEADER,\n INGEST_LIMIT_BYTES,\n host_allowed,\n app_dir_candidates,\n resolve_app_dir,\n resolve_app_file,\n parse_last_event_id,\n parse_since,\n serve_trajectory,\n handle_sse,\n handle_ingest,\n}\n","/**\n * JSONL file tailer.\n *\n * Follows a path for appends and emits one parsed trajectory event per\n * complete line. Handles these pathological cases:\n *\n * - A file that doesn't exist yet: a missing file is a wait, not an\n * error. The tail reads it from its first line once it appears, and the\n * directories above it can be missing too.\n * - Rotation: a file renamed away and recreated under the same name is a\n * new inode, so the tail starts the new file from its first line rather\n * than at the old file's offset. A file whose directory is moved away,\n * and a new directory made in its place, rotates the same way.\n * - Truncation: a stat shorter than the current offset means the file\n * shrank in place. Reset offset to 0 and re-stream.\n * - Partial last line: if the trailing chunk has no `\\n`, buffer it and\n * wait. Never parse a half-written line.\n * - Schema failures: a line that fails `parse_trajectory_event` is\n * dropped and surfaced to `on_parse_error`. The stream keeps going.\n *\n * Two fs.watch watchers drive the reads. A watch on the file itself carries\n * every append, but it follows the file's inode, so it can't see a file\n * appear, after a rename it reports on the old one, and it reports nothing\n * when the file's directory moves away with the file inside. A second watch,\n * on a directory, covers those. While the file is missing, it sits on the\n * closest directory above the path that exists and waits for the next name\n * down, so it moves down a level each time a directory on the path appears.\n * Once a pass finds the file, the file watch moves onto it, and the directory\n * watch stays on the file's own directory, where it reports that directory\n * moving or going away. Appends never depend on the directory watch, because\n * macOS serves a directory through FSEvents, whose stream starts\n * asynchronously and drops what happens before it is live, while a file watch\n * is kqueue's and holds from the moment it is made. Reads are serialized, and change events that arrive mid-read are coalesced\n * into one extra pass rather than dropped, so a burst of appends never starts\n * overlapping reads. Each pass re-stats and re-reads from the saved offset,\n * which also covers platforms where fs.watch misses some append\n * notifications: the next successful change event catches the file up\n * regardless.\n */\n\nimport { type FSWatcher, type WatchListener, statSync, watch as fs_watch } from 'node:fs'\nimport { open, stat } from 'node:fs/promises'\nimport { basename, dirname, relative, sep } from 'node:path'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\n\nexport type TailConfig = {\n readonly path: string\n readonly on_event: (event: ParsedTrajectoryEvent) => void\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n}\n\nexport type Tail = {\n readonly stop: () => void\n readonly drain: () => Promise<void>\n}\n\n/**\n * True for the errors a stat or an open throws when no file is at the path,\n * which the tail reads as waiting for the file rather than as a failure.\n *\n * Nothing at the path is one (ENOENT), and a file where a directory on the\n * path should be is the other (ENOTDIR), since the file can appear once a\n * directory takes that file's place.\n */\nfunction is_missing(err: unknown): boolean {\n const code = Reflect.get(Object(err), 'code')\n return code === 'ENOENT' || code === 'ENOTDIR'\n}\n\n/**\n * The inode of the directory at `dir`, or null when no directory is there.\n *\n * An entry that isn't a directory counts as none, since a watch on it could\n * never report the next name down the path.\n */\nfunction dir_inode(dir: string): number | null {\n try {\n const st = statSync(dir)\n return st.isDirectory() ? st.ino : null\n } catch {\n return null\n }\n}\n\n/**\n * The closest directory at or above `dir` that exists, with its inode.\n *\n * Every walk up ends at a root, which exists, so this comes back empty only\n * when even a root can't be read.\n */\nfunction nearest_dir(dir: string): { readonly path: string; readonly ino: number } | null {\n let at = dir\n let ino = dir_inode(at)\n while (ino === null) {\n const up = dirname(at)\n if (up === at) return null\n at = up\n ino = dir_inode(at)\n }\n return { path: at, ino }\n}\n\n/**\n * The first name on the way down from `dir` to `path`: the next directory\n * that has to appear, or the file's own name when `dir` holds the file.\n */\nfunction next_name(dir: string, path: string): string {\n const rest = relative(dir, path)\n const cut = rest.indexOf(sep)\n return cut === -1 ? rest : rest.slice(0, cut)\n}\n\n/**\n * Starts tailing `path` and returns a handle to stop or drain it.\n *\n * Watches the file with `fs.watch` and re-reads from the last known offset\n * on every change, buffering an incomplete trailing line until the rest\n * arrives. A missing file is waited for through a watch on the closest\n * directory above it that exists, and a new file at the path (a different\n * inode) is read from its first line. Overlapping change events are coalesced: a read already in flight\n * absorbs any events that fire while it runs instead of starting a second\n * concurrent read.\n */\nexport function start_tail(config: TailConfig): Tail {\n const { path, on_event, on_parse_error, on_io_error } = config\n let inode: number | null = null\n let offset = 0\n let buffer = ''\n let busy = false\n let pending = false\n let closed = false\n let file_watcher: FSWatcher | null = null\n let dir_watcher: FSWatcher | null = null\n let watched_dir: string | null = null\n let watched_ino: number | null = null\n let last_drain: Promise<void> = Promise.resolve()\n\n // A stat or open that finds nothing at the path is the wait for the file,\n // which the CLI has already warned about, so only other failures report.\n const report = (err: unknown): void => {\n if (on_io_error && !is_missing(err)) on_io_error(err)\n }\n\n const handle_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n on_event(result.data)\n }\n\n // Starts a watch, reporting one that can't start (a directory that doesn't\n // exist, say) rather than throwing out of a read pass. A pass that was in\n // flight when the tail stopped starts nothing, so stop() leaves no watch\n // holding the process open.\n const watch = (target: string, listener: WatchListener<string>): FSWatcher | null => {\n if (closed) return null\n try {\n return fs_watch(target, { persistent: true }, listener)\n } catch (err) {\n if (on_io_error) on_io_error(err)\n return null\n }\n }\n\n // Keeps the one directory watch on `dir`, whose inode is `ino`, and returns\n // true when it armed a new one. A watch already on that directory stays.\n // Any other is replaced, including one on an older directory at the same\n // path, because a watch that follows an inode (inotify's) goes on\n // reporting the old directory wherever it moved. An event for the next\n // name down the path starts a pass, and so does one for the directory's\n // own name, which is how a platform reports the directory itself moving\n // or going away. A platform that can't name the entry in an event passes\n // null, which starts a pass rather than risk missing one.\n const watch_dir = (dir: string, ino: number): boolean => {\n if (dir_watcher !== null && watched_dir === dir && watched_ino === ino) return false\n dir_watcher?.close()\n watched_dir = dir\n watched_ino = ino\n const next = next_name(dir, path)\n const own = basename(dir)\n dir_watcher = watch(dir, (_event, filename) => {\n if (filename === null || filename === next || filename === own) schedule()\n })\n return dir_watcher !== null\n }\n\n // Points the directory watch at the closest directory above the path that\n // exists, and returns true when that armed a new watch.\n const watch_nearest = (): boolean => {\n const dir = nearest_dir(dirname(path))\n return dir !== null && watch_dir(dir.path, dir.ino)\n }\n\n // Waits for the file through a watch on the closest directory above the\n // path that exists. Each pass that still finds no file comes back here, so\n // the watch moves down a level each time the next directory on the path\n // appears. Arming a watch schedules one more pass, which catches whatever\n // appeared between the last stat and the watch. A watch that stays where\n // it was, or fails to arm, schedules nothing, or every pass would start\n // another and spin.\n const await_file = (): void => {\n if (watch_nearest()) schedule()\n }\n\n // Follows the file now at the path from its first line. The file watch\n // moves onto it, and whatever it reports starts a pass, which goes back to\n // waiting when the file moved away or was deleted. The directory watch\n // moves onto the file's own directory and stays there while the file is\n // followed, because a directory that moves away takes the file with it,\n // and the file watch reports nothing for that.\n const adopt = (ino: number): void => {\n inode = ino\n offset = 0\n buffer = ''\n file_watcher?.close()\n file_watcher = watch(path, schedule)\n watch_nearest()\n }\n\n // Stats the path and returns the size to read up to, or null when nothing\n // is there. A missing file forgets its inode, so whatever appears next is\n // read from the top even if the filesystem reuses the number. A new inode\n // (the first sighting, or a file recreated after a rotation) is adopted,\n // and a file shorter than the offset was truncated in place, so both start\n // over at offset 0, since the saved offset means nothing in either.\n const locate = async (): Promise<number | null> => {\n let st\n try {\n st = await stat(path)\n } catch (err) {\n if (is_missing(err)) {\n inode = null\n await_file()\n }\n report(err)\n return null\n }\n if (st.ino !== inode) {\n adopt(st.ino)\n } else if (st.size < offset) {\n offset = 0\n buffer = ''\n }\n return st.size\n }\n\n const read_more = async (): Promise<void> => {\n const size = await locate()\n if (size === null || size === offset) return\n\n const fh = await open(path, 'r').catch((err: unknown) => {\n report(err)\n return null\n })\n if (!fh) return\n try {\n const length = size - offset\n const buf = Buffer.alloc(length)\n const { bytesRead } = await fh.read(buf, 0, length, offset)\n offset += bytesRead\n buffer += buf.subarray(0, bytesRead).toString('utf8')\n } catch (err) {\n // A path that stats and opens can still refuse a read (a directory\n // answers EISDIR). The watcher starts read passes without awaiting\n // them, so the error is reported here rather than left to reject one.\n report(err)\n return\n } finally {\n await fh.close()\n }\n\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n const line = buffer.slice(0, nl)\n buffer = buffer.slice(nl + 1)\n handle_line(line)\n nl = buffer.indexOf('\\n')\n }\n // Anything left in `buffer` has no trailing newline yet; keep it for\n // the next read instead of parsing a half-written line.\n }\n\n // Coalesces watcher bursts: if `schedule` fires while a read is already\n // running, it just flags `pending` and returns. The running loop below\n // checks `pending` after each pass and does one more pass if it was set,\n // so a burst of change events never starts overlapping reads.\n const schedule = (): void => {\n if (closed) return\n if (busy) {\n pending = true\n return\n }\n busy = true\n last_drain = (async (): Promise<void> => {\n try {\n let keep_going = true\n while (keep_going) {\n pending = false\n await read_more()\n keep_going = pending && !closed\n }\n } finally {\n busy = false\n }\n })()\n }\n\n schedule()\n\n const stop = (): void => {\n closed = true\n file_watcher?.close()\n file_watcher = null\n dir_watcher?.close()\n dir_watcher = null\n }\n\n const drain = async (): Promise<void> => {\n schedule()\n await last_drain\n }\n\n return { stop, drain }\n}\n","/**\n * `start_viewer` programmatic embed implementation.\n *\n * Spin up the server, optionally start tailing a JSONL file, and return a\n * handle that can stop both. `start_viewer` only depends on core's wire-format\n * schema; it never reaches into the engine, composites, or any provider.\n */\n\nimport { create_broadcaster } from './broadcast.js'\nimport { start_server, type ViewerServer } from './server.js'\nimport { start_tail, type Tail } from './tail.js'\n\nexport type StartViewerOptions = {\n readonly path?: string\n readonly host?: string\n readonly port?: number\n readonly buffer?: number\n /** Whether the server takes `POST /api/ingest`, which `http_logger` posts to; default true. */\n readonly ingest?: boolean\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport type ViewerHandle = {\n readonly url: string\n readonly host: string\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`\n * is set, a file tail that feeds the same broadcaster.\n *\n * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. SSE is always\n * available, HTTP ingest is on unless `ingest` is false, and tailing is opt-in\n * via `path`.\n */\nexport async function start_viewer(options: StartViewerOptions = {}): Promise<ViewerHandle> {\n const host = options.host ?? '127.0.0.1'\n const port = options.port ?? 4242\n const buffer = options.buffer ?? 1000\n const broadcaster = create_broadcaster({\n buffer,\n ...(options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}),\n })\n const server = await start_server({\n broadcaster,\n host,\n port,\n ingest: options.ingest,\n // The tailed file is `/api/trajectory`'s full-history source; an\n // ingest-only viewer leaves it unset and that route serves the ring.\n ...(options.path !== undefined ? { trajectory_path: options.path } : {}),\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n })\n\n let tail: Tail | null = null\n if (options.path !== undefined) {\n tail = start_tail({\n path: options.path,\n on_event: (event) => { broadcaster.emit(event) },\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n ...(options.on_io_error ? { on_io_error: options.on_io_error } : {}),\n })\n }\n\n return wrap_handle(server, tail, host)\n}\n\n/**\n * Combines the server and optional tail into a single `ViewerHandle`.\n *\n * `close` stops the tail first, then closes the server, mirroring the\n * startup order (server first, tail second) in reverse. The port is the one\n * the server reports binding rather than the requested `port` option, since\n * a caller that passes `0` gets whatever port the OS actually bound.\n */\nfunction wrap_handle(server: ViewerServer, tail: Tail | null, host: string): ViewerHandle {\n return {\n url: server.url,\n host,\n port: server.port,\n close: async () => {\n if (tail) tail.stop()\n await server.close()\n },\n }\n}\n","#!/usr/bin/env tsx\n/**\n * fascicle-viewer CLI.\n *\n * fascicle-viewer <path> # tail a JSONL file (primary)\n * fascicle-viewer --listen # accept HTTP push only\n * fascicle-viewer <path> --listen # both producers feed the same broadcaster\n *\n * Flags: --port <n> --host <h> --buffer <n> --no-open --help\n *\n * `POST /api/ingest` is mounted only under `--listen`, so a viewer that only\n * tails a file takes no posts from anything.\n *\n * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT\n * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`\n * so the `fascicle-viewer` bin shim can drive it from the bundled\n * `dist/viewer.js`.\n */\n\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { parseArgs } from 'node:util'\nimport { fileURLToPath } from 'node:url'\nimport { is_loopback_host } from './server.js'\nimport { start_viewer } from './start_viewer.js'\n\ntype CliArgs = {\n readonly path?: string\n readonly host: string\n readonly port: number\n readonly buffer: number\n readonly listen: boolean\n readonly open: boolean\n}\n\nconst HELP = `\\\nfascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.\n\nUsage:\n fascicle-viewer <path> tail a JSONL file\n fascicle-viewer --listen accept HTTP push only\n fascicle-viewer <path> --listen both producers feed the same broadcaster\n\nOptions:\n --listen accept HTTP push on /api/ingest (off unless set)\n --port <n> port (default 4242)\n --host <h> bind host (default 127.0.0.1; a non-loopback host warns)\n --buffer <n> ring-buffer size (default 1000)\n --no-open do not open the browser\n --help show this message\n`\n\n/**\n * Parses CLI argv into a validated `CliArgs`, exiting on bad input.\n *\n * `--help` prints usage and exits 0. Invalid numeric flags, or a missing\n * <path> without `--listen`, write to stderr and exit 2.\n */\nexport function parse(argv: readonly string[]): CliArgs {\n const { values, positionals } = parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n port: { type: 'string', default: '4242' },\n host: { type: 'string', default: '127.0.0.1' },\n buffer: { type: 'string', default: '1000' },\n listen: { type: 'boolean', default: false },\n open: { type: 'boolean', default: true },\n 'no-open': { type: 'boolean', default: false },\n help: { type: 'boolean', default: false },\n },\n })\n if (values.help) {\n process.stdout.write(HELP)\n process.exit(0)\n }\n const port_raw = values.port\n const buffer_raw = values.buffer\n const port = Number.parseInt(port_raw, 10)\n const buffer = Number.parseInt(buffer_raw, 10)\n if (!Number.isFinite(port) || port <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --port '${port_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --buffer '${buffer_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n const path = positionals[0]\n const listen = values.listen\n if (path === undefined && !listen) {\n process.stderr.write('fascicle-viewer: a <path> is required unless --listen is set\\n')\n process.stderr.write(HELP)\n process.exit(2)\n }\n return {\n ...(path !== undefined ? { path } : {}),\n host: values.host,\n port,\n buffer,\n listen,\n open: !values['no-open'] && values.open,\n }\n}\n\n/**\n * Opens `url` in the platform's default browser, best-effort.\n *\n * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)\n * detached and swallows failures; the CLI prints the URL either way.\n */\nexport function open_browser(url: string): void {\n const platform = process.platform\n const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'\n const args = platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url]\n try {\n const child = spawn(cmd, args, { stdio: 'ignore', detached: true })\n child.on('error', () => {})\n child.unref()\n } catch {\n // Best-effort. The CLI logs the URL anyway.\n }\n}\n\n/**\n * CLI entry point: parses argv, starts the viewer, and wires shutdown.\n *\n * Warns but proceeds when the tailed path does not exist yet or when the\n * bind host is not loopback (the dashboard has no auth). Optionally opens the\n * browser, then installs SIGINT/SIGTERM handlers that close the viewer\n * before exiting.\n */\nexport async function run_viewer_cli(argv: readonly string[]): Promise<void> {\n const args = parse(argv)\n\n if (args.path !== undefined && !existsSync(args.path)) {\n process.stderr.write(\n `fascicle-viewer: warning: ${args.path} does not exist yet, so the viewer will read it from its first line once it is created\\n`,\n )\n }\n if (!is_loopback_host(args.host)) {\n process.stderr.write(\n `fascicle-viewer: warning: binding ${args.host} reaches beyond this machine, and the dashboard has no auth, so anyone who can reach it reads your trajectory stream; pass --host 127.0.0.1 to keep it local\\n`,\n )\n }\n\n const handle = await start_viewer({\n ...(args.path !== undefined ? { path: args.path } : {}),\n host: args.host,\n port: args.port,\n buffer: args.buffer,\n ingest: args.listen,\n on_parse_error: (err, line) => {\n const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line\n process.stderr.write(\n `fascicle-viewer: skipped malformed line: ${preview}\\n ${describe_error(err)}\\n`,\n )\n },\n on_io_error: (err) => {\n process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\\n`)\n },\n })\n\n if (args.path !== undefined) process.stderr.write(`fascicle-viewer: watching ${args.path}\\n`)\n if (args.listen) process.stderr.write(`fascicle-viewer: listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`fascicle-viewer: viewer at ${handle.url}\\n`)\n\n if (args.open) open_browser(handle.url)\n\n const shutdown = async (): Promise<void> => {\n process.stderr.write('\\nfascicle-viewer: shutting down\\n')\n await handle.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\n/**\n * Renders an unknown thrown value as a human-readable message.\n */\nfunction describe_error(err: unknown): string {\n if (err instanceof Error) return err.message\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n}\n\n// ESM main-module detection. The bundler inlines this file into dist/viewer.js,\n// so a fragile suffix check (`endsWith('/cli.js')`) would fire whenever a\n// consumer's own entry script happened to be named cli.js, see\n// https://nodejs.org/api/esm.html#importmetaurl. Compare the resolved path of\n// this module against argv[1] so the auto-execute only fires when the file is\n// run directly (for example, `tsx src/viewer/cli.ts`), not when imported.\nconst invoked_directly =\n process.argv[1] !== undefined &&\n process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) {\n void run_viewer_cli(process.argv.slice(2)).catch((err: unknown) => {\n process.stderr.write(`fascicle-viewer: ${describe_error(err)}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,mBAAmB,QAAwC;CAGzE,MAAM,MAAM,KAAK,IAAI,GAAG,OAAO,SAAS,CAAC;CACzC,MAAM,OAAyB,CAAC;CAChC,MAAM,8BAAc,IAAI,IAAgB;CACxC,IAAI,UAAU;CAEd,MAAM,QAAQ,UAAiD;EAC7D,MAAM,QAAwB;GAAE,IAAI;GAAW;EAAM;EACrD,KAAK,KAAK,KAAK;EACf,IAAI,KAAK,SAAS,KAAK,KAAK,OAAO,GAAG,KAAK,SAAS,GAAG;EAGvD,KAAK,MAAM,MAAM,MAAM,KAAK,WAAW,GACrC,IAAI;GACF,GAAG,KAAK;EACV,SAAS,KAAK;GACZ,YAAY,OAAO,EAAE;GACrB,IAAI,OAAO,qBAAqB,OAAO,oBAAoB,GAAG;EAChE;EAEF,OAAO;CACT;CAEA,MAAM,aAAa,OAAiC;EAClD,YAAY,IAAI,EAAE;EAClB,aAAa;GAAE,YAAY,OAAO,EAAE;EAAE;C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C5C,IAAI,eAAe,OAAO,OAAO,IAAI;CACrC,IAAI;EACF,OAAO,KAAK,UAAU,GAAG;CAC3B,QAAQ;EACN,OAAO,OAAO,GAAG;CACnB;AACF;AAYA,IAHE,QAAQ,KAAK,OAAO,KAAA,KACpB,QAAQ,KAAK,OAAO,cAAc,YAAY,GAAG,GAGjD,eAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,QAAiB;CACjE,QAAQ,OAAO,MAAM,oBAAoB,eAAe,GAAG,EAAE,GAAG;CAChE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fascicle",
3
- "version": "0.16.2",
3
+ "version": "0.16.3",
4
4
  "description": "Compose agents like plain values. A TypeScript toolkit that wires LLM calls, tools, and functions into typed steps over eight providers. No framework, no ambient state.",
5
5
  "keywords": [
6
6
  "agents",