@copilotkit/aimock 1.45.1 → 1.47.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 (492) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +25 -1
  4. package/README.md +11 -2
  5. package/dist/agui-mock.cjs +25 -25
  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 +25 -25
  10. package/dist/agui-mock.js.map +1 -1
  11. package/dist/agui-types.d.cts.map +1 -1
  12. package/dist/aimock-cli.cjs +15 -1
  13. package/dist/aimock-cli.cjs.map +1 -1
  14. package/dist/aimock-cli.d.cts.map +1 -1
  15. package/dist/aimock-cli.d.ts.map +1 -1
  16. package/dist/aimock-cli.js +16 -2
  17. package/dist/aimock-cli.js.map +1 -1
  18. package/dist/api-key-auth.cjs +10 -9
  19. package/dist/api-key-auth.cjs.map +1 -1
  20. package/dist/api-key-auth.d.cts.map +1 -1
  21. package/dist/api-key-auth.d.ts.map +1 -1
  22. package/dist/api-key-auth.js +11 -10
  23. package/dist/api-key-auth.js.map +1 -1
  24. package/dist/aws-event-stream.cjs +20 -23
  25. package/dist/aws-event-stream.cjs.map +1 -1
  26. package/dist/aws-event-stream.d.cts +0 -1
  27. package/dist/aws-event-stream.d.ts +0 -1
  28. package/dist/aws-event-stream.js +20 -24
  29. package/dist/aws-event-stream.js.map +1 -1
  30. package/dist/batches.cjs +2 -4
  31. package/dist/batches.cjs.map +1 -1
  32. package/dist/batches.d.cts.map +1 -1
  33. package/dist/batches.d.ts.map +1 -1
  34. package/dist/batches.js +2 -4
  35. package/dist/batches.js.map +1 -1
  36. package/dist/bedrock-converse.cjs +139 -161
  37. package/dist/bedrock-converse.cjs.map +1 -1
  38. package/dist/bedrock-converse.d.cts.map +1 -1
  39. package/dist/bedrock-converse.d.ts.map +1 -1
  40. package/dist/bedrock-converse.js +137 -159
  41. package/dist/bedrock-converse.js.map +1 -1
  42. package/dist/bedrock.cjs +175 -216
  43. package/dist/bedrock.cjs.map +1 -1
  44. package/dist/bedrock.d.cts.map +1 -1
  45. package/dist/bedrock.d.ts.map +1 -1
  46. package/dist/bedrock.js +172 -213
  47. package/dist/bedrock.js.map +1 -1
  48. package/dist/byteplus-video.cjs +11 -10
  49. package/dist/byteplus-video.cjs.map +1 -1
  50. package/dist/byteplus-video.d.cts.map +1 -1
  51. package/dist/byteplus-video.d.ts.map +1 -1
  52. package/dist/byteplus-video.js +5 -4
  53. package/dist/byteplus-video.js.map +1 -1
  54. package/dist/chaos.cjs +5 -4
  55. package/dist/chaos.cjs.map +1 -1
  56. package/dist/chaos.d.cts.map +1 -1
  57. package/dist/chaos.d.ts.map +1 -1
  58. package/dist/chaos.js +5 -4
  59. package/dist/chaos.js.map +1 -1
  60. package/dist/cli.cjs +15 -0
  61. package/dist/cli.cjs.map +1 -1
  62. package/dist/cli.js +15 -0
  63. package/dist/cli.js.map +1 -1
  64. package/dist/cohere.cjs +107 -180
  65. package/dist/cohere.cjs.map +1 -1
  66. package/dist/cohere.d.cts.map +1 -1
  67. package/dist/cohere.d.ts.map +1 -1
  68. package/dist/cohere.js +106 -179
  69. package/dist/cohere.js.map +1 -1
  70. package/dist/config-loader.cjs +29 -1
  71. package/dist/config-loader.cjs.map +1 -1
  72. package/dist/config-loader.d.cts +7 -1
  73. package/dist/config-loader.d.cts.map +1 -1
  74. package/dist/config-loader.d.ts +7 -1
  75. package/dist/config-loader.d.ts.map +1 -1
  76. package/dist/config-loader.js +29 -2
  77. package/dist/config-loader.js.map +1 -1
  78. package/dist/count-tokens.cjs +146 -0
  79. package/dist/count-tokens.cjs.map +1 -0
  80. package/dist/count-tokens.js +146 -0
  81. package/dist/count-tokens.js.map +1 -0
  82. package/dist/elevenlabs-audio.cjs +36 -34
  83. package/dist/elevenlabs-audio.cjs.map +1 -1
  84. package/dist/elevenlabs-audio.d.cts.map +1 -1
  85. package/dist/elevenlabs-audio.d.ts.map +1 -1
  86. package/dist/elevenlabs-audio.js +33 -31
  87. package/dist/elevenlabs-audio.js.map +1 -1
  88. package/dist/elevenlabs-voice.cjs +38 -37
  89. package/dist/elevenlabs-voice.cjs.map +1 -1
  90. package/dist/elevenlabs-voice.d.cts.map +1 -1
  91. package/dist/elevenlabs-voice.d.ts.map +1 -1
  92. package/dist/elevenlabs-voice.js +33 -32
  93. package/dist/elevenlabs-voice.js.map +1 -1
  94. package/dist/embedding-request.cjs +16 -0
  95. package/dist/embedding-request.cjs.map +1 -0
  96. package/dist/embedding-request.js +14 -0
  97. package/dist/embedding-request.js.map +1 -0
  98. package/dist/embeddings.cjs +30 -20
  99. package/dist/embeddings.cjs.map +1 -1
  100. package/dist/embeddings.d.cts.map +1 -1
  101. package/dist/embeddings.d.ts.map +1 -1
  102. package/dist/embeddings.js +30 -20
  103. package/dist/embeddings.js.map +1 -1
  104. package/dist/fal-audio.cjs +45 -43
  105. package/dist/fal-audio.cjs.map +1 -1
  106. package/dist/fal-audio.d.cts.map +1 -1
  107. package/dist/fal-audio.d.ts.map +1 -1
  108. package/dist/fal-audio.js +42 -40
  109. package/dist/fal-audio.js.map +1 -1
  110. package/dist/fal.cjs +17 -15
  111. package/dist/fal.cjs.map +1 -1
  112. package/dist/fal.js +16 -14
  113. package/dist/fal.js.map +1 -1
  114. package/dist/files.cjs +2 -4
  115. package/dist/files.cjs.map +1 -1
  116. package/dist/files.d.cts.map +1 -1
  117. package/dist/files.d.ts.map +1 -1
  118. package/dist/files.js +2 -4
  119. package/dist/files.js.map +1 -1
  120. package/dist/fine-tuning.cjs +2 -4
  121. package/dist/fine-tuning.cjs.map +1 -1
  122. package/dist/fine-tuning.d.cts.map +1 -1
  123. package/dist/fine-tuning.d.ts.map +1 -1
  124. package/dist/fine-tuning.js +2 -4
  125. package/dist/fine-tuning.js.map +1 -1
  126. package/dist/fixture-loader.cjs +140 -44
  127. package/dist/fixture-loader.cjs.map +1 -1
  128. package/dist/fixture-loader.d.cts.map +1 -1
  129. package/dist/fixture-loader.d.ts.map +1 -1
  130. package/dist/fixture-loader.js +141 -46
  131. package/dist/fixture-loader.js.map +1 -1
  132. package/dist/gemini-embeddings.cjs +26 -24
  133. package/dist/gemini-embeddings.cjs.map +1 -1
  134. package/dist/gemini-embeddings.js +26 -24
  135. package/dist/gemini-embeddings.js.map +1 -1
  136. package/dist/gemini-interactions.cjs +113 -156
  137. package/dist/gemini-interactions.cjs.map +1 -1
  138. package/dist/gemini-interactions.d.cts +0 -1
  139. package/dist/gemini-interactions.d.cts.map +1 -1
  140. package/dist/gemini-interactions.d.ts +0 -1
  141. package/dist/gemini-interactions.d.ts.map +1 -1
  142. package/dist/gemini-interactions.js +113 -156
  143. package/dist/gemini-interactions.js.map +1 -1
  144. package/dist/gemini.cjs +295 -218
  145. package/dist/gemini.cjs.map +1 -1
  146. package/dist/gemini.d.cts.map +1 -1
  147. package/dist/gemini.d.ts.map +1 -1
  148. package/dist/gemini.js +295 -219
  149. package/dist/gemini.js.map +1 -1
  150. package/dist/grok-video.cjs +14 -12
  151. package/dist/grok-video.cjs.map +1 -1
  152. package/dist/grok-video.d.cts.map +1 -1
  153. package/dist/grok-video.d.ts.map +1 -1
  154. package/dist/grok-video.js +8 -6
  155. package/dist/grok-video.js.map +1 -1
  156. package/dist/helpers.cjs +411 -75
  157. package/dist/helpers.cjs.map +1 -1
  158. package/dist/helpers.d.cts +51 -1
  159. package/dist/helpers.d.cts.map +1 -1
  160. package/dist/helpers.d.ts +51 -1
  161. package/dist/helpers.d.ts.map +1 -1
  162. package/dist/helpers.js +402 -74
  163. package/dist/helpers.js.map +1 -1
  164. package/dist/images.cjs +30 -28
  165. package/dist/images.cjs.map +1 -1
  166. package/dist/images.d.cts.map +1 -1
  167. package/dist/images.d.ts.map +1 -1
  168. package/dist/images.js +27 -25
  169. package/dist/images.js.map +1 -1
  170. package/dist/index.cjs +4 -2
  171. package/dist/index.d.cts +4 -4
  172. package/dist/index.d.ts +4 -4
  173. package/dist/index.js +4 -4
  174. package/dist/journal.cjs +3 -1
  175. package/dist/journal.cjs.map +1 -1
  176. package/dist/journal.d.cts.map +1 -1
  177. package/dist/journal.d.ts.map +1 -1
  178. package/dist/journal.js +2 -1
  179. package/dist/journal.js.map +1 -1
  180. package/dist/llmock.cjs +3 -0
  181. package/dist/llmock.cjs.map +1 -1
  182. package/dist/llmock.d.cts.map +1 -1
  183. package/dist/llmock.d.ts.map +1 -1
  184. package/dist/llmock.js +3 -0
  185. package/dist/llmock.js.map +1 -1
  186. package/dist/mcp-fakes.d.cts.map +1 -1
  187. package/dist/mcp-handler.cjs +7 -3
  188. package/dist/mcp-handler.cjs.map +1 -1
  189. package/dist/mcp-handler.js +7 -3
  190. package/dist/mcp-handler.js.map +1 -1
  191. package/dist/mcp-recorder.cjs +2 -1
  192. package/dist/mcp-recorder.cjs.map +1 -1
  193. package/dist/mcp-recorder.js +3 -2
  194. package/dist/mcp-recorder.js.map +1 -1
  195. package/dist/messages.cjs +235 -202
  196. package/dist/messages.cjs.map +1 -1
  197. package/dist/messages.d.cts.map +1 -1
  198. package/dist/messages.d.ts.map +1 -1
  199. package/dist/messages.js +234 -202
  200. package/dist/messages.js.map +1 -1
  201. package/dist/metrics.cjs +5 -2
  202. package/dist/metrics.cjs.map +1 -1
  203. package/dist/metrics.d.cts.map +1 -1
  204. package/dist/metrics.d.ts.map +1 -1
  205. package/dist/metrics.js +6 -3
  206. package/dist/metrics.js.map +1 -1
  207. package/dist/misbehavior.cjs +62 -3
  208. package/dist/misbehavior.cjs.map +1 -1
  209. package/dist/misbehavior.d.cts.map +1 -1
  210. package/dist/misbehavior.d.ts.map +1 -1
  211. package/dist/misbehavior.js +63 -4
  212. package/dist/misbehavior.js.map +1 -1
  213. package/dist/model-utils.cjs +1 -0
  214. package/dist/model-utils.cjs.map +1 -1
  215. package/dist/model-utils.js +1 -1
  216. package/dist/model-utils.js.map +1 -1
  217. package/dist/moderation.cjs +15 -12
  218. package/dist/moderation.cjs.map +1 -1
  219. package/dist/moderation.js +14 -11
  220. package/dist/moderation.js.map +1 -1
  221. package/dist/ndjson-writer.cjs +21 -23
  222. package/dist/ndjson-writer.cjs.map +1 -1
  223. package/dist/ndjson-writer.d.cts +0 -1
  224. package/dist/ndjson-writer.d.cts.map +1 -1
  225. package/dist/ndjson-writer.d.ts +0 -1
  226. package/dist/ndjson-writer.d.ts.map +1 -1
  227. package/dist/ndjson-writer.js +21 -24
  228. package/dist/ndjson-writer.js.map +1 -1
  229. package/dist/ollama.cjs +276 -210
  230. package/dist/ollama.cjs.map +1 -1
  231. package/dist/ollama.d.cts.map +1 -1
  232. package/dist/ollama.d.ts.map +1 -1
  233. package/dist/ollama.js +273 -207
  234. package/dist/ollama.js.map +1 -1
  235. package/dist/openapi.cjs +323 -3
  236. package/dist/openapi.cjs.map +1 -1
  237. package/dist/openapi.d.cts.map +1 -1
  238. package/dist/openapi.d.ts.map +1 -1
  239. package/dist/openapi.js +324 -4
  240. package/dist/openapi.js.map +1 -1
  241. package/dist/openrouter-chat.cjs +11 -155
  242. package/dist/openrouter-chat.cjs.map +1 -1
  243. package/dist/openrouter-chat.js +11 -155
  244. package/dist/openrouter-chat.js.map +1 -1
  245. package/dist/openrouter-video.cjs +51 -74
  246. package/dist/openrouter-video.cjs.map +1 -1
  247. package/dist/openrouter-video.d.cts.map +1 -1
  248. package/dist/openrouter-video.d.ts.map +1 -1
  249. package/dist/openrouter-video.js +37 -60
  250. package/dist/openrouter-video.js.map +1 -1
  251. package/dist/raw-validation.cjs +177 -0
  252. package/dist/raw-validation.cjs.map +1 -0
  253. package/dist/raw-validation.js +176 -0
  254. package/dist/raw-validation.js.map +1 -0
  255. package/dist/recorder.cjs +176 -95
  256. package/dist/recorder.cjs.map +1 -1
  257. package/dist/recorder.d.cts.map +1 -1
  258. package/dist/recorder.d.ts.map +1 -1
  259. package/dist/recorder.js +176 -95
  260. package/dist/recorder.js.map +1 -1
  261. package/dist/rerank.cjs +13 -11
  262. package/dist/rerank.cjs.map +1 -1
  263. package/dist/rerank.js +12 -10
  264. package/dist/rerank.js.map +1 -1
  265. package/dist/response/catalog/anthropic-page.cjs +39 -0
  266. package/dist/response/catalog/anthropic-page.cjs.map +1 -0
  267. package/dist/response/catalog/anthropic-page.js +38 -0
  268. package/dist/response/catalog/anthropic-page.js.map +1 -0
  269. package/dist/response/catalog/collect.cjs +61 -0
  270. package/dist/response/catalog/collect.cjs.map +1 -0
  271. package/dist/response/catalog/collect.js +59 -0
  272. package/dist/response/catalog/collect.js.map +1 -0
  273. package/dist/response/catalog/gemini-page.cjs +25 -0
  274. package/dist/response/catalog/gemini-page.cjs.map +1 -0
  275. package/dist/response/catalog/gemini-page.js +24 -0
  276. package/dist/response/catalog/gemini-page.js.map +1 -0
  277. package/dist/response/catalog/render.cjs +182 -0
  278. package/dist/response/catalog/render.cjs.map +1 -0
  279. package/dist/response/catalog/render.js +171 -0
  280. package/dist/response/catalog/render.js.map +1 -0
  281. package/dist/response/deliver.cjs +144 -0
  282. package/dist/response/deliver.cjs.map +1 -0
  283. package/dist/response/deliver.js +143 -0
  284. package/dist/response/deliver.js.map +1 -0
  285. package/dist/response/errors.cjs +225 -0
  286. package/dist/response/errors.cjs.map +1 -0
  287. package/dist/response/errors.js +224 -0
  288. package/dist/response/errors.js.map +1 -0
  289. package/dist/response/finish.cjs +39 -0
  290. package/dist/response/finish.cjs.map +1 -0
  291. package/dist/response/finish.js +35 -0
  292. package/dist/response/finish.js.map +1 -0
  293. package/dist/response/frame-loop.cjs +102 -0
  294. package/dist/response/frame-loop.cjs.map +1 -0
  295. package/dist/response/frame-loop.js +100 -0
  296. package/dist/response/frame-loop.js.map +1 -0
  297. package/dist/response/lifecycle.cjs +223 -0
  298. package/dist/response/lifecycle.cjs.map +1 -0
  299. package/dist/response/lifecycle.js +211 -0
  300. package/dist/response/lifecycle.js.map +1 -0
  301. package/dist/response/policy.cjs +126 -0
  302. package/dist/response/policy.cjs.map +1 -0
  303. package/dist/response/policy.js +120 -0
  304. package/dist/response/policy.js.map +1 -0
  305. package/dist/response/profiles.cjs +69 -0
  306. package/dist/response/profiles.cjs.map +1 -0
  307. package/dist/response/profiles.js +65 -0
  308. package/dist/response/profiles.js.map +1 -0
  309. package/dist/response/proxy.cjs +71 -0
  310. package/dist/response/proxy.cjs.map +1 -0
  311. package/dist/response/proxy.js +70 -0
  312. package/dist/response/proxy.js.map +1 -0
  313. package/dist/response/raw.cjs +228 -0
  314. package/dist/response/raw.cjs.map +1 -0
  315. package/dist/response/raw.js +227 -0
  316. package/dist/response/raw.js.map +1 -0
  317. package/dist/response/timing.cjs +157 -0
  318. package/dist/response/timing.cjs.map +1 -0
  319. package/dist/response/timing.js +150 -0
  320. package/dist/response/timing.js.map +1 -0
  321. package/dist/response/usage/codecs/anthropic.cjs +52 -0
  322. package/dist/response/usage/codecs/anthropic.cjs.map +1 -0
  323. package/dist/response/usage/codecs/anthropic.js +50 -0
  324. package/dist/response/usage/codecs/anthropic.js.map +1 -0
  325. package/dist/response/usage/codecs/cohere.cjs +36 -0
  326. package/dist/response/usage/codecs/cohere.cjs.map +1 -0
  327. package/dist/response/usage/codecs/cohere.js +35 -0
  328. package/dist/response/usage/codecs/cohere.js.map +1 -0
  329. package/dist/response/usage/codecs/converse.cjs +16 -0
  330. package/dist/response/usage/codecs/converse.cjs.map +1 -0
  331. package/dist/response/usage/codecs/converse.js +15 -0
  332. package/dist/response/usage/codecs/converse.js.map +1 -0
  333. package/dist/response/usage/codecs/gemini.cjs +31 -0
  334. package/dist/response/usage/codecs/gemini.cjs.map +1 -0
  335. package/dist/response/usage/codecs/gemini.js +31 -0
  336. package/dist/response/usage/codecs/gemini.js.map +1 -0
  337. package/dist/response/usage/codecs/interactions.cjs +22 -0
  338. package/dist/response/usage/codecs/interactions.cjs.map +1 -0
  339. package/dist/response/usage/codecs/interactions.js +21 -0
  340. package/dist/response/usage/codecs/interactions.js.map +1 -0
  341. package/dist/response/usage/codecs/ollama.cjs +17 -0
  342. package/dist/response/usage/codecs/ollama.cjs.map +1 -0
  343. package/dist/response/usage/codecs/ollama.js +17 -0
  344. package/dist/response/usage/codecs/ollama.js.map +1 -0
  345. package/dist/response/usage/codecs/openai.cjs +52 -0
  346. package/dist/response/usage/codecs/openai.cjs.map +1 -0
  347. package/dist/response/usage/codecs/openai.js +50 -0
  348. package/dist/response/usage/codecs/openai.js.map +1 -0
  349. package/dist/response/usage/codecs/openrouter.cjs +68 -0
  350. package/dist/response/usage/codecs/openrouter.cjs.map +1 -0
  351. package/dist/response/usage/codecs/openrouter.js +67 -0
  352. package/dist/response/usage/codecs/openrouter.js.map +1 -0
  353. package/dist/response/usage/codecs/realtime.cjs +19 -0
  354. package/dist/response/usage/codecs/realtime.cjs.map +1 -0
  355. package/dist/response/usage/codecs/realtime.js +18 -0
  356. package/dist/response/usage/codecs/realtime.js.map +1 -0
  357. package/dist/response/usage/codecs/responses.cjs +21 -0
  358. package/dist/response/usage/codecs/responses.cjs.map +1 -0
  359. package/dist/response/usage/codecs/responses.js +20 -0
  360. package/dist/response/usage/codecs/responses.js.map +1 -0
  361. package/dist/response/usage/estimate.cjs +23 -0
  362. package/dist/response/usage/estimate.cjs.map +1 -0
  363. package/dist/response/usage/estimate.js +21 -0
  364. package/dist/response/usage/estimate.js.map +1 -0
  365. package/dist/response/usage/fields.cjs +72 -0
  366. package/dist/response/usage/fields.cjs.map +1 -0
  367. package/dist/response/usage/fields.js +70 -0
  368. package/dist/response/usage/fields.js.map +1 -0
  369. package/dist/response/usage/recording.cjs +52 -0
  370. package/dist/response/usage/recording.cjs.map +1 -0
  371. package/dist/response/usage/recording.js +52 -0
  372. package/dist/response/usage/recording.js.map +1 -0
  373. package/dist/responses.cjs +304 -196
  374. package/dist/responses.cjs.map +1 -1
  375. package/dist/responses.d.cts.map +1 -1
  376. package/dist/responses.d.ts.map +1 -1
  377. package/dist/responses.js +303 -195
  378. package/dist/responses.js.map +1 -1
  379. package/dist/route-registry.cjs +45 -0
  380. package/dist/route-registry.cjs.map +1 -1
  381. package/dist/route-registry.d.cts.map +1 -1
  382. package/dist/route-registry.d.ts.map +1 -1
  383. package/dist/route-registry.js +41 -1
  384. package/dist/route-registry.js.map +1 -1
  385. package/dist/router.cjs +24 -4
  386. package/dist/router.cjs.map +1 -1
  387. package/dist/router.d.cts +7 -1
  388. package/dist/router.d.cts.map +1 -1
  389. package/dist/router.d.ts +7 -1
  390. package/dist/router.d.ts.map +1 -1
  391. package/dist/router.js +24 -5
  392. package/dist/router.js.map +1 -1
  393. package/dist/search.cjs +13 -11
  394. package/dist/search.cjs.map +1 -1
  395. package/dist/search.js +12 -10
  396. package/dist/search.js.map +1 -1
  397. package/dist/server.cjs +293 -248
  398. package/dist/server.cjs.map +1 -1
  399. package/dist/server.d.cts.map +1 -1
  400. package/dist/server.d.ts.map +1 -1
  401. package/dist/server.js +294 -249
  402. package/dist/server.js.map +1 -1
  403. package/dist/speech.cjs +20 -18
  404. package/dist/speech.cjs.map +1 -1
  405. package/dist/speech.d.cts.map +1 -1
  406. package/dist/speech.d.ts.map +1 -1
  407. package/dist/speech.js +19 -17
  408. package/dist/speech.js.map +1 -1
  409. package/dist/sse-writer.cjs +56 -30
  410. package/dist/sse-writer.cjs.map +1 -1
  411. package/dist/sse-writer.d.cts +0 -1
  412. package/dist/sse-writer.d.cts.map +1 -1
  413. package/dist/sse-writer.d.ts +0 -1
  414. package/dist/sse-writer.d.ts.map +1 -1
  415. package/dist/sse-writer.js +55 -31
  416. package/dist/sse-writer.js.map +1 -1
  417. package/dist/stream-collapse.cjs +118 -11
  418. package/dist/stream-collapse.cjs.map +1 -1
  419. package/dist/stream-collapse.d.cts +10 -9
  420. package/dist/stream-collapse.d.cts.map +1 -1
  421. package/dist/stream-collapse.d.ts +10 -9
  422. package/dist/stream-collapse.d.ts.map +1 -1
  423. package/dist/stream-collapse.js +118 -11
  424. package/dist/stream-collapse.js.map +1 -1
  425. package/dist/transcription.cjs +31 -43
  426. package/dist/transcription.cjs.map +1 -1
  427. package/dist/transcription.d.cts.map +1 -1
  428. package/dist/transcription.d.ts.map +1 -1
  429. package/dist/transcription.js +31 -43
  430. package/dist/transcription.js.map +1 -1
  431. package/dist/types.cjs.map +1 -1
  432. package/dist/types.d.cts +231 -9
  433. package/dist/types.d.cts.map +1 -1
  434. package/dist/types.d.ts +231 -9
  435. package/dist/types.d.ts.map +1 -1
  436. package/dist/types.js.map +1 -1
  437. package/dist/vector-mock.cjs +3 -8
  438. package/dist/vector-mock.cjs.map +1 -1
  439. package/dist/vector-mock.d.cts.map +1 -1
  440. package/dist/vector-mock.d.ts.map +1 -1
  441. package/dist/vector-mock.js +3 -8
  442. package/dist/vector-mock.js.map +1 -1
  443. package/dist/vector-stores.cjs +2 -4
  444. package/dist/vector-stores.cjs.map +1 -1
  445. package/dist/vector-stores.d.cts.map +1 -1
  446. package/dist/vector-stores.d.ts.map +1 -1
  447. package/dist/vector-stores.js +2 -4
  448. package/dist/vector-stores.js.map +1 -1
  449. package/dist/veo-video.cjs +16 -14
  450. package/dist/veo-video.cjs.map +1 -1
  451. package/dist/veo-video.js +10 -8
  452. package/dist/veo-video.js.map +1 -1
  453. package/dist/video.cjs +21 -19
  454. package/dist/video.cjs.map +1 -1
  455. package/dist/video.d.cts.map +1 -1
  456. package/dist/video.d.ts.map +1 -1
  457. package/dist/video.js +20 -18
  458. package/dist/video.js.map +1 -1
  459. package/dist/ws-framing.cjs +12 -6
  460. package/dist/ws-framing.cjs.map +1 -1
  461. package/dist/ws-framing.d.cts +2 -0
  462. package/dist/ws-framing.d.cts.map +1 -1
  463. package/dist/ws-framing.d.ts +2 -0
  464. package/dist/ws-framing.d.ts.map +1 -1
  465. package/dist/ws-framing.js +12 -6
  466. package/dist/ws-framing.js.map +1 -1
  467. package/dist/ws-gemini-live.cjs +131 -96
  468. package/dist/ws-gemini-live.cjs.map +1 -1
  469. package/dist/ws-gemini-live.d.cts +0 -1
  470. package/dist/ws-gemini-live.d.cts.map +1 -1
  471. package/dist/ws-gemini-live.d.ts +0 -1
  472. package/dist/ws-gemini-live.d.ts.map +1 -1
  473. package/dist/ws-gemini-live.js +130 -95
  474. package/dist/ws-gemini-live.js.map +1 -1
  475. package/dist/ws-live.cjs +6 -5
  476. package/dist/ws-live.cjs.map +1 -1
  477. package/dist/ws-live.js +5 -4
  478. package/dist/ws-live.js.map +1 -1
  479. package/dist/ws-realtime.cjs +108 -124
  480. package/dist/ws-realtime.cjs.map +1 -1
  481. package/dist/ws-realtime.d.cts.map +1 -1
  482. package/dist/ws-realtime.d.ts.map +1 -1
  483. package/dist/ws-realtime.js +105 -121
  484. package/dist/ws-realtime.js.map +1 -1
  485. package/dist/ws-responses.cjs +80 -59
  486. package/dist/ws-responses.cjs.map +1 -1
  487. package/dist/ws-responses.d.cts.map +1 -1
  488. package/dist/ws-responses.d.ts.map +1 -1
  489. package/dist/ws-responses.js +79 -58
  490. package/dist/ws-responses.js.map +1 -1
  491. package/package.json +4 -1
  492. package/skills/write-fixtures/SKILL.md +57 -16
@@ -73,5 +73,5 @@ function isReasoningModel(model) {
73
73
  }
74
74
 
75
75
  //#endregion
76
- export { isReasoningModel, normalizeModelName };
76
+ export { isReasoningModel, normalizeModelName, stripProviderPrefix };
77
77
  //# sourceMappingURL=model-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-utils.js","names":[],"sources":["../src/model-utils.ts"],"sourcesContent":["const DATE_SUFFIX_RE = /[-](\\d{8}(-v\\d+([:.]\\d+)*)?)$|[-]\\d{4}-\\d{2}-\\d{2}$/;\n\nexport function normalizeModelName(\n model: string | undefined,\n skipNormalization?: boolean,\n): string | undefined {\n if (!model || skipNormalization) return model;\n return model.replace(DATE_SUFFIX_RE, \"\");\n}\n\n// ─── Reasoning-capability map ───────────────────────────────────────────────\n//\n// `isReasoningModel` answers: \"would the REAL provider for this model id emit a\n// reasoning/thinking channel?\" aimock uses it to gate synthesized reasoning so a\n// fixture's `reasoning` field is not replayed for a model that cannot reason\n// (the gpt-4.1 false-green described in aimock#254).\n//\n// Policy (see the #254 spec for the full rationale):\n// - The KNOWN-NON-REASONING list (NONREASONING_FAMILIES) is the load-bearing\n// guard. A match there → false.\n// - The reasoning list (REASONING_FAMILIES) is mostly documentation; because\n// unknown ids default to `true` it is not load-bearing for correctness.\n// - UNKNOWN id → true (assume reasoning-capable). A false negative silently\n// breaks legitimate replays and is hard to notice; a false positive merely\n// fails to catch one mis-wiring class. Failing open keeps the blast radius\n// small and bounds maintenance to the explicit non-reasoning list.\n//\n// Env overrides let users correct drift without a release:\n// AIMOCK_REASONING_MODELS — comma-separated ids/prefixes forced capable.\n// AIMOCK_NONREASONING_MODELS — comma-separated ids/prefixes forced incapable.\n// Env entries are normalized IDENTICALLY to the incoming model id (date suffix\n// + provider/region prefix stripped, lowercased) so a prefixed entry such as\n// `anthropic.claude-opus-4` matches the already-stripped id.\n//\n// Precedence is BETWEEN lists, enforced by the sequential `if` checks below:\n// env-nonreasoning > env-reasoning > built-in-nonreasoning > built-in-reasoning > unknown(true)\n// Within any single list the result is order-INDEPENDENT — `matchesAny` uses\n// `Array.some(startsWith)`, so any prefix match yields that list's verdict.\n\n// Known non-reasoning families — the load-bearing denylist. Entries are matched\n// as prefixes against the normalized, lowercased, provider-stripped model id.\n// Order within this list does not matter (see `matchesAny`): any prefix that\n// matches the id produces `false`.\nconst NONREASONING_FAMILIES = [\n \"gpt-4.1\", // the exact model from aimock#254 (covers -mini / -nano)\n \"gpt-4o\", // covers gpt-4o-mini\n \"gpt-4-turbo\",\n \"gpt-4\", // plain gpt-4; order-independent, and prefix-safe since longer ids (gpt-4.1/gpt-4o/gpt-4-turbo) are also denylisted\n \"gpt-3.5\",\n \"claude-3-5-\", // Sonnet/Haiku 3.5 — no extended thinking\n \"claude-3-haiku\",\n \"claude-3-opus\",\n \"claude-3-sonnet\",\n \"gemini-1.5-\",\n];\n\n// Reasoning-capable families (informational; unknown already defaults to true).\nconst REASONING_FAMILIES = [\n \"o1\",\n \"o3\",\n \"o4\",\n \"gpt-5\",\n \"deepseek-r1\",\n \"deepseek-reasoner\",\n \"claude-3-7-sonnet\",\n \"claude-opus-4\",\n \"claude-sonnet-4\",\n \"claude-haiku-4\",\n \"gpt-oss\",\n \"gemini-2.5-pro\",\n \"gemini-2.5-flash\",\n \"gemini-2.0-flash-thinking\",\n \"qwq\",\n \"qwen3\",\n];\n\n/**\n * Strip a leading provider segment that Bedrock (and similar) prepend before\n * the actual family token — e.g. `anthropic.`, `us.anthropic.`, `eu.`. Keeps\n * everything from the recognised family token onward so prefix matching works.\n */\nfunction stripProviderPrefix(id: string): string {\n // Remove leading region/provider segments (dot-separated) until we hit the\n // model token. Provider/region segments never contain a hyphen, whereas\n // model families do (e.g. `claude-3-5-sonnet`, `gpt-4.1`). So drop any\n // leading dot-separated segment that has no hyphen.\n let rest = id;\n while (true) {\n const dot = rest.indexOf(\".\");\n if (dot === -1) break;\n const head = rest.slice(0, dot);\n if (head.length === 0 || head.includes(\"-\")) break;\n rest = rest.slice(dot + 1);\n }\n return rest;\n}\n\n// Normalize each comma-separated env entry IDENTICALLY to the incoming model id\n// (date-suffix + provider/region prefix stripped, lowercased) so a prefixed\n// entry such as `anthropic.claude-opus-4` matches the already-stripped id.\nfunction parseEnvList(raw: string | undefined): string[] {\n if (!raw) return [];\n return raw\n .split(\",\")\n .map((s) => stripProviderPrefix(normalizeModelName(s.trim())?.toLowerCase() ?? \"\"))\n .filter((s) => s.length > 0);\n}\n\nfunction matchesAny(id: string, families: readonly string[]): boolean {\n return families.some((fam) => id.startsWith(fam));\n}\n\n/**\n * Returns whether the real provider for `model` would emit a reasoning/thinking\n * channel. Absence of a model id, or an unrecognised id, defaults to `true`\n * (assume capable) — see the policy note above.\n */\nexport function isReasoningModel(model: string | undefined): boolean {\n if (!model) return true;\n\n const normalized = normalizeModelName(model)?.toLowerCase() ?? \"\";\n const id = stripProviderPrefix(normalized);\n\n // Env overrides win, parsed fresh so they remain test-stubbable.\n const envNon = parseEnvList(process.env.AIMOCK_NONREASONING_MODELS);\n if (matchesAny(id, envNon)) return false;\n const envReasoning = parseEnvList(process.env.AIMOCK_REASONING_MODELS);\n if (matchesAny(id, envReasoning)) return true;\n\n // Built-in denylist is the active guard.\n if (matchesAny(id, NONREASONING_FAMILIES)) return false;\n // Built-in reasoning list short-circuits to capable.\n if (matchesAny(id, REASONING_FAMILIES)) return true;\n\n // Unknown → assume reasoning-capable (fail open).\n return true;\n}\n"],"mappings":";AAAA,MAAM,iBAAiB;AAEvB,SAAgB,mBACd,OACA,mBACoB;AACpB,KAAI,CAAC,SAAS,kBAAmB,QAAO;AACxC,QAAO,MAAM,QAAQ,gBAAgB,GAAG;;AAoC1C,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAGD,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;AAOD,SAAS,oBAAoB,IAAoB;CAK/C,IAAI,OAAO;AACX,QAAO,MAAM;EACX,MAAM,MAAM,KAAK,QAAQ,IAAI;AAC7B,MAAI,QAAQ,GAAI;EAChB,MAAM,OAAO,KAAK,MAAM,GAAG,IAAI;AAC/B,MAAI,KAAK,WAAW,KAAK,KAAK,SAAS,IAAI,CAAE;AAC7C,SAAO,KAAK,MAAM,MAAM,EAAE;;AAE5B,QAAO;;AAMT,SAAS,aAAa,KAAmC;AACvD,KAAI,CAAC,IAAK,QAAO,EAAE;AACnB,QAAO,IACJ,MAAM,IAAI,CACV,KAAK,MAAM,oBAAoB,mBAAmB,EAAE,MAAM,CAAC,EAAE,aAAa,IAAI,GAAG,CAAC,CAClF,QAAQ,MAAM,EAAE,SAAS,EAAE;;AAGhC,SAAS,WAAW,IAAY,UAAsC;AACpE,QAAO,SAAS,MAAM,QAAQ,GAAG,WAAW,IAAI,CAAC;;;;;;;AAQnD,SAAgB,iBAAiB,OAAoC;AACnE,KAAI,CAAC,MAAO,QAAO;CAGnB,MAAM,KAAK,oBADQ,mBAAmB,MAAM,EAAE,aAAa,IAAI,GACrB;AAI1C,KAAI,WAAW,IADA,aAAa,QAAQ,IAAI,2BAA2B,CACzC,CAAE,QAAO;AAEnC,KAAI,WAAW,IADM,aAAa,QAAQ,IAAI,wBAAwB,CACtC,CAAE,QAAO;AAGzC,KAAI,WAAW,IAAI,sBAAsB,CAAE,QAAO;AAElD,KAAI,WAAW,IAAI,mBAAmB,CAAE,QAAO;AAG/C,QAAO"}
1
+ {"version":3,"file":"model-utils.js","names":[],"sources":["../src/model-utils.ts"],"sourcesContent":["const DATE_SUFFIX_RE = /[-](\\d{8}(-v\\d+([:.]\\d+)*)?)$|[-]\\d{4}-\\d{2}-\\d{2}$/;\n\nexport function normalizeModelName(\n model: string | undefined,\n skipNormalization?: boolean,\n): string | undefined {\n if (!model || skipNormalization) return model;\n return model.replace(DATE_SUFFIX_RE, \"\");\n}\n\n// ─── Reasoning-capability map ───────────────────────────────────────────────\n//\n// `isReasoningModel` answers: \"would the REAL provider for this model id emit a\n// reasoning/thinking channel?\" aimock uses it to gate synthesized reasoning so a\n// fixture's `reasoning` field is not replayed for a model that cannot reason\n// (the gpt-4.1 false-green described in aimock#254).\n//\n// Policy (see the #254 spec for the full rationale):\n// - The KNOWN-NON-REASONING list (NONREASONING_FAMILIES) is the load-bearing\n// guard. A match there → false.\n// - The reasoning list (REASONING_FAMILIES) is mostly documentation; because\n// unknown ids default to `true` it is not load-bearing for correctness.\n// - UNKNOWN id → true (assume reasoning-capable). A false negative silently\n// breaks legitimate replays and is hard to notice; a false positive merely\n// fails to catch one mis-wiring class. Failing open keeps the blast radius\n// small and bounds maintenance to the explicit non-reasoning list.\n//\n// Env overrides let users correct drift without a release:\n// AIMOCK_REASONING_MODELS — comma-separated ids/prefixes forced capable.\n// AIMOCK_NONREASONING_MODELS — comma-separated ids/prefixes forced incapable.\n// Env entries are normalized IDENTICALLY to the incoming model id (date suffix\n// + provider/region prefix stripped, lowercased) so a prefixed entry such as\n// `anthropic.claude-opus-4` matches the already-stripped id.\n//\n// Precedence is BETWEEN lists, enforced by the sequential `if` checks below:\n// env-nonreasoning > env-reasoning > built-in-nonreasoning > built-in-reasoning > unknown(true)\n// Within any single list the result is order-INDEPENDENT — `matchesAny` uses\n// `Array.some(startsWith)`, so any prefix match yields that list's verdict.\n\n// Known non-reasoning families — the load-bearing denylist. Entries are matched\n// as prefixes against the normalized, lowercased, provider-stripped model id.\n// Order within this list does not matter (see `matchesAny`): any prefix that\n// matches the id produces `false`.\nconst NONREASONING_FAMILIES = [\n \"gpt-4.1\", // the exact model from aimock#254 (covers -mini / -nano)\n \"gpt-4o\", // covers gpt-4o-mini\n \"gpt-4-turbo\",\n \"gpt-4\", // plain gpt-4; order-independent, and prefix-safe since longer ids (gpt-4.1/gpt-4o/gpt-4-turbo) are also denylisted\n \"gpt-3.5\",\n \"claude-3-5-\", // Sonnet/Haiku 3.5 — no extended thinking\n \"claude-3-haiku\",\n \"claude-3-opus\",\n \"claude-3-sonnet\",\n \"gemini-1.5-\",\n];\n\n// Reasoning-capable families (informational; unknown already defaults to true).\nconst REASONING_FAMILIES = [\n \"o1\",\n \"o3\",\n \"o4\",\n \"gpt-5\",\n \"deepseek-r1\",\n \"deepseek-reasoner\",\n \"claude-3-7-sonnet\",\n \"claude-opus-4\",\n \"claude-sonnet-4\",\n \"claude-haiku-4\",\n \"gpt-oss\",\n \"gemini-2.5-pro\",\n \"gemini-2.5-flash\",\n \"gemini-2.0-flash-thinking\",\n \"qwq\",\n \"qwen3\",\n];\n\n/**\n * Strip a leading provider segment that Bedrock (and similar) prepend before\n * the actual family token — e.g. `anthropic.`, `us.anthropic.`, `eu.`. Keeps\n * everything from the recognised family token onward so prefix matching works.\n */\nexport function stripProviderPrefix(id: string): string {\n // Remove leading region/provider segments (dot-separated) until we hit the\n // model token. Provider/region segments never contain a hyphen, whereas\n // model families do (e.g. `claude-3-5-sonnet`, `gpt-4.1`). So drop any\n // leading dot-separated segment that has no hyphen.\n let rest = id;\n while (true) {\n const dot = rest.indexOf(\".\");\n if (dot === -1) break;\n const head = rest.slice(0, dot);\n if (head.length === 0 || head.includes(\"-\")) break;\n rest = rest.slice(dot + 1);\n }\n return rest;\n}\n\n// Normalize each comma-separated env entry IDENTICALLY to the incoming model id\n// (date-suffix + provider/region prefix stripped, lowercased) so a prefixed\n// entry such as `anthropic.claude-opus-4` matches the already-stripped id.\nfunction parseEnvList(raw: string | undefined): string[] {\n if (!raw) return [];\n return raw\n .split(\",\")\n .map((s) => stripProviderPrefix(normalizeModelName(s.trim())?.toLowerCase() ?? \"\"))\n .filter((s) => s.length > 0);\n}\n\nfunction matchesAny(id: string, families: readonly string[]): boolean {\n return families.some((fam) => id.startsWith(fam));\n}\n\n/**\n * Returns whether the real provider for `model` would emit a reasoning/thinking\n * channel. Absence of a model id, or an unrecognised id, defaults to `true`\n * (assume capable) — see the policy note above.\n */\nexport function isReasoningModel(model: string | undefined): boolean {\n if (!model) return true;\n\n const normalized = normalizeModelName(model)?.toLowerCase() ?? \"\";\n const id = stripProviderPrefix(normalized);\n\n // Env overrides win, parsed fresh so they remain test-stubbable.\n const envNon = parseEnvList(process.env.AIMOCK_NONREASONING_MODELS);\n if (matchesAny(id, envNon)) return false;\n const envReasoning = parseEnvList(process.env.AIMOCK_REASONING_MODELS);\n if (matchesAny(id, envReasoning)) return true;\n\n // Built-in denylist is the active guard.\n if (matchesAny(id, NONREASONING_FAMILIES)) return false;\n // Built-in reasoning list short-circuits to capable.\n if (matchesAny(id, REASONING_FAMILIES)) return true;\n\n // Unknown → assume reasoning-capable (fail open).\n return true;\n}\n"],"mappings":";AAAA,MAAM,iBAAiB;AAEvB,SAAgB,mBACd,OACA,mBACoB;AACpB,KAAI,CAAC,SAAS,kBAAmB,QAAO;AACxC,QAAO,MAAM,QAAQ,gBAAgB,GAAG;;AAoC1C,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAGD,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;AAOD,SAAgB,oBAAoB,IAAoB;CAKtD,IAAI,OAAO;AACX,QAAO,MAAM;EACX,MAAM,MAAM,KAAK,QAAQ,IAAI;AAC7B,MAAI,QAAQ,GAAI;EAChB,MAAM,OAAO,KAAK,MAAM,GAAG,IAAI;AAC/B,MAAI,KAAK,WAAW,KAAK,KAAK,SAAS,IAAI,CAAE;AAC7C,SAAO,KAAK,MAAM,MAAM,EAAE;;AAE5B,QAAO;;AAMT,SAAS,aAAa,KAAmC;AACvD,KAAI,CAAC,IAAK,QAAO,EAAE;AACnB,QAAO,IACJ,MAAM,IAAI,CACV,KAAK,MAAM,oBAAoB,mBAAmB,EAAE,MAAM,CAAC,EAAE,aAAa,IAAI,GAAG,CAAC,CAClF,QAAQ,MAAM,EAAE,SAAS,EAAE;;AAGhC,SAAS,WAAW,IAAY,UAAsC;AACpE,QAAO,SAAS,MAAM,QAAQ,GAAG,WAAW,IAAI,CAAC;;;;;;;AAQnD,SAAgB,iBAAiB,OAAoC;AACnE,KAAI,CAAC,MAAO,QAAO;CAGnB,MAAM,KAAK,oBADQ,mBAAmB,MAAM,EAAE,aAAa,IAAI,GACrB;AAI1C,KAAI,WAAW,IADA,aAAa,QAAQ,IAAI,2BAA2B,CACzC,CAAE,QAAO;AAEnC,KAAI,WAAW,IADM,aAAa,QAAQ,IAAI,wBAAwB,CACtC,CAAE,QAAO;AAGzC,KAAI,WAAW,IAAI,sBAAsB,CAAE,QAAO;AAElD,KAAI,WAAW,IAAI,mBAAmB,CAAE,QAAO;AAG/C,QAAO"}
@@ -1,3 +1,5 @@
1
+ const require_errors = require('./response/errors.cjs');
2
+ const require_policy = require('./response/policy.cjs');
1
3
  const require_helpers = require('./helpers.cjs');
2
4
 
3
5
  //#region src/moderation.ts
@@ -62,11 +64,11 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
62
64
  }
63
65
  });
64
66
  res.writeHead(400, { "Content-Type": "application/json" });
65
- res.end(JSON.stringify({ error: {
67
+ res.end(require_errors.renderError("openai", "validation", {
66
68
  message: `Malformed JSON: ${detail}`,
67
69
  type: "invalid_request_error",
68
70
  code: "invalid_json"
69
- } }));
71
+ }).body);
70
72
  return;
71
73
  }
72
74
  if (!require_helpers.isJsonObject(body)) {
@@ -82,10 +84,10 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
82
84
  }
83
85
  });
84
86
  res.writeHead(400, { "Content-Type": "application/json" });
85
- res.end(JSON.stringify({ error: {
87
+ res.end(require_errors.renderError("openai", "validation", {
86
88
  message: "Request body must be a JSON object",
87
89
  type: "invalid_request_error"
88
- } }));
90
+ }).body);
89
91
  return;
90
92
  }
91
93
  const normalized = require_helpers.normalizeTextInput(body.input ?? "");
@@ -102,12 +104,13 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
102
104
  }
103
105
  });
104
106
  res.writeHead(400, { "Content-Type": "application/json" });
105
- res.end(JSON.stringify({ error: {
107
+ res.end(require_errors.renderError("openai", "validation", {
106
108
  message: "Invalid parameter: 'input' must be a string, an array of strings, or an array of multimodal parts",
107
109
  type: "invalid_request_error",
108
110
  param: null,
109
- code: null
110
- } }));
111
+ code: null,
112
+ includeParam: true
113
+ }).body);
111
114
  return;
112
115
  }
113
116
  const inputText = normalized;
@@ -121,7 +124,7 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
121
124
  }
122
125
  if (matchedFixture) logger.debug(`Moderation fixture matched for input "${inputText.slice(0, 80)}"`);
123
126
  else logger.debug(`No moderation fixture matched for input "${inputText.slice(0, 80)}" — returning unflagged`);
124
- if (!matchedFixture && require_helpers.resolveStrictMode(defaults.strict, req.headers)) {
127
+ if (!matchedFixture && require_policy.resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {
125
128
  const strictMessage = require_helpers.strictNoMatchMessage(0);
126
129
  logger.error(require_helpers.strictNoMatchLogLine(req.method ?? "POST", req.url ?? "/v1/moderations", 0));
127
130
  journal.add({
@@ -133,15 +136,15 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
133
136
  response: {
134
137
  status: 503,
135
138
  fixture: null,
136
- ...require_helpers.strictOverrideField(defaults.strict, req.headers)
139
+ ...require_policy.strictOverrideField(defaults.strict, req.headers)
137
140
  }
138
141
  });
139
142
  res.writeHead(503, { "Content-Type": "application/json" });
140
- res.end(JSON.stringify({ error: {
143
+ res.end(require_errors.renderError("openai", "strict-miss", {
141
144
  message: strictMessage,
142
145
  type: "invalid_request_error",
143
146
  code: "no_fixture_match"
144
- } }));
147
+ }).body);
145
148
  return;
146
149
  }
147
150
  journal.add({
@@ -153,7 +156,7 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
153
156
  response: {
154
157
  status: 200,
155
158
  fixture: null,
156
- ...require_helpers.strictOverrideField(defaults.strict, req.headers)
159
+ ...require_policy.strictOverrideField(defaults.strict, req.headers)
157
160
  }
158
161
  });
159
162
  res.writeHead(200, { "Content-Type": "application/json" });
@@ -1 +1 @@
1
- {"version":3,"file":"moderation.cjs","names":["flattenHeaders","isJsonObject","normalizeTextInput","matchesPattern","resolveStrictMode","strictNoMatchMessage","strictNoMatchLogLine","strictOverrideField","generateId"],"sources":["../src/moderation.ts"],"sourcesContent":["/**\n * Moderation API support for LLMock.\n *\n * Handles POST /v1/moderations requests (OpenAI-compatible). Matches\n * fixtures by comparing the request `input` field against registered\n * patterns. First match wins; no match returns a default unflagged result.\n */\n\nimport type * as http from \"node:http\";\nimport {\n flattenHeaders,\n generateId,\n isJsonObject,\n matchesPattern,\n normalizeTextInput,\n resolveStrictMode,\n strictNoMatchLogLine,\n strictNoMatchMessage,\n strictOverrideField,\n} from \"./helpers.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\n\n// ─── Moderation types ─────────────────────────────────────────────────────\n\nexport interface ModerationResult {\n flagged: boolean;\n categories: Record<string, boolean>;\n category_scores?: Record<string, number>;\n}\n\nexport interface ModerationFixture {\n match: string | RegExp;\n result: ModerationResult;\n}\n\n/**\n * Model echoed when the caller sends no `model`.\n *\n * The real API echoes back the model the request asked for. `text-moderation-*`\n * was removed from the OpenAI API on 2025-10-27; `omni-moderation-latest` is\n * the current moderation model, so it stands in when the caller omits one.\n */\nconst DEFAULT_MODERATION_MODEL = \"omni-moderation-latest\";\n\n// ─── Default unflagged result ─────────────────────────────────────────────\n\nconst DEFAULT_RESULT: ModerationResult = {\n flagged: false,\n categories: {\n sexual: false,\n hate: false,\n harassment: false,\n \"self-harm\": false,\n \"sexual/minors\": false,\n \"hate/threatening\": false,\n \"violence/graphic\": false,\n \"self-harm/intent\": false,\n \"self-harm/instructions\": false,\n \"harassment/threatening\": false,\n violence: false,\n illicit: false,\n \"illicit/violent\": false,\n },\n category_scores: {\n sexual: 0,\n hate: 0,\n harassment: 0,\n \"self-harm\": 0,\n \"sexual/minors\": 0,\n \"hate/threatening\": 0,\n \"violence/graphic\": 0,\n \"self-harm/intent\": 0,\n \"self-harm/instructions\": 0,\n \"harassment/threatening\": 0,\n violence: 0,\n illicit: 0,\n \"illicit/violent\": 0,\n },\n};\n\n// ─── Request handler ──────────────────────────────────────────────────────\n\nexport async function handleModeration(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: ModerationFixture[],\n journal: Journal,\n defaults: { logger: Logger; strict?: boolean },\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let body: { input?: string | string[]; model?: unknown };\n try {\n body = JSON.parse(raw) as { input?: string | string[]; model?: unknown };\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n },\n }),\n );\n return;\n }\n\n // Reject bodies that parsed but are not a JSON object (e.g. `null`) before\n // touching fields — otherwise `body.input` throws a TypeError that surfaces\n // as a 500 instead of a 400.\n if (!isJsonObject(body)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Normalize input to a single string for matching — reject non-string\n // inputs with 400 instead of crashing in matchesPattern()/slice() (500).\n const rawInput: unknown = body.input ?? \"\";\n const normalized = normalizeTextInput(rawInput);\n if (normalized === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: {\n message:\n \"Invalid parameter: 'input' must be a string, an array of strings, or an array of multimodal parts\",\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n const inputText = normalized;\n\n // Echo the requested model, like the real API. A missing (or non-string)\n // `model` falls back to the current default rather than a removed id.\n const requestedModel =\n typeof body.model === \"string\" && body.model.length > 0 ? body.model : DEFAULT_MODERATION_MODEL;\n\n // Find first matching fixture\n let matchedResult: ModerationResult = DEFAULT_RESULT;\n let matchedFixture: ModerationFixture | null = null;\n\n for (const fixture of fixtures) {\n if (matchesPattern(inputText, fixture.match)) {\n matchedFixture = fixture;\n matchedResult = fixture.result;\n break;\n }\n }\n\n if (matchedFixture) {\n logger.debug(`Moderation fixture matched for input \"${inputText.slice(0, 80)}\"`);\n } else {\n logger.debug(\n `No moderation fixture matched for input \"${inputText.slice(0, 80)}\" — returning unflagged`,\n );\n }\n\n // Strict mode turns the lenient default (unflagged) into a no-match error,\n // like every other fixture-matching handler. These fixtures carry no\n // sequence/turn state, so the skipped count is always 0.\n if (!matchedFixture && resolveStrictMode(defaults.strict, req.headers)) {\n const strictMessage = strictNoMatchMessage(0);\n logger.error(strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v1/moderations\", 0));\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n res.writeHead(503, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: {\n status: 200,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: generateId(\"modr\"),\n model: requestedModel,\n results: [matchedResult],\n }),\n );\n}\n"],"mappings":";;;;;;;;;;AA2CA,MAAM,2BAA2B;AAIjC,MAAM,iBAAmC;CACvC,SAAS;CACT,YAAY;EACV,QAAQ;EACR,MAAM;EACN,YAAY;EACZ,aAAa;EACb,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;EACpB,oBAAoB;EACpB,0BAA0B;EAC1B,0BAA0B;EAC1B,UAAU;EACV,SAAS;EACT,mBAAmB;EACpB;CACD,iBAAiB;EACf,QAAQ;EACR,MAAM;EAC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,MAAM,IAAI,OAAO;EACjB,SAASP,+BAAe,IAAI,QAAQ;EACpC,MAAM;EACN,SAAS;EACT,UAAU;GACR,QAAQ;GACR,SAAS;GACT,GAAGO,oCAAoB,SAAS,QAAQ,IAAI,QAAQ;GACrD;EACF,CAAC;AAEF,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IACF,KAAK,UAAU;EACb,IAAIC,2BAAW,OAAO;EACtB,OAAO;EACP,SAAS,CAAC,cAAc;EACzB,CAAC,CACH"}
1
+ {"version":3,"file":"moderation.cjs","names":["flattenHeaders","renderError","isJsonObject","normalizeTextInput","matchesPattern","resolveRequestDecisions","strictNoMatchMessage","strictNoMatchLogLine","strictOverrideField","generateId"],"sources":["../src/moderation.ts"],"sourcesContent":["/**\n * Moderation API support for LLMock.\n *\n * Handles POST /v1/moderations requests (OpenAI-compatible). Matches\n * fixtures by comparing the request `input` field against registered\n * patterns. First match wins; no match returns a default unflagged result.\n */\n\nimport type * as http from \"node:http\";\nimport { resolveRequestDecisions, strictOverrideField } from \"./response/policy.js\";\nimport { renderError } from \"./response/errors.js\";\nimport {\n flattenHeaders,\n generateId,\n isJsonObject,\n matchesPattern,\n normalizeTextInput,\n strictNoMatchLogLine,\n strictNoMatchMessage,\n} from \"./helpers.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\n\n// ─── Moderation types ─────────────────────────────────────────────────────\n\nexport interface ModerationResult {\n flagged: boolean;\n categories: Record<string, boolean>;\n category_scores?: Record<string, number>;\n}\n\nexport interface ModerationFixture {\n match: string | RegExp;\n result: ModerationResult;\n}\n\n/**\n * Model echoed when the caller sends no `model`.\n *\n * The real API echoes back the model the request asked for. `text-moderation-*`\n * was removed from the OpenAI API on 2025-10-27; `omni-moderation-latest` is\n * the current moderation model, so it stands in when the caller omits one.\n */\nconst DEFAULT_MODERATION_MODEL = \"omni-moderation-latest\";\n\n// ─── Default unflagged result ─────────────────────────────────────────────\n\nconst DEFAULT_RESULT: ModerationResult = {\n flagged: false,\n categories: {\n sexual: false,\n hate: false,\n harassment: false,\n \"self-harm\": false,\n \"sexual/minors\": false,\n \"hate/threatening\": false,\n \"violence/graphic\": false,\n \"self-harm/intent\": false,\n \"self-harm/instructions\": false,\n \"harassment/threatening\": false,\n violence: false,\n illicit: false,\n \"illicit/violent\": false,\n },\n category_scores: {\n sexual: 0,\n hate: 0,\n harassment: 0,\n \"self-harm\": 0,\n \"sexual/minors\": 0,\n \"hate/threatening\": 0,\n \"violence/graphic\": 0,\n \"self-harm/intent\": 0,\n \"self-harm/instructions\": 0,\n \"harassment/threatening\": 0,\n violence: 0,\n illicit: 0,\n \"illicit/violent\": 0,\n },\n};\n\n// ─── Request handler ──────────────────────────────────────────────────────\n\nexport async function handleModeration(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: ModerationFixture[],\n journal: Journal,\n defaults: { logger: Logger; strict?: boolean },\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let body: { input?: string | string[]; model?: unknown };\n try {\n body = JSON.parse(raw) as { input?: string | string[]; model?: unknown };\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n renderError(\"openai\", \"validation\", {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n }).body,\n );\n return;\n }\n\n // Reject bodies that parsed but are not a JSON object (e.g. `null`) before\n // touching fields — otherwise `body.input` throws a TypeError that surfaces\n // as a 500 instead of a 400.\n if (!isJsonObject(body)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n renderError(\"openai\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Normalize input to a single string for matching — reject non-string\n // inputs with 400 instead of crashing in matchesPattern()/slice() (500).\n const rawInput: unknown = body.input ?? \"\";\n const normalized = normalizeTextInput(rawInput);\n if (normalized === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n renderError(\"openai\", \"validation\", {\n message:\n \"Invalid parameter: 'input' must be a string, an array of strings, or an array of multimodal parts\",\n type: \"invalid_request_error\",\n param: null,\n code: null,\n includeParam: true,\n }).body,\n );\n return;\n }\n const inputText = normalized;\n\n // Echo the requested model, like the real API. A missing (or non-string)\n // `model` falls back to the current default rather than a removed id.\n const requestedModel =\n typeof body.model === \"string\" && body.model.length > 0 ? body.model : DEFAULT_MODERATION_MODEL;\n\n // Find first matching fixture\n let matchedResult: ModerationResult = DEFAULT_RESULT;\n let matchedFixture: ModerationFixture | null = null;\n\n for (const fixture of fixtures) {\n if (matchesPattern(inputText, fixture.match)) {\n matchedFixture = fixture;\n matchedResult = fixture.result;\n break;\n }\n }\n\n if (matchedFixture) {\n logger.debug(`Moderation fixture matched for input \"${inputText.slice(0, 80)}\"`);\n } else {\n logger.debug(\n `No moderation fixture matched for input \"${inputText.slice(0, 80)}\" — returning unflagged`,\n );\n }\n\n // Strict mode turns the lenient default (unflagged) into a no-match error,\n // like every other fixture-matching handler. These fixtures carry no\n // sequence/turn state, so the skipped count is always 0.\n if (!matchedFixture && resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {\n const strictMessage = strictNoMatchMessage(0);\n logger.error(strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v1/moderations\", 0));\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n res.writeHead(503, { \"Content-Type\": \"application/json\" });\n res.end(\n renderError(\"openai\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n }).body,\n );\n return;\n }\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: {\n status: 200,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: generateId(\"modr\"),\n model: requestedModel,\n results: [matchedResult],\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;AA2CA,MAAM,2BAA2B;AAIjC,MAAM,iBAAmC;CACvC,SAAS;CACT,YAAY;EACV,QAAQ;EACR,MAAM;EACN,YAAY;EACZ,aAAa;EACb,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;EACpB,oBAAoB;EACpB,0BAA0B;EAC1B,0BAA0B;EAC1B,UAAU;EACV,SAAS;EACT,mBAAmB;EACpB;CACD,iBAAiB;EACf,QAAQ;EACR,MAAM;EACN,YAAY;EACZ,aAAa;EACb,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;EACpB,oBAAoB;EACpB,0BAA0B;EAC1B,0BAA0B;EAC1B,UAAU;EACV,SAAS;EACT,mBAAmB;EACpB;CACF;AAID,eAAsB,iBACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACe;CACf,MAAM,EAAE,WAAW;AACnB,gBAAe,IAAI;CAEnB,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,MAAM,IAAI;UACf,UAAU;EACjB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SAAS,CAAC,cAAc;EACzB,CAAC,CACH"}
@@ -1,4 +1,6 @@
1
- import { flattenHeaders, generateId, isJsonObject, matchesPattern, normalizeTextInput, resolveStrictMode, strictNoMatchLogLine, strictNoMatchMessage, strictOverrideField } from "./helpers.js";
1
+ import { renderError } from "./response/errors.js";
2
+ import { resolveRequestDecisions, strictOverrideField } from "./response/policy.js";
3
+ import { flattenHeaders, generateId, isJsonObject, matchesPattern, normalizeTextInput, strictNoMatchLogLine, strictNoMatchMessage } from "./helpers.js";
2
4
 
3
5
  //#region src/moderation.ts
4
6
  /**
@@ -62,11 +64,11 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
62
64
  }
63
65
  });
64
66
  res.writeHead(400, { "Content-Type": "application/json" });
65
- res.end(JSON.stringify({ error: {
67
+ res.end(renderError("openai", "validation", {
66
68
  message: `Malformed JSON: ${detail}`,
67
69
  type: "invalid_request_error",
68
70
  code: "invalid_json"
69
- } }));
71
+ }).body);
70
72
  return;
71
73
  }
72
74
  if (!isJsonObject(body)) {
@@ -82,10 +84,10 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
82
84
  }
83
85
  });
84
86
  res.writeHead(400, { "Content-Type": "application/json" });
85
- res.end(JSON.stringify({ error: {
87
+ res.end(renderError("openai", "validation", {
86
88
  message: "Request body must be a JSON object",
87
89
  type: "invalid_request_error"
88
- } }));
90
+ }).body);
89
91
  return;
90
92
  }
91
93
  const normalized = normalizeTextInput(body.input ?? "");
@@ -102,12 +104,13 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
102
104
  }
103
105
  });
104
106
  res.writeHead(400, { "Content-Type": "application/json" });
105
- res.end(JSON.stringify({ error: {
107
+ res.end(renderError("openai", "validation", {
106
108
  message: "Invalid parameter: 'input' must be a string, an array of strings, or an array of multimodal parts",
107
109
  type: "invalid_request_error",
108
110
  param: null,
109
- code: null
110
- } }));
111
+ code: null,
112
+ includeParam: true
113
+ }).body);
111
114
  return;
112
115
  }
113
116
  const inputText = normalized;
@@ -121,7 +124,7 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
121
124
  }
122
125
  if (matchedFixture) logger.debug(`Moderation fixture matched for input "${inputText.slice(0, 80)}"`);
123
126
  else logger.debug(`No moderation fixture matched for input "${inputText.slice(0, 80)}" — returning unflagged`);
124
- if (!matchedFixture && resolveStrictMode(defaults.strict, req.headers)) {
127
+ if (!matchedFixture && resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {
125
128
  const strictMessage = strictNoMatchMessage(0);
126
129
  logger.error(strictNoMatchLogLine(req.method ?? "POST", req.url ?? "/v1/moderations", 0));
127
130
  journal.add({
@@ -137,11 +140,11 @@ async function handleModeration(req, res, raw, fixtures, journal, defaults, setC
137
140
  }
138
141
  });
139
142
  res.writeHead(503, { "Content-Type": "application/json" });
140
- res.end(JSON.stringify({ error: {
143
+ res.end(renderError("openai", "strict-miss", {
141
144
  message: strictMessage,
142
145
  type: "invalid_request_error",
143
146
  code: "no_fixture_match"
144
- } }));
147
+ }).body);
145
148
  return;
146
149
  }
147
150
  journal.add({
@@ -1 +1 @@
1
- {"version":3,"file":"moderation.js","names":[],"sources":["../src/moderation.ts"],"sourcesContent":["/**\n * Moderation API support for LLMock.\n *\n * Handles POST /v1/moderations requests (OpenAI-compatible). Matches\n * fixtures by comparing the request `input` field against registered\n * patterns. First match wins; no match returns a default unflagged result.\n */\n\nimport type * as http from \"node:http\";\nimport {\n flattenHeaders,\n generateId,\n isJsonObject,\n matchesPattern,\n normalizeTextInput,\n resolveStrictMode,\n strictNoMatchLogLine,\n strictNoMatchMessage,\n strictOverrideField,\n} from \"./helpers.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\n\n// ─── Moderation types ─────────────────────────────────────────────────────\n\nexport interface ModerationResult {\n flagged: boolean;\n categories: Record<string, boolean>;\n category_scores?: Record<string, number>;\n}\n\nexport interface ModerationFixture {\n match: string | RegExp;\n result: ModerationResult;\n}\n\n/**\n * Model echoed when the caller sends no `model`.\n *\n * The real API echoes back the model the request asked for. `text-moderation-*`\n * was removed from the OpenAI API on 2025-10-27; `omni-moderation-latest` is\n * the current moderation model, so it stands in when the caller omits one.\n */\nconst DEFAULT_MODERATION_MODEL = \"omni-moderation-latest\";\n\n// ─── Default unflagged result ─────────────────────────────────────────────\n\nconst DEFAULT_RESULT: ModerationResult = {\n flagged: false,\n categories: {\n sexual: false,\n hate: false,\n harassment: false,\n \"self-harm\": false,\n \"sexual/minors\": false,\n \"hate/threatening\": false,\n \"violence/graphic\": false,\n \"self-harm/intent\": false,\n \"self-harm/instructions\": false,\n \"harassment/threatening\": false,\n violence: false,\n illicit: false,\n \"illicit/violent\": false,\n },\n category_scores: {\n sexual: 0,\n hate: 0,\n harassment: 0,\n \"self-harm\": 0,\n \"sexual/minors\": 0,\n \"hate/threatening\": 0,\n \"violence/graphic\": 0,\n \"self-harm/intent\": 0,\n \"self-harm/instructions\": 0,\n \"harassment/threatening\": 0,\n violence: 0,\n illicit: 0,\n \"illicit/violent\": 0,\n },\n};\n\n// ─── Request handler ──────────────────────────────────────────────────────\n\nexport async function handleModeration(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: ModerationFixture[],\n journal: Journal,\n defaults: { logger: Logger; strict?: boolean },\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let body: { input?: string | string[]; model?: unknown };\n try {\n body = JSON.parse(raw) as { input?: string | string[]; model?: unknown };\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n },\n }),\n );\n return;\n }\n\n // Reject bodies that parsed but are not a JSON object (e.g. `null`) before\n // touching fields — otherwise `body.input` throws a TypeError that surfaces\n // as a 500 instead of a 400.\n if (!isJsonObject(body)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Normalize input to a single string for matching — reject non-string\n // inputs with 400 instead of crashing in matchesPattern()/slice() (500).\n const rawInput: unknown = body.input ?? \"\";\n const normalized = normalizeTextInput(rawInput);\n if (normalized === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: {\n message:\n \"Invalid parameter: 'input' must be a string, an array of strings, or an array of multimodal parts\",\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n const inputText = normalized;\n\n // Echo the requested model, like the real API. A missing (or non-string)\n // `model` falls back to the current default rather than a removed id.\n const requestedModel =\n typeof body.model === \"string\" && body.model.length > 0 ? body.model : DEFAULT_MODERATION_MODEL;\n\n // Find first matching fixture\n let matchedResult: ModerationResult = DEFAULT_RESULT;\n let matchedFixture: ModerationFixture | null = null;\n\n for (const fixture of fixtures) {\n if (matchesPattern(inputText, fixture.match)) {\n matchedFixture = fixture;\n matchedResult = fixture.result;\n break;\n }\n }\n\n if (matchedFixture) {\n logger.debug(`Moderation fixture matched for input \"${inputText.slice(0, 80)}\"`);\n } else {\n logger.debug(\n `No moderation fixture matched for input \"${inputText.slice(0, 80)}\" — returning unflagged`,\n );\n }\n\n // Strict mode turns the lenient default (unflagged) into a no-match error,\n // like every other fixture-matching handler. These fixtures carry no\n // sequence/turn state, so the skipped count is always 0.\n if (!matchedFixture && resolveStrictMode(defaults.strict, req.headers)) {\n const strictMessage = strictNoMatchMessage(0);\n logger.error(strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v1/moderations\", 0));\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n res.writeHead(503, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: {\n status: 200,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: generateId(\"modr\"),\n model: requestedModel,\n results: [matchedResult],\n }),\n );\n}\n"],"mappings":";;;;;;;;;;AA2CA,MAAM,2BAA2B;AAIjC,MAAM,iBAAmC;CACvC,SAAS;CACT,YAAY;EACV,QAAQ;EACR,MAAM;EACN,YAAY;EACZ,aAAa;EACb,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;EACpB,oBAAoB;EACpB,0BAA0B;EAC1B,0BAA0B;EAC1B,UAAU;EACV,SAAS;EACT,mBAAmB;EACpB;CACD,iBAAiB;EACf,QAAQ;EACR,MAAM;EACN,YAAY;EACZ,aAAa;EACb,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;EACpB,oBAAoB;EACpB,0BAA0B;EAC1B,0BAA0B;EAC1B,UAAU;EACV,SAAS;EACT,mBAAmB;EACpB;CACF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;AAEF,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IACF,KAAK,UAAU;EACb,IAAI,WAAW,OAAO;EACtB,OAAO;EACP,SAAS,CAAC,cAAc;EACzB,CAAC,CACH"}
1
+ {"version":3,"file":"moderation.js","names":[],"sources":["../src/moderation.ts"],"sourcesContent":["/**\n * Moderation API support for LLMock.\n *\n * Handles POST /v1/moderations requests (OpenAI-compatible). Matches\n * fixtures by comparing the request `input` field against registered\n * patterns. First match wins; no match returns a default unflagged result.\n */\n\nimport type * as http from \"node:http\";\nimport { resolveRequestDecisions, strictOverrideField } from \"./response/policy.js\";\nimport { renderError } from \"./response/errors.js\";\nimport {\n flattenHeaders,\n generateId,\n isJsonObject,\n matchesPattern,\n normalizeTextInput,\n strictNoMatchLogLine,\n strictNoMatchMessage,\n} from \"./helpers.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\n\n// ─── Moderation types ─────────────────────────────────────────────────────\n\nexport interface ModerationResult {\n flagged: boolean;\n categories: Record<string, boolean>;\n category_scores?: Record<string, number>;\n}\n\nexport interface ModerationFixture {\n match: string | RegExp;\n result: ModerationResult;\n}\n\n/**\n * Model echoed when the caller sends no `model`.\n *\n * The real API echoes back the model the request asked for. `text-moderation-*`\n * was removed from the OpenAI API on 2025-10-27; `omni-moderation-latest` is\n * the current moderation model, so it stands in when the caller omits one.\n */\nconst DEFAULT_MODERATION_MODEL = \"omni-moderation-latest\";\n\n// ─── Default unflagged result ─────────────────────────────────────────────\n\nconst DEFAULT_RESULT: ModerationResult = {\n flagged: false,\n categories: {\n sexual: false,\n hate: false,\n harassment: false,\n \"self-harm\": false,\n \"sexual/minors\": false,\n \"hate/threatening\": false,\n \"violence/graphic\": false,\n \"self-harm/intent\": false,\n \"self-harm/instructions\": false,\n \"harassment/threatening\": false,\n violence: false,\n illicit: false,\n \"illicit/violent\": false,\n },\n category_scores: {\n sexual: 0,\n hate: 0,\n harassment: 0,\n \"self-harm\": 0,\n \"sexual/minors\": 0,\n \"hate/threatening\": 0,\n \"violence/graphic\": 0,\n \"self-harm/intent\": 0,\n \"self-harm/instructions\": 0,\n \"harassment/threatening\": 0,\n violence: 0,\n illicit: 0,\n \"illicit/violent\": 0,\n },\n};\n\n// ─── Request handler ──────────────────────────────────────────────────────\n\nexport async function handleModeration(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: ModerationFixture[],\n journal: Journal,\n defaults: { logger: Logger; strict?: boolean },\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let body: { input?: string | string[]; model?: unknown };\n try {\n body = JSON.parse(raw) as { input?: string | string[]; model?: unknown };\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n renderError(\"openai\", \"validation\", {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n }).body,\n );\n return;\n }\n\n // Reject bodies that parsed but are not a JSON object (e.g. `null`) before\n // touching fields — otherwise `body.input` throws a TypeError that surfaces\n // as a 500 instead of a 400.\n if (!isJsonObject(body)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n renderError(\"openai\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Normalize input to a single string for matching — reject non-string\n // inputs with 400 instead of crashing in matchesPattern()/slice() (500).\n const rawInput: unknown = body.input ?? \"\";\n const normalized = normalizeTextInput(rawInput);\n if (normalized === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: { status: 400, fixture: null },\n });\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(\n renderError(\"openai\", \"validation\", {\n message:\n \"Invalid parameter: 'input' must be a string, an array of strings, or an array of multimodal parts\",\n type: \"invalid_request_error\",\n param: null,\n code: null,\n includeParam: true,\n }).body,\n );\n return;\n }\n const inputText = normalized;\n\n // Echo the requested model, like the real API. A missing (or non-string)\n // `model` falls back to the current default rather than a removed id.\n const requestedModel =\n typeof body.model === \"string\" && body.model.length > 0 ? body.model : DEFAULT_MODERATION_MODEL;\n\n // Find first matching fixture\n let matchedResult: ModerationResult = DEFAULT_RESULT;\n let matchedFixture: ModerationFixture | null = null;\n\n for (const fixture of fixtures) {\n if (matchesPattern(inputText, fixture.match)) {\n matchedFixture = fixture;\n matchedResult = fixture.result;\n break;\n }\n }\n\n if (matchedFixture) {\n logger.debug(`Moderation fixture matched for input \"${inputText.slice(0, 80)}\"`);\n } else {\n logger.debug(\n `No moderation fixture matched for input \"${inputText.slice(0, 80)}\" — returning unflagged`,\n );\n }\n\n // Strict mode turns the lenient default (unflagged) into a no-match error,\n // like every other fixture-matching handler. These fixtures carry no\n // sequence/turn state, so the skipped count is always 0.\n if (!matchedFixture && resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {\n const strictMessage = strictNoMatchMessage(0);\n logger.error(strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v1/moderations\", 0));\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n res.writeHead(503, { \"Content-Type\": \"application/json\" });\n res.end(\n renderError(\"openai\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n }).body,\n );\n return;\n }\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/moderations\",\n headers: flattenHeaders(req.headers),\n body: null,\n service: \"moderation\",\n response: {\n status: 200,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id: generateId(\"modr\"),\n model: requestedModel,\n results: [matchedResult],\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;AA2CA,MAAM,2BAA2B;AAIjC,MAAM,iBAAmC;CACvC,SAAS;CACT,YAAY;EACV,QAAQ;EACR,MAAM;EACN,YAAY;EACZ,aAAa;EACb,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;EACpB,oBAAoB;EACpB,0BAA0B;EAC1B,0BAA0B;EAC1B,UAAU;EACV,SAAS;EACT,mBAAmB;EACpB;CACD,iBAAiB;EACf,QAAQ;EACR,MAAM;EACN,YAAY;EACZ,aAAa;EACb,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;EACpB,oBAAoB;EACpB,0BAA0B;EAC1B,0BAA0B;EAC1B,UAAU;EACV,SAAS;EACT,mBAAmB;EACpB;CACF;AAID,eAAsB,iBACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACe;CACf,MAAM,EAAE,WAAW;AACnB,gBAAe,IAAI;CAEnB,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,MAAM,IAAI;UACf,UAAU;EACjB,MAAM,SAAS,oBAAoB,QAAQ,SAAS,UAAU;AAC9D,UAAQ,IAAI;GACV,QAAQ,IAAI,UAAU;GACtB,MAAM,IAAI,OAAO;GACjB,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,SAAS;GACT,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC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MAAM,GAAG,GAAG,CAAC,yBACpE;AAMH,KAAI,CAAC,kBAAkB,wBAAwB,SAAS,QAAQ,IAAI,QAAQ,CAAC,aAAa;EACxF,MAAM,gBAAgB,qBAAqB,EAAE;AAC7C,SAAO,MAAM,qBAAqB,IAAI,UAAU,QAAQ,IAAI,OAAO,mBAAmB,EAAE,CAAC;AACzF,UAAQ,IAAI;GACV,QAAQ,IAAI,UAAU;GACtB,MAAM,IAAI,OAAO;GACjB,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,SAAS;GACT,UAAU;IACR,QAAQ;IACR,SAAS;IACT,GAAG,oBAAoB,SAAS,QAAQ,IAAI,QAAQ;IACrD;GACF,CAAC;AACF,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IACF,YAAY,UAAU,eAAe;GACnC,SAAS;GACT,MAAM;GACN,MAAM;GACP,CAAC,CAAC,KACJ;AACD;;AAGF,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,SAAS;EACT,UAAU;GACR,QAAQ;GACR,SAAS;GACT,GAAG,oBAAoB,SAAS,QAAQ,IAAI,QAAQ;GACrD;EACF,CAAC;AAEF,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IACF,KAAK,UAAU;EACb,IAAI,WAAW,OAAO;EACtB,OAAO;EACP,SAAS,CAAC,cAAc;EACzB,CAAC,CACH"}
@@ -1,32 +1,30 @@
1
- const require_sse_writer = require('./sse-writer.cjs');
1
+ const require_frame_loop = require('./response/frame-loop.cjs');
2
2
 
3
3
  //#region src/ndjson-writer.ts
4
4
  async function writeNDJSONStream(res, chunks, options) {
5
5
  const opts = options ?? {};
6
- const latency = opts.latency ?? 0;
7
- const profile = opts.streamingProfile;
8
- const { recordedTimings, replaySpeed } = opts;
9
- const signal = opts.signal;
10
- const onChunkSent = opts.onChunkSent;
11
- if (res.writableEnded) return true;
12
- res.setHeader("Content-Type", "application/x-ndjson");
13
- res.setHeader("Cache-Control", "no-cache");
14
- res.setHeader("Connection", "keep-alive");
15
- let chunkIndex = 0;
16
- for (const chunk of chunks) {
17
- const chunkDelay = require_sse_writer.calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);
18
- if (chunkDelay > 0) await require_sse_writer.delay(chunkDelay, signal);
19
- if (signal?.aborted) return false;
20
- if (res.writableEnded) return true;
21
- res.write(JSON.stringify(chunk) + "\n");
22
- onChunkSent?.();
23
- if (signal?.aborted) return false;
24
- chunkIndex++;
25
- }
26
- if (!res.writableEnded) res.end();
27
- return true;
6
+ return require_frame_loop.runFrameLoop(require_frame_loop.httpSink(res), chunks, ndjsonCodec(), {
7
+ latency: opts.latency,
8
+ streamingProfile: opts.streamingProfile,
9
+ recordedTimings: opts.recordedTimings,
10
+ replaySpeed: opts.replaySpeed
11
+ }, {
12
+ signal: chunks.length > 0 ? opts.signal : void 0,
13
+ onChunkSent: opts.onChunkSent
14
+ });
15
+ }
16
+ function ndjsonCodec() {
17
+ return {
18
+ headers: {
19
+ "Content-Type": "application/x-ndjson",
20
+ "Cache-Control": "no-cache",
21
+ Connection: "keep-alive"
22
+ },
23
+ encode: (frame) => JSON.stringify(frame) + "\n"
24
+ };
28
25
  }
29
26
 
30
27
  //#endregion
28
+ exports.ndjsonCodec = ndjsonCodec;
31
29
  exports.writeNDJSONStream = writeNDJSONStream;
32
30
  //# sourceMappingURL=ndjson-writer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ndjson-writer.cjs","names":["calculateDelay","delay"],"sources":["../src/ndjson-writer.ts"],"sourcesContent":["/**\n * NDJSON streaming writer for Ollama endpoints.\n *\n * Mirrors writeSSEStream from sse-writer.ts but writes newline-delimited JSON\n * (one JSON object per line) instead of SSE events.\n */\n\nimport type * as http from \"node:http\";\nimport type { StreamingProfile, RecordedTimings } from \"./types.js\";\nimport { delay, calculateDelay } from \"./sse-writer.js\";\n\nexport interface NDJSONStreamOptions {\n latency?: number;\n streamingProfile?: StreamingProfile;\n recordedTimings?: RecordedTimings;\n replaySpeed?: number;\n signal?: AbortSignal;\n onChunkSent?: () => void;\n}\n\nexport async function writeNDJSONStream(\n res: http.ServerResponse,\n chunks: object[],\n options?: NDJSONStreamOptions,\n): Promise<boolean> {\n const opts = options ?? {};\n const latency = opts.latency ?? 0;\n const profile = opts.streamingProfile;\n const { recordedTimings, replaySpeed } = opts;\n const signal = opts.signal;\n const onChunkSent = opts.onChunkSent;\n\n if (res.writableEnded) return true;\n res.setHeader(\"Content-Type\", \"application/x-ndjson\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.setHeader(\"Connection\", \"keep-alive\");\n\n let chunkIndex = 0;\n for (const chunk of chunks) {\n const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);\n if (chunkDelay > 0) {\n await delay(chunkDelay, signal);\n }\n if (signal?.aborted) return false;\n if (res.writableEnded) return true;\n res.write(JSON.stringify(chunk) + \"\\n\");\n onChunkSent?.();\n if (signal?.aborted) return false;\n chunkIndex++;\n }\n\n if (!res.writableEnded) {\n res.end();\n }\n return true;\n}\n"],"mappings":";;;AAoBA,eAAsB,kBACpB,KACA,QACA,SACkB;CAClB,MAAM,OAAO,WAAW,EAAE;CAC1B,MAAM,UAAU,KAAK,WAAW;CAChC,MAAM,UAAU,KAAK;CACrB,MAAM,EAAE,iBAAiB,gBAAgB;CACzC,MAAM,SAAS,KAAK;CACpB,MAAM,cAAc,KAAK;AAEzB,KAAI,IAAI,cAAe,QAAO;AAC9B,KAAI,UAAU,gBAAgB,uBAAuB;AACrD,KAAI,UAAU,iBAAiB,WAAW;AAC1C,KAAI,UAAU,cAAc,aAAa;CAEzC,IAAI,aAAa;AACjB,MAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,aAAaA,kCAAe,YAAY,SAAS,SAAS,iBAAiB,YAAY;AAC7F,MAAI,aAAa,EACf,OAAMC,yBAAM,YAAY,OAAO;AAEjC,MAAI,QAAQ,QAAS,QAAO;AAC5B,MAAI,IAAI,cAAe,QAAO;AAC9B,MAAI,MAAM,KAAK,UAAU,MAAM,GAAG,KAAK;AACvC,iBAAe;AACf,MAAI,QAAQ,QAAS,QAAO;AAC5B;;AAGF,KAAI,CAAC,IAAI,cACP,KAAI,KAAK;AAEX,QAAO"}
1
+ {"version":3,"file":"ndjson-writer.cjs","names":["runFrameLoop","httpSink"],"sources":["../src/ndjson-writer.ts"],"sourcesContent":["/**\n * NDJSON streaming writer for Ollama endpoints.\n *\n * Mirrors writeSSEStream from sse-writer.ts but writes newline-delimited JSON\n * (one JSON object per line) instead of SSE events.\n */\n\nimport type * as http from \"node:http\";\nimport type { StreamingProfile, RecordedTimings } from \"./types.js\";\nimport { httpSink, runFrameLoop, type FrameCodec } from \"./response/frame-loop.js\";\n\nexport interface NDJSONStreamOptions {\n latency?: number;\n streamingProfile?: StreamingProfile;\n recordedTimings?: RecordedTimings;\n replaySpeed?: number;\n signal?: AbortSignal;\n onChunkSent?: () => void;\n}\n\nexport async function writeNDJSONStream(\n res: http.ServerResponse,\n chunks: object[],\n options?: NDJSONStreamOptions,\n): Promise<boolean> {\n const opts = options ?? {};\n // Base contract (public API): with no frames, an aborted signal does not\n // stop the writer; it still finishes the stream (any trailer, then end())\n // and returns true. The frame loop returns false there, so pass it no\n // signal when there are no frames (it reads the signal only per frame and\n // after the loop).\n return runFrameLoop(\n httpSink(res),\n chunks,\n ndjsonCodec(),\n {\n latency: opts.latency,\n streamingProfile: opts.streamingProfile,\n recordedTimings: opts.recordedTimings,\n replaySpeed: opts.replaySpeed,\n },\n { signal: chunks.length > 0 ? opts.signal : undefined, onChunkSent: opts.onChunkSent },\n );\n}\n\n// Internal (not part of the public API): newline-delimited JSON, one object\n// per line, no trailer (Ollama). Line comments, not JSDoc, so the bundled\n// .d.ts does not attach this comment to a public declaration.\nexport function ndjsonCodec<F = object>(): FrameCodec<F> {\n return {\n headers: {\n \"Content-Type\": \"application/x-ndjson\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n encode: (frame) => JSON.stringify(frame) + \"\\n\",\n };\n}\n"],"mappings":";;;AAoBA,eAAsB,kBACpB,KACA,QACA,SACkB;CAClB,MAAM,OAAO,WAAW,EAAE;AAM1B,QAAOA,gCACLC,4BAAS,IAAI,EACb,QACA,aAAa,EACb;EACE,SAAS,KAAK;EACd,kBAAkB,KAAK;EACvB,iBAAiB,KAAK;EACtB,aAAa,KAAK;EACnB,EACD;EAAE,QAAQ,OAAO,SAAS,IAAI,KAAK,SAAS;EAAW,aAAa,KAAK;EAAa,CACvF;;AAMH,SAAgB,cAAyC;AACvD,QAAO;EACL,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,YAAY;GACb;EACD,SAAS,UAAU,KAAK,UAAU,MAAM,GAAG;EAC5C"}
@@ -12,7 +12,6 @@ interface NDJSONStreamOptions {
12
12
  onChunkSent?: () => void;
13
13
  }
14
14
  declare function writeNDJSONStream(res: http$1.ServerResponse, chunks: object[], options?: NDJSONStreamOptions): Promise<boolean>;
15
- //# sourceMappingURL=ndjson-writer.d.ts.map
16
15
  //#endregion
17
16
  export { NDJSONStreamOptions, writeNDJSONStream };
18
17
  //# sourceMappingURL=ndjson-writer.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ndjson-writer.d.cts","names":[],"sources":["../src/ndjson-writer.ts"],"sourcesContent":[],"mappings":";;;;;AAgBW,UALM,mBAAA,CAKN;EAAW,OAAA,CAAA,EAAA,MAAA;EAIA,gBAAA,CAAA,EAPD,gBAOkB;EAAA,eAAA,CAAA,EANnB,eAMmB;aAC3B,CAAA,EAAA,MAAA;QAEA,CAAA,EAPD,WAOC;aACT,CAAA,EAAA,GAAA,GAAA,IAAA;;iBAJmB,iBAAA,MACf,MAAA,CAAK,4CAEA,sBACT"}
1
+ {"version":3,"file":"ndjson-writer.d.cts","names":[],"sources":["../src/ndjson-writer.ts"],"sourcesContent":[],"mappings":";;;;;AAgBsB,UALL,mBAAA,CAKK;EAIA,OAAA,CAAA,EAAA,MAAA;EAAiB,gBAAA,CAAA,EAPlB,gBAOkB;iBAC3B,CAAA,EAPQ,eAOR;aAEA,CAAA,EAAA,MAAA;QACT,CAAA,EARQ,WAQR;EAAO,WAAA,CAAA,EAAA,GAAA,GAAA,IAAA;;iBAJY,iBAAA,MACf,MAAA,CAAK,4CAEA,sBACT"}
@@ -12,7 +12,6 @@ interface NDJSONStreamOptions {
12
12
  onChunkSent?: () => void;
13
13
  }
14
14
  declare function writeNDJSONStream(res: http$1.ServerResponse, chunks: object[], options?: NDJSONStreamOptions): Promise<boolean>;
15
- //# sourceMappingURL=ndjson-writer.d.ts.map
16
15
  //#endregion
17
16
  export { NDJSONStreamOptions, writeNDJSONStream };
18
17
  //# sourceMappingURL=ndjson-writer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ndjson-writer.d.ts","names":[],"sources":["../src/ndjson-writer.ts"],"sourcesContent":[],"mappings":";;;;;AAgBW,UALM,mBAAA,CAKN;EAAW,OAAA,CAAA,EAAA,MAAA;EAIA,gBAAA,CAAA,EAPD,gBAOkB;EAAA,eAAA,CAAA,EANnB,eAMmB;aAC3B,CAAA,EAAA,MAAA;QAEA,CAAA,EAPD,WAOC;aACT,CAAA,EAAA,GAAA,GAAA,IAAA;;iBAJmB,iBAAA,MACf,MAAA,CAAK,4CAEA,sBACT"}
1
+ {"version":3,"file":"ndjson-writer.d.ts","names":[],"sources":["../src/ndjson-writer.ts"],"sourcesContent":[],"mappings":";;;;;AAgBsB,UALL,mBAAA,CAKK;EAIA,OAAA,CAAA,EAAA,MAAA;EAAiB,gBAAA,CAAA,EAPlB,gBAOkB;iBAC3B,CAAA,EAPQ,eAOR;aAEA,CAAA,EAAA,MAAA;QACT,CAAA,EARQ,WAQR;EAAO,WAAA,CAAA,EAAA,GAAA,GAAA,IAAA;;iBAJY,iBAAA,MACf,MAAA,CAAK,4CAEA,sBACT"}
@@ -1,32 +1,29 @@
1
- import { calculateDelay, delay } from "./sse-writer.js";
1
+ import { httpSink, runFrameLoop } from "./response/frame-loop.js";
2
2
 
3
3
  //#region src/ndjson-writer.ts
4
4
  async function writeNDJSONStream(res, chunks, options) {
5
5
  const opts = options ?? {};
6
- const latency = opts.latency ?? 0;
7
- const profile = opts.streamingProfile;
8
- const { recordedTimings, replaySpeed } = opts;
9
- const signal = opts.signal;
10
- const onChunkSent = opts.onChunkSent;
11
- if (res.writableEnded) return true;
12
- res.setHeader("Content-Type", "application/x-ndjson");
13
- res.setHeader("Cache-Control", "no-cache");
14
- res.setHeader("Connection", "keep-alive");
15
- let chunkIndex = 0;
16
- for (const chunk of chunks) {
17
- const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);
18
- if (chunkDelay > 0) await delay(chunkDelay, signal);
19
- if (signal?.aborted) return false;
20
- if (res.writableEnded) return true;
21
- res.write(JSON.stringify(chunk) + "\n");
22
- onChunkSent?.();
23
- if (signal?.aborted) return false;
24
- chunkIndex++;
25
- }
26
- if (!res.writableEnded) res.end();
27
- return true;
6
+ return runFrameLoop(httpSink(res), chunks, ndjsonCodec(), {
7
+ latency: opts.latency,
8
+ streamingProfile: opts.streamingProfile,
9
+ recordedTimings: opts.recordedTimings,
10
+ replaySpeed: opts.replaySpeed
11
+ }, {
12
+ signal: chunks.length > 0 ? opts.signal : void 0,
13
+ onChunkSent: opts.onChunkSent
14
+ });
15
+ }
16
+ function ndjsonCodec() {
17
+ return {
18
+ headers: {
19
+ "Content-Type": "application/x-ndjson",
20
+ "Cache-Control": "no-cache",
21
+ Connection: "keep-alive"
22
+ },
23
+ encode: (frame) => JSON.stringify(frame) + "\n"
24
+ };
28
25
  }
29
26
 
30
27
  //#endregion
31
- export { writeNDJSONStream };
28
+ export { ndjsonCodec, writeNDJSONStream };
32
29
  //# sourceMappingURL=ndjson-writer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ndjson-writer.js","names":[],"sources":["../src/ndjson-writer.ts"],"sourcesContent":["/**\n * NDJSON streaming writer for Ollama endpoints.\n *\n * Mirrors writeSSEStream from sse-writer.ts but writes newline-delimited JSON\n * (one JSON object per line) instead of SSE events.\n */\n\nimport type * as http from \"node:http\";\nimport type { StreamingProfile, RecordedTimings } from \"./types.js\";\nimport { delay, calculateDelay } from \"./sse-writer.js\";\n\nexport interface NDJSONStreamOptions {\n latency?: number;\n streamingProfile?: StreamingProfile;\n recordedTimings?: RecordedTimings;\n replaySpeed?: number;\n signal?: AbortSignal;\n onChunkSent?: () => void;\n}\n\nexport async function writeNDJSONStream(\n res: http.ServerResponse,\n chunks: object[],\n options?: NDJSONStreamOptions,\n): Promise<boolean> {\n const opts = options ?? {};\n const latency = opts.latency ?? 0;\n const profile = opts.streamingProfile;\n const { recordedTimings, replaySpeed } = opts;\n const signal = opts.signal;\n const onChunkSent = opts.onChunkSent;\n\n if (res.writableEnded) return true;\n res.setHeader(\"Content-Type\", \"application/x-ndjson\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.setHeader(\"Connection\", \"keep-alive\");\n\n let chunkIndex = 0;\n for (const chunk of chunks) {\n const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);\n if (chunkDelay > 0) {\n await delay(chunkDelay, signal);\n }\n if (signal?.aborted) return false;\n if (res.writableEnded) return true;\n res.write(JSON.stringify(chunk) + \"\\n\");\n onChunkSent?.();\n if (signal?.aborted) return false;\n chunkIndex++;\n }\n\n if (!res.writableEnded) {\n res.end();\n }\n return true;\n}\n"],"mappings":";;;AAoBA,eAAsB,kBACpB,KACA,QACA,SACkB;CAClB,MAAM,OAAO,WAAW,EAAE;CAC1B,MAAM,UAAU,KAAK,WAAW;CAChC,MAAM,UAAU,KAAK;CACrB,MAAM,EAAE,iBAAiB,gBAAgB;CACzC,MAAM,SAAS,KAAK;CACpB,MAAM,cAAc,KAAK;AAEzB,KAAI,IAAI,cAAe,QAAO;AAC9B,KAAI,UAAU,gBAAgB,uBAAuB;AACrD,KAAI,UAAU,iBAAiB,WAAW;AAC1C,KAAI,UAAU,cAAc,aAAa;CAEzC,IAAI,aAAa;AACjB,MAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,aAAa,eAAe,YAAY,SAAS,SAAS,iBAAiB,YAAY;AAC7F,MAAI,aAAa,EACf,OAAM,MAAM,YAAY,OAAO;AAEjC,MAAI,QAAQ,QAAS,QAAO;AAC5B,MAAI,IAAI,cAAe,QAAO;AAC9B,MAAI,MAAM,KAAK,UAAU,MAAM,GAAG,KAAK;AACvC,iBAAe;AACf,MAAI,QAAQ,QAAS,QAAO;AAC5B;;AAGF,KAAI,CAAC,IAAI,cACP,KAAI,KAAK;AAEX,QAAO"}
1
+ {"version":3,"file":"ndjson-writer.js","names":[],"sources":["../src/ndjson-writer.ts"],"sourcesContent":["/**\n * NDJSON streaming writer for Ollama endpoints.\n *\n * Mirrors writeSSEStream from sse-writer.ts but writes newline-delimited JSON\n * (one JSON object per line) instead of SSE events.\n */\n\nimport type * as http from \"node:http\";\nimport type { StreamingProfile, RecordedTimings } from \"./types.js\";\nimport { httpSink, runFrameLoop, type FrameCodec } from \"./response/frame-loop.js\";\n\nexport interface NDJSONStreamOptions {\n latency?: number;\n streamingProfile?: StreamingProfile;\n recordedTimings?: RecordedTimings;\n replaySpeed?: number;\n signal?: AbortSignal;\n onChunkSent?: () => void;\n}\n\nexport async function writeNDJSONStream(\n res: http.ServerResponse,\n chunks: object[],\n options?: NDJSONStreamOptions,\n): Promise<boolean> {\n const opts = options ?? {};\n // Base contract (public API): with no frames, an aborted signal does not\n // stop the writer; it still finishes the stream (any trailer, then end())\n // and returns true. The frame loop returns false there, so pass it no\n // signal when there are no frames (it reads the signal only per frame and\n // after the loop).\n return runFrameLoop(\n httpSink(res),\n chunks,\n ndjsonCodec(),\n {\n latency: opts.latency,\n streamingProfile: opts.streamingProfile,\n recordedTimings: opts.recordedTimings,\n replaySpeed: opts.replaySpeed,\n },\n { signal: chunks.length > 0 ? opts.signal : undefined, onChunkSent: opts.onChunkSent },\n );\n}\n\n// Internal (not part of the public API): newline-delimited JSON, one object\n// per line, no trailer (Ollama). Line comments, not JSDoc, so the bundled\n// .d.ts does not attach this comment to a public declaration.\nexport function ndjsonCodec<F = object>(): FrameCodec<F> {\n return {\n headers: {\n \"Content-Type\": \"application/x-ndjson\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n encode: (frame) => JSON.stringify(frame) + \"\\n\",\n };\n}\n"],"mappings":";;;AAoBA,eAAsB,kBACpB,KACA,QACA,SACkB;CAClB,MAAM,OAAO,WAAW,EAAE;AAM1B,QAAO,aACL,SAAS,IAAI,EACb,QACA,aAAa,EACb;EACE,SAAS,KAAK;EACd,kBAAkB,KAAK;EACvB,iBAAiB,KAAK;EACtB,aAAa,KAAK;EACnB,EACD;EAAE,QAAQ,OAAO,SAAS,IAAI,KAAK,SAAS;EAAW,aAAa,KAAK;EAAa,CACvF;;AAMH,SAAgB,cAAyC;AACvD,QAAO;EACL,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,YAAY;GACb;EACD,SAAS,UAAU,KAAK,UAAU,MAAM,GAAG;EAC5C"}