Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tts.test.ts

811 lines25.6 KB

1import { describe, expect, it, vi } from 'vitest'
2import { generateSpeech } from '@tanstack/ai'
3import {
4 BYTEPLUS_TTS_MAX_OUTPUT_SECONDS,
5 BYTEPLUS_TTS_MAX_REFERENCES,
6 BytePlusTTSAdapter,
7 createBytePlusSpeech,
8 toDurationSeconds,
9 toSpeechRate,
10} from '../src/adapters/tts'
11import type { Logger } from '@tanstack/ai'
12import type { BytePlusTTSResult } from '../src/audio/tts-provider-options'
13​
14const BASE_URL = 'https://voice.test'
15​
16/**
17 * Captures what the adapter routes through `logger.warn`. Passed as
18 * `debug: { logger }`, which turns every category on — including the `errors`
19 * category that gates `warn`.
20 */
21function captureLogger(): Logger & { warnings: Array<string> } {
22 const warnings: Array<string> = []
23 return {
24 warnings,
25 debug: () => {},
26 info: () => {},
27 warn: (message: string) => {
28 warnings.push(message)
29 },
30 error: () => {},
31 }
33​
34function jsonResponse(body: unknown, status = 200): Response {
35 return new Response(JSON.stringify(body), {
36 status,
37 headers: { 'Content-Type': 'application/json' },
38 })
40​
41// A fresh `Response` per call — a `Response` body can only be read once, so a
42// shared instance breaks any test that fetches twice.
43function ttsFetch(
44 body: unknown = { audio: 'QUJD', duration: 1.5 },
45 status = 200,
46) {
47 return vi
48 .fn<typeof fetch>()
49 .mockImplementation(() => Promise.resolve(jsonResponse(body, status)))
51​
52function adapterWith(
53 fetchImpl: typeof fetch,
54 defaultHeaders?: Record<string, string>,
55) {
56 return new BytePlusTTSAdapter('seed-audio-1.0', {
57 apiKey: 'voice-key',
58 baseURL: BASE_URL,
59 fetch: fetchImpl,
60 ...(defaultHeaders && { defaultHeaders }),
61 })
63​
64function lastRequest(fetchMock: ReturnType<typeof ttsFetch>) {
65 const call = fetchMock.mock.calls.at(-1)
66 if (!call) throw new Error('fetch was not called')
67 const [url, init] = call
68 return {
69 url: String(url),
70 init: init as RequestInit,
71 headers: new Headers(init?.headers),
72 body: JSON.parse(String(init?.body)),
73 }
75​
76describe('BytePlusTTSAdapter', () => {
77 it('posts to /api/v3/tts/create with the Seed Speech key and default speaker', async () => {
78 const fetchMock = ttsFetch()
79 const result: BytePlusTTSResult = await generateSpeech({
80 threadId: 'thread-1',
81 adapter: adapterWith(fetchMock),
82 text: 'welcome to the guitar store',
83 })
84​
85 const { url, init, headers, body } = lastRequest(fetchMock)
86 expect(url).toBe(`${BASE_URL}/api/v3/tts/create`)
87 expect(init.method).toBe('POST')
88 expect(headers.get('x-api-key')).toBe('voice-key')
89 expect(headers.get('content-type')).toBe('application/json')
90 // Seed Speech uses X-Api-Key, never an Ark-style bearer token.
91 expect(headers.get('authorization')).toBeNull()
92​
93 // `text_prompt` (not `text`) and the voice inside `references` are both
94 // load-bearing: a top-level `speaker` is silently ignored by the server,
95 // and `text` belongs to the /tts/unidirectional endpoint.
96 expect(body).toEqual({
97 model: 'seed-audio-1.0',
98 text_prompt: 'welcome to the guitar store',
99 references: [{ speaker: 'en_female_stokie_uranus_bigtts' }],
100 audio_config: { format: 'mp3', sample_rate: 24000 },
101 })
102 expect(body.speaker).toBeUndefined()
103​
104 expect(result.model).toBe('seed-audio-1.0')
105 expect(result.audio).toBe('QUJD')
106 expect(result.format).toBe('mp3')
107 expect(result.contentType).toBe('audio/mpeg')
108 expect(result.duration).toBe(1.5)
109 expect(result.id).toMatch(/^byteplus-/)
110 })
111​
112 it('sends a per-request X-Api-Request-Id', async () => {
113 const fetchMock = ttsFetch()
114 await generateSpeech({
115 threadId: 'thread-1',
116 adapter: adapterWith(fetchMock),
117 text: 'hi',
118 })
119 const first = lastRequest(fetchMock).headers.get('x-api-request-id')
120 expect(first).toBeTruthy()
121​
122 await generateSpeech({
123 threadId: 'thread-1',
124 adapter: adapterWith(fetchMock),
125 text: 'hi',
126 })
127 expect(lastRequest(fetchMock).headers.get('x-api-request-id')).not.toBe(
128 first,
129 )
130 })
131​
132 it('sends TTSOptions.voice as speaker and lets modelOptions.speaker win', async () => {
133 // Deliberately synthetic ids — the adapter passes `speaker` through
134 // verbatim, and inventing plausible-looking BytePlus voice ids in a test
135 // is how they end up copied into docs as if they were real.
136 const fetchMock = ttsFetch()
137 await generateSpeech({
138 threadId: 'thread-1',
139 adapter: adapterWith(fetchMock),
140 text: 'hi',
141 voice: 'test-voice-from-options',
142 })
143 expect(lastRequest(fetchMock).body.references).toEqual([
144 { speaker: 'test-voice-from-options' },
145 ])
146​
147 await generateSpeech({
148 threadId: 'thread-1',
149 adapter: adapterWith(fetchMock),
150 text: 'hi',
151 voice: 'test-voice-from-options',
152 modelOptions: { speaker: 'test-voice-from-model-options' },
153 })
154 expect(lastRequest(fetchMock).body.references).toEqual([
155 { speaker: 'test-voice-from-model-options' },
156 ])
157 })
158​
159 it('lets an explicit references array replace the speaker entry', async () => {
160 const fetchMock = ttsFetch()
161 await generateSpeech({
162 threadId: 'thread-1',
163 adapter: adapterWith(fetchMock),
164 text: 'say it like @Audio1',
165 voice: 'test-voice-from-options',
166 modelOptions: {
167 references: [{ audio_url: 'https://example.com/clip.wav' }],
168 },
169 })
170 expect(lastRequest(fetchMock).body.references).toEqual([
171 { audio_url: 'https://example.com/clip.wav' },
172 ])
173 })
174​
175 // The endpoint takes an object here, not the boolean the field looked like.
176 describe('watermark', () => {
177 it('normalizes `true` to the audible marker', async () => {
178 const fetchMock = ttsFetch()
179 await generateSpeech({
180 threadId: 'thread-1',
181 adapter: adapterWith(fetchMock),
182 text: 'hi',
183 modelOptions: { watermark: true },
184 })
185 expect(lastRequest(fetchMock).body.watermark).toEqual({
186 aigc_watermark: true,
187 })
188 })
189​
190 it('normalizes `false` to the audible marker off', async () => {
191 const fetchMock = ttsFetch()
192 await generateSpeech({
193 threadId: 'thread-1',
194 adapter: adapterWith(fetchMock),
195 text: 'hi',
196 modelOptions: { watermark: false },
197 })
198 expect(lastRequest(fetchMock).body.watermark).toEqual({
199 aigc_watermark: false,
200 })
201 })
202​
203 it('forwards an explicit config unchanged', async () => {
204 const fetchMock = ttsFetch()
205 await generateSpeech({
206 threadId: 'thread-1',
207 adapter: adapterWith(fetchMock),
208 text: 'hi',
209 modelOptions: {
210 watermark: {
211 aigc_metadata: { enable: true, content_producer: 'guitar-store' },
212 },
213 },
214 })
215 expect(lastRequest(fetchMock).body.watermark).toEqual({
216 aigc_metadata: { enable: true, content_producer: 'guitar-store' },
217 })
218 })
219​
220 it('omits watermark when unset', async () => {
221 const fetchMock = ttsFetch()
222 await generateSpeech({
223 threadId: 'thread-1',
224 adapter: adapterWith(fetchMock),
225 text: 'hi',
226 })
227 expect(lastRequest(fetchMock).body).not.toHaveProperty('watermark')
228 })
229 })
230​
231 describe('format mapping', () => {
232 it.each([
233 ['mp3', 'mp3', 'audio/mpeg'],
234 ['wav', 'wav', 'audio/wav'],
235 ['pcm', 'pcm', 'audio/L16;rate=24000'],
236 ['opus', 'ogg_opus', 'audio/ogg;codecs=opus'],
237 ] as const)('maps %s to %s', async (requested, wireFormat, contentType) => {
238 const fetchMock = ttsFetch()
239 const result = await generateSpeech({
240 threadId: 'thread-1',
241 adapter: adapterWith(fetchMock),
242 text: 'hi',
243 format: requested,
244 })
245 expect(lastRequest(fetchMock).body.audio_config.format).toBe(wireFormat)
246 expect(result.format).toBe(wireFormat)
247 expect(result.contentType).toBe(contentType)
248 })
249​
250 it.each(['aac', 'flac'] as const)(
251 'falls back to mp3 for unsupported format %s and warns',
252 async (requested) => {
253 const fetchMock = ttsFetch()
254 const logger = captureLogger()
255 const result = await generateSpeech({
256 threadId: 'thread-1',
257 adapter: adapterWith(fetchMock),
258 text: 'hi',
259 format: requested,
260 debug: { logger },
261 })
262 expect(lastRequest(fetchMock).body.audio_config.format).toBe('mp3')
263 expect(result.format).toBe('mp3')
264 expect(
265 logger.warnings.some(
266 (w) => w.includes(requested) && w.includes('falling back to mp3'),
267 ),
268 ).toBe(true)
269 },
270 )
271​
272 it('lets modelOptions.format override the generic format', async () => {
273 const fetchMock = ttsFetch()
274 await generateSpeech({
275 threadId: 'thread-1',
276 adapter: adapterWith(fetchMock),
277 text: 'hi',
278 format: 'mp3',
279 modelOptions: { format: 'ogg_opus' },
280 })
281 expect(lastRequest(fetchMock).body.audio_config.format).toBe('ogg_opus')
282 })
283​
284 it('reports the caller sample rate in the pcm content type', async () => {
285 const fetchMock = ttsFetch()
286 const result = await generateSpeech({
287 threadId: 'thread-1',
288 adapter: adapterWith(fetchMock),
289 text: 'hi',
290 format: 'pcm',
291 modelOptions: { sample_rate: 48000 },
292 })
293 expect(lastRequest(fetchMock).body.audio_config.sample_rate).toBe(48000)
294 expect(result.contentType).toBe('audio/L16;rate=48000')
295 })
296​
297 it('always sends an explicit sample_rate rather than trusting the server default', async () => {
298 // The documented default (40000) is not a value the endpoint accepts,
299 // so omitting the field is never safe.
300 const fetchMock = ttsFetch()
301 await generateSpeech({
302 threadId: 'thread-1',
303 adapter: adapterWith(fetchMock),
304 text: 'hi',
305 })
306 expect(lastRequest(fetchMock).body.audio_config.sample_rate).toBe(24000)
307 })
308 })
309​
310 describe('speed → speech_rate', () => {
311 it.each([
312 [0.25, -50],
313 [0.5, -50],
314 [0.75, -25],
315 [1, 0],
316 [1.5, 50],
317 [2, 100],
318 [4, 100],
319 ])('maps speed %s to speech_rate %s', (speed, expected) => {
320 expect(toSpeechRate(speed)).toBe(expected)
321 })
322​
323 it('forwards the derived speech_rate on the request', async () => {
324 const fetchMock = ttsFetch()
325 await generateSpeech({
326 threadId: 'thread-1',
327 adapter: adapterWith(fetchMock),
328 text: 'hi',
329 speed: 1.25,
330 })
331 expect(lastRequest(fetchMock).body.audio_config.speech_rate).toBe(25)
332 })
333​
334 it('omits speech_rate when no speed is given', async () => {
335 const fetchMock = ttsFetch()
336 await generateSpeech({
337 threadId: 'thread-1',
338 adapter: adapterWith(fetchMock),
339 text: 'hi',
340 })
341 expect(
342 lastRequest(fetchMock).body.audio_config.speech_rate,
343 ).toBeUndefined()
344 })
345​
346 it('warns when the speed clamps outside the documented 0.5×–2× range', async () => {
347 const logger = captureLogger()
348 await generateSpeech({
349 threadId: 'thread-1',
350 adapter: adapterWith(ttsFetch()),
351 text: 'hi',
352 speed: 4,
353 debug: { logger },
354 })
355 expect(
356 logger.warnings.some(
357 (w) => w.includes('4×') && w.includes('clamping speech_rate'),
358 ),
359 ).toBe(true)
360 })
361​
362 it('does not warn for a speed inside the documented range', async () => {
363 const logger = captureLogger()
364 await generateSpeech({
365 threadId: 'thread-1',
366 adapter: adapterWith(ttsFetch()),
367 text: 'hi',
368 speed: 1.5,
369 debug: { logger },
370 })
371 expect(logger.warnings).toHaveLength(0)
372 })
373​
374 it('lets an explicit modelOptions.speech_rate win over speed', async () => {
375 const fetchMock = ttsFetch()
376 await generateSpeech({
377 threadId: 'thread-1',
378 adapter: adapterWith(fetchMock),
379 text: 'hi',
380 speed: 2,
381 modelOptions: { speech_rate: -10 },
382 })
383 expect(lastRequest(fetchMock).body.audio_config.speech_rate).toBe(-10)
384 })
385 })
386​
387 it('forwards pitch, loudness and subtitle options inside audio_config', async () => {
388 const subtitle = {
389 sentences: [{ text: 'hi', start_time: 0, end_time: 200 }],
390 words: [{ text: 'hi', start_time: 0, end_time: 200 }],
391 }
392 const fetchMock = ttsFetch({
393 audio: 'QUJD',
394 duration: 2,
395 original_duration: 2,
396 url: 'https://voice.test/out.mp3',
397 subtitle,
398 })
399 const result: BytePlusTTSResult = await generateSpeech({
400 threadId: 'thread-1',
401 adapter: adapterWith(fetchMock),
402 text: 'hi',
403 modelOptions: {
404 pitch_rate: -3,
405 loudness_rate: 20,
406 enable_subtitle: true,
407 },
408 })
409​
410 const { body } = lastRequest(fetchMock)
411 expect(body.audio_config.pitch_rate).toBe(-3)
412 expect(body.audio_config.loudness_rate).toBe(20)
413 // enable_subtitle is the sixth member of audio_config, not a top-level
414 // field — at the top level the server ignores it.
415 expect(body.audio_config.enable_subtitle).toBe(true)
416 expect(body.enable_subtitle).toBeUndefined()
417​
418 // Subtitle timings stay in milliseconds while the durations are seconds.
419 expect(result.subtitle).toEqual(subtitle)
420 expect(result.url).toBe('https://voice.test/out.mp3')
421 })
422​
423 describe('durations', () => {
424 it('reports duration and original_duration as seconds', async () => {
425 const fetchMock = ttsFetch({
426 audio: 'QUJD',
427 duration: 12.5,
428 original_duration: 10,
429 })
430 const result: BytePlusTTSResult = await generateSpeech({
431 threadId: 'thread-1',
432 adapter: adapterWith(fetchMock),
433 text: 'hi',
434 })
435 expect(result.duration).toBe(12.5)
436 expect(result.originalDuration).toBe(10)
437 })
438​
439 it('passes a slowed clip longer than the 120s cap straight through', async () => {
440 // A 120s (billed) clip at speech_rate -50 plays for 240s. Rescaling it
441 // as if it were milliseconds — which an earlier heuristic did — would
442 // corrupt it to 0.24s.
443 const fetchMock = ttsFetch({
444 audio: 'QUJD',
445 duration: BYTEPLUS_TTS_MAX_OUTPUT_SECONDS * 2,
446 original_duration: BYTEPLUS_TTS_MAX_OUTPUT_SECONDS,
447 })
448 const result: BytePlusTTSResult = await generateSpeech({
449 threadId: 'thread-1',
450 adapter: adapterWith(fetchMock),
451 text: 'hi',
452 speed: 0.5,
453 })
454 expect(result.duration).toBe(240)
455 expect(result.originalDuration).toBe(BYTEPLUS_TTS_MAX_OUTPUT_SECONDS)
456 })
457​
458 it.each([
459 [12.5, 12.5],
460 [BYTEPLUS_TTS_MAX_OUTPUT_SECONDS + 1, 121],
461 [0, undefined],
462 [-5, undefined],
463 [Number.NaN, undefined],
464 [undefined, undefined],
465 ])('toDurationSeconds(%s) is %s', (raw, expected) => {
466 expect(toDurationSeconds(raw)).toBe(expected)
467 })
468​
469 it('coerces string durations and drops unusable ones', async () => {
470 const stringDuration = ttsFetch({ audio: 'QUJD', duration: '3.2' })
471 expect(
472 (
473 await generateSpeech({
474 threadId: 'thread-1',
475 adapter: adapterWith(stringDuration),
476 text: 'hi',
477 })
478 ).duration,
479 ).toBe(3.2)
480​
481 const missing = ttsFetch({ audio: 'QUJD' })
482 expect(
483 (
484 await generateSpeech({
485 threadId: 'thread-1',
486 adapter: adapterWith(missing),
487 text: 'hi',
488 })
489 ).duration,
490 ).toBeUndefined()
491 })
492 })
493​
494 describe('dialogue turns', () => {
495 it('maps turns to references and a role-structured text_prompt', async () => {
496 const fetchMock = ttsFetch()
497 await generateSpeech({
498 threadId: 'thread-1',
499 adapter: adapterWith(fetchMock),
500 turns: [
501 { text: 'Knock knock.', voice: 'test-voice-a' },
502 { text: 'Who is there?', voice: 'test-voice-b' },
503 { text: 'Seed.', voice: 'test-voice-a' },
504 ],
505 })
506​
507 const { body } = lastRequest(fetchMock)
508 // One reference per distinct voice, in first-appearance order, and each
509 // line cites its voice by that 1-based position.
510 expect(body.references).toEqual([
511 { speaker: 'test-voice-a' },
512 { speaker: 'test-voice-b' },
513 ])
514 expect(body.text_prompt).toBe(
515 '@Audio1: Knock knock.\n@Audio2: Who is there?\n@Audio1: Seed.',
516 )
517 })
518​
519 it('rejects more distinct voices than references allows', async () => {
520 const fetchMock = ttsFetch()
521 await expect(
522 generateSpeech({
523 threadId: 'thread-1',
524 adapter: adapterWith(fetchMock),
525 turns: [
526 { text: 'a', voice: 'v1' },
527 { text: 'b', voice: 'v2' },
528 { text: 'c', voice: 'v3' },
529 { text: 'd', voice: 'v4' },
530 ],
531 }),
532 ).rejects.toThrow(
533 `byteplus accepts at most ${BYTEPLUS_TTS_MAX_REFERENCES} distinct voices per request; received 4.`,
534 )
535 expect(fetchMock).not.toHaveBeenCalled()
536 })
537​
538 it('lets modelOptions.references override the turn-derived ones', async () => {
539 const fetchMock = ttsFetch()
540 await generateSpeech({
541 threadId: 'thread-1',
542 adapter: adapterWith(fetchMock),
543 turns: [{ text: 'hi', voice: 'test-voice-a' }],
544 modelOptions: { references: [{ audio_url: 'https://example.test/a' }] },
545 })
546​
547 const { body } = lastRequest(fetchMock)
548 expect(body.references).toEqual([{ audio_url: 'https://example.test/a' }])
549 // The prompt still carries the markers — they address references
550 // positionally, so a caller-supplied array lines up with them.
551 expect(body.text_prompt).toBe('@Audio1: hi')
552 })
553 })
554​
555 describe('timestamps', () => {
556 const SUBTITLE = {
557 text: 'hi there',
558 sentences: [{ text: 'hi there', start_time: 0, end_time: 1200 }],
559 words: [
560 { text: 'hi', start_time: 0, end_time: 400 },
561 { text: 'there', start_time: 400, end_time: 1200 },
562 ],
563 }
564​
565 it('sets audio_config.enable_subtitle', async () => {
566 const fetchMock = ttsFetch()
567 await generateSpeech({
568 threadId: 'thread-1',
569 adapter: adapterWith(fetchMock),
570 text: 'hi there',
571 timestamps: true,
572 })
573 expect(lastRequest(fetchMock).body.audio_config.enable_subtitle).toBe(
574 true,
575 )
576 })
577​
578 it('is off unless asked for', async () => {
579 const fetchMock = ttsFetch()
580 await generateSpeech({
581 threadId: 'thread-1',
582 adapter: adapterWith(fetchMock),
583 text: 'hi',
584 })
585 expect(
586 lastRequest(fetchMock).body.audio_config.enable_subtitle,
587 ).toBeUndefined()
588 })
589​
590 it('lets an explicit modelOptions.enable_subtitle:false win', async () => {
591 const fetchMock = ttsFetch()
592 await generateSpeech({
593 threadId: 'thread-1',
594 adapter: adapterWith(fetchMock),
595 text: 'hi',
596 timestamps: true,
597 modelOptions: { enable_subtitle: false },
598 })
599 expect(lastRequest(fetchMock).body.audio_config.enable_subtitle).toBe(
600 false,
601 )
602 })
603​
604 it('maps words to alignment and sentences to segments, in seconds', async () => {
605 const fetchMock = ttsFetch({
606 audio: 'QUJD',
607 duration: 1.2,
608 subtitle: SUBTITLE,
609 })
610 const result: BytePlusTTSResult = await generateSpeech({
611 threadId: 'thread-1',
612 adapter: adapterWith(fetchMock),
613 text: 'hi there',
614 timestamps: true,
615 })
616​
617 // Subtitle times are milliseconds on a response whose `duration` is
618 // seconds — the adapter is the only place that conversion happens.
619 expect(result.alignment).toEqual({
620 unit: 'word',
621 texts: ['hi', 'there'],
622 startSeconds: [0, 0.4],
623 endSeconds: [0.4, 1.2],
624 })
625 expect(result.segments).toEqual([
626 { startSeconds: 0, endSeconds: 1.2, text: 'hi there' },
627 ])
628 // The raw block stays put for callers already reading it.
629 expect(result.subtitle).toEqual(SUBTITLE)
630 })
631​
632 it('drops subtitle entries that carry no timings', async () => {
633 const fetchMock = ttsFetch({
634 audio: 'QUJD',
635 subtitle: { words: [{ text: 'hi' }], sentences: [] },
636 })
637 const result: BytePlusTTSResult = await generateSpeech({
638 threadId: 'thread-1',
639 adapter: adapterWith(fetchMock),
640 text: 'hi',
641 timestamps: true,
642 })
643 expect(result.alignment).toBeUndefined()
644 expect(result.segments).toBeUndefined()
645 })
646​
647 it('returns no alignment when the response has no subtitle', async () => {
648 const fetchMock = ttsFetch()
649 const result: BytePlusTTSResult = await generateSpeech({
650 threadId: 'thread-1',
651 adapter: adapterWith(fetchMock),
652 text: 'hi',
653 timestamps: true,
654 })
655 expect(result.alignment).toBeUndefined()
656 expect(result.segments).toBeUndefined()
657 })
658 })
659​
660 describe('errors', () => {
661 it('surfaces the numeric Seed Speech error envelope on a 401', async () => {
662 const fetchMock = ttsFetch(
663 { code: 45000010, message: 'Invalid X-Api-Key' },
664 401,
665 )
666 await expect(
667 generateSpeech({
668 threadId: 'thread-1',
669 adapter: adapterWith(fetchMock),
670 text: 'hi',
671 debug: false,
672 }),
673 ).rejects.toThrow(
674 'BytePlus Seed Speech text-to-speech failed (401 45000010): Invalid X-Api-Key',
675 )
676 })
677​
678 it('rejects a 200 carrying a non-zero code even when audio is present', async () => {
679 const fetchMock = ttsFetch({
680 code: 45000010,
681 message: 'Invalid X-Api-Key',
682 audio: 'QUJD',
683 duration: 1.5,
684 })
685 await expect(
686 generateSpeech({
687 threadId: 'thread-1',
688 adapter: adapterWith(fetchMock),
689 text: 'hi',
690 debug: false,
691 }),
692 ).rejects.toThrow(
693 'BytePlus Seed Speech text-to-speech failed (200 45000010): Invalid X-Api-Key',
694 )
695 })
696​
697 it('accepts a 200 that reports code 0', async () => {
698 const fetchMock = ttsFetch({ code: 0, audio: 'QUJD', duration: 1.5 })
699 const result = await generateSpeech({
700 threadId: 'thread-1',
701 adapter: adapterWith(fetchMock),
702 text: 'hi',
703 })
704 expect(result.audio).toBe('QUJD')
705 })
706​
707 // Only the *error* envelope was verified live; the success envelope is
708 // docs-derived. A string-typed code must not slip through as success —
709 // `readStringField` already renders both forms in the error message, so
710 // requiring a number here would have returned a failed 200 as valid audio.
711 it('rejects a 200 whose non-zero code arrives as a string', async () => {
712 const fetchMock = ttsFetch({
713 code: '45000010',
714 message: 'Invalid X-Api-Key',
715 audio: 'QUJD',
716 duration: 1.5,
717 })
718 await expect(
719 generateSpeech({
720 threadId: 'thread-1',
721 adapter: adapterWith(fetchMock),
722 text: 'hi',
723 debug: false,
724 }),
725 ).rejects.toThrow(/45000010/)
726 })
727​
728 it('accepts a 200 whose success code arrives as the string "0"', async () => {
729 const fetchMock = ttsFetch({ code: '0', audio: 'QUJD', duration: 1.5 })
730 const result = await generateSpeech({
731 threadId: 'thread-1',
732 adapter: adapterWith(fetchMock),
733 text: 'hi',
734 })
735 expect(result.audio).toBe('QUJD')
736 })
737​
738 it('accepts a 200 that omits code entirely', async () => {
739 const fetchMock = ttsFetch({ audio: 'QUJD', duration: 1.5 })
740 const result = await generateSpeech({
741 threadId: 'thread-1',
742 adapter: adapterWith(fetchMock),
743 text: 'hi',
744 })
745 expect(result.audio).toBe('QUJD')
746 })
747​
748 // An empty string is a *well-formed* success envelope carrying nothing to
749 // play, so it needs its own message — reusing the envelope-error phrasing
750 // ("failed (200)") gives no hint that the adapter is the one rejecting it.
751 it('rejects a success envelope whose audio is an empty string', async () => {
752 const fetchMock = ttsFetch({ code: 0, audio: '', duration: 1.5 })
753 await expect(
754 generateSpeech({
755 threadId: 'thread-1',
756 adapter: adapterWith(fetchMock),
757 text: 'hi',
758 debug: false,
759 }),
760 ).rejects.toThrow(/success response with no audio/)
761 })
762​
763 it('fails when a 200 response carries no audio', async () => {
764 const fetchMock = ttsFetch({ code: 45000151, message: 'Quota exceeded' })
765 await expect(
766 generateSpeech({
767 threadId: 'thread-1',
768 adapter: adapterWith(fetchMock),
769 text: 'hi',
770 debug: false,
771 }),
772 ).rejects.toThrow(
773 'BytePlus Seed Speech text-to-speech failed (200 45000151): Quota exceeded',
774 )
775 })
776​
777 it('keeps non-JSON error bodies diagnosable', async () => {
778 const fetchMock = vi
779 .fn<typeof fetch>()
780 .mockResolvedValue(new Response('<html>502</html>', { status: 502 }))
781 await expect(
782 generateSpeech({
783 threadId: 'thread-1',
784 adapter: adapterWith(fetchMock),
785 text: 'hi',
786 debug: false,
787 }),
788 ).rejects.toThrow('<html>502</html>')
789 })
790 })
791​
792 it('merges configured default headers into the request', async () => {
793 const fetchMock = ttsFetch()
794 await generateSpeech({
795 threadId: 'thread-1',
796 adapter: adapterWith(fetchMock, { 'X-Test-Id': 'abc' }),
797 text: 'hi',
798 })
799 expect(lastRequest(fetchMock).headers.get('x-test-id')).toBe('abc')
800 })
801​
802 it('createBytePlusSpeech wires the explicit key through', async () => {
803 const fetchMock = ttsFetch()
804 const adapter = createBytePlusSpeech('seed-audio-1.0', 'explicit-key', {
805 baseURL: BASE_URL,
806 fetch: fetchMock,
807 })
808 await generateSpeech({ threadId: 'thread-1', adapter, text: 'hi' })
809 expect(lastRequest(fetchMock).headers.get('x-api-key')).toBe('explicit-key')
810 })
811})