"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(e,t)=>{for(var s in t)__defProp(e,s,{get:t[s],enumerable:!0})},__copyProps=(e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of __getOwnPropNames(t))__hasOwnProp.call(e,i)||i===s||__defProp(e,i,{get:()=>t[i],enumerable:!(o=__getOwnPropDesc(t,i))||o.enumerable});return e},__toESM=(e,t,s)=>(s=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?s:__defProp(s,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(__defProp({},"__esModule",{value:!0}),e),session_exports={};__export(session_exports,{Session:()=>Session}),module.exports=__toCommonJS(session_exports);var import_child_process=require("child_process"),import_fs=__toESM(require("fs")),import_net=__toESM(require("net")),import_os=__toESM(require("os")),import_path=__toESM(require("path")),import_package=require("../../package"),import_socketConnection=require("../utils/socketConnection"),import_registry=require("./registry");class Session{constructor(e){this.config=e.config,this.name=this.config.name,this._sessionFile=e}isCompatible(e){return(0,import_socketConnection.compareSemver)(e.version,this.config.version)>=0}async run(e,t,s){if(!this.isCompatible(e))throw Error(`Client is v${e.version}, session '${this.name}' is v${this.config.version}. Run

  playwright-cli${"default"!==this.name?` -s=${this.name}`:""} open

to restart the browser session.`);let{socket:o}=await this._connect();if(!o)throw Error(`Browser '${this.name}' is not open. Run

  playwright-cli${"default"!==this.name?` -s=${this.name}`:""} open

to start the browser session.`);return await SocketConnectionClient.sendAndClose(o,"run",{args:t,cwd:process.cwd(),raw:s?.raw,json:s?.json})}async stop(){return await this.canConnect()?(await this._stopDaemon(),{wasOpen:!0}):{wasOpen:!1}}async deleteData(){await this.stop();let e=(await import_fs.default.promises.readdir(this._sessionFile.daemonDir).catch(()=>[])).filter(e=>e===`${this.name}.session`||e.startsWith(`ud-${this.name}-`));if(0===e.length)return{existed:!1,deletedUserDataDir:!1};let t=!1;for(let s of e){let e=import_path.default.resolve(this._sessionFile.daemonDir,s);for(let o=0;o<5;o++)try{await import_fs.default.promises.rm(e,{recursive:!0}),s.startsWith("ud-")&&(t=!0);break}catch(e){if("ENOENT"===e.code)break;if(await new Promise(e=>setTimeout(e,1e3)),4===o)throw e}}return{existed:!0,deletedUserDataDir:t}}async _connect(){return await new Promise(e=>{let t=import_net.default.createConnection(this.config.socketPath,()=>{e({socket:t})});t.on("error",t=>{"win32"!==import_os.default.platform()?import_fs.default.promises.unlink(this.config.socketPath).catch(()=>{}).then(()=>e({error:t})):e({error:t})})})}async canConnect(){let{socket:e}=await this._connect();return!!e&&(e.destroy(),!0)}static async startDaemon(e,t,s){await import_fs.default.promises.mkdir(e.daemonProfilesDir,{recursive:!0});let o=(0,import_package.libPath)("entry","cliDaemon.js"),i=(0,import_registry.resolveSessionName)(t.session),r=import_path.default.join(e.daemonProfilesDir,i+".err"),n=import_fs.default.openSync(r,"w"),a=[o,i];t.headed&&a.push("--headed"),t.extension&&a.push("--extension"),t.browser&&a.push(`--browser=${t.browser}`),t.persistent&&a.push("--persistent"),t.profile&&a.push(`--profile=${t.profile}`),t.config&&a.push(`--config=${t.config}`),t.cdp&&a.push(`--cdp=${t.cdp}`),t.endpoint?a.push(`--endpoint=${t.endpoint}`):"attach"===s&&process.env.PLAYWRIGHT_CLI_SESSION&&a.push(`--endpoint=${process.env.PLAYWRIGHT_CLI_SESSION}`);let c=(0,import_child_process.spawn)(process.execPath,a,{detached:!0,stdio:["ignore","pipe",n],cwd:process.cwd()}),l=!1,p=()=>{l=!0,c.kill("SIGINT")},_=()=>{l=!0,c.kill("SIGTERM")};process.on("SIGINT",p),process.on("SIGTERM",_);let d="",h=(e,t)=>e(Object.assign(Error(`Daemon pid=${c.pid}: ${t}`),{daemonPid:c.pid}));return await new Promise((e,t)=>{c.stdout.on("data",s=>{if(!(d+=s.toString()).includes("<EOF>"))return;let o=d.match(/### Error\n([\s\S]*)<EOF>/),i=o?o[1].trim():void 0;if(i){let e=import_fs.default.readFileSync(r,"utf-8");h(t,i+(e?"\n"+e:""))}d.match(/### Success\nDaemon listening on (.*)\n<EOF>/)&&e()}),c.on("close",e=>{if(!l){let s=import_fs.default.readFileSync(r,"utf-8");h(t,`Daemon process exited with code ${e}`+(s?"\n"+s:""))}})}),process.off("SIGINT",p),process.off("SIGTERM",_),c.stdout.destroy(),c.unref(),{pid:c.pid,sessionName:i,endpoint:t.endpoint}}async _stopDaemon(){let e,{socket:t}=await this._connect();if(t&&(await SocketConnectionClient.sendAndClose(t,"stop",{}).catch(t=>e=t),e&&!e?.message?.includes("Session closed")))throw e}async deleteSessionConfig(){await import_fs.default.promises.rm(this._sessionFile.file).catch(()=>{})}}class SocketConnectionClient{constructor(e){this._nextMessageId=1,this._callbacks=new Map,this._connection=new import_socketConnection.SocketConnection(e),this._connection.onmessage=e=>this._onMessage(e),this._connection.onclose=()=>this._rejectCallbacks()}async send(e,t={}){let s=this._nextMessageId++,o=new Promise((o,i)=>{this._callbacks.set(s,{resolve:o,reject:i,method:e,params:t})}),[i]=await Promise.all([o,this._connection.send({id:s,method:e,params:t})]);return i}static async sendAndClose(e,t,s={}){let o=new SocketConnectionClient(e);try{return await o.send(t,s)}finally{o.close()}}close(){this._connection.close()}_onMessage(e){if(e.id&&this._callbacks.has(e.id)){let t=this._callbacks.get(e.id);this._callbacks.delete(e.id),e.error?t.reject(Error(e.error)):t.resolve(e.result)}else if(e.id)throw Error(`Unexpected message id: ${e.id}`);else throw Error(`Unexpected message without id: ${JSON.stringify(e)}`)}_rejectCallbacks(){for(let e of this._callbacks.values())e.reject(Error("Session closed"));this._callbacks.clear()}}