storebound/cli/shots/browser.ts

45 lines
2.7 KiB
TypeScript

// Playwright is an optional peer dependency of storebound, resolved from the project (or the storebound folder), so a
// project that never renders screenshots never downloads a browser. The compiled desktop sidecar carries its own
// playwright-core (tools/build-sidecars.ts bundles it) and renders with the Chrome for Testing the desktop app manages
// (STOREBOUND_CHROME), so desktop users need neither playwright nor a browser in their project.
// Launch order: STOREBOUND_CHROME, Playwright's own Chromium, then an installed Google Chrome (channel "chrome").
import { join } from 'node:path';
import { compiled } from '../lib/runner';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function chromium(root: string): Promise<any> {
for (const base of [root, join(import.meta.dir, '../..')]) {
try {
const p = Bun.resolveSync('playwright', base);
return (await import(p)).chromium;
} catch { /* next */ }
}
// only reached in the compiled sidecar: the bundled playwright-core (not a runtime dependency of the npm package)
if (compiled()) return (await import('playwright-core')).chromium;
throw new Error('playwright not found: in your project run `bun add -d playwright` (and `bunx playwright install chromium` if Google Chrome is not installed)');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function launch(root: string, opts: Record<string, unknown>): Promise<any> {
const c = await chromium(root);
// the desktop app's own Chrome for Testing (or any Chrome the user points at)
const exe = process.env.STOREBOUND_CHROME;
if (exe) { try { return await c.launch({ ...opts, executablePath: exe }); } catch { /* fall back below */ } }
try { return await c.launch(opts); } catch (e) {
try { return await c.launch({ ...opts, channel: 'chrome' }); } catch { throw e; }
}
}
/**
* A persistent browser profile (cookies of a console sign-in the owner did by hand stay there between runs; storebound
* never reads them). Same resolution and launch order as `launch`. Used by `storebound console fill` (visible window).
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function launchPersistent(root: string, userDataDir: string, opts: Record<string, unknown>): Promise<any> {
const c = await chromium(root);
const exe = process.env.STOREBOUND_CHROME;
if (exe) { try { return await c.launchPersistentContext(userDataDir, { ...opts, executablePath: exe }); } catch { /* fall back below */ } }
try { return await c.launchPersistentContext(userDataDir, opts); } catch (e) {
try { return await c.launchPersistentContext(userDataDir, { ...opts, channel: 'chrome' }); } catch { throw e; }
}
}