@browserless.io/cli 0.5.2 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +93 -75
- package/README.md +73 -19
- package/build/agent/ws-client.js +1 -1
- package/build/api/client.js +1 -1
- package/build/api/profiles.js +1 -1
- package/build/api/upload.js +1 -1
- package/build/auth/disclaimer.js +7 -3
- package/build/auth/server-url.js +2 -2
- package/build/browsers/discover.js +5 -5
- package/build/capture/cdp-pipe.js +1 -0
- package/build/capture/cdp.js +3 -3
- package/build/capture/cleanup.js +1 -0
- package/build/capture/copy-profile.js +1 -1
- package/build/capture/index.js +1 -1
- package/build/capture/launch.js +7 -7
- package/build/capture/profile-lock.js +5 -5
- package/build/cli-utils/agent-format.js +5 -3
- package/build/cli-utils/capture-runner.js +7 -26
- package/build/cli-utils/client.js +2 -2
- package/build/cli.js +4 -4
- package/build/commands/agent/chat.js +12 -9
- package/build/commands/auth/login.js +1 -1
- package/build/commands/profile/delete.js +1 -1
- package/build/commands/profile/launch.js +3 -3
- package/build/commands/profile/list.js +1 -1
- package/build/commands/profile/refresh.js +2 -2
- package/build/commands/profile/rename.js +1 -1
- package/build/commands/profile/show.js +1 -1
- package/build/commands/profile/sources/add.js +1 -1
- package/build/commands/profile/upload.js +2 -2
- package/build/errors.js +1 -1
- package/build/regions.js +1 -1
- package/build/telemetry/api.js +1 -1
- package/build/telemetry/index.js +2 -2
- package/build/utils/interrupt.js +1 -0
- package/build/utils/spinner.js +3 -3
- package/build/utils/terminal.js +3 -0
- package/build/version.js +1 -1
- package/package.json +20 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var h=Object.defineProperty;var d=(o,i)=>h(o,"name",{value:i,configurable:!0});import r from"node:fs/promises";import a from"node:path";import m from"node:os";import{CaptureError as p}from"../errors.js";import{COOKIE_DB_FILES as _,createLockGate as D,isWindowsLockError as w}from"./profile-lock.js";const g=new Set(["Cache","Code Cache","GPUCache","GraphiteDawnCache","ShaderCache","Service Worker","Crashpad","optimization_guide_model_store","Default Cache"]),E=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"]),k=["SingletonLock","SingletonSocket","SingletonCookie"],R=d(async(o,i={interactive:!1},l,s)=>{const e=D(o,i),n=i.platform??process.platform;for(const c of _)await e.ensureReadable(a.join(o.profilePath,c));return e.retryOnLock(()=>P(o,n,l,s))},"buildTempUserDataDir"),y="browserless-cli-",b=/^browserless-cli-[A-Za-z0-9]{6,}$/,j=3600*1e3,F=d(async({dir:o=m.tmpdir(),maxAgeMs:i=j,now:l=Date.now(),uid:s=process.getuid?.()}={})=>{const e=await r.readdir(o).catch(()=>[]);await Promise.all(e.filter(n=>b.test(n)).map(async n=>{const c=a.join(o,n),u=await r.lstat(c).catch(()=>null);!u?.isDirectory()||l-u.mtimeMs<i||s!==void 0&&u.uid!==s||await r.rm(c,{recursive:!0,force:!0}).catch(()=>{})}))},"sweepStaleTempDirs"),P=d(async(o,i,l,s)=>{const e=await r.mkdtemp(a.join(m.tmpdir(),y));l?.(e);const n=a.join(o.userDataDir,"Local State"),c=a.join(e,"Local State");try{await r.copyFile(n,c)}catch(t){const f=t?.code;if(f!=="ENOENT")throw await r.rm(e,{recursive:!0,force:!0}).catch(()=>{}),w(t,i)?t:new p(`Failed to copy ${n} (${f??"unknown error"}): ${t.message}`,"profile-copy-failed")}try{await r.writeFile(a.join(e,"First Run"),"")}catch(t){throw await r.rm(e,{recursive:!0,force:!0}).catch(()=>{}),new p(`Failed to write First Run marker in ${e}: ${t.message}`,"profile-copy-failed")}const u=a.join(e,o.profileDirName);try{await r.cp(o.profilePath,u,{recursive:!0,force:!0,filter:d(t=>{if(s?.aborted)return!1;const f=a.relative(o.profilePath,t);if(!f)return!0;const S=f.split(a.sep)[0];return!(g.has(S)||E.has(S))},"filter")})}catch(t){throw await r.rm(e,{recursive:!0,force:!0}).catch(()=>{}),w(t,i)?t:new p(`Failed to copy profile from ${o.profilePath}: ${t?.message??t}`,"profile-copy-failed")}if(s?.aborted)throw await r.rm(e,{recursive:!0,force:!0}).catch(()=>{}),new p("Profile copy interrupted before it finished","profile-copy-failed");return await Promise.all(k.flatMap(t=>[r.unlink(a.join(e,t)).catch(()=>{}),r.unlink(a.join(u,t)).catch(()=>{})])),e},"copyOnce");export{R as buildTempUserDataDir,F as sweepStaleTempDirs};
|
package/build/capture/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var o=(e,s)=>f(e,"name",{value:s,configurable:!0});import{buildTempUserDataDir as w,sweepStaleTempDirs as y}from"./copy-profile.js";import{createCaptureCleanup as h}from"./cleanup.js";import{launchBrowserWithPipe as C,startAnsweringBrowser as D,waitForCdpPipe as b}from"./launch.js";import{captureViaCdp as x}from"./cdp.js";import{onInterrupt as B}from"../utils/interrupt.js";import{CaptureError as S}from"../errors.js";const k=o(()=>process.hrtime.bigint(),"startTime"),E=o(e=>Number((process.hrtime.bigint()-e)/1000000n),"elapsedMs"),M=o(async e=>{const s=k(),i=e.onProgress;await y();let n,p,d;const c=new AbortController,l=h(()=>n,()=>p,void 0,()=>c.abort()),u=B(l);try{i?.({phase:"copying"}),n=await w(e.profile,{interactive:e.interactive??!1,onWait:o(t=>i?.({phase:"waiting-for-unlock",...t}),"onWait")},t=>{n=t},c.signal);const g=n,a=await D(o(async()=>{if(c.signal.aborted)throw new S("Capture interrupted before the browser started","profile-copy-failed");i?.({phase:"launching"}),p=C({profile:e.profile,userDataDir:g,passwordStoreOverride:e.passwordStoreOverride});const t=await p;return i?.({phase:"waiting-for-debugger"}),t},"startBrowser"),{onRestart:o(()=>i?.({phase:"restarting-browser"}),"onRestart")});d=a.passwordStoreDefaulted,await b(a.cdp,void 0,a.diagnostics),i?.({phase:"capturing-origins",attempted:0,total:0,origin:""});const r=await x(e.profile,a.cdp,e.excludedDomains??[],t=>i?.({phase:"capturing-origins",...t}),e.onlyDomains??[]);i?.({phase:"done"});const m=JSON.stringify(r.state);return{state:r.state,diagnostics:{cookieCountBeforeExclusion:r.cookieCountTotal,cookieCountExcluded:r.cookieCountExcluded,originCountBeforeExclusion:r.state.origins.length+r.originCountSkippedByExclusion+r.originCountSkippedByOnlyDomain,originCountExcluded:r.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:r.originCountSkippedByOnlyDomain,excludedDomains:e.excludedDomains??[],onlyDomains:e.onlyDomains??[],durationMs:E(s),failedOrigins:r.failedOrigins},capHit:r.capHit,passwordStoreDefaulted:d,serialized:m}}finally{await l(),u()}},"captureFromProfile");export{M as captureFromProfile};
|
package/build/capture/launch.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
Browser process: pid=${
|
|
3
|
-
Launch command: ${
|
|
4
|
-
|
|
5
|
-
Browser stderr (last ${Math.min(
|
|
6
|
-
${
|
|
7
|
-
Browser stderr: <empty>`)}throw new c(`Browser CDP
|
|
1
|
+
var S=Object.defineProperty;var o=(e,r)=>S(e,"name",{value:r,configurable:!0});import y from"node:net";import k from"node:path";import{spawn as P,spawnSync as T}from"node:child_process";import{resolveLinuxPasswordStore as x}from"../browsers/password-store.js";import{CaptureError as c}from"../errors.js";import{CDP_PIPE_CLOSED as D,connectCdpPipe as $}from"./cdp-pipe.js";const w=o(e=>new Promise(r=>setTimeout(r,e)),"sleep"),W=o(()=>new Promise((e,r)=>{const t=y.createServer();t.unref(),t.on("error",r),t.listen(0,"127.0.0.1",()=>{const s=t.address();t.close(()=>{typeof s=="object"&&s?e(s.port):r(new Error("Could not pick a free port"))})})}),"pickFreePort"),F=o(async(e,r=Number(process.env.BROWSERLESS_CDP_WAIT_MS)||15e3,t)=>{const s=Date.now()+r;let a,n="<not fetched>";for(;Date.now()<s;){try{if((await fetch(`http://127.0.0.1:${e}/json/version`)).ok){const i=await fetch(`http://127.0.0.1:${e}/json/list`);if(i.ok){const d=await i.json();if(Array.isArray(d)&&d.some(p=>typeof p?.webSocketDebuggerUrl=="string"))return;n=JSON.stringify(d)}}}catch(l){a=l}await w(150)}throw new c(`Browser CDP endpoint did not expose an inspectable target within ${r}ms (last error: ${String(a)})${g(t,`Last /json/list: ${n}`)}`,"cdp-timeout")},"waitForDebuggerEndpoint"),g=o((e,r)=>{if(!e)return"";const t=e.getProcessState(),s=e.getStderr().trim();return`
|
|
2
|
+
Browser process: pid=${t.pid??"unspawned"} exitCode=${t.exitCode} signal=${t.signalCode}
|
|
3
|
+
Launch command: ${t.spawnfile} ${t.spawnargs.slice(1).join(" ")}
|
|
4
|
+
${r}`+(s?`
|
|
5
|
+
Browser stderr (last ${Math.min(s.length,2e3)} chars):
|
|
6
|
+
${s.slice(-2e3)}`:`
|
|
7
|
+
Browser stderr: <empty>`)},"describeLaunch"),f=1e3,H=o(async(e,r=Number(process.env.BROWSERLESS_CDP_WAIT_MS)||15e3,t)=>{const s=Date.now()+r;let a,n="<not fetched>";for(;Date.now()<s;){let l;try{const{targetInfos:i}=await Promise.race([e.send("Target.getTargets"),new Promise((d,p)=>{l=setTimeout(()=>p(new Error("Target.getTargets did not answer")),Math.min(f,Math.max(s-Date.now(),0)))})]);if(i.some(d=>d.type==="page"))return;n=JSON.stringify(i)}catch(i){if(a=i,i instanceof Error&&i.message.startsWith(D))break}finally{clearTimeout(l)}await w(150)}throw new c(`Browser CDP pipe did not expose an inspectable target within ${r}ms (last error: ${String(a)})${g(t,`Last Target.getTargets: ${n}`)}`,"cdp-timeout")},"waitForCdpPipe"),v=["--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(",")],G=o(e=>m(e,{port:e.port}),"launchBrowser"),J=o(async e=>{const r=await m(e,{pipe:!0}),{stdio:t}=r.child;return{...r,cdp:$(t[3],t[4])}},"launchBrowserWithPipe"),m=o(async(e,r)=>{const t=e.headless??!0,s=["port"in r?`--remote-debugging-port=${r.port}`:"--remote-debugging-pipe",`--user-data-dir=${e.userDataDir}`,`--profile-directory=${e.profile.profileDirName}`,"--no-first-run","--no-default-browser-check"];t&&s.push("--headless=new","--disable-gpu",...v);let a=!1;if(process.platform==="linux"){const{store:p,defaulted:C}=await x(e.profile.userDataDir,e.passwordStoreOverride);s.push(`--password-store=${p}`),a=C}s.push("about:blank");const n=P(e.profile.binaryPath,s,{detached:!1,stdio:"port"in r?["ignore","pipe","pipe"]:["ignore","pipe","pipe","pipe","pipe"]}),l=[];let i=0;const d=64*1024;return n.stdout?.on("data",()=>{}),n.stderr?.on("data",p=>{i>=d||(l.push(p),i+=p.length)}),{child:n,passwordStoreDefaulted:a,diagnostics:{getStderr:o(()=>Buffer.concat(l).toString("utf-8"),"getStderr"),getProcessState:o(()=>({pid:n.pid,exitCode:n.exitCode,signalCode:n.signalCode,spawnfile:n.spawnfile,spawnargs:n.spawnargs}),"getProcessState")}}},"spawnBrowser"),z=o(async e=>{const r=await fetch(`http://127.0.0.1:${e}/json/version`);if(!r.ok)throw new c(`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 c(`CDP /json/version returned an unexpected payload: ${JSON.stringify(t)}`,"cdp-metadata-invalid");return{Browser:t.Browser,webSocketDebuggerUrl:t.webSocketDebuggerUrl}},"fetchCdpMetadata"),u=o((e,r)=>new Promise(t=>{if(e.exitCode!==null||e.signalCode!==null){t();return}const s=setTimeout(t,r);e.once("exit",()=>{clearTimeout(s),t()})}),"waitExitOrTimeout"),E=o((e,r=process.env)=>k.win32.join(r.SystemRoot||"C:\\Windows","System32",e),"windowsSystemExe"),b=new WeakMap,_=o((e,r=2e3)=>{if(!e)return Promise.resolve();const t=b.get(e);if(t)return t;if(e.killed)return Promise.resolve();const s=B(e,r);return b.set(e,s),s},"killBrowser"),B=o(async(e,r)=>{if(process.platform==="win32"&&typeof e.pid=="number"){T(E("taskkill.exe"),["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0}),await u(e,r),h(e);return}e.kill("SIGTERM"),await u(e,r),e.exitCode===null&&e.signalCode===null&&(e.kill("SIGKILL"),await u(e,5e3)),h(e),e.unref()},"stopBrowser"),h=o(e=>{for(const r of e.stdio)r?.destroy()},"closeStdio"),R=1e4,A=o(async(e,r)=>{const t=Date.now()+r;for(;Date.now()<t;){let s;const a=await Promise.race([e.send("Target.getTargets").then(()=>!0,()=>!0),new Promise(n=>{s=setTimeout(()=>n(!1),Math.min(f,Math.max(t-Date.now(),0)))})]);if(clearTimeout(s),a)return!0}return!1},"answersWithin"),q=o(async(e,r={})=>{const t=await e();return await A(t.cdp,r.silenceMs??R)||t.child.exitCode!==null||t.child.signalCode!==null?t:(r.onRestart?.(),t.cdp.close(),await(r.kill??_)(t.child),e())},"startAnsweringBrowser");export{R as CDP_SILENCE_RESTART_MS,z as fetchCdpMetadata,_ as killBrowser,G as launchBrowser,J as launchBrowserWithPipe,W as pickFreePort,q as startAnsweringBrowser,H as waitForCdpPipe,F as waitForDebuggerEndpoint,E as windowsSystemExe};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`):`${
|
|
3
|
-
`):[`Can't capture ${
|
|
4
|
-
`)},"formatProfileLockedMessage"),
|
|
5
|
-
`),"formatAccessDeniedMessage"),
|
|
1
|
+
var C=Object.defineProperty;var i=(e,n)=>C(e,"name",{value:n,configurable:!0});import g from"node:fs/promises";import l from"node:path";import{checkProfileLock as R}from"../browsers/lock.js";import{CaptureError as b}from"../errors.js";import{terminalSafe as a}from"../utils/terminal.js";const M=12e4,x=1e3,_=1500,B=[l.join("Network","Cookies"),l.join("Network","Cookies-journal"),"Cookies","Cookies-journal"],f=i((e,n=process.platform)=>n==="win32"&&typeof e=="object"&&e!==null&&"code"in e&&(e.code==="EBUSY"||e.code==="EPERM"),"isWindowsLockError"),L=i(async e=>{try{return await((await g.stat(e)).isDirectory()?await g.opendir(e):await g.open(e,"r")).close(),null}catch(n){return n.code==="ENOENT"?null:n}},"probeReadable"),W=i((e,n,s,w=M)=>{const o=a(e.browserDisplayName),u=a(e.profileDisplayName),c=a(n.relativePath),m=a(n.code),{browserRunning:h}=n,y=a(l.win32.basename(e.binaryPath)),d=Math.round(w/6e4);return s==="wait"?h?[`${o} is still running, so Windows keeps ${c} locked.`,`Quit ${o} completely now (menu \u2192 Exit, or right-click its icon in the taskbar notification area \u2192 Exit). The capture continues automatically once it has closed \u2014 waiting up to ${d} minutes (Ctrl+C to cancel).`].join(`
|
|
2
|
+
`):`${c} is locked by another program. Waiting up to ${d} minutes for it to be released (Ctrl+C to cancel).`:h?[`Can't capture ${o} / ${u}: ${c} is locked (${m}) because ${o} is still running.`,`On Windows, ${o} keeps its cookie database locked while it runs, including in the background after its last window is closed.`,`Quit ${o} completely (menu \u2192 Exit, or right-click its icon in the taskbar notification area \u2192 Exit; end any leftover ${y} processes in Task Manager), then re-run this command.`,'To stop it running in the background, turn off "Continue running background apps" under Settings \u2192 System.'].join(`
|
|
3
|
+
`):[`Can't capture ${o} / ${u}: ${c} is locked (${m}) by another program.`,`${o} is not running, but antivirus, backup or cloud-sync software can hold browser files open for a while. Wait a few seconds and re-run this command; if it keeps failing, restart Windows and try again.`].join(`
|
|
4
|
+
`)},"formatProfileLockedMessage"),N=i((e,n)=>[`Can't capture ${a(e.browserDisplayName)} / ${a(e.profileDisplayName)}: Windows denied access to ${a(n)} (EPERM).`,`Either your Windows account can't read this file, or another program is holding it (antivirus, backup or cloud-sync software, or ${a(e.browserDisplayName)} itself if it is still running).`,`Quit ${a(e.browserDisplayName)} completely, wait a few seconds and re-run this command. If it keeps failing, check that your Windows account can read the files in this browser profile.`].join(`
|
|
5
|
+
`),"formatAccessDeniedMessage"),K=i((e,n)=>{const s=n.platform??process.platform,w=n.probe??L,o=n.isBrowserRunning??(async r=>(await R(r)).locked),u=n.sleep??(r=>new Promise(t=>setTimeout(t,r))),c=n.now??Date.now,m=n.timeoutMs??M,h=n.pollMs??x,y=n.retryDelayMs??_;let d,E=!1;const p=i(async(r,t)=>t==="EPERM"?new b(N(e,l.relative(e.userDataDir,r)),"profile-copy-failed"):new b(W(e,{relativePath:l.relative(e.userDataDir,r),browserRunning:await o(e.userDataDir),code:t},"fail"),"profile-file-locked"),"fileError"),k=i(async r=>{let t=await w(r);if(t?.code==="EPERM"&&(await u(y),t=await w(r),t?.code==="EPERM"))throw await p(r,t.code);return t},"probeWithPermissionRetry"),$=i(async r=>{if(s!=="win32")return;let t=await k(r);if(!f(t,s))return;const D=await o(e.userDataDir);if(!n.interactive){if(D)throw await p(r,t.code);if(await u(y),t=await w(r),f(t,s))throw await p(r,t.code);return}for(d??=c()+m,E||(n.onWait?.({relativePath:l.relative(e.userDataDir,r),browserRunning:D,code:t.code}),E=!0);c()<d;)if(await u(h),t=await k(r),!f(t,s))return;throw await p(r,t.code)},"ensureReadable");return{ensureReadable:$,retryOnLock:i(async r=>{try{return await r()}catch(t){if(!f(t,s))throw t;await $(t.path??e.profilePath)}try{return await r()}catch(t){throw f(t,s)?await p(t.path??e.profilePath,t.code):t}},"retryOnLock")}},"createLockGate");export{B as COOKIE_DB_FILES,x as LOCK_POLL_MS,_ as LOCK_RETRY_DELAY_MS,M as LOCK_WAIT_TIMEOUT_MS,K as createLockGate,N as formatAccessDeniedMessage,W as formatProfileLockedMessage,f as isWindowsLockError,L as probeReadable};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
var d=Object.defineProperty;var s=(t,e)=>d(t,"name",{value:e,configurable:!0});import{green as
|
|
1
|
+
var d=Object.defineProperty;var s=(t,e)=>d(t,"name",{value:e,configurable:!0});import{green as m,red as p}from"../utils/ansi.js";import{isAgentEndResult as h}from"../agent/types.js";import{terminalSafe as g}from"../utils/terminal.js";const y=/\b(log[- _]?in|sign[- _]?in|sign[- _]?up|authenticate|log on)/i,A=s(t=>y.test(t),"hasLoginIntent"),R=s(t=>{if(typeof t!="string")return;const e=t.trim();return e||void 0},"normalizeRationale"),S=s((t,e)=>{const n=[];return e.username&&n.push(`USERNAME=${e.username}`),e.password&&n.push(`PASSWORD=${e.password}`),n.length===0?t:`Credentials available for this task (do not echo back):
|
|
2
2
|
${n.join(`
|
|
3
3
|
`)}
|
|
4
4
|
|
|
5
|
-
`+t},"withCredentials"),
|
|
6
|
-
|
|
5
|
+
`+t},"withCredentials"),b=s((t,e)=>{const n=typeof t=="string"?t:t===null||typeof t!="object"?String(t):JSON.stringify(t),o=[...n];return o.length>e?`${o.slice(0,e-1).join("")}\u2026`:n},"previewValue"),_=/^(pass(word|code)?|secret|token|auth(orization)?|cookie|credentials?|api[-_]?key|otp|mfa|text|value)$/i,w=s((t,e=60)=>{if(!t||typeof t!="object")return"";const n=t;if(Array.isArray(n.commands)){const r=n.commands;return[...`${r.length} cmds: ${r.map(i=>i&&typeof i=="object"&&"method"in i&&typeof i.method=="string"?i.method:"?").join(" \u2192 ")}`].slice(0,e).join("")}const o=Object.entries(n).filter(([,r])=>r!==void 0);if(o.length===0)return"";const c=[];let l=0;for(const[r,a]of o){const i=_.test(r)?"[REDACTED]":b(a,30),u=`${r}=${i}`,f=[...u].length;if(l+f+2>e)break;c.push(u),l+=f+2}return c.join(" ")},"summarizeParams"),N=s((t,e)=>{const n=e&&typeof e=="object"?e:{};if(t==="browserless_skill")return{method:"skill",params:{id:n.id}};if(t==="browserless_agent"){const o=n.commands;return Array.isArray(o)&&o.length>0?{method:"commands",params:{commands:o}}:{method:typeof n.method=="string"?n.method:"agent",params:n.params}}return{method:typeof t=="string"?t:"?",params:e}},"unwrapToolCall"),x=s(t=>{if(!h(t.result))return"";const e=t.result,n=[`Result: ${e.success?m("success"):p("failed")}`];for(const o of["reason_code","final_url","evidence"])if(typeof e[o]=="string"){const c=` ${o}: `;n.push(c+g(e[o],{preserveLayout:o==="evidence"}).replaceAll(`
|
|
6
|
+
`,`
|
|
7
|
+
${" ".repeat(c.length)}`))}return n.join(`
|
|
8
|
+
`)},"formatEndResult");export{x as formatEndResult,A as hasLoginIntent,R as normalizeRationale,w as summarizeParams,N as unwrapToolCall,S as withCredentials};
|
|
@@ -1,27 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).forEach(e);return}if(
|
|
3
|
-
`)},"warnDropped"),
|
|
1
|
+
var v=Object.defineProperty;var l=(t,e)=>v(t,"name",{value:e,configurable:!0});import{resolveProfile as F}from"../browsers/discover.js";import{captureFromProfile as R}from"../capture/index.js";import{applyOnlyFilter as A,mergeExclusionPatterns as B,normalizeExclusion as x}from"../capture/exclusion.js";import{readConfig as I}from"../config/store.js";import{ensureTermsAccepted as P,isCi as L}from"../auth/disclaimer.js";import{formatProfileLockedMessage as z}from"../capture/profile-lock.js";import{CDP_SILENCE_RESTART_MS as M}from"../capture/launch.js";import{UsageError as N}from"../errors.js";import{version as G}from"../version.js";import{terminalSafe as E}from"../utils/terminal.js";import{collectRepeated as k,parseNonNegativeInt as j}from"./client.js";import{formatBytes as m,measureOriginSizes as H,SERVER_ARTIFACT_CAP_BYTES as D,trimStateToFit as U}from"./trim-state.js";const Y=l((t,e)=>t===!0&&!e,"captureIsInteractive"),K=l((t,e)=>{const o={copying:"copying profile data\u2026",launching:"launching headless browser\u2026","waiting-for-debugger":"waiting for browser to be ready\u2026","restarting-browser":`browser did not respond in ${M/1e3}s; restarting it\u2026`};let r="",d=0;return i=>{if(i.phase!=="done"){if(i.phase==="waiting-for-unlock"){z(t,i,"wait").split(`
|
|
2
|
+
`).forEach(e);return}if(i.phase==="capturing-origins"){if(i.attempted===0){r!=="capturing-origins"&&(r="capturing-origins",e("capturing per-origin storage\u2026"));return}if(!(i.attempted===i.total)&&i.attempted-d<5)return;d=i.attempted;const u=i.origin.length>50?i.origin.slice(0,47)+"\u2026":i.origin;e(` ${i.attempted}/${i.total} ${u}`);return}i.phase!==r&&(r=i.phase,e(o[i.phase]??i.phase))}}},"createProgressRenderer"),fe=l((t,e={})=>{const a=e.sourceOptional?t.option.bind(t):t.requiredOption.bind(t),o=e.sourceOptional?". Optional here \u2014 read from the profile's stored settings when omitted":"";return a("--browser <key>",`Source browser key (chrome / brave / edge / ...) or display name${o}`),a("--profile <name>",`Source profile display name or directory (e.g. "Personal", "Default")${o}`),t.option("--exclude-domain <domain>","Append a domain to the exclusion list for this run (repeatable)",k).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)",k).option("--only-domain <domain>","Capture only cookies / origins matching this domain \u2014 discard everything else (suffix-match; repeatable; applies after --exclude-domain)",k)},"addCaptureFlags"),X=l(t=>{if(t.length>0&&!t.some(e=>x(e)!==null))throw new N(`--only-domain: no valid domain pattern in ${JSON.stringify(t)}. Use a hostname like "example.com" or "*.example.com".`,"invalid-only-domain")},"validateOnlyDomain"),$=100,q=253,_=255,C=8*1024,J=/[$`\\!\u0000-\u001f\u007f]/,V=/^[A-Za-z0-9*._-]+$/,S=l((t,e)=>{process.stderr.write(` \u2192 Not storing ${t} for refresh (${e}); a later flagless \`profile refresh\` of this profile will not replay it
|
|
3
|
+
`)},"warnDropped"),Z=l(t=>{const e=`they serialize past the server's ${C}-byte limit`;process.stderr.write(t==="upload"?` \u2192 Not storing any capture settings (${e}); a later flagless \`profile refresh\` of this profile will have nothing to replay
|
|
4
4
|
`:` \u2192 Not updating the stored capture settings (${e}); whatever this profile already had is left as it was, so it no longer matches this run and a later flagless \`profile refresh\` will not reflect these filters. Shorten the domain lists to update them
|
|
5
|
-
`)},"warnOverCap"),
|
|
6
|
-
`)})},"warnUnusableExcludes"),
|
|
7
|
-
`),"w"),
|
|
8
|
-
`);const
|
|
9
|
-
`)},"writeLine"),f={profile:o,excludedDomains:d,onlyDomains:e.onlyDomain??[],passwordStoreOverride:e.passwordStore,interactive:j(process.stdin.isTTY,R()),onProgress:H(o,r)},i=await C(f);if(e.onlyDomain&&e.onlyDomain.length>0){const a=F(i.state,e.onlyDomain),h=i.state.cookies.length-a.state.cookies.length,n=i.diagnostics.originCountSkippedByOnlyDomain+a.originsDropped;(h>0||n>0)&&(i.state=a.state,i.serialized=JSON.stringify(a.state),process.stderr.write(` \u2192 --only-domain kept ${i.state.cookies.length} cookies / ${i.state.origins.length} origins; dropped ${h} cookies / ${n} origins not matching: ${e.onlyDomain.join(", ")}
|
|
10
|
-
`))}const c=i.diagnostics,S=Buffer.byteLength(i.serialized,"utf-8");if(process.stderr.write(`> Captured ${c.cookieCountBeforeExclusion} cookies, ${c.originCountBeforeExclusion} origins in ${c.durationMs}ms (artifact: ${u(S)})
|
|
11
|
-
`),c.cookieCountExcluded>0||c.originCountExcluded>0){const a=c.excludedDomains.length?c.excludedDomains.join(", "):"(none)";process.stderr.write(` \u2192 Excluded ${c.cookieCountExcluded} cookies / ${c.originCountExcluded} origins matching: ${a}
|
|
12
|
-
`)}if(i.capHit&&process.stderr.write(` ! Hit the per-capture origin cap \u2014 some origins may be missing
|
|
13
|
-
`),c.failedOrigins.length>0){process.stderr.write(` ! ${c.failedOrigins.length} origin(s) failed to capture \u2014 their localStorage / IndexedDB is missing from the upload:
|
|
14
|
-
`);for(const a of c.failedOrigins)process.stderr.write(` - ${a.origin}: ${a.error}
|
|
15
|
-
`)}if(i.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>
|
|
16
|
-
`),S>x){const a=G(i.state),g=10;process.stderr.write(` ! artifact size ${u(S)} exceeds the ${u(x)} server cap \u2014 heaviest origins:
|
|
17
|
-
`);for(const{origin:h,bytes:n}of a.slice(0,g))process.stderr.write(` ${u(n).padStart(10)} ${h}
|
|
18
|
-
`);if(a.length>g&&process.stderr.write(` \u2026 and ${a.length-g} more origins below ${u(a[g].bytes)}
|
|
19
|
-
`),e.autoFit){const h=e.keepDomain??[],n=M(i.state,x,h);if(n.dropped.length===0&&n.finalBytes<=x)process.stderr.write(` ! --auto-fit had nothing to drop \u2014 artifact unchanged
|
|
20
|
-
`);else{if(i.state=n.state,i.serialized=n.serialized,c.failedOrigins=[...c.failedOrigins,...n.dropped.map(w=>({origin:w,error:"dropped by --auto-fit to fit under the server cap",kind:"unknown"}))],n.dropped.length>0){process.stderr.write(` --auto-fit: dropped ${n.dropped.length} origin(s), now ${u(n.finalBytes)}:
|
|
21
|
-
`);for(const w of n.dropped)process.stderr.write(` - ${w}
|
|
22
|
-
`)}if(n.protectedFromDrop.length>0){process.stderr.write(` --auto-fit: ${n.protectedFromDrop.length} heavy origin(s) protected by --keep-domain:
|
|
23
|
-
`);for(const w of n.protectedFromDrop)process.stderr.write(` - ${w}
|
|
24
|
-
`)}n.finalBytes>x&&(n.protectedFromDrop.length>0?process.stderr.write(` ! Still ${u(n.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.
|
|
25
|
-
`):process.stderr.write(` ! Even after dropping every droppable origin the artifact is still over cap. The cookies alone may be too heavy.
|
|
26
|
-
`))}}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.
|
|
27
|
-
`)}return i},"runCapture");export{le as SETTINGS_REPLAY_SOURCE,ae as addCaptureFlags,de as buildCaptureSettings,j as captureIsInteractive,H as createProgressRenderer,pe as mergeStoredSettings,ce as printEffectiveSettings,fe as runCapture,U as validateOnlyDomain,q as warnUnusableExcludes};
|
|
5
|
+
`)},"warnOverCap"),T=l((t,e)=>{const a=e?.trim();if(a){if(J.test(a)){S(`--${t}`,"it contains characters a shell would interpret");return}if(a.length>_){S(`--${t}`,`it exceeds ${_} characters`);return}return a}},"safeScalar"),O=l((t,e,a=!1)=>{const o=[...new Set((e??[]).map(d=>x(d)).filter(d=>d!==null))],r=o.filter(d=>d.length<=q&&V.test(d));return r.length<o.length&&S(`${o.length-r.length} of ${o.length} --${t} patterns`,"the server only stores plain hostname patterns"),r.length?(r.length>$&&S(`${r.length-$} of ${r.length} --${t} patterns`,`the server stores at most ${$}`),r.slice(0,$)):a&&!(e??[]).length?[]:void 0},"safeDomains"),g=l((t,e)=>e===void 0?{}:{[t]:e},"withKey"),ue={browser:"browser",profile:"profile",excludeDomains:"excludeDomain",onlyDomains:"onlyDomain",keepDomains:"keepDomain",autoFit:"autoFit",passwordStore:"passwordStore"},me=l((t,e,a)=>{const o={...g("browser",T("browser",t.browser)),...g("profile",T("profile",t.profile)),...g("excludeDomains",O("exclude-domain",e.excludedDomains,t.defaultExcludes===!1)),...g("onlyDomains",O("only-domain",t.onlyDomain)),...g("keepDomains",O("keep-domain",t.keepDomain)),...t.autoFit?{autoFit:!0}:{},...g("passwordStore",T("password-store",t.passwordStore)),cliVersion:G};if(Buffer.byteLength(JSON.stringify(o),"utf8")>C){Z(a);return}return o},"buildCaptureSettings"),Q=l(t=>{(t??[]).filter(e=>x(e)===null).forEach(e=>{process.stderr.write(` ! --exclude-domain "${E(e)}" is not a usable domain pattern \u2014 nothing was excluded for it
|
|
6
|
+
`)})},"warnUnusableExcludes"),he=l((t,e)=>{if(!e)return t;const a=t.defaultExcludes===!1,o=(t.excludeDomain??[]).some(d=>x(d)!==null),r=!o&&e.excludeDomains!==void 0;return{...t,browser:t.browser??e.browser,profile:t.profile??e.profile,passwordStore:t.passwordStore??e.passwordStore,excludeDomain:o?t.excludeDomain:a?[]:e.excludeDomains,onlyDomain:t.onlyDomain??e.onlyDomains,keepDomain:t.keepDomain??e.keepDomains,autoFit:t.autoFit??e.autoFit,defaultExcludes:r?!1:t.defaultExcludes}},"mergeStoredSettings"),ge=l((t,e,a={})=>{if(!e)return;const o=l(u=>process.stderr.write(`${E(u)}
|
|
7
|
+
`),"w"),r=a.userOptedOut===!0;o("> Refreshing with these effective settings:"),t.browser&&o(` --browser ${t.browser}`),t.profile&&o(` --profile ${t.profile}`);const d=(t.excludeDomain??[]).filter(u=>x(u)!==null);d.length&&o(` --exclude-domain ${d.join(", ")}`),t.onlyDomain?.length&&(o(` --only-domain ${t.onlyDomain.join(", ")}`),o(" ! only these domains are captured \u2014 everything else in the saved"),o(" profile is replaced, not kept")),t.keepDomain?.length&&o(` --keep-domain ${t.keepDomain.join(", ")}`),t.autoFit&&o(" --auto-fit (only acts if the capture exceeds the 2 MB cap)"),t.passwordStore&&o(` --password-store ${t.passwordStore}`),r&&o(" --no-default-excludes");const i=r&&!d.length,f=e.excludeDomains?.length;i&&f&&(o(` ! --no-default-excludes drops the ${f} stored exclusion pattern(s) for this run,`),o(" and re-pass --exclude-domain if you want to keep them.")),i?(o(" ! Unless the settings exceed the 8 KB cap (reported after the capture), the"),o(" refreshed profile is stored with NO exclusion list, so later flagless refreshes"),o(" replay 'exclude nothing' and stop applying this machine's config.")):r?(o(" ! --no-default-excludes is in force: ONLY the --exclude-domain patterns above"),o(" are excluded, and this machine's own config is not applied.")):f===void 0&&(o(" (no stored exclusion list \u2014 this machine's own config applies)"),o(" This run stores the effective list on the profile, so later flagless refreshes"),o(" replay that snapshot instead of re-reading this config.")),o(" Pass --browser, --profile, --password-store or a domain flag to override."),r||(o(f===void 0?" --exclude-domain adds to this machine's config for this run; there is no stored list to replace.":" --exclude-domain replaces the stored list and re-applies this machine's config."),f&&o(" --no-default-excludes drops the stored list for good."))},"printEffectiveSettings"),ye=l(async t=>{const{flags:e,requiresDisclaimer:a}=t;if(!e.browser||!e.profile){const n=[e.browser?null:"--browser",e.profile?null:"--profile"].filter(Boolean);throw new N(`${n.join(" and ")} ${n.length>1?"are":"is"} required: this profile has no stored capture settings to read them from (it was not created by the CLI, or this server does not return them yet)`,"missing-capture-settings")}const o=await F(e.browser,e.profile);a&&await P({acceptViaFlag:!!e.acceptTerms,ttlDaysOverride:e.termsTtlDays!==void 0?j("--terms-ttl-days",e.termsTtlDays):void 0});const r=await I(),d=B(r.excluded_domains,e.excludeDomain,e.defaultExcludes===!1);X(e.onlyDomain??[]),Q(e.excludeDomain);const i=l(n=>process.stderr.write(`${E(n)}
|
|
8
|
+
`),"w");i(`> Capturing ${o.browserDisplayName} / ${o.profileDisplayName}`);const f=l(n=>{i(` ${n}`)},"writeLine"),u={profile:o,excludedDomains:d,onlyDomains:e.onlyDomain??[],passwordStoreOverride:e.passwordStore,interactive:Y(process.stdin.isTTY,L()),onProgress:K(o,f)},p=await R(u);if(e.onlyDomain&&e.onlyDomain.length>0){const n=A(p.state,e.onlyDomain),h=p.state.cookies.length-n.state.cookies.length,s=p.diagnostics.originCountSkippedByOnlyDomain+n.originsDropped;(h>0||s>0)&&(p.state=n.state,p.serialized=JSON.stringify(n.state),i(` \u2192 --only-domain kept ${p.state.cookies.length} cookies / ${p.state.origins.length} origins; dropped ${h} cookies / ${s} origins not matching: ${e.onlyDomain.join(", ")}`))}const c=p.diagnostics,b=Buffer.byteLength(p.serialized,"utf-8");if(i(`> Captured ${c.cookieCountBeforeExclusion} cookies, ${c.originCountBeforeExclusion} origins in ${c.durationMs}ms (artifact: ${m(b)})`),c.cookieCountExcluded>0||c.originCountExcluded>0){const n=c.excludedDomains.length?c.excludedDomains.join(", "):"(none)";i(` \u2192 Excluded ${c.cookieCountExcluded} cookies / ${c.originCountExcluded} origins matching: ${n}`)}if(p.capHit&&i(" ! Hit the per-capture origin cap \u2014 some origins may be missing"),c.failedOrigins.length>0){i(` ! ${c.failedOrigins.length} origin(s) failed to capture \u2014 their localStorage / IndexedDB is missing from the upload:`);for(const n of c.failedOrigins)i(` - ${n.origin}: ${n.error}`)}if(p.passwordStoreDefaulted&&i(' ! Linux password-store could not be detected \u2014 defaulted to "basic". If decryption failed, re-run with --password-store=<your store>'),b>D){const n=H(p.state),y=10;i(` ! artifact size ${m(b)} exceeds the ${m(D)} server cap \u2014 heaviest origins:`);for(const{origin:h,bytes:s}of n.slice(0,y))i(` ${m(s).padStart(10)} ${h}`);if(n.length>y&&i(` \u2026 and ${n.length-y} more origins below ${m(n[y].bytes)}`),e.autoFit){const h=e.keepDomain??[],s=U(p.state,D,h);if(s.dropped.length===0&&s.finalBytes<=D)i(" ! --auto-fit had nothing to drop \u2014 artifact unchanged");else{if(p.state=s.state,p.serialized=s.serialized,c.failedOrigins=[...c.failedOrigins,...s.dropped.map(w=>({origin:w,error:"dropped by --auto-fit to fit under the server cap",kind:"unknown"}))],s.dropped.length>0){i(` --auto-fit: dropped ${s.dropped.length} origin(s), now ${m(s.finalBytes)}:`);for(const w of s.dropped)i(` - ${w}`)}if(s.protectedFromDrop.length>0){i(` --auto-fit: ${s.protectedFromDrop.length} heavy origin(s) protected by --keep-domain:`);for(const w of s.protectedFromDrop)i(` - ${w}`)}s.finalBytes>D&&(s.protectedFromDrop.length>0?i(` ! Still ${m(s.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.`):i(" ! Even after dropping every droppable origin the artifact is still over cap. The cookies alone may be too heavy."))}}else i(" 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.")}return p},"runCapture");export{ue as SETTINGS_REPLAY_SOURCE,fe as addCaptureFlags,me as buildCaptureSettings,Y as captureIsInteractive,K as createProgressRenderer,he as mergeStoredSettings,ge as printEffectiveSettings,ye as runCapture,X as validateOnlyDomain,Q as warnUnusableExcludes};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var i=Object.defineProperty;var o=(e,r)=>i(e,"name",{value:r,configurable:!0});import{resolveServer as
|
|
2
|
-
`)},"printJson"),g=/^\d+$/,
|
|
1
|
+
var i=Object.defineProperty;var o=(e,r)=>i(e,"name",{value:r,configurable:!0});import{resolveServer as l,resolveToken as a}from"../auth/store.js";import{UsageError as c}from"../errors.js";import{KNOWN_REGIONS as p}from"../regions.js";const m=o(async e=>{const r=await l({server:e.server,region:e.region}),{token:t,source:n}=await a({flag:e.token,server:r});return{server:r,token:t,source:n}},"buildClient"),h=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"),E=o(e=>v(e.option("--token <token>","API token (overrides env / keychain / file). Visible to other local users in the process list \u2014 prefer BROWSERLESS_TOKEN or `auth login`")).option("--json","Emit the server response as JSON"),"addClientFlags"),S=o(e=>{process.stdout.write(JSON.stringify(e,null,2)+`
|
|
2
|
+
`)},"printJson"),g=/^\d+$/,k=o((e,r,t=0)=>{const n=o(()=>{throw new c(`${e} must be a${t>0?" positive":" non-negative"} integer (got "${r}")`,"invalid-integer-flag")},"fail");g.test(r)||n();const s=Number(r);return(!Number.isFinite(s)||!Number.isInteger(s)||s<t)&&n(),s},"parseNonNegativeInt");export{E as addClientFlags,v as addServerOverrideFlags,m as buildClient,h as collectRepeated,k as parseNonNegativeInt,S as printJson};
|
package/build/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`):e instanceof Error?process.stderr.write(`${e.stack??e.message}
|
|
4
|
-
`):process.stderr.write(`${
|
|
5
|
-
`),process.exitCode=
|
|
2
|
+
var m=Object.defineProperty;var i=(e,o)=>m(e,"name",{value:o,configurable:!0});import{Command as a}from"commander";import{version as p}from"./version.js";import{registerProfile as c}from"./commands/profile/index.js";import{registerAuth as f}from"./commands/auth/index.js";import{registerConfig as g}from"./commands/config/index.js";import{registerAgent as l}from"./commands/agent/index.js";import{exitCodeFor as u,UserFacingError as d}from"./errors.js";import*as s from"./telemetry/index.js";import{terminalSafe as t}from"./utils/terminal.js";const r=new a;r.name("browserless").description("Browserless CLI \u2014 manage profiles, sessions, and more.").version(p),c(r),f(r),g(r),l(r);const n=i(e=>e.name()==="terms"&&e.parent?.name()==="profile","isProfileTerms");r.hook("preAction",(e,o)=>{if(!n(o))try{s.begin(o)}catch{}}),r.hook("postAction",async(e,o)=>{if(!n(o))try{await s.complete({status:"ok",exitCode:0})}catch{}}),r.parseAsync(process.argv).catch(async e=>{e instanceof d?process.stderr.write(`${t(e.message,{preserveLayout:!0})}
|
|
3
|
+
`):e instanceof Error?process.stderr.write(`${t(e.stack??e.message,{preserveLayout:!0})}
|
|
4
|
+
`):process.stderr.write(`${t(e,{preserveLayout:!0})}
|
|
5
|
+
`),process.exitCode=u(e);try{await s.complete(s.errorResult(e,process.exitCode))}catch{}});
|
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
var
|
|
2
|
-
`))},"ensureTextStart"),
|
|
3
|
-
`),
|
|
4
|
-
`);const{method:
|
|
5
|
-
|
|
1
|
+
var S=Object.defineProperty;var r=(e,c)=>S(e,"name",{value:c,configurable:!0});import{stdout as x,stderr as E}from"node:process";import{buildClient as _,printJson as A}from"../../cli-utils/client.js";import{buildPrompts as P}from"../../cli-utils/prompts.js";import{ApiError as T}from"../../errors.js";import{AgentClient as $}from"../../agent/ws-client.js";import{loadHistory as L,saveHistory as v}from"../../agent/history.js";import{normalizeRationale as I,formatEndResult as R,hasLoginIntent as B,summarizeParams as z,unwrapToolCall as F,withCredentials as G}from"../../cli-utils/agent-format.js";import{colorsFor as h}from"../../utils/ansi.js";import{Spinner as H}from"../../utils/spinner.js";import{terminalSafe as k}from"../../utils/terminal.js";const M={buildClient:_,makeClient:r(e=>new $(e),"makeClient")},b=r(e=>new Promise(c=>{const n=r(()=>{e.off("end",d),e.off("awaiting_input",o),e.off("agent_error",l),e.off("close",s)},"cleanup"),d=r(p=>{n(),c({kind:"end",payload:p})},"onEnd"),o=r(p=>{n(),c({kind:"awaiting_input",payload:p})},"onAwait"),l=r(p=>{n(),c({kind:"error",payload:p})},"onErr"),s=r(()=>{n(),c({kind:"closed"})},"onClose");e.once("end",d),e.once("awaiting_input",o),e.once("agent_error",l),e.once("close",s)}),"waitForTurnEnd"),j=r((e,c)=>{const n=c?E:x,d=h(n),o=new H({out:n}),l=new Map;let s="idle";const p=r(()=>{s==="status"&&(o.clear(),n.write(`
|
|
2
|
+
`))},"ensureTextStart"),g=r(()=>{s==="text"&&n.write(`
|
|
3
|
+
`),s==="status"&&o.clear()},"ensureLineEndedBeforeBlock");e.on("data",t=>{typeof t.text!="string"||t.text.length===0||(p(),s="text",n.write(k(t.text.replace(/\r$/,""),{preserveLayout:!0})))});const m=r(({rationale:t,method:a,summary:w})=>{const i=[];return t&&i.push({text:`${t}: `}),a&&a!=="commands"&&(i.push({text:a,style:d.gray}),w&&i.push({text:" "})),w&&i.push({text:w,style:d.dim}),i},"formatLine");return e.on("tool_call",t=>{s==="text"&&n.write(`
|
|
4
|
+
`);const{method:a,params:w}=F(t.method,t.params),i=I(t.rationale),u={rationale:i?k(i):void 0,summary:k(z(w)),method:k(a)};l.set(t.id??"",u),s="status",o.set(m(u))}),e.on("tool_result",t=>{const a=l.get(t.id??"")??{method:"?",summary:""};l.delete(t.id??""),s==="text"&&n.write(`
|
|
5
|
+
`),o.done([{text:t.ok?"\u2713":"\u2717",style:t.ok?d.green:d.red},{text:" "},...m(a)]),s="idle"}),e.on("usage",()=>{}),{printEnd:r(t=>{if(g(),s="idle",c){A({type:"end",result:t.result??null});return}const a=R(t);n.write(a?`
|
|
6
|
+
${a}
|
|
6
7
|
`:`
|
|
7
|
-
`)},"printEnd"),clearStatus:
|
|
8
|
+
`)},"printEnd"),clearStatus:r(()=>{g(),s="idle"},"clearStatus"),dispose:r(()=>o.clear(),"dispose")}},"createRenderer"),D=r((e,c)=>{let n=0;const d=r(()=>{if(n+=1,n===1){c(),process.stderr.write(h(process.stderr).gray(`
|
|
8
9
|
(stop sent \u2014 press Ctrl-C again to exit)
|
|
9
|
-
`));try{e.stop()}catch{}}else process.exit(130)},"handler"),
|
|
10
|
-
`));const
|
|
11
|
-
|
|
10
|
+
`));try{e.stop()}catch{}}else process.exit(130)},"handler"),o=["SIGINT","SIGBREAK"];return o.forEach(l=>process.on(l,d)),()=>o.forEach(l=>process.off(l,d))},"installSigint"),O=r(async(e,c,n=M)=>{const d=!!e.json,o=await n.buildClient(e),l=d?E:x;l.write(h(l).dim(`agent \u2192 ${o.server} (token from ${o.source})
|
|
11
|
+
`));const s=e.history!==!1&&!c,p=s?await L().catch(()=>[]):[],m=c??P(p,s?i=>v(i):async()=>{},l),t=n.makeClient({server:o.server,token:o.token});await t.connect();const a=j(t,d),w=D(t,a.clearStatus);try{let i=!0;for(;;){let u;if(i&&e.prompt)u=e.prompt;else{try{u=await m.line("> ")}catch{break}if(u===""){if(i)continue;break}}if(i&&B(u))try{const y=await m.linePrivate("Username (blank to skip): "),C=y?await m.password("Password (blank to skip): "):"";u=G(u,{username:y,password:C})}catch{break}i?t.start(u):t.send(u),i=!1;let f=await b(t);for(;f.kind==="awaiting_input";){const y=await m.linePrivate("Enter code: ");if(!y){f={kind:"closed"};break}t.send(y),f=await b(t)}if(f.kind==="closed")break;if(f.kind==="error"){if(a.clearStatus(),process.stderr.write(`error: ${k(f.payload.message||f.payload.code||"unknown",{preserveLayout:!0}).replaceAll(`
|
|
12
|
+
`,`
|
|
13
|
+
`)}
|
|
14
|
+
`),f.payload.retryable!==!0)throw new T("Agent session ended with an error.",0,void 0,"agent-session-error");continue}a.printEnd(f.payload)}}finally{w(),a.dispose(),t.close()}},"runAgentChat");export{O as runAgentChat};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var
|
|
1
|
+
var c=Object.defineProperty;var n=(o,e)=>c(o,"name",{value:e,configurable:!0});import{resolveServer as d,persistToken as f}from"../../auth/store.js";import{validateToken as l}from"../../api/auth.js";import{addServerOverrideFlags as m}from"../../cli-utils/client.js";import{PreconditionError as i}from"../../errors.js";import{recordToken as h}from"../../telemetry/token-cache.js";const k=n(async()=>{const o=[];for await(const e of process.stdin)o.push(Buffer.from(e));return Buffer.concat(o).toString("utf-8").trim()},"readFromStdin"),p=n(async(o,e)=>{const r=await d({server:e.server,region:e.region});let t=o?.trim();if(!t){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");t=await k()}if(!t)throw new i("No token provided.","no-token");if(!await l({server:r,token:t}))throw new i(`Token rejected by ${r} \u2014 double-check it and retry.`,"invalid-token");h({token:t,server:r});const{mode:a,warning:s}=await f({server:r,token:t});console.log(a==="keychain"?`\u2713 Token saved to OS keychain for ${r}`:`\u2713 Token saved to ~/.browserless/config.json for ${r}`),s&&console.log(`! ${s}`)},"action"),$=n(o=>{const e=o.command("login [token]").description("Validate and persist an API token. Without an argument it is read from stdin \u2014 prefer that: an argument shows up in the process list for other local users and in shell history.");m(e).action(p)},"registerAuthLogin");export{$ as registerAuthLogin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var r=Object.defineProperty;var t=(o,e)=>r(o,"name",{value:e,configurable:!0});import{addClientFlags as l,buildClient as a,printJson as c}from"../../cli-utils/client.js";import{deleteProfile as s}from"../../api/profiles.js";import{terminalSafe as m}from"../../utils/terminal.js";const d=t(async(o,e)=>{const i=await a(e),n=await s(i,o);if(e.json){c(n);return}console.log(`\u2713 Deleted profile "${m(n.name)}"`)},"action"),D=t(o=>{const e=o.command("delete <name>").description("Delete a cloud profile");l(e).action(d)},"registerDelete");export{D as registerDelete};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var u=Object.defineProperty;var s=(e,r)=>u(e,"name",{value:r,configurable:!0});import{printJson as
|
|
1
|
+
var u=Object.defineProperty;var s=(e,r)=>u(e,"name",{value:r,configurable:!0});import{printJson as f}from"../../cli-utils/client.js";import{resolveProfile as h}from"../../browsers/discover.js";import{checkProfileLock as b}from"../../browsers/lock.js";import{fetchCdpMetadata as m,killBrowser as g,launchBrowser as y,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","missing-required-flag");const r=await h(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 y({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
2
|
> Shutting down browser
|
|
3
|
-
`),await
|
|
3
|
+
`),await g(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?f({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
4
|
`),process.stderr.write(` ${o.Browser}
|
|
5
5
|
`),process.stderr.write(` HTTP endpoint: http://127.0.0.1:${t}
|
|
6
6
|
`),process.stderr.write(` WebSocket: ${o.webSocketDebuggerUrl}
|
|
@@ -9,4 +9,4 @@ var u=Object.defineProperty;var s=(e,r)=>u(e,"name",{value:r,configurable:!0});i
|
|
|
9
9
|
Note: this is your real ${r.browserDisplayName} profile \u2014 anything you do here persists.
|
|
10
10
|
`),process.stderr.write(`Press Ctrl-C to stop, or fully quit the browser (cmd-Q on macOS).
|
|
11
11
|
`)),await new Promise(p=>{a.once("exit",()=>p())}),process.stderr.write(`> Browser exited
|
|
12
|
-
`)}finally{await d()}},"action"),
|
|
12
|
+
`)}finally{await d()}},"action"),q=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,q as registerLaunch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var
|
|
1
|
+
var g=Object.defineProperty;var e=(n,o)=>g(n,"name",{value:o,configurable:!0});import{addClientFlags as p,buildClient as h,parseNonNegativeInt as c,printJson as S}from"../../cli-utils/client.js";import{listProfiles as w}from"../../api/profiles.js";import{terminalSafe as A}from"../../utils/terminal.js";const C=e(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,s=await w(o,{limit:d,offset:m});if(n.json){S(s);return}if(s.length===0){console.log("No profiles found.");return}const f=["NAME","COOKIES","ORIGINS","UPDATED","LAST USED"],a=s.map(t=>[t.name,String(t.cookieCount),String(t.originCount),t.updatedAt,t.lastUsedAt??"-"].map(i=>A(i))),u=f.map((t,i)=>Math.max(t.length,...a.map(r=>r[i].length))),l=e(t=>console.log(t.map((i,r)=>i.padEnd(u[r])).join(" ")),"print");l(f);for(const t of a)l(t)},"action"),D=e(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(C)},"registerList");export{D as registerList};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),t.submit();const r=await
|
|
1
|
+
var d=Object.defineProperty;var s=(e,t)=>d(e,"name",{value:t,configurable:!0});import{addClientFlags as m,buildClient as f,printJson as p}from"../../cli-utils/client.js";import{addCaptureFlags as u,buildCaptureSettings as g,mergeStoredSettings as h,printEffectiveSettings as S,runCapture as C}from"../../cli-utils/capture-runner.js";import{getProfile as w}from"../../api/profiles.js";import{refreshProfile as $}from"../../api/refresh.js";import{withProfileSetup as x}from"../../telemetry/profile-setup.js";import{terminalSafe as i}from"../../utils/terminal.js";const I=s(e=>x(e.attemptId,"refresh",async t=>{const o=await f(e),l=await w(o,e.name),c=e.defaultExcludes===!1,n=h(e,l.captureSettings);S(n,l.captureSettings,{userOptedOut:c});const a=await C({flags:n,requiresDisclaimer:!0});t.ready(),process.stderr.write(`> Refreshing profile "${e.name}" on ${o.server}
|
|
2
|
+
`),t.submit();const r=await $(o,{attemptId:t.attemptId,name:e.name,state:a.state,serialized:a.serialized,captureSettings:g(n,a.diagnostics,"refresh")});if(e.json){p(r);return}console.log(`\u2713 Profile "${i(r.name)}" refreshed`),console.log(` id: ${i(r.id)}`),console.log(` cookies: ${i(r.cookieCount)}`),console.log(` origins: ${i(r.originCount)}`),console.log(` updated: ${i(r.updatedAt)}`)}),"action"),y=s(e=>{const t=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").option("--attempt-id <UUID>","Optional setup correlation ID");u(m(t),{sourceOptional:!0}).action(I)},"registerRefresh");export{y as registerRefresh};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var o=(n,e)=>m(n,"name",{value:e,configurable:!0});import{addClientFlags as c,buildClient as s,printJson as l}from"../../cli-utils/client.js";import{renameProfile as d}from"../../api/profiles.js";import{terminalSafe as r}from"../../utils/terminal.js";const f=o(async(n,e,t)=>{const a=await s(t),i=await d(a,n,e);if(t.json){l(i);return}console.log(`\u2713 Renamed "${r(n)}" \u2192 "${r(i.name)}"`)},"action"),R=o(n=>{const e=n.command("rename <old> <new>").description("Rename a cloud profile");c(e).action(f)},"registerRename");export{R as registerRename};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var s=Object.defineProperty;var i=(n,t)=>s(n,"name",{value:t,configurable:!0});import{addClientFlags as a,buildClient as c,printJson as r}from"../../cli-utils/client.js";import{getProfile as d}from"../../api/profiles.js";import{terminalSafe as e}from"../../utils/terminal.js";const m=i(async(n,t)=>{const l=await c(t),o=await d(l,n);if(t.json){r(o);return}console.log(`name: ${e(o.name)}`),console.log(`id: ${e(o.id)}`),console.log(`cookies: ${e(o.cookieCount)}`),console.log(`origins: ${e(o.originCount)}`),console.log(`created: ${e(o.createdAt)}`),console.log(`updated: ${e(o.updatedAt)}`),console.log(`last used: ${e(o.lastUsedAt??"-")}`)},"action"),$=i(n=>{const t=n.command("show <name>").description("Show a single cloud profile's metadata");a(t).action(m)},"registerShow");export{$ as registerShow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var t=(r,e)=>m(r,"name",{value:e,configurable:!0});import s from"node:fs/promises";import d from"node:path";import{addCustomBrowser as u}from"../../../browsers/custom.js";import{findBuiltInByKeyOrName as c}from"../../../browsers/registry.js";import{UsageError as a}from"../../../errors.js";const h=t(async r=>{if(!r.name||!r.path||!r.userDataDir)throw new a("profile sources add requires --name, --path, and --user-data-dir");if(c(r.name))throw new a(`"${r.name}" collides with a built-in browser. Pick a different name (e.g. "${r.name}-custom").`);const e=d.resolve(r.path),i=d.resolve(r.userDataDir),[o,n]=await Promise.all([s.stat(e).catch(()=>null),s.stat(i).catch(()=>null)]);if(!o)throw new a(`--path does not exist: ${r.path}`);if(o.isDirectory())throw new a(`--path must point at a binary, not a directory: ${r.path}`);if(!n)throw new a(`--user-data-dir does not exist: ${r.userDataDir}`);if(!n.isDirectory())throw new a(`--user-data-dir must point at a directory: ${r.userDataDir}`);await u({name:r.name,binaryPath:e,userDataDir:i}),console.log(`\u2713 Registered custom browser "${r.name}"`)},"action"),p=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(h)},"registerSourcesAdd");export{p as registerSourcesAdd};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
1
|
+
var s=Object.defineProperty;var l=(e,t)=>s(e,"name",{value:t,configurable:!0});import{addClientFlags as d,buildClient as c,printJson as p}from"../../cli-utils/client.js";import{addCaptureFlags as m,buildCaptureSettings as u,runCapture as f}from"../../cli-utils/capture-runner.js";import{uploadProfile as g}from"../../api/upload.js";import{withProfileSetup as C}from"../../telemetry/profile-setup.js";import{terminalSafe as a}from"../../utils/terminal.js";const w={runCapture:f},$=l((e,t)=>C(e.attemptId,"create",async r=>{const i=await c(e),n=await t.runCapture({flags:e,requiresDisclaimer:!0});r.ready(),process.stderr.write(`> Uploading to ${i.server}
|
|
2
|
+
`),r.submit();const o=await g(i,{attemptId:r.attemptId,name:e.name,state:n.state,serialized:n.serialized,captureSettings:u(e,n.diagnostics,"upload")});if(e.json){p(o);return}console.log(`\u2713 Profile "${a(o.name)}" uploaded`),console.log(` id: ${a(o.id)}`),console.log(` cookies: ${a(o.cookieCount)}`),console.log(` origins: ${a(o.originCount)}`),console.log(` created: ${a(o.createdAt)}`)}),"action"),h=l((e,t=w)=>{const r=e.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").option("--attempt-id <UUID>","Optional setup correlation ID");m(d(r)).action(i=>$(i,t))},"registerUpload");export{h as registerUpload};
|
package/build/errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Object.defineProperty;var s=(t,e)=>c(t,"name",{value:e,configurable:!0});class n extends Error{static{s(this,"UserFacingError")}exitCode=1;constructor(e){super(e),this.name="UserFacingError"}}class a extends n{static{s(this,"UsageError")}code;constructor(e,o){super(e),this.code=o,this.name="UsageError",this.exitCode=2}}class d extends n{static{s(this,"PreconditionError")}code;constructor(e,o){super(e),this.code=o,this.name="PreconditionError",this.exitCode=3}}class u extends n{static{s(this,"CaptureError")}code;constructor(e,o){super(e),this.code=o,this.name="CaptureError",this.exitCode=4}}class p extends n{static{s(this,"ApiError")}status;body;code;constructor(e,o,r,i){super(e),this.status=o,this.body=r,this.code=i,this.name="ApiError",this.exitCode=5}}const E=s(t=>t instanceof n?t.exitCode:1,"exitCodeFor"),f=s(t=>{if(t&&typeof t=="object"){const e=t.code;if(typeof e=="string"&&e.length>0)return e}},"errorCodeOf"),l={400:"bad-request",401:"unauthorized",403:"forbidden",404:"not-found",409:"conflict",413:"payload-too-large",429:"rate-limited"},h=new Set(["request-timeout","network-unreachable","response-read-failed","websocket-failed","websocket-not-open"]),C=s(t=>{let e="internal",o="unknown",r;return t instanceof a?(e="usage",o=t.code??"unknown"):t instanceof d?(e="precondition",o=t.code??"unknown"):t instanceof u?(e="capture",o=t.code??"unknown"):t instanceof p?(r=t.status>0?t.status:void 0,e=(t.code?h.has(t.code):t.status===0)?"network":"api",o=t.code??l[t.status]??(t.status>=400&&t.status<=499?"client-error":t.status>=500&&t.status<=599?"server-error":t.status===0?"unknown":"http-error")):t instanceof n||(o=f(t)??"unknown"),{errorName:t instanceof Error?t.name:void 0,errorCode:/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(o)?o:"unknown",errorCategory:e,httpStatus:r}},"errorTelemetryOf");export{p as ApiError,u as CaptureError,d as PreconditionError,a as UsageError,n as UserFacingError,f as errorCodeOf,C as errorTelemetryOf,E as exitCodeFor};
|
package/build/regions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var n=Object.defineProperty;var r=(o,e)=>n(o,"name",{value:e,configurable:!0});import{UsageError as t}from"./errors.js";const s={sfo:"https://production-sfo.browserless.io",lon:"https://production-lon.browserless.io",ams:"https://production-ams.browserless.io"},i=Object.keys(s),p=r(o=>Object.prototype.hasOwnProperty.call(s,o),"isKnownRegion"),w=r(o=>{if(!p(o))throw new t(`Unknown region "${o}". Known regions: ${i.join(", ")}. For self-hosted or staging, pass --server <url> instead.`,"unknown-region");return s[o]},"regionToServerUrl");export{i as KNOWN_REGIONS,s as REGION_URLS,p as isKnownRegion,w as regionToServerUrl};
|
package/build/telemetry/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var
|
|
1
|
+
var c=Object.defineProperty;var s=(t,e)=>c(t,"name",{value:e,configurable:!0});import{version as l}from"../version.js";import{isLoopbackHostname as p}from"../utils/loopback.js";const h="https://api.browserless.io",u=s(()=>{const t=process.env.BROWSERLESS_API_URL?.trim()||h;return t.endsWith("/")?t.slice(0,-1):t},"apiBaseUrl"),m=s(t=>{try{const{protocol:e,hostname:r}=new URL(t);return e!=="http:"&&e!=="https:"?!1:p(r)||e==="https:"&&(r==="browserless.io"||r.endsWith(".browserless.io"))}catch{return!1}},"isTrustedApiBase"),f=2e3,b=`@browserless.io/cli/${l}`,w=s(async(t,e)=>{const r=e.timeoutMs??f,o=e.baseUrl??u();if(!m(o))return!1;const n=new AbortController,a=setTimeout(()=>n.abort(),r);try{const i=await fetch(`${o}/v2/cli/events`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":b,Authorization:`Bearer ${e.token}`},body:JSON.stringify({events:t}),signal:n.signal,redirect:"error"});return await i.text().catch(()=>{}),i.ok}catch{return!1}finally{clearTimeout(a)}},"postCliEvents");export{u as apiBaseUrl,m as isTrustedApiBase,w as postCliEvents};
|
package/build/telemetry/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var E=Object.defineProperty;var t=(e,r)=>E(e,"name",{value:r,configurable:!0});import{performance as p}from"node:perf_hooks";import{readConfig as
|
|
2
|
-
`)},"debug");let c,i=[];const
|
|
1
|
+
var E=Object.defineProperty;var t=(e,r)=>E(e,"name",{value:r,configurable:!0});import{performance as p}from"node:perf_hooks";import{readConfig as _}from"../config/store.js";import{errorTelemetryOf as l}from"../errors.js";import{REGION_URLS as R,KNOWN_REGIONS as g,isKnownRegion as v}from"../regions.js";import{version as h}from"../version.js";import{commandPath as S,usedFlagNames as T}from"./command-meta.js";import{getRecordedToken as y}from"./token-cache.js";import{getOrCreateDeviceId as w}from"./device-id.js";import{apiBaseUrl as L,isTrustedApiBase as O,postCliEvents as k}from"./api.js";const C="CLI Command Run",d=t(e=>e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false","isTruthyEnv"),N=t(()=>{const e=Number(process.env.BROWSERLESS_TELEMETRY_TIMEOUT_MS);return e>0?e:2e3},"flushTimeoutMs"),s=t(e=>{d(process.env.BROWSERLESS_TELEMETRY_DEBUG)&&process.stderr.write(`[telemetry] ${e}
|
|
2
|
+
`)},"debug");let c,i=[];const j=t(e=>{c&&i.length<6&&i.push(e)},"recordProfileSetupEvent"),F=t((e,r)=>({status:"error",exitCode:r,...l(e)}),"errorResult"),x=t(async()=>{if(d(process.env.BROWSERLESS_TELEMETRY_DISABLED)||d(process.env.DO_NOT_TRACK))return!1;try{const e=await _();return e.telemetry===void 0||e.telemetry===!0}catch{return!1}},"isEnabled"),V=t(e=>{i=[],c={command:S(e),flags:T(e),startedAt:p.now()}},"begin"),M=t(e=>{let r;try{r=new URL(e).origin}catch{return"custom"}return g.find(o=>{try{return new URL(R[o]).origin===r}catch{return!1}})??"custom"},"bucketServerUrl"),B=t(()=>Number(process.versions.node.split(".")[0])||0,"nodeMajor"),I=t((e,r,a,o)=>{const n={command:e.command,flags:e.flags,status:r.status,exit_code:r.exitCode,error_name:r.status==="error"?r.errorName:void 0,error_code:r.status==="error"?r.errorCode:void 0,error_category:r.status==="error"?r.errorCategory:void 0,http_status:r.status==="error"?r.httpStatus:void 0,duration_ms:Math.round(p.now()-e.startedAt),cli_version:h,os:process.platform,arch:process.arch,node_major:B(),is_ci:d(process.env.CI),server_region:a,cli_device_id:o};return{event_type:C,time:Date.now(),event_properties:n}},"buildEvent"),q=t(async e=>{const r=c;c=void 0;const a=i;if(i=[],!!r)try{if(!await x()){s("skipped: telemetry disabled");return}const o=y();if(!o){s("skipped: no token resolved this run");return}const n=M(o.server);if(!v(n)){s("skipped: non-cloud server");return}if(!O(L())){s("skipped: BROWSERLESS_API_URL is not a Browserless host");return}const m=await w(),f=I(r,e,n,m),u=await k([f,...a],{token:o.token,timeoutMs:N()});s(u?`sent (${n})`:`send failed (${n})`)}catch{s("skipped: error while flushing")}},"complete"),z=t(()=>{c=void 0,i=[]},"_resetForTests");export{z as _resetForTests,V as begin,M as bucketServerUrl,q as complete,F as errorResult,N as flushTimeoutMs,x as isEnabled,j as recordProfileSetupEvent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var o=(r,e)=>a(r,"name",{value:e,configurable:!0});const d={SIGINT:130,SIGTERM:143,SIGBREAK:130},i=o((r,{target:e=process,exit:I=o(n=>process.exit(n),"exit")}={})=>{let n;const E=Object.entries(d).map(([c,t])=>{const s=o(()=>{n??=r().catch(()=>{}),n.finally(()=>I(t))},"handler");return e.once(c,s),[c,s]});return()=>E.forEach(([c,t])=>e.off(c,t))},"onInterrupt");export{i as onInterrupt};
|
package/build/utils/spinner.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),this.active=!1;return}this.
|
|
3
|
-
`),this.active=!1}clear(){if(this.stopTimer(),!this.isTTY){this.active=!1;return}this.active&&this.out.write("\r\x1B[K"),this.active=!1}render(){const t=
|
|
1
|
+
var c=Object.defineProperty;var a=(h,t)=>c(h,"name",{value:t,configurable:!0});import u from"string-width";const l=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],f=80,m=100,p=new Intl.Segmenter(void 0,{granularity:"grapheme"}),T=a((h,t)=>{let i=0,s="",o="";for(const{segment:e}of p.segment(h)){const n=e.replace(/[\ud800-\udfff]/gu,"\uFFFD"),r=u(n);if(i+r>t)return`${o}\u2026`;s+=n,i+=r,i<=t-1&&(o=s)}return s},"clipToWidth");class g{static{a(this,"Spinner")}out;isTTY;intervalMs;timer=null;idx=0;parts=[];active=!1;constructor(t={}){this.out=t.out??process.stdout,this.isTTY=t.isTTY??!!this.out.isTTY,this.intervalMs=t.intervalMs??f}isActive(){return this.active}set(t){this.parts=typeof t=="string"?[{text:t}]:t,this.isTTY&&(this.active=!0,this.render(),this.intervalMs>0&&!this.timer&&(this.timer=setInterval(()=>this.render(),this.intervalMs),this.timer.unref?.()))}done(t){if(this.stopTimer(),this.parts=typeof t=="string"?[{text:t}]:t,!this.isTTY){this.out.write(`${this.parts.map(({text:i})=>i).join("")}
|
|
2
|
+
`),this.active=!1;return}this.writeLine(this.parts),this.out.write(`
|
|
3
|
+
`),this.active=!1}clear(){if(this.stopTimer(),!this.isTTY){this.active=!1;return}this.active&&this.out.write("\r\x1B[K"),this.active=!1}render(){const t=l[this.idx%l.length];this.idx+=1,this.writeLine([{text:`${t} `},...this.parts])}writeLine(t){const i=T(t.map(({text:e})=>e).join(""),this.maxWidth());let s=0;const o=t.map(({text:e,style:n})=>{const r=i.slice(s,s+e.length);return s+=e.length,r&&n?n(r):r}).join("");this.out.write(`\r\x1B[K${o}`)}maxWidth(){const t=this.out.columns;return typeof t=="number"&&t>10?t-1:m}stopTimer(){this.timer&&(clearInterval(this.timer),this.timer=null)}}export{g as Spinner};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var n=Object.defineProperty;var r=(u,t)=>n(u,"name",{value:t,configurable:!0});const o=r((u,t={})=>(t.preserveLayout?String(u).replace(/\r\n/g,`
|
|
2
|
+
`):String(u)).replace(/\u{1f3f4}[\u{e0020}-\u{e007e}]+\u{e007f}|[\x00-\x1f\x7f-\x9f\u00ad\u061c\u180e\u200b\u200e-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff\u{e0000}-\u{e007f}]/gu,e=>{if(e.startsWith("\u{1F3F4}")||t.preserveLayout&&(e===`
|
|
3
|
+
`||e===" "))return e;const f=e.codePointAt(0);return f>65535?`\\u{${f.toString(16)}}`:`\\u${f.toString(16).padStart(4,"0")}`}),"terminalSafe");export{o as terminalSafe};
|
package/build/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.6.1";export{o as version};
|