screenreader-speech-capture-client 0.0.0-stage → 0.0.1-preview.0

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 ADDED
@@ -0,0 +1,356 @@
1
+ #!/usr/bin/env node
2
+ import { a as BridgeNotReadyError, c as SpeechTimeoutError, d as ClientConfigError, i as BridgeHttpError, n as createClientConfig, o as BridgeUnreachableError, p as URL_ENV, s as IncompatibleBridgeError, t as SpeechCaptureClient } from "./main-DH_3C5Dp.mjs";
3
+ import { parseArgs } from "node:util";
4
+ // package.json
5
+ var version = "0.0.1-preview.0";
6
+ // src/adapters/in/cli/run.ts
7
+ /** Exit codes (docs/client.md#cli-for-agents). */
8
+ const EXIT = {
9
+ ok: 0,
10
+ timeout: 1,
11
+ bridge: 2,
12
+ usage: 3
13
+ };
14
+ var UsageError = class extends Error {};
15
+ const NAME = "screenreader-speech-capture-client";
16
+ const SOURCE_LABEL = {
17
+ explicit: "--url",
18
+ env: URL_ENV,
19
+ config: "config file",
20
+ default: "default"
21
+ };
22
+ function helpText() {
23
+ return `Usage: ${NAME} <command> [options]
24
+
25
+ Commands:
26
+ status [--wait-ready] [--timeout <ms>]
27
+ Bridge health and versions; --wait-ready waits until it is ready
28
+ (default timeout 120000)
29
+ clear Clear the speech buffer
30
+ speech [--since <seq>] [--limit <n>] [--include-markers]
31
+ Recorded speech entries, oldest first
32
+ text [--since <seq>] [--separator <s>]
33
+ All speech joined into one text (one line per entry)
34
+ wait <text> [--regex] [--normalize] [--since <seq>] [--timeout <ms>]
35
+ Wait until speech contains <text> (or matches the regex);
36
+ also finds speech that arrived before the call (default timeout 5000)
37
+ wait-silence [--quiet-for <ms>] [--timeout <ms>]
38
+ Wait until nothing was spoken for --quiet-for ms (default 500, 10000)
39
+ mark <label> Insert a marker and print its seq, for --since
40
+
41
+ config set url <url> Store the bridge URL for this user
42
+ config get url Show the bridge URL in use and where it comes from
43
+ config unset url Remove the stored bridge URL
44
+ config list Show all settings and where they come from
45
+ config path Show the path of the config file
46
+
47
+ Options:
48
+ --url <url> Bridge URL (env ${URL_ENV}, then the config file, default http://localhost:5151)
49
+ --json Machine-readable output
50
+ -h, --help Show this help
51
+ -v, --version Show the version
52
+
53
+ --since <seq> takes a seq printed by mark (default 0: everything since the last clear).
54
+
55
+ Exit codes: 0 success, 1 timeout / no match, 2 bridge not reachable, HTTP error or
56
+ incompatible bridge, 3 invalid usage or config.
57
+ `;
58
+ }
59
+ /** Runs one CLI invocation and returns its exit code. */
60
+ async function runCli(argv, io) {
61
+ try {
62
+ return await dispatch(argv, io);
63
+ } catch (error) {
64
+ if (error instanceof UsageError) {
65
+ io.stderr(`${NAME}: ${error.message}\nRun with --help to see the commands.\n`);
66
+ return EXIT.usage;
67
+ }
68
+ if (error instanceof ClientConfigError) {
69
+ io.stderr(`${NAME}: ${error.message}\n`);
70
+ return EXIT.usage;
71
+ }
72
+ if (error instanceof BridgeNotReadyError) {
73
+ io.stderr(`${NAME}: ${error.message}\n`);
74
+ return EXIT.timeout;
75
+ }
76
+ if (error instanceof BridgeUnreachableError || error instanceof BridgeHttpError || error instanceof IncompatibleBridgeError) {
77
+ io.stderr(`${NAME}: ${error.message}\n`);
78
+ return EXIT.bridge;
79
+ }
80
+ throw error;
81
+ }
82
+ }
83
+ async function dispatch(argv, io) {
84
+ let parsed;
85
+ try {
86
+ parsed = parseArgs({
87
+ args: [...argv],
88
+ allowPositionals: true,
89
+ options: OPTIONS
90
+ });
91
+ } catch (error) {
92
+ throw new UsageError(error.message);
93
+ }
94
+ const { values, positionals } = parsed;
95
+ if (values.help) {
96
+ io.stdout(helpText());
97
+ return EXIT.ok;
98
+ }
99
+ if (values.version) {
100
+ io.stdout(`${io.version}\n`);
101
+ return EXIT.ok;
102
+ }
103
+ const [command, ...rest] = positionals;
104
+ if (command === void 0) throw new UsageError("Missing command.");
105
+ if (!isCommand(command)) throw new UsageError(`Unknown command "${command}".`);
106
+ checkOptions(command, values);
107
+ const globals = {
108
+ url: values.url,
109
+ json: values.json
110
+ };
111
+ if (command === "config") return config(rest, globals, io);
112
+ const ctx = {
113
+ ...globals,
114
+ values,
115
+ speech: io.speech(values.url),
116
+ out: (json, text) => io.stdout(values.json ? `${JSON.stringify(json)}\n` : `${text}\n`),
117
+ io
118
+ };
119
+ return SPEECH_COMMANDS[command](rest, ctx);
120
+ }
121
+ /** Every option; {@link COMMAND_OPTIONS} says which command takes which. */
122
+ const OPTIONS = {
123
+ url: { type: "string" },
124
+ json: {
125
+ type: "boolean",
126
+ default: false
127
+ },
128
+ help: {
129
+ type: "boolean",
130
+ short: "h",
131
+ default: false
132
+ },
133
+ version: {
134
+ type: "boolean",
135
+ short: "v",
136
+ default: false
137
+ },
138
+ since: { type: "string" },
139
+ limit: { type: "string" },
140
+ timeout: { type: "string" },
141
+ "quiet-for": { type: "string" },
142
+ "include-markers": { type: "boolean" },
143
+ separator: { type: "string" },
144
+ regex: { type: "boolean" },
145
+ normalize: { type: "boolean" },
146
+ "wait-ready": { type: "boolean" }
147
+ };
148
+ /** Options every command takes. */
149
+ const GLOBAL_OPTIONS = [
150
+ "url",
151
+ "json",
152
+ "help",
153
+ "version"
154
+ ];
155
+ const COMMAND_OPTIONS = {
156
+ config: [],
157
+ status: ["wait-ready", "timeout"],
158
+ clear: [],
159
+ speech: [
160
+ "since",
161
+ "limit",
162
+ "include-markers"
163
+ ],
164
+ text: ["since", "separator"],
165
+ wait: [
166
+ "regex",
167
+ "normalize",
168
+ "since",
169
+ "timeout"
170
+ ],
171
+ "wait-silence": ["quiet-for", "timeout"],
172
+ mark: []
173
+ };
174
+ const isCommand = (name) => Object.hasOwn(COMMAND_OPTIONS, name);
175
+ function checkOptions(command, values) {
176
+ const allowed = [...GLOBAL_OPTIONS, ...COMMAND_OPTIONS[command]];
177
+ for (const [name, value] of Object.entries(values)) if (value !== void 0 && !allowed.includes(name)) throw new UsageError(`"${command}" does not take --${name}.`);
178
+ }
179
+ const SPEECH_COMMANDS = {
180
+ async status(args, { values, speech, out }) {
181
+ expectArgs(args, 0, "status [--wait-ready] [--timeout <ms>]");
182
+ const timeout = optionalInt(values, "timeout", 0);
183
+ if (!values["wait-ready"] && timeout !== void 0) throw new UsageError("--timeout needs --wait-ready.");
184
+ const status = values["wait-ready"] ? await speech.waitForReady({ timeout }) : await speech.status();
185
+ out(status, formatStatus(status));
186
+ return EXIT.ok;
187
+ },
188
+ async clear(args, { speech, out }) {
189
+ expectArgs(args, 0, "clear");
190
+ await speech.clear();
191
+ out({ cleared: true }, "Speech buffer cleared.");
192
+ return EXIT.ok;
193
+ },
194
+ async speech(args, { values, speech, out }) {
195
+ expectArgs(args, 0, "speech [--since <seq>] [--limit <n>] [--include-markers]");
196
+ const entries = await speech.getSpeech({
197
+ since: optionalInt(values, "since", 0) ?? 0,
198
+ limit: optionalInt(values, "limit", 1),
199
+ includeMarkers: values["include-markers"] ?? false
200
+ });
201
+ out({ entries }, entries.map(formatEntry).join("\n"));
202
+ return EXIT.ok;
203
+ },
204
+ async text(args, { values, speech, out }) {
205
+ expectArgs(args, 0, "text [--since <seq>] [--separator <s>]");
206
+ const text = await speech.getText({
207
+ since: optionalInt(values, "since", 0) ?? 0,
208
+ separator: values.separator
209
+ });
210
+ out({ text }, text);
211
+ return EXIT.ok;
212
+ },
213
+ async wait(args, { values, speech, out, io, json }) {
214
+ const [text] = expectArgs(args, 1, "wait <text> [--regex] [--normalize] [--timeout <ms>]");
215
+ if (text.trim() === "") throw new UsageError("The text to wait for must not be empty.");
216
+ let match = text;
217
+ if (values.regex) try {
218
+ match = new RegExp(text, "u");
219
+ } catch (error) {
220
+ throw new UsageError(`Invalid --regex: ${error.message}`);
221
+ }
222
+ try {
223
+ const entry = await speech.waitForOutput(match, {
224
+ since: optionalInt(values, "since", 0) ?? 0,
225
+ timeout: optionalInt(values, "timeout", 0),
226
+ normalize: values.normalize ?? false
227
+ });
228
+ out({
229
+ matched: true,
230
+ entry
231
+ }, formatEntry(entry));
232
+ return EXIT.ok;
233
+ } catch (error) {
234
+ if (!(error instanceof SpeechTimeoutError)) throw error;
235
+ if (json) io.stdout(`${JSON.stringify({
236
+ matched: false,
237
+ entries: error.entries
238
+ })}\n`);
239
+ io.stderr(`${NAME}: ${error.message}.${seenText(error.entries)}\n`);
240
+ return EXIT.timeout;
241
+ }
242
+ },
243
+ async "wait-silence"(args, { values, speech, out, io }) {
244
+ expectArgs(args, 0, "wait-silence [--quiet-for <ms>] [--timeout <ms>]");
245
+ const quietFor = optionalInt(values, "quiet-for", 1);
246
+ try {
247
+ await speech.waitForSilence({
248
+ quietFor,
249
+ timeout: optionalInt(values, "timeout", 0)
250
+ });
251
+ out({ silent: true }, "Silent.");
252
+ return EXIT.ok;
253
+ } catch (error) {
254
+ if (!(error instanceof SpeechTimeoutError)) throw error;
255
+ io.stderr(`${NAME}: ${error.message}.\n`);
256
+ return EXIT.timeout;
257
+ }
258
+ },
259
+ async mark(args, { speech, out }) {
260
+ const [label] = expectArgs(args, 1, "mark <label>");
261
+ const entry = await speech.mark(label);
262
+ out(entry, String(entry.seq));
263
+ return EXIT.ok;
264
+ }
265
+ };
266
+ /** An integer option >= `min`, `undefined` if not given. */
267
+ function optionalInt(values, name, min) {
268
+ const raw = values[name];
269
+ if (raw === void 0) return void 0;
270
+ const value = Number(raw);
271
+ if (typeof raw !== "string" || !/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < min) throw new UsageError(`--${name} must be an integer >= ${min}, got "${String(raw)}".`);
272
+ return value;
273
+ }
274
+ function formatEntry(entry) {
275
+ return entry.kind === "marker" ? `#${entry.seq} [marker] ${entry.text}` : `#${entry.seq} ${entry.text}`;
276
+ }
277
+ function seenText(entries) {
278
+ if (entries.length === 0) return " No speech arrived.";
279
+ return ` Speech seen:\n${entries.map((e) => ` ${formatEntry(e)}`).join("\n")}`;
280
+ }
281
+ function formatStatus(status) {
282
+ const { bridge, tcp, buffer, input } = status;
283
+ const connections = tcp.connections.length;
284
+ const range = buffer.firstSeq === null ? "empty" : `seq ${buffer.firstSeq}-${buffer.lastSeq ?? buffer.firstSeq}`;
285
+ return [
286
+ `bridge ${bridge.version} (API ${bridge.apiVersion}), ${bridge.state}`,
287
+ `tcp ${tcp.host}:${tcp.port} ${tcp.listening ? "listening" : "not listening"}, ${connections} voice connection${connections === 1 ? "" : "s"}, ${tcp.encoding}`,
288
+ `buffer ${buffer.size} of ${buffer.maxEntries} entries (${range})`,
289
+ `input ${input.enabled ? "enabled" : "disabled"}`
290
+ ].join("\n");
291
+ }
292
+ async function config(args, globals, io) {
293
+ const { config } = io;
294
+ const file = config.location;
295
+ const explicit = { url: globals.url };
296
+ const out = (json, text) => io.stdout(globals.json ? `${JSON.stringify(json)}\n` : `${text}\n`);
297
+ const [action, ...rest] = args;
298
+ switch (action) {
299
+ case "set": {
300
+ const [key, value] = expectArgs(rest, 2, "config set <key> <value>");
301
+ const result = await config.set(key, value);
302
+ out({
303
+ ...result,
304
+ file
305
+ }, `Saved ${result.key} = ${result.value} to ${file}`);
306
+ if (result.shadowedBy === "env") io.stderr(`Note: ${URL_ENV} is set and takes precedence over the config file.\n`);
307
+ return EXIT.ok;
308
+ }
309
+ case "get": {
310
+ const [key] = expectArgs(rest, 1, "config get <key>");
311
+ const result = await config.get(key, explicit);
312
+ out(result, `${result.value} (${SOURCE_LABEL[result.source]})`);
313
+ return EXIT.ok;
314
+ }
315
+ case "unset": {
316
+ const [key] = expectArgs(rest, 1, "config unset <key>");
317
+ const result = await config.unset(key);
318
+ out({
319
+ ...result,
320
+ file
321
+ }, `Removed ${result.key} from ${file}`);
322
+ return EXIT.ok;
323
+ }
324
+ case "list": {
325
+ expectArgs(rest, 0, "config list");
326
+ const entries = await config.list(explicit);
327
+ out({
328
+ file,
329
+ settings: entries
330
+ }, [`# ${file}`, ...entries.map((e) => `${e.key} = ${e.value} (${SOURCE_LABEL[e.source]})`)].join("\n"));
331
+ return EXIT.ok;
332
+ }
333
+ case "path":
334
+ expectArgs(rest, 0, "config path");
335
+ out({ file }, file);
336
+ return EXIT.ok;
337
+ case void 0: throw new UsageError("Missing config action: set, get, unset, list or path.");
338
+ default: throw new UsageError(`Unknown config action "${action}": use set, get, unset, list or path.`);
339
+ }
340
+ }
341
+ function expectArgs(args, count, usage) {
342
+ if (args.length !== count) throw new UsageError(`Usage: ${NAME} ${usage}`);
343
+ return args;
344
+ }
345
+ // src/adapters/in/cli/cli.ts
346
+ process.exitCode = await runCli(process.argv.slice(2), {
347
+ config: createClientConfig(process.env),
348
+ speech: (url) => new SpeechCaptureClient({
349
+ baseUrl: url,
350
+ env: process.env
351
+ }),
352
+ stdout: (text) => process.stdout.write(text),
353
+ stderr: (text) => process.stderr.write(text),
354
+ version
355
+ });
356
+ export {};
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { i as BridgeHttpError, a as BridgeNotReadyError, o as BridgeUnreachableError, l as CONFIG_PATH_ENV, d as ClientConfigError, f as DEFAULT_BRIDGE_URL, s as IncompatibleBridgeError, t as SpeechCaptureClient, c as SpeechTimeoutError, p as URL_ENV, u as clientConfigFile, n as createClientConfig, m as normalizeBridgeUrl, r as normalizeText } from "./main-DH_3C5Dp.mjs";
@@ -0,0 +1,580 @@
1
+ import { setTimeout } from "node:timers/promises";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ // ../shared/src/api-version.ts
6
+ /** Path prefix of every API route. */
7
+ const API_PREFIX = "/api/v1";
8
+ // src/adapters/out/clock/system-clock.ts
9
+ var SystemClock = class {
10
+ now() {
11
+ return performance.now();
12
+ }
13
+ async sleep(ms) {
14
+ await setTimeout(ms);
15
+ }
16
+ };
17
+ // src/domain/bridge-url.ts
18
+ /** Bridge URL used when nothing else is configured. */
19
+ const DEFAULT_BRIDGE_URL = "http://localhost:5151";
20
+ /** Environment variable with the bridge URL. */
21
+ const URL_ENV = "SR_SPEECH_URL";
22
+ /** The config file or a configured value is invalid. */
23
+ var ClientConfigError = class extends Error {
24
+ name = "ClientConfigError";
25
+ };
26
+ /**
27
+ * Checks a bridge URL and returns it normalised: only `http:` / `https:`, no trailing slash, so
28
+ * API paths can be appended directly.
29
+ */
30
+ function normalizeBridgeUrl(input, origin = "URL") {
31
+ let url;
32
+ try {
33
+ url = new URL(input.trim());
34
+ } catch {
35
+ throw new ClientConfigError(`${origin} "${input}" is not a valid URL (e.g. http://my-vm:5151)`);
36
+ }
37
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new ClientConfigError(`${origin} "${input}" must start with http:// or https://`);
38
+ if (url.search !== "" || url.hash !== "") throw new ClientConfigError(`${origin} "${input}" must not contain a query or fragment`);
39
+ return url.href.replace(/\/+$/, "");
40
+ }
41
+ /** Checks the parsed content of a config file. `origin` names the file in errors. */
42
+ function parseClientConfig(raw, origin) {
43
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new ClientConfigError(`The client config file ${origin} must contain a JSON object`);
44
+ const { url } = raw;
45
+ if (url === void 0) return {};
46
+ if (typeof url !== "string") throw new ClientConfigError(`"url" in the client config file ${origin} must be a string`);
47
+ return { url: normalizeBridgeUrl(url, `"url" in ${origin}`) };
48
+ }
49
+ const isSet = (value) => value !== void 0 && value !== "";
50
+ /** True if the stored value can't win, so the config file doesn't have to be read. */
51
+ const overridesStored = (sources) => isSet(sources.explicit) || isSet(sources.env);
52
+ /**
53
+ * The bridge URL to use: explicit value, then `SR_SPEECH_URL`, then the config file, then
54
+ * {@link DEFAULT_BRIDGE_URL}.
55
+ */
56
+ function pickBridgeUrl(sources) {
57
+ if (isSet(sources.explicit)) return {
58
+ value: normalizeBridgeUrl(sources.explicit),
59
+ source: "explicit"
60
+ };
61
+ if (isSet(sources.env)) return {
62
+ value: normalizeBridgeUrl(sources.env, URL_ENV),
63
+ source: "env"
64
+ };
65
+ if (isSet(sources.stored)) return {
66
+ value: sources.stored,
67
+ source: "config"
68
+ };
69
+ return {
70
+ value: DEFAULT_BRIDGE_URL,
71
+ source: "default"
72
+ };
73
+ }
74
+ /** Keys the client config stores, each with the check that normalises a value before saving. */
75
+ const CONFIG_KEYS = { url: (value) => normalizeBridgeUrl(value) };
76
+ /** Checks a key name given by a user. */
77
+ function parseConfigKey(key) {
78
+ if (Object.hasOwn(CONFIG_KEYS, key)) return key;
79
+ throw new ClientConfigError(`Unknown config key "${key}". Known keys: ${Object.keys(CONFIG_KEYS).join(", ")}.`);
80
+ }
81
+ // src/adapters/out/fs-config/fs-client-config-store.ts
82
+ /**
83
+ * The client config file (docs/client.md#bridge-url): JSON, one per user. Keys this version
84
+ * doesn't know are kept when saving.
85
+ */
86
+ var FsClientConfigStore = class {
87
+ location;
88
+ constructor(location) {
89
+ this.location = location;
90
+ }
91
+ async load() {
92
+ return parseClientConfig(await this.readRaw(), this.location);
93
+ }
94
+ /**
95
+ * Writes a temporary file and renames it, so a crash never leaves half a file. Values already
96
+ * in the file aren't checked, so `config set` can repair an invalid one.
97
+ */
98
+ async save(patch) {
99
+ const raw = await this.readRaw();
100
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new ClientConfigError(`The client config file ${this.location} must contain a JSON object`);
101
+ const next = { ...raw };
102
+ for (const [key, value] of Object.entries(patch)) if (value === void 0) delete next[key];
103
+ else next[key] = value;
104
+ await fs.mkdir(path.dirname(this.location), { recursive: true });
105
+ const temporary = `${this.location}.${process.pid}.tmp`;
106
+ try {
107
+ await fs.writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, "utf8");
108
+ await fs.rename(temporary, this.location);
109
+ } catch (error) {
110
+ await fs.rm(temporary, { force: true });
111
+ throw error;
112
+ }
113
+ }
114
+ /** The parsed file, `{}` if it doesn't exist. */
115
+ async readRaw() {
116
+ let text;
117
+ try {
118
+ text = await fs.readFile(this.location, "utf8");
119
+ } catch (error) {
120
+ if (error.code === "ENOENT") return {};
121
+ throw new ClientConfigError(`Cannot read the client config file ${this.location}: ${error.message}`, { cause: error });
122
+ }
123
+ try {
124
+ return JSON.parse(text);
125
+ } catch (error) {
126
+ throw new ClientConfigError(`The client config file ${this.location} is not valid JSON: ${error.message}`, { cause: error });
127
+ }
128
+ }
129
+ };
130
+ // src/adapters/out/fs-config/paths.ts
131
+ const APP = "screenreader-speech-capture";
132
+ /** Environment variable that points the client at a different config file. */
133
+ const CONFIG_PATH_ENV = "SR_SPEECH_CLIENT_CONFIG";
134
+ /**
135
+ * The client's config file: `%APPDATA%\screenreader-speech-capture\client.json` on Windows,
136
+ * `$XDG_CONFIG_HOME` (or `~/.config`) + `screenreader-speech-capture/client.json` on Linux and
137
+ * macOS. It sits next to the bridge's `config.json` but is a separate file, so a bridge and a
138
+ * client on the same machine never share settings. `SR_SPEECH_CLIENT_CONFIG` overrides the path.
139
+ */
140
+ function clientConfigFile(platform = process.platform, env = process.env, home = os.homedir()) {
141
+ const override = env[CONFIG_PATH_ENV];
142
+ if (override !== void 0 && override !== "") return override;
143
+ if (platform === "win32") {
144
+ const base = env.APPDATA ?? path.win32.join(home, "AppData", "Roaming");
145
+ return path.win32.join(base, APP, "client.json");
146
+ }
147
+ const base = env.XDG_CONFIG_HOME ?? path.posix.join(home, ".config");
148
+ return path.posix.join(base, APP, "client.json");
149
+ }
150
+ // src/domain/errors.ts
151
+ /** A wait ended without a match. `entries` holds the speech seen while waiting, oldest first. */
152
+ var SpeechTimeoutError = class extends Error {
153
+ entries;
154
+ name = "SpeechTimeoutError";
155
+ constructor(message, entries) {
156
+ super(message);
157
+ this.entries = entries;
158
+ }
159
+ };
160
+ /** `waitForReady` timed out: the bridge was not reachable or not `ready` in time. */
161
+ var BridgeNotReadyError = class extends Error {
162
+ name = "BridgeNotReadyError";
163
+ };
164
+ /** The bridge speaks another major version of the HTTP API (docs/http-api.md#versioning). */
165
+ var IncompatibleBridgeError = class extends Error {
166
+ bridgeApiVersion;
167
+ clientApiVersion;
168
+ name = "IncompatibleBridgeError";
169
+ constructor(bridgeApiVersion, clientApiVersion) {
170
+ super(`The bridge speaks API ${bridgeApiVersion}, this client needs API ${clientApiVersion}. Install the bridge and the client in the same version.`);
171
+ this.bridgeApiVersion = bridgeApiVersion;
172
+ this.clientApiVersion = clientApiVersion;
173
+ }
174
+ };
175
+ /** No connection to the bridge (wrong URL, bridge not running, network). */
176
+ var BridgeUnreachableError = class extends Error {
177
+ url;
178
+ name = "BridgeUnreachableError";
179
+ constructor(url, options) {
180
+ const reason = describeCause(options?.cause);
181
+ super(`The bridge at ${url} is not reachable${reason ? ` (${reason})` : ""}`, options);
182
+ this.url = url;
183
+ }
184
+ };
185
+ /** The bridge answered with an error (docs/http-api.md#errors). */
186
+ var BridgeHttpError = class extends Error {
187
+ status;
188
+ code;
189
+ details;
190
+ name = "BridgeHttpError";
191
+ constructor(status, code, message, details) {
192
+ super(`${message} (HTTP ${status}, ${code})`);
193
+ this.status = status;
194
+ this.code = code;
195
+ this.details = details;
196
+ }
197
+ };
198
+ function describeCause(cause) {
199
+ if (!(cause instanceof Error)) return void 0;
200
+ const inner = cause.cause;
201
+ if (typeof inner === "object" && inner !== null && "code" in inner) return String(inner.code);
202
+ return inner instanceof Error ? inner.message : cause.message;
203
+ }
204
+ // src/adapters/out/http/fetch-bridge-api.ts
205
+ /** A request that gets no answer in this time fails as unreachable (the bridge answers at once). */
206
+ const REQUEST_TIMEOUT_MS = 1e4;
207
+ /** {@link BridgeApi} over `fetch` (docs/http-api.md). */
208
+ var FetchBridgeApi = class {
209
+ options;
210
+ #baseUrl;
211
+ constructor(options) {
212
+ this.options = options;
213
+ }
214
+ async status() {
215
+ return toStatus(await this.json("GET", "/status"));
216
+ }
217
+ async listSpeech(query) {
218
+ const params = new URLSearchParams({ since: String(query.since) });
219
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
220
+ const page = await this.json("GET", `/speech?${params.toString()}`);
221
+ return {
222
+ entries: page.entries.map(toEntry),
223
+ truncated: page.truncated,
224
+ hasMore: page.hasMore
225
+ };
226
+ }
227
+ async clear() {
228
+ await this.request("DELETE", "/speech");
229
+ }
230
+ async mark(label) {
231
+ const body = { label };
232
+ return toEntry(await this.json("POST", "/markers", body));
233
+ }
234
+ async json(method, path, body) {
235
+ return await (await this.request(method, path, body)).json();
236
+ }
237
+ async request(method, path, body) {
238
+ const base = await this.base();
239
+ let response;
240
+ try {
241
+ response = await (this.options.fetch ?? fetch)(`${base}${API_PREFIX}${path}`, {
242
+ method,
243
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
244
+ ...body === void 0 ? {} : {
245
+ headers: { "content-type": "application/json" },
246
+ body: JSON.stringify(body)
247
+ }
248
+ });
249
+ } catch (error) {
250
+ throw new BridgeUnreachableError(base, { cause: error });
251
+ }
252
+ if (!response.ok) throw await toHttpError(response);
253
+ return response;
254
+ }
255
+ base() {
256
+ this.#baseUrl ??= this.options.baseUrl().catch((error) => {
257
+ this.#baseUrl = void 0;
258
+ throw error;
259
+ });
260
+ return this.#baseUrl;
261
+ }
262
+ };
263
+ async function toHttpError(response) {
264
+ try {
265
+ const { error } = await response.json();
266
+ return new BridgeHttpError(response.status, error.code, error.message, error.details);
267
+ } catch {
268
+ return new BridgeHttpError(response.status, "HTTP_ERROR", response.statusText);
269
+ }
270
+ }
271
+ const toEntry = (dto) => ({
272
+ seq: dto.seq,
273
+ kind: dto.kind,
274
+ text: dto.text,
275
+ receivedAt: dto.receivedAt,
276
+ source: dto.source,
277
+ voice: dto.voice,
278
+ connectionId: dto.connectionId
279
+ });
280
+ const toStatus = (dto) => dto;
281
+ // src/application/services/client-config-service.ts
282
+ var ClientConfigService = class {
283
+ deps;
284
+ constructor(deps) {
285
+ this.deps = deps;
286
+ }
287
+ get location() {
288
+ return this.deps.store.location;
289
+ }
290
+ async get(key, explicit = {}) {
291
+ const k = parseConfigKey(key);
292
+ const sources = {
293
+ explicit: explicit[k],
294
+ env: this.deps.envUrl
295
+ };
296
+ return {
297
+ key: k,
298
+ ...overridesStored(sources) ? pickBridgeUrl(sources) : pickBridgeUrl({
299
+ ...sources,
300
+ stored: (await this.deps.store.load())[k]
301
+ })
302
+ };
303
+ }
304
+ list(explicit = {}) {
305
+ return Promise.all(Object.keys(CONFIG_KEYS).map((k) => this.get(k, explicit)));
306
+ }
307
+ async set(key, value) {
308
+ const k = parseConfigKey(key);
309
+ const normalized = CONFIG_KEYS[k](value);
310
+ await this.deps.store.save({ [k]: normalized });
311
+ return {
312
+ key: k,
313
+ value: normalized,
314
+ ...overridesStored({ env: this.deps.envUrl }) ? { shadowedBy: "env" } : {}
315
+ };
316
+ }
317
+ async unset(key) {
318
+ const k = parseConfigKey(key);
319
+ await this.deps.store.save({ [k]: void 0 });
320
+ return { key: k };
321
+ }
322
+ };
323
+ // src/domain/api-version.ts
324
+ /** Major part of a `<major>.<minor>` API version, `undefined` if it isn't one. */
325
+ function major(version) {
326
+ const match = /^(\d+)\.\d+$/.exec(version);
327
+ return match ? Number(match[1]) : void 0;
328
+ }
329
+ /**
330
+ * Throws {@link IncompatibleBridgeError} unless the bridge's API has the client's major version
331
+ * (docs/http-api.md#versioning). A newer or older minor version is fine: minor versions only add
332
+ * things.
333
+ */
334
+ function checkApiVersion(bridgeApiVersion, clientApiVersion) {
335
+ const bridge = major(bridgeApiVersion);
336
+ if (bridge === void 0 || bridge !== major(clientApiVersion)) throw new IncompatibleBridgeError(bridgeApiVersion, clientApiVersion);
337
+ }
338
+ // src/domain/speech-entry.ts
339
+ const isSpeech = (entry) => entry.kind === "speech";
340
+ // src/domain/text-match.ts
341
+ /** Lower case, whitespace runs collapsed to one space, trimmed (same rule as the bridge). */
342
+ function normalizeText(text) {
343
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
344
+ }
345
+ /** Builds the test for one {@link SpeechMatch}. Markers never match. */
346
+ function toMatcher(match, options = {}) {
347
+ const prepare = options.normalize ? normalizeText : (text) => text;
348
+ let test;
349
+ if (typeof match === "function") test = match;
350
+ else if (match instanceof RegExp) {
351
+ let flags = match.flags.replace(/[gy]/g, "");
352
+ if (options.normalize && !flags.includes("i")) flags += "i";
353
+ const pattern = new RegExp(match.source, flags);
354
+ test = (entry) => pattern.test(prepare(entry.text));
355
+ } else {
356
+ const needle = prepare(match);
357
+ if (needle === "") throw new TypeError("The text to wait for must not be empty");
358
+ test = (entry) => prepare(entry.text).includes(needle);
359
+ }
360
+ return (entry) => isSpeech(entry) && test(entry);
361
+ }
362
+ /**
363
+ * Feeds `entries` into an ordered search for `matchers` and returns the matches found so far
364
+ * (`found` extended). Other entries may come in between. Done when the result has
365
+ * `matchers.length` entries.
366
+ */
367
+ function advanceSequence(matchers, found, entries) {
368
+ const result = [...found];
369
+ for (const entry of entries) {
370
+ const next = matchers[result.length];
371
+ if (next === void 0) break;
372
+ if (next(entry)) result.push(entry);
373
+ }
374
+ return result;
375
+ }
376
+ // src/application/services/speech-capture-service.ts
377
+ /** Largest `limit` the bridge accepts for `GET /api/v1/speech`. */
378
+ const MAX_PAGE = 1e4;
379
+ const DEFAULTS = {
380
+ timeout: 5e3,
381
+ quietFor: 500,
382
+ silenceTimeout: 1e4,
383
+ readyTimeout: 12e4
384
+ };
385
+ var SpeechCaptureService = class {
386
+ deps;
387
+ #cursor = 0;
388
+ #compatible;
389
+ constructor(deps) {
390
+ this.deps = deps;
391
+ }
392
+ cursor() {
393
+ return this.#cursor;
394
+ }
395
+ setCursor(seq) {
396
+ if (!Number.isSafeInteger(seq) || seq < 0) throw new RangeError(`The cursor must be a seq (an integer >= 0), got ${seq}`);
397
+ this.#cursor = seq;
398
+ }
399
+ async getSpeech(options = {}) {
400
+ await this.compatible();
401
+ const entries = await this.fetchSince(options.since ?? this.#cursor);
402
+ const wanted = options.includeMarkers ? entries : entries.filter(isSpeech);
403
+ return options.limit === void 0 ? wanted : wanted.slice(0, options.limit);
404
+ }
405
+ async getText(options = {}) {
406
+ return (await this.getSpeech({ since: options.since })).map((e) => e.text).join(options.separator ?? "\n");
407
+ }
408
+ async clear() {
409
+ await this.compatible();
410
+ await this.deps.api.clear();
411
+ this.#cursor = 0;
412
+ }
413
+ async mark(label) {
414
+ await this.compatible();
415
+ return this.deps.api.mark(label);
416
+ }
417
+ async status() {
418
+ const status = await this.deps.api.status();
419
+ checkApiVersion(status.bridge.apiVersion, this.deps.apiVersion);
420
+ this.#compatible = Promise.resolve();
421
+ return status;
422
+ }
423
+ async waitForReady(options = {}) {
424
+ const { clock } = this.deps;
425
+ const timeout = options.timeout ?? DEFAULTS.readyTimeout;
426
+ const deadline = clock.now() + timeout;
427
+ let last;
428
+ for (;;) {
429
+ try {
430
+ const status = await this.status();
431
+ if (status.bridge.state === "ready") return status;
432
+ last = `state is ${status.bridge.state}`;
433
+ } catch (error) {
434
+ const starting = error instanceof BridgeHttpError && error.status === 503;
435
+ if (!(error instanceof BridgeUnreachableError) && !starting) throw error;
436
+ last = error.message;
437
+ }
438
+ const left = deadline - clock.now();
439
+ if (left <= 0) throw new BridgeNotReadyError(`The bridge was not ready within ${timeout} ms: ${last}`);
440
+ await clock.sleep(Math.min(this.pollMs * 10, left));
441
+ }
442
+ }
443
+ async waitForOutput(match, options = {}) {
444
+ const test = toMatcher(match, options);
445
+ await this.compatible();
446
+ const entry = await this.search(options, (entries) => entries.find(test), `No speech matched ${describe(match)}`);
447
+ this.#cursor = entry.seq;
448
+ return entry;
449
+ }
450
+ async waitForSequence(matches, options = {}) {
451
+ if (matches.length === 0) throw new TypeError("waitForSequence needs at least one match");
452
+ const matchers = matches.map((m) => toMatcher(m, options));
453
+ await this.compatible();
454
+ let found = [];
455
+ const result = await this.search(options, (entries) => {
456
+ found = advanceSequence(matchers, found, entries);
457
+ return found.length === matchers.length ? found : void 0;
458
+ }, () => `Only ${found.length} of ${matches.length} matches occurred in order (next: ${describe(matches[found.length])})`);
459
+ this.#cursor = result.at(-1).seq;
460
+ return result;
461
+ }
462
+ async waitForSilence(options = {}) {
463
+ const { clock } = this.deps;
464
+ const quietFor = options.quietFor ?? DEFAULTS.quietFor;
465
+ const timeout = options.timeout ?? DEFAULTS.silenceTimeout;
466
+ await this.compatible();
467
+ const start = clock.now();
468
+ let from = await this.endSeq();
469
+ let lastSpeech = start;
470
+ const seen = [];
471
+ for (;;) {
472
+ const entries = await this.fetchSince(from);
473
+ if (entries.length > 0) from = entries.at(-1).seq;
474
+ const speech = entries.filter(isSpeech);
475
+ const now = clock.now();
476
+ if (speech.length > 0) {
477
+ seen.push(...speech);
478
+ lastSpeech = now;
479
+ }
480
+ const quiet = now - lastSpeech;
481
+ if (quiet >= quietFor) return;
482
+ if (now - start >= timeout) throw new SpeechTimeoutError(`Speech did not pause for ${quietFor} ms within ${timeout} ms`, seen);
483
+ await clock.sleep(Math.min(this.pollMs, quietFor - quiet, start + timeout - now));
484
+ }
485
+ }
486
+ async record(fn, options = {}) {
487
+ await this.compatible();
488
+ const start = await this.endSeq();
489
+ const result = await fn();
490
+ await this.waitForSilence(options);
491
+ const entries = await this.fetchSince(start);
492
+ if (entries.length > 0) this.#cursor = entries.at(-1).seq;
493
+ return {
494
+ result,
495
+ entries: entries.filter(isSpeech)
496
+ };
497
+ }
498
+ get pollMs() {
499
+ return this.deps.pollMs ?? 50;
500
+ }
501
+ /** Checks the API version once. A failed check is repeated on the next call. */
502
+ compatible() {
503
+ this.#compatible ??= this.status().then(() => void 0, (error) => {
504
+ this.#compatible = void 0;
505
+ throw error;
506
+ });
507
+ return this.#compatible;
508
+ }
509
+ /** The `seq` of the newest entry in the buffer, 0 if it is empty. */
510
+ async endSeq() {
511
+ return (await this.deps.api.status()).buffer.lastSeq ?? 0;
512
+ }
513
+ /** Every entry with `seq > since`, across pages. */
514
+ async fetchSince(since) {
515
+ const all = [];
516
+ let from = since;
517
+ for (;;) {
518
+ const page = await this.deps.api.listSpeech({
519
+ since: from,
520
+ limit: MAX_PAGE
521
+ });
522
+ all.push(...page.entries);
523
+ const last = page.entries.at(-1);
524
+ if (!page.hasMore || last === void 0) return all;
525
+ from = last.seq;
526
+ }
527
+ }
528
+ /**
529
+ * Polls for entries after the cursor (or `options.since`) until `step` returns a result.
530
+ * Rejects with {@link SpeechTimeoutError} (and the speech seen) after `options.timeout`.
531
+ */
532
+ async search(options, step, failure) {
533
+ const { clock } = this.deps;
534
+ const timeout = options.timeout ?? DEFAULTS.timeout;
535
+ const deadline = clock.now() + timeout;
536
+ const seen = [];
537
+ let from = options.since ?? this.#cursor;
538
+ for (;;) {
539
+ const entries = await this.fetchSince(from);
540
+ if (entries.length > 0) from = entries.at(-1).seq;
541
+ seen.push(...entries.filter(isSpeech));
542
+ const result = step(entries);
543
+ if (result !== void 0) return result;
544
+ const left = deadline - clock.now();
545
+ if (left <= 0) throw new SpeechTimeoutError(`${typeof failure === "string" ? failure : failure()} within ${timeout} ms`, seen);
546
+ await clock.sleep(Math.min(this.pollMs, left));
547
+ }
548
+ }
549
+ };
550
+ function describe(match) {
551
+ if (typeof match === "string") return JSON.stringify(match);
552
+ if (match instanceof RegExp) return String(match);
553
+ return "the predicate";
554
+ }
555
+ // src/main.ts
556
+ /**
557
+ * The client's per-user settings, stored in the config file (docs/client.md#bridge-url).
558
+ * `SR_SPEECH_URL` and `SR_SPEECH_CLIENT_CONFIG` are read from `env` once, here.
559
+ */
560
+ function createClientConfig(env = process.env) {
561
+ return new ClientConfigService({
562
+ store: new FsClientConfigStore(clientConfigFile(void 0, env)),
563
+ envUrl: env[URL_ENV]
564
+ });
565
+ }
566
+ /**
567
+ * Talks to the bridge (docs/client.md#library): `new SpeechCaptureClient()` uses the stored
568
+ * bridge URL. The URL is resolved on the first request.
569
+ */
570
+ var SpeechCaptureClient = class extends SpeechCaptureService {
571
+ constructor(options = {}) {
572
+ const config = createClientConfig(options.env ?? process.env);
573
+ super({
574
+ api: new FetchBridgeApi({ baseUrl: async () => (await config.get("url", { url: options.baseUrl })).value }),
575
+ clock: new SystemClock(),
576
+ apiVersion: "1.0"
577
+ });
578
+ }
579
+ };
580
+ export { BridgeNotReadyError as a, SpeechTimeoutError as c, ClientConfigError as d, DEFAULT_BRIDGE_URL as f, BridgeHttpError as i, CONFIG_PATH_ENV as l, normalizeBridgeUrl as m, createClientConfig as n, BridgeUnreachableError as o, URL_ENV as p, normalizeText as r, IncompatibleBridgeError as s, SpeechCaptureClient as t, clientConfigFile as u };
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "screenreader-speech-capture-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1-preview.0",
4
+ "description": "Test client for the screenreader-speech-capture bridge: library, Playwright fixture and CLI.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "exports": {
11
+ ".": "./dist/index.mjs"
12
+ },
13
+ "bin": {
14
+ "screenreader-speech-capture-client": "./dist/cli.mjs"
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "devDependencies": {
20
+ "@screenreader-speech-capture/shared": "0.0.0",
21
+ "tsdown": "0.23.7"
22
+ },
23
+ "scripts": {
24
+ "build": "tsdown",
25
+ "typecheck": "tsc --noEmit"
26
+ }
6
27
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.