@copilotkit/aimock 1.42.1 → 1.44.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 (442) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +65 -0
  4. package/README.md +108 -16
  5. package/dist/agui-handler.d.ts.map +1 -1
  6. package/dist/agui-mock.cjs +1 -1
  7. package/dist/agui-mock.cjs.map +1 -1
  8. package/dist/agui-mock.d.cts.map +1 -1
  9. package/dist/agui-mock.d.ts.map +1 -1
  10. package/dist/agui-mock.js +1 -1
  11. package/dist/agui-mock.js.map +1 -1
  12. package/dist/agui-recorder.cjs +33 -11
  13. package/dist/agui-recorder.cjs.map +1 -1
  14. package/dist/agui-recorder.d.cts +10 -1
  15. package/dist/agui-recorder.d.cts.map +1 -1
  16. package/dist/agui-recorder.d.ts +10 -1
  17. package/dist/agui-recorder.d.ts.map +1 -1
  18. package/dist/agui-recorder.js +33 -11
  19. package/dist/agui-recorder.js.map +1 -1
  20. package/dist/agui-types.d.cts +1 -0
  21. package/dist/agui-types.d.cts.map +1 -1
  22. package/dist/agui-types.d.ts +1 -0
  23. package/dist/agui-types.d.ts.map +1 -1
  24. package/dist/aimock-cli.cjs +38 -10
  25. package/dist/aimock-cli.cjs.map +1 -1
  26. package/dist/aimock-cli.d.cts +5 -0
  27. package/dist/aimock-cli.d.cts.map +1 -1
  28. package/dist/aimock-cli.d.ts +5 -0
  29. package/dist/aimock-cli.d.ts.map +1 -1
  30. package/dist/aimock-cli.js +38 -10
  31. package/dist/aimock-cli.js.map +1 -1
  32. package/dist/batches.cjs +458 -0
  33. package/dist/batches.cjs.map +1 -0
  34. package/dist/batches.d.cts +57 -0
  35. package/dist/batches.d.cts.map +1 -0
  36. package/dist/batches.d.ts +57 -0
  37. package/dist/batches.d.ts.map +1 -0
  38. package/dist/batches.js +453 -0
  39. package/dist/batches.js.map +1 -0
  40. package/dist/bedrock-converse.cjs +44 -12
  41. package/dist/bedrock-converse.cjs.map +1 -1
  42. package/dist/bedrock-converse.d.cts.map +1 -1
  43. package/dist/bedrock-converse.d.ts.map +1 -1
  44. package/dist/bedrock-converse.js +46 -14
  45. package/dist/bedrock-converse.js.map +1 -1
  46. package/dist/bedrock.cjs +10 -8
  47. package/dist/bedrock.cjs.map +1 -1
  48. package/dist/bedrock.d.cts.map +1 -1
  49. package/dist/bedrock.d.ts.map +1 -1
  50. package/dist/bedrock.js +12 -10
  51. package/dist/bedrock.js.map +1 -1
  52. package/dist/byteplus-video.cjs +3 -3
  53. package/dist/byteplus-video.cjs.map +1 -1
  54. package/dist/byteplus-video.js +4 -4
  55. package/dist/byteplus-video.js.map +1 -1
  56. package/dist/chaos.cjs +625 -72
  57. package/dist/chaos.cjs.map +1 -1
  58. package/dist/chaos.d.cts +164 -7
  59. package/dist/chaos.d.cts.map +1 -1
  60. package/dist/chaos.d.ts +164 -7
  61. package/dist/chaos.d.ts.map +1 -1
  62. package/dist/chaos.js +616 -74
  63. package/dist/chaos.js.map +1 -1
  64. package/dist/cli.cjs +131 -30
  65. package/dist/cli.cjs.map +1 -1
  66. package/dist/cli.js +132 -31
  67. package/dist/cli.js.map +1 -1
  68. package/dist/cohere.cjs +37 -9
  69. package/dist/cohere.cjs.map +1 -1
  70. package/dist/cohere.d.cts.map +1 -1
  71. package/dist/cohere.d.ts.map +1 -1
  72. package/dist/cohere.js +39 -11
  73. package/dist/cohere.js.map +1 -1
  74. package/dist/config-loader.cjs +1 -1
  75. package/dist/config-loader.js +1 -1
  76. package/dist/constants.cjs +8 -0
  77. package/dist/constants.cjs.map +1 -1
  78. package/dist/constants.d.cts +6 -2
  79. package/dist/constants.d.ts +6 -2
  80. package/dist/constants.js +8 -1
  81. package/dist/constants.js.map +1 -1
  82. package/dist/convert.cjs +1 -1
  83. package/dist/convert.cjs.map +1 -1
  84. package/dist/convert.js +1 -1
  85. package/dist/convert.js.map +1 -1
  86. package/dist/echo-text.cjs +65 -0
  87. package/dist/echo-text.cjs.map +1 -0
  88. package/dist/echo-text.d.cts +22 -0
  89. package/dist/echo-text.d.cts.map +1 -0
  90. package/dist/echo-text.d.ts +22 -0
  91. package/dist/echo-text.d.ts.map +1 -0
  92. package/dist/echo-text.js +65 -0
  93. package/dist/echo-text.js.map +1 -0
  94. package/dist/elevenlabs-audio.cjs +3 -3
  95. package/dist/elevenlabs-audio.cjs.map +1 -1
  96. package/dist/elevenlabs-audio.js +4 -4
  97. package/dist/elevenlabs-audio.js.map +1 -1
  98. package/dist/elevenlabs-voice.cjs +1053 -0
  99. package/dist/elevenlabs-voice.cjs.map +1 -0
  100. package/dist/elevenlabs-voice.d.cts +72 -0
  101. package/dist/elevenlabs-voice.d.cts.map +1 -0
  102. package/dist/elevenlabs-voice.d.ts +72 -0
  103. package/dist/elevenlabs-voice.d.ts.map +1 -0
  104. package/dist/elevenlabs-voice.js +1048 -0
  105. package/dist/elevenlabs-voice.js.map +1 -0
  106. package/dist/embeddings.cjs +26 -5
  107. package/dist/embeddings.cjs.map +1 -1
  108. package/dist/embeddings.d.cts +1 -1
  109. package/dist/embeddings.d.cts.map +1 -1
  110. package/dist/embeddings.d.ts +1 -1
  111. package/dist/embeddings.d.ts.map +1 -1
  112. package/dist/embeddings.js +27 -6
  113. package/dist/embeddings.js.map +1 -1
  114. package/dist/fal-audio.cjs +3 -3
  115. package/dist/fal-audio.cjs.map +1 -1
  116. package/dist/fal-audio.js +4 -4
  117. package/dist/fal-audio.js.map +1 -1
  118. package/dist/fal.cjs +28 -4
  119. package/dist/fal.cjs.map +1 -1
  120. package/dist/fal.d.cts +16 -1
  121. package/dist/fal.d.cts.map +1 -1
  122. package/dist/fal.d.ts +16 -1
  123. package/dist/fal.d.ts.map +1 -1
  124. package/dist/fal.js +28 -5
  125. package/dist/fal.js.map +1 -1
  126. package/dist/files.cjs +1069 -0
  127. package/dist/files.cjs.map +1 -0
  128. package/dist/files.d.cts +68 -0
  129. package/dist/files.d.cts.map +1 -0
  130. package/dist/files.d.ts +68 -0
  131. package/dist/files.d.ts.map +1 -0
  132. package/dist/files.js +1056 -0
  133. package/dist/files.js.map +1 -0
  134. package/dist/fine-tuning.cjs +1033 -0
  135. package/dist/fine-tuning.cjs.map +1 -0
  136. package/dist/fine-tuning.d.cts +96 -0
  137. package/dist/fine-tuning.d.cts.map +1 -0
  138. package/dist/fine-tuning.d.ts +96 -0
  139. package/dist/fine-tuning.d.ts.map +1 -0
  140. package/dist/fine-tuning.js +1026 -0
  141. package/dist/fine-tuning.js.map +1 -0
  142. package/dist/fixture-loader-services.cjs +116 -0
  143. package/dist/fixture-loader-services.cjs.map +1 -0
  144. package/dist/fixture-loader-services.d.cts +48 -0
  145. package/dist/fixture-loader-services.d.cts.map +1 -0
  146. package/dist/fixture-loader-services.d.ts +48 -0
  147. package/dist/fixture-loader-services.d.ts.map +1 -0
  148. package/dist/fixture-loader-services.js +114 -0
  149. package/dist/fixture-loader-services.js.map +1 -0
  150. package/dist/fixture-loader.cjs +0 -0
  151. package/dist/fixture-loader.cjs.map +1 -1
  152. package/dist/fixture-loader.d.cts +131 -5
  153. package/dist/fixture-loader.d.cts.map +1 -1
  154. package/dist/fixture-loader.d.ts +131 -5
  155. package/dist/fixture-loader.d.ts.map +1 -1
  156. package/dist/fixture-loader.js +0 -0
  157. package/dist/fixture-loader.js.map +1 -1
  158. package/dist/gemini-embeddings.cjs +44 -4
  159. package/dist/gemini-embeddings.cjs.map +1 -1
  160. package/dist/gemini-embeddings.js +46 -6
  161. package/dist/gemini-embeddings.js.map +1 -1
  162. package/dist/gemini-interactions.cjs +51 -7
  163. package/dist/gemini-interactions.cjs.map +1 -1
  164. package/dist/gemini-interactions.d.cts.map +1 -1
  165. package/dist/gemini-interactions.d.ts.map +1 -1
  166. package/dist/gemini-interactions.js +53 -9
  167. package/dist/gemini-interactions.js.map +1 -1
  168. package/dist/gemini.cjs +19 -8
  169. package/dist/gemini.cjs.map +1 -1
  170. package/dist/gemini.d.cts.map +1 -1
  171. package/dist/gemini.d.ts.map +1 -1
  172. package/dist/gemini.js +21 -10
  173. package/dist/gemini.js.map +1 -1
  174. package/dist/grok-video.cjs +14 -14
  175. package/dist/grok-video.cjs.map +1 -1
  176. package/dist/grok-video.js +15 -15
  177. package/dist/grok-video.js.map +1 -1
  178. package/dist/helpers.cjs +497 -10
  179. package/dist/helpers.cjs.map +1 -1
  180. package/dist/helpers.d.cts +38 -2
  181. package/dist/helpers.d.cts.map +1 -1
  182. package/dist/helpers.d.ts +38 -2
  183. package/dist/helpers.d.ts.map +1 -1
  184. package/dist/helpers.js +487 -12
  185. package/dist/helpers.js.map +1 -1
  186. package/dist/images.cjs +57 -125
  187. package/dist/images.cjs.map +1 -1
  188. package/dist/images.d.cts.map +1 -1
  189. package/dist/images.d.ts.map +1 -1
  190. package/dist/images.js +58 -126
  191. package/dist/images.js.map +1 -1
  192. package/dist/index.cjs +71 -9
  193. package/dist/index.d.cts +17 -7
  194. package/dist/index.d.ts +17 -7
  195. package/dist/index.js +21 -11
  196. package/dist/jest.cjs +24 -12
  197. package/dist/jest.cjs.map +1 -1
  198. package/dist/jest.d.cts +6 -3
  199. package/dist/jest.d.cts.map +1 -1
  200. package/dist/jest.d.ts +6 -3
  201. package/dist/jest.d.ts.map +1 -1
  202. package/dist/jest.js +25 -13
  203. package/dist/jest.js.map +1 -1
  204. package/dist/journal.cjs +61 -4
  205. package/dist/journal.cjs.map +1 -1
  206. package/dist/journal.d.cts +60 -3
  207. package/dist/journal.d.cts.map +1 -1
  208. package/dist/journal.d.ts +60 -3
  209. package/dist/journal.d.ts.map +1 -1
  210. package/dist/journal.js +61 -5
  211. package/dist/journal.js.map +1 -1
  212. package/dist/live-fixture.cjs +1192 -0
  213. package/dist/live-fixture.cjs.map +1 -0
  214. package/dist/live-fixture.js +1187 -0
  215. package/dist/live-fixture.js.map +1 -0
  216. package/dist/live-recorder.cjs +256 -0
  217. package/dist/live-recorder.cjs.map +1 -0
  218. package/dist/live-recorder.js +254 -0
  219. package/dist/live-recorder.js.map +1 -0
  220. package/dist/live-replay.cjs +286 -0
  221. package/dist/live-replay.cjs.map +1 -0
  222. package/dist/live-replay.js +285 -0
  223. package/dist/live-replay.js.map +1 -0
  224. package/dist/live-sanitize.cjs +196 -0
  225. package/dist/live-sanitize.cjs.map +1 -0
  226. package/dist/live-sanitize.js +196 -0
  227. package/dist/live-sanitize.js.map +1 -0
  228. package/dist/live-types.d.cts +71 -0
  229. package/dist/live-types.d.cts.map +1 -0
  230. package/dist/live-types.d.ts +71 -0
  231. package/dist/live-types.d.ts.map +1 -0
  232. package/dist/llmock.cjs +132 -49
  233. package/dist/llmock.cjs.map +1 -1
  234. package/dist/llmock.d.cts +51 -5
  235. package/dist/llmock.d.cts.map +1 -1
  236. package/dist/llmock.d.ts +51 -5
  237. package/dist/llmock.d.ts.map +1 -1
  238. package/dist/llmock.js +133 -50
  239. package/dist/llmock.js.map +1 -1
  240. package/dist/mcp-fakes-mount.cjs +216 -0
  241. package/dist/mcp-fakes-mount.cjs.map +1 -0
  242. package/dist/mcp-fakes-mount.js +210 -0
  243. package/dist/mcp-fakes-mount.js.map +1 -0
  244. package/dist/mcp-fakes.cjs +1619 -0
  245. package/dist/mcp-fakes.cjs.map +1 -0
  246. package/dist/mcp-fakes.d.cts +101 -0
  247. package/dist/mcp-fakes.d.cts.map +1 -0
  248. package/dist/mcp-fakes.d.ts +101 -0
  249. package/dist/mcp-fakes.d.ts.map +1 -0
  250. package/dist/mcp-fakes.js +1614 -0
  251. package/dist/mcp-fakes.js.map +1 -0
  252. package/dist/mcp-handler.cjs +331 -17
  253. package/dist/mcp-handler.cjs.map +1 -1
  254. package/dist/mcp-handler.js +330 -18
  255. package/dist/mcp-handler.js.map +1 -1
  256. package/dist/mcp-mock.cjs +217 -49
  257. package/dist/mcp-mock.cjs.map +1 -1
  258. package/dist/mcp-mock.d.cts +66 -1
  259. package/dist/mcp-mock.d.cts.map +1 -1
  260. package/dist/mcp-mock.d.ts +66 -1
  261. package/dist/mcp-mock.d.ts.map +1 -1
  262. package/dist/mcp-mock.js +218 -50
  263. package/dist/mcp-mock.js.map +1 -1
  264. package/dist/mcp-stub.cjs +5 -1
  265. package/dist/mcp-stub.d.cts +3 -1
  266. package/dist/mcp-stub.d.ts +3 -1
  267. package/dist/mcp-stub.js +3 -1
  268. package/dist/mcp-types.d.cts +6 -0
  269. package/dist/mcp-types.d.ts +6 -0
  270. package/dist/message-text.cjs +192 -0
  271. package/dist/message-text.cjs.map +1 -0
  272. package/dist/message-text.d.cts +31 -0
  273. package/dist/message-text.d.cts.map +1 -0
  274. package/dist/message-text.d.ts +31 -0
  275. package/dist/message-text.d.ts.map +1 -0
  276. package/dist/message-text.js +184 -0
  277. package/dist/message-text.js.map +1 -0
  278. package/dist/messages.cjs +49 -7
  279. package/dist/messages.cjs.map +1 -1
  280. package/dist/messages.d.cts.map +1 -1
  281. package/dist/messages.d.ts.map +1 -1
  282. package/dist/messages.js +51 -9
  283. package/dist/messages.js.map +1 -1
  284. package/dist/metrics.cjs +278 -45
  285. package/dist/metrics.cjs.map +1 -1
  286. package/dist/metrics.d.cts +17 -7
  287. package/dist/metrics.d.cts.map +1 -1
  288. package/dist/metrics.d.ts +17 -7
  289. package/dist/metrics.d.ts.map +1 -1
  290. package/dist/metrics.js +270 -29
  291. package/dist/metrics.js.map +1 -1
  292. package/dist/moderation.cjs +10 -1
  293. package/dist/moderation.cjs.map +1 -1
  294. package/dist/moderation.d.cts.map +1 -1
  295. package/dist/moderation.d.ts.map +1 -1
  296. package/dist/moderation.js +10 -1
  297. package/dist/moderation.js.map +1 -1
  298. package/dist/ollama.cjs +10 -6
  299. package/dist/ollama.cjs.map +1 -1
  300. package/dist/ollama.d.cts.map +1 -1
  301. package/dist/ollama.d.ts.map +1 -1
  302. package/dist/ollama.js +11 -7
  303. package/dist/ollama.js.map +1 -1
  304. package/dist/openapi.cjs +3405 -0
  305. package/dist/openapi.cjs.map +1 -0
  306. package/dist/openapi.d.cts +30 -0
  307. package/dist/openapi.d.cts.map +1 -0
  308. package/dist/openapi.d.ts +30 -0
  309. package/dist/openapi.d.ts.map +1 -0
  310. package/dist/openapi.js +3404 -0
  311. package/dist/openapi.js.map +1 -0
  312. package/dist/openrouter-video.cjs +9 -9
  313. package/dist/openrouter-video.cjs.map +1 -1
  314. package/dist/openrouter-video.d.cts.map +1 -1
  315. package/dist/openrouter-video.d.ts.map +1 -1
  316. package/dist/openrouter-video.js +10 -10
  317. package/dist/openrouter-video.js.map +1 -1
  318. package/dist/recorder.cjs +54 -10
  319. package/dist/recorder.cjs.map +1 -1
  320. package/dist/recorder.d.cts.map +1 -1
  321. package/dist/recorder.d.ts.map +1 -1
  322. package/dist/recorder.js +52 -12
  323. package/dist/recorder.js.map +1 -1
  324. package/dist/responses.cjs +47 -7
  325. package/dist/responses.cjs.map +1 -1
  326. package/dist/responses.d.cts.map +1 -1
  327. package/dist/responses.d.ts.map +1 -1
  328. package/dist/responses.js +48 -9
  329. package/dist/responses.js.map +1 -1
  330. package/dist/route-registry.cjs +951 -0
  331. package/dist/route-registry.cjs.map +1 -0
  332. package/dist/route-registry.d.cts +33 -0
  333. package/dist/route-registry.d.cts.map +1 -0
  334. package/dist/route-registry.d.ts +33 -0
  335. package/dist/route-registry.d.ts.map +1 -0
  336. package/dist/route-registry.js +866 -0
  337. package/dist/route-registry.js.map +1 -0
  338. package/dist/router.cjs +21 -34
  339. package/dist/router.cjs.map +1 -1
  340. package/dist/router.d.cts +4 -1
  341. package/dist/router.d.cts.map +1 -1
  342. package/dist/router.d.ts +4 -1
  343. package/dist/router.d.ts.map +1 -1
  344. package/dist/router.js +21 -35
  345. package/dist/router.js.map +1 -1
  346. package/dist/server.cjs +1252 -777
  347. package/dist/server.cjs.map +1 -1
  348. package/dist/server.d.cts +5 -1
  349. package/dist/server.d.cts.map +1 -1
  350. package/dist/server.d.ts +5 -1
  351. package/dist/server.d.ts.map +1 -1
  352. package/dist/server.js +1185 -710
  353. package/dist/server.js.map +1 -1
  354. package/dist/speech.cjs +6 -4
  355. package/dist/speech.cjs.map +1 -1
  356. package/dist/speech.js +7 -5
  357. package/dist/speech.js.map +1 -1
  358. package/dist/suite.cjs +1 -1
  359. package/dist/suite.js +1 -1
  360. package/dist/transcription.cjs +6 -6
  361. package/dist/transcription.cjs.map +1 -1
  362. package/dist/transcription.d.cts.map +1 -1
  363. package/dist/transcription.d.ts.map +1 -1
  364. package/dist/transcription.js +7 -7
  365. package/dist/transcription.js.map +1 -1
  366. package/dist/types.cjs +18 -0
  367. package/dist/types.cjs.map +1 -0
  368. package/dist/types.d.cts +320 -17
  369. package/dist/types.d.cts.map +1 -1
  370. package/dist/types.d.ts +320 -17
  371. package/dist/types.d.ts.map +1 -1
  372. package/dist/types.js +17 -0
  373. package/dist/types.js.map +1 -0
  374. package/dist/validate-cli.cjs +983 -0
  375. package/dist/validate-cli.cjs.map +1 -0
  376. package/dist/validate-cli.js +982 -0
  377. package/dist/validate-cli.js.map +1 -0
  378. package/dist/vector-stores.cjs +1180 -0
  379. package/dist/vector-stores.cjs.map +1 -0
  380. package/dist/vector-stores.d.cts +106 -0
  381. package/dist/vector-stores.d.cts.map +1 -0
  382. package/dist/vector-stores.d.ts +106 -0
  383. package/dist/vector-stores.d.ts.map +1 -0
  384. package/dist/vector-stores.js +1164 -0
  385. package/dist/vector-stores.js.map +1 -0
  386. package/dist/vector-types.d.cts.map +1 -1
  387. package/dist/vector-types.d.ts.map +1 -1
  388. package/dist/veo-video.cjs +13 -13
  389. package/dist/veo-video.cjs.map +1 -1
  390. package/dist/veo-video.js +14 -14
  391. package/dist/veo-video.js.map +1 -1
  392. package/dist/video.cjs +23 -4
  393. package/dist/video.cjs.map +1 -1
  394. package/dist/video.d.cts +1 -1
  395. package/dist/video.d.cts.map +1 -1
  396. package/dist/video.d.ts +1 -1
  397. package/dist/video.d.ts.map +1 -1
  398. package/dist/video.js +24 -5
  399. package/dist/video.js.map +1 -1
  400. package/dist/vitest.cjs +23 -11
  401. package/dist/vitest.cjs.map +1 -1
  402. package/dist/vitest.d.cts +5 -2
  403. package/dist/vitest.d.cts.map +1 -1
  404. package/dist/vitest.d.ts +5 -2
  405. package/dist/vitest.d.ts.map +1 -1
  406. package/dist/vitest.js +25 -13
  407. package/dist/vitest.js.map +1 -1
  408. package/dist/watcher.cjs +2 -1
  409. package/dist/watcher.cjs.map +1 -1
  410. package/dist/watcher.js +2 -1
  411. package/dist/watcher.js.map +1 -1
  412. package/dist/ws-framing.cjs +150 -35
  413. package/dist/ws-framing.cjs.map +1 -1
  414. package/dist/ws-framing.d.cts +18 -3
  415. package/dist/ws-framing.d.cts.map +1 -1
  416. package/dist/ws-framing.d.ts +18 -3
  417. package/dist/ws-framing.d.ts.map +1 -1
  418. package/dist/ws-framing.js +151 -36
  419. package/dist/ws-framing.js.map +1 -1
  420. package/dist/ws-gemini-live.cjs +2 -2
  421. package/dist/ws-gemini-live.js +2 -2
  422. package/dist/ws-live.cjs +401 -0
  423. package/dist/ws-live.cjs.map +1 -0
  424. package/dist/ws-live.js +400 -0
  425. package/dist/ws-live.js.map +1 -0
  426. package/dist/ws-realtime.cjs +46 -2
  427. package/dist/ws-realtime.cjs.map +1 -1
  428. package/dist/ws-realtime.d.cts.map +1 -1
  429. package/dist/ws-realtime.d.ts.map +1 -1
  430. package/dist/ws-realtime.js +46 -2
  431. package/dist/ws-realtime.js.map +1 -1
  432. package/dist/ws-responses.cjs +16 -4
  433. package/dist/ws-responses.cjs.map +1 -1
  434. package/dist/ws-responses.js +16 -4
  435. package/dist/ws-responses.js.map +1 -1
  436. package/dist/ws-upstream.cjs +118 -0
  437. package/dist/ws-upstream.cjs.map +1 -0
  438. package/dist/ws-upstream.js +115 -0
  439. package/dist/ws-upstream.js.map +1 -0
  440. package/fixtures/openai-live-client.json +390 -0
  441. package/fixtures/openai-live-managed.json +709 -0
  442. package/package.json +4 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"elevenlabs-voice.js","names":[],"sources":["../src/elevenlabs-voice.ts"],"sourcesContent":["import type http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RawJSONResponse,\n VoiceDesignResponse,\n} from \"./types.js\";\nimport {\n isErrorResponse,\n isJSONResponse,\n isJsonObject,\n serializeErrorResponse,\n flattenHeaders,\n getContext,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n wouldProxyMiss,\n} from \"./helpers.js\";\nimport { releaseOneShotError } from \"./fixture-loader.js\";\nimport { selectFixtureForServing } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\nimport type { ProxyCapturedResponse, ProxyOptions } from \"./recorder.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\nimport { applyChaosAsync, type ChaosAsyncOutcome } from \"./chaos.js\";\n\n/**\n * ElevenLabs Voice Design record + replay: `POST /v1/text-to-voice/design`\n * (previews), `POST /v1/text-to-voice` (create a voice from a preview),\n * `GET /v1/voices/{voice_id}`, `DELETE /v1/voices/{voice_id}`.\n *\n * PROVENANCE OF EVERY WIRE FACT IN THIS FILE. Read this before changing a\n * field name, a status code, or a literal below.\n *\n * FIRSTHAND — observed by this repo against live `api.elevenlabs.io` on\n * 2026-09-15, with NO api key and with a deliberately invalid one. No\n * ElevenLabs api key is reachable from this machine (1Password holds an\n * `elevenlabs.io` web login, not a key), so only the pre-auth and auth layers\n * were ever exercised:\n * - `POST /v1/text-to-voice/design` with a >=20-char `voice_description` and\n * no credential -> 401\n * `{\"detail\":{\"type\":\"authentication_error\",\"code\":\"unauthorized\",\n * \"message\":\"Neither authorization header nor xi-api-key received, please\n * provide one.\",\"status\":\"needs_authorization\",\"request_id\":\"<hex>\"}}`.\n * Same envelope from `GET /v1/voices/{id}`; with a bogus `xi-api-key` the\n * message/status become `\"Invalid API key\"` / `\"invalid_api_key\"`.\n * - `voice_description` shorter than 20 chars -> 422 with a pydantic-style\n * `{\"detail\":[{\"type\":\"string_too_short\",\"loc\":[\"body\",\n * \"voice_description\"],...}]}`; `POST /v1/text-to-voice` reports missing\n * `voice_name` / `generated_voice_id` the same way. So the real service\n * validates the body BEFORE it authenticates. THIS HANDLER NOW ENFORCES\n * THAT 20-CODE-POINT MINIMUM on `POST /v1/text-to-voice/design`\n * (`VOICE_DESCRIPTION_MIN_LENGTH`) and answers with that same `422\n * {\"detail\":[...]}` envelope rather than aimock's house error shape — the\n * one response on this surface whose real shape was observed. The `msg`\n * STRING it fills in (\"String should have at least 20 characters\") is\n * AUTHORED: the observed body was recorded with `msg` elided, so only the\n * status, the `detail` array and the `loc`/`type` values are firsthand.\n * ORDER ON `POST /v1/text-to-voice/design`: missing-parameter 400 ->\n * fixture match (a registered short-description fixture still serves) ->\n * chaos -> strict refusal / record-mode proxy (so the REAL 422 is recorded\n * verbatim instead of pre-empted) -> this local 20-code-point 422 ->\n * no-match 404. `POST /v1/text-to-voice` follows the same order, with its\n * empty-string 422 in the same slot ahead of the synthesized voice.\n * The minimum is NOT enforced on `POST /v1/text-to-voice`, whose\n * `voice_description` bound has never been probed; that route rejects only\n * an EMPTY description, which is short under any `min_length >= 1`.\n * - `GET /v1/voices/aimock-nonexistent-voice` -> 400\n * `{\"detail\":{\"type\":\"invalid_request\",\"code\":\"bad_request\",\"message\":\"An\n * invalid ID has been received: ...\",\"status\":\"invalid_uid\",...}}`.\n * KNOWN DIVERGENCE, recorded rather than papered over: every real envelope\n * above is keyed `detail`, while this handler still emits aimock's house\n * `{ error: { message, type, code } }` shape — and aimock's own 400/404/503\n * codes — for EVERY failure except the `voice_description` minimum. That is\n * deliberate consistency with every other surface here, but it means those\n * ERROR envelopes are NOT wire-faithful to ElevenLabs. Making the whole\n * module speak `detail` is a FOLLOW-UP: it is a breaking change for every\n * existing consumer of this surface, and the shapes of the OTHER failures\n * (missing parameter, unknown voice, strict-mode refusal) have not been\n * observed, so they cannot be authored from the one case that has. A\n * RECORDED fixture is a second exception: it replays the upstream `detail`\n * body verbatim under the upstream status, so it is faithful by\n * construction.\n *\n * SECONDARY — the official client `@elevenlabs/elevenlabs-js`, pinned to the\n * exact published version `2.68.0` (`node_modules/@elevenlabs/elevenlabs-js/\n * package.json` -> `\"version\": \"2.68.0\"`). Every claim below was read out of\n * these files, at that version, and nowhere else:\n * - `api/resources/textToVoice/client/Client.d.ts` /`.js` — the routes, and\n * the `@throws` list for each (`UnprocessableEntityError` only);\n * - `api/resources/textToVoice/client/requests/VoiceDesignRequestModel.d.ts`\n * and `.../BodyCreateANewVoiceFromVoicePreviewV1TextToVoicePost.d.ts` —\n * the request bodies;\n * - `api/types/VoiceDesignPreviewResponse.d.ts`,\n * `api/types/VoicePreviewResponseModel.d.ts`, `api/types/Voice.d.ts`,\n * `api/types/HttpValidationError.d.ts`, `api/types/ValidationError.d.ts`,\n * `api/types/ValidationErrorLocItem.d.ts` — the response models;\n * - the matching `serialization/types/*.d.ts` `Raw` interfaces and\n * `serialization/types/*.js` schemas — the on-wire snake_case names and\n * each field's optional/nullable treatment;\n * - `api/errors/UnprocessableEntityError.js` (422) and\n * `api/errors/ConflictError.js` (409, never declared for these routes).\n * It pins:\n * - the four routes above, and that create-from-preview is `POST\n * /v1/text-to-voice` taking `voice_name`, `voice_description`,\n * `generated_voice_id`, optional `labels`;\n * - the design SUCCESS body `{ previews: [...], text }` where each preview is\n * `{ audio_base_64, generated_voice_id, media_type, duration_secs,\n * language? }` — `language` optional, the rest required;\n * - `model_id` values `eleven_multilingual_ttv_v2` / `eleven_ttv_v3`;\n * - the `Voice` object's wire fields. Every key `buildSyntheticVoice()`\n * emits (`voice_id`, `name`, `category`, `description`, `labels`,\n * `preview_url`, `available_for_tiers`, `settings`, `sharing`,\n * `high_quality_base_model_ids`, `samples`, `safety_control`,\n * `voice_verification` with its four inner keys, `permission_on_resource`,\n * `is_owner`, `is_legacy`, `is_mixed`) appears in `Voice.Raw` /\n * `VoiceVerificationResponse.Raw`, and `\"generated\"` is one of that SDK's\n * six `VoiceCategory` tokens;\n * - `DELETE /v1/voices/{id}` answering `{ status: \"ok\" }`.\n * ElevenLabs' own documentation site is a client-rendered SPA and was NOT\n * read; the SDK is the only document behind these shapes.\n *\n * UNVERIFIED / HAND-AUTHORED — name it, do not soften it:\n * - NO successful response from ElevenLabs has ever been observed by this\n * repo, for any of these four routes. There is no recorded fixture or tape\n * for this surface anywhere in the tree; the drift test in\n * `src/__tests__/drift/elevenlabs-voice.drift.ts` restates the same\n * hand-authored shape it checks, so it detects mock-vs-fixture divergence\n * only and can\n * never detect divergence from the real API.\n * - The VALUES `buildSyntheticVoice()` fills those fields with (`null`s, `[]`,\n * `is_owner: true`, `is_legacy`/`is_mixed` false, the zeroed\n * `voice_verification`) are aimock's choices for a just-created voice, not\n * anything observed. The SDK marks all of them optional and nullable, so\n * they are plausible, not confirmed.\n * - `voice_id === generated_voice_id` for a created voice. AUTHORED — see\n * `buildSyntheticVoice()`. The SDK relates the two nowhere; aimock picks\n * the alias so a caller can GET back what it just created. No code should\n * depend on it as a wire fact.\n * - Re-creating an already-created `generated_voice_id` overwrites and\n * answers 200. AUTHORED — see `rememberElevenLabsVoice()`. The real\n * behaviour is unknown and the SDK declares no `ConflictError` for the\n * route, so aimock warns through the module logger instead of inventing a\n * rejection.\n * - `Voice.Raw` carries further fields this handler never emits\n * (`fine_tuning`, `verified_languages`, `collection_ids`,\n * `created_at_unix`, `favorited_at_unix`, `is_bookmarked`,\n * `recording_quality`, `labelling_status`, `recording_quality_reason`). A\n * consumer reading them off a replayed voice gets `undefined`.\n * The standing rule still holds: THE MOCK NEVER AUTHORS A WIRE VALUE IT DID\n * NOT OBSERVE. This surface currently does, and this block is where that debt\n * is declared. Recording one real design + create round-trip against a funded\n * key would retire most of it.\n */\n\nconst VOICE_STORE_MAX = 10_000;\n\n/**\n * `POST /v1/text-to-voice/design` rejects a `voice_description` shorter than\n * this. FIRSTHAND: observed against live `api.elevenlabs.io` on 2026-09-15 (see\n * the PROVENANCE block above) — a sub-20-character description comes back 422\n * with a pydantic `string_too_short` entry, BEFORE the request is even\n * authenticated, so the bound is observable without a key.\n *\n * THE UNIT IS CODE POINTS, NOT UTF-16 CODE UNITS. The bound is pydantic's\n * `min_length`, which is `len(str)` in Python — a count of code points. A\n * JavaScript `String.length` counts UTF-16 code units instead, so it\n * DOUBLE-COUNTS every non-BMP character: a 19-emoji description is 19 code\n * points to the real service (422) and 38 `.length` to JavaScript (would have\n * passed here and then failed on the wire, which is the exact class of\n * divergence this mock exists to prevent). Measure with `[...s].length`, whose\n * string iterator yields code points. Grapheme clusters are deliberately NOT\n * the unit: Python does not count those either, so `Intl.Segmenter` would\n * re-introduce the same disagreement from the other side.\n */\nconst VOICE_DESCRIPTION_MIN_LENGTH = 20;\n\n/**\n * The real service answers body-validation failures with FastAPI/pydantic's\n * envelope: HTTP 422 and `{\"detail\":[{\"loc\":[...],\"msg\":...,\"type\":...}]}`.\n * The key set is pinned by `@elevenlabs/elevenlabs-js@2.68.0`\n * (`api/types/HttpValidationError.d.ts` -> `detail?: ValidationError[]`,\n * `api/types/ValidationError.d.ts` -> `{ loc, msg, type }`,\n * `serialization/types/ValidationError.d.ts` for the identical on-wire Raw),\n * and the status by `api/errors/UnprocessableEntityError.js`\n * (`statusCode: 422`), which is what that SDK throws for these routes.\n *\n * DELIBERATE DIVERGENCE FROM ITS SIBLINGS: every other validation failure in\n * this file answers aimock's house `400 {\"error\":{...}}`. This one does not,\n * because this is the only body-validation response on this surface whose real\n * shape this repo has actually observed. Aligning the rest is a follow-up, not\n * a licence to author the others' shapes from this one.\n */\nfunction writeValidationError(\n res: http.ServerResponse,\n loc: Array<string | number>,\n msg: string,\n type: string,\n): void {\n writeErrorResponse(res, 422, JSON.stringify({ detail: [{ loc, msg, type }] }));\n}\n\n/**\n * Voices created via POST /v1/text-to-voice, keyed by voice_id.\n *\n * MODULE-GLOBAL, deliberately: it is the same shape every other bounded store\n * here uses (`FalJobMap` in `./fal-audio.ts`, `FalQueueStateMap` in `./fal.ts`,\n * and the four video job maps), so one process shares one voice store across\n * every `LLMock` instance. `performFullReset` (`./server.ts`) clears it\n * alongside those siblings, which is what `POST /__aimock/reset` and\n * `LLMock.reset()` both route through. `stop()` does NOT clear it — no sibling\n * store is cleared on `stop()` either; reset is the isolation barrier, not\n * server teardown. A test file that creates voices must therefore reset (or\n * call `clearElevenLabsVoices()`) between tests, or a voice saved by one test\n * is still visible to the next.\n */\nconst elevenLabsVoices = new Map<string, Record<string, unknown>>();\n\nexport function clearElevenLabsVoices(): void {\n elevenLabsVoices.clear();\n}\n\n/**\n * Store a created voice under its own `voice_id` — the id the client sees in\n * the body we are about to write, so a follow-up `GET /v1/voices/{id}` by that\n * id hits.\n *\n * Returns `false` when the body carries no string `voice_id` and nothing was\n * stored, so the caller can say so instead of dropping the voice silently.\n *\n * AUTHORED: a second create for a `voice_id` already in the store OVERWRITES\n * the first, and still answers 200. Whether the real\n * `POST /v1/text-to-voice` accepts an already-consumed `generated_voice_id` is\n * UNKNOWN to this repo — no successful create has ever been observed, and\n * `@elevenlabs/elevenlabs-js@2.68.0` gives no signal either way: its\n * `api/resources/textToVoice/client/Client.d.ts` declares only\n * `@throws UnprocessableEntityError` for `create`, and never `ConflictError`\n * (`api/errors/ConflictError.js`), so authoring a 409 here would be inventing a\n * status nothing supports. Overwrite-and-200 is aimock's choice; it is made\n * AUDIBLE via `logger.warn` rather than silent, so a test that overwrites a\n * voice by accident can see it.\n *\n * EVICTION IS FIFO AND SILENT, by insertion order — the same rule every\n * sibling store applies (see `FalJobMap.set`, `src/fal-audio.ts:107-116`, and\n * the identical block in `fal.ts` / `openrouter-video.ts` / `grok-video.ts` /\n * `byteplus-video.ts`). Once the map exceeds `VOICE_STORE_MAX`, the\n * oldest-inserted entries are deleted with no log line and no error: a later\n * `GET /v1/voices/{id}` for an evicted voice is indistinguishable from one for\n * a voice that never existed (404, or 503 under strict). It is NOT LRU —\n * reading a voice does not refresh it, and re-saving an existing `voice_id`\n * keeps its ORIGINAL insertion slot, because `Map.set` on a present key does\n * not reorder. The cap exists to bound a long-lived mock process, not to model\n * anything ElevenLabs does; at 10k voices per process no test approaches it.\n */\nexport function rememberElevenLabsVoice(voice: Record<string, unknown>, logger?: Logger): boolean {\n const voiceId = typeof voice.voice_id === \"string\" ? voice.voice_id : undefined;\n if (!voiceId) return false;\n if (elevenLabsVoices.has(voiceId)) {\n logger?.warn(\n `ElevenLabs voice '${voiceId}' already existed and was overwritten; aimock does not know whether the real API rejects a reused generated_voice_id`,\n );\n }\n elevenLabsVoices.set(voiceId, voice);\n if (elevenLabsVoices.size > VOICE_STORE_MAX) {\n const excess = elevenLabsVoices.size - VOICE_STORE_MAX;\n const iter = elevenLabsVoices.keys();\n for (let i = 0; i < excess; i++) {\n const next = iter.next();\n if (!next.done) elevenLabsVoices.delete(next.value);\n }\n }\n return true;\n}\n\n/**\n * The status a recorded `{ json, status }` replay must answer with.\n *\n * `proxyAndRecord` persists the upstream status alongside the verbatim body for\n * this surface (`src/recorder.ts:901` — `{ json: parsedResponse, status:\n * upstreamStatus }`), and `RawJSONResponse.status` (`src/types.ts:476`) is the\n * field it lands in. Replaying every such fixture as 200 turns every recorded\n * ElevenLabs error — all of which carry a `detail` body, not aimock's house\n * error envelope, so `isErrorResponse()` never claims them — into a fabricated\n * success. `src/fal-audio.ts:1061` reads the same field the same way.\n *\n * Only `status` round-trips: that recorder branch stores no headers for a\n * verbatim-JSON recording, so there is no recorded header to honour here.\n */\nfunction replayStatus(response: RawJSONResponse): number {\n return response.status ?? 200;\n}\n\nexport function voiceDesignToJson(response: VoiceDesignResponse): RawJSONResponse {\n const previews = response.previews.map((preview, index) => {\n const entry: Record<string, unknown> = {\n generated_voice_id: preview.generated_voice_id || `aimock-preview-${index}`,\n audio_base_64: preview.audio_base_64 ?? \"\",\n media_type: preview.media_type ?? \"audio/mpeg\",\n duration_secs: preview.duration_secs ?? 0,\n };\n // `language` is OMITTED, never null, when the caller did not supply one:\n // the SDK models it `language?: string` (absent-or-string, never null) in\n // `api/types/VoicePreviewResponseModel.d.ts`, and its runtime schema\n // (`serialization/types/VoicePreviewResponseModel.js`,\n // `core.serialization.string().optional()`) parses an incoming `null` away\n // to `undefined`. A `null` here is therefore a value no SDK consumer can\n // ever observe from the real API.\n if (typeof preview.language === \"string\") entry.language = preview.language;\n return entry;\n });\n return {\n json: {\n previews,\n text: response.text ?? \"\",\n },\n };\n}\n\nfunction writeJson(res: http.ServerResponse, status: number, payload: unknown): void {\n res.writeHead(status, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(payload));\n}\n\n/**\n * The journal `source` for a chaos fault on a request no fixture answers — the\n * same rule `src/server.ts` applies, via the shared {@link wouldProxyMiss}:\n * the miss is aimock's own answer, \"internal\", unless record mode has an\n * ElevenLabs upstream to forward it to AND strict mode (server default or the\n * per-request `X-AIMock-Strict` header) is not refusing it first. Both halves\n * used to be hardcoded — design/create said \"proxy\" with no record config at\n * all, and the slot routes said \"internal\" while record mode was about to\n * proxy the very same miss.\n */\nfunction noFixtureSource(\n defaults: HandlerDefaults,\n headers: http.IncomingHttpHeaders,\n): \"proxy\" | \"internal\" {\n return wouldProxyMiss(resolveStrictMode(defaults.strict, headers), defaults.record, \"elevenlabs\")\n ? \"proxy\"\n : \"internal\";\n}\n\nfunction parseJsonObject(\n body: string,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n journal: Journal,\n path: string,\n method: string,\n): Record<string, unknown> | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: null,\n response: { status: 400, fixture: null },\n });\n return null;\n }\n\n if (!isJsonObject(parsed)) {\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: null,\n response: { status: 400, fixture: null },\n });\n return null;\n }\n\n return parsed;\n}\n\nfunction buildSyntheticReq(\n parsed: Record<string, unknown>,\n matchText: string,\n endpoint: \"elevenlabs-voice-design\" | \"elevenlabs-voice\",\n modelFallback: string,\n req: http.IncomingMessage,\n): ChatCompletionRequest {\n return {\n model: typeof parsed.model_id === \"string\" ? parsed.model_id : modelFallback,\n messages: [{ role: \"user\", content: matchText }],\n _endpointType: endpoint,\n _context: getContext(req),\n };\n}\n\nasync function missPath(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n syntheticReq: ChatCompletionRequest,\n fixtures: Fixture[],\n defaults: HandlerDefaults,\n journal: Journal,\n path: string,\n method: string,\n body: string,\n skippedBySequenceOrTurn: number,\n proxyOptions?: ProxyOptions,\n): Promise<\"handled\" | \"miss\"> {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n return \"handled\";\n }\n\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"elevenlabs\",\n req.url ?? path,\n fixtures,\n defaults,\n body,\n proxyOptions,\n );\n if (outcome === \"handled_by_hook\") return \"handled\";\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return \"handled\";\n }\n }\n\n return \"miss\";\n}\n\nfunction writeNoMatch(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n syntheticReq: ChatCompletionRequest,\n defaults: HandlerDefaults,\n journal: Journal,\n path: string,\n method: string,\n): void {\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n}\n\n/**\n * Builds the `beforeWriteResponse` observer for the voice routes. It NEVER\n * handles the response — it returns `false` so `proxyAndRecord` relays the\n * upstream bytes and the caller still journals the `\"relayed\"` outcome — it\n * only copies a successfully proxied voice object into the in-process store, so\n * a follow-up `GET /v1/voices/{id}` answers from memory exactly as it does\n * after an in-process create instead of hitting upstream a second time.\n *\n * It is a FACTORY OVER THE LOGGER, not a bare function, because the store has\n * exactly two things worth saying and neither can be said without one: the\n * AUTHORED overwrite of an already-stored `voice_id`, which\n * `rememberElevenLabsVoice` documents as made AUDIBLE rather than silent, and a\n * 2xx voice body carrying no string `voice_id`, which it reports by returning\n * `false`. Both are already reported on the in-process and fixture-replay paths\n * (see the `create` handler's `defaults.logger` calls); passing the observer a\n * bare function dropped both on EVERY proxy path, which is the one path where\n * the body came from somewhere aimock does not control.\n */\nfunction rememberProxiedVoice(logger: Logger): (captured: ProxyCapturedResponse) => false {\n return (captured: ProxyCapturedResponse): false => {\n if (captured.status < 200 || captured.status >= 300) return false;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(captured.body.toString(\"utf-8\"));\n } catch (err) {\n // ONLY a malformed upstream body is swallowed: a non-JSON 2xx carries no\n // voice to remember and the relay is unaffected. `JSON.parse` throws\n // `SyntaxError` and nothing else, so ANY other error came from a genuine\n // defect in this hook and must propagate — `proxyAndRecord` turns a\n // rejected hook into `beforeWriteResponse hook failed for <provider>`\n // (`src/recorder.ts`), which is a visible failure instead of a voice that\n // vanished under the label \"upstream sent HTML\".\n if (err instanceof SyntaxError) return false;\n throw err;\n }\n\n if (!isJsonObject(parsed)) return false;\n if (!rememberElevenLabsVoice(parsed, logger)) {\n logger.warn(\n `ElevenLabs relayed a ${captured.status} voice body from upstream that carries no ` +\n `string \\`voice_id\\` — the voice was NOT stored, so a follow-up ` +\n `GET /v1/voices/{id} will miss and re-hit upstream instead of replaying from ` +\n `memory. Upstream body: ${captured.body.toString(\"utf-8\").slice(0, 200)}`,\n );\n }\n return false;\n };\n}\n\nfunction buildSyntheticVoice(parsed: Record<string, unknown>): Record<string, unknown> {\n // AUTHORED: `voice_id === generated_voice_id`. Nothing in\n // `@elevenlabs/elevenlabs-js@2.68.0` says the created voice keeps the\n // preview's id — `api/resources/textToVoice/client/requests/\n // BodyCreateANewVoiceFromVoicePreviewV1TextToVoicePost.d.ts` documents\n // `generatedVoiceId` only as \"the generated_voice_id to create\", and the\n // returned `api/types/Voice.d.ts` relates `voiceId` to it nowhere. This is\n // aimock's choice so that a caller can GET the voice it just created; treat\n // it as a mock convention, not a wire fact, and do not build logic on it.\n const generatedVoiceId = String(parsed.generated_voice_id);\n const labels =\n parsed.labels && typeof parsed.labels === \"object\" && !Array.isArray(parsed.labels)\n ? (parsed.labels as Record<string, unknown>)\n : {};\n return {\n voice_id: generatedVoiceId,\n name: String(parsed.voice_name),\n category: \"generated\",\n description: String(parsed.voice_description),\n labels,\n preview_url: null,\n available_for_tiers: [],\n settings: null,\n sharing: null,\n high_quality_base_model_ids: [],\n samples: null,\n safety_control: null,\n voice_verification: {\n requires_verification: false,\n is_verified: false,\n verification_failures: [],\n verification_attempts_count: 0,\n },\n permission_on_resource: null,\n is_owner: true,\n is_legacy: false,\n is_mixed: false,\n };\n}\n\nexport async function handleElevenLabsVoiceDesign(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n body: string,\n fixtures: Fixture[],\n defaults: HandlerDefaults,\n journal: Journal,\n): Promise<void> {\n const path = req.url ?? \"/v1/text-to-voice/design\";\n const method = req.method ?? \"POST\";\n\n const parsed = parseJsonObject(body, req, res, journal, path, method);\n if (!parsed) return;\n\n // ONLY a non-string (or absent) `voice_description` is MISSING. An empty\n // string is PRESENT AND TOO SHORT: a truthiness test here folded `\"\"` into\n // the missing case and answered aimock's house 400, while the real service\n // answers the same firsthand-observed 422 `string_too_short` it answers for\n // every other sub-minimum description (PROVENANCE block above). `\"\"` is the\n // shortest such description there is, so it is the one case where the house\n // 400 and the observed 422 disagree most visibly.\n const description =\n typeof parsed.voice_description === \"string\" ? parsed.voice_description : undefined;\n\n const syntheticReq = buildSyntheticReq(\n parsed,\n description ?? \"\",\n \"elevenlabs-voice-design\",\n \"eleven_multilingual_ttv_v2\",\n req,\n );\n\n if (description === undefined) {\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Missing required parameter: 'voice_description'\",\n type: \"invalid_request_error\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 400, fixture: null },\n });\n return;\n }\n\n const testId = getTestId(req);\n const matchCounts = journal.getFixtureMatchCountsForTest(testId);\n const { fixture, skippedBySequenceOrTurn } = selectFixtureForServing(\n fixtures,\n syntheticReq,\n matchCounts,\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n service: \"elevenlabs-voice\",\n },\n fixture ? \"fixture\" : noFixtureSource(defaults, req.headers),\n defaults.registry,\n defaults.logger,\n )\n ) {\n releaseOneShotError(fixtures, fixture);\n return;\n }\n\n if (!fixture) {\n const outcome = await missPath(\n req,\n res,\n syntheticReq,\n fixtures,\n defaults,\n journal,\n path,\n method,\n body,\n skippedBySequenceOrTurn,\n );\n if (outcome === \"handled\") return;\n\n // THE LOCAL MINIMUM IS THE LAST RESORT, NOT THE FIRST GATE. It used to run\n // ahead of fixture matching and ahead of `missPath`, which meant a\n // registered short-description fixture could never be served and — worse —\n // record mode answered aimock's own AUTHORED `msg` instead of forwarding,\n // so the one response on this surface whose real shape was observed could\n // never be recorded. `missPath` has already refused (strict) or proxied and\n // recorded (record) by the time we get here, so this only fires when\n // nothing else can answer.\n // Code points, not `.length`: see `VOICE_DESCRIPTION_MIN_LENGTH`.\n if ([...description].length < VOICE_DESCRIPTION_MIN_LENGTH) {\n writeValidationError(\n res,\n [\"body\", \"voice_description\"],\n `String should have at least ${VOICE_DESCRIPTION_MIN_LENGTH} characters`,\n \"string_too_short\",\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 422, fixture: null },\n });\n return;\n }\n\n writeNoMatch(req, res, syntheticReq, defaults, journal, path, method);\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status, fixture },\n });\n return;\n }\n\n if (!isJSONResponse(response)) {\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response is not a JSON type for voice design\",\n type: \"server_error\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n return;\n }\n\n const status = replayStatus(response);\n writeJson(res, status, response.json);\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status, fixture },\n });\n}\n\nexport async function handleElevenLabsVoiceCreate(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n body: string,\n fixtures: Fixture[],\n defaults: HandlerDefaults,\n journal: Journal,\n): Promise<void> {\n const path = req.url ?? \"/v1/text-to-voice\";\n const method = req.method ?? \"POST\";\n\n const parsed = parseJsonObject(body, req, res, journal, path, method);\n if (!parsed) return;\n\n // ONLY a non-string (or absent) field is MISSING here, for the same reason\n // the design handler stopped folding `\"\"` into the missing case: an empty\n // string is PRESENT AND TOO SHORT, and the house 400 said the caller had\n // omitted a field it had actually sent. `voice_name` and `generated_voice_id`\n // follow the same rule as `voice_description`.\n const missing =\n typeof parsed.voice_name !== \"string\"\n ? \"voice_name\"\n : typeof parsed.voice_description !== \"string\"\n ? \"voice_description\"\n : typeof parsed.generated_voice_id !== \"string\"\n ? \"generated_voice_id\"\n : null;\n const tooShort =\n parsed.voice_name === \"\"\n ? \"voice_name\"\n : parsed.voice_description === \"\"\n ? \"voice_description\"\n : parsed.generated_voice_id === \"\"\n ? \"generated_voice_id\"\n : null;\n\n const syntheticReq = buildSyntheticReq(\n parsed,\n typeof parsed.generated_voice_id === \"string\" ? parsed.generated_voice_id : \"\",\n \"elevenlabs-voice\",\n \"eleven_multilingual_ttv_v2\",\n req,\n );\n\n if (missing) {\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Missing required parameter: '${missing}'`,\n type: \"invalid_request_error\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 400, fixture: null },\n });\n return;\n }\n\n const testId = getTestId(req);\n const matchCounts = journal.getFixtureMatchCountsForTest(testId);\n const { fixture, skippedBySequenceOrTurn } = selectFixtureForServing(\n fixtures,\n syntheticReq,\n matchCounts,\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n service: \"elevenlabs-voice\",\n },\n fixture ? \"fixture\" : noFixtureSource(defaults, req.headers),\n defaults.registry,\n defaults.logger,\n )\n ) {\n releaseOneShotError(fixtures, fixture);\n return;\n }\n\n if (!fixture) {\n const outcome = await missPath(\n req,\n res,\n syntheticReq,\n fixtures,\n defaults,\n journal,\n path,\n method,\n body,\n skippedBySequenceOrTurn,\n { beforeWriteResponse: rememberProxiedVoice(defaults.logger) },\n );\n if (outcome === \"handled\") return;\n\n // THE LOCAL MINIMUM IS THE LAST RESORT, NOT THE FIRST GATE — same position\n // as the design handler's, for the same reasons: a registered fixture,\n // chaos, strict and the record proxy all get their turn first, so record\n // mode forwards and records the REAL 422 instead of authoring one.\n // An EMPTY string is the one length this route can answer without\n // authoring an unobserved bound: it is under ANY `min_length >= 1`, so\n // `string_too_short` holds whatever the real minimum on\n // `POST /v1/text-to-voice` turns out to be. THE 20-CODE-POINT BOUND IS\n // DELIBERATELY NOT ENFORCED HERE — that minimum was observed on\n // `/v1/text-to-voice/design` only (PROVENANCE block), and this route's\n // bounds have never been probed. The `msg` string is AUTHORED, like its\n // design sibling's.\n if (tooShort) {\n writeValidationError(\n res,\n [\"body\", tooShort],\n \"String should have at least 1 character\",\n \"string_too_short\",\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 422, fixture: null },\n });\n return;\n }\n\n const voice = buildSyntheticVoice(parsed);\n rememberElevenLabsVoice(voice, defaults.logger);\n writeJson(res, 200, voice);\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status, fixture },\n });\n return;\n }\n\n if (!isJSONResponse(response)) {\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response is not a JSON type for voice create\",\n type: \"server_error\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n return;\n }\n\n const status = replayStatus(response);\n\n // Store the voice under the `voice_id` the CLIENT is about to see (this same\n // body), so its follow-up `GET /v1/voices/{id}` by the id it received hits.\n // Only a 2xx replay creates a voice: a recorded 4xx/5xx `detail` body carries\n // no voice, and remembering it would resurrect the fabricated-success bug\n // from the other side.\n //\n // A 2xx body with no string `voice_id` is an AUTHORING error, not an\n // unservable fixture: the body is still what the recording says the client\n // gets, so serve it and name the defect, the way `src/byteplus-video.ts:469`\n // and `:479` name an envelope that is servable but will strand the client\n // later. (The 500 `server_error` treatment a few lines above — and in\n // `src/fal-audio.ts:1071` — is reserved for a response that CANNOT be served\n // at all, which this one can.)\n if (status >= 200 && status < 300) {\n const remembered =\n isJsonObject(response.json) && rememberElevenLabsVoice(response.json, defaults.logger);\n if (!remembered) {\n defaults.logger.warn(\n `ElevenLabs voice create fixture matched generated_voice_id ` +\n `\"${String(parsed.generated_voice_id)}\" but its json carries no string \\`voice_id\\` — ` +\n `the voice was NOT stored, so a follow-up GET /v1/voices/{id} will 404 with a ` +\n `\"voice not found\" message that points at the id instead of at the fixture. Add a ` +\n `string voice_id to the fixture's json`,\n );\n }\n }\n\n writeJson(res, status, response.json);\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status, fixture },\n });\n}\n\n/**\n * The synthetic request the slot routes (GET/DELETE /v1/voices/{id}) match and\n * journal on. The voice id stands in for the user message so the entry carries\n * the one thing that identifies the request.\n *\n * The endpoint type is the CALLER's, not a constant: ONE ROUTE, ONE ENDPOINT\n * TYPE. GET declares \"elevenlabs-voice-get\" and DELETE declares\n * \"elevenlabs-voice-delete\", so neither route's fixtures can ever be confused\n * with the create route's (\"elevenlabs-voice\") — all three would otherwise\n * carry the same voice id as their match text and answer for one another.\n */\nfunction buildVoiceSlotReq(\n req: http.IncomingMessage,\n voiceId: string,\n endpointType: \"elevenlabs-voice-get\" | \"elevenlabs-voice-delete\",\n): ChatCompletionRequest {\n return {\n model: \"eleven_multilingual_ttv_v2\",\n messages: [{ role: \"user\", content: voiceId }],\n _endpointType: endpointType,\n _context: getContext(req),\n };\n}\n\n/**\n * Gate a slot route on chaos exactly as {@link handleElevenLabsVoiceDesign} and\n * {@link handleElevenLabsVoiceCreate} gate theirs: the same `applyChaosAsync`\n * call, awaited BEFORE anything is served, so a configured latency/drop/429\n * applies to a store hit as well as to a miss. It is called AFTER the fixture\n * match and is handed the fixture that matched, because chaos can be authored\n * ON a fixture (`Fixture.chaos`, folded in by `chaos.ts`): passing null here\n * dropped a fixture-level `chaos` block on the floor for these two routes\n * while design/create honoured the identical block. The journal source follows\n * the same fixture/no-fixture split design/create use, via the same\n * {@link noFixtureSource}: \"internal\" when this process answers the miss,\n * \"proxy\" when record mode has an ElevenLabs upstream and would forward it.\n *\n * `applyChaosAsync` reads the per-testId chaos scope off `req.url`, which is\n * why the raw url — not the fallback `path` — is what it is handed, matching\n * design/create. The context carries `service: \"elevenlabs-voice\"` like every\n * other journal write in this module, so a faulted request stays selectable by\n * `GET /__aimock/journal?service=elevenlabs-voice`.\n */\nasync function gateVoiceSlotChaos(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n syntheticReq: ChatCompletionRequest,\n fixture: Fixture | null,\n defaults: HandlerDefaults,\n journal: Journal,\n path: string,\n method: string,\n): Promise<ChaosAsyncOutcome> {\n return await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n service: \"elevenlabs-voice\",\n },\n fixture ? \"fixture\" : noFixtureSource(defaults, req.headers),\n defaults.registry,\n defaults.logger,\n );\n}\n\n/**\n * Refuse a slot-route miss under strict mode, mirroring {@link missPath}: the\n * refusal is LOGGED through the shared `strictNoMatchLogLine` and the client\n * message names strict mode, so a strict 503 is never mistaken for the route's\n * own 404.\n *\n * `skippedBySequenceOrTurn` is the count `selectFixtureForServing` handed the\n * caller. Both slot routes are fixture routes now, so a candidate fixture CAN\n * be skipped by sequence/turn state here exactly as on create — hardcoding 0\n * told every such refusal \"no fixture matched\" when the truth was \"a fixture\n * matched the content and was held back by its sequenceIndex\". When the count\n * is non-zero the client message switches to the shared\n * {@link strictNoMatchMessage} wording that names it; otherwise the\n * voice-specific message is kept, since naming the id is the more useful thing\n * to say when nothing matched at all.\n */\nfunction writeVoiceSlotStrictRefusal(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n syntheticReq: ChatCompletionRequest,\n defaults: HandlerDefaults,\n journal: Journal,\n path: string,\n method: string,\n voiceId: string,\n skippedBySequenceOrTurn: number,\n): void {\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n error: {\n message:\n skippedBySequenceOrTurn > 0\n ? strictNoMatchMessage(skippedBySequenceOrTurn)\n : `Strict mode: voice '${voiceId}' not found`,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n}\n\n/**\n * Proxy a slot-route miss upstream in record mode. Returns \"handled\" when the\n * upstream answer was relayed (or a hook took over), \"miss\" when no upstream is\n * configured for the provider — `proxyAndRecord` already warns on that path, so\n * the caller falls through to its own miss answer.\n */\nasync function proxyVoiceSlotMiss(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n syntheticReq: ChatCompletionRequest,\n defaults: HandlerDefaults,\n journal: Journal,\n path: string,\n method: string,\n fixtures: Fixture[] = [],\n proxyOptions?: ProxyOptions,\n): Promise<\"handled\" | \"miss\"> {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"elevenlabs\",\n req.url ?? path,\n fixtures,\n defaults,\n \"\",\n proxyOptions,\n );\n if (outcome === \"handled_by_hook\") return \"handled\";\n if (outcome === \"not_configured\") return \"miss\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return \"handled\";\n}\n\n/**\n * Replay a fixture that matched on a slot route (`GET`/`DELETE /v1/voices/{id}`).\n *\n * Both slot routes replay identically, so the body lives here once: resolve,\n * relay an error envelope under its own status, refuse a non-JSON response,\n * and otherwise write the recorded JSON under {@link replayStatus} — the\n * UPSTREAM status the recorder persisted, not a hardcoded 200. GET used to\n * hardcode 200, which turned every recorded ElevenLabs failure (a `detail`\n * body that `isErrorResponse()` never claims) into a fabricated success.\n *\n * Returns the status actually written, or `null` when the fixture could not be\n * served as a success (an error envelope was relayed, or the response was not\n * JSON at all). DELETE uses that to decide whether the local store entry is\n * gone.\n */\nasync function replayVoiceSlotFixture(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n syntheticReq: ChatCompletionRequest,\n fixture: Fixture,\n journal: Journal,\n path: string,\n method: string,\n routeLabel: string,\n): Promise<number | null> {\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status, fixture },\n });\n return null;\n }\n\n if (!isJSONResponse(response)) {\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: `Fixture response is not a JSON type for ${routeLabel}`,\n type: \"server_error\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n return null;\n }\n\n const status = replayStatus(response);\n writeJson(res, status, response.json);\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status, fixture },\n });\n return status;\n}\n\n/**\n * FIXTURE BEFORE STORE, on both slot routes.\n *\n * A registered or recorded fixture is explicit authoring intent and wins over\n * the in-process voice store, which is a replay CONVENIENCE populated as a\n * side effect of create. That is the order every other replay route in this\n * repo uses — fixture match first, internal state only on a miss — and without\n * it a fixture authored specifically for `GET /v1/voices/{id}` (a recorded 401,\n * say) was silently unreachable for any id that create had already stored.\n *\n * The shadowing is AUDIBLE rather than silent: when a fixture wins over a\n * present store entry this logs at debug, so a test whose store entry stopped\n * being served can see why.\n */\nfunction logVoiceSlotShadow(\n defaults: HandlerDefaults,\n method: string,\n path: string,\n voiceId: string,\n): void {\n defaults.logger.debug(\n `ElevenLabs ${method} ${path}: a matching fixture shadows the in-process voice ` +\n `store entry for '${voiceId}' — the fixture is being served`,\n );\n}\n\nexport async function handleElevenLabsVoiceGet(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n voiceId: string,\n fixtures: Fixture[],\n defaults: HandlerDefaults,\n journal: Journal,\n): Promise<void> {\n const path = req.url ?? `/v1/voices/${voiceId}`;\n const method = req.method ?? \"GET\";\n\n // DISTINCT endpoint type from the create route on purpose. GET used to\n // declare \"elevenlabs-voice\", the same type `POST /v1/text-to-voice`\n // declares, with the voice_id as the match text on both sides — so a fixture\n // recorded on GET became a first-class candidate for create (and hijacked\n // it), while create's own fixtures could be handed to GET. One route, one\n // endpoint type; `src/router.ts` and `src/recorder.ts` both know this name.\n const syntheticReq = buildVoiceSlotReq(req, voiceId, \"elevenlabs-voice-get\");\n\n // GET is a first-class replay route, exactly like design and create: a\n // registered or previously recorded fixture serves it. Without this the\n // route could only ever answer from the in-process store, so nothing\n // recorded to disk was reachable on a later run. See\n // {@link logVoiceSlotShadow} for why the fixture is consulted BEFORE the\n // store. The match runs BEFORE the chaos gate — and the count is incremented\n // before it, as design/create do — so a fixture-level `chaos` block reaches\n // the gate; see {@link gateVoiceSlotChaos}.\n const testId = getTestId(req);\n const matchCounts = journal.getFixtureMatchCountsForTest(testId);\n const { fixture, skippedBySequenceOrTurn } = selectFixtureForServing(\n fixtures,\n syntheticReq,\n matchCounts,\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (await gateVoiceSlotChaos(req, res, syntheticReq, fixture, defaults, journal, path, method)) {\n releaseOneShotError(fixtures, fixture);\n return;\n }\n\n const stored = elevenLabsVoices.get(voiceId);\n\n if (fixture) {\n if (stored) logVoiceSlotShadow(defaults, method, path, voiceId);\n await replayVoiceSlotFixture(\n req,\n res,\n syntheticReq,\n fixture,\n journal,\n path,\n method,\n \"voice get\",\n );\n return;\n }\n\n const serveStored = (voice: Record<string, unknown>): void => {\n writeJson(res, 200, voice);\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n };\n\n // IN RECORD MODE THE LOCAL STORE IS NOT AUTHORITATIVE, the same guard DELETE\n // carries. Answering a locally-known voice from memory kept the GET out of\n // the tape entirely — a proxied create left the voice in the store, so no\n // `elevenlabs-voice-get` fixture was ever recorded and the replay run, which\n // has only the tape, 404'd on the GET that \"worked\" while recording.\n if (stored && !defaults.record) {\n serveStored(stored);\n return;\n }\n\n // STRICT BEFORE RECORD, the precedence missPath() uses. A strict server\n // refuses the miss outright; it must not silently proxy it upstream.\n if (resolveStrictMode(defaults.strict, req.headers)) {\n writeVoiceSlotStrictRefusal(\n req,\n res,\n syntheticReq,\n defaults,\n journal,\n path,\n method,\n voiceId,\n skippedBySequenceOrTurn,\n );\n return;\n }\n\n if (defaults.record) {\n // The REAL fixtures array, not a throwaway `[]`: `persistFixture`\n // (`src/recorder.ts`) pushes the freshly recorded fixture into whatever\n // array it is handed, so passing a discarded literal made the live server\n // forget what it had just recorded and re-hit upstream on every\n // subsequent GET.\n const outcome = await proxyVoiceSlotMiss(\n req,\n res,\n syntheticReq,\n defaults,\n journal,\n path,\n method,\n fixtures,\n { beforeWriteResponse: rememberProxiedVoice(defaults.logger) },\n );\n if (outcome === \"handled\") return;\n // Record mode is on but NO ElevenLabs upstream is configured (`--record`\n // aimed at another provider): the proxy cannot forward, and the create\n // that handed this id out was synthesized locally on that same path. The\n // store is the only thing that knows the voice, so it answers.\n if (stored) {\n serveStored(stored);\n return;\n }\n }\n\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: `Voice '${voiceId}' not found`,\n type: \"invalid_request_error\",\n code: \"voice_not_found\",\n },\n }),\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 404, fixture: null, ...strictOverrideField(defaults.strict, req.headers) },\n });\n}\n\n/**\n * DELETE /v1/voices/{voice_id}. A first-class record/replay route, exactly\n * like GET: chaos, then a fixture match, then the in-process store, then\n * strict, then record, then the lenient answer.\n *\n * The success body is `{ status: \"ok\" }` — SECONDARY, from\n * `@elevenlabs/elevenlabs-js@2.68.0`: `voices.delete()` parses the response as\n * `DeleteVoiceResponseModel`, whose only wire field is `status: string`, and\n * whose doc comment reads \"The status of the voice deletion request. If the\n * request was successful, the status will be 'ok'.\" In record mode nothing is\n * authored at all — the upstream's own response is relayed AND recorded.\n *\n * IN RECORD MODE THE LOCAL STORE IS NOT AUTHORITATIVE. A locally-known voice\n * used to be deleted from the map and answered 200 without the request ever\n * leaving the process, so the real voice leaked upstream and the tape got a\n * hole exactly where the delete belonged. Record mode forwards regardless of\n * what the store knows; the store is a replay convenience, not a claim about\n * what exists upstream. It still evicts ONLY on a 2xx from upstream, the same\n * rule the fixture-replay branch applies: a refused delete must not lose the\n * local voice.\n *\n * A miss on a LENIENT server stays an idempotent 200: deleting an id that was\n * never saved is not an error on this surface.\n */\nexport async function handleElevenLabsVoiceDelete(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n voiceId: string,\n fixtures: Fixture[],\n defaults: HandlerDefaults,\n journal: Journal,\n): Promise<void> {\n const path = req.url ?? `/v1/voices/${voiceId}`;\n const method = req.method ?? \"DELETE\";\n\n // Its OWN endpoint type, for the same reason GET has one: DELETE used to\n // declare \"elevenlabs-voice\" with the voice id as its match text — byte for\n // byte what `POST /v1/text-to-voice` declares — so a recorded DELETE\n // (`{\"status\":\"ok\"}`) was a first-class candidate for create and hijacked it\n // on the next run.\n const syntheticReq = buildVoiceSlotReq(req, voiceId, \"elevenlabs-voice-delete\");\n\n // Match (and count) BEFORE the chaos gate, exactly as GET and design/create\n // do, so a fixture-level `chaos` block reaches the gate.\n const testId = getTestId(req);\n const matchCounts = journal.getFixtureMatchCountsForTest(testId);\n const { fixture, skippedBySequenceOrTurn } = selectFixtureForServing(\n fixtures,\n syntheticReq,\n matchCounts,\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (await gateVoiceSlotChaos(req, res, syntheticReq, fixture, defaults, journal, path, method)) {\n releaseOneShotError(fixtures, fixture);\n return;\n }\n\n const stored = elevenLabsVoices.has(voiceId);\n\n if (fixture) {\n if (stored) logVoiceSlotShadow(defaults, method, path, voiceId);\n const status = await replayVoiceSlotFixture(\n req,\n res,\n syntheticReq,\n fixture,\n journal,\n path,\n method,\n \"voice delete\",\n );\n // Only a 2xx replay says the voice is gone. A replayed 4xx/5xx is the\n // recording saying the delete did NOT happen, so the local entry stays.\n if (status !== null && status >= 200 && status < 300) elevenLabsVoices.delete(voiceId);\n return;\n }\n\n if (stored && !defaults.record) {\n elevenLabsVoices.delete(voiceId);\n writeJson(res, 200, { status: \"ok\" });\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: {\n status: 200,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n return;\n }\n\n // STRICT BEFORE RECORD, the precedence missPath() and GET both use.\n if (resolveStrictMode(defaults.strict, req.headers)) {\n writeVoiceSlotStrictRefusal(\n req,\n res,\n syntheticReq,\n defaults,\n journal,\n path,\n method,\n voiceId,\n skippedBySequenceOrTurn,\n );\n return;\n }\n\n if (defaults.record) {\n // Evict ONLY on a 2xx from upstream, the same rule the fixture-replay\n // branch above applies: an upstream 4xx/5xx is upstream saying the delete\n // did NOT happen, and dropping the entry anyway lost a local voice to a\n // refusal. `beforeWriteResponse` observes the captured upstream status and\n // returns `false`, so `proxyAndRecord` still relays the bytes and the\n // caller still journals the `\"relayed\"` outcome.\n // The REAL fixtures array, for the same reason GET passes it: the\n // throwaway `[]` this used to pass meant every recorded DELETE was\n // discarded on the spot, never replayed, and every repeat re-hit upstream.\n const outcome = await proxyVoiceSlotMiss(\n req,\n res,\n syntheticReq,\n defaults,\n journal,\n path,\n method,\n fixtures,\n {\n beforeWriteResponse: (captured): false => {\n if (captured.status >= 200 && captured.status < 300) {\n elevenLabsVoices.delete(voiceId);\n }\n return false;\n },\n },\n );\n if (outcome === \"handled\") return;\n }\n\n elevenLabsVoices.delete(voiceId);\n writeJson(res, 200, { status: \"ok\" });\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n service: \"elevenlabs-voice\",\n body: syntheticReq,\n response: { status: 200, fixture: null, ...strictOverrideField(defaults.strict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GF,KAAI,SAAS,QA4BX;MAlBgB,MAAM,mBACpB,KACA,KACA,cACA,UACA,SACA,MACA,QACA,UACA,EACE,sBAAsB,aAAoB;AACxC,OAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAC9C,kBAAiB,OAAO,QAAQ;AAElC,UAAO;KAEV,CACF,KACe,UAAW;;AAG7B,kBAAiB,OAAO,QAAQ;AAChC,WAAU,KAAK,KAAK,EAAE,QAAQ,MAAM,CAAC;AACrC,SAAQ,IAAI;EACV;EACA;EACA,SAAS,eAAe,IAAI,QAAQ;EACpC,SAAS;EACT,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM,GAAG,oBAAoB,SAAS,QAAQ,IAAI,QAAQ;GAAE;EAC/F,CAAC"}
@@ -1,11 +1,12 @@
1
1
  const require_helpers = require('./helpers.cjs');
2
- const require_router = require('./router.cjs');
3
2
  const require_sse_writer = require('./sse-writer.cjs');
4
3
  const require_chaos = require('./chaos.cjs');
4
+ const require_fixture_loader = require('./fixture-loader.cjs');
5
+ const require_router = require('./router.cjs');
5
6
  const require_recorder = require('./recorder.cjs');
6
7
 
7
8
  //#region src/embeddings.ts
8
- async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setCorsHeaders, providerKey = "openai") {
9
+ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setCorsHeaders, providerKey = "openai", requireModel = false) {
9
10
  const { logger } = defaults;
10
11
  setCorsHeaders(res);
11
12
  let embeddingReq;
@@ -64,6 +65,23 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
64
65
  } }));
65
66
  return;
66
67
  }
68
+ if (requireModel && embeddingReq.model === void 0) {
69
+ journal.add({
70
+ method: req.method ?? "POST",
71
+ path: req.url ?? "/v1/embeddings",
72
+ headers: require_helpers.flattenHeaders(req.headers),
73
+ body: null,
74
+ response: {
75
+ status: 400,
76
+ fixture: null
77
+ }
78
+ });
79
+ require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
80
+ message: "Missing required parameter: 'model'",
81
+ type: "invalid_request_error"
82
+ } }));
83
+ return;
84
+ }
67
85
  const inputs = require_helpers.normalizeEmbeddingInput(embeddingReq.input);
68
86
  if (inputs === null) {
69
87
  journal.add({
@@ -93,17 +111,20 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
93
111
  _context: require_helpers.getContext(req)
94
112
  };
95
113
  const testId = require_helpers.getTestId(req);
96
- const { fixture, skippedBySequenceOrTurn } = require_router.matchFixtureDiagnostic(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
114
+ const { fixture, skippedBySequenceOrTurn } = require_router.selectFixtureForServing(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
97
115
  if (fixture) {
98
116
  journal.incrementFixtureMatchCount(fixture, fixtures, testId);
99
117
  logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);
100
118
  } else logger.debug(`No fixture matched for request`);
101
- if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, req.url, journal, {
119
+ if (await require_chaos.applyChaosAsync(res, fixture, defaults.chaos, req.headers, req.url, journal, {
102
120
  method: req.method ?? "POST",
103
121
  path: req.url ?? "/v1/embeddings",
104
122
  headers: require_helpers.flattenHeaders(req.headers),
105
123
  body: syntheticReq
106
- }, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) return;
124
+ }, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) {
125
+ require_fixture_loader.releaseOneShotError(fixtures, fixture);
126
+ return;
127
+ }
107
128
  if (fixture) {
108
129
  const response = await require_helpers.resolveResponse(fixture, syntheticReq);
109
130
  if (require_helpers.isErrorResponse(response)) {
@@ -1 +1 @@
1
- {"version":3,"file":"embeddings.cjs","names":["flattenHeaders","isJsonObject","normalizeEmbeddingInput","getContext","getTestId","matchFixtureDiagnostic","applyChaos","resolveResponse","isErrorResponse","serializeErrorResponse","isEmbeddingResponse","buildEmbeddingResponse","resolveStrictMode","strictNoMatchMessage","strictNoMatchLogLine","strictOverrideField","proxyAndRecord","validateEmbeddingDimensions","MAX_EMBEDDING_DIMENSIONS","generateDeterministicEmbedding"],"sources":["../src/embeddings.ts"],"sourcesContent":["/**\n * OpenAI Embeddings API support for aimock.\n *\n * Handles POST /v1/embeddings requests. Matches fixtures using the `inputText`\n * field, and falls back to generating a deterministic embedding from the input\n * text hash when no fixture matches.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RecordProviderKey,\n} from \"./types.js\";\nimport {\n isEmbeddingResponse,\n isErrorResponse,\n serializeErrorResponse,\n generateDeterministicEmbedding,\n buildEmbeddingResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n validateEmbeddingDimensions,\n isJsonObject,\n normalizeEmbeddingInput,\n MAX_EMBEDDING_DIMENSIONS,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Embeddings API request types ──────────────────────────────────────────\n\ninterface EmbeddingRequest {\n // Validated at runtime — these arrive as arbitrary JSON, so the declared\n // type must not claim a shape the parser cannot guarantee.\n input: unknown;\n model: string;\n encoding_format?: \"float\" | \"base64\";\n dimensions?: unknown;\n [key: string]: unknown;\n}\n\n// ─── Request handler ───────────────────────────────────────────────────────\n\nexport async function handleEmbeddings(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n providerKey: RecordProviderKey = \"openai\",\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let embeddingReq: EmbeddingRequest;\n try {\n embeddingReq = JSON.parse(raw) as EmbeddingRequest;\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/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Malformed JSON body: ${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 `embeddingReq.input` throws a TypeError that\n // surfaces as a 500 instead of a 400.\n if (!isJsonObject(embeddingReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\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 // Validate required input parameter\n if (embeddingReq.input === undefined || embeddingReq.input === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Missing required parameter: 'input'\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Normalize input to array of strings — reject non-string inputs with 400\n // instead of crashing downstream in createHash().update() (500).\n const inputs = normalizeEmbeddingInput(embeddingReq.input);\n if (inputs === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message:\n \"Invalid parameter: 'input' must be a string, an array of strings, or an array of tokens\",\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n\n // Concatenate all inputs for matching purposes\n const combinedInput = inputs.join(\" \");\n\n // Build a synthetic ChatCompletionRequest for the fixture router.\n // We attach `embeddingInput` so the router's inputText matching can use it.\n const syntheticReq: ChatCompletionRequest = {\n model: embeddingReq.model,\n messages: [],\n embeddingInput: combinedInput,\n _endpointType: \"embedding\",\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n logger.debug(`No fixture matched for request`);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (fixture) {\n const response = await resolveResponse(fixture, syntheticReq);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Embedding response — use the fixture's embedding for each input\n if (isEmbeddingResponse(response)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n const embeddings = inputs.map(() => [...response.embedding]);\n const body = buildEmbeddingResponse(embeddings, embeddingReq.model);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n return;\n }\n\n // Fixture matched but response type is not compatible with embeddings\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message:\n \"Fixture response did not match any known embedding type (must have embedding or error)\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n // No fixture match — check strict mode first, then try proxy\n if (resolveStrictMode(defaults.strict, req.headers)) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(\n req.method ?? \"POST\",\n req.url ?? \"/v1/embeddings\",\n skippedBySequenceOrTurn,\n ),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\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 if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n providerKey,\n req.url ?? \"/v1/embeddings\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n // No fixture match — generate deterministic embeddings from input text\n logger.warn(\n `No embedding fixture matched for \"${combinedInput.slice(0, 80)}\" — returning deterministic fallback`,\n );\n // Validate dimensions here, on the only path that reads it: a bad value\n // either throws RangeError in `new Array()` below or, past the serialization\n // budget MAX_EMBEDDING_DIMENSIONS encodes, kills the process outright. The\n // fixture-replay, chaos, strict and record/proxy branches above never touch\n // it, so they must not be gated.\n const dimensions = validateEmbeddingDimensions(embeddingReq.dimensions);\n if (dimensions === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Invalid parameter: 'dimensions' must be an integer between 1 and ${MAX_EMBEDDING_DIMENSIONS}`,\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n\n const embeddings = inputs.map((input) => generateDeterministicEmbedding(input, dimensions));\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n\n const body = buildEmbeddingResponse(embeddings, embeddingReq.model);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n"],"mappings":";;;;;;;AAsDA,eAAsB,iBACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,cAAiC,UAClB;CACf,MAAM,EAAE,WAAW;AACnB,gBAAe,IAAI;CAEnB,IAAI;AACJ,KAAI;AACF,iBAAe,KAAK,MAAM,IAAI;UACvB,UAAU;EACjB,MAAM,SAAS,oBAAoB,QAAQ,SAAS,UAAU;AAC9D,UAAQ,IAAI;GACV,QAAQ,IAAI,UAAU;GACtB,MAAM,IAAI,OAAO;GACjB,SAASA,+BAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,wCACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS,wBAAwB;GACjC,MAAM;GACN,MAAM;GACP,EACF,CAAC,CACH;AACD;;AAMF,KAAI,CAACC,6BAAa,aAAa,EAAE;AAC/B,UAA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,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS,oEAAoEkB;GAC7E,MAAM;GACN,OAAO;GACP,MAAM;GACP,EACF,CAAC,CACH;AACD;;CAGF,MAAM,aAAa,OAAO,KAAK,UAAUC,+CAA+B,OAAO,WAAW,CAAC;AAE3F,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAASnB,+BAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM;EACzC,CAAC;CAEF,MAAM,OAAOW,uCAAuB,YAAY,aAAa,MAAM;AACnE,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IAAI,KAAK,UAAU,KAAK,CAAC"}
1
+ {"version":3,"file":"embeddings.cjs","names":["flattenHeaders","isJsonObject","normalizeEmbeddingInput","getContext","getTestId","selectFixtureForServing","applyChaosAsync","resolveResponse","isErrorResponse","serializeErrorResponse","isEmbeddingResponse","buildEmbeddingResponse","resolveStrictMode","strictNoMatchMessage","strictNoMatchLogLine","strictOverrideField","proxyAndRecord","validateEmbeddingDimensions","MAX_EMBEDDING_DIMENSIONS","generateDeterministicEmbedding"],"sources":["../src/embeddings.ts"],"sourcesContent":["/**\n * OpenAI Embeddings API support for aimock.\n *\n * Handles POST /v1/embeddings requests. Matches fixtures using the `inputText`\n * field, and falls back to generating a deterministic embedding from the input\n * text hash when no fixture matches.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RecordProviderKey,\n} from \"./types.js\";\nimport {\n isEmbeddingResponse,\n isErrorResponse,\n serializeErrorResponse,\n generateDeterministicEmbedding,\n buildEmbeddingResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n validateEmbeddingDimensions,\n isJsonObject,\n normalizeEmbeddingInput,\n MAX_EMBEDDING_DIMENSIONS,\n} from \"./helpers.js\";\nimport { releaseOneShotError } from \"./fixture-loader.js\";\nimport { selectFixtureForServing } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaosAsync } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Embeddings API request types ──────────────────────────────────────────\n\ninterface EmbeddingRequest {\n // Validated at runtime — these arrive as arbitrary JSON, so the declared\n // type must not claim a shape the parser cannot guarantee.\n input: unknown;\n model: string;\n encoding_format?: \"float\" | \"base64\";\n dimensions?: unknown;\n [key: string]: unknown;\n}\n\n// ─── Request handler ───────────────────────────────────────────────────────\n\nexport async function handleEmbeddings(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n providerKey: RecordProviderKey = \"openai\",\n // Native HTTP dispatch opts in; direct callers and compatible routes retain defaults.\n requireModel = false,\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let embeddingReq: EmbeddingRequest;\n try {\n embeddingReq = JSON.parse(raw) as EmbeddingRequest;\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/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Malformed JSON body: ${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 `embeddingReq.input` throws a TypeError that\n // surfaces as a 500 instead of a 400.\n if (!isJsonObject(embeddingReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\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 // Validate required input parameter\n if (embeddingReq.input === undefined || embeddingReq.input === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Missing required parameter: 'input'\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (requireModel && embeddingReq.model === undefined) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Missing required parameter: 'model'\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Normalize input to array of strings — reject non-string inputs with 400\n // instead of crashing downstream in createHash().update() (500).\n const inputs = normalizeEmbeddingInput(embeddingReq.input);\n if (inputs === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message:\n \"Invalid parameter: 'input' must be a string, an array of strings, or an array of tokens\",\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n\n // Concatenate all inputs for matching purposes\n const combinedInput = inputs.join(\" \");\n\n // Build a synthetic ChatCompletionRequest for the fixture router.\n // We attach `embeddingInput` so the router's inputText matching can use it.\n const syntheticReq: ChatCompletionRequest = {\n model: embeddingReq.model,\n messages: [],\n embeddingInput: combinedInput,\n _endpointType: \"embedding\",\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = selectFixtureForServing(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n ) {\n releaseOneShotError(fixtures, fixture);\n return;\n }\n\n if (fixture) {\n const response = await resolveResponse(fixture, syntheticReq);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Embedding response — use the fixture's embedding for each input\n if (isEmbeddingResponse(response)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n const embeddings = inputs.map(() => [...response.embedding]);\n const body = buildEmbeddingResponse(embeddings, embeddingReq.model);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n return;\n }\n\n // Fixture matched but response type is not compatible with embeddings\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message:\n \"Fixture response did not match any known embedding type (must have embedding or error)\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n // No fixture match — check strict mode first, then try proxy\n if (resolveStrictMode(defaults.strict, req.headers)) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(\n req.method ?? \"POST\",\n req.url ?? \"/v1/embeddings\",\n skippedBySequenceOrTurn,\n ),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\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 if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n providerKey,\n req.url ?? \"/v1/embeddings\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n // No fixture match — generate deterministic embeddings from input text\n logger.warn(\n `No embedding fixture matched for \"${combinedInput.slice(0, 80)}\" — returning deterministic fallback`,\n );\n // Validate dimensions here, on the only path that reads it: a bad value\n // either throws RangeError in `new Array()` below or, past the serialization\n // budget MAX_EMBEDDING_DIMENSIONS encodes, kills the process outright. The\n // fixture-replay, chaos, strict and record/proxy branches above never touch\n // it, so they must not be gated.\n const dimensions = validateEmbeddingDimensions(embeddingReq.dimensions);\n if (dimensions === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Invalid parameter: 'dimensions' must be an integer between 1 and ${MAX_EMBEDDING_DIMENSIONS}`,\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n\n const embeddings = inputs.map((input) => generateDeterministicEmbedding(input, dimensions));\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n\n const body = buildEmbeddingResponse(embeddings, embeddingReq.model);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n"],"mappings":";;;;;;;;AAuDA,eAAsB,iBACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,cAAiC,UAEjC,eAAe,OACA;CACf,MAAM,EAAE,WAAW;AACnB,gBAAe,IAAI;CAEnB,IAAI;AACJ,KAAI;AACF,iBAAe,KAAK,MAAM,IAAI;UACvB,UAAU;EACjB,MAAM,SAAS,oBAAoB,QAAQ,SAAS,UAAU;AAC9D,UAAQ,IAAI;GACV,QAAQ,IAAI,UAAU;GACtB,MAAM,IAAI,OAAO;GACjB,SAASA,+BAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,wCACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS,wBAAwB;GACjC,MAAM;GACN,MAAM;GACP,EACF,CAAC,CACH;AACD;;AAMF,KAAI,CAACC,6BAAa,aAAa,EAAE;AAC/B,UAAQ,IAAI;GACV,QAAQ,IAAI,UAAU;GACtB,MAAM,IAAI,OAAO;GACjB,SAASD,+BAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,wCACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS;GACT,M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AAI,OAAO;GACjB,SAASjB,+BAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,wCACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS,oEAAoEkB;GAC7E,MAAM;GACN,OAAO;GACP,MAAM;GACP,EACF,CAAC,CACH;AACD;;CAGF,MAAM,aAAa,OAAO,KAAK,UAAUC,+CAA+B,OAAO,WAAW,CAAC;AAE3F,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAASnB,+BAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM;EACzC,CAAC;CAEF,MAAM,OAAOW,uCAAuB,YAAY,aAAa,MAAM;AACnE,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IAAI,KAAK,UAAU,KAAK,CAAC"}
@@ -4,7 +4,7 @@ import * as http$1 from "node:http";
4
4
 
5
5
  //#region src/embeddings.d.ts
6
6
 
7
- declare function handleEmbeddings(req: http$1.IncomingMessage, res: http$1.ServerResponse, raw: string, fixtures: Fixture[], journal: Journal, defaults: HandlerDefaults, setCorsHeaders: (res: http$1.ServerResponse) => void, providerKey?: RecordProviderKey): Promise<void>;
7
+ declare function handleEmbeddings(req: http$1.IncomingMessage, res: http$1.ServerResponse, raw: string, fixtures: Fixture[], journal: Journal, defaults: HandlerDefaults, setCorsHeaders: (res: http$1.ServerResponse) => void, providerKey?: RecordProviderKey, requireModel?: boolean): Promise<void>;
8
8
  //# sourceMappingURL=embeddings.d.ts.map
9
9
 
10
10
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"embeddings.d.cts","names":[],"sources":["../src/embeddings.ts"],"sourcesContent":[],"mappings":";;;;;;AA2DW,iBALW,gBAAA,CAKX,GAAA,EAJJ,MAAA,CAAK,eAID,EAAA,GAAA,EAHJ,MAAA,CAAK,cAGD,EAAA,GAAA,EAAA,MAAA,EAAA,QAAA,EADC,OACD,EAAA,EAAA,OAAA,EAAA,OAAA,EAAA,QAAA,EACC,eADD,EAAA,cAAA,EAAA,CAAA,GAAA,EAEa,MAAA,CAAK,cAFlB,EAAA,GAAA,IAAA,EAAA,WAAA,CAAA,EAGI,iBAHJ,CAAA,EAIR,OAJQ,CAAA,IAAA,CAAA"}
1
+ {"version":3,"file":"embeddings.d.cts","names":[],"sources":["../src/embeddings.ts"],"sourcesContent":[],"mappings":";;;;;;AA4DW,iBALW,gBAAA,CAKX,GAAA,EAJJ,MAAA,CAAK,eAID,EAAA,GAAA,EAHJ,MAAA,CAAK,cAGD,EAAA,GAAA,EAAA,MAAA,EAAA,QAAA,EADC,OACD,EAAA,EAAA,OAAA,EAAA,OAAA,EAAA,QAAA,EACC,eADD,EAAA,cAAA,EAAA,CAAA,GAAA,EAEa,MAAA,CAAK,cAFlB,EAAA,GAAA,IAAA,EAAA,WAAA,CAAA,EAGI,iBAHJ,EAAA,YAAA,CAAA,EAAA,OAAA,CAAA,EAMR,OANQ,CAAA,IAAA,CAAA"}
@@ -4,7 +4,7 @@ import * as http$1 from "node:http";
4
4
 
5
5
  //#region src/embeddings.d.ts
6
6
 
7
- declare function handleEmbeddings(req: http$1.IncomingMessage, res: http$1.ServerResponse, raw: string, fixtures: Fixture[], journal: Journal, defaults: HandlerDefaults, setCorsHeaders: (res: http$1.ServerResponse) => void, providerKey?: RecordProviderKey): Promise<void>;
7
+ declare function handleEmbeddings(req: http$1.IncomingMessage, res: http$1.ServerResponse, raw: string, fixtures: Fixture[], journal: Journal, defaults: HandlerDefaults, setCorsHeaders: (res: http$1.ServerResponse) => void, providerKey?: RecordProviderKey, requireModel?: boolean): Promise<void>;
8
8
  //# sourceMappingURL=embeddings.d.ts.map
9
9
 
10
10
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"embeddings.d.ts","names":[],"sources":["../src/embeddings.ts"],"sourcesContent":[],"mappings":";;;;;;AA2DW,iBALW,gBAAA,CAKX,GAAA,EAJJ,MAAA,CAAK,eAID,EAAA,GAAA,EAHJ,MAAA,CAAK,cAGD,EAAA,GAAA,EAAA,MAAA,EAAA,QAAA,EADC,OACD,EAAA,EAAA,OAAA,EAAA,OAAA,EAAA,QAAA,EACC,eADD,EAAA,cAAA,EAAA,CAAA,GAAA,EAEa,MAAA,CAAK,cAFlB,EAAA,GAAA,IAAA,EAAA,WAAA,CAAA,EAGI,iBAHJ,CAAA,EAIR,OAJQ,CAAA,IAAA,CAAA"}
1
+ {"version":3,"file":"embeddings.d.ts","names":[],"sources":["../src/embeddings.ts"],"sourcesContent":[],"mappings":";;;;;;AA4DW,iBALW,gBAAA,CAKX,GAAA,EAJJ,MAAA,CAAK,eAID,EAAA,GAAA,EAHJ,MAAA,CAAK,cAGD,EAAA,GAAA,EAAA,MAAA,EAAA,QAAA,EADC,OACD,EAAA,EAAA,OAAA,EAAA,OAAA,EAAA,QAAA,EACC,eADD,EAAA,cAAA,EAAA,CAAA,GAAA,EAEa,MAAA,CAAK,cAFlB,EAAA,GAAA,IAAA,EAAA,WAAA,CAAA,EAGI,iBAHJ,EAAA,YAAA,CAAA,EAAA,OAAA,CAAA,EAMR,OANQ,CAAA,IAAA,CAAA"}
@@ -1,11 +1,12 @@
1
1
  import { MAX_EMBEDDING_DIMENSIONS, buildEmbeddingResponse, flattenHeaders, generateDeterministicEmbedding, getContext, getTestId, isEmbeddingResponse, isErrorResponse, isJsonObject, normalizeEmbeddingInput, resolveResponse, resolveStrictMode, serializeErrorResponse, strictNoMatchLogLine, strictNoMatchMessage, strictOverrideField, validateEmbeddingDimensions } from "./helpers.js";
2
- import { matchFixtureDiagnostic } from "./router.js";
3
2
  import { writeErrorResponse } from "./sse-writer.js";
4
- import { applyChaos } from "./chaos.js";
3
+ import { applyChaosAsync } from "./chaos.js";
4
+ import { releaseOneShotError } from "./fixture-loader.js";
5
+ import { selectFixtureForServing } from "./router.js";
5
6
  import { proxyAndRecord } from "./recorder.js";
6
7
 
7
8
  //#region src/embeddings.ts
8
- async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setCorsHeaders, providerKey = "openai") {
9
+ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setCorsHeaders, providerKey = "openai", requireModel = false) {
9
10
  const { logger } = defaults;
10
11
  setCorsHeaders(res);
11
12
  let embeddingReq;
@@ -64,6 +65,23 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
64
65
  } }));
65
66
  return;
66
67
  }
68
+ if (requireModel && embeddingReq.model === void 0) {
69
+ journal.add({
70
+ method: req.method ?? "POST",
71
+ path: req.url ?? "/v1/embeddings",
72
+ headers: flattenHeaders(req.headers),
73
+ body: null,
74
+ response: {
75
+ status: 400,
76
+ fixture: null
77
+ }
78
+ });
79
+ writeErrorResponse(res, 400, JSON.stringify({ error: {
80
+ message: "Missing required parameter: 'model'",
81
+ type: "invalid_request_error"
82
+ } }));
83
+ return;
84
+ }
67
85
  const inputs = normalizeEmbeddingInput(embeddingReq.input);
68
86
  if (inputs === null) {
69
87
  journal.add({
@@ -93,17 +111,20 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
93
111
  _context: getContext(req)
94
112
  };
95
113
  const testId = getTestId(req);
96
- const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
114
+ const { fixture, skippedBySequenceOrTurn } = selectFixtureForServing(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
97
115
  if (fixture) {
98
116
  journal.incrementFixtureMatchCount(fixture, fixtures, testId);
99
117
  logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);
100
118
  } else logger.debug(`No fixture matched for request`);
101
- if (applyChaos(res, fixture, defaults.chaos, req.headers, req.url, journal, {
119
+ if (await applyChaosAsync(res, fixture, defaults.chaos, req.headers, req.url, journal, {
102
120
  method: req.method ?? "POST",
103
121
  path: req.url ?? "/v1/embeddings",
104
122
  headers: flattenHeaders(req.headers),
105
123
  body: syntheticReq
106
- }, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) return;
124
+ }, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) {
125
+ releaseOneShotError(fixtures, fixture);
126
+ return;
127
+ }
107
128
  if (fixture) {
108
129
  const response = await resolveResponse(fixture, syntheticReq);
109
130
  if (isErrorResponse(response)) {
@@ -1 +1 @@
1
- {"version":3,"file":"embeddings.js","names":[],"sources":["../src/embeddings.ts"],"sourcesContent":["/**\n * OpenAI Embeddings API support for aimock.\n *\n * Handles POST /v1/embeddings requests. Matches fixtures using the `inputText`\n * field, and falls back to generating a deterministic embedding from the input\n * text hash when no fixture matches.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RecordProviderKey,\n} from \"./types.js\";\nimport {\n isEmbeddingResponse,\n isErrorResponse,\n serializeErrorResponse,\n generateDeterministicEmbedding,\n buildEmbeddingResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n validateEmbeddingDimensions,\n isJsonObject,\n normalizeEmbeddingInput,\n MAX_EMBEDDING_DIMENSIONS,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Embeddings API request types ──────────────────────────────────────────\n\ninterface EmbeddingRequest {\n // Validated at runtime — these arrive as arbitrary JSON, so the declared\n // type must not claim a shape the parser cannot guarantee.\n input: unknown;\n model: string;\n encoding_format?: \"float\" | \"base64\";\n dimensions?: unknown;\n [key: string]: unknown;\n}\n\n// ─── Request handler ───────────────────────────────────────────────────────\n\nexport async function handleEmbeddings(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n providerKey: RecordProviderKey = \"openai\",\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let embeddingReq: EmbeddingRequest;\n try {\n embeddingReq = JSON.parse(raw) as EmbeddingRequest;\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/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Malformed JSON body: ${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 `embeddingReq.input` throws a TypeError that\n // surfaces as a 500 instead of a 400.\n if (!isJsonObject(embeddingReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\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 // Validate required input parameter\n if (embeddingReq.input === undefined || embeddingReq.input === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Missing required parameter: 'input'\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Normalize input to array of strings — reject non-string inputs with 400\n // instead of crashing downstream in createHash().update() (500).\n const inputs = normalizeEmbeddingInput(embeddingReq.input);\n if (inputs === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message:\n \"Invalid parameter: 'input' must be a string, an array of strings, or an array of tokens\",\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n\n // Concatenate all inputs for matching purposes\n const combinedInput = inputs.join(\" \");\n\n // Build a synthetic ChatCompletionRequest for the fixture router.\n // We attach `embeddingInput` so the router's inputText matching can use it.\n const syntheticReq: ChatCompletionRequest = {\n model: embeddingReq.model,\n messages: [],\n embeddingInput: combinedInput,\n _endpointType: \"embedding\",\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n logger.debug(`No fixture matched for request`);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (fixture) {\n const response = await resolveResponse(fixture, syntheticReq);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Embedding response — use the fixture's embedding for each input\n if (isEmbeddingResponse(response)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n const embeddings = inputs.map(() => [...response.embedding]);\n const body = buildEmbeddingResponse(embeddings, embeddingReq.model);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n return;\n }\n\n // Fixture matched but response type is not compatible with embeddings\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message:\n \"Fixture response did not match any known embedding type (must have embedding or error)\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n // No fixture match — check strict mode first, then try proxy\n if (resolveStrictMode(defaults.strict, req.headers)) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(\n req.method ?? \"POST\",\n req.url ?? \"/v1/embeddings\",\n skippedBySequenceOrTurn,\n ),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\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 if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n providerKey,\n req.url ?? \"/v1/embeddings\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n // No fixture match — generate deterministic embeddings from input text\n logger.warn(\n `No embedding fixture matched for \"${combinedInput.slice(0, 80)}\" — returning deterministic fallback`,\n );\n // Validate dimensions here, on the only path that reads it: a bad value\n // either throws RangeError in `new Array()` below or, past the serialization\n // budget MAX_EMBEDDING_DIMENSIONS encodes, kills the process outright. The\n // fixture-replay, chaos, strict and record/proxy branches above never touch\n // it, so they must not be gated.\n const dimensions = validateEmbeddingDimensions(embeddingReq.dimensions);\n if (dimensions === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Invalid parameter: 'dimensions' must be an integer between 1 and ${MAX_EMBEDDING_DIMENSIONS}`,\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n\n const embeddings = inputs.map((input) => generateDeterministicEmbedding(input, dimensions));\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n\n const body = buildEmbeddingResponse(embeddings, embeddingReq.model);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n"],"mappings":";;;;;;;AAsDA,eAAsB,iBACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,cAAiC,UAClB;CACf,MAAM,EAAE,WAAW;AACnB,gBAAe,IAAI;CAEnB,IAAI;AACJ,KAAI;AACF,iBAAe,KAAK,MAAM,IAAI;UACvB,UAAU;EACjB,MAAM,SAAS,oBAAoB,QAAQ,SAAS,UAAU;AAC9D,UAAQ,IAAI;GACV,QAAQ,IAAI,UAAU;GACtB,MAAM,IAAI,OAAO;GACjB,SAAS,eAAe,IAAI,QAAQ;GACp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AAe,MAAM;AACvB,UAAQ,IAAI;GACV,QAAQ,IAAI,UAAU;GACtB,MAAM,IAAI,OAAO;GACjB,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,qBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS,oEAAoE;GAC7E,MAAM;GACN,OAAO;GACP,MAAM;GACP,EACF,CAAC,CACH;AACD;;CAGF,MAAM,aAAa,OAAO,KAAK,UAAU,+BAA+B,OAAO,WAAW,CAAC;AAE3F,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM;EACzC,CAAC;CAEF,MAAM,OAAO,uBAAuB,YAAY,aAAa,MAAM;AACnE,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IAAI,KAAK,UAAU,KAAK,CAAC"}
1
+ {"version":3,"file":"embeddings.js","names":[],"sources":["../src/embeddings.ts"],"sourcesContent":["/**\n * OpenAI Embeddings API support for aimock.\n *\n * Handles POST /v1/embeddings requests. Matches fixtures using the `inputText`\n * field, and falls back to generating a deterministic embedding from the input\n * text hash when no fixture matches.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RecordProviderKey,\n} from \"./types.js\";\nimport {\n isEmbeddingResponse,\n isErrorResponse,\n serializeErrorResponse,\n generateDeterministicEmbedding,\n buildEmbeddingResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n validateEmbeddingDimensions,\n isJsonObject,\n normalizeEmbeddingInput,\n MAX_EMBEDDING_DIMENSIONS,\n} from \"./helpers.js\";\nimport { releaseOneShotError } from \"./fixture-loader.js\";\nimport { selectFixtureForServing } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaosAsync } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Embeddings API request types ──────────────────────────────────────────\n\ninterface EmbeddingRequest {\n // Validated at runtime — these arrive as arbitrary JSON, so the declared\n // type must not claim a shape the parser cannot guarantee.\n input: unknown;\n model: string;\n encoding_format?: \"float\" | \"base64\";\n dimensions?: unknown;\n [key: string]: unknown;\n}\n\n// ─── Request handler ───────────────────────────────────────────────────────\n\nexport async function handleEmbeddings(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n providerKey: RecordProviderKey = \"openai\",\n // Native HTTP dispatch opts in; direct callers and compatible routes retain defaults.\n requireModel = false,\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let embeddingReq: EmbeddingRequest;\n try {\n embeddingReq = JSON.parse(raw) as EmbeddingRequest;\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/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Malformed JSON body: ${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 `embeddingReq.input` throws a TypeError that\n // surfaces as a 500 instead of a 400.\n if (!isJsonObject(embeddingReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\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 // Validate required input parameter\n if (embeddingReq.input === undefined || embeddingReq.input === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Missing required parameter: 'input'\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (requireModel && embeddingReq.model === undefined) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Missing required parameter: 'model'\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Normalize input to array of strings — reject non-string inputs with 400\n // instead of crashing downstream in createHash().update() (500).\n const inputs = normalizeEmbeddingInput(embeddingReq.input);\n if (inputs === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message:\n \"Invalid parameter: 'input' must be a string, an array of strings, or an array of tokens\",\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n\n // Concatenate all inputs for matching purposes\n const combinedInput = inputs.join(\" \");\n\n // Build a synthetic ChatCompletionRequest for the fixture router.\n // We attach `embeddingInput` so the router's inputText matching can use it.\n const syntheticReq: ChatCompletionRequest = {\n model: embeddingReq.model,\n messages: [],\n embeddingInput: combinedInput,\n _endpointType: \"embedding\",\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = selectFixtureForServing(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n ) {\n releaseOneShotError(fixtures, fixture);\n return;\n }\n\n if (fixture) {\n const response = await resolveResponse(fixture, syntheticReq);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Embedding response — use the fixture's embedding for each input\n if (isEmbeddingResponse(response)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n const embeddings = inputs.map(() => [...response.embedding]);\n const body = buildEmbeddingResponse(embeddings, embeddingReq.model);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n return;\n }\n\n // Fixture matched but response type is not compatible with embeddings\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message:\n \"Fixture response did not match any known embedding type (must have embedding or error)\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n // No fixture match — check strict mode first, then try proxy\n if (resolveStrictMode(defaults.strict, req.headers)) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(\n req.method ?? \"POST\",\n req.url ?? \"/v1/embeddings\",\n skippedBySequenceOrTurn,\n ),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\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 if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n providerKey,\n req.url ?? \"/v1/embeddings\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n // No fixture match — generate deterministic embeddings from input text\n logger.warn(\n `No embedding fixture matched for \"${combinedInput.slice(0, 80)}\" — returning deterministic fallback`,\n );\n // Validate dimensions here, on the only path that reads it: a bad value\n // either throws RangeError in `new Array()` below or, past the serialization\n // budget MAX_EMBEDDING_DIMENSIONS encodes, kills the process outright. The\n // fixture-replay, chaos, strict and record/proxy branches above never touch\n // it, so they must not be gated.\n const dimensions = validateEmbeddingDimensions(embeddingReq.dimensions);\n if (dimensions === null) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Invalid parameter: 'dimensions' must be an integer between 1 and ${MAX_EMBEDDING_DIMENSIONS}`,\n type: \"invalid_request_error\",\n param: null,\n code: null,\n },\n }),\n );\n return;\n }\n\n const embeddings = inputs.map((input) => generateDeterministicEmbedding(input, dimensions));\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/embeddings\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n\n const body = buildEmbeddingResponse(embeddings, embeddingReq.model);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n"],"mappings":";;;;;;;;AAuDA,eAAsB,iBACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,cAAiC,UAEjC,eAAe,OACA;CACf,MAAM,EAAE,WAAW;AACnB,gBAAe,IAAI;CAEnB,IAAI;AACJ,KAAI;AACF,iBAAe,KAAK,MAAM,IAAI;UACvB,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,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,qBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS,wBAAwB;GACjC,MAAM;GACN,MAAM;GACP,EACF,CAAC,CACH;AACD;;AAMF,KAAI,CAAC,aAAa,aAAa,EAAE;AAC/B,UAAQ,IAAI;GACV,QAAQ,IAAI,UAAU;GACtB,MAAM,IAAI,OAAO;GACjB,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,qBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS;GACT,MAAM;GACP,EACF,CAAC,CACH;AACD;;AAIF,KAAI,aAAa,UAAU,UAAa,aAAa,U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,CAAC;AACF,qBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS,oEAAoE;GAC7E,MAAM;GACN,OAAO;GACP,MAAM;GACP,EACF,CAAC,CACH;AACD;;CAGF,MAAM,aAAa,OAAO,KAAK,UAAU,+BAA+B,OAAO,WAAW,CAAC;AAE3F,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM;EACzC,CAAC;CAEF,MAAM,OAAO,uBAAuB,YAAY,aAAa,MAAM;AACnE,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IAAI,KAAK,UAAU,KAAK,CAAC"}
@@ -1,9 +1,9 @@
1
1
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
2
  const require_api_key_auth = require('./api-key-auth.cjs');
3
3
  const require_helpers = require('./helpers.cjs');
4
- const require_router = require('./router.cjs');
5
4
  const require_sse_writer = require('./sse-writer.cjs');
6
5
  const require_chaos = require('./chaos.cjs');
6
+ const require_router = require('./router.cjs');
7
7
  const require_recorder = require('./recorder.cjs');
8
8
  const require_fal = require('./fal.cjs');
9
9
  let node_crypto = require("node:crypto");
@@ -200,7 +200,7 @@ async function handleQueueSubmit(req, res, body, pathname, modelId, testId, fixt
200
200
  };
201
201
  const { fixture, skippedBySequenceOrTurn } = require_router.matchFixtureDiagnostic(fixtures, syntheticReq, matchCounts, defaults.requestTransform);
202
202
  if (fixture) journal.incrementFixtureMatchCount(fixture, fixtures, testId);
203
- if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, req.url, journal, {
203
+ if (await require_chaos.applyChaosAsync(res, fixture, defaults.chaos, req.headers, req.url, journal, {
204
204
  method: req.method ?? "POST",
205
205
  path: pathname,
206
206
  headers: require_helpers.flattenHeaders(req.headers),
@@ -659,7 +659,7 @@ async function handleSyncRun(req, res, body, pathname, modelId, fixtures, defaul
659
659
  };
660
660
  const { fixture, skippedBySequenceOrTurn } = require_router.matchFixtureDiagnostic(fixtures, syntheticReq, matchCounts, defaults.requestTransform);
661
661
  if (fixture) journal.incrementFixtureMatchCount(fixture, fixtures, require_helpers.getTestId(req));
662
- if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, req.url, journal, {
662
+ if (await require_chaos.applyChaosAsync(res, fixture, defaults.chaos, req.headers, req.url, journal, {
663
663
  method: req.method ?? "POST",
664
664
  path: pathname,
665
665
  headers: require_helpers.flattenHeaders(req.headers),