import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import { connect, type AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { chromium } from 'playwright-core';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { BrowserClaw, type CrawlPage } from './browser.js';
import { UnknownOptionError } from './errors.js';
const executablePath = [chromium.executablePath(), '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(
(candidate) => candidate !== '' && existsSync(candidate),
);
const FORM_PAGE = `
options
`;
function listen(server: Server, port = 0): Promise {
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, '127.0.0.1', () => {
resolve((server.address() as AddressInfo).port);
});
});
}
async function freePort(): Promise {
const probe = createServer();
const port = await listen(probe);
await new Promise((resolve) => probe.close(resolve));
return port;
}
function isListening(port: number): Promise {
return new Promise((resolve) => {
const socket = connect(port, '127.0.0.1');
socket.once('connect', () => {
socket.destroy();
resolve(true);
});
socket.once('error', () => {
resolve(false);
});
});
}
describe.skipIf(executablePath === undefined)('unknown option rejection (real Chromium)', () => {
let server: Server;
let origin: string;
let browser: BrowserClaw;
let page: CrawlPage;
let input: string;
let button: string;
const profiles: string[] = [];
const scratchProfile = (): string => {
const dir = mkdtempSync(path.join(tmpdir(), 'browserclaw-options-'));
profiles.push(dir);
return dir;
};
const refFor = async (role: string, name: string): Promise => {
const { refs } = await page.snapshot({ interactive: true, compact: true });
const found = Object.entries(refs).find(([, info]) => info.role === role && info.name === name)?.[0];
if (found === undefined) throw new Error(`no ${role} "${name}" in the snapshot`);
return found;
};
const state = async (): Promise<{ clicks: number; value: string }> =>
(await page.evaluate('() => ({ clicks: window.__clicks || 0, value: document.querySelector("#name").value })')) as {
clicks: number;
value: string;
};
beforeAll(async () => {
server = createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'text/html' });
res.end(FORM_PAGE);
});
origin = `http://localhost:${String(await listen(server))}`;
browser = await BrowserClaw.launch({
url: `${origin}/form`,
headless: true,
userDataDir: scratchProfile(),
cdpPort: await freePort(),
noSandbox: process.platform === 'linux',
executablePath,
ssrfPolicy: { allowedHostnames: ['localhost'] },
});
page = await browser.currentPage();
input = await refFor('textbox', 'Name');
button = await refFor('button', 'Save');
}, 60_000);
afterAll(async () => {
await browser.stop();
for (const dir of profiles) rmSync(dir, { recursive: true, force: true });
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
});
it('click with a Playwright-style timeout option throws UnknownOptionError and does not click', async () => {
const error = await page.click(button, { timeout: 1000 } as never).catch((err: unknown) => err);
expect(error).toBeInstanceOf(UnknownOptionError);
expect((error as UnknownOptionError).options).toEqual(['timeout']);
expect((await state()).clicks).toBe(0);
await page.click(button, { timeoutMs: 5000 });
expect((await state()).clicks).toBe(1);
}, 30_000);
it('fill with { ref, text } throws and leaves the field unchanged', async () => {
await expect(page.fill([{ ref: input, text: 'Jane' }] as never)).rejects.toThrow(
'page.fill() got unknown option "fields[0].text". Expected fields[i]: { ref, type?, value? }.',
);
expect((await state()).value).toBe('');
await page.fill([{ ref: input, value: 'Jane' }]);
expect((await state()).value).toBe('Jane');
await page.fill([{ ref: input, value: '' }]);
}, 30_000);
it('batch with one bad action throws before the first action runs', async () => {
const before = await state();
await expect(
page.batch([
{ kind: 'type', ref: input, text: 'typed by batch' },
{ kind: 'click', ref: button, timeout: 1000 } as never,
]),
).rejects.toThrow(UnknownOptionError);
expect(await state()).toEqual(before);
}, 30_000);
it('launch with a misspelled option throws before Chrome starts', async () => {
const cdpPort = await freePort();
const userDataDir = scratchProfile();
await expect(BrowserClaw.launch({ headles: true, cdpPort, userDataDir, executablePath } as never)).rejects.toThrow(
'BrowserClaw.launch() got unknown option "headles".',
);
expect(await isListening(cdpPort)).toBe(false);
expect(readdirSync(userDataDir)).toEqual([]);
}, 30_000);
it('launch with a misspelled ssrfPolicy key throws', async () => {
const cdpPort = await freePort();
const error = await BrowserClaw.launch({
headless: true,
cdpPort,
userDataDir: scratchProfile(),
executablePath,
ssrfPolicy: { hostnameAllowList: ['localhost'] } as never,
}).catch((err: unknown) => err);
expect(error).toBeInstanceOf(UnknownOptionError);
expect((error as UnknownOptionError).options).toEqual(['ssrfPolicy.hostnameAllowList']);
expect(await isListening(cdpPort)).toBe(false);
}, 30_000);
});