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

client.ts

50 lines1.4 KB

1import { getApiKeyFromEnv } from '@tanstack/ai-utils'
2import { createClient, createConfig } from '../generated/client/index'
3import type { Client } from '../generated/client/index'
4​
5export const DEFAULT_WORLDLABS_API_URL = 'https://api.worldlabs.ai'
6​
7export interface WorldLabsClientConfig {
8 apiKey?: string
9 baseUrl?: string
10 fetch?: typeof fetch
11 defaultHeaders?: Record<string, string>
13​
14export function getWorldLabsApiKeyFromEnv(): string {
15 return getApiKeyFromEnv('WORLDLABS_API_KEY')
17​
18export function resolveWorldLabsApiKey(config?: WorldLabsClientConfig): string {
19 return config?.apiKey ?? getWorldLabsApiKeyFromEnv()
21​
22export function resolveWorldLabsApiUrl(config?: WorldLabsClientConfig): string {
23 return (config?.baseUrl ?? DEFAULT_WORLDLABS_API_URL).replace(/\/+$/, '')
25​
26export function createWorldLabsClient(config: WorldLabsClientConfig = {}): {
27 client: Client
28 apiKey: string
29 baseUrl: string
30} {
31 const apiKey = resolveWorldLabsApiKey(config)
32 const baseUrl = resolveWorldLabsApiUrl(config)
33 const fetchImpl = config.fetch ?? globalThis.fetch
34 if (typeof fetchImpl !== 'function') {
35 throw new Error(
36 'global fetch is not available. Pass `fetch` in the World Labs adapter config.',
37 )
38 }
39​
40 const client = createClient(
41 createConfig({
42 baseUrl,
43 auth: apiKey,
44 fetch: fetchImpl,
45 headers: config.defaultHeaders,
46 }),
47 )
48​
49 return { client, apiKey, baseUrl }