fascicle 0.16.5 → 0.17.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +3 -2
  3. package/dist/AGENTS.md +69 -18
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.js +7 -2
  6. package/dist/acp.js.map +1 -1
  7. package/dist/agents.d.ts +1 -1
  8. package/dist/{engine-B6rIIM4J.js → engine-Bde18P7H.js} +1163 -236
  9. package/dist/engine-Bde18P7H.js.map +1 -0
  10. package/dist/index.d.ts +114 -16
  11. package/dist/index.js +226 -16
  12. package/dist/index.js.map +1 -1
  13. package/dist/{invoke-LbzZLZFw.js → invoke-BbJLQcLl.js} +62 -106
  14. package/dist/invoke-BbJLQcLl.js.map +1 -0
  15. package/dist/{leading_system-WhW76tRn.js → leading_system-DmNxhvzL.js} +45 -16
  16. package/dist/leading_system-DmNxhvzL.js.map +1 -0
  17. package/dist/mcp.d.ts +2 -1
  18. package/dist/mcp.js +6 -3
  19. package/dist/mcp.js.map +1 -1
  20. package/dist/otel.js +48 -3
  21. package/dist/otel.js.map +1 -1
  22. package/dist/{search-CpCJYMUm.js → search-DjhdMsJ8.js} +4 -1
  23. package/dist/search-DjhdMsJ8.js.map +1 -0
  24. package/dist/search_worker.js +1 -1
  25. package/dist/testing.d.ts +77 -2
  26. package/dist/testing.js +202 -19
  27. package/dist/testing.js.map +1 -1
  28. package/dist/{types-Sw0oHW-_.d.ts → types-C7pO0jLq.d.ts} +218 -21
  29. package/dist/viewer-app/assets/index-9eVv6Mar.css +1 -0
  30. package/dist/viewer-app/assets/index-BkS2ZQu0.js +4 -0
  31. package/dist/viewer-app/index.html +2 -2
  32. package/dist/viewer.d.ts +64 -10
  33. package/dist/viewer.js +265 -64
  34. package/dist/viewer.js.map +1 -1
  35. package/package.json +1 -1
  36. package/dist/engine-B6rIIM4J.js.map +0 -1
  37. package/dist/invoke-LbzZLZFw.js.map +0 -1
  38. package/dist/leading_system-WhW76tRn.js.map +0 -1
  39. package/dist/search-CpCJYMUm.js.map +0 -1
  40. package/dist/viewer-app/assets/index-Cev83tcH.css +0 -1
  41. package/dist/viewer-app/assets/index-D8UmFVfR.js +0 -2
@@ -5,8 +5,8 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <title>fascicle viewer</title>
7
7
  <link rel="icon" href="data:," />
8
- <script type="module" crossorigin src="/assets/index-D8UmFVfR.js"></script>
9
- <link rel="stylesheet" crossorigin href="/assets/index-Cev83tcH.css">
8
+ <script type="module" crossorigin src="./assets/index-BkS2ZQu0.js"></script>
9
+ <link rel="stylesheet" crossorigin href="./assets/index-9eVv6Mar.css">
10
10
  </head>
11
11
  <body>
12
12
  <div id="root"></div>
package/dist/viewer.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { o as ParsedTrajectoryEvent } from "./trajectory-BKGNxi7u.js";
2
- import { ServerResponse } from "node:http";
2
+ import { IncomingMessage, ServerResponse } from "node:http";
3
3
  //#region src/viewer/start_viewer.d.ts
4
4
  /**
5
5
  * `start_viewer` programmatic embed implementation.
@@ -15,6 +15,14 @@ type StartViewerOptions = {
15
15
  readonly buffer?: number;
16
16
  /** Whether the server takes `POST /api/ingest`, which `http_logger` posts to; default true. */
17
17
  readonly ingest?: boolean;
18
+ /**
19
+ * Whether the tail and `/api/trajectory` follow a link at the last name of
20
+ * `path`; default true. False reads only a regular file with no other
21
+ * name, opened with `O_NOFOLLOW` and checked on its handle, for a host that
22
+ * checks the path itself before it starts the viewer. A refusal goes to
23
+ * `on_io_error`, and the route serves the ring, as it does for no file.
24
+ */
25
+ readonly follow_links?: boolean;
18
26
  readonly on_parse_error?: (err: unknown, line: string) => void;
19
27
  readonly on_io_error?: (err: unknown) => void;
20
28
  readonly on_subscriber_error?: (err: unknown) => void;
@@ -64,10 +72,8 @@ type BroadcasterConfig = {
64
72
  export declare function create_broadcaster(config: BroadcasterConfig): Broadcaster;
65
73
  //#endregion
66
74
  //#region src/viewer/server.d.ts
67
- type ServerConfig = {
75
+ type ViewerHandlerConfig = {
68
76
  readonly broadcaster: Broadcaster;
69
- readonly host: string;
70
- readonly port: number;
71
77
  /**
72
78
  * Where the compiled canvas lives, defaulting to the bundled
73
79
  * `dist/viewer-app`. The tests point it at a fixture directory so the suite
@@ -86,22 +92,60 @@ type ServerConfig = {
86
92
  * viewer that only tails a file from taking posts.
87
93
  */
88
94
  readonly ingest?: boolean | undefined;
95
+ /**
96
+ * The path the handler is mounted under, such as `/viewer/abc`, which it
97
+ * takes off each request before routing it; default the root. A request
98
+ * for the bare path is redirected to it with a trailing slash, since the
99
+ * canvas resolves its assets and its API requests against the page.
100
+ */
101
+ readonly base_path?: string;
102
+ /**
103
+ * Whether `/api/trajectory` follows a link at the last name of
104
+ * `trajectory_path`; default true. False opens the file with `O_NOFOLLOW`
105
+ * and serves only a regular file with no other name, checked on the handle
106
+ * it opened, so a link swapped in after a host checked the path is never
107
+ * served. Anything else is served as no file, from the ring. Throws on a
108
+ * platform with no `O_NOFOLLOW`.
109
+ */
110
+ readonly follow_links?: boolean | undefined;
89
111
  readonly on_parse_error?: (err: unknown, line: string) => void;
90
112
  };
113
+ /**
114
+ * Answers one request and returns true, or returns false without touching
115
+ * the response when the request isn't one the viewer serves: outside its
116
+ * `base_path`, a route the API doesn't claim, or a file the canvas doesn't
117
+ * ship.
118
+ */
119
+ type ViewerHandler = (req: IncomingMessage, res: ServerResponse) => boolean;
120
+ type ServerConfig = Omit<ViewerHandlerConfig, 'base_path'> & {
121
+ readonly host: string;
122
+ readonly port: number;
123
+ };
91
124
  type ViewerServer = {
92
125
  readonly url: string;
93
126
  /** The port the socket bound, which differs from the requested one for `port: 0`. */
94
127
  readonly port: number;
95
128
  readonly close: () => Promise<void>;
96
129
  };
130
+ /**
131
+ * Builds the viewer's request handler: the five API routes (health, snapshot,
132
+ * trajectory, SSE, ingest) and the compiled app's static files, for a host to
133
+ * mount on a `node:http` server of its own, or on any framework that hands
134
+ * over the raw request and response.
135
+ *
136
+ * The API routes are matched first and exactly, so no file the canvas ships
137
+ * can ever shadow one. The handler checks no `Host`, so a host that mounts it
138
+ * decides who may reach it, behind its own auth. `start_server` puts the
139
+ * loopback check in front of it.
140
+ */
141
+ export declare function create_viewer_handler(config: ViewerHandlerConfig): ViewerHandler;
97
142
  /**
98
143
  * Starts the HTTP server and resolves once it is listening.
99
144
  *
100
- * Wires the five API routes (health, snapshot, trajectory, SSE, ingest) plus
101
- * the compiled app's static files to a single request handler, and resolves
102
- * with the bound URL and port and a `close` that shuts the socket down. The
103
- * `Host` check runs before anything else, then the API routes are matched
104
- * first and exactly, so no file the canvas ships can ever shadow one.
145
+ * Mounts `create_viewer_handler` at the root behind the `Host` check, answers
146
+ * a JSON 404 naming the route for anything the handler doesn't serve, and
147
+ * resolves with the bound URL and port and a `close` that shuts the socket
148
+ * down.
105
149
  */
106
150
  export declare function start_server(config: ServerConfig): Promise<ViewerServer>;
107
151
  //#endregion
@@ -111,6 +155,16 @@ type TailConfig = {
111
155
  readonly on_event: (event: ParsedTrajectoryEvent) => void;
112
156
  readonly on_parse_error?: (err: unknown, line: string) => void;
113
157
  readonly on_io_error?: (err: unknown) => void;
158
+ /**
159
+ * Whether a link at the path's last name is followed; default true. False
160
+ * opens the file with `O_NOFOLLOW` and reads only a regular file with no
161
+ * other name, checked on the handle it opened, so a link swapped in after
162
+ * a host checked the path is never read. What it refuses goes to
163
+ * `on_io_error`, and the tail waits for a file it can read, as it does for
164
+ * a missing one. Directories above the file are still followed. Throws on a
165
+ * platform with no `O_NOFOLLOW`.
166
+ */
167
+ readonly follow_links?: boolean | undefined;
114
168
  };
115
169
  type Tail = {
116
170
  readonly stop: () => void;
@@ -140,5 +194,5 @@ export declare function start_tail(config: TailConfig): Tail;
140
194
  */
141
195
  export declare function run_viewer_cli(argv: readonly string[]): Promise<void>;
142
196
  //#endregion
143
- export type { BroadcastEvent, Broadcaster, BroadcasterConfig, ServerConfig, StartViewerOptions, Subscriber, Tail, TailConfig, ViewerHandle, ViewerServer };
197
+ export type { BroadcastEvent, Broadcaster, BroadcasterConfig, ServerConfig, StartViewerOptions, Subscriber, Tail, TailConfig, ViewerHandle, ViewerHandler, ViewerHandlerConfig, ViewerServer };
144
198
  //# sourceMappingURL=viewer.d.ts.map
package/dist/viewer.js CHANGED
@@ -2,7 +2,7 @@ import "./core-BOFcG3tp.js";
2
2
  import { l as parse_trajectory_event } from "./trajectory-DeURWIhj.js";
3
3
  import { open, stat } from "node:fs/promises";
4
4
  import { basename, dirname, extname, relative, resolve, sep } from "node:path";
5
- import { createReadStream, existsSync, statSync, watch } from "node:fs";
5
+ import { constants, createReadStream, existsSync, statSync, watch } from "node:fs";
6
6
  import { spawn } from "node:child_process";
7
7
  import { pipeline } from "node:stream";
8
8
  import { fileURLToPath } from "node:url";
@@ -57,6 +57,85 @@ function create_broadcaster(config) {
57
57
  };
58
58
  }
59
59
  //#endregion
60
+ //#region src/viewer/no_follow.ts
61
+ /**
62
+ * Opening the trajectory without following a link, for `follow_links: false`.
63
+ *
64
+ * A host can check the trajectory's path before it starts a viewer, but the
65
+ * check can't hold for long, because the tail and `/api/trajectory` open the
66
+ * path again on every read. A link swapped in after the check would point the
67
+ * viewer at any file the user can read and serve it over HTTP. So with links
68
+ * not followed, every open of the trajectory goes through `open_unfollowed`,
69
+ * which opens it with `O_NOFOLLOW`, where a link at the last name fails rather
70
+ * than being followed, and then checks the handle it opened rather than the
71
+ * path, so what it checked is what gets read.
72
+ *
73
+ * Only the last name is covered. A directory above the file is still followed,
74
+ * since Node has no `openat` to walk a path one directory handle at a time, so
75
+ * a host keeps checking those itself.
76
+ */
77
+ /**
78
+ * The flags that open the trajectory for reading without following a link at
79
+ * its last name. `O_NONBLOCK` keeps a FIFO planted at the path from holding
80
+ * the open until some writer turns up, and changes nothing for a regular file.
81
+ *
82
+ * Throws where the platform has no `O_NOFOLLOW` (Windows), so that asking not
83
+ * to follow links never quietly follows one.
84
+ */
85
+ function no_follow_flags() {
86
+ const no_follow = Reflect.get(constants, "O_NOFOLLOW");
87
+ if (typeof no_follow !== "number") throw new Error("follow_links: false needs O_NOFOLLOW, which this platform doesn't have");
88
+ return constants.O_RDONLY | no_follow | constants.O_NONBLOCK;
89
+ }
90
+ /**
91
+ * Why the viewer won't read what it opened, or undefined when it may.
92
+ *
93
+ * Only a regular file with no other name is read. A hard link can stand at the
94
+ * path as well as a symbolic one, and `O_NOFOLLOW` can't tell it from the file
95
+ * it names, so a file with a second name is refused too.
96
+ */
97
+ function refusal(stats) {
98
+ if (!stats.isFile()) return "it isn't a regular file";
99
+ if (stats.nlink !== 1) return `it's one of ${String(stats.nlink)} hard links to the same file`;
100
+ }
101
+ /**
102
+ * Opens `path` with `flags` (see `no_follow_flags`) and checks the handle it
103
+ * opened. Never throws: whatever it couldn't open or wouldn't keep comes back
104
+ * as the error, with the handle already closed.
105
+ */
106
+ async function open_unfollowed(path, flags) {
107
+ let handle;
108
+ try {
109
+ handle = await open(path, flags);
110
+ } catch (error) {
111
+ return {
112
+ kind: Reflect.get(Object(error), "code") === "ELOOP" ? "refused" : "failed",
113
+ error
114
+ };
115
+ }
116
+ let stats;
117
+ try {
118
+ stats = await handle.stat();
119
+ } catch (error) {
120
+ await handle.close();
121
+ return {
122
+ kind: "failed",
123
+ error
124
+ };
125
+ }
126
+ const reason = refusal(stats);
127
+ if (reason === void 0) return {
128
+ kind: "opened",
129
+ handle,
130
+ stats
131
+ };
132
+ await handle.close();
133
+ return {
134
+ kind: "refused",
135
+ error: /* @__PURE__ */ new Error(`follow_links is false, so the viewer won't read ${path}: ${reason}`)
136
+ };
137
+ }
138
+ //#endregion
60
139
  //#region src/viewer/server.ts
61
140
  /**
62
141
  * Tiny HTTP server: 5 API routes, SSE fan-out, NDJSON ingest, plus the
@@ -79,7 +158,13 @@ function create_broadcaster(config) {
79
158
  * A server bound to a loopback name answers only requests whose `Host` names
80
159
  * loopback too, so a web page can't reach it by rebinding a domain of its own
81
160
  * to 127.0.0.1. Ingest is mounted unless the config turns it off, reads only
82
- * `application/x-ndjson`, and refuses a body past 8 MB.
161
+ * `application/x-ndjson`, and refuses a body past 8 MB. With `follow_links`
162
+ * false, `/api/trajectory` serves the file only through a handle opened
163
+ * without following a link at its last name (see `no_follow.ts`).
164
+ *
165
+ * The routes live in `create_viewer_handler`, which a host can mount under a
166
+ * path of its own on a server of its own. `start_server` is that handler on a
167
+ * socket, behind the `Host` check, with a 404 for whatever it doesn't serve.
83
168
  */
84
169
  const SSE_HEARTBEAT_MS = 15e3;
85
170
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -123,47 +208,110 @@ const NDJSON = "application/x-ndjson";
123
208
  */
124
209
  const INGEST_LIMIT_BYTES = 8e6;
125
210
  /**
126
- * Starts the HTTP server and resolves once it is listening.
211
+ * The base a request target is parsed against to read its path. A path never
212
+ * depends on the authority it's parsed against, so a fixed one serves every
213
+ * request, whatever `Host` it names or leaves out.
214
+ */
215
+ const ROUTE_BASE = "http://localhost";
216
+ /**
217
+ * Builds the viewer's request handler: the five API routes (health, snapshot,
218
+ * trajectory, SSE, ingest) and the compiled app's static files, for a host to
219
+ * mount on a `node:http` server of its own, or on any framework that hands
220
+ * over the raw request and response.
127
221
  *
128
- * Wires the five API routes (health, snapshot, trajectory, SSE, ingest) plus
129
- * the compiled app's static files to a single request handler, and resolves
130
- * with the bound URL and port and a `close` that shuts the socket down. The
131
- * `Host` check runs before anything else, then the API routes are matched
132
- * first and exactly, so no file the canvas ships can ever shadow one.
222
+ * The API routes are matched first and exactly, so no file the canvas ships
223
+ * can ever shadow one. The handler checks no `Host`, so a host that mounts it
224
+ * decides who may reach it, behind its own auth. `start_server` puts the
225
+ * loopback check in front of it.
133
226
  */
134
- function start_server(config) {
135
- const { broadcaster, host, port, app_dir, trajectory_path, ingest = true, on_parse_error } = config;
136
- const handler = (req, res) => {
137
- if (!host_allowed(host, req.headers.host)) {
138
- send_forbidden_host(res, host);
139
- return;
227
+ function create_viewer_handler(config) {
228
+ const { broadcaster, app_dir, trajectory_path, ingest = true, on_parse_error } = config;
229
+ const base_path = normalize_base_path(config.base_path);
230
+ const no_follow = config.follow_links === false ? no_follow_flags() : void 0;
231
+ return (req, res) => {
232
+ const method = req.method ?? "GET";
233
+ const target = new URL(req.url ?? "/", ROUTE_BASE);
234
+ if (target.pathname === base_path) {
235
+ if (method !== "GET") return false;
236
+ redirect_to_slash(res, base_path, target.search);
237
+ return true;
140
238
  }
141
- const route = resolve_route(req, host, port);
239
+ const path = path_under(target.pathname, base_path);
240
+ if (path === void 0) return false;
241
+ const route = `${method} ${path}`;
142
242
  if (route === "GET /api/health") {
143
243
  send_json(res, 200, { ok: true });
144
- return;
244
+ return true;
145
245
  }
146
246
  if (route === "GET /api/snapshot") {
147
247
  send_json(res, 200, { events: broadcaster.snapshot() });
148
- return;
248
+ return true;
149
249
  }
150
250
  if (route === "GET /api/trajectory") {
151
- serve_trajectory(res, broadcaster, trajectory_path);
152
- return;
251
+ serve_trajectory(res, broadcaster, trajectory_path, no_follow);
252
+ return true;
153
253
  }
154
254
  if (route === "GET /api/events") {
155
255
  handle_sse(req, res, broadcaster);
156
- return;
256
+ return true;
157
257
  }
158
258
  if (ingest && route === "POST /api/ingest") {
159
259
  handle_ingest(req, res, broadcaster, on_parse_error);
160
- return;
260
+ return true;
161
261
  }
162
- if (route.startsWith("GET /")) {
163
- serve_app_asset(res, route, app_dir);
262
+ return route.startsWith("GET /") && serve_app_asset(res, path, app_dir);
263
+ };
264
+ }
265
+ /**
266
+ * A base path with its trailing slash taken off, so `/viewer/abc/` and
267
+ * `/viewer/abc` mount the same way, and the root reads as `''`.
268
+ *
269
+ * Throws on a path that doesn't start with a slash, which no request path
270
+ * could ever fall under.
271
+ */
272
+ function normalize_base_path(base_path) {
273
+ if (base_path === void 0) return "";
274
+ if (!base_path.startsWith("/")) throw new TypeError(`viewer base_path must start with a slash; got ${JSON.stringify(base_path)}`);
275
+ return base_path.replace(/\/$/, "");
276
+ }
277
+ /**
278
+ * The part of a request path under `base_path`, starting with its slash, or
279
+ * undefined when the request falls outside it. `/viewer/abcd` is outside
280
+ * `/viewer/abc`, and every path is under the root's `''`.
281
+ */
282
+ function path_under(pathname, base_path) {
283
+ return pathname.startsWith(`${base_path}/`) ? pathname.slice(base_path.length) : void 0;
284
+ }
285
+ /**
286
+ * Redirects a request for the bare base path to the same path with a trailing
287
+ * slash, which is what the canvas resolves its relative URLs against.
288
+ *
289
+ * The `Location` names only the last segment, which a browser resolves
290
+ * against the path it asked for, so the redirect still lands when another
291
+ * proxy in front of the host has taken a prefix of its own off.
292
+ */
293
+ function redirect_to_slash(res, base_path, search) {
294
+ res.statusCode = 308;
295
+ res.setHeader("location", `${base_path.slice(base_path.lastIndexOf("/") + 1)}/${search}`);
296
+ res.end();
297
+ }
298
+ /**
299
+ * Starts the HTTP server and resolves once it is listening.
300
+ *
301
+ * Mounts `create_viewer_handler` at the root behind the `Host` check, answers
302
+ * a JSON 404 naming the route for anything the handler doesn't serve, and
303
+ * resolves with the bound URL and port and a `close` that shuts the socket
304
+ * down.
305
+ */
306
+ function start_server(config) {
307
+ const { host, port } = config;
308
+ const viewer = create_viewer_handler(config);
309
+ const handler = (req, res) => {
310
+ if (!host_allowed(host, req.headers.host)) {
311
+ send_forbidden_host(res, host);
164
312
  return;
165
313
  }
166
- send_not_found(res, route);
314
+ if (!viewer(req, res)) send_not_found(res, resolve_route(req));
167
315
  };
168
316
  const http_server = createServer(handler);
169
317
  return new Promise((res_ok, res_err) => {
@@ -242,23 +390,13 @@ function send_forbidden_host(res, bound) {
242
390
  });
243
391
  }
244
392
  /**
245
- * Builds a `"METHOD /path"` route key from a request.
393
+ * Builds a `"METHOD /path"` route key from a request, the key a 404 names.
246
394
  *
247
- * Resolves the path against the client's `Host` header when it parses, and
248
- * against the server's own `host`/`port` otherwise. A header can be present yet
249
- * malformed (`'in valid'`), which `??` cannot catch because it is neither null
250
- * nor undefined; fed to `new URL` it throws. Trying the header inside a
251
- * try/catch and falling back to the server's authority keeps route resolution
252
- * total for any header a client sends.
395
+ * The path is read against a fixed base rather than the client's `Host`, which
396
+ * can be absent or malformed and changes no path either way.
253
397
  */
254
- function resolve_route(req, host, port) {
255
- const method = req.method ?? "GET";
256
- const path = req.url ?? "/";
257
- const header = req.headers.host;
258
- if (header !== void 0) try {
259
- return `${method} ${new URL(path, `http://${header}`).pathname}`;
260
- } catch {}
261
- return `${method} ${new URL(path, `http://${format_authority(host, port)}`).pathname}`;
398
+ function resolve_route(req) {
399
+ return `${req.method ?? "GET"} ${new URL(req.url ?? "/", ROUTE_BASE).pathname}`;
262
400
  }
263
401
  /**
264
402
  * Closes the HTTP server and resolves once every connection is torn down.
@@ -302,20 +440,49 @@ function send_not_found(res, route) {
302
440
  * broadcaster's newest id, the seam the client resumes SSE from; the client
303
441
  * still takes the larger of that and its own folded count, so a file that ran
304
442
  * ahead of the broadcaster is not re-folded.
443
+ *
444
+ * With `no_follow` set (`follow_links: false`), the file is served through
445
+ * `serve_unfollowed` instead, after the headers and the ring are taken here.
305
446
  */
306
- function serve_trajectory(res, broadcaster, trajectory_path) {
447
+ function serve_trajectory(res, broadcaster, trajectory_path, no_follow) {
307
448
  const ring = broadcaster.snapshot();
308
449
  res.statusCode = 200;
309
450
  res.setHeader("content-type", "application/x-ndjson; charset=utf-8");
310
451
  res.setHeader("cache-control", "no-store");
311
452
  res.setHeader(CURSOR_HEADER, String(ring.at(-1)?.id ?? 0));
453
+ if (trajectory_path !== void 0 && no_follow !== void 0) {
454
+ serve_unfollowed(res, trajectory_path, no_follow, ring);
455
+ return;
456
+ }
312
457
  if (trajectory_path !== void 0) {
313
458
  if (stat_file(trajectory_path) !== null) {
314
459
  stream_file(res, trajectory_path);
315
460
  return;
316
461
  }
317
462
  }
318
- res.end(ring.map((entry) => `${JSON.stringify(entry.event)}\n`).join(""));
463
+ res.end(ring_ndjson(ring));
464
+ }
465
+ /**
466
+ * The ring's events as NDJSON, one per line, which is the whole history a
467
+ * server holds when there's no file it may serve.
468
+ */
469
+ function ring_ndjson(ring) {
470
+ return ring.map((entry) => `${JSON.stringify(entry.event)}\n`).join("");
471
+ }
472
+ /**
473
+ * Serves the trajectory from a handle opened without following a link at the
474
+ * path's last name and checked before a byte is read (see `open_unfollowed`),
475
+ * so the file that passed the check is the file that's streamed. A path that
476
+ * can't be opened that way, or that holds anything but a regular file with no
477
+ * other name, is served as no file, from the ring. Never rejects.
478
+ */
479
+ async function serve_unfollowed(res, path, flags, ring) {
480
+ const opened = await open_unfollowed(path, flags);
481
+ if (opened.kind !== "opened") {
482
+ res.end(ring_ndjson(ring));
483
+ return;
484
+ }
485
+ pipeline(opened.handle.createReadStream(), res, () => {});
319
486
  }
320
487
  /**
321
488
  * Where the compiled canvas can be, relative to this module.
@@ -368,31 +535,30 @@ function resolve_app_file(dir, url_path) {
368
535
  return file === dir ? resolve(dir, "index.html") : file;
369
536
  }
370
537
  /**
371
- * Streams one file of the compiled canvas as the response body.
538
+ * Streams one file of the compiled canvas as the response body, returning
539
+ * whether it answered.
372
540
  *
373
541
  * A missing app directory is a 500 naming the build step, because the server
374
542
  * is fine and the operator forgot to compile; a missing file inside a present
375
- * app is an ordinary 404.
543
+ * app goes unanswered, for the caller's 404.
376
544
  */
377
- function serve_app_asset(res, route, override) {
545
+ function serve_app_asset(res, path, override) {
378
546
  const dir = resolve_app_dir(override);
379
547
  if (dir === null) {
380
548
  res.statusCode = 500;
381
549
  res.setHeader("content-type", "text/plain");
382
550
  res.end("viewer app not built; run `pnpm build`");
383
- return;
551
+ return true;
384
552
  }
385
- const file = resolve_app_file(dir, route.slice(route.indexOf(" ") + 1));
553
+ const file = resolve_app_file(dir, path);
386
554
  const stats = file === null ? null : stat_file(file);
387
- if (file === null || stats === null) {
388
- send_not_found(res, route);
389
- return;
390
- }
555
+ if (file === null || stats === null) return false;
391
556
  res.statusCode = 200;
392
557
  res.setHeader("content-type", CONTENT_TYPES[extname(file)] ?? FALLBACK_CONTENT_TYPE);
393
558
  res.setHeader("cache-control", "no-store");
394
559
  res.setHeader("content-length", String(stats.size));
395
560
  stream_file(res, file);
561
+ return true;
396
562
  }
397
563
  /**
398
564
  * Streams a file as the response body, dropping the connection if the read
@@ -624,6 +790,14 @@ function handle_ingest(req, res, broadcaster, on_parse_error) {
624
790
  * which also covers platforms where fs.watch misses some append
625
791
  * notifications: the next successful change event catches the file up
626
792
  * regardless.
793
+ *
794
+ * With `follow_links: false`, a pass opens the path first, without following
795
+ * a link at its last name, and takes the inode and size from the handle it
796
+ * opened, then reads through that same handle (see `no_follow.ts`). What it
797
+ * won't read, a link or anything but a regular file with no other name, goes
798
+ * to `on_io_error`, and the tail waits as it does for a missing file. The
799
+ * watches still follow a link, but a watch only starts a pass, and every pass
800
+ * opens the path again without following one, so nothing is read through it.
627
801
  */
628
802
  /**
629
803
  * True for the errors a stat or an open throws when no file is at the path,
@@ -693,6 +867,7 @@ function next_name(dir, path) {
693
867
  */
694
868
  function start_tail(config) {
695
869
  const { path, on_event, on_parse_error, on_io_error } = config;
870
+ const no_follow = config.follow_links === false ? no_follow_flags() : void 0;
696
871
  let inode = null;
697
872
  let offset = 0;
698
873
  let buffer = "";
@@ -759,33 +934,57 @@ function start_tail(config) {
759
934
  file_watcher = watch$1(path, schedule);
760
935
  watch_nearest();
761
936
  };
937
+ const forget = () => {
938
+ inode = null;
939
+ await_file();
940
+ };
941
+ const track = (st) => {
942
+ if (st.ino !== inode) adopt(st.ino);
943
+ else if (st.size < offset) {
944
+ offset = 0;
945
+ buffer = "";
946
+ }
947
+ return st.size;
948
+ };
762
949
  const locate = async () => {
763
950
  let st;
764
951
  try {
765
952
  st = await stat(path);
766
953
  } catch (err) {
767
- if (is_missing(err)) {
768
- inode = null;
769
- await_file();
770
- }
954
+ if (is_missing(err)) forget();
771
955
  report(err);
772
956
  return null;
773
957
  }
774
- if (st.ino !== inode) adopt(st.ino);
775
- else if (st.size < offset) {
776
- offset = 0;
777
- buffer = "";
778
- }
779
- return st.size;
958
+ return track(st);
780
959
  };
781
- const read_more = async () => {
960
+ const open_followed = async () => {
782
961
  const size = await locate();
783
- if (size === null || size === offset) return;
962
+ if (size === null || size === offset) return null;
784
963
  const fh = await open(path, "r").catch((err) => {
785
964
  report(err);
786
965
  return null;
787
966
  });
788
- if (!fh) return;
967
+ return fh === null ? null : {
968
+ fh,
969
+ size
970
+ };
971
+ };
972
+ const open_checked = async (flags) => {
973
+ const opened = await open_unfollowed(path, flags);
974
+ if (opened.kind !== "opened") {
975
+ if (opened.kind === "refused" || is_missing(opened.error)) forget();
976
+ report(opened.error);
977
+ return null;
978
+ }
979
+ return {
980
+ fh: opened.handle,
981
+ size: track(opened.stats)
982
+ };
983
+ };
984
+ const read_more = async () => {
985
+ const opened = await (no_follow === void 0 ? open_followed() : open_checked(no_follow));
986
+ if (opened === null) return;
987
+ const { fh, size } = opened;
789
988
  try {
790
989
  const length = size - offset;
791
990
  const buf = Buffer.alloc(length);
@@ -872,12 +1071,14 @@ async function start_viewer(options = {}) {
872
1071
  host,
873
1072
  port,
874
1073
  ingest: options.ingest,
1074
+ follow_links: options.follow_links,
875
1075
  ...options.path !== void 0 ? { trajectory_path: options.path } : {},
876
1076
  ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}
877
1077
  });
878
1078
  let tail = null;
879
1079
  if (options.path !== void 0) tail = start_tail({
880
1080
  path: options.path,
1081
+ follow_links: options.follow_links,
881
1082
  on_event: (event) => {
882
1083
  broadcaster.emit(event);
883
1084
  },
@@ -1095,6 +1296,6 @@ if (process.argv[1] !== void 0 && process.argv[1] === fileURLToPath(import.meta.
1095
1296
  process.exit(1);
1096
1297
  });
1097
1298
  //#endregion
1098
- export { create_broadcaster, run_viewer_cli, start_server, start_tail, start_viewer };
1299
+ export { create_broadcaster, create_viewer_handler, run_viewer_cli, start_server, start_tail, start_viewer };
1099
1300
 
1100
1301
  //# sourceMappingURL=viewer.js.map