screenreader-speech-capture 0.0.1-preview.2 → 0.0.1-preview.4

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 (2) hide show
  1. package/dist/cli.mjs +1573 -330
  2. package/package.json +3 -6
package/dist/cli.mjs CHANGED
@@ -1,10 +1,491 @@
1
1
  #!/usr/bin/env node
2
+ import http from "node:http";
2
3
  import net from "node:net";
3
- import { TextDecoder as TextDecoder$1 } from "node:util";
4
- import { performance } from "node:perf_hooks";
5
- import { monotonicFactory } from "ulid";
4
+ import { TextDecoder as TextDecoder$1, parseArgs } from "node:util";
5
+ import fs from "node:fs/promises";
6
+ import path from "node:path";
7
+ import fs$1 from "node:fs";
8
+ import os from "node:os";
6
9
  // package.json
7
- var version = "0.0.1-preview.2";
10
+ var version = "0.0.1-preview.3";
11
+ // ../shared/src/api-version.ts
12
+ /** Path prefix of every API route. */
13
+ const API_PREFIX = "/api/v1";
14
+ // ../shared/src/errors.ts
15
+ /** HTTP status for each error code. */
16
+ const ERROR_STATUS = {
17
+ INVALID_REQUEST: 400,
18
+ NOT_FOUND: 404,
19
+ INPUT_DISABLED: 409,
20
+ SERVICE_UNAVAILABLE: 503,
21
+ INTERNAL: 500
22
+ };
23
+ // src/domain/errors.ts
24
+ /** An expected error with a stable code, for example a bad request. */
25
+ var AppError = class extends Error {
26
+ code;
27
+ details;
28
+ name = "AppError";
29
+ constructor(code, message, details) {
30
+ super(message);
31
+ this.code = code;
32
+ this.details = details;
33
+ }
34
+ };
35
+ /** `INVALID_REQUEST` for one field. */
36
+ function invalidField(field, message) {
37
+ return new AppError("INVALID_REQUEST", `${field}: ${message}`, { field });
38
+ }
39
+ // src/adapters/in/net/listen.ts
40
+ /** Thrown when a listener can't use its port (for example `EADDRINUSE`). */
41
+ var ListenError = class extends Error {
42
+ code;
43
+ name = "ListenError";
44
+ constructor(message, code) {
45
+ super(message);
46
+ this.code = code;
47
+ }
48
+ };
49
+ /**
50
+ * Starts `server` on `host:port` and resolves with the bound port (useful with port 0).
51
+ * Rejects with a `ListenError` that says what went wrong, naming the port.
52
+ */
53
+ async function listen(server, host, port) {
54
+ await new Promise((resolve, reject) => {
55
+ const onError = (error) => {
56
+ reject(new ListenError(`Cannot listen on ${host}:${port}: ${error.code === "EADDRINUSE" ? "the port is already in use (is another bridge running?)" : error.message}`, error.code));
57
+ };
58
+ server.once("error", onError);
59
+ server.listen(port, host, () => {
60
+ server.off("error", onError);
61
+ resolve();
62
+ });
63
+ });
64
+ return server.address().port;
65
+ }
66
+ // src/adapters/in/http/response.ts
67
+ function sendJson(res, status, body) {
68
+ const data = JSON.stringify(body);
69
+ res.writeHead(status, {
70
+ "content-type": "application/json; charset=utf-8",
71
+ "content-length": Buffer.byteLength(data)
72
+ });
73
+ res.end(data);
74
+ }
75
+ // src/adapters/in/http/errors.ts
76
+ /**
77
+ * Sends the error body every endpoint uses (docs/http-api.md#errors). An `AppError` keeps its
78
+ * code. Anything else is `INTERNAL`, with the details in the bridge log only.
79
+ */
80
+ function sendError(res, error, logger) {
81
+ let body;
82
+ if (error instanceof AppError) {
83
+ body = { error: {
84
+ code: error.code,
85
+ message: error.message
86
+ } };
87
+ if (error.details !== void 0) body.error.details = error.details;
88
+ } else {
89
+ logger.error(`internal error: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
90
+ body = { error: {
91
+ code: "INTERNAL",
92
+ message: "Internal error, see the bridge log"
93
+ } };
94
+ }
95
+ if (res.headersSent) {
96
+ res.destroy();
97
+ return;
98
+ }
99
+ sendJson(res, ERROR_STATUS[body.error.code], body);
100
+ }
101
+ // src/adapters/in/http/router.ts
102
+ /** Exact-path router: method + path → handler. Anything else is `NOT_FOUND`. */
103
+ var Router = class {
104
+ routes = /* @__PURE__ */ new Map();
105
+ add(method, path, handler) {
106
+ this.routes.set(`${method} ${path}`, handler);
107
+ return this;
108
+ }
109
+ find(method, path) {
110
+ const handler = this.routes.get(`${method} ${path}`);
111
+ if (!handler) throw new AppError("NOT_FOUND", `Unknown endpoint ${method} ${path}`);
112
+ return handler;
113
+ }
114
+ };
115
+ // src/adapters/in/http/sse.ts
116
+ /** The open Server-Sent Events responses: starts them, pings them and ends them on shutdown. */
117
+ var SseHub = class {
118
+ settings;
119
+ streams = /* @__PURE__ */ new Set();
120
+ constructor(settings) {
121
+ this.settings = settings;
122
+ }
123
+ /** Starts the SSE response on `res`. `onClose` runs once when the stream ends. */
124
+ open(res, onClose) {
125
+ res.writeHead(200, {
126
+ "content-type": "text/event-stream; charset=utf-8",
127
+ "cache-control": "no-cache",
128
+ connection: "keep-alive"
129
+ });
130
+ res.flushHeaders();
131
+ const send = (frame) => {
132
+ if (res.destroyed || res.writableEnded) return;
133
+ res.write(frame);
134
+ if (res.writableLength > this.settings.maxBufferedBytes) res.destroy();
135
+ };
136
+ const ping = setInterval(() => send(": ping\n\n"), this.settings.pingMs);
137
+ ping.unref();
138
+ this.streams.add(res);
139
+ res.once("close", () => {
140
+ clearInterval(ping);
141
+ this.streams.delete(res);
142
+ onClose();
143
+ });
144
+ return send;
145
+ }
146
+ /** Ends every open stream, for shutdown. */
147
+ closeAll() {
148
+ for (const res of this.streams) res.end();
149
+ }
150
+ };
151
+ // src/adapters/in/http/dto.ts
152
+ function toSpeechEntryDto(entry) {
153
+ return {
154
+ seq: entry.seq,
155
+ kind: entry.kind,
156
+ text: entry.text,
157
+ receivedAt: entry.receivedAt.toISOString(),
158
+ source: entry.source,
159
+ voice: entry.voice,
160
+ connectionId: entry.connectionId
161
+ };
162
+ }
163
+ function toSpeechListDto(page) {
164
+ return {
165
+ entries: page.entries.map(toSpeechEntryDto),
166
+ truncated: page.truncated,
167
+ hasMore: page.hasMore
168
+ };
169
+ }
170
+ function toWaitResultDto(result) {
171
+ return result.status === "matched" ? {
172
+ matched: true,
173
+ entry: toSpeechEntryDto(result.entry)
174
+ } : {
175
+ matched: false,
176
+ entries: result.seen.map(toSpeechEntryDto)
177
+ };
178
+ }
179
+ function toStatusDto({ bridge, tcp, buffer, input }) {
180
+ return {
181
+ bridge: {
182
+ version: bridge.version,
183
+ apiVersion: bridge.apiVersion,
184
+ state: bridge.state
185
+ },
186
+ tcp: {
187
+ listening: tcp.listening,
188
+ host: tcp.host,
189
+ port: tcp.port,
190
+ encoding: tcp.encoding,
191
+ connections: tcp.connections.map(({ id, voice, connectedAt }) => ({
192
+ id,
193
+ voice,
194
+ connectedAt: connectedAt.toISOString()
195
+ }))
196
+ },
197
+ buffer: {
198
+ size: buffer.size,
199
+ maxEntries: buffer.maxEntries,
200
+ firstSeq: buffer.firstSeq,
201
+ lastSeq: buffer.lastSeq
202
+ },
203
+ input: { enabled: input.enabled }
204
+ };
205
+ }
206
+ function toConfigDto({ tcp, http, playwright, mcp, input, buffer, log }) {
207
+ return {
208
+ tcp: {
209
+ host: tcp.host,
210
+ port: tcp.port,
211
+ format: tcp.format,
212
+ encoding: tcp.encoding,
213
+ maxLineBytes: tcp.maxLineBytes
214
+ },
215
+ http: {
216
+ host: http.host,
217
+ port: http.port
218
+ },
219
+ playwright: {
220
+ enabled: playwright.enabled,
221
+ port: playwright.port,
222
+ version: playwright.version
223
+ },
224
+ mcp: {
225
+ enabled: mcp.enabled,
226
+ port: mcp.port,
227
+ version: mcp.version
228
+ },
229
+ input: { enabled: input.enabled },
230
+ buffer: { maxEntries: buffer.maxEntries },
231
+ log: {
232
+ level: log.level,
233
+ file: log.file,
234
+ consoleSpeech: log.consoleSpeech
235
+ }
236
+ };
237
+ }
238
+ // src/adapters/in/http/request.ts
239
+ /**
240
+ * An integer query parameter, `undefined` if it is missing. Only the syntax is checked here:
241
+ * defaults and ranges are use-case rules, applied by the application.
242
+ */
243
+ function intParam(url, name) {
244
+ const raw = url.searchParams.get(name);
245
+ if (raw === null || raw === "") return void 0;
246
+ if (!/^-?\d+$/.test(raw)) throw invalidField(name, "must be an integer");
247
+ return Number(raw);
248
+ }
249
+ /** A string query parameter, `undefined` if it is missing. */
250
+ function stringParam(url, name) {
251
+ return url.searchParams.get(name) ?? void 0;
252
+ }
253
+ /** A boolean query parameter (`1` / `true` / `0` / `false`), `undefined` if it is missing. */
254
+ function booleanParam(url, name) {
255
+ const raw = url.searchParams.get(name);
256
+ if (raw === null || raw === "") return void 0;
257
+ if (raw === "1" || raw === "true") return true;
258
+ if (raw === "0" || raw === "false") return false;
259
+ throw invalidField(name, "must be 1, true, 0 or false");
260
+ }
261
+ const MAX_BODY_BYTES = 1048576;
262
+ /**
263
+ * Rejects a body that isn't declared as `application/json`. Besides being the contract, this
264
+ * keeps web pages from sending it cross-origin: a browser only sends a JSON content type after
265
+ * a CORS preflight, which the bridge doesn't answer.
266
+ */
267
+ function requireJson(req) {
268
+ if ((req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase() !== "application/json") throw invalidField("content-type", "must be application/json");
269
+ }
270
+ const tooLarge = () => invalidField("body", `must be at most ${MAX_BODY_BYTES} bytes`);
271
+ /** Reads the request body as JSON. */
272
+ async function readJson(req) {
273
+ if (Number(req.headers["content-length"] ?? 0) > 1048576) throw tooLarge();
274
+ const chunks = [];
275
+ let size = 0;
276
+ for await (const chunk of req) {
277
+ size += chunk.length;
278
+ if (size > 1048576) throw tooLarge();
279
+ chunks.push(chunk);
280
+ }
281
+ try {
282
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
283
+ } catch {
284
+ throw invalidField("body", "must be valid JSON");
285
+ }
286
+ }
287
+ // src/adapters/in/http/speech-routes.ts
288
+ function isObject(value) {
289
+ return typeof value === "object" && value !== null && !Array.isArray(value);
290
+ }
291
+ /** The SSE frame for one event (docs/http-api.md, `GET /speech/stream`). */
292
+ function sseFrame(event) {
293
+ if (event.type !== "entry") return `event: ${event.type}\ndata: {}\n\n`;
294
+ const data = JSON.stringify(toSpeechEntryDto(event.entry));
295
+ return `id: ${event.entry.seq}\nevent: entry\ndata: ${data}\n\n`;
296
+ }
297
+ /** `Last-Event-ID` of an SSE reconnect, `null` on a first connect. */
298
+ function lastEventId(req) {
299
+ const raw = req.headers["last-event-id"];
300
+ if (raw === void 0 || raw === "") return null;
301
+ const value = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : NaN;
302
+ if (!Number.isSafeInteger(value)) throw invalidField("Last-Event-ID", "must be a seq");
303
+ return value;
304
+ }
305
+ function speechRoutes(router, deps) {
306
+ const { speech, waits, sse } = deps;
307
+ router.add("GET", `${API_PREFIX}/speech`, ({ res, url }) => {
308
+ sendJson(res, 200, toSpeechListDto(speech.list({
309
+ since: intParam(url, "since"),
310
+ limit: intParam(url, "limit")
311
+ })));
312
+ }).add("DELETE", `${API_PREFIX}/speech`, ({ res }) => {
313
+ speech.clear();
314
+ res.writeHead(204).end();
315
+ }).add("POST", `${API_PREFIX}/markers`, async ({ req, res }) => {
316
+ requireJson(req);
317
+ const body = await readJson(req);
318
+ if (!isObject(body) || typeof body.label !== "string") throw invalidField("label", "must be a string");
319
+ sendJson(res, 201, toSpeechEntryDto(speech.addMarker(body.label)));
320
+ }).add("GET", `${API_PREFIX}/speech/wait`, async ({ res, url }) => {
321
+ const controller = new AbortController();
322
+ res.on("close", () => {
323
+ if (!res.writableEnded) controller.abort();
324
+ });
325
+ let result;
326
+ try {
327
+ result = await waits.wait({
328
+ contains: stringParam(url, "contains"),
329
+ regex: stringParam(url, "regex"),
330
+ normalize: booleanParam(url, "normalize"),
331
+ since: intParam(url, "since"),
332
+ timeoutMs: intParam(url, "timeoutMs"),
333
+ signal: controller.signal
334
+ });
335
+ } catch (error) {
336
+ if (controller.signal.aborted) return;
337
+ throw error;
338
+ }
339
+ sendJson(res, 200, toWaitResultDto(result));
340
+ }).add("GET", `${API_PREFIX}/speech/stream`, ({ req, res }) => {
341
+ const since = lastEventId(req);
342
+ const send = sse.open(res, () => unwatch());
343
+ const unwatch = speech.watch(since, (event) => send(sseFrame(event)));
344
+ });
345
+ }
346
+ // src/adapters/in/http/status-routes.ts
347
+ function statusRoutes(router, { status, config }) {
348
+ router.add("GET", `${API_PREFIX}/status`, ({ res }) => sendJson(res, 200, toStatusDto(status.status()))).add("GET", `${API_PREFIX}/config`, ({ res }) => sendJson(res, 200, toConfigDto(config.get()))).add("PUT", `${API_PREFIX}/config`, async ({ req, res }) => {
349
+ requireJson(req);
350
+ sendJson(res, 200, toConfigDto(await config.update(await readJson(req))));
351
+ });
352
+ }
353
+ // src/adapters/in/http/http-server.ts
354
+ /** How long `stop()` waits for open requests before it closes their connections. */
355
+ const CLOSE_GRACE_MS = 1e3;
356
+ /** Bytes an SSE stream may hold for a client that stopped reading before it is closed. */
357
+ const SSE_MAX_BUFFERED_BYTES = 1048576;
358
+ /** `host:port` for a URL, with an IPv6 host in brackets. */
359
+ function hostPort(host, port) {
360
+ return host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
361
+ }
362
+ /**
363
+ * Driving adapter for the REST + SSE API (docs/http-api.md), on plain `node:http`.
364
+ */
365
+ var HttpServer = class {
366
+ deps;
367
+ server = null;
368
+ settings = null;
369
+ /** Servers replaced by `restart()` that are still finishing their open requests. */
370
+ retiring = /* @__PURE__ */ new Set();
371
+ router = new Router();
372
+ sse;
373
+ constructor(deps) {
374
+ this.deps = deps;
375
+ this.sse = new SseHub({
376
+ pingMs: deps.pingMs ?? 15e3,
377
+ maxBufferedBytes: SSE_MAX_BUFFERED_BYTES
378
+ });
379
+ speechRoutes(this.router, {
380
+ ...deps,
381
+ sse: this.sse
382
+ });
383
+ statusRoutes(this.router, deps);
384
+ }
385
+ /** Starts listening. Resolves with the bound port (useful with port 0). */
386
+ async start(settings) {
387
+ if (this.server) throw new Error("HTTP server is already running");
388
+ return this.bind(settings);
389
+ }
390
+ /**
391
+ * Moves the API to new settings (`PUT /api/v1/config`) and resolves with the bound port.
392
+ * The request that asked for it is served by the old server, so that one is not awaited: it
393
+ * stops accepting connections and lets its open requests finish in the background.
394
+ *
395
+ * A new port is bound before the old server stops, so a port that is in use leaves everything
396
+ * as it was. The same port on another host can't be bound while the old server holds it: then
397
+ * the old server stops listening first, and starts again if the new address fails.
398
+ */
399
+ async restart(settings) {
400
+ const old = this.server;
401
+ const previous = this.settings;
402
+ if (!old || !previous) return this.start(settings);
403
+ if (settings.port === 0 || settings.port !== previous.port) {
404
+ const port = await this.bind(settings, old);
405
+ this.retire(old);
406
+ return port;
407
+ }
408
+ this.server = null;
409
+ this.retire(old);
410
+ try {
411
+ return await this.bind(settings);
412
+ } catch (error) {
413
+ await this.bind(previous);
414
+ throw error;
415
+ }
416
+ }
417
+ /** Stops accepting connections, ends SSE streams and waits briefly for open requests. */
418
+ async stop() {
419
+ const server = this.server;
420
+ this.server = null;
421
+ this.settings = null;
422
+ if (server) this.retire(server);
423
+ await Promise.all(this.retiring);
424
+ if (server) this.deps.logger.info("stopped listening");
425
+ }
426
+ /** Listens on `settings` with a new server, which then replaces `replacing` (if any). */
427
+ async bind(settings, replacing = null) {
428
+ const server = http.createServer((req, res) => {
429
+ res.once("finish", () => {
430
+ if (this.server !== server) req.socket.end();
431
+ });
432
+ this.handle(req, res).catch((error) => {
433
+ this.deps.logger.error(`request failed: ${String(error)}`);
434
+ res.destroy();
435
+ });
436
+ });
437
+ const port = await listen(server, settings.host, settings.port);
438
+ server.on("error", (error) => this.deps.logger.error(`HTTP server error: ${error.message}`));
439
+ if (this.server !== replacing) {
440
+ server.close();
441
+ throw new Error("HTTP server changed while it was being restarted");
442
+ }
443
+ this.server = server;
444
+ this.settings = {
445
+ ...settings,
446
+ port
447
+ };
448
+ this.deps.logger.info(`listening on http://${hostPort(settings.host, port)}`);
449
+ return port;
450
+ }
451
+ /**
452
+ * Stops `server` from accepting connections, ends the SSE streams (clients reconnect) and
453
+ * closes its connections once their requests are done, forcing them after a grace period.
454
+ */
455
+ retire(server) {
456
+ const closed = new Promise((resolve) => server.close(() => resolve()));
457
+ this.sse.closeAll();
458
+ server.closeIdleConnections();
459
+ const force = setTimeout(() => server.closeAllConnections(), CLOSE_GRACE_MS);
460
+ const done = closed.then(() => clearTimeout(force));
461
+ this.retiring.add(done);
462
+ done.then(() => this.retiring.delete(done));
463
+ }
464
+ async handle(req, res) {
465
+ const method = req.method ?? "GET";
466
+ let path = "(invalid URL)";
467
+ res.on("finish", () => this.deps.logger.debug(`${method} ${path} → ${res.statusCode}`));
468
+ try {
469
+ const url = parseUrl(req.url);
470
+ path = url.pathname;
471
+ await this.router.find(method, url.pathname)({
472
+ req,
473
+ res,
474
+ url
475
+ });
476
+ } catch (error) {
477
+ sendError(res, error, this.deps.logger);
478
+ }
479
+ }
480
+ };
481
+ /** The request target as a URL. An absolute-form target such as `http://[` doesn't parse. */
482
+ function parseUrl(target) {
483
+ try {
484
+ return new URL(target ?? "/", "http://bridge");
485
+ } catch {
486
+ throw new AppError("INVALID_REQUEST", "The request URL is not valid");
487
+ }
488
+ }
8
489
  // src/adapters/in/tcp/text-to-socket-parser.ts
9
490
  const LF = 10;
10
491
  const CR = 13;
@@ -85,52 +566,46 @@ var TextToSocketParser = class {
85
566
  }
86
567
  };
87
568
  // src/adapters/in/tcp/tcp-listener.ts
88
- /** Thrown by `start()` when the port can't be used (for example `EADDRINUSE`). */
89
- var ListenError = class extends Error {
90
- code;
91
- name = "ListenError";
92
- constructor(message, code) {
93
- super(message);
94
- this.code = code;
95
- }
96
- };
97
569
  /**
98
570
  * Driving adapter for the socket voice: a TCP server that accepts any number of connections
99
571
  * and feeds each one through its own parser into `RecordSpeech`
100
- * (docs/speech-capture.md#listening-and-connections).
572
+ * (docs/speech-capture.md#listening-and-connections). Also reports the listener and its open
573
+ * connections for the status.
101
574
  */
102
575
  var TcpListener = class {
103
576
  recordSpeech;
577
+ clock;
104
578
  logger;
105
579
  server = null;
106
580
  sockets = /* @__PURE__ */ new Set();
107
- constructor(recordSpeech, logger) {
581
+ open = /* @__PURE__ */ new Map();
582
+ nextConnectionId = 1;
583
+ listener = null;
584
+ constructor(recordSpeech, clock, logger) {
108
585
  this.recordSpeech = recordSpeech;
586
+ this.clock = clock;
109
587
  this.logger = logger;
110
588
  }
589
+ captureStatus() {
590
+ return {
591
+ listener: this.listener && { ...this.listener },
592
+ connections: [...this.open.values()].map((connection) => ({ ...connection }))
593
+ };
594
+ }
111
595
  /** Starts listening. Resolves with the bound port (useful with port 0). */
112
596
  async start(settings) {
113
597
  if (this.server) throw new Error("TCP listener is already running");
114
598
  const server = net.createServer((socket) => this.accept(socket, settings));
115
- await new Promise((resolve, reject) => {
116
- const onError = (error) => {
117
- const reason = error.code === "EADDRINUSE" ? "the port is already in use (is another bridge running?)" : error.message;
118
- reject(new ListenError(`Cannot listen on ${settings.host}:${settings.port}: ${reason}`, error.code));
119
- };
120
- server.once("error", onError);
121
- server.listen(settings.port, settings.host, () => {
122
- server.off("error", onError);
123
- resolve();
124
- });
125
- });
599
+ const port = await listen(server, settings.host, settings.port);
126
600
  server.on("error", (error) => this.logger.error(`TCP listener error: ${error.message}`));
127
601
  this.server = server;
128
- const port = server.address().port;
129
- this.recordSpeech.listenerStarted({
602
+ this.listener = {
603
+ listening: true,
130
604
  host: settings.host,
131
605
  port,
132
606
  encoding: settings.encoding
133
- });
607
+ };
608
+ this.logger.info(`listening on ${settings.host}:${port}, encoding ${settings.encoding}`);
134
609
  return port;
135
610
  }
136
611
  /** Stops listening and closes all open connections. */
@@ -141,14 +616,32 @@ var TcpListener = class {
141
616
  const closed = new Promise((resolve) => server.close(() => resolve()));
142
617
  for (const socket of this.sockets) socket.destroy();
143
618
  await closed;
144
- this.recordSpeech.listenerStopped();
619
+ if (this.listener) this.listener = {
620
+ ...this.listener,
621
+ listening: false
622
+ };
623
+ this.logger.info("stopped listening");
145
624
  }
146
625
  accept(socket, settings) {
147
626
  this.sockets.add(socket);
148
- const id = this.recordSpeech.connectionOpened();
627
+ const id = this.nextConnectionId++;
628
+ const connection = {
629
+ id,
630
+ voice: null,
631
+ connectedAt: this.clock.now()
632
+ };
633
+ this.open.set(id, connection);
634
+ this.logger.info(`connection ${id} opened`);
149
635
  const parser = new TextToSocketParser(settings.encoding, settings.maxLineBytes, {
150
- header: (voice) => this.recordSpeech.setVoice(id, voice),
151
- line: (text) => this.recordSpeech.record(id, text),
636
+ header: (voice) => {
637
+ connection.voice = voice;
638
+ this.logger.info(`connection ${id}: voice=${voice}`);
639
+ },
640
+ line: (text) => this.recordSpeech.record({
641
+ text,
642
+ voice: connection.voice,
643
+ connectionId: id
644
+ }),
152
645
  lineCut: (max) => this.logger.warn(`connection ${id}: line longer than ${max} bytes, cut it`)
153
646
  });
154
647
  socket.on("data", (chunk) => parser.push(chunk));
@@ -156,10 +649,96 @@ var TcpListener = class {
156
649
  socket.on("close", () => {
157
650
  parser.end();
158
651
  this.sockets.delete(socket);
159
- this.recordSpeech.connectionClosed(id);
652
+ this.open.delete(id);
653
+ this.logger.info(`connection ${id} closed`);
160
654
  });
161
655
  }
162
656
  };
657
+ // src/adapters/out/clock/system-clock.ts
658
+ var SystemClock = class {
659
+ now() {
660
+ return /* @__PURE__ */ new Date();
661
+ }
662
+ };
663
+ // src/adapters/out/fs-config/fs-config-store.ts
664
+ /**
665
+ * The config file (docs/configuration.md): JSON with the settings saved so far. Only the file's
666
+ * own settings are written, never values from flags or environment variables.
667
+ */
668
+ var FsConfigStore = class {
669
+ location;
670
+ constructor(location) {
671
+ this.location = location;
672
+ }
673
+ async load() {
674
+ let text;
675
+ try {
676
+ text = await fs.readFile(this.location, "utf8");
677
+ } catch (error) {
678
+ if (error.code === "ENOENT") return void 0;
679
+ throw new Error(`Cannot read the config file ${this.location}: ${error.message}`, { cause: error });
680
+ }
681
+ try {
682
+ return JSON.parse(text);
683
+ } catch (error) {
684
+ throw new Error(`The config file ${this.location} is not valid JSON: ${error.message}`, { cause: error });
685
+ }
686
+ }
687
+ /** Writes a temporary file and renames it, so a crash never leaves half a file. */
688
+ async save(file) {
689
+ await fs.mkdir(path.dirname(this.location), { recursive: true });
690
+ const temporary = `${this.location}.${process.pid}.tmp`;
691
+ try {
692
+ await fs.writeFile(temporary, `${JSON.stringify(file, null, 2)}\n`, "utf8");
693
+ await fs.rename(temporary, this.location);
694
+ } catch (error) {
695
+ await fs.rm(temporary, { force: true });
696
+ throw error;
697
+ }
698
+ }
699
+ };
700
+ // src/adapters/out/log/file-sink.ts
701
+ /**
702
+ * Bridge log file (docs/operations.md#logging): no colours, includes the speech channel.
703
+ * Writes synchronously so nothing is lost on a crash. Log volume is small.
704
+ */
705
+ function fileSink(file, options = {}) {
706
+ const { maxBytes = 10485760, keep = 5 } = options;
707
+ const onError = options.onError ?? ((error) => process.stderr.write(`screenreader-speech-capture: log file disabled: ${error.message}\n`));
708
+ let size = 0;
709
+ let failed = false;
710
+ try {
711
+ fs$1.mkdirSync(path.dirname(file), { recursive: true });
712
+ size = fs$1.existsSync(file) ? fs$1.statSync(file).size : 0;
713
+ } catch (error) {
714
+ failed = true;
715
+ onError(error);
716
+ }
717
+ const rotate = () => {
718
+ fs$1.rmSync(`${file}.${keep}`, { force: true });
719
+ for (let i = keep - 1; i >= 1; i--) if (fs$1.existsSync(`${file}.${i}`)) fs$1.renameSync(`${file}.${i}`, `${file}.${i + 1}`);
720
+ if (keep >= 1) fs$1.renameSync(file, `${file}.1`);
721
+ else fs$1.rmSync(file, { force: true });
722
+ size = 0;
723
+ };
724
+ return {
725
+ colour: false,
726
+ speech: true,
727
+ write(line) {
728
+ if (failed) return;
729
+ const data = `${line}\n`;
730
+ const bytes = Buffer.byteLength(data);
731
+ try {
732
+ if (size > 0 && size + bytes > maxBytes) rotate();
733
+ fs$1.appendFileSync(file, data);
734
+ size += bytes;
735
+ } catch (error) {
736
+ failed = true;
737
+ onError(error);
738
+ }
739
+ }
740
+ };
741
+ }
163
742
  // src/adapters/out/log/log.ts
164
743
  const ESC = "\x1B[";
165
744
  const RESET = `${ESC}0m`;
@@ -209,9 +788,11 @@ function wantsColour(isTTY, env) {
209
788
  return isTTY === true;
210
789
  }
211
790
  /** Console sink on stdout. */
212
- function consoleSink(stream = process.stdout, env = process.env) {
791
+ function consoleSink(options = {}) {
792
+ const { speech = false, stream = process.stdout, env = process.env } = options;
213
793
  return {
214
794
  colour: wantsColour(stream.isTTY, env),
795
+ speech,
215
796
  write: (line) => void stream.write(`${line}\n`)
216
797
  };
217
798
  }
@@ -235,8 +816,9 @@ var BridgeLog = class {
235
816
  const index = this.sinks.indexOf(sink);
236
817
  if (index !== -1) this.sinks.splice(index, 1);
237
818
  }
238
- for(prefix) {
239
- const log = (level) => (message) => this.write(prefix, level, message);
819
+ for(prefix, options = {}) {
820
+ const channel = options.channel ?? "log";
821
+ const log = (level) => (message) => this.write(prefix, level, message, channel);
240
822
  return {
241
823
  error: log("error"),
242
824
  warn: log("warn"),
@@ -246,70 +828,172 @@ var BridgeLog = class {
246
828
  }
247
829
  /** Writes an INFO line whatever the level is (for the startup line). */
248
830
  always(prefix, message) {
249
- this.emit(prefix, "info", message);
831
+ this.emit(prefix, "info", message, "log");
250
832
  }
251
- write(prefix, level, message) {
833
+ write(prefix, level, message, channel) {
252
834
  if (LEVEL_RANK[level] > LEVEL_RANK[this.level]) return;
253
- this.emit(prefix, level, message);
835
+ this.emit(prefix, level, message, channel);
254
836
  }
255
- emit(prefix, level, message) {
837
+ emit(prefix, level, message, channel) {
256
838
  const time = this.now();
257
- for (const sink of this.sinks) for (const line of formatLogLines(prefix, level, time, message, sink.colour)) sink.write(line);
258
- }
259
- };
260
- // src/domain/errors.ts
261
- /** An expected error with a stable code, for example a bad request or a timeout. */
262
- var AppError = class extends Error {
263
- code;
264
- details;
265
- name = "AppError";
266
- constructor(code, message, details) {
267
- super(message);
268
- this.code = code;
269
- this.details = details;
839
+ for (const sink of this.sinks) {
840
+ if (channel === "speech" && !sink.speech) continue;
841
+ for (const line of formatLogLines(prefix, level, time, message, sink.colour)) sink.write(line);
842
+ }
270
843
  }
271
844
  };
272
- /** `INVALID_REQUEST` for one field. */
273
- function invalidField(field, message) {
274
- return new AppError("INVALID_REQUEST", `${field}: ${message}`, { field });
845
+ // src/adapters/out/log/speech-transcript.ts
846
+ /**
847
+ * Writes each recorded speech line to `transcript`, which should be a logger on the `speech`
848
+ * channel, so the text stays off the console by default (docs/operations.md#logging).
849
+ * Returns a function that stops it.
850
+ */
851
+ function logSpeechTranscript(events, transcript) {
852
+ return events.subscribe((event) => {
853
+ if (event.type !== "entry" || event.entry.kind !== "speech") return;
854
+ const { seq, connectionId, text } = event.entry;
855
+ transcript.debug(`#${seq} (connection ${connectionId}) ${text}`);
856
+ });
275
857
  }
276
- // src/domain/config.ts
277
- const LOG_LEVELS = [
278
- "error",
279
- "warn",
280
- "info",
281
- "debug"
282
- ];
283
- const DEFAULT_CONFIG = {
284
- tcp: {
285
- host: "127.0.0.1",
286
- port: 4449,
287
- format: "text-to-socket",
288
- encoding: "windows-1252",
289
- maxLineBytes: 65536
290
- },
291
- http: {
292
- host: "0.0.0.0",
293
- port: 5151
294
- },
295
- playwright: {
296
- enabled: true,
297
- port: 3e3,
298
- version: null
299
- },
300
- mcp: {
301
- enabled: true,
302
- port: 8931,
303
- version: null
304
- },
305
- input: { enabled: true },
306
- buffer: { maxEntries: 1e4 },
307
- log: {
308
- level: "info",
309
- file: null
858
+ // src/adapters/out/memory/in-process-event-bus.ts
859
+ /** Synchronous in-process event bus. A failing listener doesn't stop the others. */
860
+ var InProcessEventBus = class {
861
+ onListenerError;
862
+ listeners = /* @__PURE__ */ new Set();
863
+ constructor(onListenerError = () => {}) {
864
+ this.onListenerError = onListenerError;
310
865
  }
311
- };
312
- const integer = (min, max) => (value) => typeof value === "number" && Number.isInteger(value) && value >= min && value <= max ? void 0 : `must be an integer from ${min} to ${max}`;
866
+ publish(event) {
867
+ for (const listener of [...this.listeners]) try {
868
+ listener(event);
869
+ } catch (error) {
870
+ this.onListenerError(error);
871
+ }
872
+ }
873
+ subscribe(listener) {
874
+ this.listeners.add(listener);
875
+ return () => this.listeners.delete(listener);
876
+ }
877
+ };
878
+ // src/adapters/out/memory/memory-speech-repository.ts
879
+ /**
880
+ * In-memory list of speech entries, oldest first, capped at `maxEntries`: when full, the oldest
881
+ * entry is dropped (docs/speech-capture.md#buffer). `seq` keeps counting across clears.
882
+ */
883
+ var MemorySpeechRepository = class {
884
+ maxEntries;
885
+ entries = [];
886
+ nextSeq = 1;
887
+ /** Highest `seq` dropped because the list was full, since the last clear. */
888
+ droppedUpToSeq = 0;
889
+ constructor(maxEntries) {
890
+ this.maxEntries = maxEntries;
891
+ }
892
+ add(entry) {
893
+ const stored = {
894
+ ...entry,
895
+ seq: this.nextSeq++
896
+ };
897
+ this.entries.push(stored);
898
+ this.trim();
899
+ return stored;
900
+ }
901
+ list(since, limit) {
902
+ const after = this.entries.filter((entry) => entry.seq > since);
903
+ return {
904
+ entries: limit === void 0 ? after : after.slice(0, limit),
905
+ truncated: since < this.droppedUpToSeq,
906
+ hasMore: limit !== void 0 && after.length > limit
907
+ };
908
+ }
909
+ /**
910
+ * Changes the cap (`buffer.maxEntries`). A smaller one drops the oldest entries right away, and
911
+ * they count as truncated like any other dropped entry.
912
+ */
913
+ setMaxEntries(maxEntries) {
914
+ this.maxEntries = maxEntries;
915
+ this.trim();
916
+ }
917
+ clear() {
918
+ this.entries = [];
919
+ this.droppedUpToSeq = 0;
920
+ }
921
+ stats() {
922
+ return {
923
+ size: this.entries.length,
924
+ maxEntries: this.maxEntries,
925
+ firstSeq: this.entries[0]?.seq ?? null,
926
+ lastSeq: this.entries.at(-1)?.seq ?? null
927
+ };
928
+ }
929
+ trim() {
930
+ while (this.entries.length > this.maxEntries) this.droppedUpToSeq = this.entries.shift().seq;
931
+ }
932
+ };
933
+ // src/adapters/out/paths.ts
934
+ const APP = "screenreader-speech-capture";
935
+ /**
936
+ * Default bridge log file: `%LOCALAPPDATA%\screenreader-speech-capture\logs\bridge.log` on
937
+ * Windows, `$XDG_STATE_HOME` (or `~/.local/state`) elsewhere, for development.
938
+ */
939
+ function defaultLogFile(platform = process.platform, env = process.env, home = os.homedir()) {
940
+ if (platform === "win32") {
941
+ const base = env.LOCALAPPDATA ?? path.win32.join(home, "AppData", "Local");
942
+ return path.win32.join(base, APP, "logs", "bridge.log");
943
+ }
944
+ const base = env.XDG_STATE_HOME ?? path.posix.join(home, ".local", "state");
945
+ return path.posix.join(base, APP, "logs", "bridge.log");
946
+ }
947
+ /**
948
+ * Default config file: `%APPDATA%\screenreader-speech-capture\config.json` on Windows,
949
+ * `$XDG_CONFIG_HOME` (or `~/.config`) elsewhere, for development.
950
+ */
951
+ function defaultConfigFile(platform = process.platform, env = process.env, home = os.homedir()) {
952
+ if (platform === "win32") {
953
+ const base = env.APPDATA ?? path.win32.join(home, "AppData", "Roaming");
954
+ return path.win32.join(base, APP, "config.json");
955
+ }
956
+ const base = env.XDG_CONFIG_HOME ?? path.posix.join(home, ".config");
957
+ return path.posix.join(base, APP, "config.json");
958
+ }
959
+ // src/domain/config.ts
960
+ const LOG_LEVELS = [
961
+ "error",
962
+ "warn",
963
+ "info",
964
+ "debug"
965
+ ];
966
+ const DEFAULT_CONFIG = {
967
+ tcp: {
968
+ host: "127.0.0.1",
969
+ port: 4449,
970
+ format: "text-to-socket",
971
+ encoding: "windows-1252",
972
+ maxLineBytes: 65536
973
+ },
974
+ http: {
975
+ host: "0.0.0.0",
976
+ port: 5151
977
+ },
978
+ playwright: {
979
+ enabled: true,
980
+ port: 3e3,
981
+ version: null
982
+ },
983
+ mcp: {
984
+ enabled: true,
985
+ port: 8931,
986
+ version: null
987
+ },
988
+ input: { enabled: true },
989
+ buffer: { maxEntries: 1e4 },
990
+ log: {
991
+ level: "info",
992
+ file: null,
993
+ consoleSpeech: false
994
+ }
995
+ };
996
+ const integer = (min, max) => (value) => typeof value === "number" && Number.isInteger(value) && value >= min && value <= max ? void 0 : `must be an integer from ${min} to ${max}`;
313
997
  const port = integer(0, 65535);
314
998
  const boolean = (value) => typeof value === "boolean" ? void 0 : "must be true or false";
315
999
  const nonEmptyString = (value) => typeof value === "string" && value.trim() !== "" ? void 0 : "must be a non-empty string";
@@ -350,7 +1034,8 @@ const SCHEMA = {
350
1034
  buffer: { maxEntries: integer(1, 1e6) },
351
1035
  log: {
352
1036
  level: oneOf(LOG_LEVELS),
353
- file: nullableString
1037
+ file: nullableString,
1038
+ consoleSpeech: boolean
354
1039
  }
355
1040
  };
356
1041
  function isPlainObject(value) {
@@ -382,204 +1067,184 @@ function mergeConfig(base, patch) {
382
1067
  }
383
1068
  return result;
384
1069
  }
385
- // src/adapters/out/clock/system-clock.ts
386
- var SystemClock = class {
387
- now() {
388
- return /* @__PURE__ */ new Date();
389
- }
390
- monotonicMs() {
391
- return performance.now();
392
- }
393
- setTimeout(callback, ms) {
394
- return setTimeout(callback, ms);
395
- }
396
- clearTimeout(handle) {
397
- clearTimeout(handle);
398
- }
399
- };
400
- // src/adapters/out/clock/ulid-generator.ts
401
- /** ULIDs, strictly increasing even within the same millisecond. */
402
- var UlidGenerator = class {
403
- ulid = monotonicFactory();
404
- next() {
405
- return this.ulid();
406
- }
407
- };
408
- // src/adapters/out/memory/in-process-event-bus.ts
409
- /** Synchronous in-process event bus. A failing listener doesn't stop the others. */
410
- var InProcessEventBus = class {
411
- onListenerError;
412
- listeners = /* @__PURE__ */ new Set();
413
- constructor(onListenerError = () => {}) {
414
- this.onListenerError = onListenerError;
415
- }
416
- publish(event) {
417
- for (const listener of [...this.listeners]) try {
418
- listener(event);
419
- } catch (error) {
420
- this.onListenerError(error);
421
- }
422
- }
423
- subscribe(listener) {
424
- this.listeners.add(listener);
425
- return () => this.listeners.delete(listener);
426
- }
427
- };
428
- // src/adapters/out/memory/ring-buffer-repository.ts
1070
+ /** Names of the sections whose values differ between `a` and `b`. */
1071
+ function changedSections(a, b) {
1072
+ return Object.keys(a).filter((section) => JSON.stringify(a[section]) !== JSON.stringify(b[section]));
1073
+ }
1074
+ /** The settings in a (partial) configuration, as `section.key` → value. */
1075
+ function configFields(config) {
1076
+ const fields = /* @__PURE__ */ new Map();
1077
+ for (const [section, values] of Object.entries(config)) for (const [key, value] of Object.entries(values ?? {})) if (value !== void 0) fields.set(`${section}.${key}`, value);
1078
+ return fields;
1079
+ }
429
1080
  /**
430
- * In-memory ring buffer (docs/speech-capture.md#buffer). When it is full, the oldest entries
431
- * are dropped. `seq` keeps counting across clears.
1081
+ * Checks a partial configuration (a request body, the config file) like `mergeConfig` and
1082
+ * returns it without `undefined` values. Throws `INVALID_REQUEST` naming the field.
432
1083
  */
433
- var RingBufferRepository = class {
434
- maxEntries;
435
- /** Entries in `seq` order. Indexes before `start` are dropped and compacted away later. */
436
- entries = [];
437
- start = 0;
438
- nextSeq = 1;
439
- /** Highest `seq` dropped because the buffer was full, since the last clear. */
440
- droppedUpToSeq = 0;
441
- constructor(maxEntries) {
442
- this.maxEntries = maxEntries;
443
- }
444
- add(entry) {
445
- const stored = {
446
- ...entry,
447
- seq: this.nextSeq++
448
- };
449
- this.entries.push(stored);
450
- this.dropOverflow();
451
- return stored;
1084
+ function validatePatch(patch) {
1085
+ if (patch === void 0 || patch === null) return {};
1086
+ mergeConfig(DEFAULT_CONFIG, patch);
1087
+ return fromFields(configFields(patch));
1088
+ }
1089
+ /** `patch` on top of `base`, both partial configurations (for the config file's content). */
1090
+ function mergePatch(base, patch) {
1091
+ return fromFields(new Map([...configFields(base), ...configFields(patch)]));
1092
+ }
1093
+ function fromFields(fields) {
1094
+ const result = {};
1095
+ for (const [field, value] of fields) {
1096
+ const [section, key] = field.split(".");
1097
+ (result[section] ??= {})[key] = value;
452
1098
  }
453
- list(since, limit) {
454
- const from = this.indexAfter(since);
455
- return {
456
- entries: this.entries.slice(from, from + limit),
457
- truncated: since < this.droppedUpToSeq
458
- };
1099
+ return result;
1100
+ }
1101
+ /** The settings whose values differ between `a` and `b`. */
1102
+ function changedFields(a, b) {
1103
+ const before = configFields(a);
1104
+ return [...configFields(b)].filter(([field, to]) => before.get(field) !== to).map(([field, to]) => ({
1105
+ field,
1106
+ from: before.get(field),
1107
+ to
1108
+ }));
1109
+ }
1110
+ /** The settings that `overrides` (flags, environment) sets although the config file has them. */
1111
+ function overriddenFields(file, overrides) {
1112
+ const inFile = configFields(file);
1113
+ return [...configFields(overrides)].filter(([field]) => inFile.has(field)).map(([field, override]) => ({
1114
+ field,
1115
+ file: inFile.get(field),
1116
+ override
1117
+ }));
1118
+ }
1119
+ // src/application/services/config-service.ts
1120
+ const show$1 = (value) => JSON.stringify(value);
1121
+ /**
1122
+ * The configuration (`GET` / `PUT /api/v1/config`). An update applies to the running bridge
1123
+ * through the change listeners and is saved to the config file (docs/configuration.md).
1124
+ */
1125
+ var ConfigService = class {
1126
+ deps;
1127
+ active;
1128
+ file;
1129
+ listeners = [];
1130
+ queue = Promise.resolve();
1131
+ constructor(deps) {
1132
+ this.deps = deps;
1133
+ this.active = deps.active;
1134
+ this.file = deps.file;
459
1135
  }
460
- clear() {
461
- this.entries = [];
462
- this.start = 0;
463
- this.droppedUpToSeq = 0;
1136
+ get() {
1137
+ return this.active;
464
1138
  }
465
- resize(maxEntries) {
466
- this.maxEntries = maxEntries;
467
- this.dropOverflow();
1139
+ onChange(listener) {
1140
+ this.listeners.push(listener);
468
1141
  }
469
- stats() {
470
- const size = this.entries.length - this.start;
471
- return {
472
- size,
473
- maxEntries: this.maxEntries,
474
- firstSeq: size > 0 ? this.entries[this.start].seq : null,
475
- lastSeq: size > 0 ? this.entries[this.entries.length - 1].seq : null
476
- };
1142
+ update(patch) {
1143
+ const result = this.queue.then(() => this.apply(patch));
1144
+ this.queue = result.catch(() => void 0);
1145
+ return result;
477
1146
  }
478
- dropOverflow() {
479
- while (this.entries.length - this.start > this.maxEntries) {
480
- this.droppedUpToSeq = this.entries[this.start].seq;
481
- this.start++;
1147
+ async apply(patch) {
1148
+ const changes = validatePatch(patch);
1149
+ const previous = this.active;
1150
+ const next = mergeConfig(previous, changes);
1151
+ const changed = changedFields(previous, next);
1152
+ const saved = configFields(this.file);
1153
+ const fileChanged = [...configFields(changes)].some(([field, value]) => saved.get(field) !== value);
1154
+ if (changed.length === 0 && !fileChanged) return previous;
1155
+ const applied = [];
1156
+ try {
1157
+ if (changed.length > 0) for (const listener of this.listeners) {
1158
+ await listener(next, previous);
1159
+ applied.push(listener);
1160
+ }
1161
+ const file = mergePatch(this.file, changes);
1162
+ if (fileChanged) await this.deps.store.save(file);
1163
+ this.file = file;
1164
+ } catch (error) {
1165
+ await this.undo(applied, previous, next);
1166
+ throw error;
482
1167
  }
483
- if (this.start > 0 && this.start >= this.entries.length - this.start) {
484
- this.entries = this.entries.slice(this.start);
485
- this.start = 0;
1168
+ this.active = next;
1169
+ this.log(changes, changed);
1170
+ return next;
1171
+ }
1172
+ async undo(applied, previous, next) {
1173
+ for (const listener of applied.reverse()) try {
1174
+ await listener(previous, next);
1175
+ } catch (error) {
1176
+ this.deps.logger.error(`could not undo a configuration change: ${String(error)}`);
486
1177
  }
487
1178
  }
488
- /** Index of the first live entry with `seq > since` (binary search, entries are sorted). */
489
- indexAfter(since) {
490
- let low = this.start;
491
- let high = this.entries.length;
492
- while (low < high) {
493
- const mid = low + high >>> 1;
494
- if (this.entries[mid].seq <= since) low = mid + 1;
495
- else high = mid;
1179
+ log(changes, changed) {
1180
+ const { logger, pinned, store } = this.deps;
1181
+ for (const { field, from, to } of changed) logger.info(`${field}: ${show$1(from)} → ${show$1(to)}`);
1182
+ for (const field of configFields(changes).keys()) {
1183
+ const source = pinned?.get(field);
1184
+ if (source !== void 0) logger.warn(`${field}: saved to ${store.location}, but ${source} overrides it on the next start`);
496
1185
  }
497
- return low;
498
1186
  }
499
1187
  };
500
- // src/application/services/record-speech-service.ts
1188
+ // src/application/ports/in/query-speech.ts
1189
+ /** Page size of `list`: the default and the most a caller may ask for. */
1190
+ const LIST_LIMIT = {
1191
+ default: 1e3,
1192
+ max: 1e4
1193
+ };
1194
+ // src/application/services/int-option.ts
501
1195
  /**
502
- * Turns lines from the socket voice into speech entries (docs/speech-capture.md#from-line-to-speech-entry)
503
- * and keeps track of the listener and its open connections for the status.
1196
+ * A numeric use-case option: `fallback` if it is missing, otherwise checked to be an integer
1197
+ * from `min` to `max` (`INVALID_REQUEST` for `field` if not).
504
1198
  */
505
- var RecordSpeechService = class {
1199
+ function intOption(field, value, { fallback, min, max }) {
1200
+ if (value === void 0) return fallback;
1201
+ if (!Number.isInteger(value) || value < min || value > max) throw invalidField(field, `must be an integer from ${min} to ${max}`);
1202
+ return value;
1203
+ }
1204
+ // src/application/services/speech-service.ts
1205
+ const MAX_MARKER_LENGTH = 1e3;
1206
+ /**
1207
+ * Recording, reading, clearing and marking speech: every entry gets its `seq` from the repository
1208
+ * and `receivedAt` from the clock, and is published on the event bus
1209
+ * (docs/speech-capture.md#from-line-to-speech-entry).
1210
+ */
1211
+ var SpeechService = class {
506
1212
  deps;
507
- open = /* @__PURE__ */ new Map();
508
- nextConnectionId = 1;
509
- listener = null;
510
1213
  constructor(deps) {
511
1214
  this.deps = deps;
512
1215
  }
513
- listenerStarted(info) {
514
- this.listener = {
515
- listening: true,
516
- ...info
517
- };
518
- this.deps.logger.info(`listening on ${info.host}:${info.port}, encoding ${info.encoding}`);
519
- }
520
- listenerStopped() {
521
- if (this.listener) this.listener = {
522
- ...this.listener,
523
- listening: false
524
- };
525
- this.deps.logger.info("stopped listening");
526
- }
527
- connectionOpened() {
528
- const id = this.nextConnectionId++;
529
- this.open.set(id, {
530
- id,
531
- voice: null,
532
- connectedAt: this.deps.clock.now()
533
- });
534
- this.deps.logger.info(`connection ${id} opened`);
535
- return id;
536
- }
537
- setVoice(connectionId, voice) {
538
- const connection = this.open.get(connectionId);
539
- if (connection) connection.voice = voice;
540
- this.deps.logger.info(`connection ${connectionId}: voice=${voice}`);
541
- }
542
- record(connectionId, text) {
543
- const { repository, events, clock, ids, logger } = this.deps;
544
- const entry = repository.add({
545
- id: ids.next(),
1216
+ record({ text, voice, connectionId }) {
1217
+ this.add({
546
1218
  kind: "speech",
547
1219
  text,
548
- receivedAt: clock.now(),
549
- monotonicMs: clock.monotonicMs(),
550
1220
  source: "tcp",
551
- voice: this.open.get(connectionId)?.voice ?? null,
1221
+ voice,
552
1222
  connectionId
553
1223
  });
554
- logger.debug(`#${entry.seq} (connection ${connectionId}) ${text}`);
555
- events.publish({
556
- type: "entry",
557
- entry
558
- });
559
- }
560
- connectionClosed(connectionId) {
561
- this.open.delete(connectionId);
562
- this.deps.logger.info(`connection ${connectionId} closed`);
563
- }
564
- /** The listener, or `null` before it was started for the first time. */
565
- listenerState() {
566
- return this.listener && { ...this.listener };
567
- }
568
- /** Open connections, oldest first. */
569
- connections() {
570
- return [...this.open.values()].map((connection) => ({ ...connection }));
571
1224
  }
572
- };
573
- // src/application/services/speech-service.ts
574
- const MAX_MARKER_LENGTH = 1e3;
575
- /** Reading, clearing and marking the recorded speech. */
576
- var SpeechService = class {
577
- deps;
578
- constructor(deps) {
579
- this.deps = deps;
1225
+ list(options = {}) {
1226
+ const since = intOption("since", options.since, {
1227
+ fallback: 0,
1228
+ min: 0,
1229
+ max: Number.MAX_SAFE_INTEGER
1230
+ });
1231
+ const limit = intOption("limit", options.limit, {
1232
+ fallback: LIST_LIMIT.default,
1233
+ min: 1,
1234
+ max: LIST_LIMIT.max
1235
+ });
1236
+ return this.deps.repository.list(since, limit);
580
1237
  }
581
- list(options) {
582
- return this.deps.repository.list(options.since, options.limit);
1238
+ watch(since, listener) {
1239
+ if (since !== null) {
1240
+ const { entries, truncated } = this.deps.repository.list(since);
1241
+ if (truncated) listener({ type: "truncated" });
1242
+ for (const entry of entries) listener({
1243
+ type: "entry",
1244
+ entry
1245
+ });
1246
+ }
1247
+ return this.deps.events.subscribe(listener);
583
1248
  }
584
1249
  clear() {
585
1250
  this.deps.repository.clear();
@@ -589,104 +1254,682 @@ var SpeechService = class {
589
1254
  const text = label.trim();
590
1255
  if (text === "") throw invalidField("label", "must not be empty");
591
1256
  if (text.length > 1e3) throw invalidField("label", `must be at most ${MAX_MARKER_LENGTH} characters`);
592
- const { repository, events, clock, ids } = this.deps;
593
- const entry = repository.add({
594
- id: ids.next(),
1257
+ return this.add({
595
1258
  kind: "marker",
596
1259
  text,
597
- receivedAt: clock.now(),
598
- monotonicMs: clock.monotonicMs(),
599
1260
  source: "api",
600
1261
  voice: null,
601
1262
  connectionId: null
602
1263
  });
603
- events.publish({
1264
+ }
1265
+ add(entry) {
1266
+ const stored = this.deps.repository.add({
1267
+ ...entry,
1268
+ receivedAt: this.deps.clock.now()
1269
+ });
1270
+ this.deps.events.publish({
604
1271
  type: "entry",
605
- entry
1272
+ entry: stored
606
1273
  });
607
- return entry;
1274
+ return stored;
1275
+ }
1276
+ };
1277
+ // src/application/services/status-service.ts
1278
+ /** `GET /api/v1/status`. The composition root moves the state from `starting` to `ready`. */
1279
+ var StatusService = class {
1280
+ deps;
1281
+ state = "starting";
1282
+ constructor(deps) {
1283
+ this.deps = deps;
1284
+ }
1285
+ setState(state) {
1286
+ this.state = state;
1287
+ }
1288
+ status() {
1289
+ const { capture, repository, config, version, apiVersion } = this.deps;
1290
+ const { listener, connections } = capture.captureStatus();
1291
+ const { tcp, input } = config();
1292
+ return {
1293
+ bridge: {
1294
+ version,
1295
+ apiVersion,
1296
+ state: this.state
1297
+ },
1298
+ tcp: {
1299
+ listening: listener?.listening ?? false,
1300
+ host: listener?.host ?? tcp.host,
1301
+ port: listener?.port ?? tcp.port,
1302
+ encoding: listener?.encoding ?? tcp.encoding,
1303
+ connections
1304
+ },
1305
+ buffer: repository.stats(),
1306
+ input: { enabled: input.enabled }
1307
+ };
1308
+ }
1309
+ };
1310
+ // src/domain/text-match.ts
1311
+ /** Lower case, whitespace runs collapsed to one space, trimmed. */
1312
+ function normalizeText(text) {
1313
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
1314
+ }
1315
+ /**
1316
+ * Builds a matcher for `wait`. Exactly one of `contains` and `regex` is required.
1317
+ * Only `kind: "speech"` entries match, never markers.
1318
+ */
1319
+ function createSpeechMatcher(options) {
1320
+ const { contains, regex, normalize = false } = options;
1321
+ if (contains === void 0 && regex === void 0) throw new AppError("INVALID_REQUEST", "One of \"contains\" and \"regex\" is required", { field: "contains" });
1322
+ if (contains !== void 0 && regex !== void 0) throw new AppError("INVALID_REQUEST", "Use either \"contains\" or \"regex\", not both", { field: "regex" });
1323
+ const prepare = normalize ? normalizeText : (text) => text;
1324
+ let test;
1325
+ if (regex !== void 0) {
1326
+ let pattern;
1327
+ try {
1328
+ pattern = new RegExp(regex, normalize ? "iu" : "u");
1329
+ } catch (error) {
1330
+ throw invalidField("regex", error.message);
1331
+ }
1332
+ test = (text) => pattern.test(prepare(text));
1333
+ } else {
1334
+ const needle = prepare(contains ?? "");
1335
+ if (needle === "") throw invalidField("contains", "must not be empty");
1336
+ test = (text) => prepare(text).includes(needle);
1337
+ }
1338
+ return (entry) => entry.kind === "speech" && test(entry.text);
1339
+ }
1340
+ // src/application/ports/in/wait-for-speech.ts
1341
+ /** How long `wait` waits: the default and the most a caller may ask for. */
1342
+ const WAIT_TIMEOUT_MS = {
1343
+ default: 5e3,
1344
+ max: 3e5
1345
+ };
1346
+ // src/application/services/wait-for-speech-service.ts
1347
+ function abortReason(signal) {
1348
+ const reason = signal.reason;
1349
+ return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The wait was aborted");
1350
+ }
1351
+ const unavailable = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
1352
+ /**
1353
+ * Long-poll for a speech entry (`GET /api/v1/speech/wait`): looks in the buffer first, then
1354
+ * waits for new entries on the event bus.
1355
+ */
1356
+ var WaitForSpeechService = class {
1357
+ deps;
1358
+ pending = /* @__PURE__ */ new Set();
1359
+ closed = false;
1360
+ constructor(deps) {
1361
+ this.deps = deps;
1362
+ }
1363
+ async wait(options) {
1364
+ if (this.closed) throw unavailable();
1365
+ const { signal } = options;
1366
+ const since = intOption("since", options.since, {
1367
+ fallback: 0,
1368
+ min: 0,
1369
+ max: Number.MAX_SAFE_INTEGER
1370
+ });
1371
+ const timeoutMs = intOption("timeoutMs", options.timeoutMs, {
1372
+ fallback: WAIT_TIMEOUT_MS.default,
1373
+ min: 0,
1374
+ max: WAIT_TIMEOUT_MS.max
1375
+ });
1376
+ const matches = createSpeechMatcher(options);
1377
+ if (signal?.aborted) throw abortReason(signal);
1378
+ const seen = [...this.deps.repository.list(since).entries];
1379
+ const found = seen.find(matches);
1380
+ if (found) return {
1381
+ status: "matched",
1382
+ entry: found
1383
+ };
1384
+ return new Promise((resolve, reject) => {
1385
+ const finish = () => {
1386
+ unsubscribe();
1387
+ clearTimeout(timer);
1388
+ signal?.removeEventListener("abort", onAbort);
1389
+ this.pending.delete(fail);
1390
+ };
1391
+ const fail = (error) => {
1392
+ finish();
1393
+ reject(error);
1394
+ };
1395
+ const onAbort = () => fail(abortReason(signal));
1396
+ const unsubscribe = this.deps.events.subscribe((event) => {
1397
+ if (event.type !== "entry" || event.entry.seq <= since) return;
1398
+ seen.push(event.entry);
1399
+ if (!matches(event.entry)) return;
1400
+ finish();
1401
+ resolve({
1402
+ status: "matched",
1403
+ entry: event.entry
1404
+ });
1405
+ });
1406
+ const timer = setTimeout(() => {
1407
+ finish();
1408
+ resolve({
1409
+ status: "timeout",
1410
+ seen
1411
+ });
1412
+ }, timeoutMs);
1413
+ signal?.addEventListener("abort", onAbort, { once: true });
1414
+ this.pending.add(fail);
1415
+ });
1416
+ }
1417
+ /**
1418
+ * Rejects all pending waits, and every later one, with `SERVICE_UNAVAILABLE`. Lifecycle, so
1419
+ * not part of the `WaitForSpeech` port: only the composition root calls it.
1420
+ */
1421
+ shutdown() {
1422
+ this.closed = true;
1423
+ for (const fail of [...this.pending]) fail(unavailable());
608
1424
  }
609
1425
  };
610
1426
  // src/main.ts
1427
+ /** A setting from flags, the environment or the config file is invalid. Nothing was started. */
1428
+ var ConfigError = class extends Error {
1429
+ name = "ConfigError";
1430
+ };
1431
+ function startupMessage(config, version, configFile, file) {
1432
+ const { level, consoleSpeech } = config.log;
1433
+ let message = `starting, version ${version}, config ${configFile}, log level ${level}`;
1434
+ if (file !== null) message += `, log file ${file}`;
1435
+ if (level !== "debug") return `${message} (speech text is logged at debug)`;
1436
+ if (consoleSpeech) return `${message} (speech text also on the console)`;
1437
+ return file === null ? `${message} (speech text is not shown: no log file)` : `${message} (speech text goes to the log file only, not to the console)`;
1438
+ }
1439
+ function defaultSinks(config) {
1440
+ const file = config.log.file ?? defaultLogFile();
1441
+ return {
1442
+ sinks: [consoleSink({ speech: config.log.consoleSpeech }), fileSink(file)],
1443
+ file
1444
+ };
1445
+ }
1446
+ /** `patch` checked, with an error that says where the bad setting came from. */
1447
+ function checked(patch, origin) {
1448
+ try {
1449
+ return validatePatch(patch);
1450
+ } catch (error) {
1451
+ throw new ConfigError(`${origin(error instanceof AppError ? error.details?.field : void 0)}: ${error.message}`, { cause: error });
1452
+ }
1453
+ }
1454
+ /** Defaults, then the config file, then flags and environment variables. */
1455
+ async function loadConfig(store, overridesPatch, sourceOf) {
1456
+ let saved;
1457
+ try {
1458
+ saved = await store.load();
1459
+ } catch (error) {
1460
+ throw new ConfigError(error.message, { cause: error });
1461
+ }
1462
+ const file = checked(saved, () => `Invalid setting in the config file ${store.location}`);
1463
+ const overrides = checked(overridesPatch, (field) => field?.includes(".") ? `Invalid ${sourceOf(field)}` : "Invalid setting");
1464
+ return {
1465
+ config: mergeConfig(mergeConfig(DEFAULT_CONFIG, file), overrides),
1466
+ file,
1467
+ overrides
1468
+ };
1469
+ }
1470
+ /** `INVALID_REQUEST` naming the setting, for a listener that can't use a new address. */
1471
+ function listenFailed(section, error) {
1472
+ if (!(error instanceof ListenError)) return error;
1473
+ const field = error.code === "EADDRNOTAVAIL" ? `${section}.host` : `${section}.port`;
1474
+ return new AppError("INVALID_REQUEST", `${field}: ${error.message}`, { field });
1475
+ }
1476
+ const show = (value) => JSON.stringify(value);
1477
+ /**
1478
+ * Starts the bridge. An invalid setting rejects with a `ConfigError` before anything starts.
1479
+ * Any other failure to start is written to the bridge log before the promise rejects, and so is
1480
+ * a failure to stop.
1481
+ */
611
1482
  async function startBridge(options) {
612
- const { config, version } = options;
613
- const log = options.log ?? new BridgeLog(config.log.level, [consoleSink()]);
1483
+ const { version } = options;
1484
+ const store = options.configStore ?? new FsConfigStore(options.configFile ?? defaultConfigFile());
1485
+ const sourceOf = (field) => options.overrideSources?.get(field) ?? "a flag or environment variable";
1486
+ const { config, file: savedFile, overrides } = await loadConfig(store, options.overrides, sourceOf);
1487
+ const ownSinks = options.sinks === void 0;
1488
+ const initial = ownSinks ? defaultSinks(config) : {
1489
+ sinks: options.sinks ?? [],
1490
+ file: null
1491
+ };
1492
+ let sinks = initial.sinks;
1493
+ const log = new BridgeLog(config.log.level, sinks);
614
1494
  const bridgeLogger = log.for("bridge");
615
- log.always("bridge", `starting, version ${version}, log level ${config.log.level}` + (config.log.level === "debug" ? "" : " (set SR_SPEECH_LOG_LEVEL=debug to see the speech)"));
1495
+ const configLogger = log.for("config");
1496
+ log.always("bridge", startupMessage(config, version, store.location, initial.file));
1497
+ for (const { field, file: saved, override } of overriddenFields(savedFile, overrides)) configLogger.warn(`${field}: the config file sets ${show(saved)}, but ${sourceOf(field)} sets ${show(override)}, which wins`);
616
1498
  const clock = options.clock ?? new SystemClock();
617
- const ids = new UlidGenerator();
618
- const repository = new RingBufferRepository(config.buffer.maxEntries);
1499
+ const repository = new MemorySpeechRepository(config.buffer.maxEntries);
619
1500
  const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
620
- const recorder = new RecordSpeechService({
1501
+ logSpeechTranscript(events, log.for("speech-capture", { channel: "speech" }));
1502
+ const speech = new SpeechService({
621
1503
  repository,
622
1504
  events,
623
- clock,
624
- ids,
625
- logger: log.for("speech-capture")
1505
+ clock
626
1506
  });
627
- const speech = new SpeechService({
1507
+ const waits = new WaitForSpeechService({
628
1508
  repository,
629
- events,
630
- clock,
631
- ids
1509
+ events
1510
+ });
1511
+ const configService = new ConfigService({
1512
+ store,
1513
+ logger: configLogger,
1514
+ active: config,
1515
+ file: savedFile,
1516
+ pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
1517
+ });
1518
+ const tcp = new TcpListener(speech, clock, log.for("speech-capture"));
1519
+ const status = new StatusService({
1520
+ capture: tcp,
1521
+ repository,
1522
+ config: () => configService.get(),
1523
+ version,
1524
+ apiVersion: "1.0"
1525
+ });
1526
+ const http = new HttpServer({
1527
+ speech,
1528
+ waits,
1529
+ status,
1530
+ config: configService,
1531
+ logger: log.for("http-api"),
1532
+ ...options.ssePingMs === void 0 ? {} : { pingMs: options.ssePingMs }
1533
+ });
1534
+ const failed = (error) => bridgeLogger.error(error instanceof ListenError ? error.message : String(error));
1535
+ let tcpPort;
1536
+ let httpPort;
1537
+ try {
1538
+ tcpPort = await tcp.start(config.tcp);
1539
+ } catch (error) {
1540
+ failed(error);
1541
+ throw error;
1542
+ }
1543
+ try {
1544
+ httpPort = await http.start(config.http);
1545
+ } catch (error) {
1546
+ failed(error);
1547
+ await tcp.stop();
1548
+ throw error;
1549
+ }
1550
+ configService.onChange(async (next, previous) => {
1551
+ if (!changedSections(previous, next).includes("tcp")) return;
1552
+ const before = {
1553
+ ...previous.tcp,
1554
+ port: tcpPort
1555
+ };
1556
+ await tcp.stop();
1557
+ try {
1558
+ tcpPort = await tcp.start(next.tcp);
1559
+ } catch (error) {
1560
+ tcpPort = await tcp.start(before);
1561
+ throw listenFailed("tcp", error);
1562
+ }
632
1563
  });
633
- const tcp = new TcpListener(recorder, log.for("speech-capture"));
634
- const tcpPort = await tcp.start(config.tcp);
1564
+ configService.onChange(async (next, previous) => {
1565
+ if (!changedSections(previous, next).includes("http")) return;
1566
+ try {
1567
+ httpPort = await http.restart(next.http);
1568
+ } catch (error) {
1569
+ throw listenFailed("http", error);
1570
+ }
1571
+ });
1572
+ configService.onChange((next) => repository.setMaxEntries(next.buffer.maxEntries));
1573
+ configService.onChange((next, previous) => {
1574
+ log.setLevel(next.log.level);
1575
+ if (!ownSinks || next.log.file === previous.log.file && next.log.consoleSpeech === previous.log.consoleSpeech) return;
1576
+ for (const sink of sinks) log.removeSink(sink);
1577
+ sinks = defaultSinks(next).sinks;
1578
+ for (const sink of sinks) log.addSink(sink);
1579
+ });
1580
+ status.setState("ready");
635
1581
  bridgeLogger.info("ready");
1582
+ let stopping;
636
1583
  return {
637
- log,
638
- tcpPort,
1584
+ get tcpPort() {
1585
+ return tcpPort;
1586
+ },
1587
+ get httpPort() {
1588
+ return httpPort;
1589
+ },
639
1590
  speech,
640
- recorder,
641
- async stop() {
642
- bridgeLogger.info("stopping");
643
- await tcp.stop();
644
- bridgeLogger.info("stopped");
1591
+ capture: tcp,
1592
+ log: bridgeLogger,
1593
+ stop(reason) {
1594
+ stopping ??= shutdown(reason);
1595
+ return stopping;
645
1596
  }
646
1597
  };
1598
+ async function shutdown(reason) {
1599
+ status.setState("stopping");
1600
+ bridgeLogger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
1601
+ waits.shutdown();
1602
+ const errors = [];
1603
+ for (const listener of [http, tcp]) try {
1604
+ await listener.stop();
1605
+ } catch (error) {
1606
+ bridgeLogger.error(`shutdown failed: ${String(error)}`);
1607
+ errors.push(error);
1608
+ }
1609
+ if (errors.length === 1) throw errors[0];
1610
+ if (errors.length > 1) throw new AggregateError(errors, "shutdown failed");
1611
+ bridgeLogger.info("stopped");
1612
+ }
647
1613
  }
648
- // src/cli.ts
649
- function configFromEnv(env) {
650
- const port = env.SR_SPEECH_TCP_PORT;
651
- return mergeConfig(DEFAULT_CONFIG, {
652
- tcp: {
653
- port: port === void 0 ? void 0 : Number(port),
654
- encoding: env.SR_SPEECH_TCP_ENCODING
655
- },
656
- log: { level: env.SR_SPEECH_LOG_LEVEL }
1614
+ // src/adapters/in/cli/lifecycle.ts
1615
+ const SHUTDOWN_TIMEOUT_MS = 1e4;
1616
+ /** Ctrl+C, `kill`, closing the console window, and Ctrl+Break on Windows. */
1617
+ function shutdownSignals(platform) {
1618
+ const signals = [
1619
+ "SIGINT",
1620
+ "SIGTERM",
1621
+ "SIGHUP"
1622
+ ];
1623
+ if (platform === "win32") signals.push("SIGBREAK");
1624
+ return signals;
1625
+ }
1626
+ /** Resolves once everything written to `stream` so far is handed to the OS. */
1627
+ function drain(stream) {
1628
+ return new Promise((resolve) => stream.write("", () => resolve()));
1629
+ }
1630
+ /** Default `flush`: drains stdout and stderr. The log file is written synchronously. */
1631
+ async function flushConsole() {
1632
+ await Promise.all([drain(process.stdout), drain(process.stderr)]);
1633
+ }
1634
+ function describeError(error) {
1635
+ return error instanceof Error ? error.stack ?? String(error) : String(error);
1636
+ }
1637
+ /**
1638
+ * Starts the bridge with `start`, then stops it gracefully and exits the process
1639
+ * (docs/operations.md#shutdown):
1640
+ *
1641
+ * - on a shutdown signal. A second signal exits at once.
1642
+ * - on an uncaught exception or unhandled rejection, which is logged with its stack. Exit code 1.
1643
+ * - if the shutdown takes longer than `timeoutMs`, it exits anyway with code 1.
1644
+ *
1645
+ * The exit code is 0 unless something failed. Console output is flushed before exiting.
1646
+ *
1647
+ * The signal handlers are installed before `start`, so a signal that arrives while the bridge
1648
+ * starts is not fatal: the bridge stops as soon as it has started. Resolves once started; rejects
1649
+ * like `start`.
1650
+ */
1651
+ async function runUntilStopped(start, proc, options = {}) {
1652
+ const { timeoutMs = SHUTDOWN_TIMEOUT_MS, flush = flushConsole } = options;
1653
+ let bridge = void 0;
1654
+ /** A signal that arrived before the bridge had started. */
1655
+ let early;
1656
+ let stopping = false;
1657
+ let exiting = false;
1658
+ let exitCode = 0;
1659
+ let watchdog;
1660
+ const exit = (code) => {
1661
+ if (exiting) return proc.exit(code);
1662
+ exiting = true;
1663
+ flush().catch(() => void 0).then(() => {
1664
+ clearTimeout(watchdog);
1665
+ proc.exit(code);
1666
+ });
1667
+ };
1668
+ const shutdown = (running, reason) => {
1669
+ stopping = true;
1670
+ watchdog = setTimeout(() => {
1671
+ running.log.error(`shutdown did not finish within ${timeoutMs / 1e3} s, exiting`);
1672
+ exiting = true;
1673
+ proc.exit(1);
1674
+ }, timeoutMs).unref();
1675
+ running.stop(reason).then(() => exit(exitCode), () => exit(1));
1676
+ };
1677
+ for (const signal of shutdownSignals(proc.platform)) proc.on(signal, () => {
1678
+ if (bridge === void 0) {
1679
+ if (early === void 0) early = signal;
1680
+ else exit(1);
1681
+ return;
1682
+ }
1683
+ if (!stopping) return shutdown(bridge, signal);
1684
+ bridge.log.warn(`${signal} again, exiting without waiting`);
1685
+ exit(1);
657
1686
  });
1687
+ bridge = await start();
1688
+ const running = bridge;
1689
+ const crash = (what) => (error) => {
1690
+ running.log.error(`${what}: ${describeError(error)}`);
1691
+ exitCode = 1;
1692
+ if (!stopping) shutdown(running, "crash");
1693
+ };
1694
+ proc.on("uncaughtException", crash("uncaught exception"));
1695
+ proc.on("unhandledRejection", crash("unhandled rejection"));
1696
+ if (early !== void 0) shutdown(running, early);
658
1697
  }
659
- let config;
1698
+ // src/adapters/in/cli/options.ts
1699
+ const SETTINGS = [
1700
+ {
1701
+ flag: "tcp-host",
1702
+ field: "tcp.host",
1703
+ kind: "string",
1704
+ arg: "<addr>",
1705
+ description: "Interface for the speech TCP listener (default 127.0.0.1)"
1706
+ },
1707
+ {
1708
+ flag: "tcp-port",
1709
+ field: "tcp.port",
1710
+ kind: "integer",
1711
+ arg: "<n>",
1712
+ description: "Port the socket voice connects to (default 4449)"
1713
+ },
1714
+ {
1715
+ flag: "tcp-encoding",
1716
+ field: "tcp.encoding",
1717
+ kind: "string",
1718
+ arg: "<enc>",
1719
+ description: "Code page of the incoming text (default windows-1252)"
1720
+ },
1721
+ {
1722
+ flag: "host",
1723
+ field: "http.host",
1724
+ kind: "string",
1725
+ arg: "<addr>",
1726
+ description: "Interface for HTTP, Playwright server and MCP (default 0.0.0.0)"
1727
+ },
1728
+ {
1729
+ flag: "http-port",
1730
+ field: "http.port",
1731
+ kind: "integer",
1732
+ arg: "<n>",
1733
+ description: "HTTP API and web UI (default 5151)"
1734
+ },
1735
+ {
1736
+ flag: "playwright-port",
1737
+ field: "playwright.port",
1738
+ kind: "integer",
1739
+ arg: "<n>",
1740
+ description: "Playwright server (default 3000)"
1741
+ },
1742
+ {
1743
+ flag: "playwright-version",
1744
+ field: "playwright.version",
1745
+ kind: "string",
1746
+ arg: "<v>",
1747
+ description: "Playwright version of the server (default: bundled)"
1748
+ },
1749
+ {
1750
+ flag: "mcp-port",
1751
+ field: "mcp.port",
1752
+ kind: "integer",
1753
+ arg: "<n>",
1754
+ description: "Playwright MCP (default 8931)"
1755
+ },
1756
+ {
1757
+ flag: "no-playwright",
1758
+ field: "playwright.enabled",
1759
+ kind: "off",
1760
+ description: "Don't start the Playwright server"
1761
+ },
1762
+ {
1763
+ flag: "no-mcp",
1764
+ field: "mcp.enabled",
1765
+ kind: "off",
1766
+ description: "Don't start Playwright MCP"
1767
+ },
1768
+ {
1769
+ flag: "no-input",
1770
+ field: "input.enabled",
1771
+ kind: "off",
1772
+ description: "Disable the native input endpoints"
1773
+ },
1774
+ {
1775
+ flag: "log-level",
1776
+ field: "log.level",
1777
+ kind: "string",
1778
+ arg: "<level>",
1779
+ description: "error, warn, info (default) or debug"
1780
+ },
1781
+ {
1782
+ flag: "bridge-log",
1783
+ field: "log.file",
1784
+ kind: "string",
1785
+ arg: "<path>",
1786
+ description: "File for the bridge log"
1787
+ },
1788
+ {
1789
+ flag: "console-speech",
1790
+ field: "log.consoleSpeech",
1791
+ kind: "on",
1792
+ description: "Also write the speech to the console (feedback loop on the VM!)"
1793
+ },
1794
+ {
1795
+ flag: "config",
1796
+ kind: "string",
1797
+ arg: "<path>",
1798
+ description: "Use a different config file"
1799
+ }
1800
+ ];
1801
+ const envName = (flag) => `SR_SPEECH_${flag.toUpperCase().replaceAll("-", "_")}`;
1802
+ /** A flag or environment variable that can't be read. The message names it. */
1803
+ var UsageError = class extends Error {
1804
+ name = "UsageError";
1805
+ };
1806
+ const ON = [
1807
+ "1",
1808
+ "true",
1809
+ "yes",
1810
+ "on"
1811
+ ];
1812
+ const OFF = [
1813
+ "",
1814
+ "0",
1815
+ "false",
1816
+ "no",
1817
+ "off"
1818
+ ];
1819
+ /** The value of one setting, `undefined` when it isn't set. */
1820
+ function read(setting, raw, source) {
1821
+ if (typeof raw === "boolean") return setting.kind === "off" ? !raw : raw;
1822
+ switch (setting.kind) {
1823
+ case "string": return raw;
1824
+ case "integer":
1825
+ if (!/^\d+$/.test(raw)) throw new UsageError(`${source}: must be a whole number`);
1826
+ return Number(raw);
1827
+ case "on":
1828
+ case "off": {
1829
+ const value = raw.toLowerCase();
1830
+ if (OFF.includes(value)) return void 0;
1831
+ if (!ON.includes(value)) throw new UsageError(`${source}: must be 1 or 0`);
1832
+ return setting.kind === "on";
1833
+ }
1834
+ }
1835
+ }
1836
+ /** Reads the flags in `argv` and the `SR_SPEECH_*` variables in `env`. Flags win. */
1837
+ function parseCli(argv, env) {
1838
+ let values;
1839
+ try {
1840
+ ({values} = parseArgs({
1841
+ args: [...argv],
1842
+ strict: true,
1843
+ allowPositionals: false,
1844
+ options: {
1845
+ ...Object.fromEntries(SETTINGS.map((s) => [s.flag, { type: s.kind === "on" || s.kind === "off" ? "boolean" : "string" }])),
1846
+ help: {
1847
+ type: "boolean",
1848
+ short: "h"
1849
+ },
1850
+ version: {
1851
+ type: "boolean",
1852
+ short: "v"
1853
+ }
1854
+ }
1855
+ }));
1856
+ } catch (error) {
1857
+ throw new UsageError(error.message, { cause: error });
1858
+ }
1859
+ const result = {
1860
+ overrides: {},
1861
+ sources: /* @__PURE__ */ new Map(),
1862
+ configFile: void 0,
1863
+ help: values.help === true,
1864
+ version: values.version === true
1865
+ };
1866
+ for (const setting of SETTINGS) {
1867
+ const flag = values[setting.flag];
1868
+ const name = envName(setting.flag);
1869
+ const fromEnv = env[name];
1870
+ const [raw, source] = flag !== void 0 ? [flag, `--${setting.flag}`] : [fromEnv, name];
1871
+ if (raw === void 0) continue;
1872
+ const value = read(setting, raw, source);
1873
+ if (value === void 0) continue;
1874
+ if (setting.field === void 0) {
1875
+ result.configFile = value;
1876
+ continue;
1877
+ }
1878
+ const [section, key] = setting.field.split(".");
1879
+ (result.overrides[section] ??= {})[key] = value;
1880
+ result.sources.set(setting.field, source);
1881
+ }
1882
+ return result;
1883
+ }
1884
+ /** `--help`. */
1885
+ function helpText() {
1886
+ const rows = SETTINGS.map((s) => [`--${s.flag}${s.arg ? ` ${s.arg}` : ""}`, s.description]);
1887
+ rows.push(["-h, --help", "Show this help"], ["-v, --version", "Show the version"]);
1888
+ const width = Math.max(...rows.map(([left]) => left.length)) + 2;
1889
+ return [
1890
+ "Usage: screenreader-speech-capture [options]",
1891
+ "",
1892
+ "Captures what a screen reader says and serves it over HTTP.",
1893
+ "",
1894
+ "Options:",
1895
+ ...rows.map(([left, right]) => ` ${left.padEnd(width)}${right}`),
1896
+ "",
1897
+ "Each option can also be set as an environment variable: SR_SPEECH_ plus the name in upper",
1898
+ "snake case, for example SR_SPEECH_TCP_PORT=4450 or SR_SPEECH_NO_MCP=1. Flags win over the",
1899
+ "environment, which wins over the config file. See docs/configuration.md.",
1900
+ ""
1901
+ ].join("\n");
1902
+ }
1903
+ // src/adapters/in/cli/cli.ts
1904
+ const fail = (message) => {
1905
+ process.stderr.write(`screenreader-speech-capture: ${message}\n`);
1906
+ process.exit(2);
1907
+ };
1908
+ let options;
660
1909
  try {
661
- config = configFromEnv(process.env);
1910
+ options = parseCli(process.argv.slice(2), process.env);
662
1911
  } catch (error) {
663
- process.stderr.write(`screenreader-speech-capture: ${error.message}\n`);
664
- process.exit(2);
1912
+ if (!(error instanceof UsageError)) throw error;
1913
+ options = fail(`${error.message}\nRun with --help to see the options.`);
1914
+ }
1915
+ if (options.help) {
1916
+ process.stdout.write(helpText());
1917
+ process.exit(0);
1918
+ }
1919
+ if (options.version) {
1920
+ process.stdout.write(`${version}\n`);
1921
+ process.exit(0);
665
1922
  }
666
- const log = new BridgeLog(config.log.level, [consoleSink()]);
667
1923
  try {
668
- const bridge = await startBridge({
669
- config,
1924
+ await runUntilStopped(() => startBridge({
670
1925
  version,
671
- log
672
- });
673
- let stopping = false;
674
- const shutdown = () => {
675
- if (stopping) return;
676
- stopping = true;
677
- bridge.stop().then(() => process.exit(0), (error) => {
678
- log.for("bridge").error(`shutdown failed: ${String(error)}`);
679
- process.exit(1);
680
- });
681
- };
682
- for (const signal of [
683
- "SIGINT",
684
- "SIGTERM",
685
- "SIGHUP"
686
- ]) process.on(signal, shutdown);
1926
+ overrides: options.overrides,
1927
+ overrideSources: options.sources,
1928
+ ...options.configFile === void 0 ? {} : { configFile: options.configFile }
1929
+ }), process);
687
1930
  } catch (error) {
688
- const message = error instanceof ListenError ? error.message : String(error);
689
- log.for("bridge").error(message);
1931
+ if (error instanceof ConfigError) fail(error.message);
1932
+ await flushConsole();
690
1933
  process.exit(1);
691
1934
  }
692
1935
  export {};