import * as Playwright from "playwright"; import { chromium, devices } from "playwright"; import type { Database } from "./database"; import type { TPlatform } from "./platform"; export type Browser = { loadBrowserContext(platform: TPlatform): Promise; saveBrowserContext(platform: TPlatform, ctx: BrowserContext): Promise; newContext: () => Promise; close: () => Promise; }; export type BrowserContext = Playwright.BrowserContext; export async function createBrowser({ db, headless = true, }: { db: Database; headless?: boolean; }): Promise { const { userAgent } = devices["Desktop Chrome"]; const browser = await chromium.launch({ headless, args: ["--disable-blink-features=AutomationControlled"], }); return { async loadBrowserContext( platform: TPlatform, ): Promise { const { secrets } = await db.get( `select secrets from platforms where name = ?`, platform, ); const storageState = JSON.parse(secrets) ?? undefined; const ctx = await browser.newContext({ storageState, userAgent }); return ctx; }, async saveBrowserContext( platform: TPlatform, ctx: BrowserContext, ): Promise { const secrets = await ctx.storageState(); await db.run( `update platforms set secrets = ? where name = ?`, JSON.stringify(secrets), platform, ); }, newContext: () => browser.newContext(), close: () => browser.close(), }; }