export async function fetchJsonWithTimeout( url: string, init: RequestInit, timeoutMs: number, ): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), timeoutMs); try { const res = await fetch(url, { ...init, signal: controller.signal }); const text = await res.text(); let data: T | null = null; try { data = text ? (JSON.parse(text) as T) : null; } catch { // Keep data null and report text below. } const error = data && typeof data === "object" && "error" in data ? typeof (data as { error: unknown }).error === "object" ? JSON.stringify((data as { error: unknown }).error) : String((data as { error: unknown }).error) : text; return { ok: res.ok, status: res.status, data, error: res.ok ? undefined : error }; } catch (error) { return { ok: false, status: 0, data: null, error: error instanceof Error ? error.message : String(error) }; } finally { clearTimeout(timeout); } } export async function concurrentMap( items: T[], workers: number, fn: (item: T) => Promise, ): Promise[]> { const results: PromiseSettledResult[] = new Array(items.length); let next = 0; await Promise.all( Array.from({ length: Math.max(1, workers) }, async () => { while (next < items.length) { const index = next++; try { results[index] = { status: "fulfilled", value: await fn(items[index]) }; } catch (reason) { results[index] = { status: "rejected", reason }; } } }), ); return results; } export function getContextLength(modelInfo: Record): number { for (const [key, value] of Object.entries(modelInfo)) { if (key.endsWith(".context_length") && typeof value === "number") { return value; } } return 128000; }