barebrowse 0.21.0 → 0.23.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,55 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.23.0] - 2026-10-14
4
+
5
+ ### Added
6
+
7
+ - **barebrowse cleans up its own old output files.** Snapshots, screenshots,
8
+ articles and logs piled up in `.barebrowse/` forever. Files older than 7 days
9
+ are now removed once at MCP server start and once at `barebrowse open`
10
+ (honours `--output-dir`). Only barebrowse's exact timestamped names match, so
11
+ `session.json`, `state-*.json` (saved logins) and your own files are never
12
+ touched.
13
+
14
+ ### Fixed
15
+
16
+ - **An absurd `wait_for` timeout no longer resets the page.** A timeout above
17
+ `setTimeout`'s maximum made the outer deadline overflow and fire after about
18
+ 1ms; the resulting transient "timed out" error then wiped the page. The
19
+ deadline is now capped at the maximum.
20
+
21
+ ## [0.22.0] - 2026-10-14
22
+
23
+ ### Added
24
+
25
+ - **The MCP server releases its browser after an idle TTL.** A session left
26
+ open kept a Chromium/Firefox process and profile dir alive indefinitely.
27
+ `BAREBROWSE_IDLE_MINUTES` (default 15, `0` = off; blank or invalid falls back
28
+ to the default, values are capped at `setTimeout`'s maximum) closes the
29
+ browser once no tool call has arrived for that long. The timer pauses while a
30
+ call is in flight, so a long-running call is never cut off, and the next call
31
+ simply opens a fresh browser.
32
+
33
+ ### Fixed
34
+
35
+ - **MCP transient-error resets no longer orphan the running browser.** Five reset
36
+ sites set the page to `null` without closing it, so the next call launched a
37
+ second browser while the first kept running. They now go through
38
+ `resetPage()`, which closes the browser before forgetting it.
39
+ - **`close()` always runs hard cleanup, even when the browser is dead or hung.**
40
+ The polite tab close had no timeout and ran before cleanup, so a killed or
41
+ unresponsive browser leaked its process and temp profile dir. The polite close
42
+ is now bounded and cleanup runs in a `finally`, on both engines.
43
+ - **An ordinary `wait_for` timeout no longer resets the page.** The MCP retry
44
+ layer treated any "timed out" error as transient, which also matched
45
+ `waitFor`'s own not-found message, so a missed wait tore down the browser.
46
+ That message is now excluded.
47
+ - **`wait_for` with `timeout` of 60s or more is no longer cut off at 60s.** The
48
+ retry layer's fixed 60s outer deadline fired first and was treated as
49
+ transient, resetting the page and browser. The outer deadline is now
50
+ `max(60s, requested timeout + 5s)`.
51
+ - **The publish workflow now fails when `package-lock.json`'s version drifts from `package.json`.** npm writes that field on install, so a release that bumps `package.json` without running one leaves it behind — and nothing caught it: `npm ci` fails when the lockfile's *dependency* entries disagree, but never checks the lockfile's copy of the project's own version. `scripts/check-lockfile.mjs` (`npm run check:lockfile`) compares both places npm writes it and runs in the publish workflow. No lockfile is not a failure.
52
+
3
53
  ## [0.21.0] - 2026-09-17
4
54
 
5
55
  ### Added
package/README.md CHANGED
@@ -50,7 +50,7 @@ barebrowse click 8 # Click element
50
50
  barebrowse close # End session
51
51
  ```
52
52
 
53
- Outputs go to `.barebrowse/` as files -- agents read them with their file tools, no token waste in tool responses.
53
+ Outputs go to `.barebrowse/` as files -- agents read them with their file tools, no token waste in tool responses. Output files older than 7 days are auto-removed at session start; saved state files (`state-*.json`) are kept.
54
54
 
55
55
  **Teach your agent the commands** by installing the skill file (a markdown reference the agent reads as context). The CLI tool itself still needs `npm install barebrowse` -- the skill just teaches the agent how to use it.
56
56
 
@@ -98,6 +98,8 @@ Or manually add to your config (`claude_desktop_config.json`, `.cursor/mcp.json`
98
98
 
99
99
  MCP tools: `browse`, `goto`, `snapshot`, `readable`, `click`, `type`, `press`, `scroll`, `hover`, `select`, `back`, `forward`, `reload`, `drag`, `upload`, `pdf`, `screenshot`, `wait_for`, `tabs`, `capabilities` (reports the active engine — chromium or firefox — and what the session can do; no side effects). Plus `assess` (privacy scan) if [wearehere](https://github.com/hamr0/wearehere) is installed. Plus opt-in `eval` (`BAREBROWSE_MCP_EVAL=1`) — runs JS in the authenticated session, off by default because it can read cookies/localStorage. Session runs in hybrid mode with automatic cookie injection. Per-tool timeouts (goto/reload/wait_for 60s, back/forward 30s, interactive ops 15s, pdf/screenshot/upload 45s) with auto-retry on transient failures (idempotent only — mutating tools fail loudly to avoid double-submits).
100
100
 
101
+ **Idle release.** An MCP server can outlive its conversation, so it closes its browser after `BAREBROWSE_IDLE_MINUTES` (default `15`, `0` = never, blank/invalid = default, fractional allowed, capped at ~24.8 days) with no tool call in flight. The next call opens a fresh browser (a new job, not a resume — a page left open, e.g. a solved captcha in the headed window, is gone). A transient browser error also closes the broken browser rather than orphaning it; an ordinary `wait_for` timeout does not reset the page.
102
+
101
103
  `browse` and `snapshot` accept `pruneMode: 'act'|'read'`. `act` (default) keeps interactive elements — best for clicking/filling. `read` keeps paragraphs, headings, and long text — best for articles, docs, and content extraction. If act-mode collapses a content-heavy page near-totally, the snapshot includes a `hint: …` line suggesting `pruneMode='read'` so the agent doesn't bail to a separate HTTP fetch.
102
104
 
103
105
  `npx barebrowse doctor` reports the runtime environment first — default engine/mode, installed Chromium/Firefox binaries, cookie sources, and any live session's engine + capabilities — then scans every known MCP config location and flags scope conflicts. `npx barebrowse install --force` overwrites an existing entry pointing at a different endpoint.
@@ -96,7 +96,7 @@ const snapshot = await browse('https://example.com', {
96
96
  | `createTab()` | -- | tab handle | New tab in same browser. Returns `{ goto, botBlocked, injectCookies, waitForNetworkIdle, cdp, close }`. Tab close doesn't affect session. |
97
97
  | `engine` | -- | `'chromium'`\|`'firefox'` | Which engine drives this session. Always readable (both shapes carry it); a typed literal, so it also narrows the union: `if (page.engine === 'firefox') page.bidi.…`. |
98
98
  | `capabilities` | -- | object | Feature introspection: `{ engine, mode, attach, escapeHatch, reloadIgnoreCache, downloads, stealth, cookieInjection }`. Ask "what can this session do?" without probing for `cdp`/`bidi`. All fields are launch-fixed except `stealth`, which is a live getter reflecting the session's current headed/headless state (it can flip mid-session after a hybrid bot-challenge relaunch). `reloadIgnoreCache` is false on Firefox (upstream BiDi gap); `downloads`/`stealth`/`cookieInjection` reflect mode + attach + incognito. |
99
- | `close()` | -- | void | Close page, disconnect CDP, kill browser (if headless) |
99
+ | `close()` | -- | void | Close page, disconnect CDP, kill browser (if headless). The tab close is bounded (2.5s), so a dead/hung browser still gets killed and its profile + owned download dir removed. Attach mode never kills your browser |
100
100
 
101
101
  **connect() options** (in addition to mode/port/consent):
102
102
  - `engine: 'chromium'|'firefox'` — Browser engine. Default `chromium` (CDP). When you don't pass `engine`, `connect()` prefers Chromium but **falls back to Firefox** (with a one-line `console.warn` to stderr) if no Chromium browser is installed; if neither engine is installed it throws naming both. An **explicit** `engine` is always honored — it errors if that engine's binary is missing rather than silently switching. Attach mode (`port`) is Chromium/CDP-only and never falls back. `firefox` drives Firefox over WebDriver BiDi (CDP is deprecated there) — a separate transport with the same `page.*` API; the ARIA snapshot is reconstructed in-page since BiDi has no `getFullAXTree`. Consent auto-dismiss and stealth (headless anti-detection) work on Firefox as of v0.16.0; the CLI daemon's console/network capture and `waitForNetworkIdle` work as of v0.17.0; ad/tracker blocking (`blockAds`/`blockUrls`) and JS dialog handling (`dialogLog`/`onDialog`) work as of Phase 3; `hybrid` mode, `saveState`, `waitForNavigation`, and download tracking (`page.downloads`) work as of Phase 4. The only remaining Firefox gap is `reload()` ignoring `ignoreCache` (upstream BiDi limitation).
@@ -246,7 +246,7 @@ Action tools (click, type, press, scroll, hover, goto, back, forward, reload, dr
246
246
 
247
247
  ## CLI session mode
248
248
 
249
- For coding agents (Claude Code, Copilot, Cursor) and quick interactive testing. Commands output files to `.barebrowse/` -- agents read them with file tools, avoiding token waste in tool responses.
249
+ For coding agents (Claude Code, Copilot, Cursor) and quick interactive testing. Commands output files to `.barebrowse/` -- agents read them with file tools, avoiding token waste in tool responses. Output files older than 7 days are auto-removed at session start (CLI `open` and MCP startup); saved state files (`state-*.json`) are kept.
250
250
 
251
251
  ```bash
252
252
  barebrowse open https://example.com # Start daemon + navigate
@@ -295,6 +295,8 @@ barebrowse ships an MCP server for direct use with Claude Desktop, Cursor, or an
295
295
 
296
296
  19 core tools: `browse` (one-shot), `goto`, `snapshot`, `readable`, `click`, `type`, `press`, `scroll`, `hover`, `select`, `back`, `forward`, `reload`, `drag`, `upload`, `pdf`, `screenshot`, `wait_for`, `tabs`. Plus `assess` (privacy scan) if `wearehere` is installed (`npm install wearehere`). Plus the **opt-in `eval` tool** gated by `BAREBROWSE_MCP_EVAL=1` (default OFF) — `Runtime.evaluate` in the user's authenticated session can read cookies/localStorage and hit any same-origin endpoint, so opt-in only.
297
297
 
298
+ **Idle release:** the MCP server closes its browser after `BAREBROWSE_IDLE_MINUTES` of no tool calls (default `15`; `0` = off; blank/invalid = default; capped at ~24.8 days; calls in flight postpone it). The next call opens a fresh browser — page state (open tabs, a solved captcha) is not resumed. Transient browser errors close the broken browser instead of orphaning it; a `wait_for` that merely times out keeps the page (its outer deadline is `max(60s, timeout+5s)`).
299
+
298
300
  Action tools return `'ok'` -- the agent calls `snapshot` explicitly to observe. This avoids double-token output since MCP tool calls are cheap to chain.
299
301
 
300
302
  `browse`, `snapshot`, and `readable` accept a `maxChars` param (default 30000). If the output exceeds the limit it's saved to `.barebrowse/` and a short message with the file path is returned instead (`page-<timestamp>.yml` for snapshots, `article-<timestamp>.txt` for `readable`). `screenshot` always saves to `.barebrowse/screenshot-<timestamp>.{png,jpeg,webp}` and returns the file path (raw base64 in a JSON-RPC response would blow `maxChars`). `tabs` returns the JSON array, or with `switchTo: N` it switches and returns `'ok'`. All files MCP writes are owner-only (`0600` in a `0700` dir) — they can hold authenticated page content, so they're not world-readable on a shared host.
package/mcp-server.js CHANGED
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { browse, connect } from './src/index.js';
14
14
  import { formatReadable } from './src/readable.js';
15
+ import { cleanOld } from './src/output-clean.js';
15
16
  import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
16
17
  import { join, dirname } from 'node:path';
17
18
  import { pathToFileURL, fileURLToPath } from 'node:url';
@@ -63,6 +64,8 @@ try {
63
64
 
64
65
  function isTransient(err) {
65
66
  const m = err.message || '';
67
+ // A wait_for that simply didn't find its text is a normal result, not a broken browser.
68
+ if (m.startsWith('waitFor timed out')) return false;
66
69
  return m.includes('WebSocket') || m.includes('Target closed') || m.includes('Session closed')
67
70
  || m.includes('CDP') || m.includes('Timeout waiting for CDP event') || m.includes('timed out');
68
71
  }
@@ -95,7 +98,7 @@ async function withRetry(fn, timeoutMs, { retry = true } = {}) {
95
98
  } catch (err) {
96
99
  if (!isTransient(err)) throw err;
97
100
  // Transient failure — reset session so the next request gets a fresh page.
98
- _page = null;
101
+ resetPage();
99
102
  if (!retry) throw err;
100
103
  return await attempt();
101
104
  }
@@ -118,6 +121,52 @@ export function saveSnapshot(text, { prefix = 'page', ext = 'yml' } = {}) {
118
121
  let _page = null;
119
122
  let _pageConnecting = null;
120
123
 
124
+ /**
125
+ * Forget the current session AND close its browser. A bare `_page = null`
126
+ * orphaned the browser (still running, holding GBs) — the next getPage() just
127
+ * launched a second one. Fire-and-forget: callers are on error paths.
128
+ */
129
+ function resetPage() {
130
+ const p = _page;
131
+ _page = null;
132
+ if (p) p.close().catch(() => {});
133
+ }
134
+
135
+ // setTimeout's max delay; larger values overflow and fire after ~1ms.
136
+ const MAX_TIMER_MS = 2 ** 31 - 1;
137
+
138
+ // Idle TTL: a server can outlive its conversation by days, holding a browser
139
+ // (GBs) the whole time. After BAREBROWSE_IDLE_MINUTES (default 15, 0 = off)
140
+ // with no tools/call in flight, release it; the next call opens a fresh one.
141
+ // Capped at setTimeout's max (2^31-1 ms, ~24.8 days): beyond it Node fires after 1ms.
142
+ /**
143
+ * Outer deadline for wait_for: follows the requested wait (page.waitFor
144
+ * defaults to 30000) plus 5s slack, never below TIMEOUTS.wait_for. Otherwise a
145
+ * wait >= the fixed deadline trips withRetry's transient "timed out" and resets
146
+ * the page.
147
+ */
148
+ export function waitForDeadline(timeout) {
149
+ return Math.min(Math.max(TIMEOUTS.wait_for, (timeout || 30000) + 5000), MAX_TIMER_MS);
150
+ }
151
+
152
+ export function idleMs(raw) {
153
+ const DEFAULT = 15 * 60_000;
154
+ if (raw === undefined || String(raw).trim() === '') return DEFAULT;
155
+ const n = Number(raw);
156
+ if (!Number.isFinite(n) || n < 0) return DEFAULT;
157
+ return Math.min(n * 60_000, MAX_TIMER_MS);
158
+ }
159
+ const IDLE_MS = idleMs(process.env.BAREBROWSE_IDLE_MINUTES);
160
+ let _inflight = 0;
161
+ let _idleTimer = null;
162
+
163
+ function armIdle() {
164
+ clearTimeout(_idleTimer);
165
+ if (!IDLE_MS || _inflight) return;
166
+ _idleTimer = setTimeout(() => { if (!_inflight && _page) resetPage(); }, IDLE_MS);
167
+ _idleTimer.unref();
168
+ }
169
+
121
170
  /**
122
171
  * The engine + mode this server is configured to use, derived from env WITHOUT
123
172
  * launching a browser. Both engines ship in the library; which one this server
@@ -558,7 +607,7 @@ async function handleToolCall(name, args) {
558
607
  const page = await getPage();
559
608
  await page.waitFor({ text: args.text, selector: args.selector, timeout: args.timeout });
560
609
  return 'ok';
561
- }, TIMEOUTS.wait_for, { retry: false });
610
+ }, waitForDeadline(args.timeout), { retry: false });
562
611
  case 'tabs': return withRetry(async () => {
563
612
  const page = await getPage();
564
613
  if (typeof args.switchTo === 'number') {
@@ -639,7 +688,7 @@ async function handleToolCall(name, args) {
639
688
  } catch (err) {
640
689
  clearTimeout(timer);
641
690
  await tab.close().catch(() => {});
642
- if (isTransient(err)) _page = null;
691
+ if (isTransient(err)) resetPage();
643
692
  throw err;
644
693
  }
645
694
  } finally {
@@ -693,17 +742,22 @@ async function handleMessage(msg) {
693
742
 
694
743
  if (method === 'tools/call') {
695
744
  const { name, arguments: args } = params;
745
+ _inflight++;
746
+ clearTimeout(_idleTimer);
696
747
  try {
697
748
  const result = await handleToolCall(name, args || {});
698
749
  return jsonrpcResponse(id, {
699
750
  content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result) }],
700
751
  });
701
752
  } catch (err) {
702
- if (isTransient(err)) _page = null;
753
+ if (isTransient(err)) resetPage();
703
754
  return jsonrpcResponse(id, {
704
755
  content: [{ type: 'text', text: `Error: ${err.message}` }],
705
756
  isError: true,
706
757
  });
758
+ } finally {
759
+ _inflight--;
760
+ armIdle();
707
761
  }
708
762
  }
709
763
 
@@ -721,6 +775,7 @@ async function handleMessage(msg) {
721
775
  // runStdio() explicitly. Tests import TIMEOUTS/TOOLS without calling it.
722
776
 
723
777
  export function runStdio() {
778
+ cleanOld(OUTPUT_DIR);
724
779
  // One-line startup banner to stderr (stderr because stdout is the JSON-RPC
725
780
  // channel — must not contain non-JSON-RPC bytes). Captured by Claude Code's
726
781
  // MCP log, makes "I added barebrowse twice and got the wrong one" issues
@@ -759,8 +814,8 @@ export function runStdio() {
759
814
 
760
815
  // Prevent unhandled rejections and uncaught exceptions from crashing the server.
761
816
  // Browser OOM/crash rejects all pending CDP promises — some may not be awaited.
762
- process.on('unhandledRejection', () => { _page = null; });
763
- process.on('uncaughtException', () => { _page = null; });
817
+ process.on('unhandledRejection', () => { resetPage(); });
818
+ process.on('uncaughtException', () => { resetPage(); });
764
819
 
765
820
  // Clean up on exit
766
821
  process.on('SIGINT', async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebrowse",
3
- "version": "0.21.0",
3
+ "version": "0.23.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",
@@ -43,7 +43,8 @@
43
43
  "test:integration": "node --test test/integration/*.test.js",
44
44
  "typecheck": "tsc --noEmit",
45
45
  "build:types": "tsc",
46
- "prepublishOnly": "npm run build:types"
46
+ "prepublishOnly": "npm run build:types",
47
+ "check:lockfile": "node scripts/check-lockfile.mjs"
47
48
  },
48
49
  "keywords": [
49
50
  "browser",
package/src/daemon.js CHANGED
@@ -12,6 +12,7 @@ import { randomBytes, timingSafeEqual } from 'node:crypto';
12
12
  import { join, resolve } from 'node:path';
13
13
  import { connect } from './index.js';
14
14
  import { formatReadable } from './readable.js';
15
+ import { cleanOld } from './output-clean.js';
15
16
 
16
17
  /** Owner-only file write helper — daemon artifacts can hold authenticated content. */
17
18
  function writeFilePrivate(path, data) {
@@ -210,6 +211,7 @@ export async function startDaemon(opts, outputDir, initialUrl) {
210
211
  export async function runDaemon(opts, outputDir, initialUrl) {
211
212
  const absDir = resolve(outputDir);
212
213
  mkdirSync(absDir, { recursive: true, mode: 0o700 });
214
+ cleanOld(absDir);
213
215
 
214
216
  // Per-session auth token. The daemon binds to loopback, but loopback is
215
217
  // shared across local users — without a token any local user/process could
@@ -25,6 +25,7 @@ import { dismissConsentFirefox } from './consent-firefox.js';
25
25
  import { waitForNetworkIdleBiDi } from './network-idle.js';
26
26
  import { decideDialog, dialogLogEntry } from './dialog.js';
27
27
  import { isChallengePage, countNodes } from './challenge.js';
28
+ import { withTimeout } from './with-timeout.js';
28
29
 
29
30
  /** BiDi/WebDriver normalized key values for named keys (U+E000 block). */
30
31
  const BIDI_KEYS = {
@@ -174,17 +175,6 @@ export async function createFirefoxPage(bidi, opts = {}) {
174
175
  });
175
176
  }
176
177
 
177
- /**
178
- * Reject if `p` doesn't settle within `ms`. BiDi commands have no built-in
179
- * timeout, so a navigate/reload/traverse whose `wait:'complete'` never fires
180
- * (a page that never loads) would otherwise hang the call forever.
181
- */
182
- function withTimeout(p, ms, label) {
183
- let timer;
184
- const t = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`${label} timed out after ${ms}ms`)), ms); });
185
- return Promise.race([p, t]).finally(() => clearTimeout(timer));
186
- }
187
-
188
178
  // Download tracking, parity with the CDP `page.downloads` array. Firefox
189
179
  // downloads land in `downloadDir` (a throwaway dir the caller sets via launch
190
180
  // prefs — see connectFirefox / firefox.js), so `savedPath` is a real path the
@@ -642,8 +632,9 @@ export async function createFirefoxPage(bidi, opts = {}) {
642
632
  },
643
633
 
644
634
  async close() {
645
- try { await bidi.send('browsingContext.close', { context: topContext }); } catch {}
646
- bidi.close();
635
+ // Best-effort and bounded: a hung browser must not block the hard cleanup.
636
+ try { await withTimeout(bidi.send('browsingContext.close', { context: topContext }), 2500, 'close'); } catch {}
637
+ try { bidi.close(); } catch {}
647
638
  },
648
639
  };
649
640
 
package/src/index.js CHANGED
@@ -25,6 +25,7 @@ import { resolveBlocklistPatterns } from './blocklist.js';
25
25
  import { waitForNetworkIdle } from './network-idle.js';
26
26
  import { decideDialog, dialogLogEntry } from './dialog.js';
27
27
  import { isChallengePage } from './challenge.js';
28
+ import { withTimeout } from './with-timeout.js';
28
29
  import { readable as extractReadable } from './readable.js';
29
30
  import { assertNavigable, assertUploadAllowed } from './url-guard.js';
30
31
  import { join as pathJoin } from 'node:path';
@@ -809,16 +810,21 @@ export async function connect(opts = {}) {
809
810
  },
810
811
 
811
812
  async close() {
812
- await cdp.send('Target.closeTarget', { targetId: page.targetId });
813
- cdp.close();
814
- await cleanupBrowser(browser);
815
- // If we created the download dir ourselves, clean it up too. Caller-
816
- // supplied opts.downloadPath stays — the caller owns the lifecycle.
817
- if (ownedDownloadDir) {
818
- try {
819
- const { rmSync } = await import('node:fs');
820
- rmSync(ownedDownloadDir, { recursive: true, force: true });
821
- } catch {}
813
+ // Polite tab close is best-effort and bounded: a dead or hung browser
814
+ // must not skip the hard cleanup below (the profile dir / process leak).
815
+ try { await withTimeout(cdp.send('Target.closeTarget', { targetId: page.targetId }), 2500, 'close'); } catch {}
816
+ try { cdp.close(); } catch {}
817
+ try {
818
+ await cleanupBrowser(browser); // no-op in attach mode (process: null)
819
+ } finally {
820
+ // If we created the download dir ourselves, clean it up too. Caller-
821
+ // supplied opts.downloadPath stays — the caller owns the lifecycle.
822
+ if (ownedDownloadDir) {
823
+ try {
824
+ const { rmSync } = await import('node:fs');
825
+ rmSync(ownedDownloadDir, { recursive: true, force: true });
826
+ } catch {}
827
+ }
822
828
  }
823
829
  },
824
830
  };
@@ -929,13 +935,19 @@ async function connectFirefox(opts) {
929
935
  });
930
936
  const closePage = page.close.bind(page);
931
937
  page.close = async () => {
932
- await closePage();
933
- await cleanupFirefox(browser); // `browser` tracks the relaunched one if hybrid fired
934
- if (ownedDownloadDir) {
938
+ try {
939
+ await closePage();
940
+ } finally {
935
941
  try {
936
- const { rmSync } = await import('node:fs');
937
- rmSync(ownedDownloadDir, { recursive: true, force: true });
938
- } catch { /* best-effort reap */ }
942
+ await cleanupFirefox(browser); // `browser` tracks the relaunched one if hybrid fired
943
+ } finally {
944
+ if (ownedDownloadDir) {
945
+ try {
946
+ const { rmSync } = await import('node:fs');
947
+ rmSync(ownedDownloadDir, { recursive: true, force: true });
948
+ } catch { /* best-effort reap */ }
949
+ }
950
+ }
939
951
  }
940
952
  };
941
953
  return page;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * output-clean.js -- Age-based cleanup of barebrowse's own output files.
3
+ *
4
+ * Matches only `<prefix>-<timestamp>.<ext>` files barebrowse itself writes.
5
+ * session.json, state-*.json (deliberate saved logins) and any other file are never touched.
6
+ */
7
+
8
+ import { readdirSync, statSync, unlinkSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+
11
+ // toISOString() with [:.] -> '-': YYYY-MM-DDTHH-MM-SS-mmmZ. Exact, so a user's own
12
+ // `screenshot-2026-01-01.png` in a shared --output-dir is never matched.
13
+ const STAMP = '\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z';
14
+ const OURS = new RegExp(
15
+ `^(?:page-${STAMP}\\.(?:yml|pdf)|screenshot-${STAMP}\\.(?:png|jpeg|webp)|article-${STAMP}\\.txt|(?:console|network|dialogs)-${STAMP}\\.json)$`,
16
+ );
17
+
18
+ /**
19
+ * Delete barebrowse output files older than `days` in `dir` (non-recursive).
20
+ * Never throws; a missing dir or any per-file error is ignored.
21
+ * @param {string} dir
22
+ * @param {number} [days]
23
+ * @param {number} [now] - epoch ms, injectable for tests
24
+ */
25
+ export function cleanOld(dir, days = 7, now = Date.now()) {
26
+ try {
27
+ const cutoff = now - days * 86400000;
28
+ for (const name of readdirSync(dir)) {
29
+ if (!OURS.test(name)) continue;
30
+ try {
31
+ const path = join(dir, name);
32
+ const st = statSync(path);
33
+ if (st.isFile() && st.mtimeMs < cutoff) unlinkSync(path);
34
+ } catch {}
35
+ }
36
+ } catch {}
37
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Reject if `p` doesn't settle within `ms`. BiDi commands have no built-in
3
+ * timeout, so a navigate/reload/traverse whose `wait:'complete'` never fires
4
+ * (a page that never loads) would otherwise hang the call forever. Also bounds
5
+ * the best-effort tab close on both engines.
6
+ * @template T
7
+ * @param {Promise<T>} p
8
+ * @param {number} ms
9
+ * @param {string} label
10
+ * @returns {Promise<T>}
11
+ */
12
+ export function withTimeout(p, ms, label) {
13
+ let timer;
14
+ const t = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`${label} timed out after ${ms}ms`)), ms); });
15
+ return Promise.race([p, t]).finally(() => clearTimeout(timer));
16
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Delete barebrowse output files older than `days` in `dir` (non-recursive).
3
+ * Never throws; a missing dir or any per-file error is ignored.
4
+ * @param {string} dir
5
+ * @param {number} [days]
6
+ * @param {number} [now] - epoch ms, injectable for tests
7
+ */
8
+ export function cleanOld(dir: string, days?: number, now?: number): void;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Reject if `p` doesn't settle within `ms`. BiDi commands have no built-in
3
+ * timeout, so a navigate/reload/traverse whose `wait:'complete'` never fires
4
+ * (a page that never loads) would otherwise hang the call forever. Also bounds
5
+ * the best-effort tab close on both engines.
6
+ * @template T
7
+ * @param {Promise<T>} p
8
+ * @param {number} ms
9
+ * @param {string} label
10
+ * @returns {Promise<T>}
11
+ */
12
+ export function withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T>;