@browserless.io/cli 0.0.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 (62) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/LICENSE +21 -0
  3. package/README.md +402 -0
  4. package/build/api/auth.js +1 -0
  5. package/build/api/client.js +1 -0
  6. package/build/api/profiles.js +1 -0
  7. package/build/api/refresh.js +1 -0
  8. package/build/api/upload.js +1 -0
  9. package/build/auth/disclaimer.js +16 -0
  10. package/build/auth/keychain.js +1 -0
  11. package/build/auth/store.js +1 -0
  12. package/build/browsers/custom.js +1 -0
  13. package/build/browsers/discover.js +5 -0
  14. package/build/browsers/lock.js +1 -0
  15. package/build/browsers/password-store.js +1 -0
  16. package/build/browsers/paths.js +1 -0
  17. package/build/browsers/registry.js +1 -0
  18. package/build/capture/cdp.js +62 -0
  19. package/build/capture/copy-profile.js +1 -0
  20. package/build/capture/exclusion.js +1 -0
  21. package/build/capture/index.js +1 -0
  22. package/build/capture/launch.js +6 -0
  23. package/build/capture/types.js +0 -0
  24. package/build/cli-utils/capture-runner.js +21 -0
  25. package/build/cli-utils/client.js +2 -0
  26. package/build/cli-utils/trim-state.js +1 -0
  27. package/build/cli.js +5 -0
  28. package/build/commands/auth/index.js +1 -0
  29. package/build/commands/auth/login.js +1 -0
  30. package/build/commands/auth/logout.js +1 -0
  31. package/build/commands/auth/status.js +1 -0
  32. package/build/commands/config/get.js +1 -0
  33. package/build/commands/config/index.js +1 -0
  34. package/build/commands/config/set.js +1 -0
  35. package/build/commands/config/unset.js +1 -0
  36. package/build/commands/profile/delete.js +1 -0
  37. package/build/commands/profile/exclude/add.js +1 -0
  38. package/build/commands/profile/exclude/index.js +1 -0
  39. package/build/commands/profile/exclude/list.js +1 -0
  40. package/build/commands/profile/exclude/rm.js +1 -0
  41. package/build/commands/profile/index.js +1 -0
  42. package/build/commands/profile/inspect.js +4 -0
  43. package/build/commands/profile/launch.js +12 -0
  44. package/build/commands/profile/list.js +1 -0
  45. package/build/commands/profile/refresh.js +2 -0
  46. package/build/commands/profile/rename.js +1 -0
  47. package/build/commands/profile/show.js +1 -0
  48. package/build/commands/profile/sources/add.js +1 -0
  49. package/build/commands/profile/sources/index.js +1 -0
  50. package/build/commands/profile/sources/list.js +2 -0
  51. package/build/commands/profile/sources/rm.js +1 -0
  52. package/build/commands/profile/upload.js +2 -0
  53. package/build/config/paths.js +1 -0
  54. package/build/config/schema.js +1 -0
  55. package/build/config/store.js +1 -0
  56. package/build/errors.js +1 -0
  57. package/build/regions.js +1 -0
  58. package/build/utils/errors.js +1 -0
  59. package/build/utils/fs.js +1 -0
  60. package/build/utils/json-file.js +1 -0
  61. package/build/version.js +1 -0
  62. package/package.json +76 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@browserless.io/cli` will be documented in this file.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Browserless
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,402 @@
1
+ <!-- markdownlint-disable commands-show-output first-line-h1 no-emphasis-as-heading no-inline-html -->
2
+
3
+ <div align="center">
4
+ <a href="https://browserless.io" align="center">
5
+ <center align="center">
6
+ <picture>
7
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/browserless/browserless/main/assets/logo-white.svg" width="600">
8
+ <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/browserless/browserless/main/assets/logo.svg" width="600">
9
+ <img src="https://raw.githubusercontent.com/browserless/browserless/main/assets/logo.svg" alt="Browserless logo" width="600">
10
+ </picture>
11
+ </center>
12
+ </a>
13
+
14
+ <h3>Capture authenticated browser profiles for Browserless — straight from your terminal.</h3>
15
+
16
+ <p>
17
+ <a href="https://www.npmjs.com/package/@browserless.io/cli">
18
+ <img src="https://img.shields.io/badge/📦_Install_via_npm-CB3837?style=for-the-badge" alt="Install via npm" />
19
+ </a>
20
+ &nbsp;&nbsp;
21
+ <a href="https://docs.browserless.io/baas/features/authenticated-profiles">
22
+ <img src="https://img.shields.io/badge/📘_Dev_Docs-5C6AC4?style=for-the-badge" alt="Developer Docs" />
23
+ </a>
24
+ &nbsp;&nbsp;
25
+ <a href="https://browserless.io/">
26
+ <img src="https://img.shields.io/badge/🧪_Try_on_Cloud-4A90E2?style=for-the-badge" alt="Try on Cloud" />
27
+ </a>
28
+ </p>
29
+
30
+ <p>
31
+ <a href="https://www.npmjs.com/package/@browserless.io/cli">
32
+ <img src="https://img.shields.io/npm/v/@browserless.io/cli?style=flat-square" alt="npm version" />
33
+ </a>
34
+ <a href="https://www.npmjs.com/package/@browserless.io/cli">
35
+ <img src="https://img.shields.io/npm/dm/@browserless.io/cli?style=flat-square" alt="npm downloads" />
36
+ </a>
37
+ <a href="https://nodejs.org">
38
+ <img src="https://img.shields.io/node/v/@browserless.io/cli?style=flat-square" alt="Node version" />
39
+ </a>
40
+ <a href="https://status.browserless.io/">
41
+ <img src="https://img.shields.io/badge/Status-Operational-success?style=flat-square" alt="Status" />
42
+ </a>
43
+ </p>
44
+ </div>
45
+
46
+ <br>
47
+
48
+ ## 📋 Table of Contents
49
+
50
+ - [Get Started in Seconds](#-get-started-in-seconds)
51
+ - [Capture Commands](#-capture-commands)
52
+ - [Privacy & Domain Filtering](#-privacy--domain-filtering)
53
+ - [Managing Artifact Size](#-managing-artifact-size)
54
+ - [Custom Chromium Browsers](#-custom-chromium-browsers)
55
+ - [Shared Flags](#-shared-flags)
56
+ - [Configuration](#-configuration)
57
+ - [Environment Variables](#-environment-variables)
58
+ - [Exit Codes](#-exit-codes)
59
+ - [Why use the CLI?](#-why-use-the-cli)
60
+ - [Licensing](#-licensing)
61
+
62
+
63
+ ## 🚀 Get Started in Seconds!
64
+
65
+ ### Step 1: Install
66
+
67
+ ```bash
68
+ npm install -g @browserless.io/cli
69
+ ```
70
+
71
+ Requires Node.js ≥ 24.
72
+
73
+ ### Step 2: Log in
74
+
75
+ ```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
+ echo $TOKEN | browserless auth login
80
+ ```
81
+
82
+ Tokens are stored in your **OS keychain** when available (Keychain on
83
+ macOS, libsecret on Linux, DPAPI on Windows) and fall back to a
84
+ mode-0600 file at `~/.browserless/config.json` when not.
85
+
86
+ ```bash
87
+ browserless auth status # who am I, where is my token stored?
88
+ browserless auth logout # wipe credentials (keychain + file)
89
+ ```
90
+
91
+ ### Step 3: Capture a profile
92
+
93
+ ```bash
94
+ # Capture from your local Chrome and upload it as a cloud profile
95
+ browserless profile upload \
96
+ --browser chrome --profile Default --name my-chrome
97
+ ```
98
+
99
+ **✅ Success!** Any Browserless cloud session can now start *already
100
+ authenticated* by attaching `?profile=my-chrome` to its launch URL.
101
+
102
+ ### Picking a server
103
+
104
+ By default the CLI talks to `https://production-sfo.browserless.io`.
105
+ Two ways to point it elsewhere:
106
+
107
+ ```bash
108
+ # Production regions — short codes for production-<code>.browserless.io
109
+ browserless config set region sfo # San Francisco (default)
110
+ browserless config set region lon # London
111
+ browserless config set region ams # Amsterdam
112
+
113
+ # Or a full URL — for self-hosted / staging deployments
114
+ browserless config set server https://my-browserless.example.com
115
+ ```
116
+
117
+ Per-invocation overrides: `--region <code>` or `--server <url>`.
118
+ Passing both flags (or having both keys set in config) is an error —
119
+ they're mutually exclusive.
120
+
121
+
122
+ ## 🗂 Capture Commands
123
+
124
+ > **First-run note (macOS only).** The first time you run `profile upload`
125
+ > or `profile refresh`, macOS may show a one-time Keychain prompt:
126
+ > *"Google Chrome wants to access key 'Chrome Safe Storage' in your
127
+ > keychain"*. This is the launched Chrome reading its own existing
128
+ > keychain entry — not the CLI asking for new access. Click
129
+ > **Always Allow** and you won't see it again.
130
+ >
131
+ > **Liability disclaimer.** The first `profile upload` or `profile refresh`
132
+ > shows a one-screen disclaimer and asks you to type `I accept`. The
133
+ > acknowledgment is recorded and re-prompted every 7 days by default.
134
+ > Use `--accept-terms` (or `BROWSERLESS_ACCEPT_TERMS=1`) in scripts /
135
+ > non-interactive shells; `--terms-ttl-days <n>` tunes the re-prompt
136
+ > window (0 to re-prompt every run).
137
+
138
+ ```bash
139
+ # Discover local browser profiles
140
+ browserless profile sources list
141
+
142
+ # Capture and upload as a new cloud profile (strict create)
143
+ browserless profile upload \
144
+ --browser chrome --profile Default --name my-chrome
145
+
146
+ # Re-capture and overwrite an existing cloud profile (strict replace)
147
+ browserless profile refresh \
148
+ --browser chrome --profile Default --name my-chrome
149
+
150
+ # Capture and print a summary without uploading (handy for debugging)
151
+ browserless profile inspect --browser chrome --profile Default
152
+
153
+ # Launch your real browser interactively against the local profile —
154
+ # useful for fixing up auth state (logging in, dismissing dialogs)
155
+ # before re-running `profile refresh`. Source browser must be closed.
156
+ browserless profile launch --browser chrome --profile Default
157
+
158
+ # Manage cloud profiles
159
+ browserless profile list
160
+ browserless profile list --limit 50 --offset 0
161
+ browserless profile show my-chrome
162
+ browserless profile rename my-chrome my-chrome-v2
163
+ browserless profile delete my-chrome-v2
164
+ ```
165
+
166
+ ### `--browser` and `--profile`
167
+
168
+ `--browser` accepts either the short key or the display name in quotes:
169
+
170
+ | Key | Display name |
171
+ | --------------- | -------------------------------------------------- |
172
+ | `chrome` | Google Chrome |
173
+ | `chrome-beta` | Google Chrome Beta |
174
+ | `chrome-dev` | Google Chrome Dev |
175
+ | `chrome-canary` | Google Chrome Canary |
176
+ | `brave` | Brave |
177
+ | `edge` | Microsoft Edge |
178
+ | `vivaldi` | Vivaldi |
179
+ | `opera` | Opera |
180
+ | `arc` | Arc |
181
+ | `chromium` | Chromium (incl. Snap on Linux) |
182
+ | (custom) | whatever you registered via `profile sources add` |
183
+
184
+ The match is case-insensitive: `--browser CHROME`, `--browser Chrome`,
185
+ and `--browser "google chrome"` all resolve to the same entry.
186
+
187
+ `--profile` accepts either the user-visible profile name from `Local
188
+ State` (e.g. `Personal`, `Work`) or the on-disk directory name
189
+ (`Default`, `Profile 1`). If multiple profiles match (rare — display
190
+ names should be unique within a browser), the CLI prints all candidates
191
+ so you can disambiguate by passing the directory name.
192
+
193
+
194
+ ## 🔒 Privacy & Domain Filtering
195
+
196
+ Cookies and origin storage for sensitive domains can be filtered out
197
+ **locally**, before the upload leaves your machine — Browserless never
198
+ sees them:
199
+
200
+ ```bash
201
+ browserless profile exclude add chase.com
202
+ browserless profile exclude add "*.okta.com"
203
+ browserless profile exclude list
204
+ browserless profile exclude rm chase.com
205
+ ```
206
+
207
+ Suffix-match: `example.com` matches `example.com`, `.example.com`,
208
+ `www.example.com`, and `sub.www.example.com`. The optional `*.` prefix
209
+ is the default behaviour — `*.example.com` is identical to
210
+ `example.com`. Non-ASCII / IDN domains are accepted; they're
211
+ punycode-normalized to match how Chrome stores them.
212
+
213
+ Or one-shot for a specific upload (repeatable):
214
+
215
+ ```bash
216
+ browserless profile upload \
217
+ --browser chrome --profile Default --name demo \
218
+ --exclude-domain chase.com --exclude-domain "*.okta.com"
219
+ ```
220
+
221
+ Use `--no-default-excludes` to ignore the persistent list for a single
222
+ invocation (e.g. when refreshing a profile that *needs* a domain that's
223
+ normally excluded).
224
+
225
+ > **In addition to your list**, the CLI always filters out cookies and
226
+ > origin storage for `localhost`, `*.local`, `*.internal`, and IP-literal
227
+ > hosts. These aren't user-configurable — they protect against accidentally
228
+ > uploading intranet / corp / local-network state that would never apply
229
+ > to a cloud session anyway.
230
+
231
+
232
+ ## 📦 Managing Artifact Size
233
+
234
+ The Browserless server caps uploaded profiles at **2 MB** of serialized
235
+ state (cookies + per-origin localStorage + IndexedDB). Real-world
236
+ profiles usually fit easily, but a handful of heavyweight sites
237
+ (figma.com, google.com, vendor analytics) can push you over. When the
238
+ capture exceeds the cap, the CLI prints the heaviest origins on stderr
239
+ and the upload returns HTTP 400 — pick one of the flags below to fit
240
+ under it.
241
+
242
+ | Flag | Effect |
243
+ | ------------------- | --------------------------------------------------------------------------------------------------------------- |
244
+ | `--auto-fit` | Drop the heaviest origins (largest first) until the artifact fits under the cap. Cookies are never dropped. |
245
+ | `--keep-domain <d>` | Protect a domain from `--auto-fit` drops — suffix-match (same syntax as `--exclude-domain`), repeatable. |
246
+ | `--only-domain <d>` | Allowlist: capture only cookies / origins matching these domains, discard everything else. Suffix-match, repeatable. Applies after `--exclude-domain`. |
247
+
248
+ ```bash
249
+ # Auto-drop heaviest origins so the upload succeeds, but never drop google.com
250
+ browserless profile upload \
251
+ --browser chrome --profile Default --name demo \
252
+ --auto-fit --keep-domain google.com --keep-domain github.com
253
+
254
+ # Capture only the sites you care about — everything else is discarded locally
255
+ browserless profile upload \
256
+ --browser chrome --profile Default --name demo \
257
+ --only-domain github.com --only-domain "*.atlassian.net"
258
+ ```
259
+
260
+ `--auto-fit` reports each origin it dropped on stderr; `--only-domain`
261
+ reports how many cookies / origins it kept and dropped. If `--auto-fit`
262
+ can't reach the cap because every remaining heavy origin is protected
263
+ by `--keep-domain`, the CLI tells you which `--keep-domain` to relax.
264
+
265
+
266
+ ## 🧩 Custom Chromium Browsers
267
+
268
+ Register any Chromium-based binary the built-in registry doesn't know
269
+ about (Thorium, Cromite, a self-built Chromium, ...):
270
+
271
+ ```bash
272
+ browserless profile sources add \
273
+ --name my-chromium \
274
+ --path /path/to/chromium \
275
+ --user-data-dir /path/to/user-data-dir
276
+ browserless profile sources rm my-chromium
277
+ ```
278
+
279
+ The `--name` doubles as both the display name and the `--browser <key>`
280
+ value. Registrations are stored in `~/.browserless/custom-browsers.json`.
281
+ If the binary or `user-data-dir` later goes missing, `profile sources
282
+ list` flags the entry under "Registered custom browsers with missing
283
+ paths" so you can clean it up with `profile sources rm`.
284
+
285
+
286
+ ## ⚙️ Shared Flags
287
+
288
+ Every command that hits the cloud API accepts:
289
+
290
+ | Flag | Effect |
291
+ | ----------------- | --------------------------------------------------------------- |
292
+ | `--token <tok>` | Override token resolution (flag > env > keychain > config file) |
293
+ | `--server <url>` | Override the configured server URL |
294
+ | `--region <code>` | `sfo` / `lon` / `ams` — shorthand for `--server` |
295
+ | `--json` | Emit the server response as JSON (script-friendly) |
296
+
297
+ Capture commands (`upload`, `refresh`, `inspect`) also accept:
298
+
299
+ | Flag | Effect |
300
+ | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
301
+ | `--exclude-domain <d>` | Append a domain to the exclusion list for this run (repeatable) |
302
+ | `--no-default-excludes` | Skip the persistent exclusion list for this run |
303
+ | `--only-domain <d>` | Allowlist: capture only domains matching this pattern (repeatable, applies after `--exclude-domain`) |
304
+ | `--auto-fit` | If the artifact exceeds the 2 MB server cap, drop the heaviest origins until it fits (see [Managing Artifact Size](#-managing-artifact-size)) |
305
+ | `--keep-domain <d>` | Domain that `--auto-fit` must never drop (repeatable) |
306
+ | `--accept-terms` | Pre-accept the liability disclaimer |
307
+ | `--terms-ttl-days <n>` | Override the re-prompt TTL for this run (0 = every run) |
308
+ | `--password-store <s>` | Linux only — pass `basic` / `gnome-libsecret` / `kwallet5` through to the launched browser if auto-detection picks wrong |
309
+
310
+
311
+ ## 🛠 Configuration
312
+
313
+ `~/.browserless/config.json` is created with mode 0600 on first use.
314
+ Manage user-managed keys via the commands below; CLI-managed keys are
315
+ written automatically and not user-editable.
316
+
317
+ | Key | Kind | How to change |
318
+ | ------------------- | ----------- | ------------------------------------------------------------------------ |
319
+ | `server` | user scalar | `browserless config set server <url>` (mutually exclusive with `region`) |
320
+ | `region` | user scalar | `browserless config set region <sfo\|lon\|ams>` |
321
+ | `terms_ttl_days` | user scalar | `browserless config set terms_ttl_days <n>` (default 7) |
322
+ | `excluded_domains` | user list | `browserless profile exclude add/rm/list` |
323
+ | `accepted_terms_at` | CLI-managed | written when you accept the disclaimer |
324
+ | `token_storage` | CLI-managed | written by `auth login` (`keychain` or `file`) |
325
+ | `api_key` | CLI-managed | written by `auth login` only when keychain is unavailable |
326
+
327
+ ```bash
328
+ browserless config get server
329
+ browserless config get api_key # redacted by default
330
+ browserless config get api_key --show-sensitive # print verbatim
331
+ browserless config set terms_ttl_days 30
332
+ browserless config unset region
333
+ ```
334
+
335
+ `config set` is scalar-only — list keys (`excluded_domains`) go through
336
+ `profile exclude`, CLI-managed keys can't be set directly (they have
337
+ side-effects the CLI itself owns).
338
+
339
+
340
+ ## 🌍 Environment Variables
341
+
342
+ | Variable | Effect |
343
+ | ------------------------------ | ---------------------------------------------------------------------- |
344
+ | `BROWSERLESS_TOKEN` | Use this token without a stored credential (overrides keychain + file) |
345
+ | `BROWSERLESS_ACCEPT_TERMS` | `1` to pre-accept the liability disclaimer |
346
+ | `BROWSERLESS_CONFIG_DIR` | Override `~/.browserless/` location (CI / multi-tenant) |
347
+ | `BROWSERLESS_DISABLE_KEYCHAIN` | `1` to force plaintext config-file storage even if the keychain works |
348
+ | `BROWSERLESS_CDP_WAIT_MS` | Override the 15 s CDP-readiness timeout (raise on slow CI runners) |
349
+
350
+
351
+ ## 🚦 Exit Codes
352
+
353
+ | Code | Meaning |
354
+ | ---- | ------------------------------------------------------------------------------------------------------- |
355
+ | 0 | Success |
356
+ | 1 | Internal bug — prints a stack trace |
357
+ | 2 | Bad arguments (`UsageError`) |
358
+ | 3 | Precondition failed — no token, disclaimer declined, profile busy, corrupt config (`PreconditionError`) |
359
+ | 4 | Local capture pipeline failed — copy / browser launch / CDP (`CaptureError`) |
360
+ | 5 | Server returned a non-2xx response (`ApiError`) |
361
+
362
+
363
+ ## 💡 Why use the CLI?
364
+
365
+ **Sharing a logged-in browser session with a cloud worker is painful.**
366
+
367
+ Cookies live in OS-encrypted SQLite. localStorage and IndexedDB are
368
+ spread across LevelDB on disk. Manually re-logging in on every cloud
369
+ session is busywork — and rolling your own cookie export usually ends
370
+ in *"why am I randomly logged out of everything?"* when Chrome Sync
371
+ realises a copy of the profile woke up on a server farm.
372
+
373
+ **The CLI does this once, safely.** It launches a *temporary copy* of
374
+ your profile in a controlled-headless mode that suppresses Chrome Sync
375
+ / Safe Browsing / component-update traffic, reads cookies +
376
+ localStorage + IndexedDB via CDP, applies your domain-exclusion list
377
+ **locally**, and uploads only the result. Your real profile is never
378
+ touched; sensitive domains never leave your machine.
379
+
380
+ Once uploaded, any Browserless cloud session can attach the profile
381
+ via `?profile=<name>` and start *already authenticated*.
382
+
383
+
384
+ ## 📜 Licensing
385
+
386
+ Distributed as part of the Browserless platform. The `LICENSE` file
387
+ ships in the package; see [browserless.io](https://browserless.io) for
388
+ full terms.
389
+
390
+ If you're building a commercial application on Browserless, a
391
+ [commercial license](https://www.browserless.io/contact) covers
392
+ priority support, on-premise deployment, source modification, and
393
+ the admin UI in addition to keeping your software proprietary.
394
+
395
+
396
+ <div align="center">
397
+
398
+ **Happy capturing!**
399
+
400
+ Need help? Reach out to us at **support@browserless.io**
401
+
402
+ </div>
@@ -0,0 +1 @@
1
+ var o=Object.defineProperty;var e=(t,r)=>o(t,"name",{value:r,configurable:!0});import{apiFetch as a}from"./client.js";import{ApiError as i}from"../errors.js";const c=e(async t=>{try{return await a(t,{method:"GET",path:"/profiles",query:{limit:1}}),!0}catch(r){if(r instanceof i&&r.status===401)return!1;throw r}},"validateToken");export{c as validateToken};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var f=(r,e)=>u(r,"name",{value:e,configurable:!0});import{ApiError as d}from"../errors.js";const $=3e4,l=f((r,e,n,t)=>{const a=r.endsWith("/")?r:`${r}/`,m=e.replace(/^\/+/,""),c=new URL(m,a);if(c.searchParams.set("token",n),t)for(const[h,s]of Object.entries(t))s!==void 0&&c.searchParams.set(h,String(s));return c},"buildUrl"),w=f((r,e,n)=>{if(!n)return`HTTP ${r} ${e}`;try{const a=JSON.parse(n);if(a?.message&&typeof a.message=="string")return a.message}catch{}const t=n.trim();return t.length>200?`HTTP ${r} ${e}: ${t.slice(0,200)}\u2026`:`HTTP ${r} ${e}: ${t}`},"messageFromBody"),T=f(async(r,e)=>{const n=l(r.server,e.path,r.token,e.query),t={method:e.method};let a;e.rawBody!==void 0?a=e.rawBody:e.body!==void 0&&(a=JSON.stringify(e.body)),a!==void 0&&(t.body=a,t.headers={"Content-Type":"application/json"});const m=e.timeoutMs??$,c=new AbortController,h=setTimeout(()=>c.abort(),m);t.signal=c.signal;let s;try{s=await fetch(n,t)}catch(i){throw i?.name==="AbortError"?new d(`Request to ${r.server}${e.path} timed out after ${m}ms`,0):new d(`Failed to reach ${r.server}: ${i?.message??i}`,0)}finally{clearTimeout(h)}let o;try{o=await s.text()}catch(i){throw i?.name==="AbortError"?new d(`Request to ${r.server}${e.path} timed out after ${m}ms`,0):new d(`Failed to read response from ${r.server}${e.path}: ${i?.message??i}`,0)}if(!s.ok)throw new d(w(s.status,s.statusText,o),s.status,o);if(!(s.status===204||!o))try{return JSON.parse(o)}catch{throw new d(`Server returned non-JSON response: ${o}`,s.status,o)}},"apiFetch");export{T as apiFetch};
@@ -0,0 +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};
@@ -0,0 +1 @@
1
+ var f=Object.defineProperty;var e=(r,o)=>f(r,"name",{value:o,configurable:!0});import{apiFetch as i}from"./client.js";import{buildProfileBody as t}from"./upload.js";const a=e(async(r,o)=>i(r,{method:"POST",path:"/profile/refresh",rawBody:t(o)}),"refreshProfile");export{a as refreshProfile};
@@ -0,0 +1 @@
1
+ var o=Object.defineProperty;var i=(e,t)=>o(e,"name",{value:t,configurable:!0});import{apiFetch as n}from"./client.js";const d=i(e=>e.serialized!==void 0?`{"name":${JSON.stringify(e.name)},"state":${e.serialized}}`:JSON.stringify({name:e.name,state:e.state}),"buildProfileBody"),a=i(async(e,t)=>n(e,{method:"POST",path:"/profile/upload",rawBody:d(t)}),"uploadProfile");export{d as buildProfileBody,a as uploadProfile};
@@ -0,0 +1,16 @@
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=`
2
+ Heads up \u2014 uploading a profile sends authentication state to Browserless:
3
+
4
+ \u2022 Cookies, localStorage and IndexedDB from the browser profile you select
5
+ are read locally, encrypted, and uploaded to the Browserless server you
6
+ are pointing at.
7
+ \u2022 Only upload profiles you have authority to share. Cookies for banking,
8
+ healthcare, employer-SSO or other sensitive sites should be added to the
9
+ domain exclusion list (\`browserless profile exclude add <domain>\`).
10
+ \u2022 Your local browser profile is never modified \u2014 the CLI runs against a
11
+ temporary copy and cleans it up after capture.
12
+
13
+ By continuing you confirm you understand the above and accept responsibility
14
+ 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{R as ensureTermsAccepted};
@@ -0,0 +1 @@
1
+ var i=Object.defineProperty;var n=(e,r)=>i(e,"name",{value:r,configurable:!0});import{errMessage as c}from"../utils/errors.js";const l="@browserless.io/cli";let a;const o=n(async()=>{if(a!==void 0)return a;if(process.env.BROWSERLESS_DISABLE_KEYCHAIN==="1")return a=null,null;try{const e=await import("@napi-rs/keyring");a="default"in e?e.default:e}catch{a=null}return a},"loadKeyring"),d=n(e=>{a=e},"__setKeyringForTests"),f=n(async()=>await o()!==null,"keychainAvailable"),k=n(async e=>{const r=await o();if(!r)return{ok:!1,reason:"unavailable"};try{return{ok:!0,value:new r.Entry(l,e).getPassword()}}catch(t){return{ok:!1,reason:"op-failed",error:c(t)}}},"readFromKeychain"),w=n(async(e,r)=>{const t=await o();if(!t)return{ok:!1,reason:"unavailable"};try{return new t.Entry(l,e).setPassword(r),{ok:!0}}catch(s){return{ok:!1,reason:"op-failed",error:c(s)}}},"writeToKeychain"),p=n(async e=>{const r=await o();if(!r)return{ok:!1,reason:"unavailable"};try{return{ok:!0,existed:new r.Entry(l,e).deletePassword()}}catch(t){return{ok:!1,reason:"op-failed",error:c(t)}}},"deleteFromKeychain");export{d as __setKeyringForTests,p as deleteFromKeychain,f as keychainAvailable,k as readFromKeychain,w as writeToKeychain};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var t=(e,n)=>c(e,"name",{value:n,configurable:!0});import{readConfig as s,updateConfig as a}from"../config/store.js";import{DEFAULT_SERVER as f}from"../config/schema.js";import{deleteFromKeychain as g,readFromKeychain as u,writeToKeychain as k}from"./keychain.js";import{PreconditionError as i}from"../errors.js";import{regionToServerUrl as l}from"../regions.js";const w="BROWSERLESS_TOKEN",b=t(async e=>{const n=typeof e=="string"?e:e?.server,o=typeof e=="string"?void 0:e?.region;if(o&&n)throw new i("--region and --server are mutually exclusive \u2014 pass one or the other.","server-region-conflict");if(o)return l(o);if(n)return n;const r=await s();if(r.region&&r.server)throw new i(`Both "region" (${r.region}) and "server" (${r.server}) are set in ~/.browserless/config.json \u2014 unset one with \`browserless config unset region\` or \`browserless config unset server\`.`,"server-region-conflict");return r.region?l(r.region):r.server??f},"resolveServer"),S=t(async e=>{if(e.flag)return{token:e.flag,source:"flag"};const n=process.env[w];if(n)return{token:n,source:"env"};const o=await u(e.server);if(o.ok){if(o.value!==null)return{token:o.value,source:"keychain"}}else if(o.reason==="op-failed")throw new i(`Keychain is available but read failed: ${o.error}. Retry, or set BROWSERLESS_DISABLE_KEYCHAIN=1 to bypass and use the plaintext fallback at ~/.browserless/config.json.`,"keychain-read-failed");const r=await s();if(r.api_key)return{token:r.api_key,source:"file"};throw new i("No API token configured. Run `browserless auth login` to set one.","no-token")},"resolveToken"),_=t(async e=>{const n=await k(e.server,e.token);if(n.ok)return await a(o=>{o.token_storage="keychain",delete o.api_key}),{mode:"keychain"};if(n.reason==="op-failed")throw new i(`Keychain is available but write failed: ${n.error}. Retry, or set BROWSERLESS_DISABLE_KEYCHAIN=1 to store the token in plaintext at ~/.browserless/config.json instead.`,"keychain-write-failed");return await a(o=>{o.token_storage="file",o.api_key=e.token}),{mode:"file",warning:"Token stored in plaintext at ~/.browserless/config.json \u2014 keychain unavailable on this system."}},"persistToken"),m=t(async e=>{const n=await g(e);if(!n.ok&&n.reason==="op-failed")throw new i(`Could not delete the keychain entry for ${e}: ${n.error}. The token may still be stored \u2014 fix the keychain access and re-run \`browserless auth logout\`.`,"keychain-delete-failed");await a(o=>{delete o.api_key,delete o.token_storage})},"clearToken"),R=t(async()=>(await s()).token_storage??"none","getTokenStorageMode");export{m as clearToken,R as getTokenStorageMode,_ as persistToken,b as resolveServer,S as resolveToken};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var t=(e,r)=>c(e,"name",{value:r,configurable:!0});import{customBrowsersFile as s}from"../config/paths.js";import{PreconditionError as m,UsageError as w}from"../errors.js";import{readJsonFile as f,writeSecureJsonFile as d}from"../utils/json-file.js";const l=t(e=>!!e&&typeof e=="object"&&typeof e.name=="string"&&typeof e.binaryPath=="string"&&typeof e.userDataDir=="string","isCustomBrowserShape"),u=t(e=>Array.isArray(e),"isUnknownArray"),a=t(async()=>{const e=s(),r=await f(e,{defaults:[],validate:u,errorCode:"invalid-custom-browsers-file",shapeHint:"a JSON array"});if(!r.every(l))throw new m(`${e} contains entries that do not match the expected shape ({ name, binaryPath, userDataDir }). Inspect and fix the file.`,"invalid-custom-browsers-file");return r},"readCustomBrowsers"),i=t(e=>d(s(),e),"writeCustomBrowsers"),g=t(async e=>{const r=await a();if(r.some(o=>o.name.toLowerCase()===e.name.toLowerCase()))throw new w(`A custom browser named "${e.name}" is already registered. Use \`profile sources rm\` first.`);await i([...r,e])},"addCustomBrowser"),x=t(async e=>{const r=await a(),o=r.filter(n=>n.name.toLowerCase()!==e.toLowerCase());return o.length===r.length?!1:(await i(o),!0)},"removeCustomBrowser");export{g as addCustomBrowser,a as readCustomBrowsers,x as removeCustomBrowser};
@@ -0,0 +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};
@@ -0,0 +1 @@
1
+ var i=Object.defineProperty;var n=(t,e)=>i(t,"name",{value:e,configurable:!0});import a from"node:fs/promises";import o from"node:path";import{pathExists as s}from"../utils/fs.js";const c=n(t=>{const e=t.trim().match(/^(.+)-(\d+)$/);return e?{hostname:e[1],pid:Number(e[2])}:null},"parseTarget"),l=n(t=>{try{return process.kill(t,0),!0}catch{return!1}},"isPidAlive"),d=n(async t=>{try{return await a.readlink(t)}catch{return null}},"readSymlinkTarget"),k=n(async t=>{if(process.platform==="win32")return await s(o.join(t,"lockfile"))?{locked:!0}:{locked:!1};const e=await d(o.join(t,"SingletonLock"));if(e===null)return{locked:!1};const r=c(e);return r?l(r.pid)?{locked:!0,pid:r.pid,hostname:r.hostname}:{locked:!1,pid:r.pid,hostname:r.hostname}:{locked:!1}},"checkProfileLock");export{k as checkProfileLock};
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var s=(e,t)=>l(e,"name",{value:t,configurable:!0});import i from"node:fs/promises";import d from"node:path";import{home_ as u}from"./paths.js";const f=["basic","gnome","gnome-libsecret","kwallet","kwallet5","detect"],a=s(e=>f.includes(e),"isValidPasswordStore"),p=s(async e=>{if(process.platform!=="linux")return null;const t=d.join(e,"Default","Preferences");try{const c=await i.readFile(t,"utf-8"),o=JSON.parse(c),n=o?.profile?.password_manager?.encryption_backend??o?.password_manager_enabled_pref;if(typeof n=="string"&&a(n))return n}catch{}const r=process.env.XDG_CURRENT_DESKTOP?.toLowerCase()??"";return r.includes("kde")?"kwallet5":r.includes("gnome")||r.includes("unity")?"gnome-libsecret":null},"detectLinuxPasswordStore"),x=s(async(e,t)=>{if(t&&a(t))return{store:t,defaulted:!1};const r=await p(e);return r?{store:r,defaulted:!1}:{store:"basic",defaulted:!0}},"resolveLinuxPasswordStore");export{p as detectLinuxPasswordStore,a as isValidPasswordStore,x as resolveLinuxPasswordStore};
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var o=(s,p)=>a(s,"name",{value:p,configurable:!0});import t from"node:os";import e from"node:path";const r=t.homedir(),c=o(()=>process.env.LOCALAPPDATA??e.join(r,"AppData","Local"),"winLocalAppData"),A=o(()=>process.env.APPDATA??e.join(r,"AppData","Roaming"),"winAppData"),P=o(()=>process.env.ProgramFiles??"C:\\Program Files","winProgramFiles"),l=o(()=>process.env["ProgramFiles(x86)"]??"C:\\Program Files (x86)","winProgramFilesX86"),g=o(()=>r,"home_");export{g as home_,A as winAppData,c as winLocalAppData,P as winProgramFiles,l as winProgramFilesX86};
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var t=(e,n)=>m(e,"name",{value:n,configurable:!0});import o from"node:path";import{home_ as c,winAppData as s,winLocalAppData as r,winProgramFiles as a,winProgramFilesX86 as p}from"./paths.js";const i=c(),h=[{key:"chrome",displayName:"Google Chrome",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/Google/Chrome"),linux:o.join(i,".config/google-chrome"),win32:o.join(r(),"Google","Chrome","User Data")},binaryPathByPlatform:{darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"],linux:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable"],win32:[o.join(a(),"Google","Chrome","Application","chrome.exe"),o.join(p(),"Google","Chrome","Application","chrome.exe"),o.join(r(),"Google","Chrome","Application","chrome.exe")]}},{key:"chrome-beta",displayName:"Google Chrome Beta",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/Google/Chrome Beta"),linux:o.join(i,".config/google-chrome-beta"),win32:o.join(r(),"Google","Chrome Beta","User Data")},binaryPathByPlatform:{darwin:["/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta"],linux:["/usr/bin/google-chrome-beta"],win32:[o.join(a(),"Google","Chrome Beta","Application","chrome.exe")]}},{key:"chrome-dev",displayName:"Google Chrome Dev",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/Google/Chrome Dev"),linux:o.join(i,".config/google-chrome-unstable"),win32:o.join(r(),"Google","Chrome Dev","User Data")},binaryPathByPlatform:{darwin:["/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev"],linux:["/usr/bin/google-chrome-unstable"],win32:[o.join(a(),"Google","Chrome Dev","Application","chrome.exe")]}},{key:"chrome-canary",displayName:"Google Chrome Canary",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/Google/Chrome Canary"),win32:o.join(r(),"Google","Chrome SxS","User Data")},binaryPathByPlatform:{darwin:["/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"],win32:[o.join(r(),"Google","Chrome SxS","Application","chrome.exe")]}},{key:"edge",displayName:"Microsoft Edge",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/Microsoft Edge"),linux:o.join(i,".config/microsoft-edge"),win32:o.join(r(),"Microsoft","Edge","User Data")},binaryPathByPlatform:{darwin:["/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"],linux:["/usr/bin/microsoft-edge","/usr/bin/microsoft-edge-stable"],win32:[o.join(p(),"Microsoft","Edge","Application","msedge.exe"),o.join(a(),"Microsoft","Edge","Application","msedge.exe")]}},{key:"brave",displayName:"Brave",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/BraveSoftware/Brave-Browser"),linux:o.join(i,".config/BraveSoftware/Brave-Browser"),win32:o.join(r(),"BraveSoftware","Brave-Browser","User Data")},binaryPathByPlatform:{darwin:["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"],linux:["/usr/bin/brave-browser","/usr/bin/brave"],win32:[o.join(a(),"BraveSoftware","Brave-Browser","Application","brave.exe"),o.join(p(),"BraveSoftware","Brave-Browser","Application","brave.exe"),o.join(r(),"BraveSoftware","Brave-Browser","Application","brave.exe")]}},{key:"vivaldi",displayName:"Vivaldi",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/Vivaldi"),linux:o.join(i,".config/vivaldi"),win32:o.join(r(),"Vivaldi","User Data")},binaryPathByPlatform:{darwin:["/Applications/Vivaldi.app/Contents/MacOS/Vivaldi"],linux:["/usr/bin/vivaldi","/usr/bin/vivaldi-stable"],win32:[o.join(r(),"Vivaldi","Application","vivaldi.exe")]}},{key:"opera",displayName:"Opera",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/com.operasoftware.Opera"),linux:o.join(i,".config/opera"),win32:o.join(s(),"Opera Software","Opera Stable")},binaryPathByPlatform:{darwin:["/Applications/Opera.app/Contents/MacOS/Opera"],linux:["/usr/bin/opera"],win32:[o.join(a(),"Opera","launcher.exe")]}},{key:"arc",displayName:"Arc",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/Arc/User Data")},binaryPathByPlatform:{darwin:["/Applications/Arc.app/Contents/MacOS/Arc"]}},{key:"chromium",displayName:"Chromium",userDataDirByPlatform:{darwin:o.join(i,"Library/Application Support/Chromium"),linux:[o.join(i,".config/chromium"),o.join(i,"snap/chromium/common/chromium")],win32:o.join(r(),"Chromium","User Data")},binaryPathByPlatform:{darwin:["/Applications/Chromium.app/Contents/MacOS/Chromium"],linux:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],win32:[o.join(a(),"Chromium","Application","chrome.exe"),o.join(r(),"Chromium","Application","chrome.exe")]}}],l=t((e,n)=>e.trim().toLowerCase()===n.trim().toLowerCase(),"matches"),w=t(e=>h.find(n=>l(e,n.key)||l(e,n.displayName))??null,"findBuiltInByKeyOrName");export{h as BUILT_IN_BROWSERS,w as findBuiltInByKeyOrName};
@@ -0,0 +1,62 @@
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:`
2
+ (() => {
3
+ const out = {};
4
+ for (let i = 0; i < localStorage.length; i++) {
5
+ const key = localStorage.key(i);
6
+ out[key] = localStorage.getItem(key);
7
+ }
8
+ return JSON.stringify(out);
9
+ })()
10
+ `,returnByValue:!0,awaitPromise:!1}),c=a?.result?.value?JSON.parse(a.result.value):{},i=await r.Runtime.evaluate({expression:`
11
+ (async (MAX_DBS, MAX_ENTRIES) => {
12
+ if (typeof indexedDB.databases !== 'function') return [];
13
+ const dbInfos = await indexedDB.databases();
14
+ const out = [];
15
+ for (const { name, version } of dbInfos.slice(0, MAX_DBS)) {
16
+ if (!name) continue;
17
+ try {
18
+ const db = await new Promise((resolve, reject) => {
19
+ const req = indexedDB.open(name, version);
20
+ req.onsuccess = () => resolve(req.result);
21
+ req.onerror = () => reject(req.error);
22
+ req.onupgradeneeded = () => {};
23
+ });
24
+ const stores = [];
25
+ for (const storeName of db.objectStoreNames) {
26
+ try {
27
+ const tx = db.transaction(storeName, 'readonly');
28
+ const store = tx.objectStore(storeName);
29
+ const indexes = [];
30
+ for (const indexName of store.indexNames) {
31
+ const idx = store.index(indexName);
32
+ indexes.push({
33
+ name: idx.name, keyPath: idx.keyPath,
34
+ unique: idx.unique, multiEntry: idx.multiEntry,
35
+ });
36
+ }
37
+ const [keys, values] = await Promise.all([
38
+ new Promise((res, rej) => {
39
+ const r = store.getAllKeys(undefined, MAX_ENTRIES);
40
+ r.onsuccess = () => res(r.result);
41
+ r.onerror = () => rej(r.error);
42
+ }),
43
+ new Promise((res, rej) => {
44
+ const r = store.getAll(undefined, MAX_ENTRIES);
45
+ r.onsuccess = () => res(r.result);
46
+ r.onerror = () => rej(r.error);
47
+ }),
48
+ ]);
49
+ const entries = keys.map((k, i) => ({ key: k, value: values[i] }));
50
+ stores.push({
51
+ name: storeName, keyPath: store.keyPath,
52
+ autoIncrement: store.autoIncrement, entries, indexes,
53
+ });
54
+ } catch {}
55
+ }
56
+ db.close();
57
+ out.push({ name, version, objectStores: stores });
58
+ } catch {}
59
+ }
60
+ return JSON.stringify(out);
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};
@@ -0,0 +1 @@
1
+ var p=Object.defineProperty;var n=(r,t)=>p(r,"name",{value:t,configurable:!0});import o from"node:fs/promises";import a from"node:path";import S from"node:os";import{CaptureError as s}from"../errors.js";const f=new Set(["Cache","Code Cache","GPUCache","GraphiteDawnCache","ShaderCache","Service Worker","Crashpad","optimization_guide_model_store","Default Cache"]),h=new Set(["History","History-journal","History Provider Cache","Top Sites","Top Sites-journal","Visited Links","Favicons","Favicons-journal","Shortcuts","Shortcuts-journal","Network Action Predictor","Network Action Predictor-journal","Login Data","Login Data-journal","Login Data For Account","Login Data For Account-journal","Web Data","Web Data-journal","Account Web Data","Account Web Data-journal","Affiliation Database","Affiliation Database-journal","AutofillStrikeDatabase","AutofillAiModelCache","passkey_enclave_state","trusted_vault.pb","Bookmarks","Bookmarks.bak","BookmarkMergedSurfaceOrdering","DIPS","DIPS-shm","DIPS-wal","Trust Tokens","Trust Tokens-journal","BrowsingTopicsState","BrowsingTopicsSiteData","BrowsingTopicsSiteData-journal","Reporting and NEL","Reporting and NEL-journal","SCT Auditing Pending Reports","Extensions","Extension Cookies","Extension Cookies-journal","Extension Rules","Extension Scripts","Extension State","Local Extension Settings","Managed Extension Settings","Sync Extension Settings","Sessions","Sync Data","Sync App Settings","Web Applications","Platform Notifications","Download Service","chrome_cart_db","commerce_subscription_db","discount_infos_db","discounts_db","parcel_tracking_db","heavy_ad_intervention_opt_out.db","heavy_ad_intervention_opt_out.db-journal","Safe Browsing Cookies","Safe Browsing Cookies-journal"]),m=["SingletonLock","SingletonSocket","SingletonCookie"],j=n(async r=>{const t=await o.mkdtemp(a.join(S.tmpdir(),"browserless-cli-")),c=a.join(r.userDataDir,"Local State"),d=a.join(t,"Local State");try{await o.copyFile(c,d)}catch(e){const i=e?.code;if(i!=="ENOENT")throw await o.rm(t,{recursive:!0,force:!0}).catch(()=>{}),new s(`Failed to copy ${c} (${i??"unknown error"}): ${e.message}`,"profile-copy-failed")}try{await o.writeFile(a.join(t,"First Run"),"")}catch(e){throw await o.rm(t,{recursive:!0,force:!0}).catch(()=>{}),new s(`Failed to write First Run marker in ${t}: ${e.message}`,"profile-copy-failed")}const u=a.join(t,r.profileDirName);try{await o.cp(r.profilePath,u,{recursive:!0,force:!0,filter:n(e=>{const i=a.relative(r.profilePath,e);if(!i)return!0;const l=i.split(a.sep)[0];return!(f.has(l)||h.has(l))},"filter")})}catch(e){throw await o.rm(t,{recursive:!0,force:!0}).catch(()=>{}),new s(`Failed to copy profile from ${r.profilePath}: ${e?.message??e}`,"profile-copy-failed")}return await Promise.all(m.flatMap(e=>[o.unlink(a.join(t,e)).catch(()=>{}),o.unlink(a.join(u,e)).catch(()=>{})])),t},"buildTempUserDataDir");export{j as buildTempUserDataDir};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var i=(t,e)=>u(t,"name",{value:e,configurable:!0});const c=i(t=>{let e=t.trim().toLowerCase();if(!e)return null;e.startsWith("*.")&&(e=e.slice(2)),e.startsWith(".")&&(e=e.slice(1));try{const r=new URL(e.includes("://")?e:`https://${e}`);r.hostname&&(e=r.hostname)}catch{}return e||null},"normalizeExclusion"),a=i((t,e)=>!!(t===e||t.endsWith(`.${e}`)),"hostMatches"),d=i((t,e)=>{if(e.length===0)return!1;let r;try{r=new URL(t).hostname.toLowerCase()}catch{return!0}for(const s of e){const n=c(s);if(n&&a(r,n))return!0}return!1},"originMatchesAny"),h=i(t=>{const e=t.domain.toLowerCase();return e.startsWith(".")?e.slice(1):e},"cookieHost"),p=i((t,e)=>{if(e.length===0)return!1;let r;try{r=new URL(t).hostname.toLowerCase()}catch{return!1}for(const s of e){const n=c(s);if(n&&a(r,n))return!0}return!1},"originAllowedBy"),m=i((t,e)=>{const r=e.map(c).filter(o=>o!==null);if(r.length===0)return{state:t,cookiesDropped:0,originsDropped:0};const s=i(o=>r.some(f=>a(o,f)),"isExcluded"),n=t.cookies.filter(o=>!s(h(o))),l=t.origins.filter(o=>{try{return!s(new URL(o.origin).hostname.toLowerCase())}catch{return!1}});return{state:{cookies:n,origins:l},cookiesDropped:t.cookies.length-n.length,originsDropped:t.origins.length-l.length}},"applyExclusions"),w=i((t,e,r)=>{const s=e??[];return r?s:[...t??[],...s]},"mergeExclusionPatterns"),k=i((t,e)=>{const r=e.map(c).filter(o=>o!==null);if(r.length===0)return{state:t,cookiesDropped:0,originsDropped:0};const s=i(o=>r.some(f=>a(o,f)),"isKept"),n=t.cookies.filter(o=>s(h(o))),l=t.origins.filter(o=>{try{return s(new URL(o.origin).hostname.toLowerCase())}catch{return!1}});return{state:{cookies:n,origins:l},cookiesDropped:t.cookies.length-n.length,originsDropped:t.origins.length-l.length}},"applyOnlyFilter");export{m as applyExclusions,k as applyOnlyFilter,w as mergeExclusionPatterns,c as normalizeExclusion,p as originAllowedBy,d as originMatchesAny};
@@ -0,0 +1 @@
1
+ var p=Object.defineProperty;var r=(i,n)=>p(i,"name",{value:n,configurable:!0});import g from"node:fs/promises";import{buildTempUserDataDir as m}from"./copy-profile.js";import{killBrowser as f,launchBrowser as D,pickFreePort as y,waitForDebuggerEndpoint as h}from"./launch.js";import{captureViaCdp as w}from"./cdp.js";const C=r(()=>process.hrtime.bigint(),"startTime"),k=r(i=>Number((process.hrtime.bigint()-i)/1000000n),"elapsedMs"),b=r(async i=>{const n=C(),o=i.onProgress;o?.({phase:"copying"});const c=await m(i.profile),t=await y();let a=null,d;try{o?.({phase:"launching"});const s=await D({profile:i.profile,userDataDir:c,port:t,passwordStoreOverride:i.passwordStoreOverride});a=s.child,d=s.passwordStoreDefaulted,o?.({phase:"waiting-for-debugger"}),await h(t,void 0,s.diagnostics),o?.({phase:"capturing-origins",attempted:0,total:0,origin:""});const e=await w(i.profile,t,i.excludedDomains??[],u=>o?.({phase:"capturing-origins",...u}),i.onlyDomains??[]);o?.({phase:"done"});const l=JSON.stringify(e.state);return{state:e.state,diagnostics:{cookieCountBeforeExclusion:e.cookieCountTotal,cookieCountExcluded:e.cookieCountExcluded,originCountBeforeExclusion:e.state.origins.length+e.originCountSkippedByExclusion+e.originCountSkippedByOnlyDomain,originCountExcluded:e.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:e.originCountSkippedByOnlyDomain,excludedDomains:i.excludedDomains??[],onlyDomains:i.onlyDomains??[],durationMs:k(n),failedOrigins:e.failedOrigins},capHit:e.capHit,passwordStoreDefaulted:d,serialized:l}}finally{a&&await f(a),await g.rm(c,{recursive:!0,force:!0}).catch(()=>{})}},"captureFromProfile");export{b as captureFromProfile};
@@ -0,0 +1,6 @@
1
+ var w=Object.defineProperty;var i=(e,r)=>w(e,"name",{value:r,configurable:!0});import f from"node:net";import{spawn as g,spawnSync as b}from"node:child_process";import{resolveLinuxPasswordStore as m}from"../browsers/password-store.js";import{CaptureError as p}from"../errors.js";const C=i(e=>new Promise(r=>setTimeout(r,e)),"sleep"),D=i(()=>new Promise((e,r)=>{const t=f.createServer();t.unref(),t.on("error",r),t.listen(0,"127.0.0.1",()=>{const n=t.address();t.close(()=>{typeof n=="object"&&n?e(n.port):r(new Error("Could not pick a free port"))})})}),"pickFreePort"),$=i(async(e,r=Number(process.env.BROWSERLESS_CDP_WAIT_MS)||15e3,t)=>{const n=Date.now()+r;let o;for(;Date.now()<n;){try{if((await fetch(`http://127.0.0.1:${e}/json/version`)).ok)return}catch(s){o=s}await C(150)}let a="";if(t){const s=t.getProcessState(),d=t.getStderr().trim();a=`
2
+ Browser process: pid=${s.pid??"unspawned"} exitCode=${s.exitCode} signal=${s.signalCode}
3
+ Launch command: ${s.spawnfile} ${s.spawnargs.slice(1).join(" ")}`+(d?`
4
+ Browser stderr (last ${Math.min(d.length,2e3)} chars):
5
+ ${d.slice(-2e3)}`:`
6
+ Browser stderr: <empty>`)}throw new p(`Browser CDP endpoint did not come up within ${r}ms (last error: ${String(o)})${a}`,"cdp-timeout")},"waitForDebuggerEndpoint"),k=["--disable-background-networking","--disable-component-update","--disable-sync","--disable-domain-reliability","--disable-datasaver-prompt","--no-pings","--no-service-autorun","--safebrowsing-disable-auto-update","--disable-external-intent-requests","--metrics-recording-only","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-back-forward-cache","--disable-ipc-flooding-protection","--disable-hang-monitor","--disable-popup-blocking","--disable-prompt-on-repost","--disable-search-engine-choice-screen","--disable-breakpad","--disable-client-side-phishing-detection","--disable-infobars","--disable-print-preview","--disable-desktop-notifications","--disable-speech-api","--disable-speech-synthesis-api","--suppress-message-center-popups","--noerrdialogs","--disable-blink-features=AutomationControlled","--disable-features="+["AcceptCHFrame","AutoExpandDetailsElement","AvoidUnnecessaryBeforeUnloadCheckSync","CertificateTransparencyComponentUpdater","DialMediaRouteProvider","GlobalMediaControls","HttpsUpgrades","ImprovedCookieControls","LazyFrameLoading","MediaRouter","PaintHolding","Translate","AutomationControlled","BackForwardCache","OptimizationHints","CalculateNativeWinOcclusion","AutofillServerCommunication","CrashReporting","OverscrollHistoryNavigation","InfiniteSessionRestore"].join(",")],B=i(async e=>{const r=e.headless??!0,t=[`--remote-debugging-port=${e.port}`,`--user-data-dir=${e.userDataDir}`,`--profile-directory=${e.profile.profileDirName}`,"--no-first-run","--no-default-browser-check"];r&&t.push("--headless=new","--disable-gpu",...k);let n=!1;if(process.platform==="linux"){const{store:l,defaulted:u}=await m(e.profile.userDataDir,e.passwordStoreOverride);t.push(`--password-store=${l}`),n=u}t.push("about:blank");const o=g(e.profile.binaryPath,t,{detached:!1,stdio:["ignore","pipe","pipe"]}),a=[];let s=0;const d=64*1024;return o.stdout?.on("data",()=>{}),o.stderr?.on("data",l=>{s>=d||(a.push(l),s+=l.length)}),{child:o,passwordStoreDefaulted:n,diagnostics:{getStderr:i(()=>Buffer.concat(a).toString("utf-8"),"getStderr"),getProcessState:i(()=>({pid:o.pid,exitCode:o.exitCode,signalCode:o.signalCode,spawnfile:o.spawnfile,spawnargs:o.spawnargs}),"getProcessState")}}},"launchBrowser"),P=i(async e=>{const r=await fetch(`http://127.0.0.1:${e}/json/version`);if(!r.ok)throw new p(`CDP /json/version returned ${r.status} ${r.statusText}`,"cdp-metadata-invalid");const t=await r.json();if(typeof t.webSocketDebuggerUrl!="string"||typeof t.Browser!="string")throw new p(`CDP /json/version returned an unexpected payload: ${JSON.stringify(t)}`,"cdp-metadata-invalid");return{Browser:t.Browser,webSocketDebuggerUrl:t.webSocketDebuggerUrl}},"fetchCdpMetadata"),c=i((e,r)=>new Promise(t=>{if(e.exitCode!==null||e.signalCode!==null){t();return}const n=setTimeout(t,r);e.once("exit",()=>{clearTimeout(n),t()})}),"waitExitOrTimeout"),E=i(async(e,r=2e3)=>{if(!(!e||e.killed)){if(process.platform==="win32"&&typeof e.pid=="number"){b("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0}),await c(e,r);return}e.kill("SIGTERM"),await c(e,r),!e.killed&&e.exitCode===null&&(e.kill("SIGKILL"),await c(e,5e3)),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),e.unref()}},"killBrowser");export{P as fetchCdpMetadata,E as killBrowser,B as launchBrowser,D as pickFreePort,$ as waitForDebuggerEndpoint};
File without changes
@@ -0,0 +1,21 @@
1
+ var O=Object.defineProperty;var p=(s,t)=>O(s,"name",{value:t,configurable:!0});import{resolveProfile as S}from"../browsers/discover.js";import{captureFromProfile as E}from"../capture/index.js";import{applyOnlyFilter as T,mergeExclusionPatterns as B,normalizeExclusion as C}from"../capture/exclusion.js";import{readConfig as F}from"../config/store.js";import{ensureTermsAccepted as P}from"../auth/disclaimer.js";import{UsageError as R}from"../errors.js";import{collectRepeated as h,parseNonNegativeInt as v}from"./client.js";import{formatBytes as a,measureOriginSizes as z,SERVER_ARTIFACT_CAP_BYTES as l,trimStateToFit as L}from"./trim-state.js";const U=p(s=>s.requiredOption("--browser <key>","Source browser key (chrome / brave / edge / ...) or display name").requiredOption("--profile <name>",'Source profile display name or directory (e.g. "Personal", "Default")').option("--exclude-domain <domain>","Append a domain to the exclusion list for this run (repeatable)",h).option("--no-default-excludes","Skip the persistent exclusion list for this run").option("--accept-terms","Pre-accept the liability disclaimer").option("--terms-ttl-days <n>","Override the disclaimer re-prompt TTL for this run").option("--password-store <store>","Linux only: --password-store value to pass through to the headless launch (basic / gnome-libsecret / kwallet5 / ...)").option("--auto-fit","If the captured artifact exceeds the 2 MB server cap, drop the heaviest origins (largest serialized contribution first) until it fits").option("--keep-domain <domain>","Domain that --auto-fit must never drop (suffix-match, same syntax as --exclude-domain; repeatable)",h).option("--only-domain <domain>","Capture only cookies / origins matching this domain \u2014 discard everything else (suffix-match; repeatable; applies after --exclude-domain)",h),"addCaptureFlags"),N=p(s=>{if(s.length>0&&!s.some(t=>C(t)!==null))throw new R(`--only-domain: no valid domain pattern in ${JSON.stringify(s)}. Use a hostname like "example.com" or "*.example.com".`)},"validateOnlyDomain"),V=p(async s=>{const{flags:t,requiresDisclaimer:w}=s,f=await S(t.browser,t.profile);w&&await P({acceptViaFlag:!!t.acceptTerms,ttlDaysOverride:t.termsTtlDays!==void 0?v("--terms-ttl-days",t.termsTtlDays):void 0});const x=await F(),$=B(x.excluded_domains,t.excludeDomain,t.defaultExcludes===!1);N(t.onlyDomain??[]),process.stderr.write(`> Capturing ${f.browserDisplayName} / ${f.profileDisplayName}
2
+ `);const k=5,u=p(e=>{process.stderr.write(` ${e}
3
+ `)},"writeLine"),b={copying:"copying profile data\u2026",launching:"launching headless browser\u2026","waiting-for-debugger":"waiting for browser to be ready\u2026"};let m="",y=0;const D={profile:f,excludedDomains:$,onlyDomains:t.onlyDomain??[],passwordStoreOverride:t.passwordStore,onProgress:p(e=>{if(e.phase!=="done"){if(e.phase==="capturing-origins"){if(e.attempted===0){m!=="capturing-origins"&&(m="capturing-origins",u("capturing per-origin storage\u2026"));return}if(!(e.attempted===e.total)&&e.attempted-y<k)return;y=e.attempted;const n=e.origin.length>50?e.origin.slice(0,47)+"\u2026":e.origin;u(` ${e.attempted}/${e.total} ${n}`);return}e.phase!==m&&(m=e.phase,u(b[e.phase]??e.phase))}},"onProgress")},r=await E(D);if(t.onlyDomain&&t.onlyDomain.length>0){const e=T(r.state,t.onlyDomain),n=r.state.cookies.length-e.state.cookies.length,o=r.diagnostics.originCountSkippedByOnlyDomain+e.originsDropped;(n>0||o>0)&&(r.state=e.state,r.serialized=JSON.stringify(e.state),process.stderr.write(` \u2192 --only-domain kept ${r.state.cookies.length} cookies / ${r.state.origins.length} origins; dropped ${n} cookies / ${o} origins not matching: ${t.onlyDomain.join(", ")}
4
+ `))}const i=r.diagnostics,g=Buffer.byteLength(r.serialized,"utf-8");if(process.stderr.write(`> Captured ${i.cookieCountBeforeExclusion} cookies, ${i.originCountBeforeExclusion} origins in ${i.durationMs}ms (artifact: ${a(g)})
5
+ `),i.cookieCountExcluded>0||i.originCountExcluded>0){const e=i.excludedDomains.length?i.excludedDomains.join(", "):"(none)";process.stderr.write(` \u2192 Excluded ${i.cookieCountExcluded} cookies / ${i.originCountExcluded} origins matching: ${e}
6
+ `)}if(r.capHit&&process.stderr.write(` ! Hit the per-capture origin cap \u2014 some origins may be missing
7
+ `),i.failedOrigins.length>0){process.stderr.write(` ! ${i.failedOrigins.length} origin(s) failed to capture \u2014 their localStorage / IndexedDB is missing from the upload:
8
+ `);for(const e of i.failedOrigins)process.stderr.write(` - ${e.origin}: ${e.error}
9
+ `)}if(r.passwordStoreDefaulted&&process.stderr.write(` ! Linux password-store could not be detected \u2014 defaulted to "basic". If decryption failed, re-run with --password-store=<your store>
10
+ `),g>l){const e=z(r.state),d=10;process.stderr.write(` ! artifact size ${a(g)} exceeds the ${a(l)} server cap \u2014 heaviest origins:
11
+ `);for(const{origin:n,bytes:o}of e.slice(0,d))process.stderr.write(` ${a(o).padStart(10)} ${n}
12
+ `);if(e.length>d&&process.stderr.write(` \u2026 and ${e.length-d} more origins below ${a(e[d].bytes)}
13
+ `),t.autoFit){const n=t.keepDomain??[],o=L(r.state,l,n);if(o.dropped.length===0&&o.finalBytes<=l)process.stderr.write(` ! --auto-fit had nothing to drop \u2014 artifact unchanged
14
+ `);else{if(r.state=o.state,r.serialized=o.serialized,i.failedOrigins=[...i.failedOrigins,...o.dropped.map(c=>({origin:c,error:"dropped by --auto-fit to fit under the server cap",kind:"unknown"}))],o.dropped.length>0){process.stderr.write(` --auto-fit: dropped ${o.dropped.length} origin(s), now ${a(o.finalBytes)}:
15
+ `);for(const c of o.dropped)process.stderr.write(` - ${c}
16
+ `)}if(o.protectedFromDrop.length>0){process.stderr.write(` --auto-fit: ${o.protectedFromDrop.length} heavy origin(s) protected by --keep-domain:
17
+ `);for(const c of o.protectedFromDrop)process.stderr.write(` - ${c}
18
+ `)}o.finalBytes>l&&(o.protectedFromDrop.length>0?process.stderr.write(` ! Still ${a(o.finalBytes)} after the trim \u2014 the --keep-domain origins alone exceed the cap. Remove one or more --keep-domain entries, or accept the upload will be rejected.
19
+ `):process.stderr.write(` ! Even after dropping every droppable origin the artifact is still over cap. The cookies alone may be too heavy.
20
+ `))}}else process.stderr.write(` Re-run with --auto-fit to drop the heaviest origins automatically (combine with --keep-domain <domain> to protect specific sites; or --only-domain <domain> to capture just those), or pass --exclude-domain <host> for each you want removed.
21
+ `)}return r},"runCapture");export{U as addCaptureFlags,V as runCapture,N as validateOnlyDomain};
@@ -0,0 +1,2 @@
1
+ var i=Object.defineProperty;var o=(e,r)=>i(e,"name",{value:r,configurable:!0});import{resolveServer as c,resolveToken as l}from"../auth/store.js";import{UsageError as a}from"../errors.js";import{KNOWN_REGIONS as p}from"../regions.js";const m=o(async e=>{const r=await c({server:e.server,region:e.region}),{token:t,source:n}=await l({flag:e.token,server:r});return{server:r,token:t,source:n}},"buildClient"),k=o((e,r)=>[...r??[],e],"collectRepeated"),v=o(e=>e.option("--server <url>","Browserless server URL").option("--region <code>",`Browserless region (${p.join(" | ")}) \u2014 shorthand for --server`),"addServerOverrideFlags"),x=o(e=>v(e.option("--token <token>","API token (overrides env / keychain / file)")).option("--json","Emit the server response as JSON"),"addClientFlags"),I=o(e=>{process.stdout.write(JSON.stringify(e,null,2)+`
2
+ `)},"printJson"),g=/^\d+$/,b=o((e,r,t=0)=>{const n=o(()=>{throw new a(`${e} must be a${t>0?" positive":" non-negative"} integer (got "${r}")`)},"fail");g.test(r)||n();const s=Number(r);return(!Number.isFinite(s)||!Number.isInteger(s)||s<t)&&n(),s},"parseNonNegativeInt");export{x as addClientFlags,v as addServerOverrideFlags,m as buildClient,k as collectRepeated,b as parseNonNegativeInt,I as printJson};
@@ -0,0 +1 @@
1
+ var y=Object.defineProperty;var n=(r,t)=>y(r,"name",{value:t,configurable:!0});import{originMatchesAny as l}from"../capture/exclusion.js";const B=n(r=>{try{return new URL(r),!0}catch{return!1}},"isParseableOrigin"),h=2*1024*1024,a=n(r=>r.origins.map(t=>({origin:t.origin,bytes:Buffer.byteLength(JSON.stringify(t),"utf-8")})).sort((t,s)=>s.bytes-t.bytes),"measureOriginSizes"),m=n((r,t,s=[])=>{let i=JSON.stringify(r),e=Buffer.byteLength(i,"utf-8");if(e<=t)return{state:r,serialized:i,dropped:[],protectedFromDrop:[],finalBytes:e};const u=[],g=[];let f=[...r.origins];const c=a(r);for(const{origin:o}of c){if(e<=t)break;if(s.length>0&&B(o)&&l(o,s)){g.push(o);continue}f=f.filter(p=>p.origin!==o),u.push(o),i=JSON.stringify({...r,origins:f}),e=Buffer.byteLength(i,"utf-8")}return{state:{...r,origins:f},serialized:i,dropped:u,protectedFromDrop:g,finalBytes:e}},"trimStateToFit"),S=n(r=>r>=1024*1024?`${(r/1024/1024).toFixed(2)} MB`:r>=1024?`${(r/1024).toFixed(1)} KB`:`${r} B`,"formatBytes");export{h as SERVER_ARTIFACT_CAP_BYTES,S as formatBytes,a as measureOriginSizes,m as trimStateToFit};
package/build/cli.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import{Command as e}from"commander";import{version as o}from"./version.js";import{registerProfile as i}from"./commands/profile/index.js";import{registerAuth as t}from"./commands/auth/index.js";import{registerConfig as n}from"./commands/config/index.js";import{exitCodeFor as m,UserFacingError as a}from"./errors.js";const s=new e;s.name("browserless").description("Browserless CLI \u2014 manage profiles, sessions, and more.").version(o),i(s),t(s),n(s),s.parseAsync(process.argv).catch(r=>{r instanceof a?process.stderr.write(`${r.message}
3
+ `):r instanceof Error?process.stderr.write(`${r.stack??r.message}
4
+ `):process.stderr.write(`${String(r)}
5
+ `),process.exit(m(r))});
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty;var o=(r,t)=>e(r,"name",{value:t,configurable:!0});import{registerAuthLogin as i}from"./login.js";import{registerAuthLogout as s}from"./logout.js";import{registerAuthStatus as m}from"./status.js";const n=o(r=>{const t=r.command("auth").description("Authenticate with Browserless");i(t),s(t),m(t)},"registerAuth");export{n as registerAuth};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var t=(o,e)=>c(o,"name",{value:e,configurable:!0});import{resolveServer as d,persistToken as f}from"../../auth/store.js";import{validateToken as m}from"../../api/auth.js";import{addServerOverrideFlags as k}from"../../cli-utils/client.js";import{PreconditionError as i}from"../../errors.js";const l=t(async()=>{const o=[];for await(const e of process.stdin)o.push(Buffer.from(e));return Buffer.concat(o).toString("utf-8").trim()},"readFromStdin"),v=t(async(o,e)=>{const n=await d({server:e.server,region:e.region});let r=o?.trim();if(!r){if(process.stdin.isTTY)throw new i("Pass the token as an argument or pipe it via stdin: `echo $TOKEN | browserless auth login`","no-token");r=await l()}if(!r)throw new i("No token provided.","no-token");if(!await m({server:n,token:r}))throw new i(`Token rejected by ${n} \u2014 double-check it and retry.`,"invalid-token");const{mode:a,warning:s}=await f({server:n,token:r});console.log(a==="keychain"?`\u2713 Token saved to OS keychain for ${n}`:`\u2713 Token saved to ~/.browserless/config.json for ${n}`),s&&console.log(`! ${s}`)},"action"),y=t(o=>{const e=o.command("login [token]").description("Validate and persist an API token (reads from stdin if no argument is given)");k(e).action(v)},"registerAuthLogin");export{y as registerAuthLogin};
@@ -0,0 +1 @@
1
+ var t=Object.defineProperty;var o=(e,r)=>t(e,"name",{value:r,configurable:!0});import{clearToken as s,resolveServer as n}from"../../auth/store.js";import{addServerOverrideFlags as a}from"../../cli-utils/client.js";const c=o(async e=>{const r=await n({server:e.server,region:e.region});await s(r),console.log(`\u2713 Cleared stored credentials for ${r}`)},"action"),g=o(e=>{const r=e.command("logout").description("Clear stored credentials for the configured server");a(r).action(c)},"registerAuthLogout");export{g as registerAuthLogout};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var t=(o,e)=>c(o,"name",{value:e,configurable:!0});import{getTokenStorageMode as l,resolveServer as v,resolveToken as d}from"../../auth/store.js";import{keychainAvailable as g}from"../../auth/keychain.js";import{validateToken as k}from"../../api/auth.js";import{addServerOverrideFlags as m}from"../../cli-utils/client.js";import{PreconditionError as h}from"../../errors.js";const u=t(async o=>{const e=await v({server:o.server,region:o.region}),a=await l(),s=await g();console.log(`server: ${e}`),console.log(`keychain support: ${s?"available":"unavailable"}`),console.log(`token storage: ${a}`);let r;try{r=await d({server:e})}catch(n){if(n instanceof h){console.log("token: (none \u2014 run `browserless auth login`)");return}throw n}console.log(`token source: ${r.source}`);const i=await k({server:e,token:r.token});console.log(`token check: ${i?"valid":"rejected"}`)},"action"),b=t(o=>{const e=o.command("status").description("Show which token slot is in use and where it is stored");m(e).action(u)},"registerAuthStatus");export{b as registerAuthStatus};
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var i=(o,n)=>s(o,"name",{value:n,configurable:!0});import{readConfig as t}from"../../config/store.js";import{allConfigKeys as r,isKnownKey as a,isSensitiveKey as c}from"../../config/schema.js";import{UsageError as f}from"../../errors.js";const g=i(async(o,n)=>{if(!a(o))throw new f(`Unknown config key "${o}". Known keys: ${r().join(", ")}.`);const e=(await t())[o];if(e===void 0){console.log("(unset)");return}if(c(o)&&!n.showSensitive){console.log("(redacted \u2014 pass --show-sensitive to reveal)");return}console.log(typeof e=="string"?e:JSON.stringify(e))},"action"),w=i(o=>{o.command("get <key>").description("Read a config value").option("--show-sensitive","Print sensitive values (api_key) verbatim instead of redacting").action(g)},"registerConfigGet");export{w as registerConfigGet};
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty;var i=(r,o)=>e(r,"name",{value:o,configurable:!0});import{registerConfigGet as t}from"./get.js";import{registerConfigSet as n}from"./set.js";import{registerConfigUnset as g}from"./unset.js";const p=i(r=>{const o=r.command("config").description("Read or write CLI configuration values");t(o),n(o),g(o)},"registerConfig");export{p as registerConfig};
@@ -0,0 +1 @@
1
+ var i=Object.defineProperty;var a=(t,o)=>i(t,"name",{value:o,configurable:!0});import{updateConfig as n}from"../../config/store.js";import{validateScalarSet as s}from"../../config/schema.js";const c=a(async(t,o)=>{const e=s(t,o);await n(r=>{r[t]=e}),console.log(`\u2713 Set ${t} = ${JSON.stringify(e)}`)},"action"),d=a(t=>{t.command("set <key> <value>").description("Write a scalar config value (server, region, terms_ttl_days)").action(c)},"registerConfigSet");export{d as registerConfigSet};
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var e=(t,o)=>a(t,"name",{value:o,configurable:!0});import{updateConfig as i}from"../../config/store.js";import{validateUnset as s}from"../../config/schema.js";const c=e(async t=>{const o=s(t);await i(n=>{delete n[o]}),console.log(`\u2713 Unset ${o}`)},"action"),f=e(t=>{t.command("unset <key>").description("Remove a config value, falling back to its default").action(c)},"registerConfigUnset");export{f as registerConfigUnset};
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var t=(o,e)=>l(o,"name",{value:e,configurable:!0});import{addClientFlags as r,buildClient as c,printJson as a}from"../../cli-utils/client.js";import{deleteProfile as s}from"../../api/profiles.js";const d=t(async(o,e)=>{const i=await c(e),n=await s(i,o);if(e.json){a(n);return}console.log(`\u2713 Deleted profile "${n.name}"`)},"action"),g=t(o=>{const e=o.command("delete <name>").description("Delete a cloud profile");r(e).action(d)},"registerDelete");export{g as registerDelete};
@@ -0,0 +1 @@
1
+ var i=Object.defineProperty;var t=(o,e)=>i(o,"name",{value:e,configurable:!0});import{updateConfig as a}from"../../../config/store.js";import{normalizeExclusion as r}from"../../../capture/exclusion.js";import{UsageError as s}from"../../../errors.js";const c=t(async o=>{const e=r(o);if(!e)throw new s(`"${o}" is not a valid domain pattern.`);await a(n=>{const d=new Set(n.excluded_domains??[]);d.add(e),n.excluded_domains=[...d]}),console.log(`\u2713 Excluded "${e}" from future uploads`)},"action"),f=t(o=>{o.command("add <domain>").description("Append a domain to the persistent exclusion list").action(c)},"registerExcludeAdd");export{f as registerExcludeAdd};
@@ -0,0 +1 @@
1
+ var i=Object.defineProperty;var t=(r,e)=>i(r,"name",{value:e,configurable:!0});import{registerExcludeList as o}from"./list.js";import{registerExcludeAdd as s}from"./add.js";import{registerExcludeRm as c}from"./rm.js";const x=t(r=>{const e=r.command("exclude").description("Manage the persistent domain exclusion list");o(e),s(e),c(e)},"registerProfileExclude");export{x as registerProfileExclude};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var t=(o,n)=>c(o,"name",{value:n,configurable:!0});import{readConfig as e}from"../../../config/store.js";const s=t(async()=>{const n=(await e()).excluded_domains??[];if(n.length===0){console.log("No excluded domains configured.");return}for(const i of n)console.log(i)},"action"),l=t(o=>{o.command("list").description("Print the current persistent exclusion list").action(s)},"registerExcludeList");export{l as registerExcludeList};
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var t=(o,e)=>l(o,"name",{value:e,configurable:!0});import{updateConfig as c}from"../../../config/store.js";import{normalizeExclusion as d}from"../../../capture/exclusion.js";import{UsageError as a}from"../../../errors.js";const f=t(async o=>{const e=d(o);if(!e)throw new a(`"${o}" is not a valid domain pattern.`);let n=!1;if(await c(i=>{const r=i.excluded_domains??[],s=r.filter(m=>m!==e);n=s.length!==r.length,i.excluded_domains=s}),!n)throw new a(`"${e}" was not in the exclusion list.`);console.log(`\u2713 Removed "${e}" from the exclusion list`)},"action"),g=t(o=>{o.command("rm <domain>").description("Remove a domain from the persistent exclusion list").action(f)},"registerExcludeRm");export{g as registerExcludeRm};
@@ -0,0 +1 @@
1
+ var i=Object.defineProperty;var o=(e,r)=>i(e,"name",{value:r,configurable:!0});import{registerList as t}from"./list.js";import{registerShow as m}from"./show.js";import{registerUpload as s}from"./upload.js";import{registerRefresh as f}from"./refresh.js";import{registerInspect as p}from"./inspect.js";import{registerLaunch as g}from"./launch.js";import{registerRename as c}from"./rename.js";import{registerDelete as n}from"./delete.js";import{registerProfileSources as a}from"./sources/index.js";import{registerProfileExclude as l}from"./exclude/index.js";const I=o(e=>{const r=e.command("profile").description("Manage authentication profiles");t(r),m(r),s(r),f(r),p(r),g(r),c(r),n(r),a(r),l(r)},"registerProfile");export{I as registerProfile};
@@ -0,0 +1,4 @@
1
+ var c=Object.defineProperty;var i=(s,o)=>c(s,"name",{value:o,configurable:!0});import{printJson as l}from"../../cli-utils/client.js";import{addCaptureFlags as g,runCapture as d}from"../../cli-utils/capture-runner.js";const m=i(async s=>{const o=await d({flags:s,requiresDisclaimer:!1});if(s.json){l(o.state);return}const e=new Map;for(const t of o.state.cookies)e.set(t.domain,(e.get(t.domain)??0)+1);const a=[...e.entries()].sort((t,n)=>n[1]-t[1]).slice(0,20);console.log(`
2
+ Summary:`),console.log(` cookies: ${o.state.cookies.length}`),console.log(` origins: ${o.state.origins.length}`),console.log(` duration: ${o.diagnostics.durationMs} ms`),console.log(`
3
+ Top cookie domains:`);for(const[t,n]of a)console.log(` ${n.toString().padStart(4)} ${t}`);if(o.state.origins.length>0){console.log(`
4
+ Origins with stored data:`);for(const t of o.state.origins){const n=Object.keys(t.localStorage).length,r=t.indexedDBs?.length??0;console.log(` - ${t.origin} (${n} ls keys, ${r} idb dbs)`)}}},"action"),h=i(s=>{const o=s.command("inspect").description("Capture a local profile and print a summary without uploading").option("--json","Emit the captured state as JSON");g(o).action(m)},"registerInspect");export{h as registerInspect};
@@ -0,0 +1,12 @@
1
+ var u=Object.defineProperty;var s=(e,r)=>u(e,"name",{value:r,configurable:!0});import{printJson as h}from"../../cli-utils/client.js";import{resolveProfile as f}from"../../browsers/discover.js";import{checkProfileLock as b}from"../../browsers/lock.js";import{fetchCdpMetadata as m,killBrowser as y,launchBrowser as g,pickFreePort as D,waitForDebuggerEndpoint as S}from"../../capture/launch.js";import{PreconditionError as k,UsageError as P}from"../../errors.js";const $=s((e,r)=>{const i=r?` (PID ${r})`:"";return`${e} is already running${i}. Quit it first (\u2318Q on macOS) and re-run \`browserless profile launch\`. \`profile launch\` boots a fresh process against your real profile dir, so the source browser must be closed.`},"formatProfileBusyMessage"),x=s(async e=>{if(!e.browser||!e.profile)throw new P("--browser and --profile are required");const r=await f(e.browser,e.profile),i=await b(r.userDataDir);if(i.locked)throw new k($(r.browserDisplayName,i.pid),"profile-busy");const t=await D(),{child:a,passwordStoreDefaulted:l,diagnostics:w}=await g({profile:r,userDataDir:r.userDataDir,port:t,headless:!!e.headless,passwordStoreOverride:e.passwordStore});let c=!1;const d=s(async()=>{c||(c=!0,process.stderr.write(`
2
+ > Shutting down browser
3
+ `),await y(a))},"cleanup"),n=s(o=>()=>{d().finally(()=>process.exit(o))},"signalHandler");process.once("SIGINT",n(130)),process.once("SIGTERM",n(143)),process.once("SIGBREAK",n(130));try{await S(t,void 0,w);const o=await m(t);e.json?h({pid:a.pid,httpEndpoint:`http://127.0.0.1:${t}`,webSocketDebuggerUrl:o.webSocketDebuggerUrl,browser:o.Browser,userDataDir:r.userDataDir,profileDirectory:r.profileDirName,headless:!!e.headless}):(process.stderr.write(`> Browser running (PID ${a.pid})
4
+ `),process.stderr.write(` ${o.Browser}
5
+ `),process.stderr.write(` HTTP endpoint: http://127.0.0.1:${t}
6
+ `),process.stderr.write(` WebSocket: ${o.webSocketDebuggerUrl}
7
+ `),l&&process.stderr.write(` ! Linux password-store could not be detected \u2014 defaulted to "basic". If sites that need stored passwords don't work, re-run with --password-store=<your store>
8
+ `),process.stderr.write(`
9
+ Note: this is your real ${r.browserDisplayName} profile \u2014 anything you do here persists.
10
+ `),process.stderr.write(`Press Ctrl-C to stop, or fully quit the browser (cmd-Q on macOS).
11
+ `)),await new Promise(p=>{a.once("exit",()=>p())}),process.stderr.write(`> Browser exited
12
+ `)}finally{await d()}},"action"),v=s(e=>{e.command("launch").description("Launch a local browser using your existing profile. Source browser must be closed; changes made in the launched window persist back to your real profile.").requiredOption("--browser <key>","Source browser key (chrome / brave / edge / ...) or display name").requiredOption("--profile <name>","Source profile display name or directory").option("--headless","Run the browser with no visible window").option("--password-store <store>","Linux only: --password-store value to pass through to the launched browser").option("--json","Print the launched browser metadata (PID, CDP URLs) as JSON").action(x)},"registerLaunch");export{$ as formatProfileBusyMessage,v as registerLaunch};
@@ -0,0 +1 @@
1
+ var g=Object.defineProperty;var i=(n,o)=>g(n,"name",{value:o,configurable:!0});import{addClientFlags as p,buildClient as h,parseNonNegativeInt as c,printJson as w}from"../../cli-utils/client.js";import{listProfiles as S}from"../../api/profiles.js";const A=i(async n=>{const o=await h(n),d=n.limit!==void 0?c("--limit",n.limit,1):void 0,m=n.offset!==void 0?c("--offset",n.offset):void 0,e=await S(o,{limit:d,offset:m});if(n.json){w(e);return}if(e.length===0){console.log("No profiles found.");return}const f=["NAME","COOKIES","ORIGINS","UPDATED","LAST USED"],a=e.map(t=>[t.name,String(t.cookieCount),String(t.originCount),t.updatedAt,t.lastUsedAt??"-"]),u=f.map((t,s)=>Math.max(t.length,...a.map(r=>r[s].length))),l=i(t=>console.log(t.map((s,r)=>s.padEnd(u[r])).join(" ")),"print");l(f);for(const t of a)l(t)},"action"),I=i(n=>{const o=n.command("list").description("List cloud profiles owned by the current token").option("--limit <n>","Maximum profiles to return").option("--offset <n>","Pagination offset");p(o).action(A)},"registerList");export{I as registerList};
@@ -0,0 +1,2 @@
1
+ var s=Object.defineProperty;var i=(e,o)=>s(e,"name",{value:o,configurable:!0});import{addClientFlags as t,buildClient as a,printJson as l}from"../../cli-utils/client.js";import{addCaptureFlags as c,runCapture as d}from"../../cli-utils/capture-runner.js";import{refreshProfile as f}from"../../api/refresh.js";const m=i(async e=>{const o=await d({flags:e,requiresDisclaimer:!0}),n=await a(e);process.stderr.write(`> Refreshing profile "${e.name}" on ${n.server}
2
+ `);const r=await f(n,{name:e.name,state:o.state,serialized:o.serialized});if(e.json){l(r);return}console.log(`\u2713 Profile "${r.name}" refreshed`),console.log(` id: ${r.id}`),console.log(` cookies: ${r.cookieCount}`),console.log(` origins: ${r.originCount}`),console.log(` updated: ${r.updatedAt}`)},"action"),C=i(e=>{const o=e.command("refresh").description("Capture a local browser profile and replace an existing cloud profile in place").requiredOption("--name <name>","Name of the existing cloud profile to refresh");c(t(o)).action(m)},"registerRefresh");export{C as registerRefresh};
@@ -0,0 +1 @@
1
+ var r=Object.defineProperty;var o=(n,e)=>r(n,"name",{value:e,configurable:!0});import{addClientFlags as c,buildClient as s,printJson as m}from"../../cli-utils/client.js";import{renameProfile as l}from"../../api/profiles.js";const d=o(async(n,e,t)=>{const a=await s(t),i=await l(a,n,e);if(t.json){m(i);return}console.log(`\u2713 Renamed "${n}" \u2192 "${i.name}"`)},"action"),u=o(n=>{const e=n.command("rename <old> <new>").description("Rename a cloud profile");c(e).action(d)},"registerRename");export{u as registerRename};
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var t=(n,e)=>l(n,"name",{value:e,configurable:!0});import{addClientFlags as s,buildClient as c,printJson as a}from"../../cli-utils/client.js";import{getProfile as d}from"../../api/profiles.js";const r=t(async(n,e)=>{const i=await c(e),o=await d(i,n);if(e.json){a(o);return}console.log(`name: ${o.name}`),console.log(`id: ${o.id}`),console.log(`cookies: ${o.cookieCount}`),console.log(`origins: ${o.originCount}`),console.log(`created: ${o.createdAt}`),console.log(`updated: ${o.updatedAt}`),console.log(`last used: ${o.lastUsedAt??"-"}`)},"action"),u=t(n=>{const e=n.command("show <name>").description("Show a single cloud profile's metadata");s(e).action(r)},"registerShow");export{u as registerShow};
@@ -0,0 +1 @@
1
+ var o=Object.defineProperty;var t=(r,e)=>o(r,"name",{value:e,configurable:!0});import n from"node:fs/promises";import{addCustomBrowser as s}from"../../../browsers/custom.js";import{findBuiltInByKeyOrName as d}from"../../../browsers/registry.js";import{UsageError as a}from"../../../errors.js";const m=t(async r=>{if(!r.name||!r.path||!r.userDataDir)throw new a("profile sources add requires --name, --path, and --user-data-dir");if(d(r.name))throw new a(`"${r.name}" collides with a built-in browser. Pick a different name (e.g. "${r.name}-custom").`);const[e,i]=await Promise.all([n.stat(r.path).catch(()=>null),n.stat(r.userDataDir).catch(()=>null)]);if(!e)throw new a(`--path does not exist: ${r.path}`);if(e.isDirectory())throw new a(`--path must point at a binary, not a directory: ${r.path}`);if(!i)throw new a(`--user-data-dir does not exist: ${r.userDataDir}`);if(!i.isDirectory())throw new a(`--user-data-dir must point at a directory: ${r.userDataDir}`);await s({name:r.name,binaryPath:r.path,userDataDir:r.userDataDir}),console.log(`\u2713 Registered custom browser "${r.name}"`)},"action"),D=t(r=>{r.command("add").description("Register a custom Chromium binary as a profile source").requiredOption("--name <name>","Identifier (also used as --browser key)").requiredOption("--path <path>","Path to the browser binary").requiredOption("--user-data-dir <dir>","Path to the browser's user-data-dir").action(m)},"registerSourcesAdd");export{D as registerSourcesAdd};
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var e=(o,r)=>s(o,"name",{value:r,configurable:!0});import{registerSourcesList as i}from"./list.js";import{registerSourcesAdd as c}from"./add.js";import{registerSourcesRm as t}from"./rm.js";const g=e(o=>{const r=o.command("sources").description("Manage local browser sources used as upload origins");i(r),c(r),t(r)},"registerProfileSources");export{g as registerProfileSources};
@@ -0,0 +1,2 @@
1
+ var a=Object.defineProperty;var l=(n,r)=>a(n,"name",{value:r,configurable:!0});import{printJson as c}from"../../../cli-utils/client.js";import{discoverProfiles as f,findBrokenCustomSources as m}from"../../../browsers/discover.js";const u=l(async n=>{const[r,t]=await Promise.all([f(),m()]);if(n.json){c({profiles:r,brokenCustoms:t});return}if(r.length===0&&t.length===0){console.log("No browser profiles detected. Use `profile sources add` to register a custom Chromium binary.");return}if(r.length>0){const s=r.reduce((o,e)=>{const i=`${e.browserDisplayName} (${e.browserKey})`;return(o[i]??=[]).push(e),o},{});for(const[o,e]of Object.entries(s)){console.log(`
2
+ ${o}`);for(const i of e)console.log(` ${i.profileDisplayName.padEnd(20)} (${i.profileDirName}) ${i.profilePath}`)}}if(t.length>0){console.log("\nRegistered custom browsers with missing paths (run `profile sources rm <name>` to clean up):");for(const s of t){const o=[];s.missingBinary&&o.push(`binary not found: ${s.binaryPath}`),s.missingUserDataDir&&o.push(`user-data-dir not found: ${s.userDataDir}`),console.log(` ${s.name}`);for(const e of o)console.log(` - ${e}`)}}},"action"),b=l(n=>{n.command("list").description("Show local browsers and profiles available for upload").option("--json","Emit JSON").action(u)},"registerSourcesList");export{b as registerSourcesList};
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var r=(o,e)=>s(o,"name",{value:e,configurable:!0});import{removeCustomBrowser as m}from"../../../browsers/custom.js";import{UsageError as t}from"../../../errors.js";const c=r(async o=>{if(!await m(o))throw new t(`No custom browser named "${o}" is registered.`);console.log(`\u2713 Removed custom browser "${o}"`)},"action"),d=r(o=>{o.command("rm <name>").description("Unregister a custom Chromium browser").action(c)},"registerSourcesRm");export{d as registerSourcesRm};
@@ -0,0 +1,2 @@
1
+ var n=Object.defineProperty;var a=(o,e)=>n(o,"name",{value:e,configurable:!0});import{addClientFlags as t,buildClient as l,printJson as s}from"../../cli-utils/client.js";import{addCaptureFlags as c,runCapture as d}from"../../cli-utils/capture-runner.js";import{uploadProfile as p}from"../../api/upload.js";const u=a(async o=>{const e=await d({flags:o,requiresDisclaimer:!0}),i=await l(o);process.stderr.write(`> Uploading to ${i.server}
2
+ `);const r=await p(i,{name:o.name,state:e.state,serialized:e.serialized});if(o.json){s(r);return}console.log(`\u2713 Profile "${r.name}" uploaded`),console.log(` id: ${r.id}`),console.log(` cookies: ${r.cookieCount}`),console.log(` origins: ${r.originCount}`),console.log(` created: ${r.createdAt}`)},"action"),C=a(o=>{const e=o.command("upload").description("Capture a local browser profile and upload it as a new cloud profile").requiredOption("--name <name>","Name for the new cloud profile");c(t(e)).action(u)},"registerUpload");export{C as registerUpload};
@@ -0,0 +1 @@
1
+ var n=Object.defineProperty;var o=(e,i)=>n(e,"name",{value:i,configurable:!0});import t from"node:os";import s from"node:path";const r=o(()=>process.env.BROWSERLESS_CONFIG_DIR||s.join(t.homedir(),".browserless"),"configDir"),f=o(()=>s.join(r(),"config.json"),"configFile"),j=o(()=>s.join(r(),"custom-browsers.json"),"customBrowsersFile");export{r as configDir,f as configFile,j as customBrowsersFile};
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var n=(e,t)=>l(e,"name",{value:t,configurable:!0});import{UsageError as s}from"../errors.js";import{isKnownRegion as c,KNOWN_REGIONS as d}from"../regions.js";const u="https://production-sfo.browserless.io",f=7,a={server:{kind:"scalar",sensitive:!1,parse:n(e=>{try{new URL(e)}catch{throw new s(`server must be a valid URL (got "${e}")`)}return e},"parse")},region:{kind:"scalar",sensitive:!1,parse:n(e=>{if(!c(e))throw new s(`region must be one of: ${d.join(", ")} (got "${e}"). For self-hosted or staging, use \`config set server <url>\` instead.`);return e},"parse")},terms_ttl_days:{kind:"scalar",sensitive:!1,parse:n(e=>{const t=Number(e);if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw new s(`terms_ttl_days must be a non-negative integer (got "${e}")`);return t},"parse")},excluded_domains:{kind:"list",manageHint:"`browserless profile exclude add/rm/list`",sensitive:!1},accepted_terms_at:{kind:"cli-managed",manageHint:"set automatically when you accept the disclaimer",sensitive:!1},token_storage:{kind:"cli-managed",manageHint:"set automatically by `browserless auth login`",sensitive:!1},api_key:{kind:"cli-managed",manageHint:"managed by `browserless auth login` / `auth logout`",sensitive:!0}},w=n(e=>a[e].sensitive,"isSensitiveKey"),o=n(()=>Object.keys(a),"allConfigKeys"),r=n(e=>Object.prototype.hasOwnProperty.call(a,e),"isKnownKey"),h=n((e,t)=>{if(!r(e))throw new s(`Unknown config key "${e}". Known keys: ${o().join(", ")}.`);const i=a[e];if(i.kind==="list")throw new s(`"${e}" is a list. Manage it via ${i.manageHint} \u2014 not via \`config set\`.`);if(i.kind==="cli-managed")throw new s(`"${e}" is managed by the CLI (${i.manageHint}). Editing it directly is not supported.`);return i.parse(t)},"validateScalarSet"),v=n(e=>{if(!r(e))throw new s(`Unknown config key "${e}". Known keys: ${o().join(", ")}.`);const t=a[e];if(t.kind==="cli-managed")throw new s(`"${e}" is managed by the CLI (${t.manageHint}). Use the relevant command to clear it.`);return e},"validateUnset");export{u as DEFAULT_SERVER,f as DEFAULT_TERMS_TTL_DAYS,o as allConfigKeys,r as isKnownKey,w as isSensitiveKey,h as validateScalarSet,v as validateUnset};
@@ -0,0 +1 @@
1
+ var n=Object.defineProperty;var r=(t,e)=>n(t,"name",{value:e,configurable:!0});import{configFile as i}from"./paths.js";import{readJsonFile as a,writeSecureJsonFile as c}from"../utils/json-file.js";const s=r(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isConfigShape"),f=r(async()=>{const t=await a(i(),{defaults:{},validate:r(e=>!0,"validate"),errorCode:"invalid-config-file"});return s(t)?t:{}},"readConfig"),u=r(t=>c(i(),t,{atomic:!0}),"writeConfig"),g=r(async t=>{const e=await f(),o=t(e)??e;return await u(o),o},"updateConfig");export{f as readConfig,g as updateConfig,u as writeConfig};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var t=(e,r)=>c(e,"name",{value:r,configurable:!0});class o extends Error{static{t(this,"UserFacingError")}exitCode=1;constructor(r){super(r),this.name="UserFacingError"}}class d extends o{static{t(this,"UsageError")}constructor(r){super(r),this.name="UsageError",this.exitCode=2}}class a extends o{static{t(this,"PreconditionError")}code;constructor(r,s){super(r),this.code=s,this.name="PreconditionError",this.exitCode=3}}class x extends o{static{t(this,"CaptureError")}code;constructor(r,s){super(r),this.code=s,this.name="CaptureError",this.exitCode=4}}class p extends o{static{t(this,"ApiError")}status;body;constructor(r,s,i){super(r),this.status=s,this.body=i,this.name="ApiError",this.exitCode=5}}const u=t(e=>e instanceof o?e.exitCode:1,"exitCodeFor");export{p as ApiError,x as CaptureError,a as PreconditionError,d as UsageError,o as UserFacingError,u as exitCodeFor};
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty;var r=(o,t)=>e(o,"name",{value:t,configurable:!0});import{UsageError as n}from"./errors.js";const s={sfo:"https://production-sfo.browserless.io",lon:"https://production-lon.browserless.io",ams:"https://production-ams.browserless.io"},p=Object.keys(s),i=r(o=>Object.prototype.hasOwnProperty.call(s,o),"isKnownRegion"),w=r(o=>{if(!i(o))throw new n(`Unknown region "${o}". Known regions: ${p.join(", ")}. For self-hosted or staging, pass --server <url> instead.`);return s[o]},"regionToServerUrl");export{p as KNOWN_REGIONS,s as REGION_URLS,i as isKnownRegion,w as regionToServerUrl};
@@ -0,0 +1 @@
1
+ var o=Object.defineProperty;var e=(s,n)=>o(s,"name",{value:n,configurable:!0});const a=e(s=>s instanceof Error?s.message:String(s),"errMessage");export{a as errMessage};
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var r=(t,s)=>a(t,"name",{value:s,configurable:!0});import c from"node:fs/promises";const o=r(async t=>{try{return await c.access(t),!0}catch{return!1}},"pathExists");export{o as pathExists};
@@ -0,0 +1 @@
1
+ var w=Object.defineProperty;var c=(e,r)=>w(e,"name",{value:r,configurable:!0});import a from"node:fs/promises";import s from"node:path";import{PreconditionError as m}from"../errors.js";const h=448,d=384,$=c(async(e,r)=>{let n;try{n=await a.readFile(e,"utf-8")}catch(t){const i=t?.code;if(i==="ENOENT")return r.defaults;throw new m(`Failed to read ${e} (${i??"unknown error"}): ${t.message}`,r.errorCode)}if(n.trim()==="")return r.defaults;let o;try{o=JSON.parse(n)}catch(t){throw new m(`Failed to parse ${e} \u2014 the file is not valid JSON. Inspect or remove it and retry. (${t.message})`,r.errorCode)}if(!r.validate(o)){const t=r.shapeHint??"the expected JSON shape";throw new m(`${e} does not match ${t}. Inspect and fix the file.`,r.errorCode)}return o},"readJsonFile"),F=c(async(e,r,n={})=>{const o=s.dirname(e);await a.mkdir(o,{recursive:!0,mode:h}),await a.chmod(o,h).catch(()=>{});const t=JSON.stringify(r,null,2);if(n.atomic){const i=s.join(o,`.${s.basename(e)}.${process.pid}.tmp`);await a.writeFile(i,t,{mode:d}),await a.rename(i,e),await a.chmod(e,d).catch(()=>{});return}await a.writeFile(e,t,{mode:d}),await a.chmod(e,d).catch(()=>{})},"writeSecureJsonFile");export{$ as readJsonFile,F as writeSecureJsonFile};
@@ -0,0 +1 @@
1
+ const o="0.0.1";export{o as version};
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@browserless.io/cli",
3
+ "version": "0.0.1",
4
+ "description": "Browserless CLI — manage authentication profiles, sessions, and other Browserless features from your terminal.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "browserless": "./build/cli.js"
9
+ },
10
+ "files": [
11
+ "build",
12
+ "README.md",
13
+ "LICENSE",
14
+ "CHANGELOG.md"
15
+ ],
16
+ "scripts": {
17
+ "build": "node scripts/build.mjs",
18
+ "build:publish": "node scripts/build-publish.mjs",
19
+ "dev": "npm run build && npm link",
20
+ "watch": "tsc -p tsconfig.json --watch",
21
+ "start": "node build/cli.js",
22
+ "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.{js,mjs}\"",
23
+ "prettier": "prettier '{src,scripts,.github}/**/*.{js,ts,json,yml,yaml,md}' --log-level error --write",
24
+ "test": "npm run build && mocha --exit",
25
+ "test:grep": "npm run build && mocha --exit --grep",
26
+ "test:cli": "node scripts/cli-smoke.mjs",
27
+ "test:capture": "node scripts/cli-capture-smoke.mjs",
28
+ "test:launch": "node scripts/cli-launch-smoke.mjs",
29
+ "test:keychain": "node scripts/cli-keychain-smoke.mjs",
30
+ "test:discovery": "node scripts/cli-discovery-smoke.mjs",
31
+ "test:copy-filter": "npm run build && node scripts/cli-copy-filter-smoke.mjs",
32
+ "fixture:build": "npm run build && node scripts/build-fixture-profile.js",
33
+ "verify:platform": "bash scripts/verify-cross-platform.sh",
34
+ "clean": "node scripts/clean.mjs",
35
+ "prepack": "npm run build:publish && node scripts/minify-build.mjs && node scripts/strip-test-artifacts.mjs"
36
+ },
37
+ "engines": {
38
+ "node": ">=24"
39
+ },
40
+ "mocha": {
41
+ "spec": "build/**/*.spec.js",
42
+ "timeout": 30000,
43
+ "reporter": "spec"
44
+ },
45
+ "dependencies": {
46
+ "chrome-remote-interface": "^0.34.0",
47
+ "commander": "^14.0.3"
48
+ },
49
+ "optionalDependencies": {
50
+ "@napi-rs/keyring": "^1.3.0"
51
+ },
52
+ "devDependencies": {
53
+ "@eslint/js": "^10.0.1",
54
+ "@types/chai": "^5.2.3",
55
+ "@types/chrome-remote-interface": "^0.34.0",
56
+ "@types/mocha": "^10.0.10",
57
+ "@types/node": "^25.9.1",
58
+ "@types/sinon": "^21.0.1",
59
+ "chai": "^6.2.2",
60
+ "esbuild": "^0.28.0",
61
+ "eslint": "^10.4.0",
62
+ "globals": "^17.6.0",
63
+ "mocha": "^11.7.6",
64
+ "prettier": "^3.8.3",
65
+ "sinon": "^22.0.0",
66
+ "typescript": "^6.0.3",
67
+ "typescript-eslint": "^8.60.0"
68
+ },
69
+ "overrides": {
70
+ "mocha": {
71
+ "diff": "^9.0.0",
72
+ "serialize-javascript": "^7.0.5",
73
+ "glob": "^13.0.0"
74
+ }
75
+ }
76
+ }