import "server-only"; import { getAiProvidersByType, updateAiProvider, } from "@/lib/db/queries"; import type { WorldLabsProviderConfig } from "./types"; const DEFAULT_WORLDLABS_BASE_URL = "https://api.worldlabs.ai"; let worldLabsProviderCursor = 0; export function sanitizeWorldLabsApiKey(value: string): string { return String(value || "") .replace(/[\u2028\u2029]/g, "") .replace(/[\u0000-\u001F\u007F]/g, "") .replace(/\s+/g, "") .trim(); } export function sanitizeWorldLabsBaseUrl(value: string): string { return String(value || "") .replace(/[\u2028\u2029]/g, "") .replace(/[\u0000-\u001F\u007F]/g, "") .trim(); } export async function getWorldLabsProviderConfigs(): Promise< WorldLabsProviderConfig[] > { const providers = await getAiProvidersByType({ type: "worldlabs-3d", enabledOnly: true, }); const normalizedProviders = providers .map((provider): WorldLabsProviderConfig | null => { const providerApiKey = sanitizeWorldLabsApiKey( String(provider.apiKey || "") ); if (!providerApiKey) return null; return { apiKey: providerApiKey, baseUrl: sanitizeWorldLabsBaseUrl(String(provider.baseUrl || "")) || DEFAULT_WORLDLABS_BASE_URL, providerId: provider.id, providerName: provider.name, }; }) .filter((item): item is WorldLabsProviderConfig => Boolean(item)); if (normalizedProviders.length > 0) { return normalizedProviders; } const envApiKey = sanitizeWorldLabsApiKey(String(process.env.WORLDLABS_API_KEY || "")); if (!envApiKey) { return []; } return [ { apiKey: envApiKey, baseUrl: sanitizeWorldLabsBaseUrl(String(process.env.WORLDLABS_BASE_URL || "")) || DEFAULT_WORLDLABS_BASE_URL, providerName: "WORLDLABS_API_KEY", }, ]; } export async function getWorldLabsProviderConfig( preferredProviderId?: string | null ): Promise { const providers = await getWorldLabsProviderConfigs(); const preferredId = String(preferredProviderId || "").trim(); if (preferredId) { const matchedProvider = providers.find((item) => item.providerId === preferredId) || null; if (matchedProvider) { return matchedProvider; } } const worldLabsProvider = providers.length > 0 ? providers[worldLabsProviderCursor % providers.length] : null; if (providers.length > 0) { worldLabsProviderCursor = (worldLabsProviderCursor + 1) % providers.length; } if (worldLabsProvider) { return worldLabsProvider; } throw new Error("未配置 World Labs API,请在系统设置-本地AI新增 World Labs 提供商"); } export async function disableWorldLabsProvider( providerId?: string | null, reason?: string ) { const normalizedProviderId = String(providerId || "").trim(); if (!normalizedProviderId) return; try { await updateAiProvider({ id: normalizedProviderId, isEnabled: false, }); console.warn( `[WorldLabsPool] Disabled provider ${normalizedProviderId}${ reason ? `: ${reason}` : "" }` ); } catch (error) { console.error("[WorldLabsPool] Failed to disable provider:", { providerId: normalizedProviderId, reason, error: error instanceof Error ? error.message : String(error), }); } }