/**
 * @license
 * Copyright 2025 ReverseCraft
 * SPDX-License-Identifier: Apache-2.0
 */
import e from"node:fs";import r from"node:os";import t from"node:path";import{logger as o}from"../utils/logger.js";import{puppeteer as n}from"../third-party/index.js";let s;function i(){const e=new Set(["chrome://","chrome-extension://","chrome-untrusted://"]);return function(r){if("chrome://newtab/"===r.url())return!0;if(r.url().startsWith("chrome://inspect"))return!0;for(const t of e)if(r.url().startsWith(t))return!1;return!0}}export async function ensureBrowserConnected(r){const{channel:a}=r;if(s?.connected)return s;const c={targetFilter:i(),defaultViewport:null,handleDevToolsAsPage:!0};if(r.wsEndpoint)c.browserWSEndpoint=r.wsEndpoint,r.wsHeaders&&(c.headers=r.wsHeaders);else if(r.browserURL)c.browserURL=r.browserURL;else{if(!a&&!r.userDataDir)throw new Error("Either browserURL, wsEndpoint, channel or userDataDir must be provided");{const o=r.userDataDir;if(o){const r=t.join(o,"DevToolsActivePort");try{const t=await e.promises.readFile(r,"utf8"),[o,n]=t.split("\n").map(e=>e.trim()).filter(e=>!!e);if(!o||!n)throw new Error(`Invalid DevToolsActivePort '${t}' found`);const s=parseInt(o,10);if(isNaN(s)||s<=0||s>65535)throw new Error(`Invalid port '${o}' found`);const i=`ws://127.0.0.1:${s}${n}`;c.browserWSEndpoint=i}catch(e){throw new Error(`Could not connect to Chrome in ${o}. Check if Chrome is running and remote debugging is enabled.`,{cause:e})}}else{if(!a)throw new Error("Channel must be provided if userDataDir is missing");c.channel="stable"===a?"chrome":`chrome-${a}`}}}o("Connecting Puppeteer to ",JSON.stringify(c));try{s=await n.connect(c)}catch(e){throw new Error("Could not connect to Chrome. Check if Chrome is running and remote debugging is enabled by going to chrome://inspect/#remote-debugging.",{cause:e})}return o("Connected Puppeteer"),s}export async function launch(o){const{channel:s,executablePath:a,headless:c,isolated:l}=o,u=s&&"stable"!==s?`chrome-profile-${s}`:"chrome-profile";let d=o.userDataDir;l||d||(d=t.join(r.homedir(),".cache","rc-devtools-mcp",u),await e.promises.mkdir(d,{recursive:!0}));const h=[...o.args??[],"--hide-crash-restore-bubble"];let p;c&&(h.push("--screen-info={3840x2160}"),h.push("--disable-gpu"),h.push("--disable-software-rasterizer"),"linux"===r.platform()&&h.push("--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage","--disable-accelerated-2d-canvas","--no-zygote","--font-render-hinting=none")),o.devtools&&h.push("--auto-open-devtools-for-tabs"),a||(p=s&&"stable"!==s?`chrome-${s}`:"chrome");try{const e={channel:p,targetFilter:i(),executablePath:a,defaultViewport:null,userDataDir:d,pipe:!0,headless:!!c&&"new",args:h,acceptInsecureCerts:o.acceptInsecureCerts,handleDevToolsAsPage:!0},r=await n.launch(e);if(o.logFile&&(r.process()?.stderr?.pipe(o.logFile),r.process()?.stdout?.pipe(o.logFile)),o.viewport){const[e]=await r.pages();await(e?.resize({contentWidth:o.viewport.width,contentHeight:o.viewport.height}))}return r}catch(e){if(d&&e.message.includes("The browser is already running"))throw new Error(`The browser is already running for ${d}. Use --isolated to run multiple browser instances.`,{cause:e});throw e}}export async function ensureBrowserLaunched(e){return s?.connected||(s=await launch(e)),s}