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.

41 lines
1.2 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";
export type PlaywrightStorageState = {
cookies: Array<{
name: string;
value: string;
domain?: string;
}>;
};
export function resolveStorageStatePath(): string {
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("; ");
}