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

tts.test.ts

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