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