barebrowse 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,65 @@
1
1
  # Changelog
2
2
 
3
+ ## [Unreleased]
4
+
5
+ ## [0.20.0] - 2026-08-30
6
+
7
+ ### Added
8
+
9
+ - **Publish workflow gates on the types being usable BY AN ADOPTER, not just internally.** `npm run typecheck` (`tsc --noEmit`) checks the *source*; it cannot see the generated `.d.ts` as an adopter resolves it from inside `node_modules`, which is the one thing consumers actually get. The publish workflow now packs the tarball, installs it into a clean consumer project, and compiles a quickstart against it, so a release whose published types are broken cannot reach the registry. The consumer pins `@types/node` to the major this package builds against instead of floating to the newest, so a stricter DefinitelyTyped release cannot turn the publish gate red for reasons unrelated to the commit being published. Verified locally: the quickstart compiles green against a packed tarball, and a deliberately broken dereference fails it. CI only — no runtime or published-artifact change.
10
+
11
+ ### Fixed
12
+
13
+ - **`connect()` now returns a typed page handle instead of bare `object`.** Its
14
+ JSDoc `@returns` was `Promise<object>`, so a TypeScript adopter could not
15
+ dereference `page.goto` / `page.snapshot` / `page.click` / `page.close` off the
16
+ returned handle without casting — the whole interactive surface was unusable
17
+ from types. The return is now inferred structurally from the returned object
18
+ literals and re-exported as a named `Page` type (`import type { Page } from
19
+ 'barebrowse'`), so there is no hand-maintained interface to drift. `Page` is a
20
+ union of the two engine shapes (Chromium/CDP and Firefox/BiDi): every shared
21
+ interaction method dereferences without narrowing, while an engine-specific
22
+ escape hatch (`cdp` on Chromium, `bidi` on Firefox) is exposed by narrowing
23
+ (`if ('cdp' in page) …`) — the union is sound where an intersection would falsely
24
+ claim a page carries both engines' hatches. The commonly-omitted option
25
+ parameters on `snapshot()`, `type()`, and `injectCookies()` are now typed
26
+ optional (they always were at runtime), so `page.snapshot()` and
27
+ `page.type(ref, text)` compile — and carry named, member-checked shapes
28
+ (`SnapshotOptions`, `TypeOptions`, `CookieOptions`, all exported), so a typo
29
+ like `snapshot({ mdoe: 'read' })` is now a compile error instead of a silent
30
+ no-op. `browse()` → `Promise<string>` is unchanged.
31
+ Validated by packing the tarball and compiling a strict (`nodenext`,
32
+ `skipLibCheck:false`) consumer quickstart that dereferences the real page
33
+ methods — green after, red before. The publish adopter gate missed this because
34
+ its quickstart only exercises `browse()`'s snapshot string, never the
35
+ `connect()` handle.
36
+ - **Publish workflow pinned to `npm@11` — npm 12.0.0's `npm publish --provenance` is broken.** The job ran `npm install -g npm@latest`, which started resolving to npm 12.0.0 (released 2026-07-09) on the Node 22 runner. npm 12's `libnpmpublish` provenance code does `require('sigstore')`, but the tarball bundles only the `@sigstore/*` scoped packages — so `--provenance` dies with `MODULE_NOT_FOUND` and the publish fails outright. npm@11 bundles `sigstore` and publishes fine. Pinned to the major rather than floating on `@latest`. Revisit once npm ships a provenance fix. CI only — no runtime or published-artifact change.
37
+
38
+ ### Changed
39
+
40
+ - **Agent/IDE scratch is gitignored and de-tracked (`.claude/`, `.litectx/`, `.idea/`).** Per-machine agent and IDE state is no part of the package — it regenerates locally and only added noise and churn. Now ignored, and any already-committed copies removed from tracking (local files kept on disk). Functional dot-paths (`.github/`, `.gitignore`, `.npmignore`, `.mcp.json`) stay tracked. Repo hygiene only.
41
+
42
+ ## [0.19.2] - 2026-07-11
43
+
44
+ ### Fixed
45
+
46
+ - **Firefox `saveState()` now writes `sameSite` capitalized** (`Lax`/`Strict`/`None`,
47
+ was BiDi's lowercase `lax`/`strict`/`none`). The only loader for a state file is
48
+ `connect({ storageState })`, which is CDP-only (`Network.setCookies`) and rejects
49
+ a lowercase enum — so the whole batch threw and every cookie was silently dropped,
50
+ making a Firefox-saved state useless for auth restore. Found by `/code-review` and
51
+ confirmed against real Firefox.
52
+ - **Firefox CLI/daemon `eval` accepts statement-form expressions again**
53
+ (`var x = 2; x * 3`). A Phase-4 wrapper (`await (${expr})`, added to flatten
54
+ objects) turned every statement list into a `SyntaxError` — a regression versus
55
+ the CDP `Runtime.evaluate` path. Now evaluates the raw expression (BiDi
56
+ `script.evaluate` has eval-semantics) and deserializes the `{type,value}` remote
57
+ value back to the plain value CDP's `returnByValue` yields, so deep objects stay
58
+ clean *and* statements work.
59
+ - **Firefox daemon console capture no longer dumps nested serialization** for
60
+ object/array console arguments — it falls back to the type name, matching the CDP
61
+ capture's `RemoteObject.description` ("Object").
62
+
3
63
  ## [0.19.1] - 2026-07-11
4
64
 
5
65
  ### Changed
@@ -61,6 +61,8 @@ const snapshot = await browse('https://example.com', {
61
61
 
62
62
  `connect(opts)` returns a page handle for interactive sessions. Same opts as `browse()` for mode. Supports `hybrid` mode — starts headless, auto-launches headed on bot detection (same as `browse()`).
63
63
 
64
+ **TypeScript:** the handle is the exported `Page` type — `import type { Page } from 'barebrowse'`. It's a union of the Chromium and Firefox page shapes: every method in the table below is available directly, while an engine-specific escape hatch (`cdp` on Chromium, `bidi` on Firefox) is reached by narrowing, e.g. `if ('cdp' in page) page.cdp.send(...)`.
65
+
64
66
  | Method | Args | Returns | Notes |
65
67
  |---|---|---|---|
66
68
  | `goto(url, timeout?)` | url: string, timeout: number (default 30000) | void | Navigate + wait for load + dismiss consent |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebrowse",
3
- "version": "0.19.1",
3
+ "version": "0.20.0",
4
4
  "description": "Authenticated web browsing for autonomous agents via CDP. URL in, pruned ARIA snapshot out.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/daemon.js CHANGED
@@ -67,6 +67,31 @@ export function buildDaemonArgs(opts, absDir, initialUrl, cliPath) {
67
67
  return args;
68
68
  }
69
69
 
70
+ /**
71
+ * Convert a BiDi remote value ({type,value} — see script.evaluate) into the
72
+ * plain JS value CDP's `Runtime.evaluate({returnByValue:true})` yields, so an
73
+ * `eval` returns the same shape on both engines. BiDi serializes objects/arrays
74
+ * as entry lists ([[k,v],…] / [v,…]) rather than plain values; walk them back.
75
+ * @param {object} r - BiDi remote value
76
+ * @returns {*}
77
+ */
78
+ export function deserializeBiDi(r) {
79
+ if (!r || typeof r !== 'object') return r;
80
+ switch (r.type) {
81
+ case 'undefined': return undefined;
82
+ case 'null': return null;
83
+ case 'string': case 'number': case 'boolean': case 'bigint': return r.value;
84
+ case 'array': case 'set': return (r.value || []).map(deserializeBiDi);
85
+ case 'object': case 'map':
86
+ return Object.fromEntries(
87
+ (r.value || []).map(([k, v]) => [typeof k === 'object' ? deserializeBiDi(k) : k, deserializeBiDi(v)]),
88
+ );
89
+ // date/regexp/node/function/etc. — no plain-value equivalent; use the raw
90
+ // value if BiDi provided one, else the type name (matches CDP's coarseness).
91
+ default: return r.value !== undefined ? r.value : r.type;
92
+ }
93
+ }
94
+
70
95
  /**
71
96
  * Wire Firefox/BiDi console + network capture onto the daemon's log arrays.
72
97
  * The BiDi analogue of the CDP `Runtime.consoleAPICalled` / `Network.*`
@@ -99,8 +124,12 @@ export async function attachBiDiCapture(bidi, { consoleLogs, networkLogs, pendin
99
124
  // engines — BiDi says 'warn', CDP says 'warning'.
100
125
  type: e.method === 'warn' ? 'warning' : (e.method || e.level),
101
126
  timestamp: new Date().toISOString(),
127
+ // Primitive args carry a usable `.value`; objects/arrays/functions carry a
128
+ // nested {type,value} serialization we must NOT splat into the log (it's
129
+ // deep junk) — fall back to the type name, mirroring the CDP capture which
130
+ // logs a RemoteObject's `.description` ("Object") for non-primitives.
102
131
  args: Array.isArray(e.args) && e.args.length
103
- ? e.args.map((a) => a.value ?? a.type)
132
+ ? e.args.map((a) => (a.value !== undefined && typeof a.value !== 'object' ? a.value : a.type))
104
133
  : [e.text],
105
134
  });
106
135
  });
@@ -416,13 +445,20 @@ export async function runDaemon(opts, outputDir, initialUrl) {
416
445
  // Firefox/BiDi has no page.cdp — evaluate over BiDi in the active context.
417
446
  if (!page.cdp) {
418
447
  try {
419
- // BiDi's raw result.value serializes objects into a {type,value}
420
- // entries structure, not a plain object (CDP's returnByValue does).
421
- // Stringify + parse in-page so an object/array eval matches the CDP
422
- // shape (same trick readable() uses). `undefined` → JSON `null`.
423
- const wrapped = `(async () => { const v = await (${expression}); return JSON.stringify(v === undefined ? null : v); })()`;
424
- const raw = await page.bidi.evaluate(page.context, wrapped, true);
425
- return { ok: true, value: raw == null ? null : JSON.parse(raw) };
448
+ // Evaluate the RAW expression: script.evaluate has eval-semantics, so
449
+ // statement lists ("var x = 2; x * 3") work and yield the completion
450
+ // value — matching the CDP Runtime.evaluate path. (An earlier
451
+ // `await (${expression})` wrapper flattened objects but broke every
452
+ // statement-form expression with a SyntaxError.) BiDi returns a
453
+ // {type,value} remote value; deserializeBiDi walks it back to the plain
454
+ // JS value CDP's returnByValue produces.
455
+ const res = await page.bidi.send('script.evaluate', {
456
+ expression, target: { context: page.context }, awaitPromise: true,
457
+ });
458
+ if (res.type === 'exception') {
459
+ return { ok: false, error: res.exceptionDetails?.text || 'eval error' };
460
+ }
461
+ return { ok: true, value: deserializeBiDi(res.result) };
426
462
  } catch (err) {
427
463
  return { ok: false, error: err.message || 'eval error' };
428
464
  }
@@ -46,7 +46,6 @@ const BIDI_KEYS = {
46
46
  * @param {boolean} [opts.hybrid=false] - Relaunch headed on a bot-challenge page and retry.
47
47
  * @param {boolean} [opts.headed=false] - Whether the browser was launched headed (skips hybrid fallback).
48
48
  * @param {?function(): Promise<{bidi: object, topContext: string}>} [opts.relaunchHeaded] - Hybrid relaunch hook (from connectFirefox).
49
- * @returns {Promise<object>} page object
50
49
  */
51
50
  export async function createFirefoxPage(bidi, opts = {}) {
52
51
  const defaultPruneMode = opts.pruneMode || 'act';
@@ -326,7 +325,8 @@ export async function createFirefoxPage(bidi, opts = {}) {
326
325
  }
327
326
  },
328
327
 
329
- async snapshot(pruneOpts) {
328
+ /** @param {import('./index.js').SnapshotOptions|false} [pruneOpts] */
329
+ async snapshot(pruneOpts = {}) {
330
330
  const root = await buildTree();
331
331
  if (!root) return '';
332
332
 
@@ -349,6 +349,7 @@ export async function createFirefoxPage(bidi, opts = {}) {
349
349
 
350
350
  async click(ref) { await pointerClick(ref); },
351
351
 
352
+ /** @param {string} ref @param {string} text @param {import('./index.js').TypeOptions} [typeOpts] */
352
353
  async type(ref, text, typeOpts = {}) {
353
354
  const { context, sharedId } = await resolveRef(ref);
354
355
  // Focus the field (and optionally clear it) in-page, then send real key
@@ -391,7 +392,8 @@ export async function createFirefoxPage(bidi, opts = {}) {
391
392
  * via BiDi storage.setCookie. Scoped to the URL host via the SHARED
392
393
  * scopedCookiesForUrl (same as the CDP path) — never the whole jar.
393
394
  */
394
- async injectCookies(url, cookieOpts) {
395
+ /** @param {string} url @param {import('./index.js').CookieOptions} [cookieOpts] */
396
+ async injectCookies(url, cookieOpts = {}) {
395
397
  if (incognito) return 0;
396
398
  lastInject = { url, cookieOpts }; // remember for a hybrid re-inject
397
399
  const cookies = scopedCookiesForUrl(url, { browser: cookieOpts?.browser });
@@ -575,7 +577,14 @@ export async function createFirefoxPage(bidi, opts = {}) {
575
577
  secure: !!c.secure,
576
578
  httpOnly: !!c.httpOnly,
577
579
  };
578
- if (c.sameSite && c.sameSite !== 'default') out.sameSite = c.sameSite;
580
+ // BiDi reports sameSite lowercase (strict|lax|none); the CDP saveState /
581
+ // Network.setCookies vocabulary is capitalized (Strict|Lax|None). The only
582
+ // loader for a state file is connect()'s storageState (CDP-only), which
583
+ // rejects a lowercase enum and silently drops every cookie — so capitalize
584
+ // here to keep the format truly symmetric and the round-trip working.
585
+ if (c.sameSite && c.sameSite !== 'default') {
586
+ out.sameSite = c.sameSite.charAt(0).toUpperCase() + c.sameSite.slice(1);
587
+ }
579
588
  if (c.expiry && c.expiry > 0) out.expires = c.expiry;
580
589
  return out;
581
590
  });
package/src/index.js CHANGED
@@ -162,6 +162,35 @@ export async function browse(url, opts = {}) {
162
162
  }
163
163
  }
164
164
 
165
+ /**
166
+ * The interactive page handle returned by {@link connect}. Inferred structurally
167
+ * from the returned object literals — no hand-maintained interface to drift.
168
+ *
169
+ * It is a union of the two engine page shapes (Chromium/CDP and Firefox/BiDi),
170
+ * which share every interaction method (`goto`, `snapshot`, `click`, `type`,
171
+ * `close`, …) but differ in their escape hatches — `cdp`/`createTab`/`dialogLog`
172
+ * on Chromium, `bidi`/`context` on Firefox. The shared methods dereference
173
+ * without narrowing; an engine-specific hatch requires knowing the engine
174
+ * (the default is Chromium), e.g. `if ('cdp' in page) page.cdp.send(...)`.
175
+ * @typedef {Awaited<ReturnType<typeof connect>>} Page
176
+ */
177
+
178
+ /**
179
+ * Options for `page.snapshot()`. Pass `false` instead of an object to skip
180
+ * pruning and return the raw ARIA tree.
181
+ * @typedef {{ mode?: 'act'|'browse'|'navigate'|'full'|'read' }} SnapshotOptions
182
+ */
183
+
184
+ /**
185
+ * Options for `page.type()`.
186
+ * @typedef {{ clear?: boolean, keyEvents?: boolean }} TypeOptions
187
+ */
188
+
189
+ /**
190
+ * Options for `page.injectCookies()`.
191
+ * @typedef {{ browser?: string }} CookieOptions
192
+ */
193
+
165
194
  /**
166
195
  * Connect to a browser for a long-lived interactive session.
167
196
  *
@@ -206,7 +235,10 @@ export async function browse(url, opts = {}) {
206
235
  * @param {'chromium'|'firefox'} [opts.engine='chromium'] - Browser engine.
207
236
  * 'firefox' drives over WebDriver BiDi (a separate transport / page object);
208
237
  * 'chromium' (default) uses CDP.
209
- * @returns {Promise<object>} Page handle with goto, snapshot, close
238
+ * @returns The interactive page handle — see the exported `Page` typedef. The
239
+ * return type is left uninferred here (no `{...}` tag) so tsc derives it
240
+ * structurally from the returned object literals; annotating it as `Page`
241
+ * would be a self-reference, since `Page` is `ReturnType<typeof connect>`.
210
242
  */
211
243
  export async function connect(opts = {}) {
212
244
  // Firefox is driven over WebDriver BiDi (CDP is deprecated there) — a
@@ -452,14 +484,16 @@ export async function connect(opts = {}) {
452
484
  refMap = new Map(); // refs from the pre-reload page are invalid
453
485
  },
454
486
 
455
- async injectCookies(url, cookieOpts) {
487
+ /** @param {string} url @param {CookieOptions} [cookieOpts] */
488
+ async injectCookies(url, cookieOpts = {}) {
456
489
  // No-op under incognito: callers (MCP goto, daemon) inject unconditionally,
457
490
  // so the gate has to live here, not just at the call site.
458
491
  if (incognito) return 0;
459
492
  return authenticate(page.session, url, { browser: cookieOpts?.browser });
460
493
  },
461
494
 
462
- async snapshot(pruneOpts) {
495
+ /** @param {SnapshotOptions|false} [pruneOpts] */
496
+ async snapshot(pruneOpts = {}) {
463
497
  const result = await ariaTree(page);
464
498
  refMap = result.refMap;
465
499
  const raw = formatTree(result.tree);
@@ -490,7 +524,8 @@ export async function connect(opts = {}) {
490
524
  await cdpClick(entry.session, entry.backendNodeId);
491
525
  },
492
526
 
493
- async type(ref, text, typeOpts) {
527
+ /** @param {string} ref @param {string} text @param {TypeOptions} [typeOpts] */
528
+ async type(ref, text, typeOpts = {}) {
494
529
  const entry = refMap.get(ref);
495
530
  if (!entry) throw new Error(`No element found for ref "${ref}"`);
496
531
  await cdpType(entry.session, entry.backendNodeId, text, typeOpts);
@@ -671,7 +706,8 @@ export async function connect(opts = {}) {
671
706
  tabBotBlocked = isChallengePage(tree, nodeCount);
672
707
  },
673
708
  get botBlocked() { return tabBotBlocked; },
674
- async injectCookies(url, cookieOpts) {
709
+ /** @param {string} url @param {CookieOptions} [cookieOpts] */
710
+ async injectCookies(url, cookieOpts = {}) {
675
711
  if (incognito) return 0;
676
712
  return authenticate(tab.session, url, { browser: cookieOpts?.browser });
677
713
  },
@@ -743,7 +779,6 @@ async function suppressPermissions(cdp) {
743
779
  * The navigation guard (`allowLocalUrls`/`blockPrivateNetwork`), `uploadDir`
744
780
  * sandbox, `incognito`, `proxy`, `viewport`, and `pruneMode` all apply.
745
781
  * @param {object} opts - connect() options ({ mode, proxy, binary, viewport, pruneMode, urlGuard, uploadDir, incognito, downloadPath, blockAds, blockUrls })
746
- * @returns {Promise<object>} Firefox page object
747
782
  */
748
783
  async function connectFirefox(opts) {
749
784
  const hybrid = opts.mode === 'hybrid';
package/types/daemon.d.ts CHANGED
@@ -10,6 +10,15 @@
10
10
  * @returns {string[]}
11
11
  */
12
12
  export function buildDaemonArgs(opts: object, absDir: string, initialUrl: string | undefined, cliPath: string): string[];
13
+ /**
14
+ * Convert a BiDi remote value ({type,value} — see script.evaluate) into the
15
+ * plain JS value CDP's `Runtime.evaluate({returnByValue:true})` yields, so an
16
+ * `eval` returns the same shape on both engines. BiDi serializes objects/arrays
17
+ * as entry lists ([[k,v],…] / [v,…]) rather than plain values; walk them back.
18
+ * @param {object} r - BiDi remote value
19
+ * @returns {*}
20
+ */
21
+ export function deserializeBiDi(r: object): any;
13
22
  /**
14
23
  * Wire Firefox/BiDi console + network capture onto the daemon's log arrays.
15
24
  * The BiDi analogue of the CDP `Runtime.consoleAPICalled` / `Network.*`
@@ -10,7 +10,6 @@
10
10
  * @param {boolean} [opts.hybrid=false] - Relaunch headed on a bot-challenge page and retry.
11
11
  * @param {boolean} [opts.headed=false] - Whether the browser was launched headed (skips hybrid fallback).
12
12
  * @param {?function(): Promise<{bidi: object, topContext: string}>} [opts.relaunchHeaded] - Hybrid relaunch hook (from connectFirefox).
13
- * @returns {Promise<object>} page object
14
13
  */
15
14
  export function createFirefoxPage(bidi: object, opts?: {
16
15
  pruneMode?: "act" | "browse" | "navigate" | "full" | "read" | undefined;
@@ -27,4 +26,75 @@ export function createFirefoxPage(bidi: object, opts?: {
27
26
  bidi: object;
28
27
  topContext: string;
29
28
  }>) | null | undefined;
30
- }): Promise<object>;
29
+ }): Promise<{
30
+ /** The BiDi escape hatch, analogous to connect()'s page.cdp. */
31
+ readonly bidi: any;
32
+ /** The active browsing-context id (getter so it tracks switchTab). */
33
+ readonly context: any;
34
+ /** Whether the last goto() landed on a bot-challenge page (parity w/ CDP). */
35
+ readonly botBlocked: boolean;
36
+ goto(url: any, timeout?: number): Promise<void>;
37
+ /** @param {import('./index.js').SnapshotOptions|false} [pruneOpts] */
38
+ snapshot(pruneOpts?: import("./index.js").SnapshotOptions | false): Promise<string>;
39
+ readable(): Promise<any>;
40
+ click(ref: any): Promise<void>;
41
+ /** @param {string} ref @param {string} text @param {import('./index.js').TypeOptions} [typeOpts] */
42
+ type(ref: string, text: string, typeOpts?: import("./index.js").TypeOptions): Promise<void>;
43
+ press(key: any): Promise<void>;
44
+ scroll(deltaY: any): Promise<void>;
45
+ hover(ref: any): Promise<void>;
46
+ /**
47
+ * Inject cookies from the user's real browser into this Firefox session,
48
+ * via BiDi storage.setCookie. Scoped to the URL host via the SHARED
49
+ * scopedCookiesForUrl (same as the CDP path) — never the whole jar.
50
+ */
51
+ /** @param {string} url @param {import('./index.js').CookieOptions} [cookieOpts] */
52
+ injectCookies(url: string, cookieOpts?: import("./index.js").CookieOptions): Promise<number>;
53
+ select(ref: any, value: any): Promise<void>;
54
+ drag(fromRef: any, toRef: any): Promise<void>;
55
+ upload(ref: any, files: any): Promise<void>;
56
+ goBack(): Promise<void>;
57
+ goForward(): Promise<void>;
58
+ reload(): Promise<void>;
59
+ screenshot(screenshotOpts?: {}): Promise<any>;
60
+ pdf(pdfOpts?: {}): Promise<any>;
61
+ tabs(): Promise<{
62
+ index: number;
63
+ url: any;
64
+ title: any;
65
+ context: any;
66
+ }[]>;
67
+ switchTab(index: any): Promise<void>;
68
+ waitFor(waitOpts?: {}): Promise<void>;
69
+ /**
70
+ * Wait until the network has been idle for `idle` ms, over BiDi
71
+ * network.* events. Parity with the CDP page.waitForNetworkIdle (Phase 2).
72
+ */
73
+ waitForNetworkIdle(idleOpts?: {}): Promise<void>;
74
+ /** Downloads that began in this session (Phase 4 — see setupDownloads). */
75
+ readonly downloads: any[];
76
+ dialogLog: any[];
77
+ /**
78
+ * Install a custom JS dialog handler, mirroring connect()'s page.onDialog.
79
+ * Called with `{ type, message, defaultPrompt }`; may return (sync or async)
80
+ * `{ accept: bool, promptText: string }` to override the auto-accept
81
+ * default. Pass null to restore default behavior.
82
+ */
83
+ onDialog(handler: any): void;
84
+ /**
85
+ * Persist cookies + localStorage to a JSON file (parity with the CDP
86
+ * saveState). Cookies come from BiDi storage.getCookies (whose value is a
87
+ * `{type,value}` object) and are flattened to the CDP-symmetric shape so the
88
+ * file format matches across engines. Written 0600 — it holds session
89
+ * tokens, so a multi-user host must not be able to read another user's.
90
+ */
91
+ saveState(filePath: any): Promise<void>;
92
+ /**
93
+ * Resolve when the active tab fires its next load event (parity with the
94
+ * CDP waitForNavigation → Page.loadEventFired). Scoped to topContext so a
95
+ * subframe load can't resolve it early. Falls back to a short settle delay
96
+ * for SPA navigations that fire no load event.
97
+ */
98
+ waitForNavigation(timeout?: number): Promise<void>;
99
+ close(): Promise<void>;
100
+ }>;
package/types/index.d.ts CHANGED
@@ -49,6 +49,31 @@ export function browse(url: string, opts?: {
49
49
  consent?: boolean | undefined;
50
50
  pruneMode?: "act" | "browse" | "navigate" | "full" | "read" | undefined;
51
51
  }): Promise<string>;
52
+ /**
53
+ * The interactive page handle returned by {@link connect}. Inferred structurally
54
+ * from the returned object literals — no hand-maintained interface to drift.
55
+ *
56
+ * It is a union of the two engine page shapes (Chromium/CDP and Firefox/BiDi),
57
+ * which share every interaction method (`goto`, `snapshot`, `click`, `type`,
58
+ * `close`, …) but differ in their escape hatches — `cdp`/`createTab`/`dialogLog`
59
+ * on Chromium, `bidi`/`context` on Firefox. The shared methods dereference
60
+ * without narrowing; an engine-specific hatch requires knowing the engine
61
+ * (the default is Chromium), e.g. `if ('cdp' in page) page.cdp.send(...)`.
62
+ * @typedef {Awaited<ReturnType<typeof connect>>} Page
63
+ */
64
+ /**
65
+ * Options for `page.snapshot()`. Pass `false` instead of an object to skip
66
+ * pruning and return the raw ARIA tree.
67
+ * @typedef {{ mode?: 'act'|'browse'|'navigate'|'full'|'read' }} SnapshotOptions
68
+ */
69
+ /**
70
+ * Options for `page.type()`.
71
+ * @typedef {{ clear?: boolean, keyEvents?: boolean }} TypeOptions
72
+ */
73
+ /**
74
+ * Options for `page.injectCookies()`.
75
+ * @typedef {{ browser?: string }} CookieOptions
76
+ */
52
77
  /**
53
78
  * Connect to a browser for a long-lived interactive session.
54
79
  *
@@ -93,7 +118,10 @@ export function browse(url: string, opts?: {
93
118
  * @param {'chromium'|'firefox'} [opts.engine='chromium'] - Browser engine.
94
119
  * 'firefox' drives over WebDriver BiDi (a separate transport / page object);
95
120
  * 'chromium' (default) uses CDP.
96
- * @returns {Promise<object>} Page handle with goto, snapshot, close
121
+ * @returns The interactive page handle — see the exported `Page` typedef. The
122
+ * return type is left uninferred here (no `{...}` tag) so tsc derives it
123
+ * structurally from the returned object literals; annotating it as `Page`
124
+ * would be a self-reference, since `Page` is `ReturnType<typeof connect>`.
97
125
  */
98
126
  export function connect(opts?: {
99
127
  mode?: "headed" | "headless" | "hybrid" | undefined;
@@ -116,7 +144,92 @@ export function connect(opts?: {
116
144
  incognito?: boolean | undefined;
117
145
  pruneMode?: "act" | "browse" | "navigate" | "full" | "read" | undefined;
118
146
  engine?: "chromium" | "firefox" | undefined;
119
- }): Promise<object>;
147
+ }): Promise<{
148
+ readonly bidi: any;
149
+ readonly context: any;
150
+ readonly botBlocked: boolean;
151
+ goto(url: any, timeout?: number): Promise<void>;
152
+ snapshot(pruneOpts?: import("./index.js").SnapshotOptions | false): Promise<string>;
153
+ readable(): Promise<any>;
154
+ click(ref: any): Promise<void>;
155
+ type(ref: string, text: string, typeOpts?: import("./index.js").TypeOptions): Promise<void>;
156
+ press(key: any): Promise<void>;
157
+ scroll(deltaY: any): Promise<void>;
158
+ hover(ref: any): Promise<void>;
159
+ injectCookies(url: string, cookieOpts?: import("./index.js").CookieOptions): Promise<number>;
160
+ select(ref: any, value: any): Promise<void>;
161
+ drag(fromRef: any, toRef: any): Promise<void>;
162
+ upload(ref: any, files: any): Promise<void>;
163
+ goBack(): Promise<void>;
164
+ goForward(): Promise<void>;
165
+ reload(): Promise<void>;
166
+ screenshot(screenshotOpts?: {}): Promise<any>;
167
+ pdf(pdfOpts?: {}): Promise<any>;
168
+ tabs(): Promise<{
169
+ index: number;
170
+ url: any;
171
+ title: any;
172
+ context: any;
173
+ }[]>;
174
+ switchTab(index: any): Promise<void>;
175
+ waitFor(waitOpts?: {}): Promise<void>;
176
+ waitForNetworkIdle(idleOpts?: {}): Promise<void>;
177
+ readonly downloads: any[];
178
+ dialogLog: any[];
179
+ onDialog(handler: any): void;
180
+ saveState(filePath: any): Promise<void>;
181
+ waitForNavigation(timeout?: number): Promise<void>;
182
+ close(): Promise<void>;
183
+ } | {
184
+ goto(url: any, timeout?: number): Promise<void>;
185
+ goBack(): Promise<void>;
186
+ goForward(): Promise<void>;
187
+ reload(reloadOpts?: {}): Promise<void>;
188
+ /** @param {string} url @param {CookieOptions} [cookieOpts] */
189
+ injectCookies(url: string, cookieOpts?: CookieOptions): Promise<number>;
190
+ /** @param {SnapshotOptions|false} [pruneOpts] */
191
+ snapshot(pruneOpts?: SnapshotOptions | false): Promise<string>;
192
+ readable(): Promise<any>;
193
+ click(ref: any): Promise<void>;
194
+ /** @param {string} ref @param {string} text @param {TypeOptions} [typeOpts] */
195
+ type(ref: string, text: string, typeOpts?: TypeOptions): Promise<void>;
196
+ scroll(deltaY: any): Promise<void>;
197
+ press(key: any): Promise<void>;
198
+ hover(ref: any): Promise<void>;
199
+ select(ref: any, value: any): Promise<void>;
200
+ drag(fromRef: any, toRef: any): Promise<void>;
201
+ upload(ref: any, files: any): Promise<void>;
202
+ pdf(pdfOpts?: {}): Promise<any>;
203
+ tabs(): Promise<any>;
204
+ switchTab(index: any): Promise<void>;
205
+ waitFor(waitOpts?: {}): Promise<void>;
206
+ saveState(filePath: any): Promise<void>;
207
+ readonly botBlocked: boolean;
208
+ dialogLog: any[];
209
+ /**
210
+ * Install a custom JS dialog handler. The handler is called with
211
+ * `{ type, message, defaultPrompt }` and may return (sync or async)
212
+ * `{ accept: bool, promptText: string }` to override the auto-accept
213
+ * default. Pass null to restore the default behavior.
214
+ */
215
+ onDialog(handler: any): void;
216
+ downloads: any[];
217
+ screenshot(screenshotOpts?: {}): Promise<any>;
218
+ waitForNavigation(timeout?: number): Promise<void>;
219
+ waitForNetworkIdle(idleOpts?: {}): Promise<void>;
220
+ /** Raw CDP session for escape hatch — getter so it survives hybrid fallback / tab swaps */
221
+ readonly cdp: any;
222
+ createTab(): Promise<{
223
+ goto(url: any, timeout?: number): Promise<void>;
224
+ readonly botBlocked: boolean;
225
+ /** @param {string} url @param {CookieOptions} [cookieOpts] */
226
+ injectCookies(url: string, cookieOpts?: CookieOptions): Promise<number>;
227
+ waitForNetworkIdle(idleOpts?: {}): Promise<void>;
228
+ cdp: any;
229
+ close(): Promise<void>;
230
+ }>;
231
+ close(): Promise<void>;
232
+ }>;
120
233
  /**
121
234
  * Apply Network.setBlockedURLs for ad/tracker blocking on a session.
122
235
  * Default list is on; pass blockAds:false to skip, blockUrls:[] to extend.
@@ -130,4 +243,36 @@ export function applyBlocklist(session: any, pageOpts: any): Promise<void>;
130
243
  /** Test-only: reset the warn-once flag. Not part of the public API. */
131
244
  export function _resetBlocklistWarning(): void;
132
245
  export { isChallengePage };
246
+ /**
247
+ * The interactive page handle returned by {@link connect}. Inferred structurally
248
+ * from the returned object literals — no hand-maintained interface to drift.
249
+ *
250
+ * It is a union of the two engine page shapes (Chromium/CDP and Firefox/BiDi),
251
+ * which share every interaction method (`goto`, `snapshot`, `click`, `type`,
252
+ * `close`, …) but differ in their escape hatches — `cdp`/`createTab`/`dialogLog`
253
+ * on Chromium, `bidi`/`context` on Firefox. The shared methods dereference
254
+ * without narrowing; an engine-specific hatch requires knowing the engine
255
+ * (the default is Chromium), e.g. `if ('cdp' in page) page.cdp.send(...)`.
256
+ */
257
+ export type Page = Awaited<ReturnType<typeof connect>>;
258
+ /**
259
+ * Options for `page.snapshot()`. Pass `false` instead of an object to skip
260
+ * pruning and return the raw ARIA tree.
261
+ */
262
+ export type SnapshotOptions = {
263
+ mode?: "act" | "browse" | "navigate" | "full" | "read";
264
+ };
265
+ /**
266
+ * Options for `page.type()`.
267
+ */
268
+ export type TypeOptions = {
269
+ clear?: boolean;
270
+ keyEvents?: boolean;
271
+ };
272
+ /**
273
+ * Options for `page.injectCookies()`.
274
+ */
275
+ export type CookieOptions = {
276
+ browser?: string;
277
+ };
133
278
  import { isChallengePage } from './challenge.js';