@screenreader-speech-capture/bridge 0.1.0-feat-expected-target-window.34 → 0.1.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.
Files changed (102) hide show
  1. package/dist/cli.mjs +1002 -934
  2. package/dist/ui/adapter-node.js +1 -1
  3. package/dist/ui/client/ui/_app/immutable/chunks/{BnU72Mow.js → BfHif6xP.js} +1 -1
  4. package/dist/ui/client/ui/_app/immutable/chunks/BfHif6xP.js.br +0 -0
  5. package/dist/ui/client/ui/_app/immutable/chunks/BfHif6xP.js.gz +0 -0
  6. package/dist/ui/client/ui/_app/immutable/chunks/{BS7n1gMj.js → BrPqgVT6.js} +1 -1
  7. package/dist/ui/client/ui/_app/immutable/chunks/BrPqgVT6.js.br +0 -0
  8. package/dist/ui/client/ui/_app/immutable/chunks/BrPqgVT6.js.gz +0 -0
  9. package/dist/ui/client/ui/_app/immutable/chunks/{CK3uUd4t.js → C7D7xLuA.js} +1 -1
  10. package/dist/ui/client/ui/_app/immutable/chunks/C7D7xLuA.js.br +0 -0
  11. package/dist/ui/client/ui/_app/immutable/chunks/C7D7xLuA.js.gz +0 -0
  12. package/dist/ui/client/ui/_app/immutable/chunks/{B1Ryegye.js → Cc902J0D.js} +1 -1
  13. package/dist/ui/client/ui/_app/immutable/chunks/Cc902J0D.js.br +0 -0
  14. package/dist/ui/client/ui/_app/immutable/chunks/Cc902J0D.js.gz +0 -0
  15. package/dist/ui/client/ui/_app/immutable/chunks/{CMWEX9XL.js → D9JU-e3z.js} +1 -1
  16. package/dist/ui/client/ui/_app/immutable/chunks/D9JU-e3z.js.br +0 -0
  17. package/dist/ui/client/ui/_app/immutable/chunks/D9JU-e3z.js.gz +0 -0
  18. package/dist/ui/client/ui/_app/immutable/chunks/{DOY87jO2.js → KD5R77Wj.js} +1 -1
  19. package/dist/ui/client/ui/_app/immutable/chunks/KD5R77Wj.js.br +0 -0
  20. package/dist/ui/client/ui/_app/immutable/chunks/KD5R77Wj.js.gz +0 -0
  21. package/dist/ui/client/ui/_app/immutable/chunks/{B1vArRqi.js → PzCUpBms.js} +1 -1
  22. package/dist/ui/client/ui/_app/immutable/chunks/PzCUpBms.js.br +0 -0
  23. package/dist/ui/client/ui/_app/immutable/chunks/PzCUpBms.js.gz +0 -0
  24. package/dist/ui/client/ui/_app/immutable/chunks/{4wvZDMeR.js → Roub4aju.js} +1 -1
  25. package/dist/ui/client/ui/_app/immutable/chunks/Roub4aju.js.br +0 -0
  26. package/dist/ui/client/ui/_app/immutable/chunks/Roub4aju.js.gz +0 -0
  27. package/dist/ui/client/ui/_app/immutable/chunks/{tKonUL5Y.js → ux9AxWa3.js} +1 -1
  28. package/dist/ui/client/ui/_app/immutable/chunks/ux9AxWa3.js.br +0 -0
  29. package/dist/ui/client/ui/_app/immutable/chunks/ux9AxWa3.js.gz +0 -0
  30. package/dist/ui/client/ui/_app/immutable/entry/{app.C8tsut3X.js → app.DM2PRoLw.js} +2 -2
  31. package/dist/ui/client/ui/_app/immutable/entry/app.DM2PRoLw.js.br +0 -0
  32. package/dist/ui/client/ui/_app/immutable/entry/app.DM2PRoLw.js.gz +0 -0
  33. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js +1 -0
  34. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js.br +0 -0
  35. package/dist/ui/client/ui/_app/immutable/nodes/0.fKLM0nQo.js.gz +0 -0
  36. package/dist/ui/client/ui/_app/immutable/nodes/{3.WT26F_BF.js → 3.CywuMQ0y.js} +1 -1
  37. package/dist/ui/client/ui/_app/immutable/nodes/3.CywuMQ0y.js.br +0 -0
  38. package/dist/ui/client/ui/_app/immutable/nodes/3.CywuMQ0y.js.gz +0 -0
  39. package/dist/ui/client/ui/_app/immutable/nodes/{4.tiDJxi6M.js → 4.BYvsTY13.js} +1 -1
  40. package/dist/ui/client/ui/_app/immutable/nodes/4.BYvsTY13.js.br +0 -0
  41. package/dist/ui/client/ui/_app/immutable/nodes/4.BYvsTY13.js.gz +0 -0
  42. package/dist/ui/client/ui/_app/immutable/nodes/{5.MzfJoePg.js → 5.xWNFTFjr.js} +1 -1
  43. package/dist/ui/client/ui/_app/immutable/nodes/5.xWNFTFjr.js.br +0 -0
  44. package/dist/ui/client/ui/_app/immutable/nodes/5.xWNFTFjr.js.gz +0 -0
  45. package/dist/ui/client/ui/_app/immutable/nodes/{6.bNZhqiRK.js → 6.Dnf8S10l.js} +1 -1
  46. package/dist/ui/client/ui/_app/immutable/nodes/6.Dnf8S10l.js.br +0 -0
  47. package/dist/ui/client/ui/_app/immutable/nodes/6.Dnf8S10l.js.gz +0 -0
  48. package/dist/ui/client/ui/_app/version.json +1 -1
  49. package/dist/ui/client/ui/_app/version.json.br +0 -0
  50. package/dist/ui/client/ui/_app/version.json.gz +0 -0
  51. package/dist/ui/server/chunks/composition.js +8 -5
  52. package/dist/ui/server/chunks/composition.js.map +1 -1
  53. package/dist/ui/server/chunks/instance.js +3 -3
  54. package/dist/ui/server/chunks/internal.js +1 -1
  55. package/dist/ui/server/chunks/src.js +19 -13
  56. package/dist/ui/server/chunks/src.js.map +1 -1
  57. package/dist/ui/server/entries/hooks.server.js +3 -2
  58. package/dist/ui/server/entries/hooks.server.js.map +1 -1
  59. package/dist/ui/server/entries/pages/_layout.svelte.js +1 -1
  60. package/dist/ui/server/entries/pages/_layout.svelte.js.map +1 -1
  61. package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js +1 -1
  62. package/dist/ui/server/entries/pages/setup/instructions/_page.svelte.js.map +1 -1
  63. package/dist/ui/server/manifest-full.js +1 -1
  64. package/dist/ui/server/manifest.js +1 -1
  65. package/dist/ui/server/nodes/0.js +1 -1
  66. package/dist/ui/server/nodes/3.js +1 -1
  67. package/dist/ui/server/nodes/4.js +1 -1
  68. package/dist/ui/server/nodes/5.js +1 -1
  69. package/dist/ui/server/nodes/6.js +1 -1
  70. package/dist/ui/server/server.js +1 -1
  71. package/package.json +1 -1
  72. package/dist/ui/client/ui/_app/immutable/chunks/4wvZDMeR.js.br +0 -0
  73. package/dist/ui/client/ui/_app/immutable/chunks/4wvZDMeR.js.gz +0 -0
  74. package/dist/ui/client/ui/_app/immutable/chunks/B1Ryegye.js.br +0 -0
  75. package/dist/ui/client/ui/_app/immutable/chunks/B1Ryegye.js.gz +0 -0
  76. package/dist/ui/client/ui/_app/immutable/chunks/B1vArRqi.js.br +0 -0
  77. package/dist/ui/client/ui/_app/immutable/chunks/B1vArRqi.js.gz +0 -0
  78. package/dist/ui/client/ui/_app/immutable/chunks/BS7n1gMj.js.br +0 -0
  79. package/dist/ui/client/ui/_app/immutable/chunks/BS7n1gMj.js.gz +0 -0
  80. package/dist/ui/client/ui/_app/immutable/chunks/BnU72Mow.js.br +0 -0
  81. package/dist/ui/client/ui/_app/immutable/chunks/BnU72Mow.js.gz +0 -0
  82. package/dist/ui/client/ui/_app/immutable/chunks/CK3uUd4t.js.br +0 -0
  83. package/dist/ui/client/ui/_app/immutable/chunks/CK3uUd4t.js.gz +0 -0
  84. package/dist/ui/client/ui/_app/immutable/chunks/CMWEX9XL.js.br +0 -0
  85. package/dist/ui/client/ui/_app/immutable/chunks/CMWEX9XL.js.gz +0 -0
  86. package/dist/ui/client/ui/_app/immutable/chunks/DOY87jO2.js.br +0 -0
  87. package/dist/ui/client/ui/_app/immutable/chunks/DOY87jO2.js.gz +0 -0
  88. package/dist/ui/client/ui/_app/immutable/chunks/tKonUL5Y.js.br +0 -0
  89. package/dist/ui/client/ui/_app/immutable/chunks/tKonUL5Y.js.gz +0 -0
  90. package/dist/ui/client/ui/_app/immutable/entry/app.C8tsut3X.js.br +0 -0
  91. package/dist/ui/client/ui/_app/immutable/entry/app.C8tsut3X.js.gz +0 -0
  92. package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js +0 -1
  93. package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js.br +0 -0
  94. package/dist/ui/client/ui/_app/immutable/nodes/0.3bVKqGbx.js.gz +0 -0
  95. package/dist/ui/client/ui/_app/immutable/nodes/3.WT26F_BF.js.br +0 -0
  96. package/dist/ui/client/ui/_app/immutable/nodes/3.WT26F_BF.js.gz +0 -0
  97. package/dist/ui/client/ui/_app/immutable/nodes/4.tiDJxi6M.js.br +0 -0
  98. package/dist/ui/client/ui/_app/immutable/nodes/4.tiDJxi6M.js.gz +0 -0
  99. package/dist/ui/client/ui/_app/immutable/nodes/5.MzfJoePg.js.br +0 -0
  100. package/dist/ui/client/ui/_app/immutable/nodes/5.MzfJoePg.js.gz +0 -0
  101. package/dist/ui/client/ui/_app/immutable/nodes/6.bNZhqiRK.js.br +0 -0
  102. package/dist/ui/client/ui/_app/immutable/nodes/6.bNZhqiRK.js.gz +0 -0
package/dist/cli.mjs CHANGED
@@ -1,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
+ import { once, setMaxListeners } from "node:events";
3
4
  import os, { hostname } from "node:os";
4
5
  import http from "node:http";
5
6
  import net from "node:net";
6
- import { finished } from "node:stream";
7
+ import { finished, pipeline } from "node:stream";
7
8
  import { setImmediate, setTimeout as setTimeout$1 } from "node:timers/promises";
9
+ import fs, { existsSync, readFileSync } from "node:fs";
8
10
  import { TextDecoder as TextDecoder$1, parseArgs } from "node:util";
9
- import fs, { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
11
+ import fs$1, { mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
10
12
  import path from "node:path";
11
13
  import { Worker } from "node:worker_threads";
12
- import fs$1, { existsSync, readFileSync } from "node:fs";
13
14
  import { execFile, spawn, spawnSync } from "node:child_process";
14
- import { once } from "node:events";
15
15
  import readline from "node:readline";
16
16
  // package.json
17
- var version = "0.1.0-feat-expected-target-window.34";
17
+ var version = "0.1.0";
18
18
  // ../shared/src/api-version.ts
19
19
  /**
20
20
  * `<major>.<minor>` of the HTTP API. Minor versions only add things, with the exceptions in
21
21
  * docs/usage/http-api.md#versioning. Within a major version the enums of the answers never grow
22
22
  * (`openapi/freeze.test.ts`).
23
23
  */
24
- const API_VERSION = "1.32";
24
+ const API_VERSION = "1.33";
25
25
  /** Path prefix of every API route. */
26
26
  const API_PREFIX = "/api/v1";
27
27
  /**
@@ -742,7 +742,7 @@ function safeParse(schema, input, config$1) {
742
742
  issues: dataset.issues
743
743
  };
744
744
  }
745
- // ../shared/src/limits.ts
745
+ // ../shared/src/rules/limits.ts
746
746
  /** Ranges of the speech endpoints. */
747
747
  const API_LIMITS = {
748
748
  /** `GET /speech?limit=`: the default and the most a caller may ask for. */
@@ -836,6 +836,22 @@ const isTrimmedLabel = (text, max) => {
836
836
  const trimmed = text.trim();
837
837
  return trimmed !== "" && trimmed.length <= max;
838
838
  };
839
+ // ../shared/src/rules/vocabulary.ts
840
+ /** `log.level`, from the least to the most detail. */
841
+ const LOG_LEVELS = [
842
+ "error",
843
+ "warn",
844
+ "info",
845
+ "debug"
846
+ ];
847
+ /** The buttons of a native click. */
848
+ const MOUSE_BUTTONS = [
849
+ "left",
850
+ "right",
851
+ "middle"
852
+ ];
853
+ /** Whose browser a focus or a key press means. */
854
+ const FOCUS_TARGETS = ["mcp", "playwright"];
839
855
  // ../shared/src/config.ts
840
856
  /** A `TextDecoder` label other than UTF-16 (the framing splits the bytes on 0x0A first). */
841
857
  function isSupportedEncoding(label) {
@@ -845,12 +861,6 @@ function isSupportedEncoding(label) {
845
861
  return false;
846
862
  }
847
863
  }
848
- const LOG_LEVELS = [
849
- "error",
850
- "warn",
851
- "info",
852
- "debug"
853
- ];
854
864
  const range = ({ min, max }) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min), /* @__PURE__ */ maxValue(max));
855
865
  const port = range(CONFIG_LIMITS.port);
856
866
  /** Port of a child service: `0` ("any free port") would leave the bridge no port to proxy to. */
@@ -927,14 +937,9 @@ CAPTURE.entries, `${CAPTURE.entries}`;
927
937
  const ClickRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
928
938
  x: /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(-coordinate$1), /* @__PURE__ */ maxValue(coordinate$1), /* @__PURE__ */ description("Screen x in physical pixels."), /* @__PURE__ */ examples([640])),
929
939
  y: /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(-coordinate$1), /* @__PURE__ */ maxValue(coordinate$1), /* @__PURE__ */ description("Screen y in physical pixels."), /* @__PURE__ */ examples([12])),
930
- button: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist([
931
- "left",
932
- "right",
933
- "middle"
934
- ])), /* @__PURE__ */ description("Mouse button, `left` if omitted.")),
940
+ button: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ picklist(MOUSE_BUTTONS)), /* @__PURE__ */ description("Mouse button, `left` if omitted.")),
935
941
  capture
936
942
  }), /* @__PURE__ */ description("`POST /input/click`: a native mouse click at a screen point, to give a window the focus. Added in API 1.14."));
937
- const FOCUS_TARGETS = ["mcp", "playwright"];
938
943
  const KeysRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
939
944
  keys: /* @__PURE__ */ pipe(/* @__PURE__ */ union([/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ nonEmpty()), /* @__PURE__ */ pipe(/* @__PURE__ */ array(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ nonEmpty())), /* @__PURE__ */ minLength(1), /* @__PURE__ */ maxLength(maxKeys$1))]), /* @__PURE__ */ description(`One chord (\`Insert+T\`) or a sequence of chords (\`["h", "h", "Insert+Down"]\`). Chords join modifiers (\`Control\`, \`Shift\`, \`Alt\`, \`Win\`, \`Insert\`, \`CapsLock\`) and one key with \`+\`. Names are case-insensitive (docs/usage/native-input.md#key-names); the numpad keys (\`numpad7\`, \`numpadEnter\`, …) since API 1.30. At most ${maxKeys$1} chords.`), /* @__PURE__ */ examples(["Insert+T"])),
940
945
  delayMs: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(0), /* @__PURE__ */ maxValue(delayMs$1.max))), /* @__PURE__ */ description(`Pause between the chords of a sequence in milliseconds, ${delayMs$1.default} if omitted.`)),
@@ -945,7 +950,7 @@ const FocusRequestSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ strictObject({
945
950
  target: /* @__PURE__ */ pipe(/* @__PURE__ */ picklist(FOCUS_TARGETS), /* @__PURE__ */ description("Whose browser: `mcp` (Playwright MCP) or `playwright` (the Playwright server, for tests).")),
946
951
  title: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ minLength(1), /* @__PURE__ */ maxLength(API_LIMITS.input.focusTitleLength))), /* @__PURE__ */ description("Only a window whose title contains this text, for example a marker the caller put into `document.title`. Without it, the front-most window of the target."))
947
952
  }), /* @__PURE__ */ description("`POST /input/focus`: bring a browser window the bridge started to the front. Added in API 1.21."));
948
- // ../shared/src/key-chord.ts
953
+ // ../shared/src/rules/key-chord.ts
949
954
  /**
950
955
  * The key names of `POST /input/keys` (docs/usage/native-input.md#key-names). The bridge parses
951
956
  * chords with this rule, and the CLI checks them before sending and lists the names in `--help`,
@@ -1045,38 +1050,12 @@ function parseKeyChord$1(chord) {
1045
1050
  }
1046
1051
  };
1047
1052
  }
1048
- // ../shared/src/services.ts
1053
+ // ../shared/src/rules/service-paths.ts
1049
1054
  /** The Playwright server (`connectOptions.wsEndpoint`): `ws://<bridge>:5151/playwright`. */
1050
1055
  const PLAYWRIGHT_PATH = "/playwright";
1051
1056
  /** Playwright MCP (streamable HTTP): `http://<bridge>:5151/playwright-mcp`. */
1052
1057
  const PLAYWRIGHT_MCP_PATH = "/playwright-mcp";
1053
- // ../shared/src/session.ts
1054
- const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
1055
- const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
1056
- const label = (text) => /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ check((text) => isTrimmedLabel(text, API_LIMITS.sessionLabelLength)), /* @__PURE__ */ description(`${text} Trimmed, must not be empty, at most ${API_LIMITS.sessionLabelLength} characters.`));
1057
- const sessionEntries = {
1058
- id: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing, also across restarts (since API 1.29): the first session of a bridge run gets the run's start time in milliseconds, so an id is never given out twice.")),
1059
- name: /* @__PURE__ */ string(),
1060
- run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
1061
- client: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Who started it: the `X-SR-Speech-Client` header, `null` if it wasn't sent. Added in API 1.10.")),
1062
- startedAt: timestamp$1,
1063
- endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$1), /* @__PURE__ */ description("`null` while the session is current.")),
1064
- startSeq: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("The last `seq` given out before the session started: `since=startSeq` reads the session from its start. Added in API 1.9.")),
1065
- firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
1066
- lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
1067
- entries: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
1068
- };
1069
- const StartSessionRequestSchema = /* @__PURE__ */ strictObject({
1070
- name: /* @__PURE__ */ pipe(label("For example the test title."), /* @__PURE__ */ examples(["checkout test"])),
1071
- run: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ nullable(label("Optional label that groups sessions, for example one per test run."))), /* @__PURE__ */ examples(["nightly-42"]))
1072
- });
1073
- ({ ...sessionEntries });
1074
- /**
1075
- * Request header naming the client (for example `host pid 1234`), so the bridge can tell when
1076
- * one client ends or replaces another one's session. Optional. API 1.10.
1077
- */
1078
- const CLIENT_HEADER = "x-sr-speech-client";
1079
- // ../shared/src/text-match.ts
1058
+ // ../shared/src/rules/text-match.ts
1080
1059
  /**
1081
1060
  * The `normalize` rule of the HTTP API (docs/usage/http-api.md). The bridge applies it in
1082
1061
  * `GET /speech/wait`, the client in its own waits, so both must use this one copy. It is the only
@@ -1104,6 +1083,32 @@ function createTextTest(match, normalize) {
1104
1083
  if (needle === "") return void 0;
1105
1084
  return (text) => prepare(text).includes(needle);
1106
1085
  }
1086
+ // ../shared/src/session.ts
1087
+ const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
1088
+ const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
1089
+ const label = (text) => /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ check((text) => isTrimmedLabel(text, API_LIMITS.sessionLabelLength)), /* @__PURE__ */ description(`${text} Trimmed, must not be empty, at most ${API_LIMITS.sessionLabelLength} characters.`));
1090
+ const sessionEntries = {
1091
+ id: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing, also across restarts (since API 1.29): the first session of a bridge run gets the run's start time in milliseconds, so an id is never given out twice.")),
1092
+ name: /* @__PURE__ */ string(),
1093
+ run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
1094
+ client: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Who started it: the `X-SR-Speech-Client` header, `null` if it wasn't sent. Added in API 1.10.")),
1095
+ startedAt: timestamp$1,
1096
+ endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$1), /* @__PURE__ */ description("`null` while the session is current.")),
1097
+ startSeq: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("The last `seq` given out before the session started: `since=startSeq` reads the session from its start. Added in API 1.9.")),
1098
+ firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
1099
+ lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
1100
+ entries: /* @__PURE__ */ pipe(integer$1(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
1101
+ };
1102
+ const StartSessionRequestSchema = /* @__PURE__ */ strictObject({
1103
+ name: /* @__PURE__ */ pipe(label("For example the test title."), /* @__PURE__ */ examples(["checkout test"])),
1104
+ run: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ nullable(label("Optional label that groups sessions, for example one per test run."))), /* @__PURE__ */ examples(["nightly-42"]))
1105
+ });
1106
+ ({ ...sessionEntries });
1107
+ /**
1108
+ * Request header naming the client (for example `host pid 1234`), so the bridge can tell when
1109
+ * one client ends or replaces another one's session. Optional. API 1.10.
1110
+ */
1111
+ const CLIENT_HEADER = "x-sr-speech-client";
1107
1112
  // ../shared/src/validate.ts
1108
1113
  /**
1109
1114
  * Checks `value` against `schema`. Unknown keys of an answer don't fail it and are left out of the
@@ -1123,6 +1128,104 @@ function checkDto(schema, value) {
1123
1128
  message: issue.message
1124
1129
  };
1125
1130
  }
1131
+ // src/adapters/in/cli/lifecycle.ts
1132
+ const SHUTDOWN_TIMEOUT_MS = 1e4;
1133
+ /** Ctrl+C, `kill`, closing the console window, and Ctrl+Break on Windows. */
1134
+ function shutdownSignals(platform) {
1135
+ const signals = [
1136
+ "SIGINT",
1137
+ "SIGTERM",
1138
+ "SIGHUP"
1139
+ ];
1140
+ if (platform === "win32") signals.push("SIGBREAK");
1141
+ return signals;
1142
+ }
1143
+ /** Resolves once everything written to `stream` so far is handed to the OS. */
1144
+ function drain(stream) {
1145
+ return new Promise((resolve) => stream.write("", () => resolve()));
1146
+ }
1147
+ /** Default `flush`: drains stdout and stderr. The log file is written synchronously. */
1148
+ async function flushConsole() {
1149
+ await Promise.all([drain(process.stdout), drain(process.stderr)]);
1150
+ }
1151
+ function describeError(error) {
1152
+ return error instanceof Error ? error.stack ?? String(error) : String(error);
1153
+ }
1154
+ /**
1155
+ * Starts the bridge with `start`, then stops it gracefully and exits the process
1156
+ * (docs/usage/operations.md#shutdown):
1157
+ *
1158
+ * - on a shutdown signal. A second signal exits at once.
1159
+ * - on an uncaught exception or unhandled rejection, which is logged with its stack. Exit code 1.
1160
+ * - if the shutdown takes longer than `timeoutMs`, it exits anyway with code 1.
1161
+ *
1162
+ * The exit code is 0 unless something failed. Console output is flushed before exiting.
1163
+ *
1164
+ * The signal handlers are installed before `start`, so a signal that arrives while the bridge
1165
+ * starts is not fatal: the bridge stops as soon as it has started. Resolves once started; rejects
1166
+ * like `start`.
1167
+ */
1168
+ async function runUntilStopped(start, proc, options = {}) {
1169
+ const { timeoutMs = SHUTDOWN_TIMEOUT_MS, flush = flushConsole, onForcedExit } = options;
1170
+ let bridge = void 0;
1171
+ /** A signal that arrived before the bridge had started. */
1172
+ let early;
1173
+ let stopping = false;
1174
+ let exiting = false;
1175
+ let exitCode = 0;
1176
+ let watchdog;
1177
+ /** Ends the child processes the graceful stop didn't get to. */
1178
+ const killLeftovers = () => {
1179
+ try {
1180
+ onForcedExit?.();
1181
+ } catch {}
1182
+ };
1183
+ const forceExit = (code) => {
1184
+ killLeftovers();
1185
+ proc.exit(code);
1186
+ };
1187
+ const exit = (code) => {
1188
+ if (exiting) return forceExit(code);
1189
+ exiting = true;
1190
+ flush().catch(() => void 0).then(() => {
1191
+ clearTimeout(watchdog);
1192
+ proc.exit(code);
1193
+ });
1194
+ };
1195
+ const shutdown = (running, reason) => {
1196
+ stopping = true;
1197
+ watchdog = setTimeout(() => {
1198
+ running.log.error(`shutdown did not finish within ${timeoutMs / 1e3} s, exiting`);
1199
+ exiting = true;
1200
+ forceExit(1);
1201
+ }, timeoutMs).unref();
1202
+ running.stop(reason).then(() => exit(exitCode), () => exit(1));
1203
+ };
1204
+ for (const signal of shutdownSignals(proc.platform)) proc.on(signal, () => {
1205
+ if (bridge === void 0) {
1206
+ if (early === void 0) early = signal;
1207
+ else {
1208
+ killLeftovers();
1209
+ exit(1);
1210
+ }
1211
+ return;
1212
+ }
1213
+ if (!stopping) return shutdown(bridge, signal);
1214
+ bridge.log.warn(`${signal} again, exiting without waiting`);
1215
+ killLeftovers();
1216
+ exit(1);
1217
+ });
1218
+ bridge = await start();
1219
+ const running = bridge;
1220
+ const crash = (what) => (error) => {
1221
+ running.log.error(`${what}: ${describeError(error)}`);
1222
+ exitCode = 1;
1223
+ if (!stopping) shutdown(running, "crash");
1224
+ };
1225
+ proc.on("uncaughtException", crash("uncaught exception"));
1226
+ proc.on("unhandledRejection", crash("unhandled rejection"));
1227
+ if (early !== void 0) shutdown(running, early);
1228
+ }
1126
1229
  // src/domain/errors.ts
1127
1230
  /** An expected error with a stable code, for example a bad request. */
1128
1231
  var AppError = class extends Error {
@@ -1428,7 +1531,7 @@ var ServiceProxy = class {
1428
1531
  for (const [name, value] of Object.entries(answer.headers)) if (!HOP_BY_HOP.has(name)) back[name] = value;
1429
1532
  res.writeHead(answer.statusCode ?? 502, back);
1430
1533
  res.flushHeaders();
1431
- answer.pipe(res);
1534
+ pipeline(answer, res, () => {});
1432
1535
  });
1433
1536
  upstream.on("error", (error) => {
1434
1537
  if (res.headersSent) {
@@ -1577,8 +1680,8 @@ async function readJson(req) {
1577
1680
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1578
1681
  /** The object schema of a field, behind `optional` or `nullable`; `undefined` for other types. */
1579
1682
  function nestedSchema(entry) {
1580
- if ("entries" in entry) return entry;
1581
- return "wrapped" in entry ? nestedSchema(entry.wrapped) : void 0;
1683
+ if (entry.entries) return { entries: entry.entries };
1684
+ return entry.wrapped && nestedSchema(entry.wrapped);
1582
1685
  }
1583
1686
  /** Rejects a field the schema doesn't have, naming it with its path (`capture.quietFor`). */
1584
1687
  function checkFields(body, schema, path = "") {
@@ -1593,9 +1696,58 @@ function checkFields(body, schema, path = "") {
1593
1696
  if (nested && isObject(value)) checkFields(value, nested, `${path}${name}.`);
1594
1697
  }
1595
1698
  }
1699
+ /** Whether `value` has the schema's type. An object's fields are not looked at. */
1700
+ function hasType(value, schema) {
1701
+ switch (schema.type) {
1702
+ case "string": return typeof value === "string";
1703
+ case "number": return Number.isFinite(value);
1704
+ case "picklist": return schema.options.includes(value);
1705
+ case "array": return Array.isArray(value) && value.every((item) => hasType(item, schema.item));
1706
+ case "union": return schema.options.some((option) => hasType(value, option));
1707
+ case "strict_object": return isObject(value);
1708
+ case "optional": return value === void 0 || hasType(value, schema.wrapped);
1709
+ case "nullable": return value === null || hasType(value, schema.wrapped);
1710
+ default: throw new Error(`request schema type ${schema.type} is not supported`);
1711
+ }
1712
+ }
1713
+ /** What the error says `value` must be, for a schema `hasType` supports. */
1714
+ function typeName(schema, value) {
1715
+ switch (schema.type) {
1716
+ case "optional": return typeName(schema.wrapped, value);
1717
+ case "nullable": return `${typeName(schema.wrapped, value)} or null`;
1718
+ case "union": return schema.options.map((option) => typeName(option, value)).join(" or ");
1719
+ case "array": return `an array of ${schema.item.type}s`;
1720
+ case "strict_object": return "an object";
1721
+ case "picklist": {
1722
+ if (typeof value !== "string") return "a string";
1723
+ const names = schema.options.map(String);
1724
+ return `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
1725
+ }
1726
+ default: return `a ${schema.type}`;
1727
+ }
1728
+ }
1729
+ /** Rejects the first field, in the schema's order, that doesn't have its type. */
1730
+ function checkTypes(body, schema, path = "") {
1731
+ for (const [name, entry] of Object.entries(schema.entries)) {
1732
+ const value = body[name];
1733
+ if (!hasType(value, entry)) throw invalidField(`${path}${name}`, `must be ${typeName(entry, value)}`);
1734
+ const nested = nestedSchema(entry);
1735
+ if (nested && isObject(value)) checkTypes(value, nested, `${path}${name}.`);
1736
+ }
1737
+ }
1738
+ /**
1739
+ * The body with its fields' types checked against `schema`. Only the types: ranges, lengths and
1740
+ * formats are use-case rules, applied by the application.
1741
+ */
1742
+ function typedBody(schema, body) {
1743
+ if (!isObject(body)) throw invalidField("body", "must be a JSON object");
1744
+ checkTypes(body, schema);
1745
+ return body;
1746
+ }
1596
1747
  /**
1597
1748
  * The JSON body of a POST/PUT: checks the content type, reads it, and rejects anything but an
1598
- * object with fields of `schema`. The fields' types are checked by the caller.
1749
+ * object with fields of `schema`. The fields' types are checked by the route (`typedBody`), those
1750
+ * of `PUT /config` by the domain.
1599
1751
  */
1600
1752
  async function jsonBody(req, schema) {
1601
1753
  requireJson(req);
@@ -1620,52 +1772,6 @@ function requireNoBody(req) {
1620
1772
  });
1621
1773
  });
1622
1774
  }
1623
- /** `body[name]`, or `undefined` when the body isn't a JSON object. */
1624
- function field(body, name) {
1625
- return isObject(body) ? body[name] : void 0;
1626
- }
1627
- /** A required string field of a JSON body. */
1628
- function stringField(body, name) {
1629
- const value = field(body, name);
1630
- if (typeof value !== "string") throw invalidField(name, "must be a string");
1631
- return value;
1632
- }
1633
- /** An optional string field of a JSON body. */
1634
- function optionalStringField(body, name) {
1635
- const value = field(body, name);
1636
- if (value !== void 0 && typeof value !== "string") throw invalidField(name, "must be a string");
1637
- return value;
1638
- }
1639
- /** A required number field of a JSON body. Ranges are checked by the use case. */
1640
- function numberField(body, name) {
1641
- const value = field(body, name);
1642
- if (typeof value !== "number" || !Number.isFinite(value)) throw invalidField(name, "must be a number");
1643
- return value;
1644
- }
1645
- /** An optional number field of a JSON body. */
1646
- function optionalNumberField(body, name) {
1647
- return field(body, name) === void 0 ? void 0 : numberField(body, name);
1648
- }
1649
- /** An optional field of a JSON body that is a JSON object. */
1650
- function optionalObjectField(body, name) {
1651
- const value = field(body, name);
1652
- if (value === void 0) return void 0;
1653
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidField(name, "must be an object");
1654
- return value;
1655
- }
1656
- /** A required field that is a string or an array of strings. */
1657
- function keysField(body, name) {
1658
- const value = field(body, name);
1659
- if (typeof value === "string") return value;
1660
- if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
1661
- throw invalidField(name, "must be a string or an array of strings");
1662
- }
1663
- /** An optional string field of a JSON body that may also be `null`. */
1664
- function nullableStringField(body, name) {
1665
- const value = field(body, name);
1666
- if (value !== void 0 && value !== null && typeof value !== "string") throw invalidField(name, "must be a string or null");
1667
- return value;
1668
- }
1669
1775
  /** The `X-SR-Speech-Client` header (`CLIENT_HEADER`), `null` if missing or empty. */
1670
1776
  function clientHeader(req) {
1671
1777
  const raw = req.headers[CLIENT_HEADER];
@@ -1853,32 +1959,6 @@ function hangUpSignal(req, res) {
1853
1959
  return controller.signal;
1854
1960
  }
1855
1961
  // src/adapters/in/http/routes/input-routes.ts
1856
- /** The `capture` object of an input request, `undefined` without one. */
1857
- function captureField(body) {
1858
- const capture = optionalObjectField(body, "capture");
1859
- if (capture === void 0) return void 0;
1860
- const ms = (name) => {
1861
- try {
1862
- return optionalNumberField(capture, name);
1863
- } catch {
1864
- throw invalidField(`capture.${name}`, "must be a number");
1865
- }
1866
- };
1867
- return {
1868
- quietForMs: ms("quietForMs"),
1869
- firstWithinMs: ms("firstWithinMs"),
1870
- timeoutMs: ms("timeoutMs"),
1871
- settleMs: ms("settleMs")
1872
- };
1873
- }
1874
- function toTarget(field, value) {
1875
- if (value !== "mcp" && value !== "playwright") throw invalidField(field, "must be mcp or playwright");
1876
- return value;
1877
- }
1878
- function targetField(body, name) {
1879
- const value = optionalStringField(body, name);
1880
- return value === void 0 ? void 0 : toTarget(name, value);
1881
- }
1882
1962
  /**
1883
1963
  * Runs `task` and answers with `reply`. A client that hangs up first cancels the input that isn't
1884
1964
  * sent yet (docs/usage/native-input.md#when-the-client-gives-up).
@@ -1911,10 +1991,7 @@ function answer(exchange, capture, send, record) {
1911
1991
  function inputRoutes(router, deps) {
1912
1992
  const { input, captures, focus, logger } = deps;
1913
1993
  router.add("POST", "/input/focus", { body: FocusRequestSchema }, async ({ req, res, body }) => {
1914
- const request = {
1915
- target: toTarget("target", stringField(body, "target")),
1916
- title: optionalStringField(body, "title")
1917
- };
1994
+ const request = typedBody(FocusRequestSchema, body);
1918
1995
  await whileConnected({
1919
1996
  req,
1920
1997
  res,
@@ -1924,34 +2001,23 @@ function inputRoutes(router, deps) {
1924
2001
  signal
1925
2002
  }), (focused) => sendJson(res, 200, toFocusedWindowDto(focused)));
1926
2003
  }).add("POST", "/input/click", { body: ClickRequestSchema }, async ({ req, res, body }) => {
1927
- const button = optionalStringField(body, "button");
1928
- if (button !== void 0 && button !== "left" && button !== "right" && button !== "middle") throw invalidField("button", "must be left, right or middle");
1929
- const mouseButton = button;
1930
- const request = {
1931
- x: numberField(body, "x"),
1932
- y: numberField(body, "y"),
1933
- button: mouseButton
1934
- };
2004
+ const { capture, ...request } = typedBody(ClickRequestSchema, body);
1935
2005
  await answer({
1936
2006
  req,
1937
2007
  res,
1938
2008
  logger
1939
- }, captureField(body), (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
2009
+ }, capture, (signal) => input.click(request, { signal }), (capture, signal) => captures.click({
1940
2010
  ...request,
1941
2011
  capture,
1942
2012
  signal
1943
2013
  }));
1944
2014
  }).add("POST", "/input/keys", { body: KeysRequestSchema }, async ({ req, res, body }) => {
1945
- const request = {
1946
- keys: keysField(body, "keys"),
1947
- delayMs: optionalNumberField(body, "delayMs"),
1948
- expectedTarget: targetField(body, "expectedTarget")
1949
- };
2015
+ const { capture, ...request } = typedBody(KeysRequestSchema, body);
1950
2016
  await answer({
1951
2017
  req,
1952
2018
  res,
1953
2019
  logger
1954
- }, captureField(body), (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
2020
+ }, capture, (signal) => input.pressKeys(request, { signal }), (capture, signal) => captures.pressKeys({
1955
2021
  ...request,
1956
2022
  capture,
1957
2023
  signal
@@ -1993,8 +2059,7 @@ function toSessionListDto({ sessions, currentId, outsideEntries }) {
1993
2059
  /** `POST /sessions`, `POST /sessions/end`, `DELETE /sessions`, `GET /sessions` (docs/usage/http-api.md#endpoints). */
1994
2060
  function sessionRoutes(router, { sessions }) {
1995
2061
  router.add("POST", "/sessions", { body: StartSessionRequestSchema }, ({ req, res, body }) => {
1996
- const name = stringField(body, "name");
1997
- const run = nullableStringField(body, "run");
2062
+ const { name, run } = typedBody(StartSessionRequestSchema, body);
1998
2063
  const client = clientHeader(req);
1999
2064
  sendJson(res, 201, toStartSessionResponseDto(sessions.start({
2000
2065
  name,
@@ -2069,7 +2134,7 @@ function speechRoutes(router, deps) {
2069
2134
  speech.clear(sessionParam(url));
2070
2135
  sendNoContent(res);
2071
2136
  }).add("POST", "/markers", { body: MarkerRequestSchema }, ({ res, body }) => {
2072
- const label = stringField(body, "label");
2137
+ const { label } = typedBody(MarkerRequestSchema, body);
2073
2138
  sendJson(res, 201, toSpeechEntryDto(speech.addMarker(label)));
2074
2139
  }).add("GET", "/markers/latest", { query: ["label", "session"] }, ({ res, url }) => {
2075
2140
  const label = stringParam(url, "label");
@@ -2121,7 +2186,8 @@ function toServiceStatusDto(service) {
2121
2186
  version: service.version,
2122
2187
  port: service.port,
2123
2188
  restarts: service.restarts,
2124
- exitCode: service.exitCode
2189
+ exitCode: service.exitCode,
2190
+ lastError: service.lastError
2125
2191
  };
2126
2192
  }
2127
2193
  function toInputAvailabilityDto(availability) {
@@ -2156,7 +2222,8 @@ function toStatusDto({ bridge, tcp, buffer, services, session, input }) {
2156
2222
  id,
2157
2223
  voice,
2158
2224
  connectedAt: connectedAt.toISOString()
2159
- }))
2225
+ })),
2226
+ lastSpeechAt: tcp.lastSpeechAt?.toISOString() ?? null
2160
2227
  },
2161
2228
  buffer: {
2162
2229
  size: buffer.size,
@@ -2377,38 +2444,115 @@ function parseUrl(target) {
2377
2444
  throw new AppError("INVALID_REQUEST", "The request URL is not valid");
2378
2445
  }
2379
2446
  }
2380
- // src/adapters/in/tcp/text-to-socket-parser.ts
2381
- const LF = 10;
2382
- const CR = 13;
2383
- const HEADER = /^voice=(\S.*)$/;
2447
+ // src/adapters/in/http/ui-mount.ts
2448
+ /** The environment variable the UI's BFF reads the bridge's address from. */
2449
+ const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
2450
+ /** The header adapter-node reads the request's protocol from (`PROTOCOL_HEADER`). */
2451
+ const PROTOCOL_HEADER = "x-sr-bridge-protocol";
2384
2452
  /**
2385
- * Parser for the `text-to-socket` wire format
2386
- * (docs/implementation/tcp-capture.md#framing-and-decoding), one instance per connection. Bytes are
2387
- * split at `\n` *before* decoding, so a multi-byte character split across two TCP packets is
2388
- * decoded correctly.
2453
+ * The header that tells the UI its page is opened from the bridge's own machine, where the screen
2454
+ * reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
2455
+ * Set (`1`) or removed on every request, so a client can't send it.
2389
2456
  */
2390
- var TextToSocketParser = class {
2391
- maxLineBytes;
2392
- events;
2393
- decoder;
2394
- pending = [];
2395
- pendingBytes = 0;
2396
- /** After a cut: drop bytes until the next `\n`. */
2397
- discarding = false;
2398
- firstLine = true;
2399
- constructor(encoding, maxLineBytes, events) {
2400
- this.maxLineBytes = maxLineBytes;
2401
- this.events = events;
2402
- this.decoder = new TextDecoder$1(encoding);
2457
+ const LOCAL_HEADER = "x-sr-bridge-local";
2458
+ /**
2459
+ * Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
2460
+ * a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
2461
+ * lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
2462
+ */
2463
+ const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
2464
+ /**
2465
+ * The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
2466
+ * none: the bridge runs from source, or the package was built without the UI.
2467
+ */
2468
+ function createUiMount(dir, logger) {
2469
+ const file = new URL("handler.js", dir);
2470
+ if (!existsSync(file)) {
2471
+ logger.debug(`no web UI at ${file.pathname}`);
2472
+ return;
2403
2473
  }
2404
- push(chunk) {
2405
- let start = 0;
2406
- while (start < chunk.length) {
2407
- const newline = chunk.indexOf(LF, start);
2408
- const end = newline === -1 ? chunk.length : newline;
2409
- this.append(chunk.subarray(start, end));
2410
- if (newline === -1) return;
2411
- this.completeLine();
2474
+ let settle;
2475
+ const loaded = new Promise((resolve, reject) => {
2476
+ settle = {
2477
+ resolve,
2478
+ reject
2479
+ };
2480
+ });
2481
+ loaded.catch(() => void 0);
2482
+ return {
2483
+ handler: async (req, res) => {
2484
+ if (new URL(req.url ?? "/", "http://localhost").pathname === "/") {
2485
+ res.writeHead(302, { location: "/ui/" }).end();
2486
+ return;
2487
+ }
2488
+ let handler;
2489
+ try {
2490
+ handler = await loaded;
2491
+ } catch {
2492
+ throw new AppError("SERVICE_UNAVAILABLE", "The web UI failed to start");
2493
+ }
2494
+ req.headers[PROTOCOL_HEADER] = "http";
2495
+ if (isOwnAddress(req.socket?.remoteAddress)) req.headers[LOCAL_HEADER] = "1";
2496
+ else delete req.headers[LOCAL_HEADER];
2497
+ handler(req, res, () => {
2498
+ res.statusCode = 404;
2499
+ res.end();
2500
+ });
2501
+ },
2502
+ async mount(apiUrl) {
2503
+ try {
2504
+ process.env[BRIDGE_API_URL_ENV] = apiUrl;
2505
+ process.env.PROTOCOL_HEADER = PROTOCOL_HEADER;
2506
+ globalThis[UI_LOGGER_KEY] = logger;
2507
+ const module = await import(file.href);
2508
+ if (typeof module.handler !== "function") throw new Error("handler.js has no `handler`");
2509
+ settle.resolve(module.handler);
2510
+ logger.debug(`web UI loaded from ${file.pathname}`);
2511
+ } catch (error) {
2512
+ logger.error(`web UI failed to start: ${error instanceof Error ? error.message : String(error)}`);
2513
+ settle.reject(error);
2514
+ }
2515
+ }
2516
+ };
2517
+ }
2518
+ /**
2519
+ * Where the BFF reaches the bridge's HTTP API: over loopback, whatever address it listens on.
2520
+ */
2521
+ function bridgeApiUrl(host, port) {
2522
+ return `http://${hostPort(host === "::" ? "::1" : isWildcard(host) ? "127.0.0.1" : host, port)}`;
2523
+ }
2524
+ // src/adapters/in/tcp/text-to-socket-parser.ts
2525
+ const LF = 10;
2526
+ const CR = 13;
2527
+ const HEADER = /^voice=(\S.*)$/;
2528
+ /**
2529
+ * Parser for the `text-to-socket` wire format
2530
+ * (docs/implementation/tcp-capture.md#framing-and-decoding), one instance per connection. Bytes are
2531
+ * split at `\n` *before* decoding, so a multi-byte character split across two TCP packets is
2532
+ * decoded correctly.
2533
+ */
2534
+ var TextToSocketParser = class {
2535
+ maxLineBytes;
2536
+ events;
2537
+ decoder;
2538
+ pending = [];
2539
+ pendingBytes = 0;
2540
+ /** After a cut: drop bytes until the next `\n`. */
2541
+ discarding = false;
2542
+ firstLine = true;
2543
+ constructor(encoding, maxLineBytes, events) {
2544
+ this.maxLineBytes = maxLineBytes;
2545
+ this.events = events;
2546
+ this.decoder = new TextDecoder$1(encoding);
2547
+ }
2548
+ push(chunk) {
2549
+ let start = 0;
2550
+ while (start < chunk.length) {
2551
+ const newline = chunk.indexOf(LF, start);
2552
+ const end = newline === -1 ? chunk.length : newline;
2553
+ this.append(chunk.subarray(start, end));
2554
+ if (newline === -1) return;
2555
+ this.completeLine();
2412
2556
  start = newline + 1;
2413
2557
  }
2414
2558
  }
@@ -2569,42 +2713,62 @@ var FsConfigStore = class {
2569
2713
  constructor(location) {
2570
2714
  this.location = location;
2571
2715
  }
2572
- async load() {
2716
+ async load(onWarning) {
2573
2717
  const text = await this.read(this.location);
2574
2718
  if (text === void 0) return void 0;
2575
2719
  try {
2576
2720
  return parseJson(text);
2577
2721
  } catch (error) {
2578
2722
  const backup = await this.readBackup();
2579
- if (backup !== void 0) return backup;
2580
- throw new Error(`The config file ${this.location} is not valid JSON: ${error.message}`, { cause: error });
2723
+ if (isBlank(text) && backup !== void 0) {
2724
+ onWarning?.(`The config file ${this.location} is empty: using the previous version, ${this.location}.bak`);
2725
+ return backup;
2726
+ }
2727
+ const hint = backup === void 0 ? "" : `. Fix it, or copy the previous version, ${this.location}.bak, over it`;
2728
+ throw new Error(`The config file ${this.location} is not valid JSON: ${error.message}${hint}`, { cause: error });
2581
2729
  }
2582
2730
  }
2583
2731
  /**
2584
2732
  * Writes a temporary file, flushes it to disk and renames it, so a crash never leaves half a
2585
- * file. The previous file is kept as `config.json.bak` for `load` to fall back on.
2733
+ * file. The previous file is kept (`keepPrevious`).
2586
2734
  */
2587
- async save(file) {
2588
- await fs.mkdir(path.dirname(this.location), { recursive: true });
2735
+ async save(file, onWarning) {
2736
+ await fs$1.mkdir(path.dirname(this.location), { recursive: true });
2589
2737
  const temporary = `${this.location}.${process.pid}.tmp`;
2590
2738
  try {
2591
- const handle = await fs.open(temporary, "w");
2739
+ const handle = await fs$1.open(temporary, "w");
2592
2740
  try {
2593
2741
  await handle.writeFile(`${JSON.stringify(file, null, 2)}\n`, "utf8");
2594
2742
  await handle.sync();
2595
2743
  } finally {
2596
2744
  await handle.close();
2597
2745
  }
2598
- if (await this.isValid(this.location)) await fs.copyFile(this.location, `${this.location}.bak`);
2599
- await fs.rename(temporary, this.location);
2746
+ await this.keepPrevious(onWarning);
2747
+ await fs$1.rename(temporary, this.location);
2600
2748
  } catch (error) {
2601
- await fs.rm(temporary, { force: true });
2749
+ await fs$1.rm(temporary, { force: true });
2602
2750
  throw error;
2603
2751
  }
2604
2752
  }
2753
+ /**
2754
+ * Keeps the file a save is about to replace: one that parses as `config.json.bak`, for `load`
2755
+ * to fall back on, so a broken one never overwrites a good one. A broken one (edited while the
2756
+ * bridge ran) as `config.json.broken`. A blank one holds nothing to keep.
2757
+ */
2758
+ async keepPrevious(onWarning) {
2759
+ const text = await this.read(this.location);
2760
+ if (text === void 0 || isBlank(text)) return;
2761
+ if (isJson(text)) {
2762
+ await fs$1.copyFile(this.location, `${this.location}.bak`);
2763
+ return;
2764
+ }
2765
+ const kept = `${this.location}.broken`;
2766
+ await fs$1.copyFile(this.location, kept);
2767
+ onWarning?.(`The config file ${this.location} was not valid JSON: kept as ${kept} before saving over it`);
2768
+ }
2605
2769
  async read(file) {
2606
2770
  try {
2607
- return await fs.readFile(file, "utf8");
2771
+ return await fs$1.readFile(file, "utf8");
2608
2772
  } catch (error) {
2609
2773
  if (error.code === "ENOENT") return void 0;
2610
2774
  throw new Error(`Cannot read the config file ${file}: ${error.message}`, { cause: error });
@@ -2618,21 +2782,133 @@ var FsConfigStore = class {
2618
2782
  return;
2619
2783
  }
2620
2784
  }
2621
- async isValid(file) {
2622
- try {
2623
- const text = await this.read(file);
2624
- if (text === void 0) return false;
2625
- parseJson(text);
2626
- return true;
2627
- } catch {
2628
- return false;
2629
- }
2630
- }
2631
2785
  };
2632
2786
  /** `JSON.parse` that accepts a leading byte order mark (Notepad and PowerShell write one). */
2633
2787
  function parseJson(text) {
2634
2788
  return JSON.parse(text.replace(/^\uFEFF/, ""));
2635
2789
  }
2790
+ function isJson(text) {
2791
+ try {
2792
+ parseJson(text);
2793
+ return true;
2794
+ } catch {
2795
+ return false;
2796
+ }
2797
+ }
2798
+ /** Empty, or only white space and NUL bytes: what a crash can leave of a file. */
2799
+ function isBlank(text) {
2800
+ return [...text].every((char) => char === "\0" || char.trim() === "");
2801
+ }
2802
+ // src/adapters/out/log/async-console.ts
2803
+ const MAX_PENDING_BYTES = 1048576;
2804
+ const FLUSH_TIMEOUT_MS = 1e3;
2805
+ /**
2806
+ * Hands text to `channel` without ever blocking. While the console is stuck, text piles up to
2807
+ * `maxPendingBytes`, then new lines are dropped (the log file keeps everything). When the console
2808
+ * takes text again, a line says how many were dropped.
2809
+ */
2810
+ function createAsyncConsole(options) {
2811
+ const { channel, fallback, maxPendingBytes = MAX_PENDING_BYTES } = options;
2812
+ let pending = 0;
2813
+ let dropped = 0;
2814
+ let failed = false;
2815
+ let nextFlush = 0;
2816
+ const waiting = /* @__PURE__ */ new Map();
2817
+ channel.onMessage((message) => {
2818
+ if ("written" in message) {
2819
+ pending = Math.max(0, pending - message.written);
2820
+ return;
2821
+ }
2822
+ waiting.get(message.flushed)?.();
2823
+ });
2824
+ channel.onFailure(() => {
2825
+ failed = true;
2826
+ for (const done of waiting.values()) done();
2827
+ });
2828
+ return {
2829
+ write(text) {
2830
+ if (failed) return fallback(text);
2831
+ if (pending >= maxPendingBytes) {
2832
+ dropped += 1;
2833
+ return;
2834
+ }
2835
+ if (dropped > 0) {
2836
+ const notice = `console output was blocked, ${dropped} lines dropped (see the log file)\n`;
2837
+ dropped = 0;
2838
+ pending += Buffer.byteLength(notice);
2839
+ channel.post(notice);
2840
+ }
2841
+ pending += Buffer.byteLength(text);
2842
+ channel.post(text);
2843
+ },
2844
+ flush(timeoutMs = FLUSH_TIMEOUT_MS) {
2845
+ if (failed) return Promise.resolve();
2846
+ return new Promise((resolve) => {
2847
+ const id = nextFlush++;
2848
+ const finish = () => {
2849
+ clearTimeout(timer);
2850
+ waiting.delete(id);
2851
+ resolve();
2852
+ };
2853
+ const timer = setTimeout(finish, timeoutMs);
2854
+ waiting.set(id, finish);
2855
+ channel.requestFlush(id);
2856
+ });
2857
+ }
2858
+ };
2859
+ }
2860
+ const WORKER_SOURCE = `
2861
+ const { parentPort, workerData } = require('node:worker_threads');
2862
+ const tty = require('node:tty');
2863
+ const stream = new tty.WriteStream(workerData.fd);
2864
+ stream.on('error', () => {});
2865
+ parentPort.on('message', (message) => {
2866
+ if (message.flush !== undefined) {
2867
+ stream.write('', () => parentPort.postMessage({ flushed: message.flush }));
2868
+ return;
2869
+ }
2870
+ const bytes = Buffer.byteLength(message.text);
2871
+ stream.write(message.text, () => parentPort.postMessage({ written: bytes }));
2872
+ });
2873
+ `;
2874
+ function workerChannel(fd) {
2875
+ const worker = new Worker(WORKER_SOURCE, {
2876
+ eval: true,
2877
+ workerData: { fd }
2878
+ });
2879
+ worker.unref();
2880
+ return {
2881
+ post: (text) => worker.postMessage({ text }),
2882
+ requestFlush: (id) => worker.postMessage({ flush: id }),
2883
+ onMessage: (listener) => worker.on("message", listener),
2884
+ onFailure: (listener) => {
2885
+ worker.on("error", listener);
2886
+ worker.on("exit", listener);
2887
+ }
2888
+ };
2889
+ }
2890
+ let console_;
2891
+ /**
2892
+ * A writer for stdout that can't block the bridge, or `undefined` when stdout is not a terminal
2893
+ * (a pipe or file has no selection mode, and `process.stdout` is fine there).
2894
+ */
2895
+ function terminalWriter(stream = process.stdout) {
2896
+ if (stream.isTTY !== true) return void 0;
2897
+ try {
2898
+ console_ ??= createAsyncConsole({
2899
+ channel: workerChannel(1),
2900
+ fallback: (text) => void stream.write(text)
2901
+ });
2902
+ } catch {
2903
+ return;
2904
+ }
2905
+ const writer = console_;
2906
+ return (text) => writer.write(text);
2907
+ }
2908
+ /** Waits (briefly) until the terminal writer has written everything. */
2909
+ function flushTerminal() {
2910
+ return console_?.flush() ?? Promise.resolve();
2911
+ }
2636
2912
  // src/adapters/out/memory/in-process-event-bus.ts
2637
2913
  /** Synchronous in-process event bus. A failing listener doesn't stop the others. */
2638
2914
  var InProcessEventBus = class {
@@ -2714,49 +2990,229 @@ function defaultPlaywrightDir(platform = process.platform, env = process.env, ho
2714
2990
  home
2715
2991
  });
2716
2992
  }
2717
- // src/application/services/bridge-lifecycle-service.ts
2718
- /** The bridge's state from `starting` over `ready` to `stopping`, and the shutdown order. */
2719
- var BridgeLifecycleService = class {
2720
- deps;
2721
- stopping;
2722
- constructor(deps) {
2723
- this.deps = deps;
2724
- }
2725
- start() {
2726
- this.deps.startServices().then(() => {
2727
- if (this.stopping !== void 0) return;
2728
- this.deps.state.setState("ready");
2729
- this.deps.logger.info(this.deps.readyMessage());
2730
- });
2731
- }
2732
- stop(reason) {
2733
- this.stopping ??= this.shutdown(reason);
2734
- return this.stopping;
2735
- }
2736
- async shutdown(reason) {
2737
- const { state, pending, stopOrder, logger } = this.deps;
2738
- state.setState("stopping");
2739
- logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
2740
- for (const part of pending) part.shutdown();
2741
- const errors = [];
2742
- for (const part of stopOrder) try {
2743
- await part.stop();
2744
- } catch (error) {
2745
- logger.error(`shutdown failed: ${String(error)}`);
2746
- errors.push(error);
2747
- }
2748
- if (errors.length === 1) throw errors[0];
2749
- if (errors.length > 1) throw new AggregateError(errors, "shutdown failed");
2750
- logger.info("stopped");
2751
- }
2993
+ // src/adapters/out/process/process-tree.ts
2994
+ /** How long the process group gets after `SIGTERM` before `SIGKILL` (not on Windows). */
2995
+ const TERM_GRACE_MS = 3e3;
2996
+ /**
2997
+ * Spawn options for a child whose whole tree `killTree` can end. On POSIX the child leads its own
2998
+ * process group. On Windows that isn't needed (`taskkill /T` walks the tree), and `detached`
2999
+ * there would open a new console window.
3000
+ */
3001
+ const treeSpawnOptions = {
3002
+ detached: process.platform !== "win32",
3003
+ windowsHide: true
2752
3004
  };
2753
- // src/application/services/child-services-service.ts
2754
- /** Runs the Playwright server and Playwright MCP as the configuration says. */
2755
- var ChildServicesService = class {
2756
- deps;
2757
- constructor(deps) {
2758
- this.deps = deps;
2759
- }
3005
+ function hasExited(child) {
3006
+ return child.exitCode !== null || child.signalCode !== null;
3007
+ }
3008
+ function killGroup(pid, signal) {
3009
+ try {
3010
+ process.kill(-pid, signal);
3011
+ } catch {}
3012
+ }
3013
+ /** Resolves after `ms`, or when `promise` settles, whichever comes first. */
3014
+ async function within(promise, ms) {
3015
+ let timer;
3016
+ await Promise.race([promise.catch(() => void 0), new Promise((resolve) => timer = setTimeout(resolve, ms))]);
3017
+ clearTimeout(timer);
3018
+ }
3019
+ const exec = (file, args, timeoutMs) => new Promise((resolve) => {
3020
+ execFile(file, [...args], {
3021
+ windowsHide: true,
3022
+ timeout: timeoutMs,
3023
+ killSignal: "SIGKILL"
3024
+ }, (error, stdout) => resolve({
3025
+ ok: error === null,
3026
+ stdout: String(stdout)
3027
+ }));
3028
+ });
3029
+ const TOOL_TIMEOUT_MS = 5e3;
3030
+ /** Trees that may still have processes, for `killAllTreesNow`. */
3031
+ const trees = /* @__PURE__ */ new Set();
3032
+ /**
3033
+ * Remembers a child spawned with `treeSpawnOptions`, so `killAllTreesNow` can end it when the
3034
+ * bridge has to exit without stopping gracefully. `killTree` forgets it; so does `releaseTree`.
3035
+ */
3036
+ function trackTree(child) {
3037
+ trees.add(child);
3038
+ }
3039
+ /** Forgets a child that ended on its own and left nothing behind to kill. */
3040
+ function releaseTree(child) {
3041
+ trees.delete(child);
3042
+ }
3043
+ /**
3044
+ * Ends every tracked tree at once and synchronously, without waiting for anything. For a forced
3045
+ * exit (watchdog, second Ctrl+C), when the graceful `killTree` has no time left: exiting without
3046
+ * this leaves the browsers of the Playwright server behind.
3047
+ */
3048
+ function killAllTreesNow(platform = process.platform) {
3049
+ for (const child of trees) {
3050
+ const { pid } = child;
3051
+ if (pid === void 0) continue;
3052
+ if (platform === "win32") spawnSync("taskkill", [
3053
+ "/T",
3054
+ "/F",
3055
+ "/PID",
3056
+ String(pid)
3057
+ ], {
3058
+ windowsHide: true,
3059
+ stdio: "ignore",
3060
+ timeout: TOOL_TIMEOUT_MS
3061
+ });
3062
+ else killGroup(pid, "SIGKILL");
3063
+ }
3064
+ trees.clear();
3065
+ }
3066
+ /**
3067
+ * Kills `child` and every process it started (docs/usage/operations.md#shutdown). On Windows,
3068
+ * `taskkill /T /F` limited to a few seconds (killing a process there doesn't kill its children;
3069
+ * the orphans of a child that already died are not hunted down, see
3070
+ * docs/implementation/decisions.md#child-process-trees-are-killed-by-the-bridge-not-the-os).
3071
+ * Elsewhere `SIGTERM` to the process group, then `SIGKILL` to whatever is left. Resolves
3072
+ * once `child` has exited, or after a deadline if it can't be killed. Never rejects.
3073
+ * `child` must have been spawned with `treeSpawnOptions`.
3074
+ */
3075
+ async function killTree(child, options = {}) {
3076
+ const { platform = process.platform, toolTimeoutMs = TOOL_TIMEOUT_MS } = options;
3077
+ const { exitTimeoutMs = TOOL_TIMEOUT_MS, exec: run = exec } = options;
3078
+ const { pid } = child;
3079
+ try {
3080
+ if (pid === void 0) return;
3081
+ const exited = hasExited(child) ? Promise.resolve() : once(child, "exit");
3082
+ if (platform === "win32") {
3083
+ if (!hasExited(child)) await run("taskkill", [
3084
+ "/T",
3085
+ "/F",
3086
+ "/PID",
3087
+ String(pid)
3088
+ ], toolTimeoutMs);
3089
+ await within(exited, exitTimeoutMs);
3090
+ return;
3091
+ }
3092
+ killGroup(pid, "SIGTERM");
3093
+ await within(exited, TERM_GRACE_MS);
3094
+ killGroup(pid, "SIGKILL");
3095
+ await within(exited, exitTimeoutMs);
3096
+ } finally {
3097
+ trees.delete(child);
3098
+ }
3099
+ }
3100
+ /** Writes each line of the child's stdout as `info` and of its stderr as `warn`. */
3101
+ function pipeLines(child, output) {
3102
+ if (child.stdout) readline.createInterface({
3103
+ input: child.stdout,
3104
+ crlfDelay: Infinity
3105
+ }).on("line", (line) => output.info(line));
3106
+ if (child.stderr) readline.createInterface({
3107
+ input: child.stderr,
3108
+ crlfDelay: Infinity
3109
+ }).on("line", (line) => output.warn(line));
3110
+ }
3111
+ // src/application/shared/abort.ts
3112
+ /** The error an aborted signal ends a pending request with: its reason, if that is an error. */
3113
+ function abortReason(signal) {
3114
+ const reason = signal.reason;
3115
+ return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
3116
+ }
3117
+ /**
3118
+ * The reason of the bridge's shutdown signal, which pending requests (waits, captures, input) end
3119
+ * with.
3120
+ */
3121
+ const shuttingDown = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
3122
+ /**
3123
+ * The signal of one request: aborts with the reason of the first of `signals` that aborts, or at
3124
+ * once if one already has (then the first of them in the list). `undefined` ones are skipped.
3125
+ * `dispose` takes the listeners off them again: call it when the request ends, or a long-lived
3126
+ * signal such as the shutdown's keeps them. Not `AbortSignal.any`, which keeps memory for every
3127
+ * signal made of a long-lived one (docs/implementation/decisions.md#one-shutdown-signal).
3128
+ */
3129
+ function linkSignals(...signals) {
3130
+ const controller = new AbortController();
3131
+ const removers = [];
3132
+ for (const source of signals) {
3133
+ if (source === void 0) continue;
3134
+ const abort = () => controller.abort(abortReason(source));
3135
+ if (source.aborted) {
3136
+ abort();
3137
+ break;
3138
+ }
3139
+ source.addEventListener("abort", abort, { once: true });
3140
+ removers.push(() => source.removeEventListener("abort", abort));
3141
+ }
3142
+ return {
3143
+ signal: controller.signal,
3144
+ dispose: () => {
3145
+ for (const remove of removers) remove();
3146
+ }
3147
+ };
3148
+ }
3149
+ // src/application/services/bridge-lifecycle-service.ts
3150
+ /**
3151
+ * The bridge's state from `starting` over `ready` to `stopping`, and the order of startup and
3152
+ * shutdown.
3153
+ */
3154
+ var BridgeLifecycleService = class {
3155
+ deps;
3156
+ stopping;
3157
+ constructor(deps) {
3158
+ this.deps = deps;
3159
+ }
3160
+ async start() {
3161
+ const ports = await this.listen();
3162
+ await this.deps.httpListening(ports.http);
3163
+ this.deps.services.startEnabled().then(() => {
3164
+ if (this.stopping !== void 0) return;
3165
+ this.deps.state.setState("ready");
3166
+ this.deps.logger.info(this.deps.readyMessage(ports));
3167
+ });
3168
+ return ports;
3169
+ }
3170
+ stop(reason) {
3171
+ this.stopping ??= this.shutdown(reason);
3172
+ return this.stopping;
3173
+ }
3174
+ /** TCP first, so no speech is lost while the rest starts. It stops again if HTTP fails. */
3175
+ async listen() {
3176
+ const { tcp, http } = this.deps;
3177
+ const tcpPort = await tcp.start();
3178
+ try {
3179
+ return {
3180
+ tcp: tcpPort,
3181
+ http: await http.start()
3182
+ };
3183
+ } catch (error) {
3184
+ await tcp.stop();
3185
+ throw error;
3186
+ }
3187
+ }
3188
+ async shutdown(reason) {
3189
+ const { state, shutdown, tcp, http, services, logger } = this.deps;
3190
+ state.setState("stopping");
3191
+ logger.info(reason === void 0 ? "stopping" : `stopping (${reason})`);
3192
+ shutdown.abort(shuttingDown());
3193
+ const errors = [];
3194
+ for (const stop of [
3195
+ () => http.stop(),
3196
+ () => tcp.stop(),
3197
+ () => services.stopAll()
3198
+ ]) try {
3199
+ await stop();
3200
+ } catch (error) {
3201
+ logger.error(`shutdown failed: ${String(error)}`);
3202
+ errors.push(error);
3203
+ }
3204
+ if (errors.length === 1) throw errors[0];
3205
+ if (errors.length > 1) throw new AggregateError(errors, "shutdown failed");
3206
+ logger.info("stopped");
3207
+ }
3208
+ };
3209
+ // src/application/services/child-services-service.ts
3210
+ /** Runs the Playwright server and Playwright MCP as the configuration says. */
3211
+ var ChildServicesService = class {
3212
+ deps;
3213
+ constructor(deps) {
3214
+ this.deps = deps;
3215
+ }
2760
3216
  async startEnabled() {
2761
3217
  const config = this.deps.config();
2762
3218
  const enabled = SERVICE_NAMES.filter((name) => config[name].enabled);
@@ -2975,7 +3431,7 @@ var ConfigService = class {
2975
3431
  const patched = configFields(changes);
2976
3432
  if ([...patched].some(([field, value]) => !same(saved.get(field), value))) {
2977
3433
  const file = mergePatch(this.file, changes);
2978
- await this.deps.store.save(withUnknownSettings(file, this.deps.unknownSettings ?? {}));
3434
+ await this.deps.store.save(withUnknownSettings(file, this.deps.unknownSettings ?? {}), (warning) => this.deps.logger.warn(warning));
2979
3435
  this.file = file;
2980
3436
  }
2981
3437
  this.saved = merged;
@@ -2995,14 +3451,6 @@ var ConfigService = class {
2995
3451
  // src/application/ports/in/capture-input.ts
2996
3452
  /** Defaults and ranges of the capture options, in milliseconds. */
2997
3453
  const CAPTURE_LIMITS = API_LIMITS.capture;
2998
- // src/application/shared/abort.ts
2999
- /** The error an aborted signal ends a pending request with: its reason, if that is an error. */
3000
- function abortReason(signal) {
3001
- const reason = signal.reason;
3002
- return reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
3003
- }
3004
- /** What pending requests (waits, captures) end with when the bridge shuts down. */
3005
- const shuttingDown = () => new AppError("SERVICE_UNAVAILABLE", "The bridge is shutting down");
3006
3454
  // src/domain/seq-cursor.ts
3007
3455
  /**
3008
3456
  * A follower's position in the speech log. `SpeechLog` gives every entry the next `seq`, strictly
@@ -3150,8 +3598,6 @@ const toError = (error) => error instanceof Error ? error : new Error(String(err
3150
3598
  */
3151
3599
  var InputCaptureService = class {
3152
3600
  deps;
3153
- pending = /* @__PURE__ */ new Set();
3154
- closed = false;
3155
3601
  constructor(deps) {
3156
3602
  this.deps = deps;
3157
3603
  }
@@ -3161,22 +3607,11 @@ var InputCaptureService = class {
3161
3607
  pressKeys({ capture, signal, ...request }) {
3162
3608
  return this.run(capture, signal, (hooks) => this.deps.input.pressKeys(request, hooks));
3163
3609
  }
3164
- /**
3165
- * Rejects all pending captures, and every later one, with `SERVICE_UNAVAILABLE`. The `Shutdown`
3166
- * lifecycle port: only the composition root calls it.
3167
- */
3168
- shutdown() {
3169
- this.closed = true;
3170
- for (const stop of [...this.pending]) stop.abort(shuttingDown());
3171
- }
3172
3610
  async run(capture, signal, send) {
3173
- if (this.closed) throw shuttingDown();
3611
+ this.deps.shutdown.throwIfAborted();
3174
3612
  const options = parseOptions(capture);
3175
3613
  if (signal?.aborted) throw abortReason(signal);
3176
- const stop = new AbortController();
3177
- const onAbort = () => stop.abort(abortReason(signal));
3178
- signal?.addEventListener("abort", onAbort, { once: true });
3179
- this.pending.add(stop);
3614
+ const stop = linkSignals(this.deps.shutdown, signal);
3180
3615
  try {
3181
3616
  let startSeq = 0;
3182
3617
  return {
@@ -3191,8 +3626,7 @@ var InputCaptureService = class {
3191
3626
  ...await this.record(startSeq, options, stop.signal)
3192
3627
  };
3193
3628
  } finally {
3194
- signal?.removeEventListener("abort", onAbort);
3195
- this.pending.delete(stop);
3629
+ stop.dispose();
3196
3630
  }
3197
3631
  }
3198
3632
  /**
@@ -3369,11 +3803,6 @@ function parseKeyChord(chord) {
3369
3803
  }
3370
3804
  // src/application/services/native-input-service.ts
3371
3805
  const { coordinate, delayMs, maxKeys } = API_LIMITS.input;
3372
- const BUTTONS = [
3373
- "left",
3374
- "right",
3375
- "middle"
3376
- ];
3377
3806
  function checkCoordinate(field, value) {
3378
3807
  if (!Number.isInteger(value) || Math.abs(value) > coordinate) throw invalidField(field, `must be an integer from -${coordinate} to ${coordinate}`);
3379
3808
  }
@@ -3398,16 +3827,13 @@ function parseKeys(keys) {
3398
3827
  var NativeInputService = class {
3399
3828
  deps;
3400
3829
  queue = Promise.resolve();
3401
- /** One per queued or running request. */
3402
- pending = /* @__PURE__ */ new Set();
3403
- closed = false;
3404
3830
  constructor(deps) {
3405
3831
  this.deps = deps;
3406
3832
  }
3407
3833
  async click({ x, y, button = "left" }, hooks = {}) {
3408
3834
  checkCoordinate("x", x);
3409
3835
  checkCoordinate("y", y);
3410
- if (!BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
3836
+ if (!MOUSE_BUTTONS.includes(button)) throw invalidField("button", "must be left, right or middle");
3411
3837
  let sent = false;
3412
3838
  return this.enqueue(async (signal) => {
3413
3839
  await hooks.beforeInject?.();
@@ -3509,21 +3935,31 @@ var NativeInputService = class {
3509
3935
  held.push(modifier);
3510
3936
  }
3511
3937
  await injector.keyTap(key);
3512
- } finally {
3513
- for (const modifier of held.reverse()) await injector.keyUp(modifier);
3938
+ } catch (error) {
3939
+ await this.release(held);
3940
+ throw error;
3514
3941
  }
3515
- }
3516
- exclusive(task, signal) {
3517
- return this.enqueue(task, signal);
3942
+ const failed = await this.release(held);
3943
+ if (failed !== void 0) throw failed;
3518
3944
  }
3519
3945
  /**
3520
- * Stops the running input before its next chord and rejects it, the queued input and every later
3521
- * one with `SERVICE_UNAVAILABLE`. The `Shutdown` lifecycle port: only the composition root calls
3522
- * it.
3946
+ * Releases the held keys, the last one first. Every one is tried even if another fails: a
3947
+ * modifier left down would change all later input on the desktop. Resolves with the first
3948
+ * failure, `undefined` if all were released.
3523
3949
  */
3524
- shutdown() {
3525
- this.closed = true;
3526
- for (const stop of [...this.pending]) stop.abort(shuttingDown());
3950
+ async release(held) {
3951
+ let first;
3952
+ for (const key of [...held].reverse()) try {
3953
+ await this.deps.injector.keyUp(key);
3954
+ } catch (error) {
3955
+ const failure = error instanceof Error ? error : new Error(String(error));
3956
+ this.deps.logger.error(`${key} could not be released, it may still be held down (${failure.message})`);
3957
+ first ??= failure;
3958
+ }
3959
+ return first;
3960
+ }
3961
+ exclusive(task, signal) {
3962
+ return this.enqueue(task, signal);
3527
3963
  }
3528
3964
  /**
3529
3965
  * Runs `task` after the earlier ones; a failed task doesn't stop the later ones. `task` isn't
@@ -3531,12 +3967,7 @@ var NativeInputService = class {
3531
3967
  * request leaves unsent, for the log.
3532
3968
  */
3533
3969
  async enqueue(task, signal, unsent = () => void 0) {
3534
- const stop = new AbortController();
3535
- const onAbort = () => stop.abort(abortReason(signal));
3536
- if (this.closed) stop.abort(shuttingDown());
3537
- else if (signal?.aborted) onAbort();
3538
- else signal?.addEventListener("abort", onAbort, { once: true });
3539
- this.pending.add(stop);
3970
+ const stop = linkSignals(this.deps.shutdown, signal);
3540
3971
  const run = this.queue.then(() => {
3541
3972
  stop.signal.throwIfAborted();
3542
3973
  return task(stop.signal);
@@ -3549,8 +3980,7 @@ var NativeInputService = class {
3549
3980
  if (what !== void 0) this.deps.logger.warn(`${what} (${abortReason(stop.signal).message})`);
3550
3981
  throw error;
3551
3982
  } finally {
3552
- signal?.removeEventListener("abort", onAbort);
3553
- this.pending.delete(stop);
3983
+ stop.dispose();
3554
3984
  }
3555
3985
  }
3556
3986
  };
@@ -3735,8 +4165,8 @@ function markerLabel(label) {
3735
4165
  }
3736
4166
  // src/application/services/status-service.ts
3737
4167
  /**
3738
- * `GET /api/v1/status`. The composition root moves the state from `starting` to `ready` through
3739
- * `BridgeStateControl`.
4168
+ * `GET /api/v1/status`. `BridgeLifecycleService` moves the state from `starting` to `ready` and
4169
+ * `stopping` through `BridgeStateControl`.
3740
4170
  */
3741
4171
  var StatusService = class {
3742
4172
  deps;
@@ -3765,7 +4195,8 @@ var StatusService = class {
3765
4195
  host: listener?.host ?? tcp.host,
3766
4196
  port: listener?.port ?? tcp.port,
3767
4197
  encoding: listener?.encoding ?? tcp.encoding,
3768
- connections
4198
+ connections,
4199
+ lastSpeechAt: log.lastSpeechAt ?? null
3769
4200
  },
3770
4201
  buffer: log.stats(),
3771
4202
  services: Object.fromEntries(SERVICE_NAMES.map((name) => [name, supervisors[name].status()])),
@@ -3870,13 +4301,11 @@ var LastSeen = class {
3870
4301
  */
3871
4302
  var WaitForSpeechService = class {
3872
4303
  deps;
3873
- pending = /* @__PURE__ */ new Set();
3874
- closed = false;
3875
4304
  constructor(deps) {
3876
4305
  this.deps = deps;
3877
4306
  }
3878
4307
  async wait(options) {
3879
- if (this.closed) throw shuttingDown();
4308
+ this.deps.shutdown.throwIfAborted();
3880
4309
  const { signal } = options;
3881
4310
  const since = intOption("since", options.since, {
3882
4311
  fallback: 0,
@@ -3895,18 +4324,18 @@ var WaitForSpeechService = class {
3895
4324
  const seen = new LastSeen();
3896
4325
  let done = false;
3897
4326
  let stop;
4327
+ /** The client's signal and the shutdown's. */
4328
+ const ended = linkSignals(this.deps.shutdown, signal);
3898
4329
  const finish = () => {
3899
4330
  done = true;
3900
4331
  stop?.();
3901
4332
  timer.abort();
3902
- signal?.removeEventListener("abort", onAbort);
3903
- this.pending.delete(fail);
4333
+ ended.dispose();
3904
4334
  };
3905
4335
  const fail = (error) => {
3906
4336
  finish();
3907
4337
  reject(error);
3908
4338
  };
3909
- const onAbort = () => fail(abortReason(signal));
3910
4339
  const timer = new AbortController();
3911
4340
  const startTimer = () => {
3912
4341
  if (done) return;
@@ -3919,8 +4348,7 @@ var WaitForSpeechService = class {
3919
4348
  });
3920
4349
  }, () => {});
3921
4350
  };
3922
- signal?.addEventListener("abort", onAbort, { once: true });
3923
- this.pending.add(fail);
4351
+ ended.signal.addEventListener("abort", () => fail(abortReason(ended.signal)), { once: true });
3924
4352
  const failed = (error) => fail(error instanceof Error ? error : new Error(String(error)));
3925
4353
  try {
3926
4354
  stop = followLog(this.deps, {
@@ -3946,40 +4374,7 @@ var WaitForSpeechService = class {
3946
4374
  }
3947
4375
  });
3948
4376
  }
3949
- /**
3950
- * Rejects all pending waits, and every later one, with `SERVICE_UNAVAILABLE`. The `Shutdown`
3951
- * lifecycle port, not part of `WaitForSpeech`: only the composition root calls it.
3952
- */
3953
- shutdown() {
3954
- this.closed = true;
3955
- for (const fail of [...this.pending]) fail(shuttingDown());
3956
- }
3957
4377
  };
3958
- // src/composition/lifecycle.ts
3959
- /**
3960
- * Startup order (docs/usage/operations.md#startup): the TCP listener first, so no speech is lost
3961
- * while the rest starts, then HTTP. A failure is logged, and the TCP listener stops if HTTP fails.
3962
- */
3963
- async function startListeners(tcp, http, config, logger) {
3964
- const failed = (error) => logger.error(error instanceof ListenError ? error.message : String(error));
3965
- let tcpPort;
3966
- try {
3967
- tcpPort = await tcp.start(config.tcp);
3968
- } catch (error) {
3969
- failed(error);
3970
- throw error;
3971
- }
3972
- try {
3973
- return {
3974
- tcp: tcpPort,
3975
- http: await http.start(config.http)
3976
- };
3977
- } catch (error) {
3978
- failed(error);
3979
- await tcp.stop();
3980
- throw error;
3981
- }
3982
- }
3983
4378
  // src/composition/load-config.ts
3984
4379
  /** A setting from flags, the environment or the config file is invalid. Nothing was started. */
3985
4380
  var ConfigError = class extends Error {
@@ -3995,12 +4390,14 @@ function checked(patch, origin) {
3995
4390
  }
3996
4391
  /**
3997
4392
  * Defaults, then the config file, then flags and environment variables. Settings of the file this
3998
- * bridge doesn't know are left out of `config` and `file` and returned in `unknown`.
4393
+ * bridge doesn't know are left out of `config` and `file` and returned in `unknown`. The store's
4394
+ * `warnings` are returned too: there is no log yet, it is built from the result.
3999
4395
  */
4000
4396
  async function loadConfig(store, overridesPatch, sourceOf) {
4001
4397
  let saved;
4398
+ const warnings = [];
4002
4399
  try {
4003
- saved = await store.load();
4400
+ saved = await store.load((message) => warnings.push(message));
4004
4401
  } catch (error) {
4005
4402
  throw new ConfigError(error.message, { cause: error });
4006
4403
  }
@@ -4018,7 +4415,8 @@ async function loadConfig(store, overridesPatch, sourceOf) {
4018
4415
  file,
4019
4416
  overrides,
4020
4417
  unknown,
4021
- ignored
4418
+ ignored,
4419
+ warnings
4022
4420
  };
4023
4421
  }
4024
4422
  // src/composition/summary.ts
@@ -4550,116 +4948,6 @@ var BridgeLog = class {
4550
4948
  }
4551
4949
  }
4552
4950
  };
4553
- // src/adapters/out/log/async-console.ts
4554
- const MAX_PENDING_BYTES = 1048576;
4555
- const FLUSH_TIMEOUT_MS = 1e3;
4556
- /**
4557
- * Hands text to `channel` without ever blocking. While the console is stuck, text piles up to
4558
- * `maxPendingBytes`, then new lines are dropped (the log file keeps everything). When the console
4559
- * takes text again, a line says how many were dropped.
4560
- */
4561
- function createAsyncConsole(options) {
4562
- const { channel, fallback, maxPendingBytes = MAX_PENDING_BYTES } = options;
4563
- let pending = 0;
4564
- let dropped = 0;
4565
- let failed = false;
4566
- let nextFlush = 0;
4567
- const waiting = /* @__PURE__ */ new Map();
4568
- channel.onMessage((message) => {
4569
- if ("written" in message) {
4570
- pending = Math.max(0, pending - message.written);
4571
- return;
4572
- }
4573
- waiting.get(message.flushed)?.();
4574
- });
4575
- channel.onFailure(() => {
4576
- failed = true;
4577
- for (const done of waiting.values()) done();
4578
- });
4579
- return {
4580
- write(text) {
4581
- if (failed) return fallback(text);
4582
- if (pending >= maxPendingBytes) {
4583
- dropped += 1;
4584
- return;
4585
- }
4586
- if (dropped > 0) {
4587
- const notice = `console output was blocked, ${dropped} lines dropped (see the log file)\n`;
4588
- dropped = 0;
4589
- pending += Buffer.byteLength(notice);
4590
- channel.post(notice);
4591
- }
4592
- pending += Buffer.byteLength(text);
4593
- channel.post(text);
4594
- },
4595
- flush(timeoutMs = FLUSH_TIMEOUT_MS) {
4596
- if (failed) return Promise.resolve();
4597
- return new Promise((resolve) => {
4598
- const id = nextFlush++;
4599
- const finish = () => {
4600
- clearTimeout(timer);
4601
- waiting.delete(id);
4602
- resolve();
4603
- };
4604
- const timer = setTimeout(finish, timeoutMs);
4605
- waiting.set(id, finish);
4606
- channel.requestFlush(id);
4607
- });
4608
- }
4609
- };
4610
- }
4611
- const WORKER_SOURCE = `
4612
- const { parentPort, workerData } = require('node:worker_threads');
4613
- const tty = require('node:tty');
4614
- const stream = new tty.WriteStream(workerData.fd);
4615
- stream.on('error', () => {});
4616
- parentPort.on('message', (message) => {
4617
- if (message.flush !== undefined) {
4618
- stream.write('', () => parentPort.postMessage({ flushed: message.flush }));
4619
- return;
4620
- }
4621
- const bytes = Buffer.byteLength(message.text);
4622
- stream.write(message.text, () => parentPort.postMessage({ written: bytes }));
4623
- });
4624
- `;
4625
- function workerChannel(fd) {
4626
- const worker = new Worker(WORKER_SOURCE, {
4627
- eval: true,
4628
- workerData: { fd }
4629
- });
4630
- worker.unref();
4631
- return {
4632
- post: (text) => worker.postMessage({ text }),
4633
- requestFlush: (id) => worker.postMessage({ flush: id }),
4634
- onMessage: (listener) => worker.on("message", listener),
4635
- onFailure: (listener) => {
4636
- worker.on("error", listener);
4637
- worker.on("exit", listener);
4638
- }
4639
- };
4640
- }
4641
- let console_;
4642
- /**
4643
- * A writer for stdout that can't block the bridge, or `undefined` when stdout is not a terminal
4644
- * (a pipe or file has no selection mode, and `process.stdout` is fine there).
4645
- */
4646
- function terminalWriter(stream = process.stdout) {
4647
- if (stream.isTTY !== true) return void 0;
4648
- try {
4649
- console_ ??= createAsyncConsole({
4650
- channel: workerChannel(1),
4651
- fallback: (text) => void stream.write(text)
4652
- });
4653
- } catch {
4654
- return;
4655
- }
4656
- const writer = console_;
4657
- return (text) => writer.write(text);
4658
- }
4659
- /** Waits (briefly) until the terminal writer has written everything. */
4660
- function flushTerminal() {
4661
- return console_?.flush() ?? Promise.resolve();
4662
- }
4663
4951
  // src/adapters/out/log/console-sink.ts
4664
4952
  /**
4665
4953
  * Decides whether a console stream gets colours: `NO_COLOR` turns them off, `FORCE_COLOR`
@@ -4684,40 +4972,77 @@ function consoleSink(options = {}) {
4684
4972
  /**
4685
4973
  * Bridge log file (docs/usage/operations.md#logging): no colours, includes the speech channel.
4686
4974
  * Writes synchronously so nothing is lost on a crash. Log volume is small.
4975
+ *
4976
+ * A failure doesn't end the file log. A line that can't be written is lost, and the next one tries
4977
+ * again. A file that can't be rotated keeps growing, and rotation is tried again later.
4687
4978
  */
4688
4979
  function fileSink(file, options = {}) {
4689
4980
  const { maxBytes = 10485760, keep = 5 } = options;
4690
- const onError = options.onError ?? ((error) => process.stderr.write(`screenreader-speech-capture-bridge: log file disabled: ${error.message}\n`));
4691
- let size = 0;
4692
- let failed = false;
4981
+ const onError = options.onError ?? ((error) => process.stderr.write(`screenreader-speech-capture-bridge: ${error.message}\n`));
4982
+ /** `undefined`: unknown, the folder and the size are looked at again before the next write. */
4983
+ let size;
4984
+ let writeFailed = false;
4985
+ let rotateFailed = false;
4986
+ /** After a failed rotation: don't try again before the file has this size. */
4987
+ let rotateFrom = 0;
4988
+ const report = (what, error) => onError(new Error(`cannot ${what} the log file: ${error.message}`, { cause: error }));
4989
+ const failedWrite = (error) => {
4990
+ size = void 0;
4991
+ if (!writeFailed) report("write", error);
4992
+ writeFailed = true;
4993
+ };
4994
+ const open = () => {
4995
+ fs.mkdirSync(path.dirname(file), { recursive: true });
4996
+ return fs.existsSync(file) ? fs.statSync(file).size : 0;
4997
+ };
4998
+ /**
4999
+ * Moves the older files up only as far as the first free number, dropping the oldest when there
5000
+ * is none. So a rotation that fails and is tried again doesn't push out one more file each time.
5001
+ */
5002
+ const rotate = () => {
5003
+ if (keep < 1) {
5004
+ fs.rmSync(file, { force: true });
5005
+ return;
5006
+ }
5007
+ let free = 1;
5008
+ while (free < keep && fs.existsSync(`${file}.${free}`)) free++;
5009
+ fs.rmSync(`${file}.${free}`, { force: true });
5010
+ for (let i = free - 1; i >= 1; i--) fs.renameSync(`${file}.${i}`, `${file}.${i + 1}`);
5011
+ fs.renameSync(file, `${file}.1`);
5012
+ };
5013
+ /** Rotates, and returns the size of the file to write to. */
5014
+ const tryRotate = (current) => {
5015
+ try {
5016
+ rotate();
5017
+ rotateFailed = false;
5018
+ rotateFrom = 0;
5019
+ return 0;
5020
+ } catch (error) {
5021
+ if (!rotateFailed) report("rotate", error);
5022
+ rotateFailed = true;
5023
+ rotateFrom = current + Math.ceil(maxBytes / 10);
5024
+ return current;
5025
+ }
5026
+ };
4693
5027
  try {
4694
- fs$1.mkdirSync(path.dirname(file), { recursive: true });
4695
- size = fs$1.existsSync(file) ? fs$1.statSync(file).size : 0;
5028
+ size = open();
4696
5029
  } catch (error) {
4697
- failed = true;
4698
- onError(error);
5030
+ failedWrite(error);
4699
5031
  }
4700
- const rotate = () => {
4701
- fs$1.rmSync(`${file}.${keep}`, { force: true });
4702
- for (let i = keep - 1; i >= 1; i--) if (fs$1.existsSync(`${file}.${i}`)) fs$1.renameSync(`${file}.${i}`, `${file}.${i + 1}`);
4703
- if (keep >= 1) fs$1.renameSync(file, `${file}.1`);
4704
- else fs$1.rmSync(file, { force: true });
4705
- size = 0;
4706
- };
4707
5032
  return {
4708
5033
  colour: false,
4709
5034
  speech: true,
4710
5035
  write(line) {
4711
- if (failed) return;
4712
5036
  const data = `${line}\n`;
4713
5037
  const bytes = Buffer.byteLength(data);
4714
5038
  try {
4715
- if (size > 0 && size + bytes > maxBytes) rotate();
4716
- fs$1.appendFileSync(file, data);
5039
+ size ??= open();
5040
+ if (size > 0 && size + bytes > maxBytes && size >= rotateFrom) size = tryRotate(size);
5041
+ fs.appendFileSync(file, data);
4717
5042
  size += bytes;
5043
+ writeFailed = false;
4718
5044
  } catch (error) {
4719
- failed = true;
4720
- onError(error);
5045
+ failedWrite(error);
4721
5046
  }
4722
5047
  }
4723
5048
  };
@@ -4787,147 +5112,29 @@ function proxyRoutes(services) {
4787
5112
  upstreamPath: "/mcp",
4788
5113
  scheme: "http",
4789
5114
  target: () => services.reachability("mcp")
4790
- }];
4791
- }
4792
- // src/adapters/shared/net/port-probe.ts
4793
- /** Where to probe a listener on a wildcard host: the loopback address of that family. */
4794
- const WILDCARD_PROBE = {
4795
- "0.0.0.0": "127.0.0.1",
4796
- "::": "::1"
4797
- };
4798
- /** Whether something accepts connections on `host:port`, within `timeoutMs`. */
4799
- function portOpen(host, port, timeoutMs = 1e3) {
4800
- return new Promise((resolve) => {
4801
- const socket = net.connect({
4802
- host: WILDCARD_PROBE[host] ?? host,
4803
- port
4804
- });
4805
- const done = (open) => {
4806
- socket.destroy();
4807
- resolve(open);
4808
- };
4809
- socket.setTimeout(timeoutMs, () => done(false));
4810
- socket.once("connect", () => done(true));
4811
- socket.once("error", () => done(false));
4812
- });
4813
- }
4814
- // src/adapters/out/process/process-tree.ts
4815
- /** How long the process group gets after `SIGTERM` before `SIGKILL` (not on Windows). */
4816
- const TERM_GRACE_MS = 3e3;
4817
- /**
4818
- * Spawn options for a child whose whole tree `killTree` can end. On POSIX the child leads its own
4819
- * process group. On Windows that isn't needed (`taskkill /T` walks the tree), and `detached`
4820
- * there would open a new console window.
4821
- */
4822
- const treeSpawnOptions = {
4823
- detached: process.platform !== "win32",
4824
- windowsHide: true
4825
- };
4826
- function hasExited(child) {
4827
- return child.exitCode !== null || child.signalCode !== null;
4828
- }
4829
- function killGroup(pid, signal) {
4830
- try {
4831
- process.kill(-pid, signal);
4832
- } catch {}
4833
- }
4834
- /** Resolves after `ms`, or when `promise` settles, whichever comes first. */
4835
- async function within(promise, ms) {
4836
- let timer;
4837
- await Promise.race([promise.catch(() => void 0), new Promise((resolve) => timer = setTimeout(resolve, ms))]);
4838
- clearTimeout(timer);
4839
- }
4840
- const exec = (file, args, timeoutMs) => new Promise((resolve) => {
4841
- execFile(file, [...args], {
4842
- windowsHide: true,
4843
- timeout: timeoutMs,
4844
- killSignal: "SIGKILL"
4845
- }, (error, stdout) => resolve({
4846
- ok: error === null,
4847
- stdout: String(stdout)
4848
- }));
4849
- });
4850
- const TOOL_TIMEOUT_MS = 5e3;
4851
- /** Trees that may still have processes, for `killAllTreesNow`. */
4852
- const trees = /* @__PURE__ */ new Set();
4853
- /**
4854
- * Remembers a child spawned with `treeSpawnOptions`, so `killAllTreesNow` can end it when the
4855
- * bridge has to exit without stopping gracefully. `killTree` forgets it; so does `releaseTree`.
4856
- */
4857
- function trackTree(child) {
4858
- trees.add(child);
4859
- }
4860
- /** Forgets a child that ended on its own and left nothing behind to kill. */
4861
- function releaseTree(child) {
4862
- trees.delete(child);
4863
- }
4864
- /**
4865
- * Ends every tracked tree at once and synchronously, without waiting for anything. For a forced
4866
- * exit (watchdog, second Ctrl+C), when the graceful `killTree` has no time left: exiting without
4867
- * this leaves the browsers of the Playwright server behind.
4868
- */
4869
- function killAllTreesNow(platform = process.platform) {
4870
- for (const child of trees) {
4871
- const { pid } = child;
4872
- if (pid === void 0) continue;
4873
- if (platform === "win32") spawnSync("taskkill", [
4874
- "/T",
4875
- "/F",
4876
- "/PID",
4877
- String(pid)
4878
- ], {
4879
- windowsHide: true,
4880
- stdio: "ignore",
4881
- timeout: TOOL_TIMEOUT_MS
4882
- });
4883
- else killGroup(pid, "SIGKILL");
4884
- }
4885
- trees.clear();
4886
- }
4887
- /**
4888
- * Kills `child` and every process it started (docs/usage/operations.md#shutdown). On Windows,
4889
- * `taskkill /T /F` limited to a few seconds (killing a process there doesn't kill its children;
4890
- * the orphans of a child that already died are not hunted down, see
4891
- * docs/implementation/decisions.md#child-process-trees-are-killed-by-the-bridge-not-the-os).
4892
- * Elsewhere `SIGTERM` to the process group, then `SIGKILL` to whatever is left. Resolves
4893
- * once `child` has exited, or after a deadline if it can't be killed. Never rejects.
4894
- * `child` must have been spawned with `treeSpawnOptions`.
4895
- */
4896
- async function killTree(child, options = {}) {
4897
- const { platform = process.platform, toolTimeoutMs = TOOL_TIMEOUT_MS } = options;
4898
- const { exitTimeoutMs = TOOL_TIMEOUT_MS, exec: run = exec } = options;
4899
- const { pid } = child;
4900
- try {
4901
- if (pid === void 0) return;
4902
- const exited = hasExited(child) ? Promise.resolve() : once(child, "exit");
4903
- if (platform === "win32") {
4904
- if (!hasExited(child)) await run("taskkill", [
4905
- "/T",
4906
- "/F",
4907
- "/PID",
4908
- String(pid)
4909
- ], toolTimeoutMs);
4910
- await within(exited, exitTimeoutMs);
4911
- return;
4912
- }
4913
- killGroup(pid, "SIGTERM");
4914
- await within(exited, TERM_GRACE_MS);
4915
- killGroup(pid, "SIGKILL");
4916
- await within(exited, exitTimeoutMs);
4917
- } finally {
4918
- trees.delete(child);
4919
- }
4920
- }
4921
- /** Writes each line of the child's stdout as `info` and of its stderr as `warn`. */
4922
- function pipeLines(child, output) {
4923
- if (child.stdout) readline.createInterface({
4924
- input: child.stdout,
4925
- crlfDelay: Infinity
4926
- }).on("line", (line) => output.info(line));
4927
- if (child.stderr) readline.createInterface({
4928
- input: child.stderr,
4929
- crlfDelay: Infinity
4930
- }).on("line", (line) => output.warn(line));
5115
+ }];
5116
+ }
5117
+ // src/adapters/shared/net/port-probe.ts
5118
+ /** Where to probe a listener on a wildcard host: the loopback address of that family. */
5119
+ const WILDCARD_PROBE = {
5120
+ "0.0.0.0": "127.0.0.1",
5121
+ "::": "::1"
5122
+ };
5123
+ /** Whether something accepts connections on `host:port`, within `timeoutMs`. */
5124
+ function portOpen(host, port, timeoutMs = 1e3) {
5125
+ return new Promise((resolve) => {
5126
+ const socket = net.connect({
5127
+ host: WILDCARD_PROBE[host] ?? host,
5128
+ port
5129
+ });
5130
+ const done = (open) => {
5131
+ socket.destroy();
5132
+ resolve(open);
5133
+ };
5134
+ socket.setTimeout(timeoutMs, () => done(false));
5135
+ socket.once("connect", () => done(true));
5136
+ socket.once("error", () => done(false));
5137
+ });
4931
5138
  }
4932
5139
  // src/adapters/out/process/child-process-supervisor.ts
4933
5140
  /** How long the port may take to open after the start, before it counts as a crash. */
@@ -4945,6 +5152,7 @@ var ChildProcessSupervisor = class {
4945
5152
  state = "stopped";
4946
5153
  restarts = 0;
4947
5154
  exitCode = null;
5155
+ lastError = null;
4948
5156
  crashesInRow = 0;
4949
5157
  child = null;
4950
5158
  runningSince = null;
@@ -4969,7 +5177,8 @@ var ChildProcessSupervisor = class {
4969
5177
  version,
4970
5178
  port,
4971
5179
  restarts: this.restarts,
4972
- exitCode: this.exitCode
5180
+ exitCode: this.exitCode,
5181
+ lastError: this.lastError
4973
5182
  };
4974
5183
  }
4975
5184
  start() {
@@ -4979,6 +5188,7 @@ var ChildProcessSupervisor = class {
4979
5188
  this.restarts = 0;
4980
5189
  this.crashesInRow = 0;
4981
5190
  this.exitCode = null;
5191
+ this.lastError = null;
4982
5192
  this.launch();
4983
5193
  }
4984
5194
  return settled;
@@ -5019,20 +5229,23 @@ var ChildProcessSupervisor = class {
5019
5229
  this.setState("starting");
5020
5230
  this.launchedAt = Date.now();
5021
5231
  this.options.logger.info(`starting ${this.options.name} ${settings.version}`);
5232
+ const failed = (how, error) => {
5233
+ if (!current()) return;
5234
+ const cause = `${how}: ${error instanceof Error ? error.message : String(error)}`;
5235
+ this.options.logger.error(`${this.options.name} ${cause}`);
5236
+ this.crashed(null, "failed to start", cause);
5237
+ };
5022
5238
  this.options.prepare(settings, abort.signal).then(async (command) => {
5023
5239
  if (!current()) return;
5024
5240
  if (await portOpen(settings.host, settings.port)) {
5025
5241
  if (!current()) return;
5026
- this.options.logger.error(`${this.options.name}: port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`);
5027
- this.crashed(null, "could not start");
5242
+ const cause = `port ${settings.port} is already in use (a leftover process of an earlier run, or another program)`;
5243
+ this.options.logger.error(`${this.options.name}: ${cause}`);
5244
+ this.crashed(null, "could not start", cause);
5028
5245
  return;
5029
5246
  }
5030
5247
  if (current()) this.spawn(command, settings, generation);
5031
- }, (error) => {
5032
- if (!current()) return;
5033
- this.options.logger.error(`${this.options.name} could not be prepared: ${error instanceof Error ? error.message : String(error)}`);
5034
- this.crashed(null, "failed to start");
5035
- });
5248
+ }, (error) => failed("could not be prepared", error)).catch((error) => failed("could not be started", error));
5036
5249
  }
5037
5250
  spawn(command, settings, generation) {
5038
5251
  const current = () => generation === this.generation;
@@ -5048,6 +5261,7 @@ var ChildProcessSupervisor = class {
5048
5261
  trackTree(child);
5049
5262
  pipeLines(child, this.options.output);
5050
5263
  let exited = false;
5264
+ let cause;
5051
5265
  const onExit = (code, signal) => {
5052
5266
  if (exited) return;
5053
5267
  exited = true;
@@ -5055,12 +5269,16 @@ var ChildProcessSupervisor = class {
5055
5269
  this.child = null;
5056
5270
  killTree(child);
5057
5271
  const what = code !== null ? `exited with code ${code}` : signal !== null ? `was killed (${signal})` : "failed to start";
5058
- this.crashed(code, what);
5272
+ this.crashed(code, what, cause);
5059
5273
  };
5060
5274
  child.once("exit", onExit);
5061
5275
  child.once("error", (error) => {
5062
- this.options.logger.error(`${this.options.name} could not be started: ${error.message}`);
5063
- if (child.pid === void 0) onExit(null, null);
5276
+ const failure = `could not be started: ${error.message}`;
5277
+ this.options.logger.error(`${this.options.name} ${failure}`);
5278
+ if (child.pid === void 0) {
5279
+ cause = failure;
5280
+ onExit(null, null);
5281
+ }
5064
5282
  });
5065
5283
  this.waitForPort(settings, generation, () => exited).then((open) => {
5066
5284
  if (!current() || exited) return;
@@ -5070,7 +5288,8 @@ var ChildProcessSupervisor = class {
5070
5288
  const seconds = ((Date.now() - this.launchedAt) / 1e3).toFixed(1);
5071
5289
  this.options.logger.info(`${this.options.name} running (${seconds}s)`);
5072
5290
  } else {
5073
- this.options.logger.error(`${this.options.name} did not open port ${settings.port} in time, killing it`);
5291
+ cause = `did not open port ${settings.port} in time`;
5292
+ this.options.logger.error(`${this.options.name} ${cause}, killing it`);
5074
5293
  killTree(child);
5075
5294
  }
5076
5295
  });
@@ -5083,11 +5302,13 @@ var ChildProcessSupervisor = class {
5083
5302
  }
5084
5303
  return false;
5085
5304
  }
5086
- crashed(code, what) {
5305
+ /** `what` goes to the log, `cause` to the status. */
5306
+ crashed(code, what, cause = what) {
5087
5307
  const { name, logger } = this.options;
5088
5308
  const ranForMs = this.runningSince === null ? 0 : Date.now() - this.runningSince;
5089
5309
  this.runningSince = null;
5090
5310
  this.exitCode = code;
5311
+ this.lastError = cause;
5091
5312
  const decision = nextAfterCrash(this.crashesInRow, ranForMs, this.options.policy);
5092
5313
  this.crashesInRow = decision.crashesInRow;
5093
5314
  if (decision.action === "fail") {
@@ -5411,87 +5632,6 @@ function createSupervisors(config, options, log) {
5411
5632
  })
5412
5633
  };
5413
5634
  }
5414
- // src/composition/ui.ts
5415
- /** The environment variable the UI's BFF reads the bridge's address from. */
5416
- const BRIDGE_API_URL_ENV = "SR_BRIDGE_API_URL";
5417
- /** The header adapter-node reads the request's protocol from (`PROTOCOL_HEADER`). */
5418
- const PROTOCOL_HEADER = "x-sr-bridge-protocol";
5419
- /**
5420
- * The header that tells the UI its page is opened from the bridge's own machine, where the screen
5421
- * reader would read the live log and feed it back (docs/usage/web-ui.md#accessibility-of-the-ui-itself).
5422
- * Set (`1`) or removed on every request, so a client can't send it.
5423
- */
5424
- const LOCAL_HEADER = "x-sr-bridge-local";
5425
- /**
5426
- * Where the UI's server code finds the bridge log (`packages/ui/src/lib/server/log.ts` reads it):
5427
- * a `Symbol.for` key on `globalThis`, because the bridge and the UI don't import each other. Its
5428
- * lines then get the `[web-ui]` prefix, go to the log file and never block on the console.
5429
- */
5430
- const UI_LOGGER_KEY = Symbol.for("screenreader-speech-capture.ui-logger");
5431
- /**
5432
- * The UI shipped in `dir` (`handler.js` of the `adapter-node` build). `undefined` when there is
5433
- * none: the bridge runs from source, or the package was built without the UI.
5434
- */
5435
- function createUiMount(dir, logger) {
5436
- const file = new URL("handler.js", dir);
5437
- if (!existsSync(file)) {
5438
- logger.debug(`no web UI at ${file.pathname}`);
5439
- return;
5440
- }
5441
- let settle;
5442
- const loaded = new Promise((resolve, reject) => {
5443
- settle = {
5444
- resolve,
5445
- reject
5446
- };
5447
- });
5448
- loaded.catch(() => void 0);
5449
- return {
5450
- handler: async (req, res) => {
5451
- if (new URL(req.url ?? "/", "http://localhost").pathname === "/") {
5452
- res.writeHead(302, { location: "/ui/" }).end();
5453
- return;
5454
- }
5455
- let handler;
5456
- try {
5457
- handler = await loaded;
5458
- } catch {
5459
- throw new AppError("SERVICE_UNAVAILABLE", "The web UI failed to start");
5460
- }
5461
- req.headers[PROTOCOL_HEADER] = "http";
5462
- if (isOwnAddress(req.socket?.remoteAddress)) req.headers[LOCAL_HEADER] = "1";
5463
- else delete req.headers[LOCAL_HEADER];
5464
- handler(req, res, () => {
5465
- res.statusCode = 404;
5466
- res.end();
5467
- });
5468
- },
5469
- async mount(apiUrl) {
5470
- try {
5471
- process.env[BRIDGE_API_URL_ENV] = apiUrl;
5472
- process.env.PROTOCOL_HEADER = PROTOCOL_HEADER;
5473
- globalThis[UI_LOGGER_KEY] = logger;
5474
- const module = await import(file.href);
5475
- if (typeof module.handler !== "function") throw new Error("handler.js has no `handler`");
5476
- settle.resolve(module.handler);
5477
- logger.debug(`web UI loaded from ${file.pathname}`);
5478
- } catch (error) {
5479
- logger.error(`web UI failed to start: ${error instanceof Error ? error.message : String(error)}`);
5480
- settle.reject(error);
5481
- }
5482
- }
5483
- };
5484
- }
5485
- /** The shipped UI: `ui/` next to the bundled `cli.mjs` (`dist/ui`). */
5486
- function shippedUiDir() {
5487
- return new URL("./ui/", import.meta.url);
5488
- }
5489
- /**
5490
- * Where the BFF reaches the bridge's HTTP API: over loopback, whatever address it listens on.
5491
- */
5492
- function bridgeApiUrl(host, port) {
5493
- return `http://${hostPort(host === "::" ? "::1" : isWildcard(host) ? "127.0.0.1" : host, port)}`;
5494
- }
5495
5635
  // src/domain/capture.ts
5496
5636
  /**
5497
5637
  * What the capture adapters reported about their listener and connections, for the status. The
@@ -5855,7 +5995,26 @@ var SpeechLog = class {
5855
5995
  }
5856
5996
  };
5857
5997
  // src/main.ts
5998
+ /** The web UI shipped with the package: `ui/` next to the bundled `cli.mjs` (`dist/ui`). */
5999
+ const SHIPPED_UI_DIR = new URL("./ui/", import.meta.url);
6000
+ /**
6001
+ * For an exit that can't wait for `stop()`: ends the child services' process trees at once,
6002
+ * synchronously (docs/usage/operations.md#shutdown).
6003
+ */
6004
+ function killChildProcessesNow() {
6005
+ killAllTreesNow();
6006
+ }
6007
+ /** Writes out the console output that is still buffered, before the process exits. */
6008
+ async function flushOutput() {
6009
+ await flushTerminal();
6010
+ await flushConsole();
6011
+ }
5858
6012
  const show = (value) => JSON.stringify(value);
6013
+ /** A busy port needs no stack: the message says what to do. Anything else is unexpected. */
6014
+ function describeStartFailure(error) {
6015
+ if (error instanceof ListenError) return error.message;
6016
+ return error instanceof Error ? error.stack ?? String(error) : String(error);
6017
+ }
5859
6018
  /**
5860
6019
  * Starts the bridge. An invalid setting rejects with a `ConfigError` before anything starts.
5861
6020
  * Any other failure to start is written to the bridge log before the promise rejects, and so is
@@ -5866,7 +6025,7 @@ async function startBridge(options) {
5866
6025
  const seams = options.testSeams ?? {};
5867
6026
  const store = seams.configStore ?? new FsConfigStore(options.configFile ?? defaultConfigFile());
5868
6027
  const sourceOf = (field) => options.overrideSources?.get(field) ?? "a flag or environment variable";
5869
- const { config, file: savedFile, overrides, unknown: unknownSettings, ignored } = await loadConfig(store, options.overrides, sourceOf);
6028
+ const { config, file: savedFile, overrides, unknown: unknownSettings, ignored, warnings } = await loadConfig(store, options.overrides, sourceOf);
5870
6029
  const log = createLogging(config, {
5871
6030
  version,
5872
6031
  configLocation: store.location,
@@ -5874,232 +6033,143 @@ async function startBridge(options) {
5874
6033
  });
5875
6034
  const bridgeLogger = log.for("bridge");
5876
6035
  const configLogger = log.for("config");
6036
+ for (const warning of warnings) configLogger.warn(warning);
5877
6037
  for (const name of ignored) configLogger.warn(`${name}: unknown setting in ${store.location}, ignored`);
5878
6038
  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`);
5879
- const clock = seams.clock ?? new SystemClock();
5880
- const startedAt = clock.now();
5881
- const speechLog = new SpeechLog(config.buffer.maxEntries, startedAt.getTime());
5882
- const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
5883
- new TranscriptService({
5884
- events,
5885
- transcript: log.for("speech-capture", { channel: "speech" })
5886
- }).start();
5887
- const speech = new SpeechService({
5888
- log: speechLog,
5889
- events,
5890
- clock
5891
- });
5892
- const waits = new WaitForSpeechService({
5893
- log: speechLog,
5894
- events,
5895
- clock,
5896
- pace: () => yieldEvery(256)
5897
- });
5898
- const sessions = new SessionService({
5899
- log: speechLog,
5900
- events,
5901
- clock,
5902
- logger: log.for("bridge")
5903
- });
5904
- const injector = seams.inputInjector ?? await createInputInjector(log.for("native-input"));
5905
- const windows = seams.windowSystem ?? await createWindowSystem(log.for("native-input"));
5906
- const supervisors = createSupervisors(config, seams, log);
5907
- const input = new NativeInputService({
5908
- injector,
5909
- windows,
5910
- services: supervisors,
5911
- clock,
5912
- logger: log.for("native-input")
5913
- });
5914
- const captures = new InputCaptureService({
5915
- input,
5916
- log: speechLog,
5917
- events,
5918
- clock,
5919
- pace: () => yieldEvery(256)
5920
- });
5921
- const configService = new ConfigService({
5922
- store,
5923
- logger: configLogger,
5924
- active: config,
5925
- file: savedFile,
5926
- unknownSettings,
5927
- pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
5928
- });
5929
- const focus = new WindowFocusService({
5930
- windows,
5931
- queue: input,
5932
- services: supervisors,
5933
- clock,
5934
- logger: log.for("native-input")
5935
- });
5936
- const childServices = new ChildServicesService({
5937
- supervisors,
5938
- config: () => configService.get(),
5939
- logger: bridgeLogger
5940
- });
5941
- const captureState = new CaptureState(() => clock.now());
5942
- const tcp = new TcpListener(speech, captureState, log.for("speech-capture"));
5943
- const status = new StatusService({
5944
- capture: captureState,
5945
- log: speechLog,
5946
- supervisors,
5947
- config: () => configService.get(),
5948
- version,
5949
- apiVersion: API_VERSION,
5950
- startedAt,
5951
- injector,
5952
- windows
5953
- });
5954
- const ui = createUiMount(seams.uiDir ?? shippedUiDir(), log.for("web-ui"));
5955
- const http = new HttpServer({
5956
- speech,
5957
- waits,
5958
- status,
5959
- config: configService,
5960
- sessions,
5961
- input,
5962
- captures,
5963
- focus,
5964
- logger: log.for("http-api"),
5965
- hostnames: [hostname()],
5966
- proxies: proxyRoutes(childServices),
5967
- ...ui ? { ui: ui.handler } : {},
5968
- ...seams.ssePingMs === void 0 ? {} : { pingMs: seams.ssePingMs }
5969
- });
5970
- const ports = await startListeners(tcp, http, config, bridgeLogger);
5971
- await ui?.mount(bridgeApiUrl(config.http.host, ports.http));
5972
- const lifecycle = new BridgeLifecycleService({
5973
- state: status,
5974
- pending: [
6039
+ try {
6040
+ const clock = seams.clock ?? new SystemClock();
6041
+ const startedAt = clock.now();
6042
+ const speechLog = new SpeechLog(config.buffer.maxEntries, startedAt.getTime());
6043
+ const events = new InProcessEventBus((error) => bridgeLogger.error(`event listener failed: ${String(error)}`));
6044
+ new TranscriptService({
6045
+ events,
6046
+ transcript: log.for("speech-capture", { channel: "speech" })
6047
+ }).start();
6048
+ const speech = new SpeechService({
6049
+ log: speechLog,
6050
+ events,
6051
+ clock
6052
+ });
6053
+ const shutdown = new AbortController();
6054
+ setMaxListeners(0, shutdown.signal);
6055
+ const waits = new WaitForSpeechService({
6056
+ log: speechLog,
6057
+ events,
6058
+ clock,
6059
+ pace: () => yieldEvery(256),
6060
+ shutdown: shutdown.signal
6061
+ });
6062
+ const sessions = new SessionService({
6063
+ log: speechLog,
6064
+ events,
6065
+ clock,
6066
+ logger: log.for("bridge")
6067
+ });
6068
+ const injector = seams.inputInjector ?? await createInputInjector(log.for("native-input"));
6069
+ const windows = seams.windowSystem ?? await createWindowSystem(log.for("native-input"));
6070
+ const supervisors = createSupervisors(config, seams, log);
6071
+ const input = new NativeInputService({
6072
+ injector,
6073
+ windows,
6074
+ services: supervisors,
6075
+ clock,
6076
+ logger: log.for("native-input"),
6077
+ shutdown: shutdown.signal
6078
+ });
6079
+ const captures = new InputCaptureService({
6080
+ input,
6081
+ log: speechLog,
6082
+ events,
6083
+ clock,
6084
+ pace: () => yieldEvery(256),
6085
+ shutdown: shutdown.signal
6086
+ });
6087
+ const configService = new ConfigService({
6088
+ store,
6089
+ logger: configLogger,
6090
+ active: config,
6091
+ file: savedFile,
6092
+ unknownSettings,
6093
+ pinned: new Map([...configFields(overrides).keys()].map((field) => [field, sourceOf(field)]))
6094
+ });
6095
+ const focus = new WindowFocusService({
6096
+ windows,
6097
+ queue: input,
6098
+ services: supervisors,
6099
+ clock,
6100
+ logger: log.for("native-input")
6101
+ });
6102
+ const childServices = new ChildServicesService({
6103
+ supervisors,
6104
+ config: () => configService.get(),
6105
+ logger: bridgeLogger
6106
+ });
6107
+ const captureState = new CaptureState(() => clock.now());
6108
+ const tcp = new TcpListener(speech, captureState, log.for("speech-capture"));
6109
+ const status = new StatusService({
6110
+ capture: captureState,
6111
+ log: speechLog,
6112
+ supervisors,
6113
+ config: () => configService.get(),
6114
+ version,
6115
+ apiVersion: API_VERSION,
6116
+ startedAt,
6117
+ injector,
6118
+ windows
6119
+ });
6120
+ const ui = createUiMount(seams.uiDir ?? SHIPPED_UI_DIR, log.for("web-ui"));
6121
+ const http = new HttpServer({
6122
+ speech,
5975
6123
  waits,
6124
+ status,
6125
+ config: configService,
6126
+ sessions,
6127
+ input,
5976
6128
  captures,
5977
- input
5978
- ],
5979
- startServices: () => childServices.startEnabled(),
5980
- stopOrder: [
5981
- http,
5982
- tcp,
5983
- { stop: () => childServices.stopAll() }
5984
- ],
5985
- readyMessage: () => readySummary({
5986
- config,
5987
- ports,
5988
- supervisors,
5989
- webUi: ui !== void 0,
5990
- nativeInput: injector.availability,
5991
- tookMs: clock.now().getTime() - startedAt.getTime()
5992
- }),
5993
- logger: bridgeLogger
5994
- });
5995
- lifecycle.start();
5996
- return {
5997
- tcpPort: ports.tcp,
5998
- httpPort: ports.http,
5999
- speech,
6000
- sessions,
6001
- capture: captureState,
6002
- log: bridgeLogger,
6003
- stop: (reason) => lifecycle.stop(reason)
6004
- };
6005
- }
6006
- // src/adapters/in/cli/lifecycle.ts
6007
- const SHUTDOWN_TIMEOUT_MS = 1e4;
6008
- /** Ctrl+C, `kill`, closing the console window, and Ctrl+Break on Windows. */
6009
- function shutdownSignals(platform) {
6010
- const signals = [
6011
- "SIGINT",
6012
- "SIGTERM",
6013
- "SIGHUP"
6014
- ];
6015
- if (platform === "win32") signals.push("SIGBREAK");
6016
- return signals;
6017
- }
6018
- /** Resolves once everything written to `stream` so far is handed to the OS. */
6019
- function drain(stream) {
6020
- return new Promise((resolve) => stream.write("", () => resolve()));
6021
- }
6022
- /** Default `flush`: drains stdout and stderr. The log file is written synchronously. */
6023
- async function flushConsole() {
6024
- await Promise.all([drain(process.stdout), drain(process.stderr)]);
6025
- }
6026
- function describeError(error) {
6027
- return error instanceof Error ? error.stack ?? String(error) : String(error);
6028
- }
6029
- /**
6030
- * Starts the bridge with `start`, then stops it gracefully and exits the process
6031
- * (docs/usage/operations.md#shutdown):
6032
- *
6033
- * - on a shutdown signal. A second signal exits at once.
6034
- * - on an uncaught exception or unhandled rejection, which is logged with its stack. Exit code 1.
6035
- * - if the shutdown takes longer than `timeoutMs`, it exits anyway with code 1.
6036
- *
6037
- * The exit code is 0 unless something failed. Console output is flushed before exiting.
6038
- *
6039
- * The signal handlers are installed before `start`, so a signal that arrives while the bridge
6040
- * starts is not fatal: the bridge stops as soon as it has started. Resolves once started; rejects
6041
- * like `start`.
6042
- */
6043
- async function runUntilStopped(start, proc, options = {}) {
6044
- const { timeoutMs = SHUTDOWN_TIMEOUT_MS, flush = flushConsole, onForcedExit } = options;
6045
- let bridge = void 0;
6046
- /** A signal that arrived before the bridge had started. */
6047
- let early;
6048
- let stopping = false;
6049
- let exiting = false;
6050
- let exitCode = 0;
6051
- let watchdog;
6052
- /** Ends the child processes the graceful stop didn't get to. */
6053
- const killLeftovers = () => {
6054
- try {
6055
- onForcedExit?.();
6056
- } catch {}
6057
- };
6058
- const forceExit = (code) => {
6059
- killLeftovers();
6060
- proc.exit(code);
6061
- };
6062
- const exit = (code) => {
6063
- if (exiting) return forceExit(code);
6064
- exiting = true;
6065
- flush().catch(() => void 0).then(() => {
6066
- clearTimeout(watchdog);
6067
- proc.exit(code);
6129
+ focus,
6130
+ logger: log.for("http-api"),
6131
+ hostnames: [hostname()],
6132
+ proxies: proxyRoutes(childServices),
6133
+ ...ui ? { ui: ui.handler } : {},
6134
+ ...seams.ssePingMs === void 0 ? {} : { pingMs: seams.ssePingMs }
6068
6135
  });
6069
- };
6070
- const shutdown = (running, reason) => {
6071
- stopping = true;
6072
- watchdog = setTimeout(() => {
6073
- running.log.error(`shutdown did not finish within ${timeoutMs / 1e3} s, exiting`);
6074
- exiting = true;
6075
- forceExit(1);
6076
- }, timeoutMs).unref();
6077
- running.stop(reason).then(() => exit(exitCode), () => exit(1));
6078
- };
6079
- for (const signal of shutdownSignals(proc.platform)) proc.on(signal, () => {
6080
- if (bridge === void 0) {
6081
- if (early === void 0) early = signal;
6082
- else {
6083
- killLeftovers();
6084
- exit(1);
6085
- }
6086
- return;
6087
- }
6088
- if (!stopping) return shutdown(bridge, signal);
6089
- bridge.log.warn(`${signal} again, exiting without waiting`);
6090
- killLeftovers();
6091
- exit(1);
6092
- });
6093
- bridge = await start();
6094
- const running = bridge;
6095
- const crash = (what) => (error) => {
6096
- running.log.error(`${what}: ${describeError(error)}`);
6097
- exitCode = 1;
6098
- if (!stopping) shutdown(running, "crash");
6099
- };
6100
- proc.on("uncaughtException", crash("uncaught exception"));
6101
- proc.on("unhandledRejection", crash("unhandled rejection"));
6102
- if (early !== void 0) shutdown(running, early);
6136
+ const lifecycle = new BridgeLifecycleService({
6137
+ state: status,
6138
+ tcp: {
6139
+ start: () => tcp.start(config.tcp),
6140
+ stop: () => tcp.stop()
6141
+ },
6142
+ http: {
6143
+ start: () => http.start(config.http),
6144
+ stop: () => http.stop()
6145
+ },
6146
+ httpListening: async (port) => ui?.mount(bridgeApiUrl(config.http.host, port)),
6147
+ services: childServices,
6148
+ shutdown,
6149
+ readyMessage: (ports) => readySummary({
6150
+ config,
6151
+ ports,
6152
+ supervisors,
6153
+ webUi: ui !== void 0,
6154
+ nativeInput: injector.availability,
6155
+ tookMs: clock.now().getTime() - startedAt.getTime()
6156
+ }),
6157
+ logger: bridgeLogger
6158
+ });
6159
+ const ports = await lifecycle.start();
6160
+ return {
6161
+ tcpPort: ports.tcp,
6162
+ httpPort: ports.http,
6163
+ speech,
6164
+ sessions,
6165
+ capture: captureState,
6166
+ log: bridgeLogger,
6167
+ stop: (reason) => lifecycle.stop(reason)
6168
+ };
6169
+ } catch (error) {
6170
+ bridgeLogger.error(describeStartFailure(error));
6171
+ throw error;
6172
+ }
6103
6173
  }
6104
6174
  // src/adapters/in/cli/options.ts
6105
6175
  const SETTINGS = [
@@ -6349,16 +6419,14 @@ try {
6349
6419
  overrideSources: options.sources,
6350
6420
  ...options.configFile === void 0 ? {} : { configFile: options.configFile }
6351
6421
  }), process, {
6352
- onForcedExit: () => killAllTreesNow(),
6353
- flush: async () => {
6354
- await flushTerminal();
6355
- await flushConsole();
6356
- }
6422
+ onForcedExit: killChildProcessesNow,
6423
+ flush: flushOutput
6357
6424
  });
6358
6425
  } catch (error) {
6359
6426
  if (error instanceof ConfigError) fail(error.message);
6360
- await flushTerminal();
6361
- await flushConsole();
6427
+ const reason = error instanceof Error ? error.message : String(error);
6428
+ process.stderr.write(`screenreader-speech-capture-bridge: failed to start: ${reason}\n`);
6429
+ await flushOutput();
6362
6430
  process.exit(1);
6363
6431
  }
6364
6432
  export {};