feat: 改为安装包分发并使用动态端口

This commit is contained in:
2026-10-25 02:31:23 +08:00
parent 5ca491834e
commit f5779369a5
34 changed files with 392 additions and 49 deletions
+26 -2
View File
@@ -1,4 +1,27 @@
export const API_BASE = import.meta.env.DEV ? "" : "http://127.0.0.1:8765";
let apiBase = "";
let preparing: Promise<void> | null = null;
export function initApi(): Promise<void> {
preparing ??= resolveApiBase();
return preparing;
}
async function resolveApiBase(): Promise<void> {
if (!("__TAURI_INTERNALS__" in window)) return;
const { invoke } = await import("@tauri-apps/api/core");
for (let attempt = 0; attempt < 50; attempt += 1) {
try {
const port = await invoke<number>("backend_port");
if (port > 0) {
apiBase = `http://127.0.0.1:${port}`;
return;
}
} catch {
// 窗口可能比端口命令更早就绪。
}
await new Promise((resolve) => window.setTimeout(resolve, 100));
}
}
export class ApiError extends Error {
status: number;
@@ -10,13 +33,14 @@ export class ApiError extends Error {
}
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
await initApi();
let response: Response;
try {
const headers = new Headers(init?.headers);
if (init?.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
response = await fetch(`${API_BASE}${path}`, { ...init, headers });
response = await fetch(`${apiBase}${path}`, { ...init, headers });
} catch {
throw new ApiError(0, "连接失败");
}