|
| 1 | +/** Client configuration resolution, shared by the client and its resources. */ |
| 2 | + |
| 3 | +export const DEFAULT_BASE_URL = "https://transcriptfetch.com"; |
| 4 | +export const ENV_API_KEY = "TRANSCRIPTFETCH_API_KEY"; |
| 5 | + |
| 6 | +/** Options accepted by the {@link TranscriptFetch} constructor. */ |
| 7 | +export interface ClientOptions { |
| 8 | + /** Your API key. Falls back to the TRANSCRIPTFETCH_API_KEY environment variable. */ |
| 9 | + apiKey?: string; |
| 10 | + /** Override the API origin. Defaults to https://transcriptfetch.com. */ |
| 11 | + baseUrl?: string; |
| 12 | + /** Per-request timeout in milliseconds. Defaults to 30000. */ |
| 13 | + timeout?: number; |
| 14 | + /** How many times to retry 429 and 5xx responses. Defaults to 2. */ |
| 15 | + maxRetries?: number; |
| 16 | + /** Inject a custom fetch implementation (defaults to the global fetch). */ |
| 17 | + fetch?: typeof fetch; |
| 18 | +} |
| 19 | + |
| 20 | +export interface ResolvedConfig { |
| 21 | + apiKey: string; |
| 22 | + baseUrl: string; |
| 23 | + timeout: number; |
| 24 | + maxRetries: number; |
| 25 | + fetch: typeof fetch; |
| 26 | +} |
| 27 | + |
| 28 | +/** Resolve user options into a complete config, reading env and applying defaults. */ |
| 29 | +export function resolveConfig(options: ClientOptions = {}): ResolvedConfig { |
| 30 | + const envKey = typeof process !== "undefined" ? process.env?.[ENV_API_KEY] : undefined; |
| 31 | + const apiKey = options.apiKey ?? envKey; |
| 32 | + if (!apiKey) { |
| 33 | + throw new Error( |
| 34 | + `No API key provided. Pass { apiKey } or set the ${ENV_API_KEY} environment variable.`, |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + const fetchImpl = options.fetch ?? globalThis.fetch; |
| 39 | + if (typeof fetchImpl !== "function") { |
| 40 | + throw new Error( |
| 41 | + "global fetch is not available. Use Node 18+, or pass a fetch implementation via { fetch }.", |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + return { |
| 46 | + apiKey, |
| 47 | + baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ""), |
| 48 | + timeout: options.timeout ?? 30_000, |
| 49 | + maxRetries: Math.max(0, options.maxRetries ?? 2), |
| 50 | + fetch: fetchImpl, |
| 51 | + }; |
| 52 | +} |
0 commit comments