You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import fs from "node:fs";
import { DEFAULT_RPA_STORAGE_STATE_PATH } from "@/lib/rpa/env";
import { hasEffectiveMothershipLogin } from "@/lib/rpa/mothership-login-context";
export type PlaywrightStorageState = {
cookies: Array<{
name: string;
value: string;
domain?: string;
}>;
};
export const DEFAULT_LOGGED_IN_STORAGE_STATE_PATH =
".rpa/mothership-logged-in-storage.json";
export function resolveStorageStatePath(): string {
const loggedInPath =
process.env.RPA_LOGGED_IN_STORAGE_STATE_PATH?.trim() ||
DEFAULT_LOGGED_IN_STORAGE_STATE_PATH;
// 有 MotherShip 账密时优先登录态 cookie价源对齐 dashboard
if (hasEffectiveMothershipLogin() && fs.existsSync(loggedInPath)) {
return loggedInPath;
}
return (
process.env.RPA_STORAGE_STATE_PATH?.trim() || DEFAULT_RPA_STORAGE_STATE_PATH
);
}
export function loadStorageState(
path = resolveStorageStatePath(),
): PlaywrightStorageState {
if (!fs.existsSync(path)) {
throw new Error(
`缺少 MotherShip 会话文件 ${path};系统将尝试自动获取,或运行 npm run record:mothership`,
);
}
return JSON.parse(fs.readFileSync(path, "utf8")) as PlaywrightStorageState;
}
/** 缺会话时自动 bootstrap再读取 storageState */
export async function loadStorageStateAsync(
path = resolveStorageStatePath(),
): Promise<PlaywrightStorageState> {
const { ensureMothershipStorageState } = await import(
"@/lib/rpa/ensure-storage-state"
);
await ensureMothershipStorageState();
return loadStorageState(path);
}
export function buildCookieHeader(state: PlaywrightStorageState): string {
return state.cookies.map((c) => `${c.name}=${c.value}`).join("; ");
}