Open History to see the last commit
1import type OpenAI from 'openai'
2import type { ClientOptions } from 'openai'
3import type { TextOptions } from '@tanstack/ai'
4
5/** The fetch type of the OpenAI SDK. */
6export type Fetch = NonNullable<ClientOptions['fetch']>
7
8/**
9 * Extract `headers` and `signal` from a `Request | RequestInit` for the OpenAI
10 * SDK's per-call `RequestOptions`. `Request` exposes `headers` as a `Headers`
11 * instance (HeadersInit-compatible) while `RequestInit` exposes `HeadersInit`
12 * directly — this helper accepts either shape so callers don't need to cast.
13 *
14 * Always returns an object (possibly empty) rather than `undefined` so test
15 * assertions that match the second argument shape via `expect.anything()` /
16 * `expect.objectContaining()` keep working when no request override was set.
17 */
18export function extractRequestOptions(
19 request: Request | RequestInit | undefined,
20): { headers?: HeadersInit; signal?: AbortSignal | null } {
21 if (!request) return {}
22 // Conditional spread: under exactOptionalPropertyTypes the target's
23 // `headers?: HeadersInit` and `signal?: AbortSignal | null` forbid an
24 // explicit `undefined`. Omit the keys entirely when the source values
25 // are absent so the OpenAI SDK sees `headers: undefined` as "not set"
26 // rather than a present-but-undefined value.
27 return {
28 ...(request.headers !== undefined && { headers: request.headers }),
29 ...(request.signal != null && { signal: request.signal }),
30 }
31}
32
33/**
34 * The client of one call. With `wrapFetch`, it is a copy of the client whose
35 * fetch goes through the wrapper. Without it, it is the same client.
36 * `baseFetch` is the fetch that the adapter gave the client.
37 */
38export function clientFor(
39 client: OpenAI,
40 options: Pick<TextOptions, 'wrapFetch'>,
41 baseFetch: Fetch | undefined,
42 withFetch = (fetch: Fetch) => client.withOptions({ fetch }),
43): OpenAI {
44 const { wrapFetch } = options
45 if (!wrapFetch) return client
46 // The SDK falls back to the global fetch the same way.
47 return withFetch(wrapFetch(baseFetch ?? globalThis.fetch))
48}