Open History to see the last commit
1import { afterEach, describe, expect, it } from 'vitest'
2import {
3 BYTEPLUS_ARK_BASE_URL,
4 BYTEPLUS_VOICE_BASE_URL,
5 bytePlusArkError,
6 bytePlusArkHeaders,
7 bytePlusVoiceError,
8 bytePlusVoiceHeaders,
9 getBytePlusArkApiKeyFromEnv,
10 getBytePlusVoiceApiKeyFromEnv,
11 withBytePlusArkDefaults,
12 withBytePlusVoiceDefaults,
13} from '../src/index'
14import { readJsonBody, toHeaderRecord } from '../src/utils/client'
15
16const ENV_KEYS = [
17 'ARK_API_KEY',
18 'BYTEPLUS_API_KEY',
19 'BYTEPLUS_VOICE_API_KEY',
20] as const
21const originalEnv = new Map(ENV_KEYS.map((key) => [key, process.env[key]]))
22
23afterEach(() => {
24 for (const key of ENV_KEYS) {
25 const original = originalEnv.get(key)
26 if (original === undefined) {
27 delete process.env[key]
28 } else {
29 process.env[key] = original
30 }
31 }
32})
33
34describe('API key resolution', () => {
35 it('reads the Ark key from ARK_API_KEY', () => {
36 process.env.ARK_API_KEY = 'ark-test-key'
37 expect(getBytePlusArkApiKeyFromEnv()).toBe('ark-test-key')
38 })
39
40 it('falls back to BYTEPLUS_API_KEY when ARK_API_KEY is unset', () => {
41 delete process.env.ARK_API_KEY
42 process.env.BYTEPLUS_API_KEY = 'byteplus-test-key'
43 expect(getBytePlusArkApiKeyFromEnv()).toBe('byteplus-test-key')
44 })
45
46 it('prefers ARK_API_KEY over the BYTEPLUS_API_KEY fallback', () => {
47 process.env.ARK_API_KEY = 'ark-test-key'
48 process.env.BYTEPLUS_API_KEY = 'byteplus-test-key'
49 expect(getBytePlusArkApiKeyFromEnv()).toBe('ark-test-key')
50 })
51
52 it('names both variables when neither is set', () => {
53 delete process.env.ARK_API_KEY
54 delete process.env.BYTEPLUS_API_KEY
55 expect(() => getBytePlusArkApiKeyFromEnv()).toThrow(
56 /ARK_API_KEY or BYTEPLUS_API_KEY/,
57 )
58 })
59
60 it('reads the Seed Speech key from BYTEPLUS_VOICE_API_KEY', () => {
61 process.env.BYTEPLUS_VOICE_API_KEY = 'voice-test-key'
62 expect(getBytePlusVoiceApiKeyFromEnv()).toBe('voice-test-key')
63 })
64
65 it('points at the separate Seed Speech key when it is missing', () => {
66 delete process.env.BYTEPLUS_VOICE_API_KEY
67 expect(() => getBytePlusVoiceApiKeyFromEnv()).toThrow(
68 /BYTEPLUS_VOICE_API_KEY/,
69 )
70 })
71})
72
73describe('config defaults', () => {
74 it('applies the Ark base URL and preserves the injected fetch', () => {
75 const injectedFetch: typeof fetch = () => {
76 throw new Error('not called')
77 }
78 const config = withBytePlusArkDefaults({
79 apiKey: 'ark-test-key',
80 fetch: injectedFetch,
81 })
82 expect(config.baseURL).toBe(BYTEPLUS_ARK_BASE_URL)
83 expect(config.fetch).toBe(injectedFetch)
84 })
85
86 it('keeps an explicit Ark base URL (e.g. the EU host)', () => {
87 const config = withBytePlusArkDefaults({
88 apiKey: 'ark-test-key',
89 baseURL: 'https://ark.eu-west.bytepluses.com/api/v3',
90 })
91 expect(config.baseURL).toBe('https://ark.eu-west.bytepluses.com/api/v3')
92 })
93
94 it('trims trailing slashes from an explicit Ark base URL', () => {
95 const config = withBytePlusArkDefaults({
96 apiKey: 'ark-test-key',
97 baseURL: 'https://ark.eu-west.bytepluses.com/api/v3//',
98 })
99 expect(config.baseURL).toBe('https://ark.eu-west.bytepluses.com/api/v3')
100 })
101
102 it('resolves a base URL for a null or empty override', () => {
103 // openai's ClientOptions types baseURL as nullable, so adapters that
104 // interpolate it must never see undefined.
105 expect(
106 withBytePlusArkDefaults({ apiKey: 'ark-test-key', baseURL: null })
107 .baseURL,
108 ).toBe(BYTEPLUS_ARK_BASE_URL)
109 expect(
110 withBytePlusArkDefaults({ apiKey: 'ark-test-key', baseURL: '' }).baseURL,
111 ).toBe(BYTEPLUS_ARK_BASE_URL)
112 })
113
114 it('preserves adapter-specific config fields', () => {
115 const config = withBytePlusArkDefaults({
116 apiKey: 'ark-test-key',
117 maxRetries: 4,
118 })
119 expect(config.maxRetries).toBe(4)
120 })
121
122 it('applies the Seed Speech base URL', () => {
123 const config = withBytePlusVoiceDefaults({ apiKey: 'voice-test-key' })
124 expect(config.baseURL).toBe(BYTEPLUS_VOICE_BASE_URL)
125 })
126
127 it('trims trailing slashes from an explicit Seed Speech base URL', () => {
128 const config = withBytePlusVoiceDefaults({
129 apiKey: 'voice-test-key',
130 baseURL: 'https://voice.example.com//',
131 })
132 expect(config.baseURL).toBe('https://voice.example.com')
133 })
134})
135
136describe('headers', () => {
137 it('sends the Ark key as a bearer token', () => {
138 expect(bytePlusArkHeaders('ark-test-key')).toEqual({
139 'Content-Type': 'application/json',
140 Authorization: 'Bearer ark-test-key',
141 })
142 })
143
144 it('sends the Seed Speech key as X-Api-Key', () => {
145 expect(bytePlusVoiceHeaders('voice-test-key')).toEqual({
146 'Content-Type': 'application/json',
147 'X-Api-Key': 'voice-test-key',
148 })
149 })
150
151 it('merges extra headers alongside the auth headers', () => {
152 expect(
153 bytePlusArkHeaders('ark-test-key', { 'X-Test-Id': 'abc' }),
154 ).toMatchObject({ 'X-Test-Id': 'abc' })
155 })
156
157 it('does not let extra headers clobber the Ark bearer token', () => {
158 // A caller-supplied Authorization in defaultHeaders would otherwise turn
159 // every request into a 401 that reads like a bad API key.
160 expect(
161 bytePlusArkHeaders('ark-test-key', {
162 Authorization: 'Bearer wrong-key',
163 'Content-Type': 'text/plain',
164 }),
165 ).toEqual({
166 'Content-Type': 'application/json',
167 Authorization: 'Bearer ark-test-key',
168 })
169 })
170
171 it('does not let extra headers clobber X-Api-Key', () => {
172 expect(
173 bytePlusVoiceHeaders('voice-test-key', {
174 'X-Api-Key': 'wrong-key',
175 'Content-Type': 'text/plain',
176 'X-Test-Id': 'abc',
177 }),
178 ).toEqual({
179 'Content-Type': 'application/json',
180 'X-Api-Key': 'voice-test-key',
181 'X-Test-Id': 'abc',
182 })
183 })
184
185 // Header names are case-insensitive but object keys are not, so a
186 // differently-cased duplicate survives the spread and `fetch`'s Headers
187 // constructor *appends* it: `authorization: "Bearer wrong, Bearer right"`,
188 // which 401s and reads like a bad key. `toHeaderRecord` lowercases names for
189 // the `Headers` form of `defaultHeaders`, so this is reachable from ordinary
190 // config. Assert through `new Headers(...)` — the object alone can look fine
191 // while the wire value is the concatenation.
192 it.each([
193 ['lowercase', 'authorization'],
194 ['canonical', 'Authorization'],
195 ['upper', 'AUTHORIZATION'],
196 ['mixed', 'AuThOrIzAtIoN'],
197 ])(
198 'drops a %s caller Authorization rather than appending to it',
199 (_label, key) => {
200 const built = bytePlusArkHeaders('ark-test-key', {
201 [key]: 'Bearer wrong-key',
202 })
203 expect(new Headers(built).get('authorization')).toBe(
204 'Bearer ark-test-key',
205 )
206 },
207 )
208
209 it.each([
210 ['lowercase', 'x-api-key'],
211 ['canonical', 'X-Api-Key'],
212 ['upper', 'X-API-KEY'],
213 ])(
214 'drops a %s caller X-Api-Key rather than appending to it',
215 (_label, key) => {
216 const built = bytePlusVoiceHeaders('voice-test-key', {
217 [key]: 'wrong-key',
218 })
219 expect(new Headers(built).get('x-api-key')).toBe('voice-test-key')
220 },
221 )
222
223 it('drops a differently-cased Content-Type on both hosts', () => {
224 expect(
225 new Headers(
226 bytePlusArkHeaders('ark-test-key', { 'content-type': 'text/plain' }),
227 ).get('content-type'),
228 ).toBe('application/json')
229 expect(
230 new Headers(
231 bytePlusVoiceHeaders('voice-key', { 'CONTENT-TYPE': 'text/plain' }),
232 ).get('content-type'),
233 ).toBe('application/json')
234 })
235
236 // The `Headers` form is the realistic route to the collision above:
237 // `Headers.forEach` yields lowercased names, so a caller who passes
238 // `new Headers({ Authorization: ... })` as `defaultHeaders` lands on the
239 // lowercase key even though they wrote the canonical one.
240 it('survives a Headers-instance defaultHeaders carrying an auth key', () => {
241 const built = bytePlusArkHeaders(
242 'ark-test-key',
243 toHeaderRecord(
244 new Headers({ Authorization: 'Bearer stale', 'X-Trace': 't1' }),
245 ),
246 )
247 expect(new Headers(built).get('authorization')).toBe('Bearer ark-test-key')
248 expect(new Headers(built).get('x-trace')).toBe('t1')
249 })
250
251 it('survives an entry-list defaultHeaders carrying an auth key', () => {
252 const built = bytePlusVoiceHeaders(
253 'voice-key',
254 toHeaderRecord([
255 ['X-Api-Key', 'stale'],
256 ['X-Trace', 't1'],
257 ]),
258 )
259 expect(new Headers(built).get('x-api-key')).toBe('voice-key')
260 expect(new Headers(built).get('x-trace')).toBe('t1')
261 })
262})
263
264describe('toHeaderRecord', () => {
265 it('returns an empty record for absent headers', () => {
266 expect(toHeaderRecord(undefined)).toEqual({})
267 expect(toHeaderRecord(null)).toEqual({})
268 })
269
270 it('flattens a Headers instance', () => {
271 const headers = new Headers({ 'X-Test-Id': 'abc' })
272 expect(toHeaderRecord(headers)).toEqual({ 'x-test-id': 'abc' })
273 })
274
275 it('reads an entry list', () => {
276 expect(
277 toHeaderRecord([
278 ['X-Test-Id', 'abc'],
279 ['X-Other', 'def'],
280 ]),
281 ).toEqual({ 'X-Test-Id': 'abc', 'X-Other': 'def' })
282 })
283
284 it('drops non-string values rather than serializing them', () => {
285 // openai's ClientOptions allows null/undefined as a "remove this header"
286 // signal, and an array for a repeated header. None of the three maps onto
287 // a single string, and none may reach the request as "null" or "a,b".
288 expect(
289 toHeaderRecord({
290 'X-Test-Id': 'abc',
291 'X-Removed': null,
292 'X-Absent': undefined,
293 'X-Repeated': ['a', 'b'],
294 }),
295 ).toEqual({ 'X-Test-Id': 'abc' })
296 })
297
298 it('skips entry-list pairs with a null value', () => {
299 expect(
300 toHeaderRecord([
301 ['X-Test-Id', 'abc'],
302 ['X-Removed', null],
303 ]),
304 ).toEqual({ 'X-Test-Id': 'abc' })
305 })
306})
307
308describe('readJsonBody', () => {
309 it('parses a JSON body', async () => {
310 const response = new Response(JSON.stringify({ id: 'cgt-1' }))
311 await expect(readJsonBody(response)).resolves.toEqual({ id: 'cgt-1' })
312 })
313
314 it('returns undefined for an empty body', async () => {
315 await expect(readJsonBody(new Response(''))).resolves.toBeUndefined()
316 })
317
318 it('falls back to raw text for a non-JSON body', async () => {
319 // Proxies in front of either host answer with HTML, which must still reach
320 // the error formatters instead of throwing a SyntaxError here.
321 const response = new Response('<html>Bad Gateway</html>', { status: 502 })
322 await expect(readJsonBody(response)).resolves.toBe(
323 '<html>Bad Gateway</html>',
324 )
325 })
326})
327
328describe('error formatting', () => {
329 it('reads code and message out of the Ark envelope', () => {
330 const error = bytePlusArkError(
331 404,
332 {
333 error: {
334 code: 'InvalidEndpointOrModel.NotFound',
335 message: 'The model does not exist.',
336 },
337 },
338 'video task creation',
339 )
340 expect(error.message).toBe(
341 'BytePlus Ark video task creation failed (404 InvalidEndpointOrModel.NotFound): The model does not exist.',
342 )
343 })
344
345 it('falls back to the raw body when Ark returns something else', () => {
346 const error = bytePlusArkError(502, '<html>Bad Gateway</html>')
347 expect(error.message).toBe(
348 'BytePlus Ark request failed (502): <html>Bad Gateway</html>',
349 )
350 })
351
352 it('reads the flat numeric code out of the Seed Speech envelope', () => {
353 const error = bytePlusVoiceError(
354 401,
355 { code: 45000010, message: 'Invalid X-Api-Key' },
356 'speech synthesis',
357 )
358 expect(error.message).toBe(
359 'BytePlus Seed Speech speech synthesis failed (401 45000010): Invalid X-Api-Key',
360 )
361 })
362
363 it('serializes an object body that carries no message', () => {
364 expect(
365 bytePlusArkError(500, { error: { type: 'server_error' } }).message,
366 ).toBe(
367 'BytePlus Ark request failed (500): {"error":{"type":"server_error"}}',
368 )
369 expect(
370 bytePlusVoiceError(500, { detail: 'upstream timeout' }).message,
371 ).toBe(
372 'BytePlus Seed Speech request failed (500): {"detail":"upstream timeout"}',
373 )
374 })
375
376 it('degrades to the status alone for an unreadable body', () => {
377 expect(bytePlusVoiceError(500, undefined).message).toBe(
378 'BytePlus Seed Speech request failed (500)',
379 )
380 })
381})