@browserless.io/cli 0.5.2 → 0.6.1

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +93 -75
  2. package/README.md +73 -19
  3. package/build/agent/ws-client.js +1 -1
  4. package/build/api/client.js +1 -1
  5. package/build/api/profiles.js +1 -1
  6. package/build/api/upload.js +1 -1
  7. package/build/auth/disclaimer.js +7 -3
  8. package/build/auth/server-url.js +2 -2
  9. package/build/browsers/discover.js +5 -5
  10. package/build/capture/cdp-pipe.js +1 -0
  11. package/build/capture/cdp.js +3 -3
  12. package/build/capture/cleanup.js +1 -0
  13. package/build/capture/copy-profile.js +1 -1
  14. package/build/capture/index.js +1 -1
  15. package/build/capture/launch.js +7 -7
  16. package/build/capture/profile-lock.js +5 -5
  17. package/build/cli-utils/agent-format.js +5 -3
  18. package/build/cli-utils/capture-runner.js +7 -26
  19. package/build/cli-utils/client.js +2 -2
  20. package/build/cli.js +4 -4
  21. package/build/commands/agent/chat.js +12 -9
  22. package/build/commands/auth/login.js +1 -1
  23. package/build/commands/profile/delete.js +1 -1
  24. package/build/commands/profile/launch.js +3 -3
  25. package/build/commands/profile/list.js +1 -1
  26. package/build/commands/profile/refresh.js +2 -2
  27. package/build/commands/profile/rename.js +1 -1
  28. package/build/commands/profile/show.js +1 -1
  29. package/build/commands/profile/sources/add.js +1 -1
  30. package/build/commands/profile/upload.js +2 -2
  31. package/build/errors.js +1 -1
  32. package/build/regions.js +1 -1
  33. package/build/telemetry/api.js +1 -1
  34. package/build/telemetry/index.js +2 -2
  35. package/build/utils/interrupt.js +1 -0
  36. package/build/utils/spinner.js +3 -3
  37. package/build/utils/terminal.js +3 -0
  38. package/build/version.js +1 -1
  39. package/package.json +20 -10
package/CHANGELOG.md CHANGED
@@ -1,142 +1,160 @@
1
1
  # Changelog
2
2
 
3
- ## [0.5.2](https://github.com/browserless/browserless-cli/compare/v0.5.1...v0.5.2) (2026-10-30)
3
+ ## 0.6.1 (2026-11-13)
4
4
 
5
5
 
6
6
  ### Bug Fixes
7
7
 
8
- * PLT-1989 reject authenticated API redirects ([#142](https://github.com/browserless/browserless-cli/issues/142)) ([211decc](https://github.com/browserless/browserless-cli/commit/211decc03f01896a8881c031f14a3ed56e4b6279))
9
- * PLT-1990 isolate capture smoke state and replay ([#143](https://github.com/browserless/browserless-cli/issues/143)) ([6c4f352](https://github.com/browserless/browserless-cli/commit/6c4f3520ee46213159001a528b5126fd12d88ccc))
8
+ * bound decoded API responses and body deadlines
9
+ * capture over a private pipe instead of a local debugging port, and stop the headless browser and delete the temporary profile copy when a capture is interrupted
10
+ * escape remote agent terminal output
11
+ * escape terminal controls in error and profile displays
12
+ * pin custom browser registration paths
10
13
 
11
- ## [0.5.1](https://github.com/browserless/browserless-cli/compare/v0.5.0...v0.5.1) (2026-10-22)
14
+ ## 0.6.0 (2026-11-05)
15
+
16
+
17
+ ### Features
18
+
19
+ * record failure category, code and HTTP status in CLI telemetry
20
+
21
+ ## 0.5.2 (2026-10-30)
22
+
23
+
24
+ ### Bug Fixes
25
+
26
+ * reject authenticated API redirects
27
+ * isolate capture smoke state and replay
28
+
29
+ ## 0.5.1 (2026-10-22)
12
30
 
13
31
 
14
32
  ### Bug Fixes
15
33
 
16
- * AUTO-640 detect the Windows cookie-file lock during profile capture ([#134](https://github.com/browserless/browserless-cli/issues/134)) ([3a2ca62](https://github.com/browserless/browserless-cli/commit/3a2ca628558976e3444362d368bab2b27dc8ff8d))
34
+ * detect the Windows cookie-file lock during profile capture
17
35
 
18
- ## [0.5.0](https://github.com/browserless/browserless-cli/compare/v0.4.2...v0.5.0) (2026-10-16)
36
+ ## 0.5.0 (2026-10-16)
19
37
 
20
38
 
21
39
  ### Features
22
40
 
23
- * AUTO-303 add profile terms command ([#130](https://github.com/browserless/browserless-cli/issues/130)) ([3472d1f](https://github.com/browserless/browserless-cli/commit/3472d1fd8dcb23f59f3c0d4501399d9cc49ff0dc))
41
+ * add profile terms command
24
42
 
25
- ## [0.4.2](https://github.com/browserless/browserless-cli/compare/v0.4.1...v0.4.2) (2026-10-13)
43
+ ## 0.4.2 (2026-10-13)
26
44
 
27
45
 
28
46
  ### Bug Fixes
29
47
 
30
- * PLT-1314 enforce secure server URLs before sending tokens ([#120](https://github.com/browserless/browserless-cli/issues/120)) ([de84550](https://github.com/browserless/browserless-cli/commit/de8455044faa84d99627475db49eb76a7feadfc1))
48
+ * enforce secure server URLs before sending tokens
31
49
 
32
- ## [0.4.1](https://github.com/browserless/browserless-cli/compare/v0.4.0...v0.4.1) (2026-10-06)
50
+ ## 0.4.1 (2026-10-06)
33
51
 
34
52
 
35
53
  ### Bug Fixes
36
54
 
37
- * PLT-1315 restrict telemetry to trusted API hosts ([#119](https://github.com/browserless/browserless-cli/issues/119)) ([c67453c](https://github.com/browserless/browserless-cli/commit/c67453c272feb00f890013e3d334f7c8a226a35d))
55
+ * restrict telemetry to trusted API hosts
38
56
 
39
- ## [0.4.0](https://github.com/browserless/browserless-cli/compare/v0.3.0...v0.4.0) (2026-09-22)
57
+ ## 0.4.0 (2026-09-22)
40
58
 
41
59
 
42
60
  ### Features
43
61
 
44
- * AUTO-419 track CLI profile setup attempts ([#100](https://github.com/browserless/browserless-cli/issues/100)) ([93f5f5f](https://github.com/browserless/browserless-cli/commit/93f5f5fc033dbe98788f614082e997bd31a7129c))
62
+ * track CLI profile setup attempts
45
63
 
46
- ## [0.3.0](https://github.com/browserless/browserless-cli/compare/v0.2.0...v0.3.0) (2026-08-04)
64
+ ## 0.3.0 (2026-08-04)
47
65
 
48
66
 
49
67
  ### Features
50
68
 
51
- * Profile refresh replays the capture settings a profile was created with — no flags needed ([#58](https://github.com/browserless/browserless-cli/issues/58)) ([94fe959](https://github.com/browserless/browserless-cli/commit/94fe959620909e9f7e9bfe533dd0c94c1560c712))
69
+ * Profile refresh replays the capture settings a profile was created with — no flags needed
52
70
 
53
- ## [0.2.0](https://github.com/browserless/browserless-cli/compare/v0.1.0...v0.2.0) (2026-06-18)
71
+ ## 0.2.0 (2026-06-18)
54
72
 
55
73
 
56
74
  ### Features
57
75
 
58
- * add usage telemetry ([#19](https://github.com/browserless/browserless-cli/issues/19)) ([bdaa5dd](https://github.com/browserless/browserless-cli/commit/bdaa5dd01a8c6712dcf345edae1c41a228e05097))
76
+ * add usage telemetry
59
77
 
60
- ## [0.1.0](https://github.com/browserless/browserless-cli/compare/v0.0.3...v0.1.0) (2026-06-05)
78
+ ## 0.1.0 (2026-06-05)
61
79
 
62
80
 
63
81
  ### Features
64
82
 
65
- * Interactive agent chat via `browserless agent` ([c453dba](https://github.com/browserless/browserless-cli/commit/c453dbad50aa3283f9f8340bf32ed51d185ff132))
83
+ * Interactive agent chat via `browserless agent`
66
84
 
67
- ## [0.0.3](https://github.com/browserless/browserless-cli/compare/v0.0.2...v0.0.3) (2026-06-05)
85
+ ## 0.0.3 (2026-06-05)
68
86
 
69
87
 
70
88
  ### Bug Fixes
71
89
 
72
- * **capture:** connect to the browser CDP endpoint, not a default page target ([417cb12](https://github.com/browserless/browserless-cli/commit/417cb122743bfcfdd91ebbd4d010c7558f02138c))
73
- * **capture:** retry the default-target CDP connect on "No inspectable targets" ([b834311](https://github.com/browserless/browserless-cli/commit/b8343118a801938e09ff4a5e67957762317a08b1))
74
- * **capture:** wait for an inspectable target before connecting (fixes "No inspectable targets") ([69c2e96](https://github.com/browserless/browserless-cli/commit/69c2e961e6f70fba5fd40a6ea64e3aba9f323047))
75
- * **cli:** set process.exitCode instead of process.exit() on error path ([2a6042a](https://github.com/browserless/browserless-cli/commit/2a6042a52fbdbedfcb56086566a6f0a4bdb09ea0))
76
- * **cli:** windows/macos flaky tests ([559a10d](https://github.com/browserless/browserless-cli/commit/559a10d729251cca0ba1e891bffe13b8caf7b186))
90
+ * **capture:** connect to the browser CDP endpoint, not a default page target
91
+ * **capture:** retry the default-target CDP connect on "No inspectable targets"
92
+ * **capture:** wait for an inspectable target before connecting (fixes "No inspectable targets")
93
+ * **cli:** set process.exitCode instead of process.exit() on error path
94
+ * **cli:** windows/macos flaky tests
77
95
 
78
- ## [0.0.2](https://github.com/browserless/browserless-cli/compare/v0.0.1...v0.0.2) (2026-05-27)
96
+ ## 0.0.2 (2026-05-27)
79
97
 
80
98
 
81
99
  ### Features
82
100
 
83
- * --region sfo|lon|ams shortcut + region config key ([c921251](https://github.com/browserless/browserless-cli/commit/c921251664c89bb0e66c2549767d37ae2f011734))
84
- * Add the Browserless CLI for authenticated profile management ([d2ccbbe](https://github.com/browserless/browserless-cli/commit/d2ccbbe33204f74e188a1a4bb7a999e40a7034d7))
85
- * **capture:** live progress events, skip vendor NTP origins, cap loop on attempts, + --auto-fit/--keep-domain/--only-domain for artifact size mgmt ([f83c2a9](https://github.com/browserless/browserless-cli/commit/f83c2a99d086f9ab4c267f254a42c1154de7b9d4))
86
- * **capture:** skip sensitive profile files from temp copy + CI smoke that catches future Chrome additions ([0ad3a97](https://github.com/browserless/browserless-cli/commit/0ad3a9731c6133dcd68356c33b4ce40b0d01c4d0))
87
- * **ci:** cli-smoke integration test invokes every command on every OS via stub server ([c5fb558](https://github.com/browserless/browserless-cli/commit/c5fb5581bc4255b5b118e13cc543d4a115e5ebd5))
88
- * **disclaimer:** include privacy-policy link in liability disclaimer text ([3be0c1c](https://github.com/browserless/browserless-cli/commit/3be0c1cf5c0c4c3d43b2ef70e37bbe2c533bb005))
89
- * **registry:** discover Snap-installed Chromium on Linux + CI matrix axis for it ([645a2f0](https://github.com/browserless/browserless-cli/commit/645a2f0b2466b8da172e226b39a7188052124804))
90
- * **scripts:** add npm run dev (build + npm link) for one-shot local-dev setup ([5374585](https://github.com/browserless/browserless-cli/commit/5374585462a9652b818ffabf4281a412a34df65c))
91
- * **sources:** surface broken custom-browser registrations in sources list ([fb06afe](https://github.com/browserless/browserless-cli/commit/fb06afe7ee3982404fada378904f7ddd9fb0ee4a))
101
+ * --region sfo|lon|ams shortcut + region config key
102
+ * Add the Browserless CLI for authenticated profile management
103
+ * **capture:** live progress events, skip vendor NTP origins, cap loop on attempts, + --auto-fit/--keep-domain/--only-domain for artifact size mgmt
104
+ * **capture:** skip sensitive profile files from temp copy + CI smoke that catches future Chrome additions
105
+ * **ci:** cli-smoke integration test invokes every command on every OS via stub server
106
+ * **disclaimer:** include privacy-policy link in liability disclaimer text
107
+ * **registry:** discover Snap-installed Chromium on Linux + CI matrix axis for it
108
+ * **scripts:** add npm run dev (build + npm link) for one-shot local-dev setup
109
+ * **sources:** surface broken custom-browser registrations in sources list
92
110
 
93
111
 
94
112
  ### Bug Fixes
95
113
 
96
- * address review findings — surface silent fallbacks, narrow types, add coverage (+57 tests) ([d3f5e7e](https://github.com/browserless/browserless-cli/commit/d3f5e7e2ed59e8482453cf562c803a6e6850f354))
97
- * **api:** preserve path prefix on configured server URL (self-hosted-behind-/browserless/) ([710b011](https://github.com/browserless/browserless-cli/commit/710b01104cf7185ae90ba53cfbb629e2e1a6a177))
98
- * **browsers:** swallow fs.readdir EACCES/EIO so one bad source doesn't abort discovery ([55df91b](https://github.com/browserless/browserless-cli/commit/55df91b3a5b209754cd5a04b5efcaee6254367e5))
99
- * **browsers:** try every candidate user-data-dir so Snap chromium isn't masked by a stale ~/.config/chromium ([f98c8c2](https://github.com/browserless/browserless-cli/commit/f98c8c2737958c51051dd02e60ed81fac5e198f9))
100
- * **capture:** apply --only-domain pre-navigation so the per-run origin cap isn't burned on non-matching origins ([8157a4d](https://github.com/browserless/browserless-cli/commit/8157a4df2618c3aa370fed431f66b4df256ad71e))
101
- * **capture:** fail fast on all-invalid --only-domain so pre/post filters can't silently diverge ([393c813](https://github.com/browserless/browserless-cli/commit/393c8134bb9e30f0d940979dc89683e4f335de66))
102
- * **capture:** fail-fast on consecutive transport-dead CDP errors + throw on all-origins-failed ([2de326e](https://github.com/browserless/browserless-cli/commit/2de326ed30813e07cf9022b13162e11508a0b80e))
103
- * **capture:** filter Windows process sweep to chrome family binary — was killing PowerShell itself ([a968526](https://github.com/browserless/browserless-cli/commit/a96852623552246a8bc95009bb1c5b297dd18533))
104
- * **capture:** per-origin 15 s timeout so a single hung CDP tab can't lock the whole capture ([53644e9](https://github.com/browserless/browserless-cli/commit/53644e91ff477fce02bf6a21b28c3ebfb5965ee9))
105
- * **capture:** richer CDP-timeout diagnostics (pid/exit/args) + spec slop for CI ([7d2e9b4](https://github.com/browserless/browserless-cli/commit/7d2e9b41adf609d1ff4af02675399cce80f96486))
106
- * **capture:** run Windows process sweep detached + fire-and-forget — synchronous PowerShell call was crashing the CLI ([0755b50](https://github.com/browserless/browserless-cli/commit/0755b50b54445cfa84d6ede21f227d815377dce0))
107
- * **capture:** spawnSync taskkill on Windows + poll for orphan reap in test (Chrome tree teardown is slower on Windows) ([ab8faae](https://github.com/browserless/browserless-cli/commit/ab8faaecfc35ffc8a9f61363680c327221956088))
108
- * **capture:** surface browser stderr in CDP-timeout error for diagnostics ([de047c7](https://github.com/browserless/browserless-cli/commit/de047c776588368c4e458a7789e0ff1ce7c9c300))
109
- * **capture:** sweep Chrome processes by user-data-dir on Windows — renderers/utilities use CREATE_BREAKAWAY_FROM_JOB and survive taskkill /T ([8d30d38](https://github.com/browserless/browserless-cli/commit/8d30d38d5aff8a9a3ea27f8ecb46d58cb9769dfd))
110
- * **capture:** tally origin drops from both pre-nav skip and post-capture filter so a future post-capture filter can't silently undercount ([ed28db0](https://github.com/browserless/browserless-cli/commit/ed28db0d8bf994c0ead7110645521468cd92e3ef))
111
- * **capture:** unref child + close stdio after kill — unblock Node exit when browser doesn't reap fast; bypass .cmd shim on Windows when detached so CTRL_BREAK_EVENT targets the CLI ([87a0a9b](https://github.com/browserless/browserless-cli/commit/87a0a9b59ac951e625c4915209b5047285d6974e))
112
- * **ci:** apt options go after apt-get, not after sudo ([bdcc69e](https://github.com/browserless/browserless-cli/commit/bdcc69e07566a2ed06e143cdbb276557eb9ecec0))
113
- * **ci:** avoid $HOME override in capture smoke — add BROWSERLESS_CONFIG_DIR + custom browser source ([d59e289](https://github.com/browserless/browserless-cli/commit/d59e2897957528a06a6f4c1c24e508bc85420b5a))
114
- * **ci:** BROWSERLESS_DISABLE_KEYCHAIN escape hatch + drop whitespace-arg test (Windows cmd trims it) ([0431920](https://github.com/browserless/browserless-cli/commit/0431920fb5747b3161352803bb0c4d1073f62042))
115
- * **ci:** drop flaky windows-kill dep; use inline PowerShell P/Invoke for CTRL_BREAK_EVENT ([61f976d](https://github.com/browserless/browserless-cli/commit/61f976df8d2d511d7a9b7d5d88568a05fd2e3bc9))
116
- * **ci:** make CDP-wait timeout configurable; bump to 60s in capture smoke (macOS cold-boot) ([dd9d146](https://github.com/browserless/browserless-cli/commit/dd9d1467f2f39d5bab6caae96e7cb1619fb8fffd))
117
- * **ci:** restore apt-get update before gnome-keyring install — cached lists go stale ([a0c3845](https://github.com/browserless/browserless-cli/commit/a0c3845b6bbf014bbacb1558c08767620212718a))
118
- * **ci:** same Chrome seed fix for linux smoke ([7955e33](https://github.com/browserless/browserless-cli/commit/7955e33bb8fb85a54e792748f5b0659490688e88))
119
- * **ci:** seed Chrome user-data-dir directly instead of racing first-run boot ([fbdd633](https://github.com/browserless/browserless-cli/commit/fbdd633ce39e8123933a34735e1354f350521d6b))
120
- * **ci:** spawn browserless.cmd directly on Windows — shell:true splits args with spaces ([d416399](https://github.com/browserless/browserless-cli/commit/d416399a132280eb635ed2699b270e418027a686))
121
- * **ci:** split discovery smoke — chromium uses lookup-only mode (registry hit only); inspect mode kept for brave/edge (full capture) ([baa5433](https://github.com/browserless/browserless-cli/commit/baa54339f8e246bda210d6bea351114e77fc13d5))
122
- * **ci:** Windows arg quoting — shell:true with manual cmd-metachar quoting ([efcdd7d](https://github.com/browserless/browserless-cli/commit/efcdd7d63d90ad56d82ae9a5df4201be8a1f7490))
123
- * **commands:** add missing region?: string to upload/refresh Options interfaces ([dbd984e](https://github.com/browserless/browserless-cli/commit/dbd984e510d8ed18b0b331dd55dcf3cb079950f1))
124
- * **discover:** don't apply which-fallback to user-data-dir lookup — would return a binary path as a directory and crash readdir ([eb00c03](https://github.com/browserless/browserless-cli/commit/eb00c035a6e09e5ef2afcef694583c3fb1f24285))
125
- * **exclusion:** punycode-normalize bare hostnames so Unicode patterns match IDN cookie domains ([94ac479](https://github.com/browserless/browserless-cli/commit/94ac479497d0f9e5cb87a77af6b2aebbc2c65845))
126
- * **lock:** check 'lockfile' on Windows, 'SingletonLock' on POSIX (Chrome uses different filenames) ([c122331](https://github.com/browserless/browserless-cli/commit/c12233125e32ab8e6dd14876fceddbb8c40c2cad))
127
- * **lock:** Windows lockfile is an empty marker — presence = locked (no PID) ([0093d88](https://github.com/browserless/browserless-cli/commit/0093d88b108a481419acfb1d763374c8b1b6d562))
128
- * **registry:** discover Brave at per-user install path on Windows (%LOCALAPPDATA%) — default for choco / non-admin installs ([c1ac1a5](https://github.com/browserless/browserless-cli/commit/c1ac1a54d91abb5019e9fc24b8a1fe3636353bdb))
129
- * **sh:** drop duplicate Linux pattern in verify-chrome.sh case ([ea2ded6](https://github.com/browserless/browserless-cli/commit/ea2ded65dc24cc81c840fcec827d47bf7f43f820))
130
- * **sources:** validate --path and --user-data-dir at sources add time ([9909bbb](https://github.com/browserless/browserless-cli/commit/9909bbb7bb41cb6dbdb0c94db733fd7fd38a735a))
131
- * **test:** bound chrome.exe warmup to 30s so it can't hang CI ([899b3b6](https://github.com/browserless/browserless-cli/commit/899b3b61460916f9f745253e464505f66fa12db0))
132
- * **test:** poll lstatSync for SingletonLock + skip Windows orphan-check (documented limitation) ([1a43a46](https://github.com/browserless/browserless-cli/commit/1a43a46659ce3f34ce97152919615a97bd452ec4))
133
- * **test:** skip SIGTERM-trap killBrowser test on Windows (no real signals) ([c42dffd](https://github.com/browserless/browserless-cli/commit/c42dffd1f4f5e328632e7c5e6f9dc61f58ce26a8))
134
- * **trim-state:** don't treat unparseable origins as protected by --keep-domain ([9eeb46f](https://github.com/browserless/browserless-cli/commit/9eeb46fbbb7a5550d321df687cf8fda9da1eca04))
114
+ * address review findings — surface silent fallbacks, narrow types, add coverage (+57 tests)
115
+ * **api:** preserve path prefix on configured server URL (self-hosted-behind-/browserless/)
116
+ * **browsers:** swallow fs.readdir EACCES/EIO so one bad source doesn't abort discovery
117
+ * **browsers:** try every candidate user-data-dir so Snap chromium isn't masked by a stale ~/.config/chromium
118
+ * **capture:** apply --only-domain pre-navigation so the per-run origin cap isn't burned on non-matching origins
119
+ * **capture:** fail fast on all-invalid --only-domain so pre/post filters can't silently diverge
120
+ * **capture:** fail-fast on consecutive transport-dead CDP errors + throw on all-origins-failed
121
+ * **capture:** filter Windows process sweep to chrome family binary — was killing PowerShell itself
122
+ * **capture:** per-origin 15 s timeout so a single hung CDP tab can't lock the whole capture
123
+ * **capture:** richer CDP-timeout diagnostics (pid/exit/args) + spec slop for CI
124
+ * **capture:** run Windows process sweep detached + fire-and-forget — synchronous PowerShell call was crashing the CLI
125
+ * **capture:** spawnSync taskkill on Windows + poll for orphan reap in test (Chrome tree teardown is slower on Windows)
126
+ * **capture:** surface browser stderr in CDP-timeout error for diagnostics
127
+ * **capture:** sweep Chrome processes by user-data-dir on Windows — renderers/utilities use CREATE_BREAKAWAY_FROM_JOB and survive taskkill /T
128
+ * **capture:** tally origin drops from both pre-nav skip and post-capture filter so a future post-capture filter can't silently undercount
129
+ * **capture:** unref child + close stdio after kill — unblock Node exit when browser doesn't reap fast; bypass .cmd shim on Windows when detached so CTRL_BREAK_EVENT targets the CLI
130
+ * **ci:** apt options go after apt-get, not after sudo
131
+ * **ci:** avoid $HOME override in capture smoke — add BROWSERLESS_CONFIG_DIR + custom browser source
132
+ * **ci:** BROWSERLESS_DISABLE_KEYCHAIN escape hatch + drop whitespace-arg test (Windows cmd trims it)
133
+ * **ci:** drop flaky windows-kill dep; use inline PowerShell P/Invoke for CTRL_BREAK_EVENT
134
+ * **ci:** make CDP-wait timeout configurable; bump to 60s in capture smoke (macOS cold-boot)
135
+ * **ci:** restore apt-get update before gnome-keyring install — cached lists go stale
136
+ * **ci:** same Chrome seed fix for linux smoke
137
+ * **ci:** seed Chrome user-data-dir directly instead of racing first-run boot
138
+ * **ci:** spawn browserless.cmd directly on Windows — shell:true splits args with spaces
139
+ * **ci:** split discovery smoke — chromium uses lookup-only mode (registry hit only); inspect mode kept for brave/edge (full capture)
140
+ * **ci:** Windows arg quoting — shell:true with manual cmd-metachar quoting
141
+ * **commands:** add missing region?: string to upload/refresh Options interfaces
142
+ * **discover:** don't apply which-fallback to user-data-dir lookup — would return a binary path as a directory and crash readdir
143
+ * **exclusion:** punycode-normalize bare hostnames so Unicode patterns match IDN cookie domains
144
+ * **lock:** check 'lockfile' on Windows, 'SingletonLock' on POSIX (Chrome uses different filenames)
145
+ * **lock:** Windows lockfile is an empty marker — presence = locked (no PID)
146
+ * **registry:** discover Brave at per-user install path on Windows (%LOCALAPPDATA%) — default for choco / non-admin installs
147
+ * **sh:** drop duplicate Linux pattern in verify-chrome.sh case
148
+ * **sources:** validate --path and --user-data-dir at sources add time
149
+ * **test:** bound chrome.exe warmup to 30s so it can't hang CI
150
+ * **test:** poll lstatSync for SingletonLock + skip Windows orphan-check (documented limitation)
151
+ * **test:** skip SIGTERM-trap killBrowser test on Windows (no real signals)
152
+ * **trim-state:** don't treat unparseable origins as protected by --keep-domain
135
153
 
136
154
 
137
155
  ### Reverts
138
156
 
139
- * drop Windows orphan-cleanup hacks — Chrome utility processes self-exit within ~30s; not worth the test/CLI complexity for an external-force-kill-only scenario ([caf828b](https://github.com/browserless/browserless-cli/commit/caf828b5020e36dbd2b4232a94bb7e7d5cccee9a))
157
+ * drop Windows orphan-cleanup hacks — Chrome utility processes self-exit within ~30s; not worth the test/CLI complexity for an external-force-kill-only scenario
140
158
 
141
159
  ## Changelog
142
160
 
package/README.md CHANGED
@@ -52,12 +52,15 @@
52
52
  - [Privacy & Domain Filtering](#-privacy--domain-filtering)
53
53
  - [Managing Artifact Size](#-managing-artifact-size)
54
54
  - [Custom Chromium Browsers](#-custom-chromium-browsers)
55
+ - [Hosted Agent](#-hosted-agent)
55
56
  - [Shared Flags](#-shared-flags)
56
57
  - [Configuration](#-configuration)
57
58
  - [Environment Variables](#-environment-variables)
58
59
  - [Usage Analytics](#-usage-analytics)
59
60
  - [Exit Codes](#-exit-codes)
60
61
  - [Why use the CLI?](#-why-use-the-cli)
62
+ - [Contributing](#-contributing)
63
+ - [Security](#-security)
61
64
  - [Licensing](#-licensing)
62
65
 
63
66
  ## 🚀 Get Started in Seconds!
@@ -73,10 +76,12 @@ Requires Node.js ≥ 24.
73
76
  ### Step 2: Log in
74
77
 
75
78
  ```bash
76
- # Pass your API token as a positional arg, or pipe it via stdin to keep
77
- # it out of shell history.
78
- browserless auth login <your-token>
79
+ # Recommended: pipe the token via stdin (or paste it at the prompt)
79
80
  echo $TOKEN | browserless auth login
81
+
82
+ # Also works, but a token passed as an argument is visible to other local
83
+ # users in the process list and lands in your shell history
84
+ browserless auth login <your-token>
80
85
  ```
81
86
 
82
87
  Tokens are stored in your **OS keychain** when available (Keychain on
@@ -286,16 +291,43 @@ If the binary or `user-data-dir` later goes missing, `profile sources
286
291
  list` flags the entry under "Registered custom browsers with missing
287
292
  paths" so you can clean it up with `profile sources rm`.
288
293
 
294
+ ## 🤖 Hosted Agent
295
+
296
+ `browserless agent` opens an interactive chat with the Browserless hosted
297
+ agent. The model runs on Browserless and drives a cloud browser for you; the
298
+ terminal shows its replies and each browser action as it happens.
299
+
300
+ ```bash
301
+ # Start a chat, optionally with the first task
302
+ browserless agent "find the opening hours of the Louvre"
303
+
304
+ # Scripts: stdout carries only the final result as JSON (progress goes to stderr)
305
+ browserless agent "find the opening hours of the Louvre" --json
306
+ ```
307
+
308
+ - Follow-up messages continue the same session. Ctrl-C stops the current
309
+ turn; press it again (or send an empty line) to exit.
310
+ - When the agent pauses for input — for example a one-time code — the CLI
311
+ prompts you for it.
312
+ - If your first message asks the agent to log in somewhere, the CLI asks
313
+ for a username and password (the password is masked) and sends them to
314
+ the hosted agent together with your task. Leave the prompts blank to
315
+ skip.
316
+ - Prompts you type are kept in `~/.browserless/agent_history` (mode 0600,
317
+ last 200) so the up arrow recalls them across sessions; usernames,
318
+ passwords and codes are never written there. `--no-history` turns the
319
+ file off.
320
+
289
321
  ## ⚙️ Shared Flags
290
322
 
291
323
  Every command that hits the cloud API accepts:
292
324
 
293
- | Flag | Effect |
294
- | ----------------- | --------------------------------------------------------------- |
295
- | `--token <tok>` | Override token resolution (flag > env > keychain > config file) |
296
- | `--server <url>` | Override the configured server URL |
297
- | `--region <code>` | `sfo` / `lon` / `ams` — shorthand for `--server` |
298
- | `--json` | Emit the server response as JSON (script-friendly) |
325
+ | Flag | Effect |
326
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
327
+ | `--token <tok>` | Override token resolution (flag > env > keychain > config file). Visible in the process list; prefer `BROWSERLESS_TOKEN` for scripts |
328
+ | `--server <url>` | Override the configured server URL |
329
+ | `--region <code>` | `sfo` / `lon` / `ams` — shorthand for `--server` |
330
+ | `--json` | Emit the server response as JSON (script-friendly) |
299
331
 
300
332
  Capture commands (`upload`, `refresh`, `inspect`) also accept:
301
333
 
@@ -364,13 +396,21 @@ authenticated with your token and targeted a Browserless cloud region:
364
396
 
365
397
  - the command that ran (e.g. `profile upload`) and the **names** of the flags
366
398
  you passed — never their values
367
- - the outcome: `ok` / `error`, the exit code, and the error class/code on
368
- failure (e.g. `cdp-timeout`)
399
+ - the outcome: `ok` / `error`, the exit code, and on failure the error class,
400
+ a short error code (e.g. `cdp-timeout`, `not-found`), a category (e.g.
401
+ `network`) and the server's HTTP status when there is one — never the error message
369
402
  - duration, CLI version, OS / architecture / Node major, whether it's running
370
403
  under CI
371
404
  - the production region (`sfo` / `lon` / `ams`) — never a raw server URL
372
405
  - a random per-install id (`cli_device_id`), stored in
373
406
  `~/.browserless/telemetry-device-id`
407
+ - for `profile upload` / `profile refresh`, a few setup-progress events
408
+ (`Profile Setup Method Selected`, `Profile Setup Started`,
409
+ `Profile Setup Ready`, `Profile Save Submitted`, and
410
+ `Profile Setup Failed` with a short reason code) that share a random
411
+ `attempt_id`. Pass `--attempt-id <UUID>` to keep your own id across
412
+ retries; the same id is sent to the Browserless server with the upload as
413
+ the `x-browserless-attempt-id` header
374
414
 
375
415
  **What's never in the analytics data:** your API token, profile names,
376
416
  captured URLs or domains, cookies, or any captured auth state. The token is
@@ -421,16 +461,30 @@ touched; sensitive domains never leave your machine.
421
461
  Once uploaded, any Browserless cloud session can attach the profile
422
462
  via `?profile=<name>` and start _already authenticated_.
423
463
 
424
- ## 📜 Licensing
464
+ ## 🤝 Contributing
465
+
466
+ Pull requests are welcome. [AGENTS.md](AGENTS.md) is the contributor guide —
467
+ architecture, local setup, testing patterns and conventions (coding agents
468
+ read the same file). Before opening a PR:
469
+
470
+ ```bash
471
+ npm run build && npm run lint && npm test
472
+ ```
425
473
 
426
- Distributed as part of the Browserless platform. The `LICENSE` file
427
- ships in the package; see [browserless.io](https://browserless.io) for
428
- full terms.
474
+ PR titles follow [Conventional Commits](https://www.conventionalcommits.org/)
475
+ and become the changelog entry.
476
+
477
+ ## 🔒 Security
478
+
479
+ Please report vulnerabilities privately — see [SECURITY.md](SECURITY.md).
480
+ Don't open a public issue for a security problem.
481
+
482
+ ## 📜 Licensing
429
483
 
430
- If you're building a commercial application on Browserless, a
431
- [commercial license](https://www.browserless.io/contact) covers
432
- priority support, on-premise deployment, source modification, and
433
- the admin UI in addition to keeping your software proprietary.
484
+ The Browserless CLI is open source under the [MIT License](LICENSE).
485
+ Using it with the hosted Browserless service is also covered by your
486
+ Browserless account terms and the
487
+ [privacy policy](https://www.browserless.io/privacy-policy).
434
488
 
435
489
  <div align="center">
436
490
 
@@ -1 +1 @@
1
- var d=Object.defineProperty;var c=(i,e)=>d(i,"name",{value:e,configurable:!0});import{EventEmitter as f}from"node:events";import m from"ws";import{ApiError as p,PreconditionError as w}from"../errors.js";const u=new Set([1e3,1001,1005]),g=c((i,e)=>{const r=i.replace(/^http/i,"ws").replace(/\/+$/,""),s=new URL(`${r}/chromium/cli`);return s.searchParams.set("token",e),s.toString()},"buildCliWsUrl");class $ extends f{static{c(this,"AgentClient")}ws=null;server;token;WebSocketImpl;constructor(e){super(),this.server=e.server,this.token=e.token,this.WebSocketImpl=e.WebSocketImpl??m}connect(){const e=g(this.server,this.token);return new Promise((r,s)=>{const n=new this.WebSocketImpl(e);let l=!1;const h=c(t=>{if(!l)if(l=!0,t){try{n.terminate()}catch{}s(t)}else this.ws=n,r()},"settle");n.once("open",()=>h()),n.once("unexpected-response",(t,a)=>{const o=a.statusCode??0;h(this.mapUpgradeError(o,a.statusMessage??""))}),n.on("error",t=>{if(!l){h(new p(`WebSocket connection failed: ${t.message}`,0));return}this.emit("agent_error",{code:"ws-error",message:t.message,retryable:!1})}),n.on("message",t=>this.handleMessage(t)),n.on("close",(t,a)=>{const o=a?.toString("utf8")??"";if(!u.has(t)){this.emit("agent_error",{code:`ws-closed-${t}`,message:`WebSocket closed abnormally (code ${t}${o?`: ${o}`:""})`,retryable:!1});return}this.emit("close",{code:t,reason:o})})})}start(e){this.sendFrame({type:"start",prompt:e})}send(e){this.sendFrame({type:"send",prompt:e})}stop(){this.sendFrame({type:"stop"})}close(){this.ws&&this.ws.readyState===m.OPEN&&this.ws.close()}sendFrame(e){if(!this.ws||this.ws.readyState!==m.OPEN)throw new p("Cannot send a frame: WebSocket is not open.",0);this.ws.send(JSON.stringify(e))}handleMessage(e){let r;try{r=JSON.parse(e.toString("utf8"))}catch{return}typeof r.type=="string"&&this.emit(r.type==="error"?"agent_error":r.type,r)}mapUpgradeError(e,r){const s=r?` \u2014 ${r}`:"";return e===401||e===403?new w(`Authentication failed (HTTP ${e}${s}). Check your token and server.`,"invalid-token"):new p(`Server rejected the agent connection (HTTP ${e}${s}).`,e)}}export{$ as AgentClient,g as buildCliWsUrl};
1
+ var p=Object.defineProperty;var c=(i,e)=>p(i,"name",{value:e,configurable:!0});import{EventEmitter as f}from"node:events";import h from"ws";import{ApiError as d,PreconditionError as w}from"../errors.js";import{terminalSafe as u}from"../utils/terminal.js";const S=new Set([1e3,1001,1005]),g=c((i,e)=>{const r=i.replace(/^http/i,"ws").replace(/\/+$/,""),s=new URL(`${r}/chromium/cli`);return s.searchParams.set("token",e),s.toString()},"buildCliWsUrl");class W extends f{static{c(this,"AgentClient")}ws=null;server;token;WebSocketImpl;constructor(e){super(),this.server=e.server,this.token=e.token,this.WebSocketImpl=e.WebSocketImpl??h}connect(){const e=g(this.server,this.token);return new Promise((r,s)=>{const n=new this.WebSocketImpl(e);let l=!1;const m=c(t=>{if(!l)if(l=!0,t){try{n.terminate()}catch{}s(t)}else this.ws=n,r()},"settle");n.once("open",()=>m()),n.once("unexpected-response",(t,a)=>{const o=a.statusCode??0;m(this.mapUpgradeError(o,a.statusMessage??""))}),n.on("error",t=>{if(!l){m(new d(`WebSocket connection failed: ${t.message}`,0,void 0,"websocket-failed"));return}this.emit("agent_error",{code:"ws-error",message:t.message,retryable:!1})}),n.on("message",t=>this.handleMessage(t)),n.on("close",(t,a)=>{const o=a?.toString("utf8")??"";if(!S.has(t)){this.emit("agent_error",{code:`ws-closed-${t}`,message:`WebSocket closed abnormally (code ${t}${o?`: ${o}`:""})`,retryable:!1});return}this.emit("close",{code:t,reason:o})})})}start(e){this.sendFrame({type:"start",prompt:e})}send(e){this.sendFrame({type:"send",prompt:e})}stop(){this.sendFrame({type:"stop"})}close(){this.ws&&this.ws.readyState===h.OPEN&&this.ws.close()}sendFrame(e){if(!this.ws||this.ws.readyState!==h.OPEN)throw new d("Cannot send a frame: WebSocket is not open.",0,void 0,"websocket-not-open");this.ws.send(JSON.stringify(e))}handleMessage(e){let r;try{r=JSON.parse(e.toString("utf8"))}catch{return}typeof r.type=="string"&&this.emit(r.type==="error"?"agent_error":r.type,r)}mapUpgradeError(e,r){const s=r?` \u2014 ${u(r)}`:"";return e===401||e===403?new w(`Authentication failed (HTTP ${e}${s}). Check your token and server.`,"invalid-token"):new d(`Server rejected the agent connection (HTTP ${e}${s}).`,e)}}export{W as AgentClient,g as buildCliWsUrl};
@@ -1 +1 @@
1
- var $=Object.defineProperty;var c=(e,t)=>$(e,"name",{value:t,configurable:!0});import{ApiError as f}from"../errors.js";const w=3e4,l=c(e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)?e.toLowerCase():void 0,"profileAttemptId"),y=c((e,t,n,r)=>{const s=e.endsWith("/")?e:`${e}/`,m=t.replace(/^\/+/,""),o=new URL(m,s);if(o.searchParams.set("token",n),r)for(const[h,u]of Object.entries(r))u!==void 0&&o.searchParams.set(h,String(u));return o},"buildUrl"),p=c((e,t,n)=>{if(!n)return`HTTP ${e} ${t}`;try{const s=JSON.parse(n);if(s?.message&&typeof s.message=="string")return s.message}catch{}const r=n.trim();return r.length>200?`HTTP ${e} ${t}: ${r.slice(0,200)}\u2026`:`HTTP ${e} ${t}: ${r}`},"messageFromBody"),T=c(async(e,t)=>{const n=y(e.server,t.path,e.token,t.query),r={method:t.method,redirect:"error"};let s;t.rawBody!==void 0?s=t.rawBody:t.body!==void 0&&(s=JSON.stringify(t.body)),s!==void 0&&(r.body=s,r.headers={"Content-Type":"application/json"});const m=l(t.attemptId);m&&(r.headers={...r.headers,"x-browserless-attempt-id":m});const o=t.timeoutMs??w,h=new AbortController,u=setTimeout(()=>h.abort(),o);r.signal=h.signal;let a;try{a=await fetch(n,r)}catch(d){throw d?.name==="AbortError"?new f(`Request to ${e.server}${t.path} timed out after ${o}ms`,0):new f(`Failed to reach ${e.server}: ${d?.message??d}`,0)}finally{clearTimeout(u)}let i;try{i=await a.text()}catch(d){throw d?.name==="AbortError"?new f(`Request to ${e.server}${t.path} timed out after ${o}ms`,0):new f(`Failed to read response from ${e.server}${t.path}: ${d?.message??d}`,0)}if(!a.ok)throw new f(p(a.status,a.statusText,i),a.status,i);if(!(a.status===204||!i))try{return JSON.parse(i)}catch{throw new f(`Server returned non-JSON response: ${i}`,a.status,i)}},"apiFetch");export{T as apiFetch,l as profileAttemptId};
1
+ var p=Object.defineProperty;var u=(e,t)=>p(e,"name",{value:t,configurable:!0});import{ApiError as c}from"../errors.js";import{terminalSafe as i}from"../utils/terminal.js";const b=3e4,$=10*1024*1024,g=u(e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)?e.toLowerCase():void 0,"profileAttemptId"),T=u((e,t,d,r)=>{const n=e.endsWith("/")?e:`${e}/`,h=t.replace(/^\/+/,""),f=new URL(h,n);if(f.searchParams.set("token",d),r)for(const[m,l]of Object.entries(r))l!==void 0&&f.searchParams.set(m,String(l));return f},"buildUrl"),S=u((e,t,d)=>{if(!d)return`HTTP ${e} ${i(t)}`;try{const n=JSON.parse(d);if(n?.message&&typeof n.message=="string")return i(n.message)}catch{}const r=d.trim();return r.length>200?`HTTP ${e} ${i(t)}: ${i(r.slice(0,200))}\u2026`:`HTTP ${e} ${i(t)}: ${i(r)}`},"messageFromBody"),A=u(async(e,t)=>{const d=T(e.server,t.path,e.token,t.query),r={method:t.method,redirect:"error"};let n;t.rawBody!==void 0?n=t.rawBody:t.body!==void 0&&(n=JSON.stringify(t.body)),n!==void 0&&(r.body=n,r.headers={"Content-Type":"application/json"});const h=g(t.attemptId);h&&(r.headers={...r.headers,"x-browserless-attempt-id":h});const f=t.timeoutMs??b,m=new AbortController,l=setTimeout(()=>m.abort(),f);r.signal=m.signal;let s,a="";try{s=await fetch(d,r);const o=new TextDecoder;let w=0;if(s.body){for await(const y of s.body){if(w+=y.byteLength,w>$)throw m.abort(),new c(`Response exceeds the ${$}-byte decoded body limit`,0,void 0,"response-too-large");a+=o.decode(y,{stream:!0})}a+=o.decode()}}catch(o){throw o instanceof c?o:o?.name==="AbortError"?new c(`Request to ${e.server}${t.path} timed out after ${f}ms`,0,void 0,"request-timeout"):new c(s?`Failed to read response from ${e.server}${t.path}: ${o?.message??o}`:`Failed to reach ${e.server}: ${o?.message??o}`,0,void 0,s?"response-read-failed":"network-unreachable")}finally{clearTimeout(l)}if(!s.ok)throw new c(S(s.status,s.statusText,a),s.status,a);if(!(s.status===204||!a))try{return JSON.parse(a)}catch{throw new c(`Server returned non-JSON response: ${i(a)}`,s.status,a,"invalid-response")}},"apiFetch");export{A as apiFetch,g as profileAttemptId};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var t=(o,e)=>f(o,"name",{value:e,configurable:!0});import{apiFetch as n}from"./client.js";const l=t(async(o,e={})=>n(o,{method:"GET",path:"/profiles",query:{...e.limit!==void 0?{limit:e.limit}:{},...e.offset!==void 0?{offset:e.offset}:{}}}),"listProfiles"),r=t(async(o,e)=>n(o,{method:"GET",path:`/profile/${encodeURIComponent(e)}`}),"getProfile"),c=t(async(o,e,i)=>n(o,{method:"PUT",path:`/profile/${encodeURIComponent(e)}`,body:{name:i}}),"renameProfile"),m=t(async(o,e)=>n(o,{method:"DELETE",path:`/profile/${encodeURIComponent(e)}`}),"deleteProfile");export{m as deleteProfile,r as getProfile,l as listProfiles,c as renameProfile};
1
+ var n=Object.defineProperty;var t=(e,o)=>n(e,"name",{value:o,configurable:!0});import{apiFetch as i}from"./client.js";import{UsageError as l}from"../errors.js";const c=t(async(e,o={})=>i(e,{method:"GET",path:"/profiles",query:{...o.limit!==void 0?{limit:o.limit}:{},...o.offset!==void 0?{offset:o.offset}:{}}}),"listProfiles"),r=t(e=>{if(e==="."||e==="..")throw new l(`"${e}" is not a valid profile name.`);return`/profile/${encodeURIComponent(e)}`},"profilePath"),h=t(async(e,o)=>i(e,{method:"GET",path:r(o)}),"getProfile"),m=t(async(e,o,f)=>i(e,{method:"PUT",path:r(o),body:{name:f}}),"renameProfile"),a=t(async(e,o)=>i(e,{method:"DELETE",path:r(o)}),"deleteProfile");export{a as deleteProfile,h as getProfile,c as listProfiles,m as renameProfile};
@@ -1 +1 @@
1
- var s=Object.defineProperty;var i=(t,e)=>s(t,"name",{value:e,configurable:!0});import{apiFetch as n}from"./client.js";import{ApiError as o}from"../errors.js";import{version as a}from"../version.js";const d=i(t=>{const e=t.serialized??JSON.stringify(t.state),r=t.captureSettings===void 0?"":`,"captureSettings":${JSON.stringify(t.captureSettings)}`;return`{"name":${JSON.stringify(t.name)},"state":${e}${r}}`},"buildProfileBody"),p=i((t,e)=>{throw!(t instanceof o)||t.status!==400||!/additional propert/i.test(`${t.body??""} ${t.message}`)?t:new o(`The server at ${e} rejected the profile capture settings this CLI (v${a}) sends \u2014 it predates either the field itself or one of its members. Deploy the server to every region before using this CLI against it. Server said: ${t.message}`,400,t.body)},"rethrowCaptureSettingsSkew"),u=i(async(t,e)=>{try{return await n(t,{method:"POST",path:"/profile/upload",rawBody:d(e),attemptId:e.attemptId})}catch(r){return p(r,t.server)}},"uploadProfile");export{d as buildProfileBody,p as rethrowCaptureSettingsSkew,u as uploadProfile};
1
+ var o=Object.defineProperty;var i=(t,e)=>o(t,"name",{value:e,configurable:!0});import{apiFetch as n}from"./client.js";import{ApiError as s}from"../errors.js";import{version as a}from"../version.js";const d=i(t=>{const e=t.serialized??JSON.stringify(t.state),r=t.captureSettings===void 0?"":`,"captureSettings":${JSON.stringify(t.captureSettings)}`;return`{"name":${JSON.stringify(t.name)},"state":${e}${r}}`},"buildProfileBody"),p=i((t,e)=>{throw!(t instanceof s)||t.status!==400||!/additional propert/i.test(`${t.body??""} ${t.message}`)?t:new s(`The server at ${e} rejected the profile capture settings this CLI (v${a}) sends \u2014 it predates either the field itself or one of its members. Deploy the server to every region before using this CLI against it. Server said: ${t.message}`,400,t.body,"capture-settings-rejected")},"rethrowCaptureSettingsSkew"),h=i(async(t,e)=>{try{return await n(t,{method:"POST",path:"/profile/upload",rawBody:d(e),attemptId:e.attemptId})}catch(r){return p(r,t.server)}},"uploadProfile");export{d as buildProfileBody,p as rethrowCaptureSettingsSkew,h as uploadProfile};
@@ -1,4 +1,4 @@
1
- var d=Object.defineProperty;var o=(t,e)=>d(t,"name",{value:e,configurable:!0});import u from"node:readline/promises";import{stdin as n,stdout as s}from"node:process";import{readConfig as m,updateConfig as c}from"../config/store.js";import{DEFAULT_TERMS_TTL_DAYS as f}from"../config/schema.js";import{PreconditionError as p}from"../errors.js";const w=`
1
+ var d=Object.defineProperty;var o=(t,e)=>d(t,"name",{value:e,configurable:!0});import u from"node:readline/promises";import{stdin as s,stdout as n}from"node:process";import{readConfig as m,updateConfig as c}from"../config/store.js";import{DEFAULT_TERMS_TTL_DAYS as f}from"../config/schema.js";import{PreconditionError as l}from"../errors.js";const h=`
2
2
  Heads up \u2014 uploading a profile sends authentication state to Browserless:
3
3
 
4
4
  \u2022 Cookies, localStorage and IndexedDB from the browser profile you select
@@ -7,10 +7,14 @@ Heads up \u2014 uploading a profile sends authentication state to Browserless:
7
7
  \u2022 Only upload profiles you have authority to share. Cookies for banking,
8
8
  healthcare, employer-SSO or other sensitive sites should be added to the
9
9
  domain exclusion list (\`browserless profile exclude add <domain>\`).
10
+ \u2022 Each cloud profile keeps the exclusion list it was captured with, and a
11
+ later \`profile refresh\` reuses it. To apply a domain you excluded
12
+ since, refresh with \`--exclude-domain <domain>\`: that replaces the
13
+ stored list with this machine's list plus the domain.
10
14
  \u2022 Your local browser profile is never modified \u2014 the CLI runs against a
11
15
  temporary copy and cleans it up after capture.
12
16
 
13
17
  By continuing you confirm you understand the above and accept responsibility
14
18
  for the contents of the upload. Privacy policy: https://www.browserless.io/privacy-policy
15
- `,l="I accept",y=o(()=>!!process.env.CI,"isCi"),h=o((t,e)=>{if(!t||e<=0)return!1;const r=Date.parse(t);if(!Number.isFinite(r))return!1;const a=Date.now()-r;return a>=0&&a<e*24*60*60*1e3},"isWithinTtl"),S=o(async t=>{s.write(t);const e=u.createInterface({input:n,output:s});try{return await e.question(`
16
- Type "${l}" to continue: `)}finally{e.close()}},"defaultPrompt"),R=o(async(t,e={})=>{const r=await m(),a=t.ttlDaysOverride??r.terms_ttl_days??f;if(h(r.accepted_terms_at,a))return;if(t.acceptViaFlag||process.env.BROWSERLESS_ACCEPT_TERMS==="1"){await c(i=>{i.accepted_terms_at=new Date().toISOString()});return}if(!(e.isInteractive??(n.isTTY&&!y())))throw new p("Liability disclaimer must be acknowledged before uploading. Re-run with `--accept-terms` or set BROWSERLESS_ACCEPT_TERMS=1 in non-interactive environments.","terms-not-accepted");if((await(e.prompt??S)(w)).trim()!==l)throw new p("Disclaimer not accepted \u2014 aborting.","terms-not-accepted");await c(i=>{i.accepted_terms_at=new Date().toISOString()})},"ensureTermsAccepted");export{w as DISCLAIMER_TEXT,R as ensureTermsAccepted,y as isCi};
19
+ `,p="I accept",w=o(()=>!!process.env.CI,"isCi"),y=o((t,e)=>{if(!t||e<=0)return!1;const r=Date.parse(t);if(!Number.isFinite(r))return!1;const i=Date.now()-r;return i>=0&&i<e*24*60*60*1e3},"isWithinTtl"),S=o(async t=>{n.write(t);const e=u.createInterface({input:s,output:n});try{return await e.question(`
20
+ Type "${p}" to continue: `)}finally{e.close()}},"defaultPrompt"),x=o(async(t,e={})=>{const r=await m(),i=t.ttlDaysOverride??r.terms_ttl_days??f;if(y(r.accepted_terms_at,i))return;if(t.acceptViaFlag||process.env.BROWSERLESS_ACCEPT_TERMS==="1"){await c(a=>{a.accepted_terms_at=new Date().toISOString()});return}if(!(e.isInteractive??(s.isTTY&&!w())))throw new l("Liability disclaimer must be acknowledged before uploading. Re-run with `--accept-terms` or set BROWSERLESS_ACCEPT_TERMS=1 in non-interactive environments.","terms-not-accepted");if((await(e.prompt??S)(h)).trim()!==p)throw new l("Disclaimer not accepted \u2014 aborting.","terms-not-accepted");await c(a=>{a.accepted_terms_at=new Date().toISOString()})},"ensureTermsAccepted");export{h as DISCLAIMER_TEXT,x as ensureTermsAccepted,w as isCi};
@@ -1,2 +1,2 @@
1
- var s=Object.defineProperty;var o=(r,t)=>s(r,"name",{value:t,configurable:!0});import{PreconditionError as n,UsageError as e}from"../errors.js";import{isLoopbackHostname as p}from"../utils/loopback.js";const i="BROWSERLESS_ALLOW_INSECURE_HTTP",S=o(r=>{let t;try{t=new URL(r)}catch{throw new e(`server must be a valid URL (got "${r}")`)}if(t.protocol==="https:")return r;if(t.protocol==="http:"){if(p(t.hostname))return r;if(process.env[i]==="1")return process.stderr.write(`warning: sending your Browserless token over unencrypted http:// to ${t.host} (BROWSERLESS_ALLOW_INSECURE_HTTP is set)
2
- `),r;throw new n(`Refusing to send your Browserless token over unencrypted http:// to ${t.host}. Use https://, or set BROWSERLESS_ALLOW_INSECURE_HTTP=1 to override.`,"insecure-server-url")}throw new e(`server must use https:// (got "${t.protocol}")`)},"assertSecureServerUrl");export{i as ALLOW_INSECURE_ENV,S as assertSecureServerUrl};
1
+ var s=Object.defineProperty;var t=(e,r)=>s(e,"name",{value:r,configurable:!0});import{PreconditionError as n,UsageError as o}from"../errors.js";import{isLoopbackHostname as p}from"../utils/loopback.js";const i="BROWSERLESS_ALLOW_INSECURE_HTTP",S=t(e=>{let r;try{r=new URL(e)}catch{throw new o(`server must be a valid URL (got "${e}")`,"invalid-server-url")}if(r.protocol==="https:")return e;if(r.protocol==="http:"){if(p(r.hostname))return e;if(process.env[i]==="1")return process.stderr.write(`warning: sending your Browserless token over unencrypted http:// to ${r.host} (BROWSERLESS_ALLOW_INSECURE_HTTP is set)
2
+ `),e;throw new n(`Refusing to send your Browserless token over unencrypted http:// to ${r.host}. Use https://, or set BROWSERLESS_ALLOW_INSECURE_HTTP=1 to override.`,"insecure-server-url")}throw new o(`server must use https:// (got "${r.protocol}")`,"unsupported-server-scheme")},"assertSecureServerUrl");export{i as ALLOW_INSECURE_ENV,S as assertSecureServerUrl};
@@ -1,5 +1,5 @@
1
- var N=Object.defineProperty;var n=(e,t)=>N(e,"name",{value:t,configurable:!0});import h from"node:fs/promises";import m from"node:path";import{spawn as g}from"node:child_process";import{BUILT_IN_BROWSERS as y}from"./registry.js";import{readCustomBrowsers as p}from"./custom.js";import{UsageError as w}from"../errors.js";import{pathExists as c}from"../utils/fs.js";const C=n(e=>new Promise(t=>{const r=g("which",[e],{stdio:["ignore","pipe","ignore"]});let s="";r.stdout?.on("data",o=>{s+=o.toString()}),r.on("error",()=>t(null)),r.on("exit",o=>t(o===0&&s.trim()?s.trim():null))}),"whichOnPath"),k=n(async e=>{for(const t of e)if(await c(t))return t;return null},"firstExistingPath"),b=n(async e=>{const t=await k(e);if(t)return t;if(process.platform==="linux")for(const r of e){const s=m.basename(r);if(!s)continue;const o=await C(s);if(o)return o}return null},"firstExistingBinary"),B=n(async e=>{const t=m.join(e,"Local State");try{const r=await h.readFile(t,"utf-8"),o=JSON.parse(r)?.profile?.info_cache??{};return Object.fromEntries(Object.entries(o).map(([i,l])=>[i,l?.name??i]))}catch{return{}}},"readProfileDisplayNames"),$=n(async e=>await c(m.join(e,"Preferences"))||await c(m.join(e,"Cookies"))||await c(m.join(e,"Network","Cookies")),"looksLikeProfile"),P=n(async(e,t,r,s)=>{const o=await B(e);let i;try{i=await h.readdir(e,{withFileTypes:!0})}catch{return[]}const l=i.filter(a=>a.isDirectory()).filter(a=>a.name==="Default"||/^Profile \d+$/.test(a.name));return(await Promise.all(l.map(async a=>{const f=m.join(e,a.name);return await $(f)?{browserKey:r,browserDisplayName:s,profileDirName:a.name,profileDisplayName:o[a.name]??a.name,userDataDir:e,profilePath:f,binaryPath:t}:null}))).filter(a=>a!==null)},"profilesUnder"),L=n(async e=>{const t=e.userDataDirByPlatform[process.platform],r=e.binaryPathByPlatform[process.platform]??[];if(!t||r.length===0)return[];const s=Array.isArray(t)?t:[t],o=await b(r);if(!o)return[];for(const i of s){if(!await c(i))continue;const l=await P(i,o,e.key,e.displayName);if(l.length>0)return l}return[]},"discoverBuiltIn"),x=n(async e=>await c(e.userDataDir)?await c(e.binaryPath)?P(e.userDataDir,e.binaryPath,e.name,e.name):[]:[],"discoverCustom"),j=n(async()=>{const[e,t]=await Promise.all([Promise.all(y.map(L)),p().then(r=>Promise.all(r.map(x)))]);return[...e.flat(),...t.flat()]},"discoverProfiles"),T=n(async()=>{const e=await p();return(await Promise.all(e.map(async r=>{const[s,o]=await Promise.all([c(r.binaryPath),c(r.userDataDir)]);return s&&o?null:{name:r.name,binaryPath:r.binaryPath,userDataDir:r.userDataDir,missingBinary:!s,missingUserDataDir:!o}}))).filter(r=>r!==null)},"findBrokenCustomSources"),D=n((e,t)=>{const r=e.trim().toLowerCase();return t.browserKey.toLowerCase()===r||t.browserDisplayName.toLowerCase()===r},"matchesBrowser"),E=n((e,t)=>{const r=e.trim().toLowerCase();return t.profileDirName.toLowerCase()===r||t.profileDisplayName.toLowerCase()===r},"matchesProfile"),O=n((e,t,r,s)=>{const o=e.trim().toLowerCase();if(!r.some(a=>a.key.toLowerCase()===o||a.displayName.toLowerCase()===o))throw new w(`Unknown browser "${e}". Run \`browserless profile sources list\` to see detected browsers, or register a custom one with \`profile sources add\`.`);const l=s.filter(a=>D(e,a)&&E(t,a));if(l.length===1)return l[0];if(l.length===0){const a=s.filter(u=>D(e,u));if(a.length===0)throw new w(`Browser "${e}" is registered but has no detected profiles on this machine.`);const f=a.map(u=>` - ${u.profileDisplayName} (${u.profileDirName})`).join(`
2
- `);throw new w(`No profile named "${t}" under ${e}. Available profiles:
3
- ${f}`)}const d=l.map(a=>` - ${a.profileDisplayName} (dir: ${a.profileDirName}) under ${a.browserDisplayName}`).join(`
4
- `);throw new w(`Profile "${t}" matches multiple entries \u2014 disambiguate by passing the directory name to --profile:
5
- ${d}`)},"resolveProfileFromCandidates"),J=n(async(e,t)=>{const r=await p(),s=[...y.map(i=>({key:i.key,displayName:i.displayName})),...r.map(i=>({key:i.name,displayName:i.name}))],o=await j();return O(e,t,s,o)},"resolveProfile");export{j as discoverProfiles,T as findBrokenCustomSources,J as resolveProfile,O as resolveProfileFromCandidates,C as whichOnPath};
1
+ var g=Object.defineProperty;var n=(e,r)=>g(e,"name",{value:r,configurable:!0});import y from"node:fs/promises";import f from"node:path";import{spawn as N}from"node:child_process";import{BUILT_IN_BROWSERS as P}from"./registry.js";import{readCustomBrowsers as d}from"./custom.js";import{PreconditionError as C,UsageError as p}from"../errors.js";import{pathExists as m}from"../utils/fs.js";import{terminalSafe as c}from"../utils/terminal.js";const k=n(e=>new Promise(r=>{const t=N("which",[e],{stdio:["ignore","pipe","ignore"]});let i="";t.stdout?.on("data",o=>{i+=o.toString()}),t.on("error",()=>r(null)),t.on("exit",o=>r(o===0&&i.trim()?i.trim():null))}),"whichOnPath"),$=n(async e=>{for(const r of e)if(await m(r))return r;return null},"firstExistingPath"),B=n(async e=>{const r=await $(e);if(r)return r;if(process.platform==="linux")for(const t of e){const i=f.basename(t);if(!i)continue;const o=await k(i);if(o)return o}return null},"firstExistingBinary"),L=n(async e=>{const r=f.join(e,"Local State");try{const t=await y.readFile(r,"utf-8"),o=JSON.parse(t)?.profile?.info_cache??{};return Object.fromEntries(Object.entries(o).map(([s,l])=>[s,l?.name??s]))}catch{return{}}},"readProfileDisplayNames"),x=n(async e=>await m(f.join(e,"Preferences"))||await m(f.join(e,"Cookies"))||await m(f.join(e,"Network","Cookies")),"looksLikeProfile"),D=n(async(e,r,t,i)=>{const o=await L(e);let s;try{s=await y.readdir(e,{withFileTypes:!0})}catch{return[]}const l=s.filter(a=>a.isDirectory()).filter(a=>a.name==="Default"||/^Profile \d+$/.test(a.name));return(await Promise.all(l.map(async a=>{const u=f.join(e,a.name);return await x(u)?{browserKey:t,browserDisplayName:i,profileDirName:a.name,profileDisplayName:o[a.name]??a.name,userDataDir:e,profilePath:u,binaryPath:r}:null}))).filter(a=>a!==null)},"profilesUnder"),j=n(async e=>{const r=e.userDataDirByPlatform[process.platform],t=e.binaryPathByPlatform[process.platform]??[];if(!r||t.length===0)return[];const i=Array.isArray(r)?r:[r],o=await B(t);if(!o)return[];for(const s of i){if(!await m(s))continue;const l=await D(s,o,e.key,e.displayName);if(l.length>0)return l}return[]},"discoverBuiltIn"),v=n(async e=>{if(!f.isAbsolute(e.binaryPath)||!f.isAbsolute(e.userDataDir))throw new C(`Custom browser "${e.name}" has relative paths. Remove it with \`profile sources rm <name>\` and re-register it with \`profile sources add\` from its original directory.`,"invalid-custom-browsers-file");return await m(e.userDataDir)?await m(e.binaryPath)?D(e.userDataDir,e.binaryPath,e.name,e.name):[]:[]},"discoverCustom"),E=n(async()=>{const[e,r]=await Promise.all([Promise.all(P.map(j)),d().then(t=>Promise.all(t.map(v)))]);return[...e.flat(),...r.flat()]},"discoverProfiles"),q=n(async()=>{const e=await d();return(await Promise.all(e.map(async t=>{const[i,o]=await Promise.all([m(t.binaryPath),m(t.userDataDir)]);return i&&o?null:{name:t.name,binaryPath:t.binaryPath,userDataDir:t.userDataDir,missingBinary:!i,missingUserDataDir:!o}}))).filter(t=>t!==null)},"findBrokenCustomSources"),b=n((e,r)=>{const t=e.trim().toLowerCase();return r.browserKey.toLowerCase()===t||r.browserDisplayName.toLowerCase()===t},"matchesBrowser"),S=n((e,r)=>{const t=e.trim().toLowerCase();return r.profileDirName.toLowerCase()===t||r.profileDisplayName.toLowerCase()===t},"matchesProfile"),O=n((e,r,t,i)=>{const o=e.trim().toLowerCase();if(!t.some(a=>a.key.toLowerCase()===o||a.displayName.toLowerCase()===o))throw new p(`Unknown browser "${c(e)}". Run \`browserless profile sources list\` to see detected browsers, or register a custom one with \`profile sources add\`.`,"unknown-browser");const l=i.filter(a=>b(e,a)&&S(r,a));if(l.length===1)return l[0];if(l.length===0){const a=i.filter(w=>b(e,w));if(a.length===0)throw new p(`Browser "${c(e)}" is registered but has no detected profiles on this machine.`,"browser-has-no-profiles");const u=a.map(w=>` - ${c(w.profileDisplayName)} (${c(w.profileDirName)})`).join(`
2
+ `);throw new p(`No profile named "${c(r)}" under ${c(e)}. Available profiles:
3
+ ${u}`,"local-profile-not-found")}const h=l.map(a=>` - ${c(a.profileDisplayName)} (dir: ${c(a.profileDirName)}) under ${c(a.browserDisplayName)}`).join(`
4
+ `);throw new p(`Profile "${c(r)}" matches multiple entries \u2014 disambiguate by passing the directory name to --profile:
5
+ ${h}`,"local-profile-ambiguous")},"resolveProfileFromCandidates"),z=n(async(e,r)=>{const t=await d(),i=[...P.map(s=>({key:s.key,displayName:s.displayName})),...t.map(s=>({key:s.name,displayName:s.name}))],o=await E();return O(e,r,i,o)},"resolveProfile");export{E as discoverProfiles,q as findBrokenCustomSources,z as resolveProfile,O as resolveProfileFromCandidates,k as whichOnPath};
@@ -0,0 +1 @@
1
+ var C=Object.defineProperty;var o=(f,c)=>C(f,"name",{value:c,configurable:!0});const l="CDP pipe closed",D=o((f,c)=>{let P=1,i=null;const a=new Map,d=new Map,w=new Set;let m=[];const $=o((r,e)=>`${r??""}\0${e}`,"key"),g=o(r=>{if(!i){i=r;for(const{reject:e}of a.values())e(r);a.clear();for(const e of w)e(r);w.clear(),d.clear()}},"fail"),S=o(r=>{let e;try{e=JSON.parse(r)}catch{return}if(typeof e?.id=="number"){const n=a.get(e.id);if(!n)return;a.delete(e.id),e.error?n.reject(new Error(`${n.method}: ${e.error.message??"protocol error"}`)):n.resolve(e.result??{});return}if(typeof e?.method=="string"){const n=d.get($(e.sessionId,e.method));for(const t of[...n??[]])t(e.params)}},"dispatch");c.on("data",r=>{let e=0,n=r.indexOf(0);for(;n!==-1;){m.push(r.subarray(e,n));const t=Buffer.concat(m).toString("utf8");m=[],S(t),e=n+1,n=r.indexOf(0,e)}e<r.length&&m.push(r.subarray(e))}),c.on("end",()=>g(new Error(l))),c.on("close",()=>g(new Error(l))),c.on("error",r=>g(new Error(`${l}: ${r.message}`))),f.on("error",r=>g(new Error(`${l}: ${r.message}`)));const h=o((r,e={},n)=>{if(i)return Promise.reject(i);const t=P++;return new Promise((s,p)=>{a.set(t,{method:r,resolve:s,reject:p});const O=n?{id:t,method:r,params:e,sessionId:n}:{id:t,method:r,params:e};f.write(`${JSON.stringify(O)}\0`,u=>{!u||!a.has(t)||(a.delete(t),p(new Error(`${l}: ${u.message}`)))})})},"send"),y=o((r,e,n)=>{if(i)return()=>{};const t=$(r,e),s=d.get(t)??new Set;return s.add(n),d.set(t,s),()=>{s.delete(n),s.size===0&&d.get(t)===s&&d.delete(t)}},"on"),x=o((r,e)=>new Promise((n,t)=>{if(i){t(i);return}w.add(t);const s=y(r,e,p=>{s(),w.delete(t),n(p)})}),"once"),E=o(r=>({send:o((e,n)=>h(e,n,r),"send"),on:o((e,n)=>y(r,e,n),"on"),once:o(e=>x(r,e),"once")}),"sessionFor");return{...E(void 0),session:o(r=>E(r),"session"),close:o(()=>{g(new Error(l)),f.destroy(),c.destroy()},"close")}},"connectCdpPipe");export{l as CDP_PIPE_CLOSED,D as connectCdpPipe};
@@ -1,4 +1,4 @@
1
- var _=Object.defineProperty;var d=(e,t)=>_(e,"name",{value:t,configurable:!0});import b from"node:fs/promises";import x from"node:path";import y from"chrome-remote-interface";import{CaptureError as S}from"../errors.js";import{errMessage as A}from"../utils/errors.js";import{applyExclusions as I,originAllowedBy as E,originMatchesAny as P}from"./exclusion.js";const v=50,D=5,$=1e3,R=3,j=15e3,q=d((e,t,s)=>{let r;return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),new Promise((n,a)=>{r=setTimeout(()=>a(new Error(`${s} timed out after ${t}ms`)),t)})])},"withTimeout"),M=d(e=>/ECONNREFUSED|EPIPE|socket hang up/i.test(e),"isTransportDeadError"),k=d(e=>{const t=e.startsWith(".")?e.slice(1):e;return!!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||/^\d+\.\d+\.\d+\.\d+$/.test(t)||t===""||t.includes(":"))},"isPrivateCookieDomain"),N=d(e=>{try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?!0:k(t.hostname)}catch{return!0}},"isPrivateOrigin"),O=new Set(["ntp.msn.com"]),C=d(e=>{try{return O.has(new URL(e).hostname)}catch{return!1}},"isVendorNtpOrigin"),L=d(async e=>{const t=x.join(e,"Local Storage","leveldb");let s;try{s=await b.readdir(t)}catch{return[]}const r=new Set;let n=0;const a=10*1024*1024,c=/https?:\/\/[a-zA-Z0-9.-]+(?::\d+)?/g;for(const i of s)if(!(!i.endsWith(".log")&&!i.endsWith(".ldb"))){if(n>=a)break;try{const l=await b.readFile(x.join(t,i));n+=l.byteLength;const p=l.toString("latin1");for(const f of p.matchAll(c))try{const u=new URL(f[0]);(u.protocol==="https:"||u.protocol==="http:")&&!k(u.hostname)&&!O.has(u.hostname)&&r.add(u.origin)}catch{}}catch{}}return[...r]},"enumerateLocalStorageOrigins"),F=d(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path,expires:typeof e.expires=="number"?e.expires:-1,size:e.size,httpOnly:!!e.httpOnly,secure:!!e.secure,session:!!e.session,...e.sameSite?{sameSite:e.sameSite}:{},...e.sourceScheme?{sourceScheme:e.sourceScheme}:{},...e.sourcePort?{sourcePort:e.sourcePort}:{}}),"cookieFromCdp"),H=d(async e=>{const t=await y({port:e});try{const{cookies:s}=await t.Storage.getCookies({});return s.filter(r=>!k(r.domain)).map(F)}finally{await t.close()}},"captureCookies"),U=Buffer.from("<html></html>").toString("base64"),X=d(async e=>{const t=await y({port:e.port});let s;try{s=(await t.Target.createTarget({url:"about:blank"})).targetId}finally{await t.close()}if(!s)return null;const r=await y({port:e.port,target:s});try{await r.Page.enable(),await r.Network.enable(),await r.Fetch.enable({patterns:[{urlPattern:"*"}]});const n=new Set([`${e.origin}/`]);r.on("Fetch.requestPaused",p=>{const{requestId:f,request:u}=p;n.has(u.url)?(n.delete(u.url),r.send("Fetch.fulfillRequest",{requestId:f,responseCode:200,responseHeaders:[{name:"Content-Type",value:"text/html"}],body:U}).catch(()=>{})):r.send("Fetch.failRequest",{requestId:f,errorReason:"BlockedByClient"}).catch(()=>{})}),await r.Page.navigate({url:`${e.origin}/`}),await r.Page.loadEventFired().catch(()=>{});const a=await r.Runtime.evaluate({expression:`
1
+ var I=Object.defineProperty;var u=(e,t)=>I(e,"name",{value:t,configurable:!0});import x from"node:fs/promises";import E from"node:path";import{CaptureError as w}from"../errors.js";import{errMessage as T}from"../utils/errors.js";import{applyExclusions as A,originAllowedBy as P,originMatchesAny as R}from"./exclusion.js";const v=50,D=5,$=1e3,O=3,M=15e3,N=u((e,t,n)=>{let s;return Promise.race([e.finally(()=>{s&&clearTimeout(s)}),new Promise((c,r)=>{s=setTimeout(()=>r(new Error(`${n} timed out after ${t}ms`)),t)})])},"withTimeout"),j=u(e=>/CDP pipe closed|ECONNREFUSED|EPIPE|socket hang up/i.test(e),"isTransportDeadError"),b=u(e=>{const t=e.startsWith(".")?e.slice(1):e;return!!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||/^\d+\.\d+\.\d+\.\d+$/.test(t)||t===""||t.includes(":"))},"isPrivateCookieDomain"),_=u(e=>{try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?!0:b(t.hostname)}catch{return!0}},"isPrivateOrigin"),C=new Set(["ntp.msn.com"]),B=u(e=>{try{return C.has(new URL(e).hostname)}catch{return!1}},"isVendorNtpOrigin"),q=u(async e=>{const t=E.join(e,"Local Storage","leveldb");let n;try{n=await x.readdir(t)}catch{return[]}const s=new Set;let c=0;const r=10*1024*1024,i=/https?:\/\/[a-zA-Z0-9.-]+(?::\d+)?/g;for(const a of n)if(!(!a.endsWith(".log")&&!a.endsWith(".ldb"))){if(c>=r)break;try{const d=await x.readFile(E.join(t,a));c+=d.byteLength;const p=d.toString("latin1");for(const f of p.matchAll(i))try{const l=new URL(f[0]);(l.protocol==="https:"||l.protocol==="http:")&&!b(l.hostname)&&!C.has(l.hostname)&&s.add(l.origin)}catch{}}catch{}}return[...s]},"enumerateLocalStorageOrigins"),F=u(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path,expires:typeof e.expires=="number"?e.expires:-1,size:e.size,httpOnly:!!e.httpOnly,secure:!!e.secure,session:!!e.session,...e.sameSite?{sameSite:e.sameSite}:{},...e.sourceScheme?{sourceScheme:e.sourceScheme}:{},...e.sourcePort?{sourcePort:e.sourcePort}:{}}),"cookieFromCdp"),L=3e4,U=u(async e=>{const{cookies:t}=await N(e.send("Storage.getCookies"),L,"Storage.getCookies").catch(n=>{throw new w(`Reading cookies from the headless browser failed: ${T(n)}`,"cdp-timeout")});return t.filter(n=>!b(n.domain)).map(F)},"captureCookies"),H=Buffer.from("<html></html>").toString("base64"),X=u(async e=>{const{cdp:t}=e,{targetId:n}=await t.send("Target.createTarget",{url:"about:blank"});if(!n)return null;let s,c=u(()=>{},"stopIntercepting");try{({sessionId:s}=await t.send("Target.attachToTarget",{targetId:n,flatten:!0}));const r=t.session(s);await r.send("Page.enable"),await r.send("Network.enable"),await r.send("Fetch.enable",{patterns:[{urlPattern:"*"}]});const i=new Set([`${e.origin}/`]);c=r.on("Fetch.requestPaused",S=>{const{requestId:y,request:o}=S;i.has(o.url)?(i.delete(o.url),r.send("Fetch.fulfillRequest",{requestId:y,responseCode:200,responseHeaders:[{name:"Content-Type",value:"text/html"}],body:H}).catch(()=>{})):r.send("Fetch.failRequest",{requestId:y,errorReason:"BlockedByClient"}).catch(()=>{})});const a=r.once("Page.loadEventFired").catch(()=>{});await r.send("Page.navigate",{url:`${e.origin}/`}),await a;const d=await r.send("Runtime.evaluate",{expression:`
2
2
  (() => {
3
3
  const out = {};
4
4
  for (let i = 0; i < localStorage.length; i++) {
@@ -7,7 +7,7 @@ var _=Object.defineProperty;var d=(e,t)=>_(e,"name",{value:t,configurable:!0});i
7
7
  }
8
8
  return JSON.stringify(out);
9
9
  })()
10
- `,returnByValue:!0,awaitPromise:!1}),c=a?.result?.value?JSON.parse(a.result.value):{},i=await r.Runtime.evaluate({expression:`
10
+ `,returnByValue:!0,awaitPromise:!1}),p=d?.result?.value?JSON.parse(d.result.value):{},f=await r.send("Runtime.evaluate",{expression:`
11
11
  (async (MAX_DBS, MAX_ENTRIES) => {
12
12
  if (typeof indexedDB.databases !== 'function') return [];
13
13
  const dbInfos = await indexedDB.databases();
@@ -59,4 +59,4 @@ var _=Object.defineProperty;var d=(e,t)=>_(e,"name",{value:t,configurable:!0});i
59
59
  }
60
60
  return JSON.stringify(out);
61
61
  })(${D}, ${$})
62
- `,returnByValue:!0,awaitPromise:!0}),l=i?.result?.value?JSON.parse(i.result.value):[];return Object.keys(c).length===0&&l.length===0?null:{origin:e.origin,localStorage:c,...l.length>0?{indexedDBs:l}:{}}}finally{await r.send("Fetch.disable").catch(()=>{}),await r.send("Network.disable").catch(()=>{}),await r.close().catch(()=>{});const n=await y({port:e.port});try{await n.Target.closeTarget({targetId:s})}catch{}finally{await n.close()}}},"captureOrigin"),W=d(async(e,t,s,r,n=[])=>{const a=[],c=[];let i=!1,l=0,p=0,f=0,u=0;const T=e.filter(o=>!N(o)).filter(o=>!C(o)).filter(o=>!P(o,t)).filter(o=>n.length===0||E(o,n)).length,B=Math.min(T,v);for(const o of e){if(u>=v){i=!0;break}if(!N(o)&&!C(o)){if(P(o,t)){l++;continue}if(n.length>0&&!E(o,n)){p++;continue}u++,r?.({attempted:u,total:B,origin:o});try{const m=await s(o);m&&a.push(m),f=0}catch(m){const h=A(m);if(M(h)){if(f++,f>=R)throw new S(`Headless browser appears to have crashed mid-capture \u2014 ${R} consecutive transport errors on the CDP port. Last failure on "${o}": ${h}. Retry the capture; if it persists, try a smaller profile or a different --password-store value.`,"browser-crashed-during-capture")}else f=0;let w="unknown";const g=h.toLowerCase();g.includes("timeout")||g.includes("timed out")?w="navigation-timeout":(g.includes("websocket")||g.includes("not connected")||g.includes("connection closed"))&&(w="cdp-disconnected"),c.push({origin:o,error:h,kind:w})}}}if(a.length===0&&c.length>0){const o=c.slice(0,3).map(h=>`${h.origin}: ${h.error}`).join("; "),m=c.length>3?` (+${c.length-3} more)`:"";throw new S(`All ${c.length} attempted origin(s) failed to capture; nothing usable was produced. Sample: ${o}${m}`,"all-origins-failed")}return{origins:a,failedOrigins:c,capHit:i,originCountSkippedByExclusion:l,originCountSkippedByOnlyDomain:p}},"runOriginCaptureLoop"),Y=d(async(e,t,s=[],r,n=[])=>{const a=await H(t),c=await L(e.profilePath),i=await W(c,s,p=>q(X({port:t,origin:p}),j,`per-origin capture of ${p}`),r,n),l=I({cookies:a,origins:i.origins},s);return{state:l.state,capHit:i.capHit,cookieCountTotal:a.length,cookieCountExcluded:a.length-l.state.cookies.length,originCountSkippedByExclusion:i.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:i.originCountSkippedByOnlyDomain,failedOrigins:i.failedOrigins}},"captureViaCdp");export{S as CaptureError,Y as captureViaCdp,F as cookieFromCdp,L as enumerateLocalStorageOrigins,k as isPrivateCookieDomain,N as isPrivateOrigin,M as isTransportDeadError,C as isVendorNtpOrigin,W as runOriginCaptureLoop,q as withTimeout};
62
+ `,returnByValue:!0,awaitPromise:!0}),l=f?.result?.value?JSON.parse(f.result.value):[];return Object.keys(p).length===0&&l.length===0?null:{origin:e.origin,localStorage:p,...l.length>0?{indexedDBs:l}:{}}}finally{if(c(),s){const r=t.session(s);await r.send("Fetch.disable").catch(()=>{}),await r.send("Network.disable").catch(()=>{}),await t.send("Target.detachFromTarget",{sessionId:s}).catch(()=>{})}await t.send("Target.closeTarget",{targetId:n}).catch(()=>{})}},"captureOrigin"),W=u(async(e,t,n,s,c=[])=>{const r=[],i=[];let a=!1,d=0,p=0,f=0,l=0;const S=e.filter(o=>!_(o)).filter(o=>!B(o)).filter(o=>!R(o,t)).filter(o=>c.length===0||P(o,c)).length,y=Math.min(S,v);for(const o of e){if(l>=v){a=!0;break}if(!_(o)&&!B(o)){if(R(o,t)){d++;continue}if(c.length>0&&!P(o,c)){p++;continue}l++,s?.({attempted:l,total:y,origin:o});try{const g=await n(o);g&&r.push(g),f=0}catch(g){const h=T(g);if(j(h)){if(f++,f>=O)throw new w(`Headless browser appears to have crashed mid-capture \u2014 ${O} consecutive transport errors on the CDP connection. Last failure on "${o}": ${h}. Retry the capture; if it persists, try a smaller profile or a different --password-store value.`,"browser-crashed-during-capture")}else f=0;let k="unknown";const m=h.toLowerCase();m.includes("timeout")||m.includes("timed out")?k="navigation-timeout":(m.includes("websocket")||m.includes("not connected")||m.includes("connection closed")||m.includes("pipe closed"))&&(k="cdp-disconnected"),i.push({origin:o,error:h,kind:k})}}}if(r.length===0&&i.length>0){const o=i.slice(0,3).map(h=>`${h.origin}: ${h.error}`).join("; "),g=i.length>3?` (+${i.length-3} more)`:"";throw new w(`All ${i.length} attempted origin(s) failed to capture; nothing usable was produced. Sample: ${o}${g}`,"all-origins-failed")}return{origins:r,failedOrigins:i,capHit:a,originCountSkippedByExclusion:d,originCountSkippedByOnlyDomain:p}},"runOriginCaptureLoop"),Q=u(async(e,t,n=[],s,c=[])=>{const r=await U(t),i=await q(e.profilePath),a=await W(i,n,p=>N(X({cdp:t,origin:p}),M,`per-origin capture of ${p}`),s,c),d=A({cookies:r,origins:a.origins},n);return{state:d.state,capHit:a.capHit,cookieCountTotal:r.length,cookieCountExcluded:r.length-d.state.cookies.length,originCountSkippedByExclusion:a.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:a.originCountSkippedByOnlyDomain,failedOrigins:a.failedOrigins}},"captureViaCdp");export{L as COOKIE_READ_TIMEOUT_MS,w as CaptureError,Q as captureViaCdp,F as cookieFromCdp,q as enumerateLocalStorageOrigins,b as isPrivateCookieDomain,_ as isPrivateOrigin,j as isTransportDeadError,B as isVendorNtpOrigin,W as runOriginCaptureLoop,N as withTimeout};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var i=(e,r)=>u(e,"name",{value:r,configurable:!0});import d from"node:fs/promises";import{killBrowser as f}from"./launch.js";const p=i((e,r,n=f,c=()=>{})=>{let o;return()=>o??=(async()=>{c();const t=await r()?.catch(()=>{});t&&await n(t.child);const a=e();a&&await d.rm(a,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}).catch(()=>{})})()},"createCaptureCleanup");export{p as createCaptureCleanup};