@copilotkit/aimock 1.45.1 → 1.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (492) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +25 -1
  4. package/README.md +11 -2
  5. package/dist/agui-mock.cjs +25 -25
  6. package/dist/agui-mock.cjs.map +1 -1
  7. package/dist/agui-mock.d.cts.map +1 -1
  8. package/dist/agui-mock.d.ts.map +1 -1
  9. package/dist/agui-mock.js +25 -25
  10. package/dist/agui-mock.js.map +1 -1
  11. package/dist/agui-types.d.cts.map +1 -1
  12. package/dist/aimock-cli.cjs +15 -1
  13. package/dist/aimock-cli.cjs.map +1 -1
  14. package/dist/aimock-cli.d.cts.map +1 -1
  15. package/dist/aimock-cli.d.ts.map +1 -1
  16. package/dist/aimock-cli.js +16 -2
  17. package/dist/aimock-cli.js.map +1 -1
  18. package/dist/api-key-auth.cjs +10 -9
  19. package/dist/api-key-auth.cjs.map +1 -1
  20. package/dist/api-key-auth.d.cts.map +1 -1
  21. package/dist/api-key-auth.d.ts.map +1 -1
  22. package/dist/api-key-auth.js +11 -10
  23. package/dist/api-key-auth.js.map +1 -1
  24. package/dist/aws-event-stream.cjs +20 -23
  25. package/dist/aws-event-stream.cjs.map +1 -1
  26. package/dist/aws-event-stream.d.cts +0 -1
  27. package/dist/aws-event-stream.d.ts +0 -1
  28. package/dist/aws-event-stream.js +20 -24
  29. package/dist/aws-event-stream.js.map +1 -1
  30. package/dist/batches.cjs +2 -4
  31. package/dist/batches.cjs.map +1 -1
  32. package/dist/batches.d.cts.map +1 -1
  33. package/dist/batches.d.ts.map +1 -1
  34. package/dist/batches.js +2 -4
  35. package/dist/batches.js.map +1 -1
  36. package/dist/bedrock-converse.cjs +139 -161
  37. package/dist/bedrock-converse.cjs.map +1 -1
  38. package/dist/bedrock-converse.d.cts.map +1 -1
  39. package/dist/bedrock-converse.d.ts.map +1 -1
  40. package/dist/bedrock-converse.js +137 -159
  41. package/dist/bedrock-converse.js.map +1 -1
  42. package/dist/bedrock.cjs +175 -216
  43. package/dist/bedrock.cjs.map +1 -1
  44. package/dist/bedrock.d.cts.map +1 -1
  45. package/dist/bedrock.d.ts.map +1 -1
  46. package/dist/bedrock.js +172 -213
  47. package/dist/bedrock.js.map +1 -1
  48. package/dist/byteplus-video.cjs +11 -10
  49. package/dist/byteplus-video.cjs.map +1 -1
  50. package/dist/byteplus-video.d.cts.map +1 -1
  51. package/dist/byteplus-video.d.ts.map +1 -1
  52. package/dist/byteplus-video.js +5 -4
  53. package/dist/byteplus-video.js.map +1 -1
  54. package/dist/chaos.cjs +5 -4
  55. package/dist/chaos.cjs.map +1 -1
  56. package/dist/chaos.d.cts.map +1 -1
  57. package/dist/chaos.d.ts.map +1 -1
  58. package/dist/chaos.js +5 -4
  59. package/dist/chaos.js.map +1 -1
  60. package/dist/cli.cjs +15 -0
  61. package/dist/cli.cjs.map +1 -1
  62. package/dist/cli.js +15 -0
  63. package/dist/cli.js.map +1 -1
  64. package/dist/cohere.cjs +107 -180
  65. package/dist/cohere.cjs.map +1 -1
  66. package/dist/cohere.d.cts.map +1 -1
  67. package/dist/cohere.d.ts.map +1 -1
  68. package/dist/cohere.js +106 -179
  69. package/dist/cohere.js.map +1 -1
  70. package/dist/config-loader.cjs +29 -1
  71. package/dist/config-loader.cjs.map +1 -1
  72. package/dist/config-loader.d.cts +7 -1
  73. package/dist/config-loader.d.cts.map +1 -1
  74. package/dist/config-loader.d.ts +7 -1
  75. package/dist/config-loader.d.ts.map +1 -1
  76. package/dist/config-loader.js +29 -2
  77. package/dist/config-loader.js.map +1 -1
  78. package/dist/count-tokens.cjs +146 -0
  79. package/dist/count-tokens.cjs.map +1 -0
  80. package/dist/count-tokens.js +146 -0
  81. package/dist/count-tokens.js.map +1 -0
  82. package/dist/elevenlabs-audio.cjs +36 -34
  83. package/dist/elevenlabs-audio.cjs.map +1 -1
  84. package/dist/elevenlabs-audio.d.cts.map +1 -1
  85. package/dist/elevenlabs-audio.d.ts.map +1 -1
  86. package/dist/elevenlabs-audio.js +33 -31
  87. package/dist/elevenlabs-audio.js.map +1 -1
  88. package/dist/elevenlabs-voice.cjs +38 -37
  89. package/dist/elevenlabs-voice.cjs.map +1 -1
  90. package/dist/elevenlabs-voice.d.cts.map +1 -1
  91. package/dist/elevenlabs-voice.d.ts.map +1 -1
  92. package/dist/elevenlabs-voice.js +33 -32
  93. package/dist/elevenlabs-voice.js.map +1 -1
  94. package/dist/embedding-request.cjs +16 -0
  95. package/dist/embedding-request.cjs.map +1 -0
  96. package/dist/embedding-request.js +14 -0
  97. package/dist/embedding-request.js.map +1 -0
  98. package/dist/embeddings.cjs +30 -20
  99. package/dist/embeddings.cjs.map +1 -1
  100. package/dist/embeddings.d.cts.map +1 -1
  101. package/dist/embeddings.d.ts.map +1 -1
  102. package/dist/embeddings.js +30 -20
  103. package/dist/embeddings.js.map +1 -1
  104. package/dist/fal-audio.cjs +45 -43
  105. package/dist/fal-audio.cjs.map +1 -1
  106. package/dist/fal-audio.d.cts.map +1 -1
  107. package/dist/fal-audio.d.ts.map +1 -1
  108. package/dist/fal-audio.js +42 -40
  109. package/dist/fal-audio.js.map +1 -1
  110. package/dist/fal.cjs +17 -15
  111. package/dist/fal.cjs.map +1 -1
  112. package/dist/fal.js +16 -14
  113. package/dist/fal.js.map +1 -1
  114. package/dist/files.cjs +2 -4
  115. package/dist/files.cjs.map +1 -1
  116. package/dist/files.d.cts.map +1 -1
  117. package/dist/files.d.ts.map +1 -1
  118. package/dist/files.js +2 -4
  119. package/dist/files.js.map +1 -1
  120. package/dist/fine-tuning.cjs +2 -4
  121. package/dist/fine-tuning.cjs.map +1 -1
  122. package/dist/fine-tuning.d.cts.map +1 -1
  123. package/dist/fine-tuning.d.ts.map +1 -1
  124. package/dist/fine-tuning.js +2 -4
  125. package/dist/fine-tuning.js.map +1 -1
  126. package/dist/fixture-loader.cjs +140 -44
  127. package/dist/fixture-loader.cjs.map +1 -1
  128. package/dist/fixture-loader.d.cts.map +1 -1
  129. package/dist/fixture-loader.d.ts.map +1 -1
  130. package/dist/fixture-loader.js +141 -46
  131. package/dist/fixture-loader.js.map +1 -1
  132. package/dist/gemini-embeddings.cjs +26 -24
  133. package/dist/gemini-embeddings.cjs.map +1 -1
  134. package/dist/gemini-embeddings.js +26 -24
  135. package/dist/gemini-embeddings.js.map +1 -1
  136. package/dist/gemini-interactions.cjs +113 -156
  137. package/dist/gemini-interactions.cjs.map +1 -1
  138. package/dist/gemini-interactions.d.cts +0 -1
  139. package/dist/gemini-interactions.d.cts.map +1 -1
  140. package/dist/gemini-interactions.d.ts +0 -1
  141. package/dist/gemini-interactions.d.ts.map +1 -1
  142. package/dist/gemini-interactions.js +113 -156
  143. package/dist/gemini-interactions.js.map +1 -1
  144. package/dist/gemini.cjs +295 -218
  145. package/dist/gemini.cjs.map +1 -1
  146. package/dist/gemini.d.cts.map +1 -1
  147. package/dist/gemini.d.ts.map +1 -1
  148. package/dist/gemini.js +295 -219
  149. package/dist/gemini.js.map +1 -1
  150. package/dist/grok-video.cjs +14 -12
  151. package/dist/grok-video.cjs.map +1 -1
  152. package/dist/grok-video.d.cts.map +1 -1
  153. package/dist/grok-video.d.ts.map +1 -1
  154. package/dist/grok-video.js +8 -6
  155. package/dist/grok-video.js.map +1 -1
  156. package/dist/helpers.cjs +411 -75
  157. package/dist/helpers.cjs.map +1 -1
  158. package/dist/helpers.d.cts +51 -1
  159. package/dist/helpers.d.cts.map +1 -1
  160. package/dist/helpers.d.ts +51 -1
  161. package/dist/helpers.d.ts.map +1 -1
  162. package/dist/helpers.js +402 -74
  163. package/dist/helpers.js.map +1 -1
  164. package/dist/images.cjs +30 -28
  165. package/dist/images.cjs.map +1 -1
  166. package/dist/images.d.cts.map +1 -1
  167. package/dist/images.d.ts.map +1 -1
  168. package/dist/images.js +27 -25
  169. package/dist/images.js.map +1 -1
  170. package/dist/index.cjs +4 -2
  171. package/dist/index.d.cts +4 -4
  172. package/dist/index.d.ts +4 -4
  173. package/dist/index.js +4 -4
  174. package/dist/journal.cjs +3 -1
  175. package/dist/journal.cjs.map +1 -1
  176. package/dist/journal.d.cts.map +1 -1
  177. package/dist/journal.d.ts.map +1 -1
  178. package/dist/journal.js +2 -1
  179. package/dist/journal.js.map +1 -1
  180. package/dist/llmock.cjs +3 -0
  181. package/dist/llmock.cjs.map +1 -1
  182. package/dist/llmock.d.cts.map +1 -1
  183. package/dist/llmock.d.ts.map +1 -1
  184. package/dist/llmock.js +3 -0
  185. package/dist/llmock.js.map +1 -1
  186. package/dist/mcp-fakes.d.cts.map +1 -1
  187. package/dist/mcp-handler.cjs +7 -3
  188. package/dist/mcp-handler.cjs.map +1 -1
  189. package/dist/mcp-handler.js +7 -3
  190. package/dist/mcp-handler.js.map +1 -1
  191. package/dist/mcp-recorder.cjs +2 -1
  192. package/dist/mcp-recorder.cjs.map +1 -1
  193. package/dist/mcp-recorder.js +3 -2
  194. package/dist/mcp-recorder.js.map +1 -1
  195. package/dist/messages.cjs +235 -202
  196. package/dist/messages.cjs.map +1 -1
  197. package/dist/messages.d.cts.map +1 -1
  198. package/dist/messages.d.ts.map +1 -1
  199. package/dist/messages.js +234 -202
  200. package/dist/messages.js.map +1 -1
  201. package/dist/metrics.cjs +5 -2
  202. package/dist/metrics.cjs.map +1 -1
  203. package/dist/metrics.d.cts.map +1 -1
  204. package/dist/metrics.d.ts.map +1 -1
  205. package/dist/metrics.js +6 -3
  206. package/dist/metrics.js.map +1 -1
  207. package/dist/misbehavior.cjs +62 -3
  208. package/dist/misbehavior.cjs.map +1 -1
  209. package/dist/misbehavior.d.cts.map +1 -1
  210. package/dist/misbehavior.d.ts.map +1 -1
  211. package/dist/misbehavior.js +63 -4
  212. package/dist/misbehavior.js.map +1 -1
  213. package/dist/model-utils.cjs +1 -0
  214. package/dist/model-utils.cjs.map +1 -1
  215. package/dist/model-utils.js +1 -1
  216. package/dist/model-utils.js.map +1 -1
  217. package/dist/moderation.cjs +15 -12
  218. package/dist/moderation.cjs.map +1 -1
  219. package/dist/moderation.js +14 -11
  220. package/dist/moderation.js.map +1 -1
  221. package/dist/ndjson-writer.cjs +21 -23
  222. package/dist/ndjson-writer.cjs.map +1 -1
  223. package/dist/ndjson-writer.d.cts +0 -1
  224. package/dist/ndjson-writer.d.cts.map +1 -1
  225. package/dist/ndjson-writer.d.ts +0 -1
  226. package/dist/ndjson-writer.d.ts.map +1 -1
  227. package/dist/ndjson-writer.js +21 -24
  228. package/dist/ndjson-writer.js.map +1 -1
  229. package/dist/ollama.cjs +276 -210
  230. package/dist/ollama.cjs.map +1 -1
  231. package/dist/ollama.d.cts.map +1 -1
  232. package/dist/ollama.d.ts.map +1 -1
  233. package/dist/ollama.js +273 -207
  234. package/dist/ollama.js.map +1 -1
  235. package/dist/openapi.cjs +323 -3
  236. package/dist/openapi.cjs.map +1 -1
  237. package/dist/openapi.d.cts.map +1 -1
  238. package/dist/openapi.d.ts.map +1 -1
  239. package/dist/openapi.js +324 -4
  240. package/dist/openapi.js.map +1 -1
  241. package/dist/openrouter-chat.cjs +11 -155
  242. package/dist/openrouter-chat.cjs.map +1 -1
  243. package/dist/openrouter-chat.js +11 -155
  244. package/dist/openrouter-chat.js.map +1 -1
  245. package/dist/openrouter-video.cjs +51 -74
  246. package/dist/openrouter-video.cjs.map +1 -1
  247. package/dist/openrouter-video.d.cts.map +1 -1
  248. package/dist/openrouter-video.d.ts.map +1 -1
  249. package/dist/openrouter-video.js +37 -60
  250. package/dist/openrouter-video.js.map +1 -1
  251. package/dist/raw-validation.cjs +177 -0
  252. package/dist/raw-validation.cjs.map +1 -0
  253. package/dist/raw-validation.js +176 -0
  254. package/dist/raw-validation.js.map +1 -0
  255. package/dist/recorder.cjs +176 -95
  256. package/dist/recorder.cjs.map +1 -1
  257. package/dist/recorder.d.cts.map +1 -1
  258. package/dist/recorder.d.ts.map +1 -1
  259. package/dist/recorder.js +176 -95
  260. package/dist/recorder.js.map +1 -1
  261. package/dist/rerank.cjs +13 -11
  262. package/dist/rerank.cjs.map +1 -1
  263. package/dist/rerank.js +12 -10
  264. package/dist/rerank.js.map +1 -1
  265. package/dist/response/catalog/anthropic-page.cjs +39 -0
  266. package/dist/response/catalog/anthropic-page.cjs.map +1 -0
  267. package/dist/response/catalog/anthropic-page.js +38 -0
  268. package/dist/response/catalog/anthropic-page.js.map +1 -0
  269. package/dist/response/catalog/collect.cjs +61 -0
  270. package/dist/response/catalog/collect.cjs.map +1 -0
  271. package/dist/response/catalog/collect.js +59 -0
  272. package/dist/response/catalog/collect.js.map +1 -0
  273. package/dist/response/catalog/gemini-page.cjs +25 -0
  274. package/dist/response/catalog/gemini-page.cjs.map +1 -0
  275. package/dist/response/catalog/gemini-page.js +24 -0
  276. package/dist/response/catalog/gemini-page.js.map +1 -0
  277. package/dist/response/catalog/render.cjs +182 -0
  278. package/dist/response/catalog/render.cjs.map +1 -0
  279. package/dist/response/catalog/render.js +171 -0
  280. package/dist/response/catalog/render.js.map +1 -0
  281. package/dist/response/deliver.cjs +144 -0
  282. package/dist/response/deliver.cjs.map +1 -0
  283. package/dist/response/deliver.js +143 -0
  284. package/dist/response/deliver.js.map +1 -0
  285. package/dist/response/errors.cjs +225 -0
  286. package/dist/response/errors.cjs.map +1 -0
  287. package/dist/response/errors.js +224 -0
  288. package/dist/response/errors.js.map +1 -0
  289. package/dist/response/finish.cjs +39 -0
  290. package/dist/response/finish.cjs.map +1 -0
  291. package/dist/response/finish.js +35 -0
  292. package/dist/response/finish.js.map +1 -0
  293. package/dist/response/frame-loop.cjs +102 -0
  294. package/dist/response/frame-loop.cjs.map +1 -0
  295. package/dist/response/frame-loop.js +100 -0
  296. package/dist/response/frame-loop.js.map +1 -0
  297. package/dist/response/lifecycle.cjs +223 -0
  298. package/dist/response/lifecycle.cjs.map +1 -0
  299. package/dist/response/lifecycle.js +211 -0
  300. package/dist/response/lifecycle.js.map +1 -0
  301. package/dist/response/policy.cjs +126 -0
  302. package/dist/response/policy.cjs.map +1 -0
  303. package/dist/response/policy.js +120 -0
  304. package/dist/response/policy.js.map +1 -0
  305. package/dist/response/profiles.cjs +69 -0
  306. package/dist/response/profiles.cjs.map +1 -0
  307. package/dist/response/profiles.js +65 -0
  308. package/dist/response/profiles.js.map +1 -0
  309. package/dist/response/proxy.cjs +71 -0
  310. package/dist/response/proxy.cjs.map +1 -0
  311. package/dist/response/proxy.js +70 -0
  312. package/dist/response/proxy.js.map +1 -0
  313. package/dist/response/raw.cjs +228 -0
  314. package/dist/response/raw.cjs.map +1 -0
  315. package/dist/response/raw.js +227 -0
  316. package/dist/response/raw.js.map +1 -0
  317. package/dist/response/timing.cjs +157 -0
  318. package/dist/response/timing.cjs.map +1 -0
  319. package/dist/response/timing.js +150 -0
  320. package/dist/response/timing.js.map +1 -0
  321. package/dist/response/usage/codecs/anthropic.cjs +52 -0
  322. package/dist/response/usage/codecs/anthropic.cjs.map +1 -0
  323. package/dist/response/usage/codecs/anthropic.js +50 -0
  324. package/dist/response/usage/codecs/anthropic.js.map +1 -0
  325. package/dist/response/usage/codecs/cohere.cjs +36 -0
  326. package/dist/response/usage/codecs/cohere.cjs.map +1 -0
  327. package/dist/response/usage/codecs/cohere.js +35 -0
  328. package/dist/response/usage/codecs/cohere.js.map +1 -0
  329. package/dist/response/usage/codecs/converse.cjs +16 -0
  330. package/dist/response/usage/codecs/converse.cjs.map +1 -0
  331. package/dist/response/usage/codecs/converse.js +15 -0
  332. package/dist/response/usage/codecs/converse.js.map +1 -0
  333. package/dist/response/usage/codecs/gemini.cjs +31 -0
  334. package/dist/response/usage/codecs/gemini.cjs.map +1 -0
  335. package/dist/response/usage/codecs/gemini.js +31 -0
  336. package/dist/response/usage/codecs/gemini.js.map +1 -0
  337. package/dist/response/usage/codecs/interactions.cjs +22 -0
  338. package/dist/response/usage/codecs/interactions.cjs.map +1 -0
  339. package/dist/response/usage/codecs/interactions.js +21 -0
  340. package/dist/response/usage/codecs/interactions.js.map +1 -0
  341. package/dist/response/usage/codecs/ollama.cjs +17 -0
  342. package/dist/response/usage/codecs/ollama.cjs.map +1 -0
  343. package/dist/response/usage/codecs/ollama.js +17 -0
  344. package/dist/response/usage/codecs/ollama.js.map +1 -0
  345. package/dist/response/usage/codecs/openai.cjs +52 -0
  346. package/dist/response/usage/codecs/openai.cjs.map +1 -0
  347. package/dist/response/usage/codecs/openai.js +50 -0
  348. package/dist/response/usage/codecs/openai.js.map +1 -0
  349. package/dist/response/usage/codecs/openrouter.cjs +68 -0
  350. package/dist/response/usage/codecs/openrouter.cjs.map +1 -0
  351. package/dist/response/usage/codecs/openrouter.js +67 -0
  352. package/dist/response/usage/codecs/openrouter.js.map +1 -0
  353. package/dist/response/usage/codecs/realtime.cjs +19 -0
  354. package/dist/response/usage/codecs/realtime.cjs.map +1 -0
  355. package/dist/response/usage/codecs/realtime.js +18 -0
  356. package/dist/response/usage/codecs/realtime.js.map +1 -0
  357. package/dist/response/usage/codecs/responses.cjs +21 -0
  358. package/dist/response/usage/codecs/responses.cjs.map +1 -0
  359. package/dist/response/usage/codecs/responses.js +20 -0
  360. package/dist/response/usage/codecs/responses.js.map +1 -0
  361. package/dist/response/usage/estimate.cjs +23 -0
  362. package/dist/response/usage/estimate.cjs.map +1 -0
  363. package/dist/response/usage/estimate.js +21 -0
  364. package/dist/response/usage/estimate.js.map +1 -0
  365. package/dist/response/usage/fields.cjs +72 -0
  366. package/dist/response/usage/fields.cjs.map +1 -0
  367. package/dist/response/usage/fields.js +70 -0
  368. package/dist/response/usage/fields.js.map +1 -0
  369. package/dist/response/usage/recording.cjs +52 -0
  370. package/dist/response/usage/recording.cjs.map +1 -0
  371. package/dist/response/usage/recording.js +52 -0
  372. package/dist/response/usage/recording.js.map +1 -0
  373. package/dist/responses.cjs +304 -196
  374. package/dist/responses.cjs.map +1 -1
  375. package/dist/responses.d.cts.map +1 -1
  376. package/dist/responses.d.ts.map +1 -1
  377. package/dist/responses.js +303 -195
  378. package/dist/responses.js.map +1 -1
  379. package/dist/route-registry.cjs +45 -0
  380. package/dist/route-registry.cjs.map +1 -1
  381. package/dist/route-registry.d.cts.map +1 -1
  382. package/dist/route-registry.d.ts.map +1 -1
  383. package/dist/route-registry.js +41 -1
  384. package/dist/route-registry.js.map +1 -1
  385. package/dist/router.cjs +24 -4
  386. package/dist/router.cjs.map +1 -1
  387. package/dist/router.d.cts +7 -1
  388. package/dist/router.d.cts.map +1 -1
  389. package/dist/router.d.ts +7 -1
  390. package/dist/router.d.ts.map +1 -1
  391. package/dist/router.js +24 -5
  392. package/dist/router.js.map +1 -1
  393. package/dist/search.cjs +13 -11
  394. package/dist/search.cjs.map +1 -1
  395. package/dist/search.js +12 -10
  396. package/dist/search.js.map +1 -1
  397. package/dist/server.cjs +293 -248
  398. package/dist/server.cjs.map +1 -1
  399. package/dist/server.d.cts.map +1 -1
  400. package/dist/server.d.ts.map +1 -1
  401. package/dist/server.js +294 -249
  402. package/dist/server.js.map +1 -1
  403. package/dist/speech.cjs +20 -18
  404. package/dist/speech.cjs.map +1 -1
  405. package/dist/speech.d.cts.map +1 -1
  406. package/dist/speech.d.ts.map +1 -1
  407. package/dist/speech.js +19 -17
  408. package/dist/speech.js.map +1 -1
  409. package/dist/sse-writer.cjs +56 -30
  410. package/dist/sse-writer.cjs.map +1 -1
  411. package/dist/sse-writer.d.cts +0 -1
  412. package/dist/sse-writer.d.cts.map +1 -1
  413. package/dist/sse-writer.d.ts +0 -1
  414. package/dist/sse-writer.d.ts.map +1 -1
  415. package/dist/sse-writer.js +55 -31
  416. package/dist/sse-writer.js.map +1 -1
  417. package/dist/stream-collapse.cjs +118 -11
  418. package/dist/stream-collapse.cjs.map +1 -1
  419. package/dist/stream-collapse.d.cts +10 -9
  420. package/dist/stream-collapse.d.cts.map +1 -1
  421. package/dist/stream-collapse.d.ts +10 -9
  422. package/dist/stream-collapse.d.ts.map +1 -1
  423. package/dist/stream-collapse.js +118 -11
  424. package/dist/stream-collapse.js.map +1 -1
  425. package/dist/transcription.cjs +31 -43
  426. package/dist/transcription.cjs.map +1 -1
  427. package/dist/transcription.d.cts.map +1 -1
  428. package/dist/transcription.d.ts.map +1 -1
  429. package/dist/transcription.js +31 -43
  430. package/dist/transcription.js.map +1 -1
  431. package/dist/types.cjs.map +1 -1
  432. package/dist/types.d.cts +231 -9
  433. package/dist/types.d.cts.map +1 -1
  434. package/dist/types.d.ts +231 -9
  435. package/dist/types.d.ts.map +1 -1
  436. package/dist/types.js.map +1 -1
  437. package/dist/vector-mock.cjs +3 -8
  438. package/dist/vector-mock.cjs.map +1 -1
  439. package/dist/vector-mock.d.cts.map +1 -1
  440. package/dist/vector-mock.d.ts.map +1 -1
  441. package/dist/vector-mock.js +3 -8
  442. package/dist/vector-mock.js.map +1 -1
  443. package/dist/vector-stores.cjs +2 -4
  444. package/dist/vector-stores.cjs.map +1 -1
  445. package/dist/vector-stores.d.cts.map +1 -1
  446. package/dist/vector-stores.d.ts.map +1 -1
  447. package/dist/vector-stores.js +2 -4
  448. package/dist/vector-stores.js.map +1 -1
  449. package/dist/veo-video.cjs +16 -14
  450. package/dist/veo-video.cjs.map +1 -1
  451. package/dist/veo-video.js +10 -8
  452. package/dist/veo-video.js.map +1 -1
  453. package/dist/video.cjs +21 -19
  454. package/dist/video.cjs.map +1 -1
  455. package/dist/video.d.cts.map +1 -1
  456. package/dist/video.d.ts.map +1 -1
  457. package/dist/video.js +20 -18
  458. package/dist/video.js.map +1 -1
  459. package/dist/ws-framing.cjs +12 -6
  460. package/dist/ws-framing.cjs.map +1 -1
  461. package/dist/ws-framing.d.cts +2 -0
  462. package/dist/ws-framing.d.cts.map +1 -1
  463. package/dist/ws-framing.d.ts +2 -0
  464. package/dist/ws-framing.d.ts.map +1 -1
  465. package/dist/ws-framing.js +12 -6
  466. package/dist/ws-framing.js.map +1 -1
  467. package/dist/ws-gemini-live.cjs +131 -96
  468. package/dist/ws-gemini-live.cjs.map +1 -1
  469. package/dist/ws-gemini-live.d.cts +0 -1
  470. package/dist/ws-gemini-live.d.cts.map +1 -1
  471. package/dist/ws-gemini-live.d.ts +0 -1
  472. package/dist/ws-gemini-live.d.ts.map +1 -1
  473. package/dist/ws-gemini-live.js +130 -95
  474. package/dist/ws-gemini-live.js.map +1 -1
  475. package/dist/ws-live.cjs +6 -5
  476. package/dist/ws-live.cjs.map +1 -1
  477. package/dist/ws-live.js +5 -4
  478. package/dist/ws-live.js.map +1 -1
  479. package/dist/ws-realtime.cjs +108 -124
  480. package/dist/ws-realtime.cjs.map +1 -1
  481. package/dist/ws-realtime.d.cts.map +1 -1
  482. package/dist/ws-realtime.d.ts.map +1 -1
  483. package/dist/ws-realtime.js +105 -121
  484. package/dist/ws-realtime.js.map +1 -1
  485. package/dist/ws-responses.cjs +80 -59
  486. package/dist/ws-responses.cjs.map +1 -1
  487. package/dist/ws-responses.d.cts.map +1 -1
  488. package/dist/ws-responses.d.ts.map +1 -1
  489. package/dist/ws-responses.js +79 -58
  490. package/dist/ws-responses.js.map +1 -1
  491. package/package.json +4 -1
  492. package/skills/write-fixtures/SKILL.md +57 -16
@@ -1 +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, req.headers) },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiKA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;AAoBxB,MAAM,+BAA+B;;;;;;;;;;;;;;;;;AAkBrC,SAAS,qBACP,KACA,KACA,KACA,MACM;AACN,oBAAmB,KAAK,KAAK,KAAK,UAAU,EAAE,QAAQ,CAAC;EAAE;EAAK;EAAK;EAAM,CAAC,EAAE,CAAC,CAAC;;;;;;;;;;;;;;;;AAiBhF,MAAM,mCAAmB,IAAI,KAAsC;AAEnE,SAAgB,wBAA8B;AAC5C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js","names":[],"sources":["../src/elevenlabs-voice.ts"],"sourcesContent":["import { renderError } from \"./response/errors.js\";\nimport { resolveRequestDecisions, strictOverrideField } from \"./response/policy.js\";\nimport 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 flattenHeaders,\n getContext,\n getTestId,\n resolveResponse,\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(\n !resolveRequestDecisions(defaults.strict, headers).upstream,\n defaults.record,\n \"elevenlabs\",\n )\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 renderError(\"openai\", \"validation\", {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n }).body,\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 renderError(\"openai\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\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 = resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss;\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n writeErrorResponse(\n res,\n 503,\n renderError(\"openai\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n }).body,\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 renderError(\"openai\", \"fixture-miss\", {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n }).body,\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 renderError(\"openai\", \"validation\", {\n message: \"Missing required parameter: 'voice_description'\",\n type: \"invalid_request_error\",\n }).body,\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, renderError(\"openai\", \"fixture\", response.error).body, {\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 renderError(\"openai\", \"unknown-response\", {\n message: \"Fixture response is not a JSON type for voice design\",\n type: \"server_error\",\n }).body,\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 renderError(\"openai\", \"validation\", {\n message: `Missing required parameter: '${missing}'`,\n type: \"invalid_request_error\",\n }).body,\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, renderError(\"openai\", \"fixture\", response.error).body, {\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 renderError(\"openai\", \"unknown-response\", {\n message: \"Fixture response is not a JSON type for voice create\",\n type: \"server_error\",\n }).body,\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 renderError(\"openai\", \"strict-miss\", {\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 }).body,\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, renderError(\"openai\", \"fixture\", response.error).body, {\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 renderError(\"openai\", \"unknown-response\", {\n message: `Fixture response is not a JSON type for ${routeLabel}`,\n type: \"server_error\",\n }).body,\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 (resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {\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 renderError(\"openai\", \"fixture-miss\", {\n message: `Voice '${voiceId}' not found`,\n type: \"invalid_request_error\",\n code: \"voice_not_found\",\n }).body,\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 (resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {\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, req.headers) },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgKA,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;AAoBxB,MAAM,+BAA+B;;;;;;;;;;;;;;;;;AAkBrC,SAAS,qBACP,KACA,KACA,KACA,MACM;AACN,oBAAmB,KAAK,KAAK,KAAK,UAAU,EAAE,QAAQ,CAAC;EAAE;EAAK;EAAK;EAAM,CAAC,EAAE,CAAC,CAAC;;;;;;;;;;;;;;;;AAiBhF,MAAM,mCAAmB,IAAI,KAAsC;AAEnE,SAAgB,wBAA8B;AAC5C,kBAAiB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmC1B,SAAgB,wBAAwB,OAAgC,QAA0B;CAChG,MAAM,UAAU,OAAO,MAAM,aAAa,WAAW,MAAM,WAAW;AACtE,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI,iBAAiB,IAAI,QAAQ,CAC/B,SAAQ,KACN,qBAAqB,QAAQ,sHAC9B;AAEH,kBAAiB,IAAI,SAAS,MAAM;AACpC,KAAI,iBAAiB,OAAO,iBAAiB;EAC3C,MAAM,SAAS,iBAAiB,OAAO;EACvC,MAAM,OAAO,iBAAiB,MAAM;AACpC,OAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK;GAC/B,MAAM,OAAO,KAAK,MAAM;AACxB,OAAI,CAAC,KAAK,KAAM,kBAAiB,OAAO,KAAK,MAAM;;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eAAe,IAAI,QAAQ;GACpC,SAAS;GACT,MAAM;GACN,UAAU;IACR,QAAQ;IACR,SAAS;IACT,GAAG,oBAAoB,SAAS,QAAQ,IAAI,QAAQ;IACrD;GACF,CAAC;AACF;;AAIF,KAAI,wBAAwB,SAAS,QAAQ,IAAI,QAAQ,CAAC,aAAa;AACrE,8BACE,KACA,KACA,cACA,UACA,SACA,MACA,QACA,SACA,wBACD;AACD;;AAGF,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"}
@@ -0,0 +1,16 @@
1
+
2
+ //#region src/embedding-request.ts
3
+ const embeddingRequests = /* @__PURE__ */ new WeakMap();
4
+ /** Keep exact embedding wire inputs off the canonical request seen by predicates and journals. */
5
+ function setEmbeddingRequest(request, embeddingRequest) {
6
+ embeddingRequests.set(request, embeddingRequest);
7
+ }
8
+ /** Read the original embedding wire identity for matching and recording, independent of transforms. */
9
+ function getEmbeddingRequest(request) {
10
+ return embeddingRequests.get(request);
11
+ }
12
+
13
+ //#endregion
14
+ exports.getEmbeddingRequest = getEmbeddingRequest;
15
+ exports.setEmbeddingRequest = setEmbeddingRequest;
16
+ //# sourceMappingURL=embedding-request.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedding-request.cjs","names":[],"sources":["../src/embedding-request.ts"],"sourcesContent":["import type { ChatCompletionRequest, FixtureMatch } from \"./types.js\";\n\nconst embeddingRequests = new WeakMap<\n ChatCompletionRequest,\n NonNullable<FixtureMatch[\"embeddingRequest\"]>\n>();\n\n/** Keep exact embedding wire inputs off the canonical request seen by predicates and journals. */\nexport function setEmbeddingRequest(\n request: ChatCompletionRequest,\n embeddingRequest: NonNullable<FixtureMatch[\"embeddingRequest\"]>,\n): void {\n embeddingRequests.set(request, embeddingRequest);\n}\n\n/** Read the original embedding wire identity for matching and recording, independent of transforms. */\nexport function getEmbeddingRequest(\n request: ChatCompletionRequest,\n): NonNullable<FixtureMatch[\"embeddingRequest\"]> | undefined {\n return embeddingRequests.get(request);\n}\n"],"mappings":";;AAEA,MAAM,oCAAoB,IAAI,SAG3B;;AAGH,SAAgB,oBACd,SACA,kBACM;AACN,mBAAkB,IAAI,SAAS,iBAAiB;;;AAIlD,SAAgB,oBACd,SAC2D;AAC3D,QAAO,kBAAkB,IAAI,QAAQ"}
@@ -0,0 +1,14 @@
1
+ //#region src/embedding-request.ts
2
+ const embeddingRequests = /* @__PURE__ */ new WeakMap();
3
+ /** Keep exact embedding wire inputs off the canonical request seen by predicates and journals. */
4
+ function setEmbeddingRequest(request, embeddingRequest) {
5
+ embeddingRequests.set(request, embeddingRequest);
6
+ }
7
+ /** Read the original embedding wire identity for matching and recording, independent of transforms. */
8
+ function getEmbeddingRequest(request) {
9
+ return embeddingRequests.get(request);
10
+ }
11
+
12
+ //#endregion
13
+ export { getEmbeddingRequest, setEmbeddingRequest };
14
+ //# sourceMappingURL=embedding-request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedding-request.js","names":[],"sources":["../src/embedding-request.ts"],"sourcesContent":["import type { ChatCompletionRequest, FixtureMatch } from \"./types.js\";\n\nconst embeddingRequests = new WeakMap<\n ChatCompletionRequest,\n NonNullable<FixtureMatch[\"embeddingRequest\"]>\n>();\n\n/** Keep exact embedding wire inputs off the canonical request seen by predicates and journals. */\nexport function setEmbeddingRequest(\n request: ChatCompletionRequest,\n embeddingRequest: NonNullable<FixtureMatch[\"embeddingRequest\"]>,\n): void {\n embeddingRequests.set(request, embeddingRequest);\n}\n\n/** Read the original embedding wire identity for matching and recording, independent of transforms. */\nexport function getEmbeddingRequest(\n request: ChatCompletionRequest,\n): NonNullable<FixtureMatch[\"embeddingRequest\"]> | undefined {\n return embeddingRequests.get(request);\n}\n"],"mappings":";AAEA,MAAM,oCAAoB,IAAI,SAG3B;;AAGH,SAAgB,oBACd,SACA,kBACM;AACN,mBAAkB,IAAI,SAAS,iBAAiB;;;AAIlD,SAAgB,oBACd,SAC2D;AAC3D,QAAO,kBAAkB,IAAI,QAAQ"}
@@ -1,7 +1,10 @@
1
+ const require_errors = require('./response/errors.cjs');
2
+ const require_policy = require('./response/policy.cjs');
1
3
  const require_helpers = require('./helpers.cjs');
2
4
  const require_sse_writer = require('./sse-writer.cjs');
3
5
  const require_chaos = require('./chaos.cjs');
4
6
  const require_fixture_loader = require('./fixture-loader.cjs');
7
+ const require_embedding_request = require('./embedding-request.cjs');
5
8
  const require_router = require('./router.cjs');
6
9
  const require_recorder = require('./recorder.cjs');
7
10
 
@@ -24,11 +27,11 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
24
27
  fixture: null
25
28
  }
26
29
  });
27
- require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
30
+ require_sse_writer.writeErrorResponse(res, 400, require_errors.renderError("openai", "validation", {
28
31
  message: `Malformed JSON body: ${detail}`,
29
32
  type: "invalid_request_error",
30
33
  code: "invalid_json"
31
- } }));
34
+ }).body);
32
35
  return;
33
36
  }
34
37
  if (!require_helpers.isJsonObject(embeddingReq)) {
@@ -42,10 +45,10 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
42
45
  fixture: null
43
46
  }
44
47
  });
45
- require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
48
+ require_sse_writer.writeErrorResponse(res, 400, require_errors.renderError("openai", "validation", {
46
49
  message: "Request body must be a JSON object",
47
50
  type: "invalid_request_error"
48
- } }));
51
+ }).body);
49
52
  return;
50
53
  }
51
54
  if (embeddingReq.input === void 0 || embeddingReq.input === null) {
@@ -59,10 +62,10 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
59
62
  fixture: null
60
63
  }
61
64
  });
62
- require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
65
+ require_sse_writer.writeErrorResponse(res, 400, require_errors.renderError("openai", "validation", {
63
66
  message: "Missing required parameter: 'input'",
64
67
  type: "invalid_request_error"
65
- } }));
68
+ }).body);
66
69
  return;
67
70
  }
68
71
  if (requireModel && embeddingReq.model === void 0) {
@@ -76,10 +79,10 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
76
79
  fixture: null
77
80
  }
78
81
  });
79
- require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
82
+ require_sse_writer.writeErrorResponse(res, 400, require_errors.renderError("openai", "validation", {
80
83
  message: "Missing required parameter: 'model'",
81
84
  type: "invalid_request_error"
82
- } }));
85
+ }).body);
83
86
  return;
84
87
  }
85
88
  const inputs = require_helpers.normalizeEmbeddingInput(embeddingReq.input);
@@ -94,12 +97,13 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
94
97
  fixture: null
95
98
  }
96
99
  });
97
- require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
100
+ require_sse_writer.writeErrorResponse(res, 400, require_errors.renderError("openai", "validation", {
98
101
  message: "Invalid parameter: 'input' must be a string, an array of strings, or an array of tokens",
99
102
  type: "invalid_request_error",
100
103
  param: null,
101
- code: null
102
- } }));
104
+ code: null,
105
+ includeParam: true
106
+ }).body);
103
107
  return;
104
108
  }
105
109
  const combinedInput = inputs.join(" ");
@@ -110,6 +114,11 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
110
114
  _endpointType: "embedding",
111
115
  _context: require_helpers.getContext(req)
112
116
  };
117
+ require_embedding_request.setEmbeddingRequest(syntheticReq, {
118
+ operation: "/v1/embeddings",
119
+ input: embeddingReq.input,
120
+ ...embeddingReq.dimensions !== void 0 && { dimensions: embeddingReq.dimensions }
121
+ });
113
122
  const testId = require_helpers.getTestId(req);
114
123
  const { fixture, skippedBySequenceOrTurn } = require_router.selectFixtureForServing(fixtures, syntheticReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
115
124
  if (fixture) {
@@ -168,13 +177,13 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
168
177
  fixture
169
178
  }
170
179
  });
171
- require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
180
+ require_sse_writer.writeErrorResponse(res, 500, require_errors.renderError("openai", "unknown-response", {
172
181
  message: "Fixture response did not match any known embedding type (must have embedding or error)",
173
182
  type: "server_error"
174
- } }));
183
+ }).body);
175
184
  return;
176
185
  }
177
- if (require_helpers.resolveStrictMode(defaults.strict, req.headers)) {
186
+ if (require_policy.resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {
178
187
  const strictMessage = require_helpers.strictNoMatchMessage(skippedBySequenceOrTurn);
179
188
  logger.error(require_helpers.strictNoMatchLogLine(req.method ?? "POST", req.url ?? "/v1/embeddings", skippedBySequenceOrTurn));
180
189
  journal.add({
@@ -185,14 +194,14 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
185
194
  response: {
186
195
  status: 503,
187
196
  fixture: null,
188
- ...require_helpers.strictOverrideField(defaults.strict, req.headers)
197
+ ...require_policy.strictOverrideField(defaults.strict, req.headers)
189
198
  }
190
199
  });
191
- require_sse_writer.writeErrorResponse(res, 503, JSON.stringify({ error: {
200
+ require_sse_writer.writeErrorResponse(res, 503, require_errors.renderError("openai", "strict-miss", {
192
201
  message: strictMessage,
193
202
  type: "invalid_request_error",
194
203
  code: "no_fixture_match"
195
- } }));
204
+ }).body);
196
205
  return;
197
206
  }
198
207
  if (defaults.record) {
@@ -226,12 +235,13 @@ async function handleEmbeddings(req, res, raw, fixtures, journal, defaults, setC
226
235
  fixture: null
227
236
  }
228
237
  });
229
- require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
238
+ require_sse_writer.writeErrorResponse(res, 400, require_errors.renderError("openai", "validation", {
230
239
  message: `Invalid parameter: 'dimensions' must be an integer between 1 and ${require_helpers.MAX_EMBEDDING_DIMENSIONS}`,
231
240
  type: "invalid_request_error",
232
241
  param: null,
233
- code: null
234
- } }));
242
+ code: null,
243
+ includeParam: true
244
+ }).body);
235
245
  return;
236
246
  }
237
247
  const embeddings = inputs.map((input) => require_helpers.generateDeterministicEmbedding(input, dimensions));