Your Name dd2b06f10f
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
fix: harden worldlabs asset loading
2026-05-25 17:27:25 +08:00

138 lines
3.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import "server-only";
import {
getAiProviderById,
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();
}
function providerToWorldLabsConfig(
provider: Awaited<ReturnType<typeof getAiProvidersByType>>[number] | undefined
): WorldLabsProviderConfig | null {
if (!provider) return 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,
} satisfies WorldLabsProviderConfig;
}
export async function getWorldLabsProviderConfigs(): Promise<
WorldLabsProviderConfig[]
> {
const providers = await getAiProvidersByType({
type: "worldlabs-3d",
enabledOnly: true,
});
const normalizedProviders = providers
.map((provider) => providerToWorldLabsConfig(provider))
.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,
options?: { includeDisabledPreferred?: boolean }
): Promise<WorldLabsProviderConfig> {
const providers = await getWorldLabsProviderConfigs();
const preferredId = String(preferredProviderId || "").trim();
if (preferredId) {
const matchedProvider =
providers.find((item) => item.providerId === preferredId) || null;
if (matchedProvider) {
return matchedProvider;
}
if (options?.includeDisabledPreferred) {
const disabledOrEnabledProvider = providerToWorldLabsConfig(
await getAiProviderById({ id: preferredId })
);
if (disabledOrEnabledProvider) {
return disabledOrEnabledProvider;
}
}
}
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),
});
}
}