fascicle 0.11.1 → 0.12.1

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/dist/viewer.js ADDED
@@ -0,0 +1,658 @@
1
+ import { s as parse_trajectory_event } from "./core-DDRhHu5P.js";
2
+ import { open, stat } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import { createReadStream, existsSync, statSync, watch } from "node:fs";
5
+ import { spawn } from "node:child_process";
6
+ import { fileURLToPath } from "node:url";
7
+ import { createServer } from "node:http";
8
+ import { parseArgs } from "node:util";
9
+ //#region src/viewer/broadcast.ts
10
+ /**
11
+ * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.
12
+ *
13
+ * Each event gets a monotonic `id` so SSE clients can replay from a known
14
+ * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so
15
+ * slow-client backpressure is the subscriber's responsibility. A subscriber
16
+ * that throws is unsubscribed, and the `on_subscriber_error` callback fires
17
+ * once with the captured error so the server can log it.
18
+ */
19
+ function create_broadcaster(options) {
20
+ const max = Math.max(1, options.buffer | 0);
21
+ const ring = [];
22
+ const subscribers = /* @__PURE__ */ new Set();
23
+ let next_id = 1;
24
+ const emit = (event) => {
25
+ const entry = {
26
+ id: next_id++,
27
+ event
28
+ };
29
+ ring.push(entry);
30
+ if (ring.length > max) ring.splice(0, ring.length - max);
31
+ for (const fn of Array.from(subscribers)) try {
32
+ fn(entry);
33
+ } catch (err) {
34
+ subscribers.delete(fn);
35
+ if (options.on_subscriber_error) options.on_subscriber_error(err);
36
+ }
37
+ return entry;
38
+ };
39
+ const subscribe = (fn) => {
40
+ subscribers.add(fn);
41
+ return () => {
42
+ subscribers.delete(fn);
43
+ };
44
+ };
45
+ const snapshot = () => [...ring];
46
+ const snapshot_after = (last_id) => ring.filter((e) => e.id > last_id);
47
+ const size = () => ring.length;
48
+ return {
49
+ emit,
50
+ subscribe,
51
+ snapshot,
52
+ snapshot_after,
53
+ size
54
+ };
55
+ }
56
+ //#endregion
57
+ //#region src/viewer/server.ts
58
+ /**
59
+ * Tiny HTTP server: 5 routes, SSE fan-out, NDJSON ingest.
60
+ *
61
+ * GET / -> static viewer.html
62
+ * GET /api/events -> text/event-stream replaying the ring buffer
63
+ * GET /api/snapshot -> JSON dump of the ring buffer
64
+ * POST /api/ingest -> newline-delimited trajectory events (http_logger)
65
+ * GET /api/health -> { ok: true }
66
+ *
67
+ * The server owns nothing but the socket. The broadcaster owns the event
68
+ * history; the static html lives on disk. SSE clients reconnect with
69
+ * `Last-Event-ID` and the server replays anything past their cursor from
70
+ * the ring buffer; older events are gone (bounded memory by design).
71
+ */
72
+ const SSE_HEARTBEAT_MS = 15e3;
73
+ const STATIC_HTML = resolve(dirname(fileURLToPath(import.meta.url)), "static", "viewer.html");
74
+ /**
75
+ * Starts the HTTP server and resolves once it is listening.
76
+ *
77
+ * Wires the five routes (static HTML, health, snapshot, SSE, ingest) to a
78
+ * single request handler and resolves with the bound URL and a `close`
79
+ * that shuts the socket down.
80
+ */
81
+ function start_server(options) {
82
+ const { broadcaster, host, port, on_parse_error } = options;
83
+ const handler = (req, res) => {
84
+ const route = resolve_route(req, host, port);
85
+ if (route === "GET /" || route === "GET /index.html") {
86
+ serve_static_html(res);
87
+ return;
88
+ }
89
+ if (route === "GET /api/health") {
90
+ send_json(res, 200, { ok: true });
91
+ return;
92
+ }
93
+ if (route === "GET /api/snapshot") {
94
+ send_json(res, 200, { events: broadcaster.snapshot() });
95
+ return;
96
+ }
97
+ if (route === "GET /api/events") {
98
+ handle_sse(req, res, broadcaster);
99
+ return;
100
+ }
101
+ if (route === "POST /api/ingest") {
102
+ handle_ingest(req, res, broadcaster, on_parse_error);
103
+ return;
104
+ }
105
+ res.statusCode = 404;
106
+ res.setHeader("content-type", "application/json");
107
+ res.end(JSON.stringify({
108
+ error: "not_found",
109
+ route
110
+ }));
111
+ };
112
+ const http_server = createServer(handler);
113
+ return new Promise((res_ok, res_err) => {
114
+ http_server.once("error", res_err);
115
+ http_server.listen(port, host, () => {
116
+ http_server.removeListener("error", res_err);
117
+ const addr = http_server.address();
118
+ const bound_port = addr !== null && typeof addr === "object" && "port" in addr ? addr.port : port;
119
+ res_ok({
120
+ url: `http://${host}:${bound_port}`,
121
+ close: () => close_server(http_server)
122
+ });
123
+ });
124
+ });
125
+ }
126
+ /**
127
+ * Builds a `"METHOD /path"` route key from a request.
128
+ *
129
+ * Falls back to the server's own `host`/`port` when the request has no
130
+ * `Host` header, so a malformed or missing header never throws inside
131
+ * `new URL`.
132
+ */
133
+ function resolve_route(req, host, port) {
134
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? `${host}:${port}`}`);
135
+ return `${req.method ?? "GET"} ${url.pathname}`;
136
+ }
137
+ /**
138
+ * Closes the HTTP server and resolves once every connection is torn down.
139
+ */
140
+ function close_server(server) {
141
+ return new Promise((res_ok, res_err) => {
142
+ server.close((err) => {
143
+ if (err) res_err(err);
144
+ else res_ok();
145
+ });
146
+ server.closeAllConnections?.();
147
+ });
148
+ }
149
+ /**
150
+ * Writes a JSON response with the given status code.
151
+ */
152
+ function send_json(res, status, body) {
153
+ res.statusCode = status;
154
+ res.setHeader("content-type", "application/json");
155
+ res.end(JSON.stringify(body));
156
+ }
157
+ /**
158
+ * Streams the bundled `viewer.html` as the response body.
159
+ */
160
+ function serve_static_html(res) {
161
+ let size;
162
+ try {
163
+ size = statSync(STATIC_HTML).size;
164
+ } catch {
165
+ res.statusCode = 500;
166
+ res.setHeader("content-type", "text/plain");
167
+ res.end("viewer.html missing");
168
+ return;
169
+ }
170
+ res.statusCode = 200;
171
+ res.setHeader("content-type", "text/html; charset=utf-8");
172
+ res.setHeader("cache-control", "no-store");
173
+ res.setHeader("content-length", String(size));
174
+ createReadStream(STATIC_HTML).pipe(res);
175
+ }
176
+ /**
177
+ * Handles `GET /api/events` by turning the connection into an SSE stream.
178
+ *
179
+ * Replays whatever the client missed since its `Last-Event-ID` cursor,
180
+ * subscribes it to the broadcaster for new events, and keeps the
181
+ * connection alive with a periodic heartbeat comment.
182
+ */
183
+ function handle_sse(req, res, broadcaster) {
184
+ res.statusCode = 200;
185
+ res.setHeader("content-type", "text/event-stream");
186
+ res.setHeader("cache-control", "no-store");
187
+ res.setHeader("connection", "keep-alive");
188
+ res.setHeader("x-accel-buffering", "no");
189
+ const last_event_id = parse_last_event_id(req.headers["last-event-id"]);
190
+ for (const entry of broadcaster.snapshot_after(last_event_id)) write_event(res, entry.id, entry.event);
191
+ const heartbeat = setInterval(() => {
192
+ res.write(": heartbeat\n\n");
193
+ }, SSE_HEARTBEAT_MS);
194
+ const unsubscribe = broadcaster.subscribe((entry) => {
195
+ write_event(res, entry.id, entry.event);
196
+ });
197
+ const close = () => {
198
+ clearInterval(heartbeat);
199
+ unsubscribe();
200
+ if (!res.writableEnded) {
201
+ res.write("event: close\ndata: {}\n\n");
202
+ res.end();
203
+ }
204
+ };
205
+ req.on("close", close);
206
+ req.on("error", close);
207
+ }
208
+ /**
209
+ * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.
210
+ *
211
+ * Treats a missing header or a non-numeric or non-positive value as "no
212
+ * cursor", which makes `handle_sse` replay the full ring buffer.
213
+ */
214
+ function parse_last_event_id(value) {
215
+ if (typeof value !== "string") return 0;
216
+ const n = Number.parseInt(value, 10);
217
+ return Number.isFinite(n) && n > 0 ? n : 0;
218
+ }
219
+ /**
220
+ * Writes one SSE `trajectory` event frame to the response stream.
221
+ */
222
+ function write_event(res, id, event) {
223
+ res.write(`id: ${id}\nevent: trajectory\ndata: ${JSON.stringify(event)}\n\n`);
224
+ }
225
+ /**
226
+ * Handles `POST /api/ingest`: parses newline-delimited trajectory events
227
+ * from the request body and feeds valid ones into the broadcaster.
228
+ *
229
+ * Reports how many lines were accepted vs rejected in the response body;
230
+ * a malformed line is skipped and reported via `on_parse_error`, not
231
+ * treated as a fatal request error.
232
+ */
233
+ function handle_ingest(req, res, broadcaster, on_parse_error) {
234
+ let buf = "";
235
+ let accepted = 0;
236
+ let rejected = 0;
237
+ const consume_line = (line) => {
238
+ if (line.length === 0) return;
239
+ let parsed;
240
+ try {
241
+ parsed = JSON.parse(line);
242
+ } catch (err) {
243
+ rejected++;
244
+ if (on_parse_error) on_parse_error(err, line);
245
+ return;
246
+ }
247
+ const result = parse_trajectory_event(parsed);
248
+ if (!result.success) {
249
+ rejected++;
250
+ if (on_parse_error) on_parse_error(result.error, line);
251
+ return;
252
+ }
253
+ broadcaster.emit(result.data);
254
+ accepted++;
255
+ };
256
+ req.setEncoding("utf8");
257
+ req.on("data", (chunk) => {
258
+ buf += chunk;
259
+ let nl = buf.indexOf("\n");
260
+ while (nl !== -1) {
261
+ consume_line(buf.slice(0, nl));
262
+ buf = buf.slice(nl + 1);
263
+ nl = buf.indexOf("\n");
264
+ }
265
+ });
266
+ req.on("end", () => {
267
+ if (buf.length > 0) consume_line(buf);
268
+ send_json(res, 200, {
269
+ accepted,
270
+ rejected
271
+ });
272
+ });
273
+ req.on("error", (err) => {
274
+ if (on_parse_error) on_parse_error(err, "");
275
+ send_json(res, 400, { error: "bad_request" });
276
+ });
277
+ }
278
+ //#endregion
279
+ //#region src/viewer/tail.ts
280
+ /**
281
+ * JSONL file tailer.
282
+ *
283
+ * Watches a file for appends and emits one parsed trajectory event per
284
+ * complete line. Handles three pathological cases:
285
+ *
286
+ * - Truncation / rotation: a watcher event whose stat is shorter than the
287
+ * current offset means the file shrunk. Reset offset to 0 and re-stream.
288
+ * - Partial last line: if the trailing chunk has no `\n`, buffer it and
289
+ * wait. Never parse a half-written line.
290
+ * - Schema failures: a line that fails `parse_trajectory_event` is
291
+ * dropped and surfaced to `on_parse_error`. The stream keeps going.
292
+ *
293
+ * The watcher is fs.watch-based; reads are serialized and change events
294
+ * that arrive mid-read are coalesced into one extra pass rather than
295
+ * dropped, so a burst of appends never starts overlapping reads. Each pass
296
+ * re-stats and re-reads from the saved offset, which also covers platforms
297
+ * where fs.watch misses some append notifications: the next successful
298
+ * change event catches the file up regardless.
299
+ */
300
+ /**
301
+ * Starts tailing `path` and returns a handle to stop or drain it.
302
+ *
303
+ * Watches the file with `fs.watch` and re-reads from the last known offset
304
+ * on every change, buffering an incomplete trailing line until the rest
305
+ * arrives. Overlapping change events are coalesced: a read already in
306
+ * flight absorbs any events that fire while it runs instead of starting a
307
+ * second concurrent read.
308
+ */
309
+ function start_tail(options) {
310
+ const { path, on_event, on_parse_error, on_io_error } = options;
311
+ let offset = 0;
312
+ let buffer = "";
313
+ let busy = false;
314
+ let pending = false;
315
+ let closed = false;
316
+ let watcher = null;
317
+ let last_drain = Promise.resolve();
318
+ const handle_line = (line) => {
319
+ if (line.length === 0) return;
320
+ let parsed;
321
+ try {
322
+ parsed = JSON.parse(line);
323
+ } catch (err) {
324
+ if (on_parse_error) on_parse_error(err, line);
325
+ return;
326
+ }
327
+ const result = parse_trajectory_event(parsed);
328
+ if (!result.success) {
329
+ if (on_parse_error) on_parse_error(result.error, line);
330
+ return;
331
+ }
332
+ on_event(result.data);
333
+ };
334
+ const read_more = async () => {
335
+ let st;
336
+ try {
337
+ st = await stat(path);
338
+ } catch (err) {
339
+ if (on_io_error) on_io_error(err);
340
+ return;
341
+ }
342
+ if (st.size < offset) {
343
+ offset = 0;
344
+ buffer = "";
345
+ }
346
+ if (st.size === offset) return;
347
+ const fh = await open(path, "r").catch((err) => {
348
+ if (on_io_error) on_io_error(err);
349
+ return null;
350
+ });
351
+ if (!fh) return;
352
+ try {
353
+ const length = st.size - offset;
354
+ const buf = Buffer.alloc(length);
355
+ const { bytesRead } = await fh.read(buf, 0, length, offset);
356
+ offset += bytesRead;
357
+ buffer += buf.subarray(0, bytesRead).toString("utf8");
358
+ } finally {
359
+ await fh.close();
360
+ }
361
+ let nl = buffer.indexOf("\n");
362
+ while (nl !== -1) {
363
+ const line = buffer.slice(0, nl);
364
+ buffer = buffer.slice(nl + 1);
365
+ handle_line(line);
366
+ nl = buffer.indexOf("\n");
367
+ }
368
+ };
369
+ const schedule = () => {
370
+ if (closed) return;
371
+ if (busy) {
372
+ pending = true;
373
+ return;
374
+ }
375
+ busy = true;
376
+ last_drain = (async () => {
377
+ try {
378
+ let keep_going = true;
379
+ while (keep_going) {
380
+ pending = false;
381
+ await read_more();
382
+ keep_going = pending && !closed;
383
+ }
384
+ } finally {
385
+ busy = false;
386
+ }
387
+ })();
388
+ };
389
+ schedule();
390
+ try {
391
+ watcher = watch(path, { persistent: true }, () => {
392
+ schedule();
393
+ });
394
+ } catch (err) {
395
+ if (on_io_error) on_io_error(err);
396
+ }
397
+ const stop = () => {
398
+ closed = true;
399
+ if (watcher) {
400
+ watcher.close();
401
+ watcher = null;
402
+ }
403
+ };
404
+ const drain = async () => {
405
+ schedule();
406
+ await last_drain;
407
+ };
408
+ return {
409
+ stop,
410
+ drain
411
+ };
412
+ }
413
+ //#endregion
414
+ //#region src/viewer/start_viewer.ts
415
+ /**
416
+ * `start_viewer` programmatic embed implementation.
417
+ *
418
+ * Spin up the server, optionally start tailing a JSONL file, and return a
419
+ * handle that can stop both. `start_viewer` only depends on core's wire-format
420
+ * schema; it never reaches into the engine, composites, or any provider.
421
+ */
422
+ /**
423
+ * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`
424
+ * is set, a file tail that feeds the same broadcaster.
425
+ *
426
+ * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. HTTP ingest
427
+ * and SSE are always available; tailing is opt-in via `path`.
428
+ */
429
+ async function start_viewer(options = {}) {
430
+ const host = options.host ?? "127.0.0.1";
431
+ const port = options.port ?? 4242;
432
+ const broadcaster = create_broadcaster({
433
+ buffer: options.buffer ?? 1e3,
434
+ ...options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}
435
+ });
436
+ const server = await start_server({
437
+ broadcaster,
438
+ host,
439
+ port,
440
+ ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}
441
+ });
442
+ let tail = null;
443
+ if (options.path !== void 0) tail = start_tail({
444
+ path: options.path,
445
+ on_event: (event) => {
446
+ broadcaster.emit(event);
447
+ },
448
+ ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {},
449
+ ...options.on_io_error ? { on_io_error: options.on_io_error } : {}
450
+ });
451
+ return wrap_handle(server, tail, host);
452
+ }
453
+ /**
454
+ * Combines the server and optional tail into a single `ViewerHandle`.
455
+ *
456
+ * `close` stops the tail first, then closes the server, mirroring the
457
+ * startup order (server first, tail second) in reverse. The port is read
458
+ * back from `server.url` rather than the requested `port` option, since
459
+ * a caller that passes `0` gets whatever port the OS actually bound.
460
+ */
461
+ function wrap_handle(server, tail, host) {
462
+ return {
463
+ url: server.url,
464
+ host,
465
+ port: Number(new URL(server.url).port),
466
+ close: async () => {
467
+ if (tail) tail.stop();
468
+ await server.close();
469
+ }
470
+ };
471
+ }
472
+ //#endregion
473
+ //#region src/viewer/cli.ts
474
+ /**
475
+ * fascicle-viewer CLI.
476
+ *
477
+ * fascicle-viewer <path> # tail a JSONL file (primary)
478
+ * fascicle-viewer --listen # accept HTTP push only
479
+ * fascicle-viewer <path> --listen # both producers feed the same broadcaster
480
+ *
481
+ * Flags: --port <n> --host <h> --buffer <n> --no-open --help
482
+ *
483
+ * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT
484
+ * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`
485
+ * so the umbrella's bin shim can drive it from a bundled `dist/index.js`.
486
+ */
487
+ const HELP = `\
488
+ fascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.
489
+
490
+ Usage:
491
+ fascicle-viewer <path> tail a JSONL file
492
+ fascicle-viewer --listen accept HTTP push only
493
+ fascicle-viewer <path> --listen both producers feed the same broadcaster
494
+
495
+ Options:
496
+ --port <n> port (default 4242)
497
+ --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)
498
+ --buffer <n> ring-buffer size (default 1000)
499
+ --no-open do not open the browser
500
+ --help show this message
501
+ `;
502
+ /**
503
+ * Parses CLI argv into a validated `CliArgs`, exiting on bad input.
504
+ *
505
+ * `--help` prints usage and exits 0. Invalid numeric flags, or a missing
506
+ * <path> without `--listen`, write to stderr and exit 2.
507
+ */
508
+ function parse(argv) {
509
+ const { values, positionals } = parseArgs({
510
+ args: [...argv],
511
+ allowPositionals: true,
512
+ options: {
513
+ port: {
514
+ type: "string",
515
+ default: "4242"
516
+ },
517
+ host: {
518
+ type: "string",
519
+ default: "127.0.0.1"
520
+ },
521
+ buffer: {
522
+ type: "string",
523
+ default: "1000"
524
+ },
525
+ listen: {
526
+ type: "boolean",
527
+ default: false
528
+ },
529
+ open: {
530
+ type: "boolean",
531
+ default: true
532
+ },
533
+ "no-open": {
534
+ type: "boolean",
535
+ default: false
536
+ },
537
+ help: {
538
+ type: "boolean",
539
+ default: false
540
+ }
541
+ }
542
+ });
543
+ if (values.help) {
544
+ process.stdout.write(HELP);
545
+ process.exit(0);
546
+ }
547
+ const port_raw = values.port ?? "4242";
548
+ const buffer_raw = values.buffer ?? "1000";
549
+ const port = Number.parseInt(port_raw, 10);
550
+ const buffer = Number.parseInt(buffer_raw, 10);
551
+ if (!Number.isFinite(port) || port <= 0) {
552
+ process.stderr.write(`invalid --port: ${port_raw}\n`);
553
+ process.exit(2);
554
+ }
555
+ if (!Number.isFinite(buffer) || buffer <= 0) {
556
+ process.stderr.write(`invalid --buffer: ${buffer_raw}\n`);
557
+ process.exit(2);
558
+ }
559
+ const path = positionals[0];
560
+ const listen = values.listen ?? false;
561
+ if (path === void 0 && !listen) {
562
+ process.stderr.write("fascicle-viewer: a <path> is required unless --listen is set\n");
563
+ process.stderr.write(HELP);
564
+ process.exit(2);
565
+ }
566
+ return {
567
+ ...path !== void 0 ? { path } : {},
568
+ host: values.host ?? "127.0.0.1",
569
+ port,
570
+ buffer,
571
+ listen,
572
+ open: !values["no-open"] && (values.open ?? true)
573
+ };
574
+ }
575
+ /**
576
+ * Opens `url` in the platform's default browser, best-effort.
577
+ *
578
+ * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)
579
+ * detached and swallows failures; the CLI prints the URL either way.
580
+ */
581
+ function open_browser(url) {
582
+ const platform = process.platform;
583
+ const cmd = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
584
+ const args = platform === "win32" ? [
585
+ "/c",
586
+ "start",
587
+ "\"\"",
588
+ url
589
+ ] : [url];
590
+ try {
591
+ const child = spawn(cmd, args, {
592
+ stdio: "ignore",
593
+ detached: true
594
+ });
595
+ child.on("error", () => {});
596
+ child.unref();
597
+ } catch {}
598
+ }
599
+ /**
600
+ * CLI entry point: parses argv, starts the viewer, and wires shutdown.
601
+ *
602
+ * Warns but proceeds when the tailed path does not exist yet or when the
603
+ * bind host is 0.0.0.0 (the dashboard has no auth). Optionally opens the
604
+ * browser, then installs SIGINT/SIGTERM handlers that close the viewer
605
+ * before exiting.
606
+ */
607
+ async function run_viewer_cli(argv) {
608
+ const args = parse(argv);
609
+ if (args.path !== void 0 && !existsSync(args.path)) process.stderr.write(`fascicle-viewer: warning: ${args.path} does not exist yet — will pick up events once it is created\n`);
610
+ if (args.host === "0.0.0.0") process.stderr.write("fascicle-viewer: warning: binding 0.0.0.0 — this dashboard has no auth and exposes whatever is in your trajectory stream\n");
611
+ const handle = await start_viewer({
612
+ ...args.path !== void 0 ? { path: args.path } : {},
613
+ host: args.host,
614
+ port: args.port,
615
+ buffer: args.buffer,
616
+ on_parse_error: (err, line) => {
617
+ const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line;
618
+ process.stderr.write(`fascicle-viewer: skipped malformed line: ${preview}\n ${describe_error(err)}\n`);
619
+ },
620
+ on_io_error: (err) => {
621
+ process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\n`);
622
+ }
623
+ });
624
+ if (args.path !== void 0) process.stderr.write(`watching ${args.path}\n`);
625
+ if (args.listen || args.path === void 0) process.stderr.write(`listening for HTTP push on ${handle.url}/api/ingest\n`);
626
+ process.stderr.write(`viewer at ${handle.url}\n`);
627
+ if (args.open) open_browser(handle.url);
628
+ const shutdown = async () => {
629
+ process.stderr.write("\nfascicle-viewer: shutting down\n");
630
+ await handle.close();
631
+ process.exit(0);
632
+ };
633
+ process.on("SIGINT", () => {
634
+ shutdown();
635
+ });
636
+ process.on("SIGTERM", () => {
637
+ shutdown();
638
+ });
639
+ }
640
+ /**
641
+ * Renders an unknown thrown value as a human-readable message.
642
+ */
643
+ function describe_error(err) {
644
+ if (err instanceof Error) return err.message;
645
+ try {
646
+ return JSON.stringify(err);
647
+ } catch {
648
+ return String(err);
649
+ }
650
+ }
651
+ if (process.argv[1] !== void 0 && process.argv[1] === fileURLToPath(import.meta.url)) run_viewer_cli(process.argv.slice(2)).catch((err) => {
652
+ process.stderr.write(`fascicle-viewer: ${describe_error(err)}\n`);
653
+ process.exit(1);
654
+ });
655
+ //#endregion
656
+ export { create_broadcaster, run_viewer_cli, start_server, start_tail, start_viewer };
657
+
658
+ //# sourceMappingURL=viewer.js.map