fascicle 0.12.3 → 0.12.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +61 -6
  2. package/README.md +3 -2
  3. package/dist/agents.d.ts +1 -1
  4. package/dist/agents.js +1 -1
  5. package/dist/{core-DdJEhyQc.js → core-CFdEjtiT.js} +281 -270
  6. package/dist/core-CFdEjtiT.js.map +1 -0
  7. package/dist/{engine-J4lIxpw5.js → engine-DQiQHiy8.js} +182 -34
  8. package/dist/engine-DQiQHiy8.js.map +1 -0
  9. package/dist/index.d.ts +28 -2
  10. package/dist/index.js +48 -4
  11. package/dist/index.js.map +1 -1
  12. package/dist/{invoke-CH_eJZeS.js → invoke-eEYMZmWg.js} +3 -3
  13. package/dist/{invoke-CH_eJZeS.js.map → invoke-eEYMZmWg.js.map} +1 -1
  14. package/dist/{leading_system-BUCT-PwD.js → leading_system-DQmlA6Fs.js} +2 -2
  15. package/dist/{leading_system-BUCT-PwD.js.map → leading_system-DQmlA6Fs.js.map} +1 -1
  16. package/dist/mcp.d.ts +1 -1
  17. package/dist/mcp.js +1 -1
  18. package/dist/otel.d.ts +20 -2
  19. package/dist/otel.js +228 -8
  20. package/dist/otel.js.map +1 -1
  21. package/dist/stdio.js +1 -1
  22. package/dist/testing.d.ts +1 -1
  23. package/dist/testing.js +3 -3
  24. package/dist/{types-DU6cvoA4.d.ts → types-CLigYA62.d.ts} +28 -2
  25. package/dist/viewer-app/assets/index-BGb1-MwM.js +2 -0
  26. package/dist/viewer-app/assets/index-D7kvKs40.css +1 -0
  27. package/dist/viewer-app/fonts/sora-OFL.txt +93 -0
  28. package/dist/viewer-app/fonts/sora-latin.woff2 +0 -0
  29. package/dist/viewer-app/fonts/spline-sans-mono-OFL.txt +93 -0
  30. package/dist/viewer-app/fonts/spline-sans-mono-latin.woff2 +0 -0
  31. package/dist/viewer-app/index.html +13 -0
  32. package/dist/viewer.d.ts +17 -3
  33. package/dist/viewer.js +210 -50
  34. package/dist/viewer.js.map +1 -1
  35. package/package.json +14 -3
  36. package/dist/core-DdJEhyQc.js.map +0 -1
  37. package/dist/engine-J4lIxpw5.js.map +0 -1
  38. package/dist/static/viewer.html +0 -375
@@ -0,0 +1,93 @@
1
+ Copyright 2019 The Sora Project Authors (https://github.com/sora-xor/sora-font)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+
5
+ This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Copyright 2022 The Spline Sans Mono Project Authors (https://github.com/SorkinType/SplineSansMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,13 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>fascicle viewer</title>
7
+ <script type="module" crossorigin src="/assets/index-BGb1-MwM.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/index-D7kvKs40.css">
9
+ </head>
10
+ <body>
11
+ <div id="root"></div>
12
+ </body>
13
+ </html>
package/dist/viewer.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { a as ParsedTrajectoryEvent } from "./trajectory-ByoOQZ6T.js";
2
+ import { ServerResponse } from "node:http";
2
3
 
3
4
  //#region src/viewer/start_viewer.d.ts
4
5
  /**
@@ -65,6 +66,18 @@ type ServerConfig = {
65
66
  readonly broadcaster: Broadcaster;
66
67
  readonly host: string;
67
68
  readonly port: number;
69
+ /**
70
+ * Where the compiled canvas lives, defaulting to the bundled
71
+ * `dist/viewer-app`. The tests point it at a fixture directory so the suite
72
+ * never depends on a build having run.
73
+ */
74
+ readonly app_dir?: string;
75
+ /**
76
+ * The trajectory file `/api/trajectory` streams as full history. Absent when
77
+ * the server is ingest-fed only, where that route falls back to the ring
78
+ * (D7). Threaded from the tailed `path` by `start_viewer`.
79
+ */
80
+ readonly trajectory_path?: string;
68
81
  readonly on_parse_error?: (err: unknown, line: string) => void;
69
82
  };
70
83
  type ViewerServer = {
@@ -74,9 +87,10 @@ type ViewerServer = {
74
87
  /**
75
88
  * Starts the HTTP server and resolves once it is listening.
76
89
  *
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.
90
+ * Wires the four API routes (health, snapshot, SSE, ingest) plus the compiled
91
+ * app's static files to a single request handler, and resolves with the bound
92
+ * URL and a `close` that shuts the socket down. The API routes are matched
93
+ * first and exactly, so no file the canvas ships can ever shadow one.
80
94
  */
81
95
  declare function start_server(config: ServerConfig): Promise<ViewerServer>;
82
96
  //#endregion
package/dist/viewer.js CHANGED
@@ -1,7 +1,7 @@
1
- import "./core-DdJEhyQc.js";
1
+ import "./core-CFdEjtiT.js";
2
2
  import { s as parse_trajectory_event } from "./trajectory-D1eq9eue.js";
3
3
  import { open, stat } from "node:fs/promises";
4
- import { dirname, resolve } from "node:path";
4
+ import { dirname, extname, 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 { fileURLToPath } from "node:url";
@@ -57,36 +57,60 @@ function create_broadcaster(config) {
57
57
  //#endregion
58
58
  //#region src/viewer/server.ts
59
59
  /**
60
- * Tiny HTTP server: 5 routes, SSE fan-out, NDJSON ingest.
60
+ * Tiny HTTP server: 5 API routes, SSE fan-out, NDJSON ingest, plus the
61
+ * compiled run canvas served as static files.
61
62
  *
62
- * GET / -> static viewer.html
63
- * GET /api/events -> text/event-stream replaying the ring buffer
64
- * GET /api/snapshot -> JSON dump of the ring buffer
65
- * POST /api/ingest -> newline-delimited trajectory events (http_logger)
66
- * GET /api/health -> { ok: true }
63
+ * GET /api/events -> text/event-stream, replaying past the client cursor
64
+ * GET /api/trajectory -> the full run history as NDJSON (file, or ring)
65
+ * GET /api/snapshot -> JSON dump of the ring buffer
66
+ * POST /api/ingest -> newline-delimited trajectory events (http_logger)
67
+ * GET /api/health -> { ok: true }
68
+ * GET /<anything> -> a file from the compiled app, `/` being index.html
67
69
  *
68
- * The server owns nothing but the socket. The broadcaster owns the event
69
- * history; the static html lives on disk. SSE clients reconnect with
70
- * `Last-Event-ID` and the server replays anything past their cursor from
71
- * the ring buffer; older events are gone (bounded memory by design).
70
+ * The server owns nothing but the socket. The broadcaster owns the recent
71
+ * event ring; the tailed file owns the full history; the canvas is a vite build
72
+ * on disk. A client folds `/api/trajectory` for the whole run and then follows
73
+ * `/api/events`, which replays anything past the cursor it names and streams
74
+ * new events live. The ring is bounded memory by design, so history older than
75
+ * it is served from the file the tail already reads (D7).
72
76
  */
73
77
  const SSE_HEARTBEAT_MS = 15e3;
74
- const STATIC_HTML = resolve(dirname(fileURLToPath(import.meta.url)), "static", "viewer.html");
78
+ const HERE = dirname(fileURLToPath(import.meta.url));
79
+ /**
80
+ * The header `/api/trajectory` stamps with the broadcaster's newest id: the
81
+ * seam the client resumes SSE from after folding the history dump. The client
82
+ * carries the same literal (`app/history.ts`); the two ends cannot share a
83
+ * module because the browser bundle must not pull in node builtins.
84
+ */
85
+ const CURSOR_HEADER = "x-fascicle-cursor";
86
+ /**
87
+ * Content types for everything the compiled app ships. Anything outside the
88
+ * map is served as an opaque download rather than guessed at, which keeps a
89
+ * stray file from being executed as script by a browser.
90
+ */
91
+ const CONTENT_TYPES = {
92
+ ".css": "text/css; charset=utf-8",
93
+ ".html": "text/html; charset=utf-8",
94
+ ".js": "text/javascript; charset=utf-8",
95
+ ".json": "application/json; charset=utf-8",
96
+ ".png": "image/png",
97
+ ".svg": "image/svg+xml",
98
+ ".txt": "text/plain; charset=utf-8",
99
+ ".woff2": "font/woff2"
100
+ };
101
+ const FALLBACK_CONTENT_TYPE = "application/octet-stream";
75
102
  /**
76
103
  * Starts the HTTP server and resolves once it is listening.
77
104
  *
78
- * Wires the five routes (static HTML, health, snapshot, SSE, ingest) to a
79
- * single request handler and resolves with the bound URL and a `close`
80
- * that shuts the socket down.
105
+ * Wires the four API routes (health, snapshot, SSE, ingest) plus the compiled
106
+ * app's static files to a single request handler, and resolves with the bound
107
+ * URL and a `close` that shuts the socket down. The API routes are matched
108
+ * first and exactly, so no file the canvas ships can ever shadow one.
81
109
  */
82
110
  function start_server(config) {
83
- const { broadcaster, host, port, on_parse_error } = config;
111
+ const { broadcaster, host, port, app_dir, trajectory_path, on_parse_error } = config;
84
112
  const handler = (req, res) => {
85
113
  const route = resolve_route(req, host, port);
86
- if (route === "GET /" || route === "GET /index.html") {
87
- serve_static_html(res);
88
- return;
89
- }
90
114
  if (route === "GET /api/health") {
91
115
  send_json(res, 200, { ok: true });
92
116
  return;
@@ -95,6 +119,10 @@ function start_server(config) {
95
119
  send_json(res, 200, { events: broadcaster.snapshot() });
96
120
  return;
97
121
  }
122
+ if (route === "GET /api/trajectory") {
123
+ serve_trajectory(res, broadcaster, trajectory_path);
124
+ return;
125
+ }
98
126
  if (route === "GET /api/events") {
99
127
  handle_sse(req, res, broadcaster);
100
128
  return;
@@ -103,37 +131,53 @@ function start_server(config) {
103
131
  handle_ingest(req, res, broadcaster, on_parse_error);
104
132
  return;
105
133
  }
106
- res.statusCode = 404;
107
- res.setHeader("content-type", "application/json");
108
- res.end(JSON.stringify({
109
- error: "not_found",
110
- route
111
- }));
134
+ if (route.startsWith("GET /")) {
135
+ serve_app_asset(res, route, app_dir);
136
+ return;
137
+ }
138
+ send_not_found(res, route);
112
139
  };
113
140
  const http_server = createServer(handler);
114
141
  return new Promise((res_ok, res_err) => {
115
142
  http_server.once("error", res_err);
116
143
  http_server.listen(port, host, () => {
117
144
  http_server.removeListener("error", res_err);
118
- const addr = http_server.address();
119
- const bound_port = addr !== null && typeof addr === "object" && "port" in addr ? addr.port : port;
120
145
  res_ok({
121
- url: `http://${host}:${bound_port}`,
146
+ url: `http://${host}:${bound_port_of(http_server.address(), port)}`,
122
147
  close: () => close_server(http_server)
123
148
  });
124
149
  });
125
150
  });
126
151
  }
127
152
  /**
153
+ * Resolves the port a listening server actually bound to.
154
+ *
155
+ * `address()` is only an `AddressInfo` for a TCP listen; it is a path string
156
+ * for a unix socket and `null` before listening, so the fallback covers both.
157
+ * The bound port differs from the requested one only when the caller passed 0
158
+ * and asked the OS to pick a free port.
159
+ */
160
+ function bound_port_of(addr, fallback) {
161
+ return addr !== null && typeof addr === "object" && "port" in addr ? addr.port : fallback;
162
+ }
163
+ /**
128
164
  * Builds a `"METHOD /path"` route key from a request.
129
165
  *
130
- * Falls back to the server's own `host`/`port` when the request has no
131
- * `Host` header, so a malformed or missing header never throws inside
132
- * `new URL`.
166
+ * Resolves the path against the client's `Host` header when it parses, and
167
+ * against the server's own `host`/`port` otherwise. A header can be present yet
168
+ * malformed (`'in valid'`), which `??` cannot catch because it is neither null
169
+ * nor undefined; fed to `new URL` it throws. Trying the header inside a
170
+ * try/catch and falling back to the server's authority keeps route resolution
171
+ * total for any header a client sends.
133
172
  */
134
173
  function resolve_route(req, host, port) {
135
- const url = new URL(req.url ?? "/", `http://${req.headers.host ?? `${host}:${port}`}`);
136
- return `${req.method ?? "GET"} ${url.pathname}`;
174
+ const method = req.method ?? "GET";
175
+ const path = req.url ?? "/";
176
+ const header = req.headers.host;
177
+ if (header !== void 0) try {
178
+ return `${method} ${new URL(path, `http://${header}`).pathname}`;
179
+ } catch {}
180
+ return `${method} ${new URL(path, `http://${host}:${port}`).pathname}`;
137
181
  }
138
182
  /**
139
183
  * Closes the HTTP server and resolves once every connection is torn down.
@@ -144,7 +188,7 @@ function close_server(server) {
144
188
  if (err) res_err(err);
145
189
  else res_ok();
146
190
  });
147
- server.closeAllConnections?.();
191
+ server.closeAllConnections();
148
192
  });
149
193
  }
150
194
  /**
@@ -156,30 +200,130 @@ function send_json(res, status, body) {
156
200
  res.end(JSON.stringify(body));
157
201
  }
158
202
  /**
159
- * Streams the bundled `viewer.html` as the response body.
203
+ * Writes the JSON 404 that names the route that missed.
204
+ */
205
+ function send_not_found(res, route) {
206
+ send_json(res, 404, {
207
+ error: "not_found",
208
+ route
209
+ });
210
+ }
211
+ /**
212
+ * Handles `GET /api/trajectory` by streaming the whole run history as NDJSON,
213
+ * one event per line, so the client folds the full run before it follows the
214
+ * live tail (D7).
215
+ *
216
+ * The tailed file is the source of truth: its bytes stream straight through,
217
+ * which keeps memory bounded no matter how long the run grew, and a finished
218
+ * `.jsonl` opened with no live producer becomes the same client path as live.
219
+ * An ingest-fed server has no file, so it falls back to the ring buffer, the
220
+ * only history it holds. Either way the response is stamped with the
221
+ * broadcaster's newest id, the seam the client resumes SSE from; the client
222
+ * still takes the larger of that and its own folded count, so a file that ran
223
+ * ahead of the broadcaster is not re-folded.
224
+ */
225
+ function serve_trajectory(res, broadcaster, trajectory_path) {
226
+ const ring = broadcaster.snapshot();
227
+ res.statusCode = 200;
228
+ res.setHeader("content-type", "application/x-ndjson; charset=utf-8");
229
+ res.setHeader("cache-control", "no-store");
230
+ res.setHeader(CURSOR_HEADER, String(ring.at(-1)?.id ?? 0));
231
+ if (trajectory_path !== void 0) {
232
+ if (stat_file(trajectory_path) !== null) {
233
+ createReadStream(trajectory_path).pipe(res);
234
+ return;
235
+ }
236
+ }
237
+ res.end(ring.map((entry) => `${JSON.stringify(entry.event)}\n`).join(""));
238
+ }
239
+ /**
240
+ * Where the compiled canvas can be, relative to this module.
241
+ *
242
+ * Published, `viewer.js` sits in `dist/` beside `dist/viewer-app/`. Running
243
+ * from source, this module is `src/viewer/server.ts` and the same build output
244
+ * is two levels up in the repo's `dist/`. The two candidates never both exist
245
+ * for the same install, so probing them in order is unambiguous.
246
+ */
247
+ function app_dir_candidates(here) {
248
+ return [resolve(here, "viewer-app"), resolve(here, "..", "..", "dist", "viewer-app")];
249
+ }
250
+ /**
251
+ * The compiled app directory, or `null` when the canvas has not been built.
252
+ *
253
+ * A directory only counts once its `index.html` is really there, so a
254
+ * half-written build reads as absent rather than as a directory that 404s
255
+ * every asset.
160
256
  */
161
- function serve_static_html(res) {
162
- let size;
257
+ function resolve_app_dir(override) {
258
+ return (override === void 0 ? app_dir_candidates(HERE) : [override]).find((dir) => stat_file(resolve(dir, "index.html")) !== null) ?? null;
259
+ }
260
+ /**
261
+ * The stats of an existing regular file, or `null` for anything else.
262
+ *
263
+ * One syscall answers both questions the asset route asks: whether to serve
264
+ * the path at all, and what `content-length` to declare. Reading the stats
265
+ * before the stream opens is what keeps a missing file a clean 404 rather
266
+ * than a stream error raised after the headers have gone out.
267
+ */
268
+ function stat_file(path) {
163
269
  try {
164
- size = statSync(STATIC_HTML).size;
270
+ const stats = statSync(path);
271
+ return stats.isFile() ? stats : null;
165
272
  } catch {
273
+ return null;
274
+ }
275
+ }
276
+ /**
277
+ * Resolves a URL path inside the compiled app directory, or `null` when it
278
+ * escapes it.
279
+ *
280
+ * The server is bound to localhost by default, but a browser will happily
281
+ * send `/../../etc/passwd`, so containment is checked on the resolved path
282
+ * rather than trusted from the URL text.
283
+ */
284
+ function resolve_app_file(dir, url_path) {
285
+ const file = resolve(dir, `.${url_path}`);
286
+ if (file !== dir && !file.startsWith(dir + sep)) return null;
287
+ return file === dir ? resolve(dir, "index.html") : file;
288
+ }
289
+ /**
290
+ * Streams one file of the compiled canvas as the response body.
291
+ *
292
+ * A missing app directory is a 500 naming the build step, because the server
293
+ * is fine and the operator forgot to compile; a missing file inside a present
294
+ * app is an ordinary 404.
295
+ */
296
+ function serve_app_asset(res, route, override) {
297
+ const dir = resolve_app_dir(override);
298
+ if (dir === null) {
166
299
  res.statusCode = 500;
167
300
  res.setHeader("content-type", "text/plain");
168
- res.end("viewer.html missing");
301
+ res.end("viewer app not built; run `pnpm build`");
302
+ return;
303
+ }
304
+ const file = resolve_app_file(dir, route.slice(route.indexOf(" ") + 1));
305
+ const stats = file === null ? null : stat_file(file);
306
+ if (file === null || stats === null) {
307
+ send_not_found(res, route);
169
308
  return;
170
309
  }
171
310
  res.statusCode = 200;
172
- res.setHeader("content-type", "text/html; charset=utf-8");
311
+ res.setHeader("content-type", CONTENT_TYPES[extname(file)] ?? FALLBACK_CONTENT_TYPE);
173
312
  res.setHeader("cache-control", "no-store");
174
- res.setHeader("content-length", String(size));
175
- createReadStream(STATIC_HTML).pipe(res);
313
+ res.setHeader("content-length", String(stats.size));
314
+ createReadStream(file).pipe(res);
176
315
  }
177
316
  /**
178
317
  * Handles `GET /api/events` by turning the connection into an SSE stream.
179
318
  *
180
- * Replays whatever the client missed since its `Last-Event-ID` cursor,
181
- * subscribes it to the broadcaster for new events, and keeps the
182
- * connection alive with a periodic heartbeat comment.
319
+ * Replays whatever the client missed since its cursor, subscribes it to the
320
+ * broadcaster for new events, and keeps the connection alive with a periodic
321
+ * heartbeat comment. The cursor is the furthest the client can name: the
322
+ * `Last-Event-ID` a reconnecting browser sends, or the `?since=` a fresh load
323
+ * sets after folding `/api/trajectory`, because native `EventSource` cannot set
324
+ * the header on a first connect. That same cursor guards the live subscription,
325
+ * so an event the history dump already carried is never delivered twice when
326
+ * the file ran ahead of the broadcaster at dump time.
183
327
  */
184
328
  function handle_sse(req, res, broadcaster) {
185
329
  res.statusCode = 200;
@@ -187,13 +331,14 @@ function handle_sse(req, res, broadcaster) {
187
331
  res.setHeader("cache-control", "no-store");
188
332
  res.setHeader("connection", "keep-alive");
189
333
  res.setHeader("x-accel-buffering", "no");
190
- const last_event_id = parse_last_event_id(req.headers["last-event-id"]);
191
- for (const entry of broadcaster.snapshot_after(last_event_id)) write_event(res, entry.id, entry.event);
334
+ res.write(": connected\n\n");
335
+ const cursor = Math.max(parse_last_event_id(req.headers["last-event-id"]), parse_since(req.url));
336
+ for (const entry of broadcaster.snapshot_after(cursor)) write_event(res, entry.id, entry.event);
192
337
  const heartbeat = setInterval(() => {
193
338
  res.write(": heartbeat\n\n");
194
339
  }, SSE_HEARTBEAT_MS);
195
340
  const unsubscribe = broadcaster.subscribe((entry) => {
196
- write_event(res, entry.id, entry.event);
341
+ if (entry.id > cursor) write_event(res, entry.id, entry.event);
197
342
  });
198
343
  const close = () => {
199
344
  clearInterval(heartbeat);
@@ -218,6 +363,20 @@ function parse_last_event_id(value) {
218
363
  return Number.isFinite(n) && n > 0 ? n : 0;
219
364
  }
220
365
  /**
366
+ * Parses the `?since=` cursor off a request URL, defaulting to 0.
367
+ *
368
+ * A fresh load sets it after folding `/api/trajectory`, since native
369
+ * `EventSource` cannot send a `Last-Event-ID` header on a first connect. The
370
+ * value reuses `parse_last_event_id`'s number rule, so a missing, absent, or
371
+ * unusable `since` reads as "no cursor" exactly as the header does.
372
+ */
373
+ function parse_since(url) {
374
+ if (typeof url !== "string") return 0;
375
+ const query = url.indexOf("?");
376
+ if (query === -1) return 0;
377
+ return parse_last_event_id(new URLSearchParams(url.slice(query + 1)).get("since") ?? void 0);
378
+ }
379
+ /**
221
380
  * Writes one SSE `trajectory` event frame to the response stream.
222
381
  */
223
382
  function write_event(res, id, event) {
@@ -438,6 +597,7 @@ async function start_viewer(options = {}) {
438
597
  broadcaster,
439
598
  host,
440
599
  port,
600
+ ...options.path !== void 0 ? { trajectory_path: options.path } : {},
441
601
  ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}
442
602
  });
443
603
  let tail = null;