@copilotkit/aimock 1.42.0 → 1.43.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 (341) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +56 -0
  4. package/README.md +102 -16
  5. package/dist/agui-mock.cjs +1 -1
  6. package/dist/agui-mock.cjs.map +1 -1
  7. package/dist/agui-mock.d.cts.map +1 -1
  8. package/dist/agui-mock.d.ts.map +1 -1
  9. package/dist/agui-mock.js +1 -1
  10. package/dist/agui-mock.js.map +1 -1
  11. package/dist/agui-recorder.cjs +33 -11
  12. package/dist/agui-recorder.cjs.map +1 -1
  13. package/dist/agui-recorder.d.cts +10 -1
  14. package/dist/agui-recorder.d.cts.map +1 -1
  15. package/dist/agui-recorder.d.ts +10 -1
  16. package/dist/agui-recorder.d.ts.map +1 -1
  17. package/dist/agui-recorder.js +33 -11
  18. package/dist/agui-recorder.js.map +1 -1
  19. package/dist/agui-types.d.cts +1 -0
  20. package/dist/agui-types.d.cts.map +1 -1
  21. package/dist/agui-types.d.ts +1 -0
  22. package/dist/agui-types.d.ts.map +1 -1
  23. package/dist/aimock-cli.cjs +38 -10
  24. package/dist/aimock-cli.cjs.map +1 -1
  25. package/dist/aimock-cli.d.cts +5 -0
  26. package/dist/aimock-cli.d.cts.map +1 -1
  27. package/dist/aimock-cli.d.ts +5 -0
  28. package/dist/aimock-cli.d.ts.map +1 -1
  29. package/dist/aimock-cli.js +38 -10
  30. package/dist/aimock-cli.js.map +1 -1
  31. package/dist/batches.cjs +458 -0
  32. package/dist/batches.cjs.map +1 -0
  33. package/dist/batches.d.cts +57 -0
  34. package/dist/batches.d.cts.map +1 -0
  35. package/dist/batches.d.ts +57 -0
  36. package/dist/batches.d.ts.map +1 -0
  37. package/dist/batches.js +453 -0
  38. package/dist/batches.js.map +1 -0
  39. package/dist/bedrock-converse.cjs +12 -8
  40. package/dist/bedrock-converse.cjs.map +1 -1
  41. package/dist/bedrock-converse.d.cts.map +1 -1
  42. package/dist/bedrock-converse.d.ts.map +1 -1
  43. package/dist/bedrock-converse.js +14 -10
  44. package/dist/bedrock-converse.js.map +1 -1
  45. package/dist/bedrock.cjs +10 -8
  46. package/dist/bedrock.cjs.map +1 -1
  47. package/dist/bedrock.d.cts.map +1 -1
  48. package/dist/bedrock.d.ts.map +1 -1
  49. package/dist/bedrock.js +12 -10
  50. package/dist/bedrock.js.map +1 -1
  51. package/dist/byteplus-video.cjs +3 -3
  52. package/dist/byteplus-video.cjs.map +1 -1
  53. package/dist/byteplus-video.js +4 -4
  54. package/dist/byteplus-video.js.map +1 -1
  55. package/dist/chaos.cjs +622 -72
  56. package/dist/chaos.cjs.map +1 -1
  57. package/dist/chaos.d.cts +164 -7
  58. package/dist/chaos.d.cts.map +1 -1
  59. package/dist/chaos.d.ts +164 -7
  60. package/dist/chaos.d.ts.map +1 -1
  61. package/dist/chaos.js +613 -74
  62. package/dist/chaos.js.map +1 -1
  63. package/dist/cli.cjs +42 -23
  64. package/dist/cli.cjs.map +1 -1
  65. package/dist/cli.js +42 -23
  66. package/dist/cli.js.map +1 -1
  67. package/dist/cohere.cjs +10 -8
  68. package/dist/cohere.cjs.map +1 -1
  69. package/dist/cohere.d.cts.map +1 -1
  70. package/dist/cohere.d.ts.map +1 -1
  71. package/dist/cohere.js +12 -10
  72. package/dist/cohere.js.map +1 -1
  73. package/dist/config-loader.d.cts.map +1 -1
  74. package/dist/config-loader.d.ts.map +1 -1
  75. package/dist/convert.cjs +1 -1
  76. package/dist/convert.cjs.map +1 -1
  77. package/dist/convert.js +1 -1
  78. package/dist/convert.js.map +1 -1
  79. package/dist/elevenlabs-audio.cjs +3 -3
  80. package/dist/elevenlabs-audio.cjs.map +1 -1
  81. package/dist/elevenlabs-audio.js +4 -4
  82. package/dist/elevenlabs-audio.js.map +1 -1
  83. package/dist/elevenlabs-voice.cjs +1053 -0
  84. package/dist/elevenlabs-voice.cjs.map +1 -0
  85. package/dist/elevenlabs-voice.d.cts +72 -0
  86. package/dist/elevenlabs-voice.d.cts.map +1 -0
  87. package/dist/elevenlabs-voice.d.ts +72 -0
  88. package/dist/elevenlabs-voice.d.ts.map +1 -0
  89. package/dist/elevenlabs-voice.js +1048 -0
  90. package/dist/elevenlabs-voice.js.map +1 -0
  91. package/dist/embeddings.cjs +8 -4
  92. package/dist/embeddings.cjs.map +1 -1
  93. package/dist/embeddings.d.cts.map +1 -1
  94. package/dist/embeddings.d.ts.map +1 -1
  95. package/dist/embeddings.js +9 -5
  96. package/dist/embeddings.js.map +1 -1
  97. package/dist/fal-audio.cjs +3 -3
  98. package/dist/fal-audio.cjs.map +1 -1
  99. package/dist/fal-audio.js +4 -4
  100. package/dist/fal-audio.js.map +1 -1
  101. package/dist/fal.cjs +28 -4
  102. package/dist/fal.cjs.map +1 -1
  103. package/dist/fal.d.cts +16 -1
  104. package/dist/fal.d.cts.map +1 -1
  105. package/dist/fal.d.ts +16 -1
  106. package/dist/fal.d.ts.map +1 -1
  107. package/dist/fal.js +28 -5
  108. package/dist/fal.js.map +1 -1
  109. package/dist/files.cjs +1071 -0
  110. package/dist/files.cjs.map +1 -0
  111. package/dist/files.d.cts +68 -0
  112. package/dist/files.d.cts.map +1 -0
  113. package/dist/files.d.ts +68 -0
  114. package/dist/files.d.ts.map +1 -0
  115. package/dist/files.js +1059 -0
  116. package/dist/files.js.map +1 -0
  117. package/dist/fine-tuning.cjs +1051 -0
  118. package/dist/fine-tuning.cjs.map +1 -0
  119. package/dist/fine-tuning.d.cts +96 -0
  120. package/dist/fine-tuning.d.cts.map +1 -0
  121. package/dist/fine-tuning.d.ts +96 -0
  122. package/dist/fine-tuning.d.ts.map +1 -0
  123. package/dist/fine-tuning.js +1044 -0
  124. package/dist/fine-tuning.js.map +1 -0
  125. package/dist/fixture-loader.cjs +0 -0
  126. package/dist/fixture-loader.cjs.map +1 -1
  127. package/dist/fixture-loader.d.cts +37 -5
  128. package/dist/fixture-loader.d.cts.map +1 -1
  129. package/dist/fixture-loader.d.ts +37 -5
  130. package/dist/fixture-loader.d.ts.map +1 -1
  131. package/dist/fixture-loader.js +0 -0
  132. package/dist/fixture-loader.js.map +1 -1
  133. package/dist/gemini-embeddings.cjs +2 -2
  134. package/dist/gemini-embeddings.cjs.map +1 -1
  135. package/dist/gemini-embeddings.js +3 -3
  136. package/dist/gemini-embeddings.js.map +1 -1
  137. package/dist/gemini-interactions.cjs +13 -7
  138. package/dist/gemini-interactions.cjs.map +1 -1
  139. package/dist/gemini-interactions.d.cts.map +1 -1
  140. package/dist/gemini-interactions.d.ts.map +1 -1
  141. package/dist/gemini-interactions.js +15 -9
  142. package/dist/gemini-interactions.js.map +1 -1
  143. package/dist/gemini.cjs +11 -7
  144. package/dist/gemini.cjs.map +1 -1
  145. package/dist/gemini.d.cts.map +1 -1
  146. package/dist/gemini.d.ts.map +1 -1
  147. package/dist/gemini.js +13 -9
  148. package/dist/gemini.js.map +1 -1
  149. package/dist/grok-video.cjs +14 -14
  150. package/dist/grok-video.cjs.map +1 -1
  151. package/dist/grok-video.js +15 -15
  152. package/dist/grok-video.js.map +1 -1
  153. package/dist/helpers.cjs +229 -7
  154. package/dist/helpers.cjs.map +1 -1
  155. package/dist/helpers.d.cts +38 -2
  156. package/dist/helpers.d.cts.map +1 -1
  157. package/dist/helpers.d.ts +38 -2
  158. package/dist/helpers.d.ts.map +1 -1
  159. package/dist/helpers.js +221 -8
  160. package/dist/helpers.js.map +1 -1
  161. package/dist/images.cjs +54 -123
  162. package/dist/images.cjs.map +1 -1
  163. package/dist/images.d.cts.map +1 -1
  164. package/dist/images.d.ts.map +1 -1
  165. package/dist/images.js +55 -124
  166. package/dist/images.js.map +1 -1
  167. package/dist/index.cjs +41 -8
  168. package/dist/index.d.cts +12 -7
  169. package/dist/index.d.ts +12 -7
  170. package/dist/index.js +14 -10
  171. package/dist/jest.cjs +14 -7
  172. package/dist/jest.cjs.map +1 -1
  173. package/dist/jest.d.cts +3 -2
  174. package/dist/jest.d.cts.map +1 -1
  175. package/dist/jest.d.ts +3 -2
  176. package/dist/jest.d.ts.map +1 -1
  177. package/dist/jest.js +14 -7
  178. package/dist/jest.js.map +1 -1
  179. package/dist/journal.cjs +41 -4
  180. package/dist/journal.cjs.map +1 -1
  181. package/dist/journal.d.cts +44 -3
  182. package/dist/journal.d.cts.map +1 -1
  183. package/dist/journal.d.ts +44 -3
  184. package/dist/journal.d.ts.map +1 -1
  185. package/dist/journal.js +41 -5
  186. package/dist/journal.js.map +1 -1
  187. package/dist/live-fixture.cjs +1192 -0
  188. package/dist/live-fixture.cjs.map +1 -0
  189. package/dist/live-fixture.js +1187 -0
  190. package/dist/live-fixture.js.map +1 -0
  191. package/dist/live-recorder.cjs +256 -0
  192. package/dist/live-recorder.cjs.map +1 -0
  193. package/dist/live-recorder.js +254 -0
  194. package/dist/live-recorder.js.map +1 -0
  195. package/dist/live-replay.cjs +286 -0
  196. package/dist/live-replay.cjs.map +1 -0
  197. package/dist/live-replay.js +285 -0
  198. package/dist/live-replay.js.map +1 -0
  199. package/dist/live-sanitize.cjs +196 -0
  200. package/dist/live-sanitize.cjs.map +1 -0
  201. package/dist/live-sanitize.js +196 -0
  202. package/dist/live-sanitize.js.map +1 -0
  203. package/dist/live-types.d.cts +71 -0
  204. package/dist/live-types.d.cts.map +1 -0
  205. package/dist/live-types.d.ts +71 -0
  206. package/dist/live-types.d.ts.map +1 -0
  207. package/dist/llmock.cjs +52 -41
  208. package/dist/llmock.cjs.map +1 -1
  209. package/dist/llmock.d.cts +16 -5
  210. package/dist/llmock.d.cts.map +1 -1
  211. package/dist/llmock.d.ts +16 -5
  212. package/dist/llmock.d.ts.map +1 -1
  213. package/dist/llmock.js +53 -42
  214. package/dist/llmock.js.map +1 -1
  215. package/dist/messages.cjs +11 -7
  216. package/dist/messages.cjs.map +1 -1
  217. package/dist/messages.d.cts.map +1 -1
  218. package/dist/messages.d.ts.map +1 -1
  219. package/dist/messages.js +13 -9
  220. package/dist/messages.js.map +1 -1
  221. package/dist/metrics.cjs +258 -5
  222. package/dist/metrics.cjs.map +1 -1
  223. package/dist/metrics.d.cts +3 -1
  224. package/dist/metrics.d.cts.map +1 -1
  225. package/dist/metrics.d.ts +3 -1
  226. package/dist/metrics.d.ts.map +1 -1
  227. package/dist/metrics.js +255 -6
  228. package/dist/metrics.js.map +1 -1
  229. package/dist/moderation.cjs +10 -1
  230. package/dist/moderation.cjs.map +1 -1
  231. package/dist/moderation.d.cts.map +1 -1
  232. package/dist/moderation.d.ts.map +1 -1
  233. package/dist/moderation.js +10 -1
  234. package/dist/moderation.js.map +1 -1
  235. package/dist/ollama.cjs +5 -5
  236. package/dist/ollama.cjs.map +1 -1
  237. package/dist/ollama.js +6 -6
  238. package/dist/ollama.js.map +1 -1
  239. package/dist/openrouter-video.cjs +5 -5
  240. package/dist/openrouter-video.cjs.map +1 -1
  241. package/dist/openrouter-video.js +6 -6
  242. package/dist/openrouter-video.js.map +1 -1
  243. package/dist/recorder.cjs +45 -9
  244. package/dist/recorder.cjs.map +1 -1
  245. package/dist/recorder.d.cts.map +1 -1
  246. package/dist/recorder.d.ts.map +1 -1
  247. package/dist/recorder.js +43 -11
  248. package/dist/recorder.js.map +1 -1
  249. package/dist/responses.cjs +4 -3
  250. package/dist/responses.cjs.map +1 -1
  251. package/dist/responses.js +5 -5
  252. package/dist/responses.js.map +1 -1
  253. package/dist/router.cjs +20 -33
  254. package/dist/router.cjs.map +1 -1
  255. package/dist/router.d.cts +4 -1
  256. package/dist/router.d.cts.map +1 -1
  257. package/dist/router.d.ts +4 -1
  258. package/dist/router.d.ts.map +1 -1
  259. package/dist/router.js +20 -34
  260. package/dist/router.js.map +1 -1
  261. package/dist/server.cjs +701 -625
  262. package/dist/server.cjs.map +1 -1
  263. package/dist/server.d.cts +1 -0
  264. package/dist/server.d.cts.map +1 -1
  265. package/dist/server.d.ts +1 -0
  266. package/dist/server.d.ts.map +1 -1
  267. package/dist/server.js +704 -628
  268. package/dist/server.js.map +1 -1
  269. package/dist/speech.cjs +2 -2
  270. package/dist/speech.cjs.map +1 -1
  271. package/dist/speech.js +3 -3
  272. package/dist/speech.js.map +1 -1
  273. package/dist/transcription.cjs +4 -4
  274. package/dist/transcription.cjs.map +1 -1
  275. package/dist/transcription.js +5 -5
  276. package/dist/transcription.js.map +1 -1
  277. package/dist/types.d.cts +119 -16
  278. package/dist/types.d.cts.map +1 -1
  279. package/dist/types.d.ts +119 -16
  280. package/dist/types.d.ts.map +1 -1
  281. package/dist/validate-cli.cjs +925 -0
  282. package/dist/validate-cli.cjs.map +1 -0
  283. package/dist/validate-cli.js +924 -0
  284. package/dist/validate-cli.js.map +1 -0
  285. package/dist/vector-types.d.cts.map +1 -1
  286. package/dist/vector-types.d.ts.map +1 -1
  287. package/dist/veo-video.cjs +13 -13
  288. package/dist/veo-video.cjs.map +1 -1
  289. package/dist/veo-video.js +14 -14
  290. package/dist/veo-video.js.map +1 -1
  291. package/dist/video.cjs +4 -4
  292. package/dist/video.cjs.map +1 -1
  293. package/dist/video.d.cts +1 -1
  294. package/dist/video.d.cts.map +1 -1
  295. package/dist/video.d.ts +1 -1
  296. package/dist/video.d.ts.map +1 -1
  297. package/dist/video.js +5 -5
  298. package/dist/video.js.map +1 -1
  299. package/dist/vitest.cjs +13 -6
  300. package/dist/vitest.cjs.map +1 -1
  301. package/dist/vitest.d.cts +2 -1
  302. package/dist/vitest.d.cts.map +1 -1
  303. package/dist/vitest.d.ts +2 -1
  304. package/dist/vitest.d.ts.map +1 -1
  305. package/dist/vitest.js +14 -7
  306. package/dist/vitest.js.map +1 -1
  307. package/dist/watcher.cjs +2 -1
  308. package/dist/watcher.cjs.map +1 -1
  309. package/dist/watcher.js +2 -1
  310. package/dist/watcher.js.map +1 -1
  311. package/dist/ws-framing.cjs +150 -35
  312. package/dist/ws-framing.cjs.map +1 -1
  313. package/dist/ws-framing.d.cts +18 -3
  314. package/dist/ws-framing.d.cts.map +1 -1
  315. package/dist/ws-framing.d.ts +18 -3
  316. package/dist/ws-framing.d.ts.map +1 -1
  317. package/dist/ws-framing.js +151 -36
  318. package/dist/ws-framing.js.map +1 -1
  319. package/dist/ws-gemini-live.cjs +2 -2
  320. package/dist/ws-gemini-live.d.ts +2 -2
  321. package/dist/ws-gemini-live.js +2 -2
  322. package/dist/ws-live.cjs +401 -0
  323. package/dist/ws-live.cjs.map +1 -0
  324. package/dist/ws-live.js +400 -0
  325. package/dist/ws-live.js.map +1 -0
  326. package/dist/ws-realtime.cjs +46 -2
  327. package/dist/ws-realtime.cjs.map +1 -1
  328. package/dist/ws-realtime.d.cts.map +1 -1
  329. package/dist/ws-realtime.d.ts +2 -2
  330. package/dist/ws-realtime.d.ts.map +1 -1
  331. package/dist/ws-realtime.js +46 -2
  332. package/dist/ws-realtime.js.map +1 -1
  333. package/dist/ws-responses.cjs +2 -2
  334. package/dist/ws-responses.js +2 -2
  335. package/dist/ws-upstream.cjs +118 -0
  336. package/dist/ws-upstream.cjs.map +1 -0
  337. package/dist/ws-upstream.js +115 -0
  338. package/dist/ws-upstream.js.map +1 -0
  339. package/fixtures/openai-live-client.json +390 -0
  340. package/fixtures/openai-live-managed.json +709 -0
  341. package/package.json +1 -1
@@ -0,0 +1,924 @@
1
+ import { entryToFixture, renderValidationRef, validateFixtures } from "./fixture-loader.js";
2
+ import { Logger } from "./logger.js";
3
+ import { readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { format, parseArgs } from "node:util";
6
+
7
+ //#region src/validate-cli.ts
8
+ /**
9
+ * `aimock validate` subcommand — offline fixture lint.
10
+ *
11
+ * Usage: `aimock validate [--strict] [--json] [--] <path> [more paths ...]`
12
+ *
13
+ * Each path is a fixture file or a directory; directories are walked
14
+ * recursively for `*.json` in the same order `--fixtures <dir>` loads them.
15
+ * For each file: read bytes, JSON-parse, require a top-level
16
+ * `{ "fixtures": [...] }` envelope, convert the entries (surfacing the
17
+ * per-entry conversion warnings the server logs), then run the
18
+ * `validateFixtures` rules over that file's entries alone, so its findings
19
+ * are attributed to it.
20
+ *
21
+ * `validateFixtures` is then run a SECOND time over the union of every
22
+ * successfully-parsed file's entries, in load order. Its rules are not all
23
+ * per-fixture: `duplicate userMessage` and the catch-all ordering check look
24
+ * at the other fixtures in the array they are given. Run per file those two
25
+ * cannot see across files, so the findings the union pass adds — a
26
+ * `userMessage` duplicated in two files, a catch-all that is last in its own
27
+ * file but not last overall — are the cross-file ones. They are reported
28
+ * against the file that owns the fixture, with the other file named in the
29
+ * message; findings the per-file pass already made are not repeated.
30
+ *
31
+ * How this compares to the server's `--validate-on-load`, in both directions:
32
+ * - Stricter: there an unreadable, unparseable or wrong-shape file is
33
+ * non-fatal — it warns on stderr, contributes zero fixtures, and startup
34
+ * continues as long as the run loaded at least one fixture from somewhere.
35
+ * Here every such file fails the run — with one deliberate exception, for
36
+ * parity: a `*.json` file the WALK turned up that parses but carries no
37
+ * top-level `fixtures` array is not a fixture file (this package's own
38
+ * `fixtures/` tree holds aimock config files alongside fixtures), and is
39
+ * passed over with a note, exactly as the loader passes over it. A file
40
+ * the caller NAMES is still validated, wrong shape and all. Two walk
41
+ * hazards the server does not
42
+ * survive are refused outright rather than mirrored: a `*.json` path that
43
+ * is not a regular file (a FIFO, a socket, a device) is a per-file error
44
+ * here, where the server's `readFileSync` blocks on it forever; and a
45
+ * directory symlink that points back at a directory already being walked
46
+ * is reported once as a cycle, where the server recurses through it until
47
+ * the kernel returns ELOOP (~32 levels deep) and loads those levels'
48
+ * fixtures over and over. One diagnostic here has no counterpart there at
49
+ * all: an entry whose `match` is a string, a number, a boolean or an array
50
+ * converts, on both sides, into an EMPTY match — a catch-all answering
51
+ * every request — and the server loads it without a word. That is a server
52
+ * bug, not a rule this lint may quietly invent an error for, so it is a
53
+ * `[warning]` (which `--strict` promotes to a failure) rather than an
54
+ * error, and the fixture still goes on to the rules exactly as the server
55
+ * would build it.
56
+ * - Equal: the `validateFixtures` rules themselves, because of the union
57
+ * pass above, and the zero-fixture rule — a run whose inputs yield no
58
+ * fixtures at all is an error here, matching the server's "No fixtures
59
+ * loaded and validation/strict mode is enabled — aborting." A single
60
+ * `{"fixtures": []}` file alongside files that do load fixtures is an
61
+ * error in neither place. Equal too in what the inputs expand to: a path
62
+ * named twice, and a directory reached both directly and through an
63
+ * acyclic symlink to it, are validated once per mention, exactly as the
64
+ * server loads one `--fixtures` source per mention — so the duplicate
65
+ * fixtures that produces are reported here as the server reports them,
66
+ * one finding per (fixture, rule), the same count the server logs.
67
+ *
68
+ * A path mentioned more than once in one run is therefore several DIFFERENT
69
+ * loads that happen to share a name, and printing that bare name for each of
70
+ * them made them indistinguishable: a warning read as if a fixture shadowed
71
+ * itself. Each mention is numbered, and every rendering surface carries that
72
+ * number — human lines and their summary, cross-file references, and a
73
+ * `mention` field on each `--json` `files[]` entry. The `<path>[<n>]` suffix
74
+ * is printed only for a path that IS mentioned more than once, because for
75
+ * every other path the name alone already names one load; the `--json` field
76
+ * is always present so a consumer never has to infer it.
77
+ * - Weaker: this is a static lint. It never starts a server, so it covers
78
+ * nothing about binding, remote `--fixtures <url>` sources (it reads local
79
+ * paths only), `--watch` reloads, or any runtime behaviour.
80
+ *
81
+ * Nothing the filesystem or a fixture entry can do is allowed to escape this
82
+ * function: a malformed entry, an unreadable path, a stat failure or a symlink
83
+ * cycle each becomes a per-file `[error]` in the report, and a crash inside
84
+ * either `validateFixtures` pass becomes a file-level or run-level `[error]`,
85
+ * so the run still emits a report (valid JSON under `--json`) and still exits
86
+ * 1. Run-level errors print after the per-file output, and the "no fixtures
87
+ * loaded" one is withheld when a file already reported why it loaded none.
88
+ *
89
+ * Prints human lines by default (`file: [error|warning] #i message`) or a
90
+ * JSON document with `--json`. Everything that contributes to a non-zero exit
91
+ * goes to stderr, so a CI log's stderr always shows the reason; `--json` keeps
92
+ * stdout to the report alone and puts the reason on stderr. The two modes
93
+ * report the same facts: a fatal file is one record that both the stdout
94
+ * tally and `files[].errors` count, and `--json` emits a document for a usage
95
+ * error too — stdout is never empty on a `--json` run, whatever failed it.
96
+ * A path naming a remote source (`https://...`) is refused as unsupported
97
+ * rather than read as a filename. Exit codes:
98
+ * 0 = clean (warnings allowed unless `--strict`), 1 = everything that fails
99
+ * the run — errors / unreadable / unparseable / wrong shape / unwalkable path
100
+ * / no fixtures loaded at all, and a usage error (no paths or an unknown
101
+ * option) too, because every other CLI surface in this package exits 1 on a
102
+ * usage error and nothing here uses sysexits codes. `--help` is handled
103
+ * separately and exits 0.
104
+ */
105
+ const VALIDATE_HELP = `
106
+ Usage: aimock validate [options] [--] <path> [more paths ...]
107
+
108
+ Validate aimock fixture files offline. Each path is a fixture file or a
109
+ directory of them (walked recursively for *.json, like --fixtures <dir>).
110
+ Files are checked one at a time and then as one combined set, so the rules
111
+ that span files -- a userMessage duplicated across two files, a catch-all
112
+ that is not last overall -- are reported here as the server reports them.
113
+
114
+ Where the server's --validate-on-load differs: there an unreadable,
115
+ unparseable or wrong-shape file only warns and startup continues, while here
116
+ every such file fails the run. The one exception, which matches the loader: a
117
+ *.json file found by WALKING a directory that has no top-level "fixtures"
118
+ array is not a fixture file (an aimock config, say) and is skipped with a
119
+ note -- a file you name on the command line is still validated. As on the
120
+ server, a run that loads no fixtures at all is an error. This is a static lint: it starts no server and reads
121
+ local paths only (no remote --fixtures URL).
122
+
123
+ A path given twice is validated twice, because the server loads one set of
124
+ fixtures per --fixtures it is given; the duplicate fixtures that produces are
125
+ reported as the server reports them, one finding per fixture and rule. Such a
126
+ path is printed as <path>[<n>], numbering its mentions from 1, so each load
127
+ and every reference to its fixtures names one of them (--json reports the
128
+ number as "mention" on every file). A directory symlink pointing back at a
129
+ directory already being walked is a symlink cycle and fails the run; one
130
+ pointing anywhere else is followed, as the server follows it.
131
+
132
+ Options:
133
+ --strict Treat warnings as errors (exit 1 on warnings)
134
+ --json Emit a JSON report instead of human lines
135
+ -h, --help Show this help message
136
+ -- Stop option parsing; every later argument is a path
137
+ (use this for a path that begins with "-")
138
+
139
+ Exit codes:
140
+ 0 all files valid (warnings allowed unless --strict)
141
+ 1 anything that failed the run: validation errors; a malformed fixture
142
+ entry; an unreadable or unparseable file; a named path of the wrong
143
+ shape (a walked one is skipped instead); a path that
144
+ cannot be stat'd, read or walked (including a symlink cycle, or a
145
+ *.json path that is not a regular file); a directory holding no *.json;
146
+ no fixtures loaded from any input; --strict warnings; or a usage error
147
+ (no paths given, or an unknown option)
148
+ `.trim();
149
+ /** The indices a ref names, in a fixed order, for identity purposes. */
150
+ function refIndices(ref) {
151
+ return ref.rule === "duplicate-user-message" ? [ref.shadows] : [ref.shadowsFrom, ref.shadowsThrough];
152
+ }
153
+ /**
154
+ * A path argument that names a remote source rather than a local file: any
155
+ * `scheme://` prefix, not just http(s), so `ftp://` and friends get the same
156
+ * explanation instead of a filesystem error. A Windows drive letter ("C:\\x")
157
+ * has no `//` and is not matched.
158
+ */
159
+ const REMOTE_SOURCE = /^[a-z][a-z0-9+.-]*:\/\//i;
160
+ /** Render an unknown thrown value as a one-line message. */
161
+ function errText(err) {
162
+ return err instanceof Error ? err.message : String(err);
163
+ }
164
+ /**
165
+ * Record why a file produced no report at all. A fatal is ONE fact, so it is
166
+ * written once, here, into both shapes that report it: `fatal`, which names
167
+ * the reason, and `errors`, which is what every tally — the human summary
168
+ * line, the `--json` consumer counting `files[].errors` — actually counts.
169
+ * Set on `fatal` alone, the two modes disagreed: stdout said "1 error(s)"
170
+ * while the same run's JSON said `"errors": []`, so a CI script adding up the
171
+ * JSON saw a clean run that had exited 1.
172
+ *
173
+ * The finding carries no `index`: a fatal is about the file, not an entry
174
+ * (see `Finding.index`).
175
+ */
176
+ function setFatal(report, message) {
177
+ report.fatal = message;
178
+ report.errors.push({ message });
179
+ }
180
+ /** A file that never got as far as a report, with its fatal already recorded. */
181
+ function fatalReport(file, mention, message) {
182
+ const report = {
183
+ file,
184
+ mention,
185
+ fixtures: 0,
186
+ errors: [],
187
+ warnings: []
188
+ };
189
+ setFatal(report, message);
190
+ return report;
191
+ }
192
+ /**
193
+ * Logger that routes `warn` AND `error` into caller-supplied sinks instead of
194
+ * the console, so the per-entry conversion diagnostics `entryToFixture` emits
195
+ * land in the report rather than being dropped on the floor — and, under
196
+ * `--json`, never interleave with the JSON document on stdout/stderr.
197
+ * Exported for tests only; it is not part of the package's public API.
198
+ * `info`/`debug` are inert: they are already below this logger's "warn" level,
199
+ * and silencing them explicitly keeps future call sites off stdout too.
200
+ */
201
+ var CollectingLogger = class CollectingLogger extends Logger {
202
+ warnSink;
203
+ errorSink;
204
+ constructor(warnSink, errorSink) {
205
+ super("warn");
206
+ this.warnSink = warnSink;
207
+ this.errorSink = errorSink;
208
+ }
209
+ /**
210
+ * Serialise exactly as the sink this logger replaces does — byte for byte.
211
+ * `Logger` writes `console.warn("[aimock]", ...args)`, and console's
212
+ * formatting IS `util.format`, so the call it makes is
213
+ * `format("[aimock]", ...args)`: `"[aimock]"` is the FORMAT STRING and holds
214
+ * no specifiers, which is what makes a caller's own `%s`/`%d` inert and its
215
+ * arguments plain trailing values. Calling `format(...args)` instead
216
+ * promoted the caller's message into the format slot — so a message that
217
+ * happened to contain `%s` (a fixture path, say) swallowed the next
218
+ * argument — and dropped the `[aimock]` prefix, leaving the report and the
219
+ * server's own stderr disagreeing about the same diagnostic.
220
+ * `util.inspect` still renders object arguments readably, which is what
221
+ * `String(a)` could not do.
222
+ */
223
+ static format(args) {
224
+ return format("[aimock]", ...args);
225
+ }
226
+ warn(...args) {
227
+ this.warnSink(CollectingLogger.format(args));
228
+ }
229
+ error(...args) {
230
+ this.errorSink(CollectingLogger.format(args));
231
+ }
232
+ info(...args) {}
233
+ debug(...args) {}
234
+ };
235
+ /**
236
+ * Why a `*.json` file the WALK turned up is not a fixture file, or
237
+ * `undefined` if it is one (or if the question cannot be answered cheaply).
238
+ *
239
+ * A directory is not a fixture directory: this package ships `fixtures/`
240
+ * holding both fixture files and eight aimock CONFIG files — the six
241
+ * `fixtures/examples/**\/*-config.json`, `full-suite.json`, and
242
+ * `agui/agui-text-response.json`, whose AG-UI fixtures sit NESTED under
243
+ * `agui` where `--fixtures` cannot see them — which is why the documented
244
+ * `aimock validate ./fixtures/` exited 1 on the package's own tree. The
245
+ * server has the same mixture to deal with and passes over it:
246
+ * `loadFixtureFile` warns "Missing or invalid \"fixtures\" array", returns no
247
+ * fixtures, and startup continues. This mirrors that skip, so a walked
248
+ * directory reports on the fixture files in it and says what it passed over.
249
+ *
250
+ * Non-fixture means the file carries no top-level `fixtures` key at all (or
251
+ * is an aimock config). A `fixtures` key that is present but not an array is
252
+ * a MALFORMED fixture file and still fails the run, as the loader would refuse
253
+ * it. The skip applies ONLY to files the walk discovered — a path the caller named explicitly is still validated, and a
254
+ * wrong-shape file there still fails the run, because naming a file is
255
+ * asking about that file.
256
+ *
257
+ * A file carrying an aimock config section (`configSections`) is named as
258
+ * what it is rather than by what it lacks, because "not a fixture file" on
259
+ * its own is read as "holds no fixtures" — false of `agui`-sectioned configs,
260
+ * which hold AG-UI fixtures that `aimock --config`, not `--fixtures`, serves.
261
+ *
262
+ * Unreadable and unparseable are deliberately NOT skips. Returning
263
+ * `undefined` for them hands the file to `validateOneFile`, which reports the
264
+ * real read error or JSON syntax error — a defect in any `*.json` file, and
265
+ * one no config file has an excuse for either.
266
+ */
267
+ function nonFixtureSkipReason(file) {
268
+ let parsed;
269
+ try {
270
+ parsed = JSON.parse(readFileSync(file, "utf-8"));
271
+ } catch {
272
+ return;
273
+ }
274
+ const asConfig = aimockConfigDescription(parsed);
275
+ if (asConfig !== void 0) return `not a fixture file — ${asConfig}`;
276
+ if (typeof parsed === "object" && parsed !== null && "fixtures" in parsed) return void 0;
277
+ return "not a fixture file — no top-level \"fixtures\" key";
278
+ }
279
+ /**
280
+ * The mock sections of `AimockConfig` (config-loader.ts). An object carrying
281
+ * any of them is an aimock config file: `aimock --config <path>` starts a
282
+ * server from it, while `--fixtures <path>` loads nothing from it.
283
+ */
284
+ const CONFIG_SECTIONS = [
285
+ "llm",
286
+ "mcp",
287
+ "a2a",
288
+ "agui",
289
+ "vector",
290
+ "services"
291
+ ];
292
+ /**
293
+ * What a parsed-but-not-fixture-shaped JSON document IS, when it is an aimock
294
+ * config file, or `undefined` when it is not one. Used by both the walk's skip
295
+ * note and the fatal a NAMED file of that shape gets, so the two surfaces
296
+ * describe the same file the same way. The sections found are listed, so an
297
+ * `agui` config is never described as a file holding no fixtures — it holds
298
+ * AG-UI ones, nested where the fixture loader does not look.
299
+ */
300
+ function aimockConfigDescription(parsed) {
301
+ if (typeof parsed !== "object" || parsed === null) return void 0;
302
+ const doc = parsed;
303
+ const sections = CONFIG_SECTIONS.filter((key) => typeof doc[key] === "object" && doc[key]);
304
+ if (sections.length === 0) return void 0;
305
+ return `an aimock config file (${sections.join(", ")}), which "aimock --config" serves and "--fixtures" does not load`;
306
+ }
307
+ /**
308
+ * Collect `*.json` files under `dirPath`, recursing into subdirectories.
309
+ * Mirrors `loadFixturesFromDir`: within a directory the `*.json` files come
310
+ * first in sorted order, then its subdirectories in sorted order, so the
311
+ * reported order matches the server's load order, and the same stat-error
312
+ * handling — a vanished entry (ENOENT) is skipped silently, every other
313
+ * failure is surfaced. Unlike the loader, which only warns, each surfaced
314
+ * failure becomes a `fatal` entry that fails the run, and it is emitted in
315
+ * walk position (an unreadable subdirectory is reported where that
316
+ * subdirectory was reached, not after every file in the tree) so the report
317
+ * reads in encounter order. Entries that are neither directories nor
318
+ * `*.json` files are ignored, as they are by the loader.
319
+ *
320
+ * `ancestors` holds the real paths of the directories this call is nested
321
+ * inside. A directory whose real path is one of them closes a symlink cycle
322
+ * and is reported instead of walked; the server has no such guard and
323
+ * recurses through the cycle until the kernel returns ELOOP. A repeat visit
324
+ * that is NOT an ancestor — `root/link -> root/sub` alongside `root/sub` — is
325
+ * no cycle: it is walked again, because the server walks it again and loads
326
+ * those fixtures twice.
327
+ *
328
+ * A `*.json` entry that is not a regular file (a FIFO, a socket, a device)
329
+ * is a `fatal` entry rather than a target, because reading it is what the
330
+ * containment promise above cannot keep: `readFileSync` on a FIFO with no
331
+ * writer blocks forever, as it does on the server.
332
+ */
333
+ function collectJsonFiles(dirPath, ancestors, out = []) {
334
+ let realPath;
335
+ try {
336
+ realPath = realpathSync(dirPath);
337
+ } catch (err) {
338
+ out.push({
339
+ file: dirPath,
340
+ fatal: `Could not resolve directory: ${errText(err)}`
341
+ });
342
+ return out;
343
+ }
344
+ if (ancestors.includes(realPath)) {
345
+ out.push({
346
+ file: dirPath,
347
+ fatal: `Symlink cycle detected: already walking ${realPath}`
348
+ });
349
+ return out;
350
+ }
351
+ let names;
352
+ try {
353
+ names = readdirSync(dirPath);
354
+ } catch (err) {
355
+ out.push({
356
+ file: dirPath,
357
+ fatal: `Could not read directory: ${errText(err)}`
358
+ });
359
+ return out;
360
+ }
361
+ const subdirs = [];
362
+ for (const name of [...names].sort()) {
363
+ const fullPath = join(dirPath, name);
364
+ let stats;
365
+ try {
366
+ stats = statSync(fullPath);
367
+ } catch (err) {
368
+ if (err.code !== "ENOENT") out.push({
369
+ file: fullPath,
370
+ fatal: `Could not stat: ${errText(err)}`
371
+ });
372
+ continue;
373
+ }
374
+ if (stats.isDirectory()) subdirs.push(name);
375
+ else if (!name.endsWith(".json")) continue;
376
+ else if (stats.isFile()) {
377
+ const skipped = nonFixtureSkipReason(fullPath);
378
+ out.push(skipped === void 0 ? { file: fullPath } : {
379
+ file: fullPath,
380
+ skipped
381
+ });
382
+ } else out.push({
383
+ file: fullPath,
384
+ fatal: "Not a regular file"
385
+ });
386
+ }
387
+ const chain = [...ancestors, realPath];
388
+ for (const sub of subdirs) collectJsonFiles(join(dirPath, sub), chain, out);
389
+ return out;
390
+ }
391
+ /** The entry shape the loader and the server both assume, quoted verbatim. */
392
+ const ENTRY_SHAPE = "every entry needs { \"match\": { ... }, \"response\": { ... } }";
393
+ /** Name a value the way a fixture author would read it back in their JSON. */
394
+ function gotText(value) {
395
+ if (value === null) return "null";
396
+ if (value === void 0) return "absent";
397
+ if (Array.isArray(value)) return "an array";
398
+ return `a ${typeof value}`;
399
+ }
400
+ /**
401
+ * Classify a raw entry's shape, or return `undefined` when nothing about it is
402
+ * worth saying. Runs before `entryToFixture`, so every branch below is driven
403
+ * by the entry itself rather than by whichever exception the conversion
404
+ * happened to throw.
405
+ *
406
+ * A missing or non-object `response` is deliberately NOT classified here: the
407
+ * conversion accepts it (`{ ...undefined }` is `{}`), the server accepts it,
408
+ * and the `validateFixtures` rules already reject it by name — "response is
409
+ * not a recognized type (must have content, toolCalls, ...)" — which is the
410
+ * more actionable message of the two. Saying it here as well would report one
411
+ * defect twice. It is still named alongside `match` when `match` is fatal,
412
+ * because then the rules never run on the entry at all and an author fixing
413
+ * `{}` would otherwise need one round trip per missing key.
414
+ */
415
+ function classifyEntry(entry) {
416
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return {
417
+ severity: "error",
418
+ convertible: false,
419
+ why: `entry is ${gotText(entry)}, expected an object — ${ENTRY_SHAPE}`
420
+ };
421
+ const match = entry.match;
422
+ if (match === null || match === void 0) return {
423
+ severity: "error",
424
+ convertible: false,
425
+ why: `missing or non-object ${["match", "response"].filter((key) => {
426
+ const value = entry[key];
427
+ return value === null || typeof value !== "object" || Array.isArray(value);
428
+ }).map((k) => `"${k}"`).join(" and ")} — ${ENTRY_SHAPE}`
429
+ };
430
+ if (typeof match !== "object" || Array.isArray(match)) return {
431
+ severity: "warning",
432
+ convertible: true,
433
+ why: `"match" is ${gotText(match)}, not an object — every match field reads as undefined, so this entry is an empty match: a CATCH-ALL answering every request. The server loads it the same way, so this warns rather than errors; --strict fails on it. ${ENTRY_SHAPE}`
434
+ };
435
+ }
436
+ /**
437
+ * The backstop for an entry `classifyEntry` passed and `entryToFixture` threw
438
+ * on anyway (a `toolCalls: [null]`, say, which `normalizeResponse` walks).
439
+ * Which entry it was is the actionable half, so that leads; the raw thrown
440
+ * text follows as `detail`, which `--json` carries as its own field and the
441
+ * human report prints on an indented continuation line. It used to say
442
+ * `see "detail"`, naming a field only the `--json` report has — in human mode
443
+ * that pointed at nothing at all.
444
+ */
445
+ function unexpectedEntryFailure(index, err) {
446
+ return {
447
+ index,
448
+ message: `Invalid fixture entry #${index}: could not be converted to a fixture`,
449
+ detail: errText(err)
450
+ };
451
+ }
452
+ /**
453
+ * Validate one fixture file into a report. Every failure mode — unreadable,
454
+ * unparseable, wrong shape, or a single malformed entry — is recorded in the
455
+ * returned report rather than thrown.
456
+ *
457
+ * The converted fixtures are handed back alongside the report, with
458
+ * `indices[i]` giving the entry index `fixtures[i]` was converted from, so the
459
+ * cross-file union pass can append them and map its findings back to a file
460
+ * and an entry index.
461
+ */
462
+ function validateOneFile(file, mention) {
463
+ const report = {
464
+ file,
465
+ mention,
466
+ fixtures: 0,
467
+ errors: [],
468
+ warnings: []
469
+ };
470
+ const fixtures = [];
471
+ const sourceIndex = [];
472
+ const runErrors = [];
473
+ const identities = [];
474
+ let raw;
475
+ try {
476
+ raw = readFileSync(file, "utf-8");
477
+ } catch (err) {
478
+ setFatal(report, `Could not read file: ${errText(err)}`);
479
+ return {
480
+ report,
481
+ fixtures,
482
+ indices: sourceIndex,
483
+ identities,
484
+ runErrors
485
+ };
486
+ }
487
+ let parsed;
488
+ try {
489
+ parsed = JSON.parse(raw);
490
+ } catch (err) {
491
+ setFatal(report, `Invalid JSON: ${errText(err)}`);
492
+ return {
493
+ report,
494
+ fixtures,
495
+ indices: sourceIndex,
496
+ identities,
497
+ runErrors
498
+ };
499
+ }
500
+ if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.fixtures)) {
501
+ const asConfig = aimockConfigDescription(parsed);
502
+ setFatal(report, asConfig === void 0 ? "Missing or invalid \"fixtures\" array (expected { \"fixtures\": [...] })" : `Missing or invalid "fixtures" array (expected { "fixtures": [...] }) — this is ${asConfig}`);
503
+ return {
504
+ report,
505
+ fixtures,
506
+ indices: sourceIndex,
507
+ identities,
508
+ runErrors
509
+ };
510
+ }
511
+ let entryIndex = 0;
512
+ const entryLogger = new CollectingLogger((message) => report.warnings.push({
513
+ index: entryIndex,
514
+ message
515
+ }), (message) => report.errors.push({
516
+ index: entryIndex,
517
+ message
518
+ }));
519
+ const entries = parsed.fixtures;
520
+ for (let index = 0; index < entries.length; index++) {
521
+ entryIndex = index;
522
+ const defect = classifyEntry(entries[index]);
523
+ if (defect !== void 0) {
524
+ const label = defect.severity === "error" ? "Invalid fixture entry" : "Fixture entry";
525
+ const finding = {
526
+ index,
527
+ message: `${label} #${index}: ${defect.why}`
528
+ };
529
+ if (!defect.convertible) {
530
+ report.errors.push(finding);
531
+ continue;
532
+ }
533
+ report.warnings.push(finding);
534
+ }
535
+ try {
536
+ fixtures.push(entryToFixture(entries[index], entryLogger));
537
+ sourceIndex.push(index);
538
+ } catch (err) {
539
+ report.errors.push(unexpectedEntryFailure(index, err));
540
+ }
541
+ }
542
+ report.fixtures = fixtures.length;
543
+ const unresolved = /* @__PURE__ */ new Set();
544
+ const toEntryIndex = (fixtureIndex) => {
545
+ const entry = sourceIndex[fixtureIndex];
546
+ if (entry !== void 0) return entry;
547
+ if (!unresolved.has(fixtureIndex)) {
548
+ unresolved.add(fixtureIndex);
549
+ runErrors.push(`finding for fixture index ${fixtureIndex}, which maps to no entry in this file`);
550
+ }
551
+ return fixtureIndex;
552
+ };
553
+ try {
554
+ for (const r of validateFixtures(fixtures)) {
555
+ const index = toEntryIndex(r.fixtureIndex);
556
+ const refs = r.ref === void 0 ? [] : refIndices(r.ref).map(toEntryIndex);
557
+ const finding = {
558
+ index,
559
+ message: r.ref === void 0 ? r.message : renderValidationRef(r.ref, (i) => String(toEntryIndex(i)))
560
+ };
561
+ identities.push({
562
+ severity: r.severity,
563
+ index,
564
+ kind: r.ref === void 0 ? `message:${r.message}` : r.ref.rule,
565
+ refs,
566
+ finding
567
+ });
568
+ if (r.severity === "error") report.errors.push(finding);
569
+ else report.warnings.push(finding);
570
+ }
571
+ } catch (err) {
572
+ report.errors.push({ message: `Validation failed for this file: ${errText(err)}` });
573
+ }
574
+ return {
575
+ report,
576
+ fixtures,
577
+ indices: sourceIndex,
578
+ identities,
579
+ runErrors
580
+ };
581
+ }
582
+ /**
583
+ * `#<index> ` for a finding that belongs to one entry; empty for a file-level
584
+ * finding, which names no entry (see Finding.index). Shared by the human lines
585
+ * and the failure summary so a reader of either can locate the same entry.
586
+ */
587
+ const findingAt = (f) => f.index === void 0 ? "" : `#${f.index} `;
588
+ /**
589
+ * One-line reason a run failed, for the stderr side of `--json` output.
590
+ *
591
+ * It NAMES the failure first — the file and the finding that caused the
592
+ * non-zero exit — and only then totals what else failed, because the line is
593
+ * often the single line a CI log shows. Leading with a fixed list of counts
594
+ * put two zeros ("0 unreadable/invalid file(s), 0 file(s) with errors") in
595
+ * front of every strict-warning failure, where the reader has to get past the
596
+ * things that did NOT happen to reach the one that did. Counts that are zero
597
+ * are omitted for the same reason, and a file whose fatal is already the lead
598
+ * is counted as unreadable/invalid only, not a second time under "with
599
+ * errors" — its fatal now rides in `errors` as well (see `setFatal`).
600
+ */
601
+ function summarizeFailure(reports, strict, runErrors, name) {
602
+ const fatalFiles = reports.filter((r) => r.fatal !== void 0);
603
+ const erroredFiles = reports.filter((r) => r.fatal === void 0 && r.errors.length > 0);
604
+ const warnedFiles = reports.filter((r) => r.warnings.length > 0);
605
+ let lead;
606
+ if (fatalFiles[0] !== void 0) lead = `${name(fatalFiles[0])}: ${fatalFiles[0].fatal}`;
607
+ else if (erroredFiles[0] !== void 0) lead = `${name(erroredFiles[0])}: ${findingAt(erroredFiles[0].errors[0])}${erroredFiles[0].errors[0].message}`;
608
+ else if (runErrors[0] !== void 0) lead = runErrors[0];
609
+ else if (warnedFiles[0] !== void 0) lead = `${name(warnedFiles[0])}: ${findingAt(warnedFiles[0].warnings[0])}${warnedFiles[0].warnings[0].message} (--strict)`;
610
+ else lead = "the run failed";
611
+ const counts = [];
612
+ if (fatalFiles.length > 0) counts.push(`${fatalFiles.length} unreadable/invalid file(s)`);
613
+ if (erroredFiles.length > 0) counts.push(`${erroredFiles.length} file(s) with errors`);
614
+ if (runErrors.length > 0) counts.push(`${runErrors.length} run-level error(s)`);
615
+ if (strict && warnedFiles.length > 0) counts.push(`${warnedFiles.length} file(s) with warnings (--strict)`);
616
+ return `Error: fixture validation failed — ${lead} [${counts.join(", ")}].`;
617
+ }
618
+ function runValidateCli(deps = {}) {
619
+ const argv = deps.argv ?? process.argv.slice(2);
620
+ const log = deps.log ?? console.log.bind(console);
621
+ const logError = deps.logError ?? console.error.bind(console);
622
+ const exit = deps.exit ?? process.exit.bind(process);
623
+ /**
624
+ * Is `flag` present as an OPTION in argv — i.e. before the `--` terminator,
625
+ * after which every argument is a path? Needed because a usage error can be
626
+ * a `parseArgs` throw, which leaves no parsed `values` to consult, and the
627
+ * output mode still has to be honoured. `--flag=value` counts: these are all
628
+ * boolean options, so giving one a value IS the usage error being reported,
629
+ * and matching the bare token alone answered "no `--json` here" for the one
630
+ * argv that most obviously asked for JSON — leaving stdout empty.
631
+ */
632
+ const flagInArgv = (flag) => {
633
+ for (const arg of argv) {
634
+ if (arg === "--") return false;
635
+ if (arg === flag || arg.startsWith(`${flag}=`)) return true;
636
+ }
637
+ return false;
638
+ };
639
+ /**
640
+ * A usage error, in whichever mode the argv asked for. `--json` promises
641
+ * "one document on stdout" (README), and a run that fails on its own argv is
642
+ * still a run: emitting nothing there handed a CI job parsing stdout an
643
+ * empty buffer — a JSON parse error standing in for a perfectly ordinary
644
+ * "no paths given". The document reports the usage error the same way a
645
+ * run-level error is reported, so one consumer shape reads both. The
646
+ * human-readable reason plus the help text stay on stderr in both modes, so
647
+ * `--json` stdout is still the document alone.
648
+ */
649
+ const usageError = (message) => {
650
+ logError(`Error: ${message}\n\n${VALIDATE_HELP}`);
651
+ if (flagInArgv("--json")) log(JSON.stringify({
652
+ strict: flagInArgv("--strict"),
653
+ failed: true,
654
+ files: [],
655
+ run: {
656
+ fixtures: 0,
657
+ errors: [message]
658
+ }
659
+ }, null, 2));
660
+ exit(1);
661
+ };
662
+ let values;
663
+ let paths;
664
+ try {
665
+ const parsed = parseArgs({
666
+ args: argv,
667
+ options: {
668
+ strict: {
669
+ type: "boolean",
670
+ default: false
671
+ },
672
+ json: {
673
+ type: "boolean",
674
+ default: false
675
+ },
676
+ help: {
677
+ type: "boolean",
678
+ short: "h",
679
+ default: false
680
+ }
681
+ },
682
+ strict: true,
683
+ allowPositionals: true
684
+ });
685
+ values = parsed.values;
686
+ paths = parsed.positionals;
687
+ } catch (err) {
688
+ usageError(err instanceof Error ? err.message : String(err));
689
+ return;
690
+ }
691
+ if (values.help === true) {
692
+ log(values.json === true ? JSON.stringify({ help: VALIDATE_HELP }, null, 2) : VALIDATE_HELP);
693
+ exit(0);
694
+ return;
695
+ }
696
+ const strict = values.strict === true;
697
+ const json = values.json === true;
698
+ if (paths.length === 0) {
699
+ usageError("no fixture paths given.");
700
+ return;
701
+ }
702
+ const targets = [];
703
+ for (const path of paths) {
704
+ if (REMOTE_SOURCE.test(path)) {
705
+ targets.push({
706
+ file: path,
707
+ fatal: "Remote fixture source: this lint reads local paths only (the server's --fixtures accepts a URL; validate does not) — download the file and validate the local copy"
708
+ });
709
+ continue;
710
+ }
711
+ let stats;
712
+ try {
713
+ stats = statSync(path);
714
+ } catch (err) {
715
+ if (err.code === "ENOENT") targets.push({ file: path });
716
+ else targets.push({
717
+ file: path,
718
+ fatal: `Could not stat: ${errText(err)}`
719
+ });
720
+ continue;
721
+ }
722
+ if (!stats.isDirectory()) {
723
+ if (stats.isFile()) targets.push({ file: path });
724
+ else targets.push({
725
+ file: path,
726
+ fatal: "Not a regular file"
727
+ });
728
+ continue;
729
+ }
730
+ const entries = collectJsonFiles(path, []);
731
+ if (entries.length === 0) {
732
+ targets.push({
733
+ file: path,
734
+ fatal: "No .json fixture files found in directory"
735
+ });
736
+ continue;
737
+ }
738
+ targets.push(...entries);
739
+ }
740
+ const mentionKey = (file) => resolve(file);
741
+ const mentionCount = /* @__PURE__ */ new Map();
742
+ for (const target of targets) mentionCount.set(mentionKey(target.file), (mentionCount.get(mentionKey(target.file)) ?? 0) + 1);
743
+ const mentionsSoFar = /* @__PURE__ */ new Map();
744
+ const nextMention = (file) => {
745
+ const mention = (mentionsSoFar.get(mentionKey(file)) ?? 0) + 1;
746
+ mentionsSoFar.set(mentionKey(file), mention);
747
+ return mention;
748
+ };
749
+ /**
750
+ * How a file is NAMED in human output and in cross-file references. A path
751
+ * this run loads more than once gets its mention number, because the bare
752
+ * path names all of those loads at once: without it a second load's findings
753
+ * read as a file shadowing itself. A path loaded once is printed unadorned —
754
+ * there is nothing to tell it apart from, and "[1]" on every line of an
755
+ * ordinary run is noise. The `--json` report carries `mention` regardless.
756
+ */
757
+ const displayName = (report) => (mentionCount.get(mentionKey(report.file)) ?? 1) > 1 ? `${report.file}[${report.mention}]` : report.file;
758
+ const reports = [];
759
+ const union = [];
760
+ const provenance = [];
761
+ const reportedBySite = /* @__PURE__ */ new Map();
762
+ const fileIds = /* @__PURE__ */ new Map();
763
+ const runErrors = [];
764
+ const siteKey = (fileId, index, severity, kind) => [
765
+ fileId,
766
+ index,
767
+ severity,
768
+ kind
769
+ ].join("\0");
770
+ for (const target of targets) {
771
+ if (target.skipped !== void 0) {
772
+ reports.push({
773
+ file: target.file,
774
+ mention: nextMention(target.file),
775
+ fixtures: 0,
776
+ errors: [],
777
+ warnings: [],
778
+ skipped: target.skipped
779
+ });
780
+ continue;
781
+ }
782
+ if (target.fatal !== void 0) {
783
+ reports.push(fatalReport(target.file, nextMention(target.file), target.fatal));
784
+ continue;
785
+ }
786
+ let report;
787
+ let fixtures = [];
788
+ let indices = [];
789
+ let identities = [];
790
+ let fileRunErrors = [];
791
+ const mention = nextMention(target.file);
792
+ try {
793
+ ({report, fixtures, indices, identities, runErrors: fileRunErrors} = validateOneFile(target.file, mention));
794
+ } catch (err) {
795
+ report = fatalReport(target.file, mention, `Validation failed: ${errText(err)}`);
796
+ }
797
+ reports.push(report);
798
+ runErrors.push(...fileRunErrors.map((e) => `${displayName(report)}: ${e}`));
799
+ const fileId = fileIds.size;
800
+ fileIds.set(report, fileId);
801
+ for (const identity of identities) {
802
+ const key = siteKey(fileId, identity.index, identity.severity, identity.kind);
803
+ const atSite = reportedBySite.get(key) ?? [];
804
+ atSite.push({
805
+ finding: identity.finding,
806
+ refs: identity.refs.map((ref) => `${fileId}:${ref}`)
807
+ });
808
+ reportedBySite.set(key, atSite);
809
+ }
810
+ for (let i = 0; i < fixtures.length; i++) {
811
+ const index = indices[i];
812
+ if (index === void 0) runErrors.push(`${displayName(report)}: converted fixture ${i} has no source entry index; cross-file findings against it are reported at its array position`);
813
+ union.push(fixtures[i]);
814
+ provenance.push({
815
+ report,
816
+ index: index ?? i
817
+ });
818
+ }
819
+ }
820
+ let noFixturesLoaded = false;
821
+ const causeAlreadyReported = reports.some((r) => r.fatal !== void 0 || r.errors.length > 0);
822
+ if (union.length === 0) {
823
+ if (!causeAlreadyReported) {
824
+ runErrors.push("No fixtures loaded from any input — the server aborts startup on this under --validate-on-load/--strict");
825
+ noFixturesLoaded = true;
826
+ }
827
+ } else {
828
+ const describe = (unionIndex) => {
829
+ const origin = provenance[unionIndex];
830
+ return origin === void 0 ? String(unionIndex) : `${displayName(origin.report)} #${origin.index}`;
831
+ };
832
+ const targetOf = (unionIndex) => {
833
+ const origin = provenance[unionIndex];
834
+ if (origin === void 0) return `union:${unionIndex}`;
835
+ const fileId = fileIds.get(origin.report);
836
+ return fileId === void 0 ? `union:${unionIndex}` : `${fileId}:${origin.index}`;
837
+ };
838
+ const renderCrossFile = (ref) => {
839
+ if (ref.rule === "duplicate-user-message") return `duplicate userMessage '${ref.userMessage}' — shadows fixture ${describe(ref.shadows)}`;
840
+ const head = "empty match acts as catch-all but is not the last fixture";
841
+ return ref.shadowsFrom === ref.shadowsThrough ? `${head} — shadows ${describe(ref.shadowsFrom)}` : `${head} — shadows every later fixture, from ${describe(ref.shadowsFrom)} through ${describe(ref.shadowsThrough)}`;
842
+ };
843
+ try {
844
+ for (const r of validateFixtures(union)) {
845
+ const origin = provenance[r.fixtureIndex];
846
+ if (origin === void 0) {
847
+ runErrors.push(`Cross-file finding for an unknown fixture index ${r.fixtureIndex}: ${r.message}`);
848
+ continue;
849
+ }
850
+ const fileId = fileIds.get(origin.report);
851
+ if (fileId === void 0) {
852
+ runErrors.push(`Cross-file finding for an unrecognised file: ${r.message}`);
853
+ continue;
854
+ }
855
+ const kind = r.ref === void 0 ? `message:${r.message}` : r.ref.rule;
856
+ const refTargets = r.ref === void 0 ? [] : refIndices(r.ref).map(targetOf);
857
+ const message = `cross-file: ${r.ref === void 0 ? r.message : renderCrossFile(r.ref)}`;
858
+ const already = reportedBySite.get(siteKey(fileId, origin.index, r.severity, kind))?.shift();
859
+ if (already !== void 0) {
860
+ if (!(already.refs.length === refTargets.length && already.refs.every((target, i) => target === refTargets[i]))) already.finding.message = message;
861
+ continue;
862
+ }
863
+ if (r.severity === "error") origin.report.errors.push({
864
+ index: origin.index,
865
+ message
866
+ });
867
+ else origin.report.warnings.push({
868
+ index: origin.index,
869
+ message
870
+ });
871
+ }
872
+ } catch (err) {
873
+ runErrors.push(`Cross-file validation failed: ${errText(err)}`);
874
+ }
875
+ }
876
+ const hasFatal = reports.some((r) => r.fatal !== void 0);
877
+ const hasErrors = reports.some((r) => r.errors.length > 0) || runErrors.length > 0;
878
+ const hasWarnings = reports.some((r) => r.warnings.length > 0);
879
+ const failed = hasFatal || hasErrors || strict && hasWarnings;
880
+ const logWarning = strict ? logError : log;
881
+ if (json) {
882
+ log(JSON.stringify({
883
+ strict,
884
+ failed,
885
+ files: reports,
886
+ run: {
887
+ fixtures: union.length,
888
+ errors: runErrors
889
+ }
890
+ }, null, 2));
891
+ if (failed) logError(summarizeFailure(reports, strict, runErrors, displayName));
892
+ } else {
893
+ const at = findingAt;
894
+ const emitDetail = (f, sink) => {
895
+ if (f.detail !== void 0) sink(` ${f.detail}`);
896
+ };
897
+ for (const r of reports) {
898
+ const name = displayName(r);
899
+ if (r.skipped !== void 0) {
900
+ log(`${name}: skipped (${r.skipped})`);
901
+ continue;
902
+ }
903
+ for (const e of r.errors) {
904
+ logError(`${name}: [error] ${at(e)}${e.message}`);
905
+ emitDetail(e, logError);
906
+ }
907
+ for (const w of r.warnings) {
908
+ logWarning(`${name}: [warning] ${at(w)}${w.message}`);
909
+ emitDetail(w, logWarning);
910
+ }
911
+ if (r.errors.length === 0 && r.warnings.length === 0) if (r.fixtures === 0 && failed) {
912
+ const why = noFixturesLoaded ? "see the run-level error" : "the run failed elsewhere";
913
+ log(`${name}: ${r.fixtures} fixture(s), loaded nothing — ${why}`);
914
+ } else log(`${name}: OK (${r.fixtures} fixture(s))`);
915
+ else log(`${name}: ${r.fixtures} fixture(s), ${r.errors.length} error(s), ${r.warnings.length} warning(s)`);
916
+ }
917
+ for (const e of runErrors) logError(`[error] ${e}`);
918
+ }
919
+ exit(failed ? 1 : 0);
920
+ }
921
+
922
+ //#endregion
923
+ export { runValidateCli };
924
+ //# sourceMappingURL=validate-cli.js.map