import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import ts from 'typescript'; import { beforeAll, describe, expect, it } from 'vitest'; import { resolveApiName, type ApiReference } from './api-format.js'; import { generateApiReference } from './api-reference.js'; const root = path.resolve(import.meta.dirname, '../..'); let ref: ApiReference; beforeAll(() => { ref = generateApiReference(root); }, 60_000); const entry = (name: string) => { const found = ref.entries.find((e) => e.name === name); if (found === undefined) throw new Error(`no entry ${name}`); return found; }; function publicMembers(): string[] { const file = path.join(root, 'src/browser.ts'); const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true); const names = new Set(); for (const statement of source.statements) { if (!ts.isClassDeclaration(statement) || statement.name === undefined) continue; const receiver = statement.name.text === 'CrawlPage' ? 'page' : 'browser'; for (const member of statement.members) { if (!(ts.isMethodDeclaration(member) || ts.isGetAccessorDeclaration(member)) || !ts.isIdentifier(member.name)) continue; const kinds = member.modifiers?.map((m) => m.kind) ?? []; if (kinds.includes(ts.SyntaxKind.PrivateKeyword) || kinds.includes(ts.SyntaxKind.ProtectedKeyword)) continue; names.add(`${kinds.includes(ts.SyntaxKind.StaticKeyword) ? 'BrowserClaw' : receiver}.${member.name.text}`); } } return [...names].sort(); } describe('generateApiReference', () => { it('includes every public CrawlPage and BrowserClaw member and no private or internal ones', () => { expect(ref.entries.map((e) => e.name).sort()).toEqual(publicMembers()); expect(ref.entries.some((e) => e.name.endsWith('.traverseHistory') || e.name.endsWith('.constructor'))).toBe(false); expect(ref.version).toBe( (JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')) as { version: string }).version, ); }); it('every entry has a summary', () => { for (const e of ref.entries) expect(e.summary, e.name).not.toBe(''); }); it('prints signatures without "| undefined"', () => { for (const e of ref.entries) for (const signature of e.signatures) expect(signature, e.name).not.toContain('undefined |'); for (const e of ref.entries) for (const signature of e.signatures) expect(signature, e.name).not.toContain('| undefined'); expect(entry('page.hover').signatures).toEqual([ 'page.hover(ref: string, opts?: { timeoutMs?: number; signal?: AbortSignal }): Promise', ]); }); it('describes fill fields and batch actions per kind', () => { expect(entry('page.fill').elements).toEqual([ { param: 'fields', typeName: 'FormField', properties: [ { name: 'ref', type: 'string', optional: false, doc: "Ref ID of the form field (e.g. `'e3'`)" }, { name: 'type', type: 'string', optional: true, doc: "Field type: `'text'`, `'checkbox'`, `'radio'`, etc." }, { name: 'value', type: 'string | number | boolean', optional: true, doc: 'Value to set. Booleans for checkboxes, strings for text fields.', }, ], }, ]); const batch = entry('page.batch').elements?.[0]; expect(batch?.param).toBe('actions'); const click = batch?.variants?.find((v) => v.kind === 'click'); expect(click?.properties.map((p) => `${p.name}${p.optional ? '?' : ''}`)).toEqual([ 'kind', 'ref?', 'selector?', 'targetId?', 'doubleClick?', 'button?', 'modifiers?', 'delayMs?', 'timeoutMs?', ]); expect(batch?.variants?.map((v) => v.kind)).toContain('batch'); }); it('merges overloads into one entry without the implementation signature', () => { const fixture = mkdtempSync(path.join(tmpdir(), 'browserclaw-api-')); try { mkdirSync(path.join(fixture, 'src')); writeFileSync(path.join(fixture, 'package.json'), '{ "version": "9.9.9" }'); writeFileSync( path.join(fixture, 'tsconfig.json'), JSON.stringify({ compilerOptions: { strict: true, target: 'ES2022', module: 'ESNext' }, include: ['src'] }), ); writeFileSync( path.join(fixture, 'src/index.ts'), [ 'export interface SelectOptions {', ' /** Per-call timeout */', ' timeoutMs?: number;', '}', 'export class CrawlPage {', ' /** Select options in a dropdown. */', ' select(ref: string, ...values: string[]): Promise;', ' select(ref: string, values: string[], opts?: SelectOptions): Promise;', ' select(ref: string, ...rest: unknown[]): Promise { return Promise.resolve(); }', '}', 'export class BrowserClaw {}', ].join('\n'), ); const select = generateApiReference(fixture).entries.find((e) => e.name === 'page.select'); expect(select?.signatures).toEqual([ 'page.select(ref: string, ...values: string[]): Promise', 'page.select(ref: string, values: string[], opts?: SelectOptions): Promise', ]); expect(select?.summary).toBe('Select options in a dropdown.'); expect(select?.options).toEqual({ typeName: 'SelectOptions', properties: [{ name: 'timeoutMs', type: 'number', optional: true, doc: 'Per-call timeout' }], }); } finally { rmSync(fixture, { recursive: true, force: true }); } }, 30_000); it('expands BC-declared option types one level', () => { const props = entry('BrowserClaw.launch').options?.properties ?? []; const ssrf = props.find((p) => p.name === 'ssrfPolicy'); expect(ssrf?.type).toBe('SsrfPolicy'); expect(ssrf?.properties?.map((p) => p.name)).toContain('allowedHostnames'); expect(ssrf?.properties?.every((p) => p.properties === undefined)).toBe(true); expect(props.find((p) => p.name === 'recordVideo')?.properties).toBeUndefined(); expect(entry('page.click').options?.properties.find((p) => p.name === 'signal')?.properties).toBeUndefined(); expect(entry('BrowserClaw.connect').options?.properties.find((p) => p.name === 'ssrfPolicy')?.properties).toEqual( ssrf?.properties, ); }); }); describe('resolveApiName', () => { it('resolveApiName accepts page.click, CrawlPage.click, click, click() and await page.click', () => { for (const input of [ 'page.click', 'CrawlPage.click', 'click', 'click()', 'page.click(', 'await page.click', ' page.click(ref) ', ]) expect(resolveApiName(ref, input), input).toEqual({ entry: entry('page.click') }); expect(resolveApiName(ref, 'launch')).toEqual({ entry: entry('BrowserClaw.launch') }); expect(resolveApiName(ref, 'browser.launch')).toEqual({ entry: entry('BrowserClaw.launch') }); expect(resolveApiName(ref, 'BrowserClaw.open')).toEqual({ entry: entry('browser.open') }); expect(resolveApiName(ref, 'url')).toEqual({ candidates: ['browser.url', 'page.url'] }); }); it('resolveApiName returns close matches for a typo', () => { expect(resolveApiName(ref, 'page.clik')).toEqual({ matches: ['page.click', 'page.clickByRole', 'page.clickBySelector', 'page.clickByText'], }); expect(resolveApiName(ref, 'page.snapshoot')).toEqual({ matches: ['page.snapshot'] }); expect(resolveApiName(ref, 'qqqqqqqq')).toEqual({ matches: [] }); }); });