Open History to see the last commit
1import { getApiKeyFromEnv } from '@tanstack/ai-utils'
2
3export const DEFAULT_REACTOR_API_URL = 'https://api.reactor.inc'
4
5export interface ReactorClientConfig {
6 apiKey?: string
7 baseUrl?: string
8 fetch?: typeof fetch
9}
10
11export function getReactorApiKeyFromEnv(): string {
12 return getApiKeyFromEnv('REACTOR_API_KEY')
13}
14
15export function resolveReactorApiKey(config?: ReactorClientConfig): string {
16 return config?.apiKey ?? getReactorApiKeyFromEnv()
17}
18
19export function resolveReactorApiUrl(config?: ReactorClientConfig): string {
20 return (config?.baseUrl ?? DEFAULT_REACTOR_API_URL).replace(/\/+$/, '')
21}
22
23export interface ReactorTokenResponse {
24 jwt: string
25 expires_at: number
26}
27
28export async function mintReactorSessionToken(args: {
29 apiKey: string
30 apiUrl: string
31 modelSlug: string
32 fetchImpl?: typeof fetch
33 abortSignal?: AbortSignal
34}): Promise<ReactorTokenResponse> {
35 const fetchImpl = args.fetchImpl ?? globalThis.fetch
36 if (typeof fetchImpl !== 'function') {
37 throw new Error(
38 'global fetch is not available. Pass `fetch` in the Reactor adapter config.',
39 )
40 }
41
42 const response = await fetchImpl(`${args.apiUrl}/tokens`, {
43 method: 'POST',
44 headers: {
45 'Reactor-API-Key': args.apiKey,
46 'Content-Type': 'application/json',
47 },
48 body: JSON.stringify({
49 authorization_details: [
50 {
51 type: 'session',
52 resources: { models: { match: [args.modelSlug] } },
53 },
54 ],
55 }),
56 ...(args.abortSignal ? { signal: args.abortSignal } : {}),
57 })
58
59 if (!response.ok) {
60 const detail = await response.text().catch(() => '')
61 throw new Error(
62 `Reactor token request failed (${response.status}${
63 response.statusText ? ` ${response.statusText}` : ''
64 })${detail ? `: ${detail}` : ''}`,
65 )
66 }
67
68 const body = (await response.json()) as {
69 jwt?: unknown
70 expires_at?: unknown
71 }
72
73 if (typeof body.jwt !== 'string' || body.jwt.length === 0) {
74 throw new Error('Reactor token response did not include a jwt.')
75 }
76
77 if (
78 typeof body.expires_at !== 'number' ||
79 !Number.isFinite(body.expires_at)
80 ) {
81 throw new Error('Reactor token response did not include expires_at.')
82 }
83
84 return { jwt: body.jwt, expires_at: body.expires_at }
85}