screenreader-speech-capture 0.0.1-preview.3 → 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.
- package/dist/cli.mjs +1463 -309
- package/package.json +3 -6
package/dist/cli.mjs
CHANGED
|
@@ -1,13 +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 fs from "node:fs";
|
|
4
|
+
import { TextDecoder as TextDecoder$1, parseArgs } from "node:util";
|
|
5
|
+
import fs from "node:fs/promises";
|
|
5
6
|
import path from "node:path";
|
|
7
|
+
import fs$1 from "node:fs";
|
|
6
8
|
import os from "node:os";
|
|
7
|
-
import { performance } from "node:perf_hooks";
|
|
8
|
-
import { monotonicFactory } from "ulid";
|
|
9
9
|
// package.json
|
|
10
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
|
+
}
|
|
11
489
|
// src/adapters/in/tcp/text-to-socket-parser.ts
|
|
12
490
|
const LF = 10;
|
|
13
491
|
const CR = 13;
|
|
@@ -88,52 +566,46 @@ var TextToSocketParser = class {
|
|
|
88
566
|
}
|
|
89
567
|
};
|
|
90
568
|
// 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
569
|
/**
|
|
101
570
|
* Driving adapter for the socket voice: a TCP server that accepts any number of connections
|
|
102
571
|
* and feeds each one through its own parser into `RecordSpeech`
|
|
103
|
-
* (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.
|
|
104
574
|
*/
|
|
105
575
|
var TcpListener = class {
|
|
106
576
|
recordSpeech;
|
|
577
|
+
clock;
|
|
107
578
|
logger;
|
|
108
579
|
server = null;
|
|
109
580
|
sockets = /* @__PURE__ */ new Set();
|
|
110
|
-
|
|
581
|
+
open = /* @__PURE__ */ new Map();
|
|
582
|
+
nextConnectionId = 1;
|
|
583
|
+
listener = null;
|
|
584
|
+
constructor(recordSpeech, clock, logger) {
|
|
111
585
|
this.recordSpeech = recordSpeech;
|
|
586
|
+
this.clock = clock;
|
|
112
587
|
this.logger = logger;
|
|
113
588
|
}
|
|
589
|
+
captureStatus() {
|
|
590
|
+
return {
|
|
591
|
+
listener: this.listener && { ...this.listener },
|
|
592
|
+
connections: [...this.open.values()].map((connection) => ({ ...connection }))
|
|
593
|
+
};
|
|
594
|
+
}
|
|
114
595
|
/** Starts listening. Resolves with the bound port (useful with port 0). */
|
|
115
596
|
async start(settings) {
|
|
116
597
|
if (this.server) throw new Error("TCP listener is already running");
|
|
117
598
|
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
|
-
});
|
|
599
|
+
const port = await listen(server, settings.host, settings.port);
|
|
129
600
|
server.on("error", (error) => this.logger.error(`TCP listener error: ${error.message}`));
|
|
130
601
|
this.server = server;
|
|
131
|
-
|
|
132
|
-
|
|
602
|
+
this.listener = {
|
|
603
|
+
listening: true,
|
|
133
604
|
host: settings.host,
|
|
134
605
|
port,
|
|
135
606
|
encoding: settings.encoding
|
|
136
|
-
}
|
|
607
|
+
};
|
|
608
|
+
this.logger.info(`listening on ${settings.host}:${port}, encoding ${settings.encoding}`);
|
|
137
609
|
return port;
|
|
138
610
|
}
|
|
139
611
|
/** Stops listening and closes all open connections. */
|
|
@@ -144,14 +616,32 @@ var TcpListener = class {
|
|
|
144
616
|
const closed = new Promise((resolve) => server.close(() => resolve()));
|
|
145
617
|
for (const socket of this.sockets) socket.destroy();
|
|
146
618
|
await closed;
|
|
147
|
-
this.
|
|
619
|
+
if (this.listener) this.listener = {
|
|
620
|
+
...this.listener,
|
|
621
|
+
listening: false
|
|
622
|
+
};
|
|
623
|
+
this.logger.info("stopped listening");
|
|
148
624
|
}
|
|
149
625
|
accept(socket, settings) {
|
|
150
626
|
this.sockets.add(socket);
|
|
151
|
-
const id = this.
|
|
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`);
|
|
152
635
|
const parser = new TextToSocketParser(settings.encoding, settings.maxLineBytes, {
|
|
153
|
-
header: (voice) =>
|
|
154
|
-
|
|
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
|
+
}),
|
|
155
645
|
lineCut: (max) => this.logger.warn(`connection ${id}: line longer than ${max} bytes, cut it`)
|
|
156
646
|
});
|
|
157
647
|
socket.on("data", (chunk) => parser.push(chunk));
|
|
@@ -159,10 +649,54 @@ var TcpListener = class {
|
|
|
159
649
|
socket.on("close", () => {
|
|
160
650
|
parser.end();
|
|
161
651
|
this.sockets.delete(socket);
|
|
162
|
-
this.
|
|
652
|
+
this.open.delete(id);
|
|
653
|
+
this.logger.info(`connection ${id} closed`);
|
|
163
654
|
});
|
|
164
655
|
}
|
|
165
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
|
+
};
|
|
166
700
|
// src/adapters/out/log/file-sink.ts
|
|
167
701
|
/**
|
|
168
702
|
* Bridge log file (docs/operations.md#logging): no colours, includes the speech channel.
|
|
@@ -174,17 +708,17 @@ function fileSink(file, options = {}) {
|
|
|
174
708
|
let size = 0;
|
|
175
709
|
let failed = false;
|
|
176
710
|
try {
|
|
177
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
178
|
-
size = fs.existsSync(file) ? fs.statSync(file).size : 0;
|
|
711
|
+
fs$1.mkdirSync(path.dirname(file), { recursive: true });
|
|
712
|
+
size = fs$1.existsSync(file) ? fs$1.statSync(file).size : 0;
|
|
179
713
|
} catch (error) {
|
|
180
714
|
failed = true;
|
|
181
715
|
onError(error);
|
|
182
716
|
}
|
|
183
717
|
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 });
|
|
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 });
|
|
188
722
|
size = 0;
|
|
189
723
|
};
|
|
190
724
|
return {
|
|
@@ -196,7 +730,7 @@ function fileSink(file, options = {}) {
|
|
|
196
730
|
const bytes = Buffer.byteLength(data);
|
|
197
731
|
try {
|
|
198
732
|
if (size > 0 && size + bytes > maxBytes) rotate();
|
|
199
|
-
fs.appendFileSync(file, data);
|
|
733
|
+
fs$1.appendFileSync(file, data);
|
|
200
734
|
size += bytes;
|
|
201
735
|
} catch (error) {
|
|
202
736
|
failed = true;
|
|
@@ -308,7 +842,95 @@ var BridgeLog = class {
|
|
|
308
842
|
}
|
|
309
843
|
}
|
|
310
844
|
};
|
|
311
|
-
// src/adapters/out/log/
|
|
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
|
+
});
|
|
857
|
+
}
|
|
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;
|
|
865
|
+
}
|
|
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
|
|
312
934
|
const APP = "screenreader-speech-capture";
|
|
313
935
|
/**
|
|
314
936
|
* Default bridge log file: `%LOCALAPPDATA%\screenreader-speech-capture\logs\bridge.log` on
|
|
@@ -322,21 +944,17 @@ function defaultLogFile(platform = process.platform, env = process.env, home = o
|
|
|
322
944
|
const base = env.XDG_STATE_HOME ?? path.posix.join(home, ".local", "state");
|
|
323
945
|
return path.posix.join(base, APP, "logs", "bridge.log");
|
|
324
946
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
};
|
|
337
|
-
/** `INVALID_REQUEST` for one field. */
|
|
338
|
-
function invalidField(field, message) {
|
|
339
|
-
return new AppError("INVALID_REQUEST", `${field}: ${message}`, { field });
|
|
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");
|
|
340
958
|
}
|
|
341
959
|
// src/domain/config.ts
|
|
342
960
|
const LOG_LEVELS = [
|
|
@@ -449,204 +1067,184 @@ function mergeConfig(base, patch) {
|
|
|
449
1067
|
}
|
|
450
1068
|
return result;
|
|
451
1069
|
}
|
|
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
|
|
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
|
+
}
|
|
496
1080
|
/**
|
|
497
|
-
*
|
|
498
|
-
*
|
|
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.
|
|
499
1083
|
*/
|
|
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;
|
|
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;
|
|
519
1098
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
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;
|
|
526
1135
|
}
|
|
527
|
-
|
|
528
|
-
this.
|
|
529
|
-
this.start = 0;
|
|
530
|
-
this.droppedUpToSeq = 0;
|
|
1136
|
+
get() {
|
|
1137
|
+
return this.active;
|
|
531
1138
|
}
|
|
532
|
-
|
|
533
|
-
this.
|
|
534
|
-
this.dropOverflow();
|
|
1139
|
+
onChange(listener) {
|
|
1140
|
+
this.listeners.push(listener);
|
|
535
1141
|
}
|
|
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
|
-
};
|
|
1142
|
+
update(patch) {
|
|
1143
|
+
const result = this.queue.then(() => this.apply(patch));
|
|
1144
|
+
this.queue = result.catch(() => void 0);
|
|
1145
|
+
return result;
|
|
544
1146
|
}
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
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;
|
|
549
1167
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
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)}`);
|
|
553
1177
|
}
|
|
554
1178
|
}
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
if (this.entries[mid].seq <= since) low = mid + 1;
|
|
562
|
-
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`);
|
|
563
1185
|
}
|
|
564
|
-
return low;
|
|
565
1186
|
}
|
|
566
1187
|
};
|
|
567
|
-
// src/application/
|
|
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
|
|
1195
|
+
/**
|
|
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).
|
|
1198
|
+
*/
|
|
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;
|
|
568
1206
|
/**
|
|
569
|
-
*
|
|
570
|
-
* and
|
|
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).
|
|
571
1210
|
*/
|
|
572
|
-
var
|
|
1211
|
+
var SpeechService = class {
|
|
573
1212
|
deps;
|
|
574
|
-
open = /* @__PURE__ */ new Map();
|
|
575
|
-
nextConnectionId = 1;
|
|
576
|
-
listener = null;
|
|
577
1213
|
constructor(deps) {
|
|
578
1214
|
this.deps = deps;
|
|
579
1215
|
}
|
|
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(),
|
|
1216
|
+
record({ text, voice, connectionId }) {
|
|
1217
|
+
this.add({
|
|
613
1218
|
kind: "speech",
|
|
614
1219
|
text,
|
|
615
|
-
receivedAt: clock.now(),
|
|
616
|
-
monotonicMs: clock.monotonicMs(),
|
|
617
1220
|
source: "tcp",
|
|
618
|
-
voice
|
|
1221
|
+
voice,
|
|
619
1222
|
connectionId
|
|
620
1223
|
});
|
|
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
1224
|
}
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
var SpeechService = class {
|
|
644
|
-
deps;
|
|
645
|
-
constructor(deps) {
|
|
646
|
-
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);
|
|
647
1237
|
}
|
|
648
|
-
|
|
649
|
-
|
|
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);
|
|
650
1248
|
}
|
|
651
1249
|
clear() {
|
|
652
1250
|
this.deps.repository.clear();
|
|
@@ -656,126 +1254,682 @@ var SpeechService = class {
|
|
|
656
1254
|
const text = label.trim();
|
|
657
1255
|
if (text === "") throw invalidField("label", "must not be empty");
|
|
658
1256
|
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(),
|
|
1257
|
+
return this.add({
|
|
662
1258
|
kind: "marker",
|
|
663
1259
|
text,
|
|
664
|
-
receivedAt: clock.now(),
|
|
665
|
-
monotonicMs: clock.monotonicMs(),
|
|
666
1260
|
source: "api",
|
|
667
1261
|
voice: null,
|
|
668
1262
|
connectionId: null
|
|
669
1263
|
});
|
|
670
|
-
|
|
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({
|
|
671
1271
|
type: "entry",
|
|
672
|
-
entry
|
|
1272
|
+
entry: stored
|
|
673
1273
|
});
|
|
674
|
-
return
|
|
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());
|
|
675
1424
|
}
|
|
676
1425
|
};
|
|
677
1426
|
// src/main.ts
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
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}`;
|
|
681
1434
|
if (file !== null) message += `, log file ${file}`;
|
|
682
1435
|
if (level !== "debug") return `${message} (speech text is logged at debug)`;
|
|
683
1436
|
if (consoleSpeech) return `${message} (speech text also on the console)`;
|
|
684
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)`;
|
|
685
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
|
+
*/
|
|
686
1482
|
async function startBridge(options) {
|
|
687
|
-
const {
|
|
688
|
-
const
|
|
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);
|
|
689
1494
|
const bridgeLogger = log.for("bridge");
|
|
690
|
-
log.
|
|
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`);
|
|
691
1498
|
const clock = options.clock ?? new SystemClock();
|
|
692
|
-
const
|
|
693
|
-
const repository = new RingBufferRepository(config.buffer.maxEntries);
|
|
1499
|
+
const repository = new MemorySpeechRepository(config.buffer.maxEntries);
|
|
694
1500
|
const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
|
|
695
|
-
|
|
1501
|
+
logSpeechTranscript(events, log.for("speech-capture", { channel: "speech" }));
|
|
1502
|
+
const speech = new SpeechService({
|
|
696
1503
|
repository,
|
|
697
1504
|
events,
|
|
698
|
-
clock
|
|
699
|
-
ids,
|
|
700
|
-
logger: log.for("speech-capture"),
|
|
701
|
-
transcript: log.for("speech-capture", { channel: "speech" })
|
|
1505
|
+
clock
|
|
702
1506
|
});
|
|
703
|
-
const
|
|
1507
|
+
const waits = new WaitForSpeechService({
|
|
704
1508
|
repository,
|
|
705
|
-
events
|
|
706
|
-
|
|
707
|
-
|
|
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 }
|
|
708
1533
|
});
|
|
709
|
-
const
|
|
710
|
-
|
|
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
|
+
}
|
|
1563
|
+
});
|
|
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");
|
|
711
1581
|
bridgeLogger.info("ready");
|
|
1582
|
+
let stopping;
|
|
712
1583
|
return {
|
|
713
|
-
|
|
714
|
-
|
|
1584
|
+
get tcpPort() {
|
|
1585
|
+
return tcpPort;
|
|
1586
|
+
},
|
|
1587
|
+
get httpPort() {
|
|
1588
|
+
return httpPort;
|
|
1589
|
+
},
|
|
715
1590
|
speech,
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
1591
|
+
capture: tcp,
|
|
1592
|
+
log: bridgeLogger,
|
|
1593
|
+
stop(reason) {
|
|
1594
|
+
stopping ??= shutdown(reason);
|
|
1595
|
+
return stopping;
|
|
721
1596
|
}
|
|
722
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
|
+
}
|
|
723
1613
|
}
|
|
724
|
-
// src/cli.ts
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
"
|
|
730
|
-
"
|
|
731
|
-
"
|
|
732
|
-
]
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
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;
|
|
745
1682
|
}
|
|
1683
|
+
if (!stopping) return shutdown(bridge, signal);
|
|
1684
|
+
bridge.log.warn(`${signal} again, exiting without waiting`);
|
|
1685
|
+
exit(1);
|
|
746
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);
|
|
747
1697
|
}
|
|
748
|
-
|
|
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;
|
|
749
1909
|
try {
|
|
750
|
-
|
|
1910
|
+
options = parseCli(process.argv.slice(2), process.env);
|
|
751
1911
|
} catch (error) {
|
|
752
|
-
|
|
753
|
-
|
|
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);
|
|
754
1922
|
}
|
|
755
|
-
const log = new BridgeLog(config.log.level, [consoleSink({ speech: config.log.consoleSpeech }), ...config.log.file === null ? [] : [fileSink(config.log.file)]]);
|
|
756
1923
|
try {
|
|
757
|
-
|
|
758
|
-
config,
|
|
1924
|
+
await runUntilStopped(() => startBridge({
|
|
759
1925
|
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);
|
|
1926
|
+
overrides: options.overrides,
|
|
1927
|
+
overrideSources: options.sources,
|
|
1928
|
+
...options.configFile === void 0 ? {} : { configFile: options.configFile }
|
|
1929
|
+
}), process);
|
|
776
1930
|
} catch (error) {
|
|
777
|
-
|
|
778
|
-
|
|
1931
|
+
if (error instanceof ConfigError) fail(error.message);
|
|
1932
|
+
await flushConsole();
|
|
779
1933
|
process.exit(1);
|
|
780
1934
|
}
|
|
781
1935
|
export {};
|