bridge-agent 0.21.0 → 0.21.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/dist/index.js CHANGED
@@ -287,7 +287,7 @@ On your first message, call bridge_get_blueprint: if the project blueprint is em
287
287
  `)).join(`
288
288
  `);var XD=/^[A-Za-z0-9][A-Za-z0-9._:\/-]{0,127}$/;function nm(e){return e?XD.test(e):!1}var QD=new Set(["claude","aider","ollama"]);function Hx(e){return QD.has(e)}var Vx=z(require("os"));async function om(){return Vx.default.platform()!=="darwin"?null:{key:"sim_ios",displayName:"iOS Simulator",binaryPath:"xcrun",authStatus:"ok"}}var oo=require("child_process"),ba=require("fs/promises"),Yx=require("crypto"),rr=z(require("fs")),Fo=z(require("path")),cu=z(require("os"));var va=require("child_process"),Gx=require("fs/promises"),Wx=z(require("path")),Jx=z(require("os"));async function ej(){return new Promise(e=>{let t=(0,va.spawn)("xcrun",["simctl","list","devices","booted","--json"],{timeout:5e3}),r="";t.stdout.on("data",n=>{r+=n.toString("utf8")}),t.on("close",n=>{if(n!==0){e(null);return}try{let o=JSON.parse(r);for(let i of Object.values(o.devices)){let s=i.find(a=>a.state==="Booted");if(s){e(s.udid);return}}e(null)}catch{e(null)}}),t.on("error",()=>e(null))})}async function tj(){return new Promise(e=>{let t=(0,va.spawn)("xcrun",["simctl","list","devices","available","--json"],{timeout:5e3}),r="";t.stdout.on("data",n=>{r+=n.toString("utf8")}),t.on("close",n=>{if(n!==0){e([]);return}try{let o=JSON.parse(r),i=[];for(let[s,a]of Object.entries(o.devices)){for(let c of a){let l=s.replace(/^com\.apple\.CoreSimulator\.SimRuntime\./,"").replace(/-/g,".");if(i.push(`${c.name} (${l})`),i.length>=3)break}if(i.length>=3)break}e(i)}catch{e([])}}),t.on("error",()=>e([]))})}async function im(e){let t=[],r=null,n=await new Promise(i=>{let s=(0,va.spawn)("xcrun",["simctl","help"],{timeout:2e3});s.on("close",a=>i(a===0)),s.on("error",()=>i(!1)),s.stdout?.resume(),s.stderr?.resume()});t.push({id:"xcrun_exists",status:n?"pass":"fail",label:"Xcode CLI tools",detail:n?void 0:"Xcode command-line tools not found. Install them to use the iOS Simulator panel.",fixCmd:n?void 0:"xcode-select --install"});let o=!1;if(n){let i=Wx.default.join(Jx.default.homedir(),".local/bin/idb");o=await(0,Gx.access)(i).then(()=>!0).catch(()=>!1)}if(t.push({id:"idb_present",status:o?"pass":"fail",label:"idb",detail:o?void 0:"idb not found at ~/.local/bin/idb. Required for simulator automation.",fixCmd:o?void 0:"pip3 install fb-idb && brew install facebook/fb/idb-companion"}),n){let i=await new Promise(s=>{let a=(0,va.spawn)("xcrun",["simctl","list","--json"],{timeout:5e3});a.on("close",c=>s(c===0)),a.on("error",()=>s(!1)),a.stdout?.resume(),a.stderr?.resume()});if(t.push({id:"simctl_ok",status:i?"pass":"fail",label:"simctl",detail:i?void 0:"simctl is not responding. Xcode may not be fully installed.",fixCmd:i?void 0:"sudo xcode-select --reset"}),i)if(r=await ej(),r)t.push({id:"booted_simulator",status:"pass",label:"Booted simulator"});else{let s=await tj();t.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:s.length>0?`No simulator is booted. Available: ${s.join(", ")}. Open Simulator.app and boot one.`:"No simulator is booted and no devices found. Open Xcode \u2192 Window \u2192 Devices and Simulators to add one.",fixCmd:"open -a Simulator"})}else t.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:"Skipped \u2014 previous check failed"})}else t.push({id:"simctl_ok",status:"fail",label:"simctl",detail:"Skipped \u2014 previous check failed"}),t.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:"Skipped \u2014 previous check failed"});return{checks:t,udid:r}}var am=Fo.default.join(cu.default.homedir(),".local/bin/idb"),tn=Fo.default.join(cu.default.homedir(),".bridge/install-sim-prereqs.sh"),sm=Fo.default.join(cu.default.homedir(),".bridge/install-sim-prereqs.sh.etag"),rj=1e4;async function Kx(e){try{let t=await new Promise((i,s)=>{let a=(0,oo.spawn)(am,["describe","--udid",e,"--json"],{timeout:1e4}),c="",l="";a.stdout.on("data",u=>{c+=u.toString("utf8")}),a.stderr.on("data",u=>{l+=u.toString("utf8")}),a.on("close",u=>{u!==0?s(new Error(l||`idb exited ${u}`)):i(c)}),a.on("error",u=>s(u))}),r=JSON.parse(t),n=r.screen_dimensions?.width_points,o=r.screen_dimensions?.height_points;if(Number.isFinite(n)&&Number.isFinite(o))return{width:n,height:o}}catch(t){console.warn("[daemon] simulator.metadata.error",{udid:e,error:String(t)})}return{}}function nj(e,t,r){let n=Buffer.from(e,"utf-8"),o=Buffer.allocUnsafe(1+n.length+4);return o.writeUInt8(n.length,0),n.copy(o,1),o.writeUInt16BE(Math.max(0,Math.min(65535,t)),1+n.length),o.writeUInt16BE(Math.max(0,Math.min(65535,r)),1+n.length+2),o}function oj(e,t){let r=`/tmp/sim_frame_${t}.png`,n=`/tmp/sim_frame_${t}.jpg`;return new Promise(o=>{let i=(0,oo.spawn)("xcrun",["simctl","io",e,"screenshot",r],{stdio:["ignore","ignore","ignore"]});i.on("close",async s=>{if(s!==0){o(null);return}try{await new Promise((a,c)=>{let l=(0,oo.spawn)("sips",["-s","format","jpeg",r,"--out",n],{stdio:["ignore","ignore","ignore"]});l.on("close",u=>u===0?a():c(new Error(`sips exited ${u}`))),l.on("error",u=>c(u))}),o(await(0,ba.readFile)(n))}catch{try{o(await(0,ba.readFile)(r))}catch{o(null)}}}),i.on("error",()=>o(null))})}function su(e,t){return new Promise((r,n)=>{let o=(0,oo.spawn)(am,[...t,"--udid",e],{timeout:15e3}),i="";o.stderr.on("data",s=>{i+=s.toString("utf8")}),o.on("close",s=>{s!==0?n(new Error(i||`idb exited ${s}`)):r()}),o.on("error",s=>n(s))})}var au=class{sessions=new Map;pendingSubscriptions=new Set;pendingUdids=new Map;pendingDaemonBootedUdids=new Set;bootedUdidsByAgent=new Map;ws=null;daemonId;config;installProc=new Map;cancelledInstalls=new Set;constructor(t,r){this.daemonId=t,this.config=r??null}updateWs(t){this.ws=t}async start(t){if(this.sessions.has(t)){console.warn("[daemon] simulator.start: session already exists",{agentId:t});return}let{checks:r,udid:n}=await im(t);if(this.sendSimHealth(t,r),r.find(d=>d.status==="fail")){if(this.bootedUdidsByAgent.has(t)){let d=this.bootedUdidsByAgent.get(t);this.pendingDaemonBootedUdids.delete(d),this.bootedUdidsByAgent.delete(t)}return}if(!n){this.sendError(t,"SPAWN_FAILED","No booted iOS simulator found");return}let i=[...this.sessions.values()].find(d=>d.udid===n);if(i){this.sendError(t,"DUPLICATE_SIMULATOR",`Simulator already attached as agent ${i.agentId}`,{existingAgentId:i.agentId,udid:n});return}let s=this.pendingUdids.get(n);if(s&&s!==t){this.sendError(t,"DUPLICATE_SIMULATOR",`Simulator already being attached as agent ${s}`,{existingAgentId:s,udid:n});return}this.pendingUdids.set(n,t);let a=this.pendingSubscriptions.has(t);this.pendingSubscriptions.delete(t);let c=await Kx(n);c.width!=null&&c.height!=null&&console.log("[daemon] simulator.metadata",{agentId:t,udid:n,logicalWidth:c.width,logicalHeight:c.height});let l=this.pendingDaemonBootedUdids.has(n);l&&(this.pendingDaemonBootedUdids.delete(n),this.bootedUdidsByAgent.delete(t));let u={agentId:t,udid:n,frameInterval:null,capturing:!1,subscribed:a,logicalWidth:c.width,logicalHeight:c.height,lastDescribeAt:Date.now(),daemonBooted:l};if(this.sessions.set(t,u),this.pendingUdids.delete(n),u.frameInterval=setInterval(async()=>{if(!(!u.subscribed||u.capturing)&&!(!this.ws||this.ws.bufferedAmount>256*1024)){u.capturing=!0;try{Date.now()-u.lastDescribeAt>=5e3&&(u.lastDescribeAt=Date.now(),Kx(n).then(p=>{p.width!=null&&p.height!=null&&(p.width!==u.logicalWidth||p.height!==u.logicalHeight)&&(console.log("[daemon] simulator.metadata.update",{agentId:t,udid:n,from:{logicalWidth:u.logicalWidth,logicalHeight:u.logicalHeight},to:p}),u.logicalWidth=p.width,u.logicalHeight=p.height)}).catch(()=>{}));let d=await oj(n,t);if(d&&this.ws&&this.ws.readyState===A.OPEN){let p=u.logicalWidth??0,f=u.logicalHeight??0,m=nj(t,p,f);this.ws.send(Buffer.concat([m,d]),{binary:!0})}}catch(d){console.error("[daemon] simulator.capture.error",{agentId:t,error:String(d)})}finally{u.capturing=!1}}},200),this.ws&&this.ws.readyState===A.OPEN){let d=(0,Yx.randomUUID)();this.ws.send(JSON.stringify({type:"session_started",agentId:t,sessionId:d})),this.ws.send(JSON.stringify({type:"agent_spawned",agentId:t,agentKey:"sim_ios",daemonId:this.daemonId}))}console.log("[daemon] simulator.started",{agentId:t,udid:n})}stop(t){let r=this.installProc.get(t);r&&(console.log("[daemon] simulator.install.cancelled",{agentId:t}),this.cancelledInstalls.add(t),r.kill("SIGTERM"),this.installProc.delete(t));let n=this.sessions.get(t);if(!n){for(let[s,a]of this.pendingUdids)if(a===t){this.pendingUdids.delete(s);break}return}n.frameInterval&&clearInterval(n.frameInterval);let o=n.udid,i=n.daemonBooted;this.sessions.delete(t),this.pendingUdids.delete(o),this.ws&&this.ws.readyState===A.OPEN&&this.ws.send(JSON.stringify({type:"exit",agentId:t,exitCode:0,signal:null})),console.log("[daemon] simulator.stop",{agentId:t,udid:o,daemonBooted:i}),i&&(0,oo.spawn)("xcrun",["simctl","shutdown",o],{stdio:"ignore"}).on("error",s=>console.warn("[daemon] simulator.shutdown.error",{udid:o,err:String(s)}))}stopAll(){for(let t of[...this.installProc.keys()])this.stop(t);for(let t of[...this.sessions.keys()])this.stop(t)}subscribe(t){let r=this.sessions.get(t);r&&(r.subscribed=!0)}unsubscribe(t){let r=this.sessions.get(t);r&&(r.subscribed=!1)}async handle(t){let r=this.sessions.get(t.agentId);if(t.type==="sim_subscribe"){r?this.subscribe(t.agentId):this.pendingSubscriptions.add(t.agentId);return}if(t.type==="sim_unsubscribe"){this.pendingSubscriptions.delete(t.agentId),r&&this.unsubscribe(t.agentId);return}if(t.type==="sim_healthcheck"){let{checks:n}=await im(t.agentId);this.sendSimHealth(t.agentId,n);return}if(t.type==="sim_install_run"){await this.handleSimInstallRun(t.agentId);return}if(t.type==="sim_install_cancel"){this.handleSimInstallCancel(t.agentId);return}if(!r){console.warn("[daemon] simulator.handle: no session",{agentId:t.agentId,type:t.type});return}try{switch(t.type){case"sim_tap":{await su(r.udid,["ui","tap",String(t.x),String(t.y)]);break}case"sim_swipe":{await su(r.udid,["ui","swipe",String(t.x1),String(t.y1),String(t.x2),String(t.y2),"--duration",String(t.duration??.5)]);break}case"sim_key":{await su(r.udid,["ui","text",t.key]);break}case"sim_button":{console.log("[daemon] simulator.button.start",{agentId:t.agentId,button:t.button,udid:r.udid}),await su(r.udid,["ui","button",t.button]),console.log("[daemon] simulator.button.done",{agentId:t.agentId,button:t.button});break}case"sim_get_source":{let n=await new Promise((o,i)=>{let s=(0,oo.spawn)(am,["ui","describe-all","--udid",r.udid],{timeout:15e3}),a="",c="";s.stdout.on("data",l=>{a+=l.toString("utf8")}),s.stderr.on("data",l=>{c+=l.toString("utf8")}),s.on("close",l=>{l!==0?i(new Error(c||`idb exited ${l}`)):o(a)}),s.on("error",l=>i(l))});this.ws&&this.ws.readyState===A.OPEN&&this.ws.send(JSON.stringify({type:"sim_source",agentId:t.agentId,source:n}));break}}}catch(n){console.error("[daemon] simulator.handle.error",{agentId:t.agentId,type:t.type,error:String(n)})}}sendError(t,r,n,o){this.ws&&this.ws.readyState===A.OPEN&&this.ws.send(JSON.stringify({type:"error",code:r,message:n,agentId:t,...o}))}sendSimHealth(t,r){this.ws&&this.ws.readyState===A.OPEN&&this.ws.send(JSON.stringify({type:"sim_health",agentId:t,checks:r}))}resolveSimInstallScriptSync(){let t=process.env.BRIDGE_SIM_INSTALL_SCRIPT;if(t)return t;if(rr.default.existsSync(tn))return tn;let r=Fo.default.join(__dirname,"../../../scripts/install-sim-prereqs.sh");return rr.default.existsSync(r)?r:null}async ensureSimInstallScript(t){let r=process.env.BRIDGE_SIM_INSTALL_SCRIPT;if(r)return r;let n=await this.fetchSimInstallScript(t);if(n)return n;if(rr.default.existsSync(tn))return console.warn("[daemon] simulator.install.script: fetch failed, using cached copy",{agentId:t}),tn;let o=Fo.default.join(__dirname,"../../../scripts/install-sim-prereqs.sh");return rr.default.existsSync(o)?o:(this.sendInstallProgress(t,{step:"error",error:"Could not download the simulator install script from the server (offline?). Check your connection and retry."}),null)}async fetchSimInstallScript(t){if(!this.config?.server||!this.config?.token)return console.warn("[daemon] simulator.install.script: no server/token in config",{agentId:t}),null;let r=`${this.config.server.replace(/\/$/,"")}/api/meta/sim-install-script`,n=null;try{rr.default.existsSync(sm)&&(n=rr.default.readFileSync(sm,"utf8").trim()||null)}catch{}let o;try{o=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,...n?{"If-None-Match":n}:{}},signal:AbortSignal.timeout(rj)})}catch(s){return console.warn("[daemon] simulator.install.script: fetch failed",{agentId:t,error:String(s)}),null}if(o.status===304)return rr.default.existsSync(tn)?tn:null;if(o.status===401)return console.error("[daemon] simulator.install.script: server rejected the daemon token",{agentId:t}),this.sendInstallProgress(t,{step:"error",error:"Server rejected the daemon token. Re-authenticate the daemon (bridge-agent auth)."}),null;if(o.status!==200)return console.warn("[daemon] simulator.install.script: unexpected status",{agentId:t,status:o.status}),null;let i=await o.text();try{rr.default.mkdirSync(Fo.default.dirname(tn),{recursive:!0}),await(0,ba.writeFile)(tn,i,{encoding:"utf8",mode:493}),rr.default.chmodSync(tn,493);let s=o.headers.get("etag");return s&&rr.default.writeFileSync(sm,s,"utf8"),tn}catch(s){return console.error("[daemon] simulator.install.script: failed to cache",{agentId:t,error:String(s)}),null}}async handleSimInstallRun(t){if(this.installProc.has(t)){this.sendInstallProgress(t,{step:"error",error:"already installing"});return}this.cancelledInstalls.delete(t);let r=await this.ensureSimInstallScript(t);if(!r)return;try{rr.default.accessSync(r,rr.default.constants.F_OK)}catch{this.sendInstallProgress(t,{step:"error",error:`install script not found at ${r}`});return}let n=(0,oo.spawn)("bash",["-lc",r],{timeout:6e5});this.installProc.set(t,n);let o="pre_check",i="",s="";n.stdout?.on("data",a=>{i+=a.toString("utf8");let c;for(;(c=i.indexOf(`
289
289
  `))!==-1;){let l=i.slice(0,c);if(i=i.slice(c+1),!!l)if(l.startsWith("STEP:"))o=l.slice(5).trim(),this.sendInstallProgress(t,{step:o});else if(l.startsWith("BOOTED_UDID:")){let u=l.slice(12).trim();this.pendingDaemonBootedUdids.add(u),this.bootedUdidsByAgent.set(t,u)}else this.sendInstallProgress(t,{stream:"stdout",line:l})}}),n.stderr?.on("data",a=>{s+=a.toString("utf8");let c;for(;(c=s.indexOf(`
290
- `))!==-1;){let l=s.slice(0,c);s=s.slice(c+1),l&&this.sendInstallProgress(t,{stream:"stderr",line:l})}}),n.on("close",a=>{if(this.installProc.delete(t),a!==0){let l=this.bootedUdidsByAgent.get(t);l&&(this.pendingDaemonBootedUdids.delete(l),this.bootedUdidsByAgent.delete(t))}if(i){let l=i;i="",l.startsWith("STEP:")?(o=l.slice(5).trim(),this.sendInstallProgress(t,{step:o})):this.sendInstallProgress(t,{stream:"stdout",line:l})}if(s){let l=s;s="",this.sendInstallProgress(t,{stream:"stderr",line:l})}let c=this.cancelledInstalls.has(t);this.cancelledInstalls.delete(t),!c&&(a===0?this.sendInstallProgress(t,{step:"done",exitCode:0}):this.sendInstallProgress(t,{step:"error",exitCode:a??void 0,error:`install script exited with code ${a}`}))}),n.on("error",a=>{this.installProc.delete(t);let c=this.bootedUdidsByAgent.get(t);c&&(this.pendingDaemonBootedUdids.delete(c),this.bootedUdidsByAgent.delete(t));let l=this.cancelledInstalls.has(t);this.cancelledInstalls.delete(t),!l&&this.sendInstallProgress(t,{step:"error",error:String(a)})})}handleSimInstallCancel(t){let r=this.installProc.get(t);if(!r)return;this.cancelledInstalls.add(t);let n=this.bootedUdidsByAgent.get(t);n&&(this.pendingDaemonBootedUdids.delete(n),this.bootedUdidsByAgent.delete(t)),r.kill("SIGTERM"),this.installProc.delete(t),this.sendInstallProgress(t,{step:"error",error:"cancelled by user"})}sendInstallProgress(t,r){this.ws&&this.ws.readyState===A.OPEN&&this.ws.send(JSON.stringify({type:"sim_install_progress",agentId:t,...r}))}};Zo();ht();var cS=z(require("path")),cj="0.21.0",aS;function Nt(){return cj}function Ht(){if(aS)return aS;if(process.pkg!==void 0)return process.execPath;let e=[...process.env.npm_config_global_prefix?[cS.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let t of e)try{return require("node:fs").realpathSync(t)}catch{}return process.execPath}var bu=require("fs"),Mi=z(require("path")),hS=z(require("os"));var dm=require("node:fs"),gu=class{cache=new Map;get(t,r){let n=this.cache.get(t);if(n&&n.mtimeMs===r.mtimeMs&&n.size===r.size)return n.value}set(t,r,n){this.cache.set(t,{mtimeMs:r.mtimeMs,size:r.size,value:n})}invalidate(t){this.cache.delete(t)}clear(){this.cache.clear()}prune(t){for(let r of this.cache.keys())t.has(r)||this.cache.delete(r)}prunePrefix(t,r){for(let n of this.cache.keys())n.startsWith(t)&&!r.has(n)&&this.cache.delete(n)}get size(){return this.cache.size}},yr=new gu,NJ=new gu;async function Mr(e){try{let t=await dm.promises.stat(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function lS(e,t){let r=await dm.promises.open(e,"r");try{let o=(await r.stat()).size-t;if(o<=0)return Buffer.alloc(0);let i=Buffer.alloc(o);return await r.read(i,0,o,t),i}finally{await r.close()}}function Tn(){return new Promise(e=>setImmediate(e))}var zi=require("node:fs"),dS=z(require("node:os")),qo=z(require("node:path")),lj=/bridge_codegraph_/,uj=new Set(["Read","Grep","Glob"]);function dj(e){return lj.test(e)?"codegraph":uj.has(e)?"nativeSearch":"other"}var pj=new Set(["assistant","user","system","summary","last-prompt","mode","permission-mode","attachment","file-history-snapshot","file-history-delta","ai-title","relocated","worktree-state","queue-operation"]);function pm(){return{input:0,cacheCreation:0,cacheRead:0,output:0}}function Sa(e,t){e.input+=t.input,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead,e.output+=t.output}async function fj(e){let t=qo.default.join(e,"subagents"),r;try{r=await zi.promises.readdir(t,{withFileTypes:!0})}catch{return[]}let n=[];for(let o of r){if(!o.isFile())continue;let i=/^agent-(.+)\.jsonl$/.exec(o.name);if(!i||!i[1])continue;let s={path:qo.default.join(t,o.name),agentId:i[1]};try{let a=await zi.promises.readFile(qo.default.join(t,`agent-${i[1]}.meta.json`),"utf-8"),c=JSON.parse(a);typeof c.agentType=="string"&&(s.agentType=c.agentType),typeof c.spawnDepth=="number"&&(s.spawnDepth=c.spawnDepth)}catch{}n.push(s)}return n.sort((o,i)=>o.path.localeCompare(i.path)),n}async function pS(e,t){let r=t??qo.default.join(dS.default.homedir(),".claude","projects"),n;try{n=await zi.promises.readdir(r,{withFileTypes:!0})}catch{return null}for(let o of n){if(!o.isDirectory())continue;let i=qo.default.join(r,o.name,`${e}.jsonl`);try{await zi.promises.access(i)}catch{continue}let s=await fj(qo.default.join(r,o.name,e));return{main:i,subagents:s,projectSlug:o.name}}return null}function ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yu(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function mj(e){return{input:yu(e.input_tokens),cacheCreation:yu(e.cache_creation_input_tokens),cacheRead:yu(e.cache_read_input_tokens),output:yu(e.output_tokens)}}function hj(e,t,r){let n;try{n=JSON.parse(e)}catch{return!1}if(r.linesParsed++,!ji(n))return!0;let o=ji(n.message)?n.message:void 0,i=n.type;if((o||typeof i=="string"&&pj.has(i)||"parentUuid"in n||"sessionId"in n)&&(r.sawClaudeMarker=!0),(n.isCompactSummary===!0||i==="system"&&(n.subtype==="compact_boundary"||n.isCompactSummary===!0))&&(r.hadCompaction=!0),o&&ji(o.usage)){let s=mj(o.usage),a=o.id;if(typeof a=="string"&&a!==""){let c=r.seen.get(a);if(c){if(c.input!==s.input||c.cacheCreation!==s.cacheCreation||c.cacheRead!==s.cacheRead)r.anomalyCount++;else if(s.output>c.output){let l=s.output-c.output;c.output=s.output,r.totals.output+=l,t&&(r.subagentTotals.output+=l)}}else r.seen.set(a,s),Sa(r.totals,s),t&&Sa(r.subagentTotals,s)}else Sa(r.totals,s),t&&Sa(r.subagentTotals,s)}if(i==="assistant"&&o&&Array.isArray(o.content)){let s=typeof o.id=="string"?o.id:void 0;for(let a of o.content){if(!ji(a)||a.type!=="tool_use")continue;let c=a.name;if(typeof c!="string"||c==="")continue;r.tools.set(c,(r.tools.get(c)??0)+1);let l=dj(c);r.buckets[l]++;let u=a.id;if(typeof u=="string"&&u!==""&&r.toolUseBucketById.set(u,l),s){let d=r.msgBuckets.get(s);d||(d=new Set,r.msgBuckets.set(s,d)),d.add(l)}}}if(i==="user"&&o&&Array.isArray(o.content))for(let s of o.content){if(!ji(s)||s.type!=="tool_result")continue;let a=s.content,c=0;typeof a=="string"?c=a.length:(Array.isArray(a)||ji(a))&&(c=JSON.stringify(a).length),r.pendingResults.push({toolUseId:typeof s.tool_use_id=="string"?s.tool_use_id:void 0,bytes:c})}return!0}async function uS(e,t,r){let o=(await zi.promises.readFile(e,"utf-8")).split(`
290
+ `))!==-1;){let l=s.slice(0,c);s=s.slice(c+1),l&&this.sendInstallProgress(t,{stream:"stderr",line:l})}}),n.on("close",a=>{if(this.installProc.delete(t),a!==0){let l=this.bootedUdidsByAgent.get(t);l&&(this.pendingDaemonBootedUdids.delete(l),this.bootedUdidsByAgent.delete(t))}if(i){let l=i;i="",l.startsWith("STEP:")?(o=l.slice(5).trim(),this.sendInstallProgress(t,{step:o})):this.sendInstallProgress(t,{stream:"stdout",line:l})}if(s){let l=s;s="",this.sendInstallProgress(t,{stream:"stderr",line:l})}let c=this.cancelledInstalls.has(t);this.cancelledInstalls.delete(t),!c&&(a===0?this.sendInstallProgress(t,{step:"done",exitCode:0}):this.sendInstallProgress(t,{step:"error",exitCode:a??void 0,error:`install script exited with code ${a}`}))}),n.on("error",a=>{this.installProc.delete(t);let c=this.bootedUdidsByAgent.get(t);c&&(this.pendingDaemonBootedUdids.delete(c),this.bootedUdidsByAgent.delete(t));let l=this.cancelledInstalls.has(t);this.cancelledInstalls.delete(t),!l&&this.sendInstallProgress(t,{step:"error",error:String(a)})})}handleSimInstallCancel(t){let r=this.installProc.get(t);if(!r)return;this.cancelledInstalls.add(t);let n=this.bootedUdidsByAgent.get(t);n&&(this.pendingDaemonBootedUdids.delete(n),this.bootedUdidsByAgent.delete(t)),r.kill("SIGTERM"),this.installProc.delete(t),this.sendInstallProgress(t,{step:"error",error:"cancelled by user"})}sendInstallProgress(t,r){this.ws&&this.ws.readyState===A.OPEN&&this.ws.send(JSON.stringify({type:"sim_install_progress",agentId:t,...r}))}};Zo();ht();var cS=z(require("path")),cj="0.21.1",aS;function Nt(){return cj}function Ht(){if(aS)return aS;if(process.pkg!==void 0)return process.execPath;let e=[...process.env.npm_config_global_prefix?[cS.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let t of e)try{return require("node:fs").realpathSync(t)}catch{}return process.execPath}var bu=require("fs"),Mi=z(require("path")),hS=z(require("os"));var dm=require("node:fs"),gu=class{cache=new Map;get(t,r){let n=this.cache.get(t);if(n&&n.mtimeMs===r.mtimeMs&&n.size===r.size)return n.value}set(t,r,n){this.cache.set(t,{mtimeMs:r.mtimeMs,size:r.size,value:n})}invalidate(t){this.cache.delete(t)}clear(){this.cache.clear()}prune(t){for(let r of this.cache.keys())t.has(r)||this.cache.delete(r)}prunePrefix(t,r){for(let n of this.cache.keys())n.startsWith(t)&&!r.has(n)&&this.cache.delete(n)}get size(){return this.cache.size}},yr=new gu,NJ=new gu;async function Mr(e){try{let t=await dm.promises.stat(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function lS(e,t){let r=await dm.promises.open(e,"r");try{let o=(await r.stat()).size-t;if(o<=0)return Buffer.alloc(0);let i=Buffer.alloc(o);return await r.read(i,0,o,t),i}finally{await r.close()}}function Tn(){return new Promise(e=>setImmediate(e))}var zi=require("node:fs"),dS=z(require("node:os")),qo=z(require("node:path")),lj=/bridge_codegraph_/,uj=new Set(["Read","Grep","Glob"]);function dj(e){return lj.test(e)?"codegraph":uj.has(e)?"nativeSearch":"other"}var pj=new Set(["assistant","user","system","summary","last-prompt","mode","permission-mode","attachment","file-history-snapshot","file-history-delta","ai-title","relocated","worktree-state","queue-operation"]);function pm(){return{input:0,cacheCreation:0,cacheRead:0,output:0}}function Sa(e,t){e.input+=t.input,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead,e.output+=t.output}async function fj(e){let t=qo.default.join(e,"subagents"),r;try{r=await zi.promises.readdir(t,{withFileTypes:!0})}catch{return[]}let n=[];for(let o of r){if(!o.isFile())continue;let i=/^agent-(.+)\.jsonl$/.exec(o.name);if(!i||!i[1])continue;let s={path:qo.default.join(t,o.name),agentId:i[1]};try{let a=await zi.promises.readFile(qo.default.join(t,`agent-${i[1]}.meta.json`),"utf-8"),c=JSON.parse(a);typeof c.agentType=="string"&&(s.agentType=c.agentType),typeof c.spawnDepth=="number"&&(s.spawnDepth=c.spawnDepth)}catch{}n.push(s)}return n.sort((o,i)=>o.path.localeCompare(i.path)),n}async function pS(e,t){let r=t??qo.default.join(dS.default.homedir(),".claude","projects"),n;try{n=await zi.promises.readdir(r,{withFileTypes:!0})}catch{return null}for(let o of n){if(!o.isDirectory())continue;let i=qo.default.join(r,o.name,`${e}.jsonl`);try{await zi.promises.access(i)}catch{continue}let s=await fj(qo.default.join(r,o.name,e));return{main:i,subagents:s,projectSlug:o.name}}return null}function ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yu(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function mj(e){return{input:yu(e.input_tokens),cacheCreation:yu(e.cache_creation_input_tokens),cacheRead:yu(e.cache_read_input_tokens),output:yu(e.output_tokens)}}function hj(e,t,r){let n;try{n=JSON.parse(e)}catch{return!1}if(r.linesParsed++,!ji(n))return!0;let o=ji(n.message)?n.message:void 0,i=n.type;if((o||typeof i=="string"&&pj.has(i)||"parentUuid"in n||"sessionId"in n)&&(r.sawClaudeMarker=!0),(n.isCompactSummary===!0||i==="system"&&(n.subtype==="compact_boundary"||n.isCompactSummary===!0))&&(r.hadCompaction=!0),o&&ji(o.usage)){let s=mj(o.usage),a=o.id;if(typeof a=="string"&&a!==""){let c=r.seen.get(a);if(c){if(c.input!==s.input||c.cacheCreation!==s.cacheCreation||c.cacheRead!==s.cacheRead)r.anomalyCount++;else if(s.output>c.output){let l=s.output-c.output;c.output=s.output,r.totals.output+=l,t&&(r.subagentTotals.output+=l)}}else r.seen.set(a,s),Sa(r.totals,s),t&&Sa(r.subagentTotals,s)}else Sa(r.totals,s),t&&Sa(r.subagentTotals,s)}if(i==="assistant"&&o&&Array.isArray(o.content)){let s=typeof o.id=="string"?o.id:void 0;for(let a of o.content){if(!ji(a)||a.type!=="tool_use")continue;let c=a.name;if(typeof c!="string"||c==="")continue;r.tools.set(c,(r.tools.get(c)??0)+1);let l=dj(c);r.buckets[l]++;let u=a.id;if(typeof u=="string"&&u!==""&&r.toolUseBucketById.set(u,l),s){let d=r.msgBuckets.get(s);d||(d=new Set,r.msgBuckets.set(s,d)),d.add(l)}}}if(i==="user"&&o&&Array.isArray(o.content))for(let s of o.content){if(!ji(s)||s.type!=="tool_result")continue;let a=s.content,c=0;typeof a=="string"?c=a.length:(Array.isArray(a)||ji(a))&&(c=JSON.stringify(a).length),r.pendingResults.push({toolUseId:typeof s.tool_use_id=="string"?s.tool_use_id:void 0,bytes:c})}return!0}async function uS(e,t,r){let o=(await zi.promises.readFile(e,"utf-8")).split(`
291
291
  `),i=o.length-1;for(let s=0;s<o.length;s++){let a=o[s];if(!a||!a.trim())continue;!hj(a,t,r)&&s===i&&(r.truncatedTail=!0)}}async function fS(e,t){let r={seen:new Map,totals:pm(),subagentTotals:pm(),anomalyCount:0,hadCompaction:!1,truncatedTail:!1,tools:new Map,buckets:{codegraph:0,nativeSearch:0,other:0},toolUseBucketById:new Map,msgBuckets:new Map,pendingResults:[],linesParsed:0,sawClaudeMarker:!1};e.main&&await uS(e.main,!1,r);for(let a of e.subagents)try{await uS(a.path,!0,r)}catch{}if(r.linesParsed>0&&!r.sawClaudeMarker)throw new Error(`not a Claude Code transcript: ${r.linesParsed} lines parsed but no message.usage shape found`);let n={codegraph:0,nativeSearch:0,other:0};for(let a of r.pendingResults){let c=a.toolUseId&&r.toolUseBucketById.get(a.toolUseId)||"other";n[c]+=a.bytes}let o={turns:0,tokens:pm()};for(let[a,c]of r.seen){let l=r.msgBuckets.get(a);l&&(l.has("codegraph")||l.has("nativeSearch"))&&(o.turns++,Sa(o.tokens,c))}let i={input:r.totals.input-o.tokens.input,cacheCreation:r.totals.cacheCreation-o.tokens.cacheCreation,cacheRead:r.totals.cacheRead-o.tokens.cacheRead,output:r.totals.output-o.tokens.output},s={};for(let[a,c]of[...r.tools.entries()].sort((l,u)=>u[1]-l[1]))s[a]=c;return{sessionId:t,projectSlug:e.projectSlug,files:{main:e.main,subagents:e.subagents.map(a=>a.path)},totals:r.totals,subagentTotals:r.subagentTotals,turns:r.seen.size,anomalyCount:r.anomalyCount,hadCompaction:r.hadCompaction,truncatedTail:r.truncatedTail,tools:s,buckets:r.buckets,resultBytes:n,attributed:o,residual:{tokens:i}}}var gj=2e5,mS=1e5,yj=/bridge_codegraph_/,_j=new Set(["Read","Grep","Glob"]);function vj(e){return yj.test(e)?"codegraph":_j.has(e)?"nativeSearch":"other"}async function bj(e){let t=Mi.default.join(hS.default.homedir(),".claude","projects");try{let r=await bu.promises.readdir(t,{withFileTypes:!0});for(let n of r){if(!n.isDirectory())continue;let o=Mi.default.join(t,n.name,`${e}.jsonl`);if(!await Mr(o))continue;let s=Mi.default.join(t,n.name,e,"subagents");return{main:o,subagents:await gS(s),subagentsDir:s}}}catch{}}async function gS(e){if(!e)return[];try{return(await bu.promises.readdir(e,{withFileTypes:!0})).filter(r=>r.isFile()&&/^agent-.+\.jsonl$/.test(r.name)).map(r=>Mi.default.join(e,r.name)).sort()}catch{return[]}}function _u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vu(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function fm(e,t,r){let n,o=!0,i=!0,s=-1,a=0,c=0,l=0,u=0,d=new Map,p=new Map,f=new Set,m=new Set,h=P=>{c=P.input+P.cacheCreation+P.cacheRead,a=Math.min(100,Math.round(c/gj*100))},g=async(P,E,q,N)=>{f.add(P);let w=await Mr(P);if(!w)return;let k=d.get(P);if(k||(k={offset:0,pending:Buffer.alloc(0)},d.set(P,k)),w.size<k.offset&&(k.offset=0,k.pending=Buffer.alloc(0),console.log("[daemon] claude-usage.rotate",{agentId:e,sessionId:t,filePath:P})),w.size===k.offset&&k.pending.length===0)return;let S=await lS(P,k.offset);if(S.length===0)return;k.offset+=S.length;let y=k.pending.length>0?Buffer.concat([k.pending,S]):S,L=y.lastIndexOf(10);if(L===-1){k.pending=y;return}let C=y.subarray(0,L+1).toString("utf-8");k.pending=y.subarray(L+1);for(let ee of C.split(`
292
292
  `)){if(!ee||!ee.trim())continue;let I;try{I=JSON.parse(ee)}catch{continue}if(!_u(I))continue;let $=_u(I.message)?I.message:void 0;if(I.type==="assistant"&&$){let ke=$.content;if(Array.isArray(ke))for(let Re of ke){if(!_u(Re)||Re.type!=="tool_use")continue;let st=Re.name;if(typeof st!="string"||st==="")continue;let ge=typeof Re.id=="string"?Re.id:void 0;if(ge){if(m.has(ge))continue;if(m.add(ge),m.size>mS){let $e=m.values().next().value;$e!==void 0&&m.delete($e)}}N[vj(st)]++}}let Oe=$&&_u($.usage)?$.usage:void 0;if(!Oe)continue;let V={input:vu(Oe.input_tokens),cacheCreation:vu(Oe.cache_creation_input_tokens),cacheRead:vu(Oe.cache_read_input_tokens),output:vu(Oe.output_tokens)};E&&h(V);let Ze=$&&typeof $.id=="string"?$.id:void 0;if(Ze){let ke=p.get(Ze);if(ke){ke.input!==V.input||ke.cacheCreation!==V.cacheCreation||ke.cacheRead!==V.cacheRead?l++:V.output>ke.output&&(q.output+=V.output-ke.output,ke.output=V.output);continue}if(p.set(Ze,V),p.size>mS){let Re=p.keys().next().value;Re!==void 0&&p.delete(Re)}}q.input+=V.input,q.cacheCreation+=V.cacheCreation,q.cacheRead+=V.cacheRead,q.output+=V.output}},_=async()=>{if(o)try{if(n||(n=await bj(t)),!n)return;n.subagents=await gS(n.subagentsDir);let P={input:0,cacheCreation:0,cacheRead:0,output:0},E={codegraph:0,nativeSearch:0,other:0},q=0;n.main&&(await g(n.main,!0,P,E),q++,await Tn());for(let k of n.subagents)await g(k,!1,P,E),q++,await Tn();if(q===0||!o)return;l!==u&&(u=l,console.warn("[daemon] claude-usage.anomaly",{agentId:e,sessionId:t,anomalyCount:l})),i&&(i=!1,s=c,r(e,a,c,null,null,!0));let N=P.input>0||P.cacheCreation>0||P.cacheRead>0||P.output>0,w=E.codegraph>0||E.nativeSearch>0||E.other>0;(N||w||c!==s)&&(s=c,r(e,a,c,{inputTokens:P.input,cacheCreationTokens:P.cacheCreation,cacheReadTokens:P.cacheRead,outputTokens:P.output},w?E:null,!1))}catch{}},b=setTimeout(()=>{_()},5e3),x=setInterval(()=>{_()},6e4);return()=>(o=!1,clearTimeout(b),clearInterval(x),{sessionId:t,files:[...f]})}async function yS(e,t){let r=[...new Set(e)],n=new Set,o;for(let l of r){let u=await pS(l).catch(()=>null);if(u){u.main&&(n.add(u.main),o=u.main);for(let d of u.subagents)n.add(d.path)}}for(let l of t)n.add(l);let i=[];for(let l of n)try{await bu.promises.access(l),i.push(l)}catch{}let s=r[r.length-1];if(!s||i.length===0)return null;let a=o&&i.includes(o)?o:i[0],c=await fS({main:a,subagents:i.filter(l=>l!==a).map(l=>({path:l,agentId:Mi.default.basename(l).replace(/\.jsonl$/,"")})),projectSlug:void 0},s);return{sessionId:s,stats:{input:c.totals.input,cacheCreation:c.totals.cacheCreation,cacheRead:c.totals.cacheRead,output:c.totals.output,turns:c.turns,codegraphCalls:c.buckets.codegraph,nativeSearchCalls:c.buckets.nativeSearch,otherCalls:c.buckets.other,hadCompaction:c.hadCompaction,anomalyCount:c.anomalyCount,truncatedTail:c.truncatedTail}}}var _E=z(i0(),1),_c=z(require("node:process"),1),vE=require("node:stream");var s0=Object.freeze({status:"aborted"});function v(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let p=u[d];p in a||(a[p]=l[p].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var rn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ho=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},ku={};function ut(e){return e&&Object.assign(ku,e),ku}var j={};Do(j,{BIGINT_FORMAT_RANGES:()=>Cm,Class:()=>Sm,NUMBER_FORMAT_RANGES:()=>Rm,aborted:()=>lo,allowsEval:()=>Em,assert:()=>Yj,assertEqual:()=>Gj,assertIs:()=>Jj,assertNever:()=>Kj,assertNotEqual:()=>Wj,assignProp:()=>ao,base64ToUint8Array:()=>m0,base64urlToUint8Array:()=>cz,cached:()=>Bi,captureStackTrace:()=>Su,cleanEnum:()=>az,cleanRegex:()=>Ea,clone:()=>Dt,cloneDef:()=>Qj,createTransparentProxy:()=>iz,defineLazy:()=>pe,esc:()=>xu,escapeRegex:()=>_r,extend:()=>u0,finalizeIssue:()=>Vt,floatSafeRemainder:()=>$m,getElementAtPath:()=>ez,getEnumValues:()=>Ia,getLengthableOrigin:()=>Oa,getParsedType:()=>oz,getSizableOrigin:()=>Pa,hexToUint8Array:()=>uz,isObject:()=>Vo,isPlainObject:()=>co,issue:()=>Zi,joinValues:()=>ne,jsonStringifyReplacer:()=>Fi,merge:()=>sz,mergeDefs:()=>Pn,normalizeParams:()=>F,nullish:()=>so,numKeys:()=>nz,objectClone:()=>Xj,omit:()=>l0,optionalKeys:()=>Om,parsedType:()=>ie,partial:()=>p0,pick:()=>c0,prefixIssues:()=>nr,primitiveTypes:()=>Pm,promiseAllObject:()=>tz,propertyKeyTypes:()=>Ta,randomString:()=>rz,required:()=>f0,safeExtend:()=>d0,shallowClone:()=>Tm,slugify:()=>Im,stringifyPrimitive:()=>oe,uint8ArrayToBase64:()=>h0,uint8ArrayToBase64url:()=>lz,uint8ArrayToHex:()=>dz,unwrapMessage:()=>$a});function Gj(e){return e}function Wj(e){return e}function Jj(e){}function Kj(e){throw new Error("Unexpected value in exhaustive check")}function Yj(e){}function Ia(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>oe(r)).join(t)}function Fi(e,t){return typeof t=="bigint"?t.toString():t}function Bi(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function so(e){return e==null}function Ea(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function $m(e,t){let r=(e.toString().split(".")[1]||"").length,n=t.toString(),o=(n.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(n)){let c=n.match(/\d?e-(\d?)/);c?.[1]&&(o=Number.parseInt(c[1]))}let i=r>o?r:o,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}var a0=Symbol("evaluating");function pe(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==a0)return n===void 0&&(n=a0,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Xj(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function ao(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Pn(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Qj(e){return Pn(e._zod.def)}function ez(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function tz(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function rz(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function xu(e){return JSON.stringify(e)}function Im(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Su="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Vo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Em=Bi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function co(e){if(Vo(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Vo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Tm(e){return co(e)?{...e}:Array.isArray(e)?[...e]:e}function nz(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var oz=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Ta=new Set(["string","number","symbol"]),Pm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function _r(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dt(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function F(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function iz(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function oe(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Om(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Rm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Cm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function c0(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Pn(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return ao(this,"shape",s),s},checks:[]});return Dt(e,i)}function l0(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Pn(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return ao(this,"shape",s),s},checks:[]});return Dt(e,i)}function u0(e,t){if(!co(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Pn(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return ao(this,"shape",i),i}});return Dt(e,o)}function d0(e,t){if(!co(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Pn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ao(this,"shape",n),n}});return Dt(e,r)}function sz(e,t){let r=Pn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return ao(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Dt(e,r)}function p0(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Pn(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return ao(this,"shape",c),c},checks:[]});return Dt(t,s)}function f0(e,t,r){let n=Pn(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return ao(this,"shape",i),i}});return Dt(t,n)}function lo(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function nr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function $a(e){return typeof e=="string"?e:e?.message}function Vt(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=$a(e.inst?._zod.def?.error?.(e))??$a(t?.error?.(e))??$a(r.customError?.(e))??$a(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Pa(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Oa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ie(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Zi(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function az(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function m0(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function h0(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function cz(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return m0(t+r)}function lz(e){return h0(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uz(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function dz(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Sm=class{constructor(...t){}};var g0=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Fi,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$u=v("$ZodError",g0),Ra=v("$ZodError",g0,{Parent:Error});function Iu(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function Eu(e,t=r=>r.message){let r={_errors:[]},n=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>n({issues:s}));else if(i.code==="invalid_key")n({issues:i.issues});else if(i.code==="invalid_element")n({issues:i.issues});else if(i.path.length===0)r._errors.push(t(i));else{let s=r,a=0;for(;a<i.path.length;){let c=i.path[a];a===i.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(i))):s[c]=s[c]||{_errors:[]},s=s[c],a++}}};return n(e),r}var Ca=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new rn;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Vt(c,i,ut())));throw Su(a,o?.callee),a}return s.value},Aa=Ca(Ra),Na=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Vt(c,i,ut())));throw Su(a,o?.callee),a}return s.value},Da=Na(Ra),ja=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new rn;return i.issues.length?{success:!1,error:new(e??$u)(i.issues.map(s=>Vt(s,o,ut())))}:{success:!0,data:i.value}},qi=ja(Ra),za=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Vt(s,o,ut())))}:{success:!0,data:i.value}},Ma=za(Ra),y0=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Ca(e)(t,r,o)};var _0=e=>(t,r,n)=>Ca(e)(t,r,n);var v0=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Na(e)(t,r,o)};var b0=e=>async(t,r,n)=>Na(e)(t,r,n);var w0=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ja(e)(t,r,o)};var k0=e=>(t,r,n)=>ja(e)(t,r,n);var x0=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return za(e)(t,r,o)};var S0=e=>async(t,r,n)=>za(e)(t,r,n);var vr={};Do(vr,{base64:()=>Wm,base64url:()=>Tu,bigint:()=>eh,boolean:()=>rh,browserEmail:()=>bz,cidrv4:()=>Vm,cidrv6:()=>Gm,cuid:()=>Am,cuid2:()=>Nm,date:()=>Km,datetime:()=>Xm,domain:()=>xz,duration:()=>Lm,e164:()=>Jm,email:()=>Fm,emoji:()=>Bm,extendedDuration:()=>fz,guid:()=>Um,hex:()=>Sz,hostname:()=>kz,html5Email:()=>yz,idnEmail:()=>vz,integer:()=>th,ipv4:()=>Zm,ipv6:()=>qm,ksuid:()=>zm,lowercase:()=>ih,mac:()=>Hm,md5_base64:()=>Iz,md5_base64url:()=>Ez,md5_hex:()=>$z,nanoid:()=>Mm,null:()=>nh,number:()=>Pu,rfc5322Email:()=>_z,sha1_base64:()=>Pz,sha1_base64url:()=>Oz,sha1_hex:()=>Tz,sha256_base64:()=>Cz,sha256_base64url:()=>Az,sha256_hex:()=>Rz,sha384_base64:()=>Dz,sha384_base64url:()=>jz,sha384_hex:()=>Nz,sha512_base64:()=>Mz,sha512_base64url:()=>Lz,sha512_hex:()=>zz,string:()=>Qm,time:()=>Ym,ulid:()=>Dm,undefined:()=>oh,unicodeEmail:()=>$0,uppercase:()=>sh,uuid:()=>Go,uuid4:()=>mz,uuid6:()=>hz,uuid7:()=>gz,xid:()=>jm});var Am=/^[cC][^\s-]{8,}$/,Nm=/^[0-9a-z]+$/,Dm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jm=/^[0-9a-vA-V]{20}$/,zm=/^[A-Za-z0-9]{27}$/,Mm=/^[a-zA-Z0-9_-]{21}$/,Lm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fz=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Um=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Go=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,mz=Go(4),hz=Go(6),gz=Go(7),Fm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,yz=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,_z=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,$0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,vz=$0,bz=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,wz="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Bm(){return new RegExp(wz,"u")}var Zm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qm=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Hm=e=>{let t=_r(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Vm=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Gm=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Wm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tu=/^[A-Za-z0-9_-]*$/,kz=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,xz=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Jm=/^\+[1-9]\d{6,14}$/,I0="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Km=new RegExp(`^${I0}$`);function E0(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ym(e){return new RegExp(`^${E0(e)}$`)}function Xm(e){let t=E0({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${I0}T(?:${n})$`)}var Qm=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},eh=/^-?\d+n?$/,th=/^-?\d+$/,Pu=/^-?\d+(?:\.\d+)?$/,rh=/^(?:true|false)$/i,nh=/^null$/i;var oh=/^undefined$/i;var ih=/^[^A-Z]*$/,sh=/^[^a-z]*$/,Sz=/^[0-9a-fA-F]*$/;function La(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Ua(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var $z=/^[0-9a-fA-F]{32}$/,Iz=La(22,"=="),Ez=Ua(22),Tz=/^[0-9a-fA-F]{40}$/,Pz=La(27,"="),Oz=Ua(27),Rz=/^[0-9a-fA-F]{64}$/,Cz=La(43,"="),Az=Ua(43),Nz=/^[0-9a-fA-F]{96}$/,Dz=La(64,""),jz=Ua(64),zz=/^[0-9a-fA-F]{128}$/,Mz=La(86,"=="),Lz=Ua(86);var Me=v("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),P0={number:"number",bigint:"bigint",object:"date"},ah=v("$ZodCheckLessThan",(e,t)=>{Me.init(e,t);let r=P0[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ch=v("$ZodCheckGreaterThan",(e,t)=>{Me.init(e,t);let r=P0[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),O0=v("$ZodCheckMultipleOf",(e,t)=>{Me.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):$m(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),R0=v("$ZodCheckNumberFormat",(e,t)=>{Me.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Rm[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=th)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),C0=v("$ZodCheckBigIntFormat",(e,t)=>{Me.init(e,t);let[r,n]=Cm[t.format];e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=o=>{let i=o.value;i<r&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>n&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),A0=v("$ZodCheckMaxSize",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!so(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;o.size<=t.maximum||n.issues.push({origin:Pa(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),N0=v("$ZodCheckMinSize",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!so(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;o.size>=t.minimum||n.issues.push({origin:Pa(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),D0=v("$ZodCheckSizeEquals",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!so(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{let o=n.value,i=o.size;if(i===t.size)return;let s=i>t.size;n.issues.push({origin:Pa(o),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),j0=v("$ZodCheckMaxLength",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!so(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=Oa(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),z0=v("$ZodCheckMinLength",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!so(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=Oa(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),M0=v("$ZodCheckLengthEquals",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!so(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Oa(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Fa=v("$ZodCheckStringFormat",(e,t)=>{var r,n;Me.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),L0=v("$ZodCheckRegex",(e,t)=>{Fa.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),U0=v("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ih),Fa.init(e,t)}),F0=v("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=sh),Fa.init(e,t)}),B0=v("$ZodCheckIncludes",(e,t)=>{Me.init(e,t);let r=_r(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Z0=v("$ZodCheckStartsWith",(e,t)=>{Me.init(e,t);let r=new RegExp(`^${_r(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),q0=v("$ZodCheckEndsWith",(e,t)=>{Me.init(e,t);let r=new RegExp(`.*${_r(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});function T0(e,t,r){e.issues.length&&t.issues.push(...nr(r,e.issues))}var H0=v("$ZodCheckProperty",(e,t)=>{Me.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>T0(o,r,t.property));T0(n,r,t.property)}}),V0=v("$ZodCheckMimeType",(e,t)=>{Me.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),G0=v("$ZodCheckOverwrite",(e,t)=>{Me.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Ou=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
293
293
  `).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
@@ -371,7 +371,7 @@ ${i}`;Z.healthError=s,Z.client=null,Z.pid=null,Z.lastStderr=n,console.error(`
371
371
  %O`,i)})}),e.on("open",r=>{r.on("error",n=>{mi(`Socket error in open event:
372
372
  %O`,n)})}),e.on("close",(r,n,o)=>{n.on("error",i=>{mi(`Socket error in close event:
373
373
  %O`,i)})}),e.on("econnreset",(r,n,o,i)=>{mi(`httpxy econnreset event:
374
- %O`,r)})};function OR(e){let t;if(/HPE_INVALID/.test(e))return t=502,t;if(/HPM_ERR_INVALID_MULTIPART_/.test(e))return t=400,t;switch(e){case"ECONNRESET":case"ENOTFOUND":case"ECONNREFUSED":case"ETIMEDOUT":t=504;break;default:t=500;break}return t}function Hb(e){return e?.replace(/[<>]/g,t=>encodeURIComponent(t))??""}function HH(e){return e&&typeof e.writeHead=="function"}function VH(e){return e&&typeof e.write=="function"&&!("writeHead"in e)}var RR=(e,t)=>{e.on("error",(r,n,o,i)=>{if(!n||!o)throw r;if(HH(o)){if(!o.headersSent){let a=OR(r.code);o.writeHead(a)}let s=n.headers&&n.headers.host;o.end(`Error occurred while trying to proxy: ${Hb(s)}${Hb(n.url)}`)}else VH(o)&&o.destroy()})};var DR=require("node:url");var GH={info:()=>{},warn:()=>{},error:()=>{}};function Up(e){return e.logger||GH}var CR=require("url");function AR({protocol:e,host:t,port:r,path:n}){let o=t?.includes(":")?`[${t}]`:t,i=`${e||"undefined:"}//${o||"[::]"}`,s=new CR.URL(i);return r&&(s.port=r),n&&(s.pathname=n),s}function NR(e){return Object.keys(e||{})?.[0]?.split(":")[1]}var jR=(e,t)=>{let r=Up(t);e.on("error",(n,o,i,s)=>{let c=`${o?.headers?.host}${o?.url}`,l=`${s?.href}`;r.error("[HPM] Error occurred while proxying request %s to %s [%s] (%s)",c,l,n.code||n,"https://nodejs.org/api/errors.html#errors_common_system_errors")}),e.on("proxyRes",(n,o,i)=>{let s=o.originalUrl??`${o.baseUrl||""}${o.url}`,a;try{let u=NR(n.req?.agent?.sockets),{protocol:d,host:p,path:f}=n.req;a=AR({protocol:d,host:p,port:u,path:f})}catch(u){console.error("[HPM] Unexpected error while creating target URL",u),a=new DR.URL(t.target),a.pathname=n.req.path}let c=a.toString(),l=`[HPM] ${o.method} ${s} -> ${c} [${n.statusCode}]`;r.info(l)}),e.on("open",n=>{r.info("[HPM] Client connected: %o",n.address())}),e.on("close",(n,o,i)=>{r.info("[HPM] Client disconnected: %o",o.address())})};function Ls(e){return e.name||"[anonymous Function]"}var WH=Be.extend("proxy-events-plugin"),zR=(e,t)=>{if(!t.on)return;let r;for(r in t.on)if(Object.prototype.hasOwnProperty.call(t.on,r)){let n=t.on[r];if(!n)continue;WH(`register event handler: "${r}" -> "${Ls(n)}"`),e.on(r,n)}};function MR(e){let t=e.on?.error?[]:[RR],r=e.ejectPlugins?[]:[PR,zR,jR,...t],n=e.plugins??[];return[...r,...n]}var lw=z(ZR(),1),rA=z(QC(),1);function nA(e="/",t,r){if(eA(e))return oA(e,t);if(tA(e))return iA(e,t);if(Array.isArray(e)){if(e.every(eA))return vG(e,t);if(e.every(tA))return _G(e,t);throw new fn('[HPM] Invalid pathFilter. Plain paths (e.g. "/api") can not be mixed with globs (e.g. "/api/**"). Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"].',"HPM_INVALID_PATH_FILTER_ARRAY_CONFIG")}if(typeof e=="function"){let n=uw(t);return!!e(n,r)}throw new fn('[HPM] Invalid pathFilter. Expecting something like: "/api" or ["/api", "/ajax"]',"HPM_INVALID_PATH_FILTER_CONFIG")}function oA(e,t){return uw(t)?.indexOf(e)===0}function iA(e,t){let r=uw(t),n=(0,rA.default)([r],e);return n&&n.length>0}function _G(e,t){return iA(e,t)}function vG(e,t){let r=!1;for(let n of e)if(oA(n,t)){r=!0;break}return r}function uw(e){return e&&new URL(e,"http://0.0.0.0").pathname}function eA(e){return typeof e=="string"&&!(0,lw.default)(e)}function tA(e){return(0,lw.default)(e)}function Bs(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}var sA=Be.extend("path-rewriter");function aA(e){let t;if(!bG(e))return;if(typeof e=="function")return e;return t=wG(e),r;function r(n){let o=n;for(let i of t)if(i.regex.test(n)){o=o.replace(i.regex,i.value),sA('rewriting path from "%s" to "%s"',n,o);break}return o}}function bG(e){if(typeof e=="function")return!0;if(Bs(e))return Object.keys(e).length!==0;if(e==null)return!1;throw new fn("[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function","HPM_INVALID_PATH_REWRITER_CONFIG")}function wG(e){let t=[];if(Bs(e))for(let[r,n]of Object.entries(e))t.push({regex:new RegExp(r),value:n}),sA('rewrite rule created: "%s" ~> "%s"',r,n);return t}var dw=Be.extend("router");async function cA(e,t,r){let n,o=r.router;return Bs(o)?n=kG(e,o):typeof o=="function"&&(n=await o(e,t,r)),n}function kG(e,t){let r,n=e.headers.host??"",o=e.url??"";for(let[i,s]of Object.entries(t))if(lA(i)){if(xG(i)){let[a,c]=SG(i);if(n===a&&o.startsWith(c)){r=s,dw('match: "%s" -> "%s"',i,r);break}}else if(o.startsWith(i)){r=s,dw('match: "%s" -> "%s"',i,r);break}}else if(i===n){r=s,dw('match: "%s" -> "%s"',n,r);break}return r}function lA(e){return e.indexOf("/")>-1}function xG(e){return lA(e)&&!e.startsWith("/")}function SG(e){let t=e.indexOf("/");return[e.slice(0,t),e.slice(t)]}var dA=Be.extend("ipv6");function pA(e){e.target=uA(e.target,"target"),e.forward=uA(e.forward,"forward")}function uA(e,t){let r=$G(e);if(r&&IG(r.hostname)){let n=TG(EG(r.hostname));dA('normalized IPv6 "%s" %s',t,e);let o=r.username||r.password?`${r.username}:${r.password}`:void 0;return{hostname:n,auth:o,pathname:r.pathname,port:r.port,protocol:r.protocol,search:r.search}}return e}function $G(e){if(typeof e=="string")return new URL(e);if(e instanceof URL)return e}function IG(e){return e.startsWith("[")&&e.endsWith("]")}function EG(e){return e.replace(/^\[|\]$/g,"")}function TG(e){return e==="::"?(dA("normalizing hostname unspecified IPv6 address (::) to loopback (::1)"),"::1"):e}var Gp=class{wsInternalSubscribedServers=new WeakSet;activeServers=new Set;proxyOptions;proxy;pathRewriter;logger;constructor(t){mR(t),this.proxyOptions=t,this.logger=Up(t),Be("create proxy server"),this.proxy=fR({}),this.registerPlugins(this.proxy,this.proxyOptions),this.pathRewriter=aA(this.proxyOptions.pathRewrite),this.middleware.upgrade=(r,n,o)=>{let i=this.#e(r);i&&!this.wsInternalSubscribedServers.has(i)&&this.handleUpgrade(r,n,o)}}#e(t){return t.socket?.server}middleware=(async(t,r,n)=>{if(this.shouldProxy(this.proxyOptions.pathFilter,t)){let i;try{if(i=await this.prepareProxyRequest(t,r),!i.target&&!i.forward)throw new Error("Must provide a proper URL as target")}catch(s){n?.(s);return}try{Be("proxy request to target: %O",i.target),await this.proxy.web(t,r,i)}catch(s){this.proxy.emit("error",s,t,r,i.target),n?.(s)}}else n?.();let o=this.#e(t);o&&!this.activeServers.has(o)&&(Be("registering server close listener"),this.activeServers.add(o),o.on("close",()=>{if(Be("server close signal received."),this.activeServers.delete(o),this.activeServers.size>0){Be(`proxy server not closed: ${this.activeServers.size} server(s) still active`);return}else Be("closing proxy server"),this.proxy.close(()=>Be("proxy server closed"))})),this.proxyOptions.ws===!0&&o&&this.catchUpgradeRequest(o)});registerPlugins(t,r){MR(r).forEach(o=>{Be(`register plugin: "${Ls(o)}"`),o(t,r)})}catchUpgradeRequest=t=>{this.wsInternalSubscribedServers.has(t)||(Be("subscribing to server upgrade event"),t.on("upgrade",this.handleUpgrade),this.wsInternalSubscribedServers.add(t))};handleUpgrade=async(t,r,n)=>{try{if(this.shouldProxy(this.proxyOptions.pathFilter,t)){let o=await this.prepareProxyRequest(t,void 0);await this.proxy.ws(t,r,o,n),Be("server upgrade event received. Proxying WebSocket")}}catch(o){this.proxy.emit("error",o,t,r)}};shouldProxy=(t,r)=>{try{return nA(t,r.url,r)}catch(n){return Be("Error: matchPathFilter() called with request url: ",`"${r.url}"`),this.logger.error(n),!1}};prepareProxyRequest=async(t,r)=>{let n=Object.assign({},this.proxyOptions);return await this.applyRouter(t,r,n),pA(n),await this.applyPathRewrite(t,r,this.pathRewriter,n),n};applyRouter=async(t,r,n)=>{let o;n.router&&(o=await cA(t,r,n),o&&(Be('router new target: "%s"',o),n.target=o))};applyPathRewrite=async(t,r,n,o)=>{if(t.url&&n){let i=await n(t.url,t,r,o);typeof i=="string"?(Be("pathRewrite new path: %s",i),t.url=i):Be("pathRewrite: no rewritten path found: %s",t.url)}}};function fA(e){let{middleware:t}=new Gp(e);return t}var To=z(require("node:zlib"),1);var Zs=Be.extend("response-interceptor");function pw(e){return async function(r,n,o){Zs("intercept proxy response");let i=r,s=[],a=0,c=mA(r.statusCode,n.method)?void 0:r.headers["content-encoding"],l=PG(r,c);l.on("data",u=>{let d=Buffer.isBuffer(u)?u:Buffer.from(u);s.push(d),a+=d.length}),l.on("end",async()=>{let u=Buffer.concat(s,a);if(s.length=0,a=0,OG(r,o),mA(r.statusCode,n.method)){o.end();return}Zs("call interceptor function: %s",Ls(e));let d=Buffer.from(await e(u,i,n,o));Zs("set content-length: %s",Buffer.byteLength(d)),o.removeHeader("trailer"),o.removeHeader("transfer-encoding"),o.setHeader("content-length",Buffer.byteLength(d)),Zs("write intercepted response"),o.write(d),o.end()}),l.on("error",u=>{s.length=0,a=0,o.end(`Error fetching proxied request: ${u.message}`)})}}function mA(e,t){return t?.toUpperCase()==="HEAD"||e!==void 0&&(e>=100&&e<200||e===204||e===304)}function PG(e,t){let r=e,n;switch(t){case"gzip":n=To.createGunzip();break;case"br":n=To.createBrotliDecompress();break;case"deflate":n=To.createInflate();break;case"zstd":n=To.createZstdDecompress();break;default:break}return n&&(Zs("decompress proxy response with 'content-encoding': %s",t),r.pipe(n),r=n),r}function OG(e,t){if(Zs("copy original response headers"),e.statusCode&&(t.statusCode=e.statusCode),e.statusMessage&&(t.statusMessage=e.statusMessage),t.setHeader){let r=Object.keys(e.headers);r=r.filter(n=>!["content-encoding","transfer-encoding","trailer"].includes(n)),r.forEach(n=>{let o=e.headers[n];n==="set-cookie"&&o&&(o=Array.isArray(o)?o:[o],o=o.map(i=>i.replace(/Domain=[^;]+?/i,""))),t.setHeader(n,o)})}else"headers"in t&&(t.headers=e.headers)}var fw='<script src="/__jerico/inspect.js"></script>',RG=16;function CG(){let e='"use strict";(()=>{var p,R,H;function P(n,t){if(H=new Date,n.nodeType!==Node.ELEMENT_NODE)throw new Error("Can\'t generate CSS selector for non-element node type.");if(n.tagName.toLowerCase()==="html")return"html";let e={root:document.body,idName:o=>!0,className:o=>!0,tagName:o=>!0,attr:(o,s)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};p={...e,...t},R=G(p.root,e);let i=v(n,"all",()=>v(n,"two",()=>v(n,"one",()=>v(n,"none"))));if(i){let o=_(I(i,n));return o.length>0&&(i=o[0]),L(i)}else throw new Error("Selector was not found.")}function G(n,t){return n.nodeType===Node.DOCUMENT_NODE?n:n===t.root?n.ownerDocument:n}function v(n,t,e){let i=null,o=[],s=n,a=0;for(;s;){let d=new Date().getTime()-H.getTime();if(p.timeoutMs!==void 0&&d>p.timeoutMs)throw new Error(`Timeout: Can\'t find a unique selector after ${d}ms`);let r=C(K(s))||C(...V(s))||C(...J(s))||C(Z(s))||[D()],h=Q(s);if(t=="all")h&&(r=r.concat(r.filter(T).map(l=>E(l,h))));else if(t=="two")r=r.slice(0,1),h&&(r=r.concat(r.filter(T).map(l=>E(l,h))));else if(t=="one"){let[l]=r=r.slice(0,1);h&&T(l)&&(r=[E(l,h)])}else t=="none"&&(r=[D()],h&&(r=[E(r[0],h)]));for(let l of r)l.level=a;if(o.push(r),o.length>=p.seedMinLength&&(i=N(o,e),i))break;s=s.parentElement,a++}return i||(i=N(o,e)),!i&&e?e():i}function N(n,t){let e=_(k(n));if(e.length>p.threshold)return t?t():null;for(let i of e)if($(i))return i;return null}function L(n){let t=n[0],e=t.name;for(let i=1;i<n.length;i++){let o=n[i].level||0;t.level===o-1?e=`${n[i].name} > ${e}`:e=`${n[i].name} ${e}`,t=n[i]}return e}function A(n){return n.map(t=>t.penalty).reduce((t,e)=>t+e,0)}function $(n){let t=L(n);switch(R.querySelectorAll(t).length){case 0:throw new Error(`Can\'t select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function K(n){let t=n.getAttribute("id");return t&&p.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function V(n){return Array.from(n.attributes).filter(e=>p.attr(e.name,e.value)).map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function J(n){return Array.from(n.classList).filter(p.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function Z(n){let t=n.tagName.toLowerCase();return p.tagName(t)?{name:t,penalty:2}:null}function D(){return{name:"*",penalty:3}}function Q(n){let t=n.parentNode;if(!t)return null;let e=t.firstChild;if(!e)return null;let i=0;for(;e&&(e.nodeType===Node.ELEMENT_NODE&&i++,e!==n);)e=e.nextSibling;return i}function E(n,t){return{name:n.name+`:nth-child(${t})`,penalty:n.penalty+1}}function T(n){return n.name!=="html"&&!n.name.startsWith("#")}function C(...n){let t=n.filter(tt);return t.length>0?t:null}function tt(n){return n!=null}function*k(n,t=[]){if(n.length>0)for(let e of n[0])yield*k(n.slice(1,n.length),t.concat(e));else yield t}function _(n){return[...n].sort((t,e)=>A(t)-A(e))}function*I(n,t,e={counter:0,visited:new Map}){if(n.length>2&&n.length>p.optimizedMinLength)for(let i=1;i<n.length-1;i++){if(e.counter>p.maxNumberOfTries)return;e.counter+=1;let o=[...n];o.splice(i,1);let s=L(o);if(e.visited.has(s))return;$(o)&&et(o,t)&&(yield o,e.visited.set(s,!0),yield*I(o,t,e))}}function et(n,t){return R.querySelector(L(n))===t}var nt=["display","position","width","height","margin","padding","color","backgroundColor","border","borderRadius","fontFamily","fontSize","fontWeight","lineHeight","textAlign","zIndex","boxShadow","flex","gridTemplate"],it=[/^id$/,/^class$/,/^role$/,/^href$/,/^src$/,/^alt$/,/^type$/,/^name$/,/^placeholder$/,/^aria-/,/^data-/],b=/token|secret|api[-_]?key|password|csrf|auth|bearer/i;function y(n){return b.test(n)}function f(n){return n&&n.replace(/\\[BRIDGE-(ORCH|INSPECT)\\][^\\n]*/gi,"")}function F(n){if(n.id&&b.test(n.id))return!0;let t=n.getAttribute&&n.getAttribute("class");if(t&&b.test(t))return!0;if(n.attributes){for(let e=0;e<n.attributes.length;e++)if(b.test(n.attributes[e].name))return!0}return!1}function U(n){let t=n;for(;t&&t!==document.body&&t!==document.documentElement;){if(F(t))return!0;t=t.parentElement}return!1}function W(n,t){let e=t||F(n);for(let i of Array.from(n.childNodes))i.nodeType===3?e&&(i.textContent||"").trim()&&(i.textContent="[redacted]"):i.nodeType===1&&W(i,e)}function z(n){return n&&(y(n)?"[redacted]":f(n))}function ot(n){try{let t=new URL(n,window.location.href);return t.protocol==="about:"?t.toString()==="about:blank"?"about:blank":"":t.protocol!=="http:"&&t.protocol!=="https:"&&t.protocol!=="file:"?"":(t.search="",t.hash="",t.toString())}catch{return""}}function rt(n){let t=window.getComputedStyle(n),e={};for(let i of nt){let o=i.replace(/[A-Z]/g,s=>"-"+s.toLowerCase());e[i]=t.getPropertyValue(o)||""}return e}function st(n){let t={};if(!n.attributes)return t;for(let e=0;e<n.attributes.length;e++){let i=n.attributes[e],o=i.name.toLowerCase();if(!it.some(d=>d.test(o)))continue;let a=i.value;y(a)||y(o)?t[o]="[redacted]":(o==="href"||o==="src")&&a?t[o]=ot(a):o==="class"?t[o]=f(a.slice(0,200)):t[o]=f(a.slice(0,500))}return t}function O(n){let t=n.cloneNode(!0);t.querySelectorAll("script").forEach(a=>a.remove()),[t,...Array.from(t.querySelectorAll("*"))].forEach(a=>{if(!a.attributes)return;let d=[],r=[];for(let h=0;h<a.attributes.length;h++){let l=a.attributes[h],c=l.name,u=l.value;if(c.toLowerCase().startsWith("on")){d.push(c);continue}if(b.test(c)||b.test(u)){r.push({name:c,value:"[redacted]"});continue}let m=a.tagName.toLowerCase();c.toLowerCase()==="value"&&(m==="input"||m==="textarea"||m==="select")&&r.push({name:c,value:"[redacted]"})}d.forEach(h=>a.removeAttribute(h)),r.forEach(({name:h,value:l})=>a.setAttribute(h,l))});let o=n.parentElement?U(n.parentElement):!1;W(t,o);let s=f(t.outerHTML||"");return s.length<=4096?s:s.slice(0,4096)+" (truncated)"}function at(n){if(!n.attributes)return null;for(let e=0;e<n.attributes.length;e++){let i=n.attributes[e].name;if(i==="data-inspector-path"||i==="data-v-inspector"||i.startsWith("data-inspector-")){let o=n.attributes[e].value;if(o)return o}}let t=n.parentElement;for(;t&&t!==document.body;){for(let e=0;e<t.attributes.length;e++){let i=t.attributes[e].name;if(i==="data-inspector-path"||i==="data-v-inspector"||i.startsWith("data-inspector-")){let o=t.attributes[e].value;if(o)return o}}t=t.parentElement}return null}var X=5,M=15,Y=256,j=1.5,B=class{host=null;shadow=null;overlay=null;highlightBox=null;hoverLabel=null;currentEl=null;nonce="";isArmed=!1;allowedOrigin="";mode="element";dragStart=null;regionScroll=null;dragMoved=!1;regionBox=null;regionDimLabel=null;annotationBar=null;hintChip=null;constructor(){this.handleMessage=this.handleMessage.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onClick=this.onClick.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onScrollResize=this.onScrollResize.bind(this),this.onPointerDown=this.onPointerDown.bind(this),this.onPointerUp=this.onPointerUp.bind(this)}init(){window.addEventListener("message",this.handleMessage)}destroy(){window.removeEventListener("message",this.handleMessage),this.teardown()}handleMessage(t){let e=t.data;!e||e.source!=="jerico-inspect"||t.source===window.parent&&(e.type==="arm"?(this.nonce=e.nonce,this.allowedOrigin=t.origin,this.mode=e.mode==="region"?"region":"element",this.arm()):(e.type==="cancel"||e.arm===!1)&&this.teardown())}arm(){this.isArmed&&this.teardown(),this.isArmed=!0,this.host=document.createElement("div"),this.host.id="__jerico-inspect-host",this.host.style.cssText="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2147483647;pointer-events:auto;cursor:crosshair;",document.documentElement.appendChild(this.host),this.shadow=this.host.attachShadow({mode:"closed"}),this.overlay=document.createElement("div"),this.overlay.style.cssText="position:fixed;top:0;left:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483647;",this.shadow.appendChild(this.overlay),this.highlightBox=document.createElement("div"),this.highlightBox.style.cssText=`\n position: fixed;\n border: 2px solid rgba(99, 102, 241, 0.85);\n border-radius: 4px;\n pointer-events: none;\n transition: all 0.05s ease-out;\n display: none;\n background: rgba(99, 102, 241, 0.05);\n box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2), 0 0 12px rgba(99, 102, 241, 0.4);\n `,this.overlay.appendChild(this.highlightBox),this.hoverLabel=document.createElement("div"),this.hoverLabel.style.cssText=`\n position: fixed;\n padding: 4px 8px;\n background: rgba(15, 17, 23, 0.95);\n color: #f3f4f6;\n font: 11px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;\n border: 1px solid rgba(255, 255, 255, 0.1);\n border-radius: 6px;\n pointer-events: none;\n white-space: nowrap;\n display: none;\n max-width: 320px;\n overflow: hidden;\n text-overflow: ellipsis;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);\n `,this.overlay.appendChild(this.hoverLabel),this.mode==="region"?(this.host.addEventListener("mousedown",this.onPointerDown,!0),this.host.addEventListener("mousemove",this.onPointerMove),this.host.addEventListener("mouseup",this.onPointerUp,!0)):(this.host.addEventListener("mousemove",this.onPointerMove),this.host.addEventListener("click",this.onClick,!0)),window.addEventListener("keydown",this.onKeyDown,!0),window.addEventListener("scroll",this.onScrollResize,!0),window.addEventListener("resize",this.onScrollResize,!0),this.showHintChip()}showHintChip(){if(!this.shadow)return;let t=document.createElement("div"),e=this.mode==="region"?"Drag a box to select an area, then describe the change \\xB7 Esc to cancel":"Click an element to inspect \\xB7 Esc to cancel";t.textContent=e,t.style.cssText=`\n position: fixed;\n top: 14px;\n left: 50%;\n transform: translateX(-50%);\n padding: 7px 14px;\n background: rgba(15, 17, 23, 0.95);\n color: #f3f4f6;\n font: 12px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;\n border: 1px solid rgba(99, 102, 241, 0.5);\n border-radius: 999px;\n box-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);\n z-index: 2147483647;\n pointer-events: none;\n opacity: 0;\n transition: opacity 0.2s ease;\n white-space: nowrap;\n max-width: 92vw;\n overflow: hidden;\n text-overflow: ellipsis;\n `,this.shadow.appendChild(t),this.hintChip=t,requestAnimationFrame(()=>{this.hintChip===t&&(t.style.opacity="1")}),setTimeout(()=>{this.hintChip===t&&this.hideHintChip()},4500)}hideHintChip(){let t=this.hintChip;t&&(this.hintChip=null,t.style.opacity="0",setTimeout(()=>{try{t.remove()}catch{}},220))}teardown(){if(this.isArmed){if(this.isArmed=!1,this.host){this.host.removeEventListener("mousemove",this.onPointerMove),this.host.removeEventListener("click",this.onClick,!0),this.host.removeEventListener("mousedown",this.onPointerDown,!0),this.host.removeEventListener("mouseup",this.onPointerUp,!0);try{this.host.remove()}catch{}this.host=null}window.removeEventListener("keydown",this.onKeyDown,!0),window.removeEventListener("scroll",this.onScrollResize,!0),window.removeEventListener("resize",this.onScrollResize,!0),this.shadow=null,this.overlay=null,this.highlightBox=null,this.hoverLabel=null,this.regionBox=null,this.regionDimLabel=null,this.hintChip=null,this.annotationBar=null,this.currentEl=null,this.dragStart=null,this.dragMoved=!1}}onPointerMove(t){if(this.mode==="region"){this.dragStart&&this.drawRegionRect(this.dragStart.x,this.dragStart.y,t.clientX,t.clientY);return}if(!this.host||!this.highlightBox||!this.hoverLabel)return;this.host.style.pointerEvents="none";let e=document.elementFromPoint(t.clientX,t.clientY);this.host.style.pointerEvents="auto",e&&e!==document.documentElement&&e!==document.body?(this.hideHintChip(),this.currentEl=e,this.updateHighlight()):(this.currentEl=null,this.highlightBox.style.display="none",this.hoverLabel.style.display="none")}updateHighlight(){if(!this.currentEl||!this.highlightBox||!this.hoverLabel)return;let t=this.currentEl.getBoundingClientRect();this.highlightBox.style.left=`${t.left}px`,this.highlightBox.style.top=`${t.top}px`,this.highlightBox.style.width=`${t.width}px`,this.highlightBox.style.height=`${t.height}px`,this.highlightBox.style.display="block";let e=this.currentEl.tagName.toLowerCase(),i=Math.round(t.width),o=Math.round(t.height),s=(this.currentEl.innerText||this.currentEl.textContent||"").trim().slice(0,30);s.length>30&&(s=s.slice(0,27)+"...");let a=[e];s&&a.push(`"${s}"`),a.push(`${i}x${o}`),this.hoverLabel.textContent=a.join(" "),this.hoverLabel.style.display="block";let d=t.bottom+6;d+28>window.innerHeight&&(d=t.top-28),this.hoverLabel.style.left=`${Math.max(4,t.left)}px`,this.hoverLabel.style.top=`${d}px`}onScrollResize(){this.currentEl&&this.updateHighlight()}onKeyDown(t){t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),this.teardown())}onPointerDown(t){this.mode==="region"&&(t.preventDefault(),t.stopPropagation(),this.hideHintChip(),this.dragStart={x:t.clientX,y:t.clientY},this.dragMoved=!1,this.drawRegionRect(t.clientX,t.clientY,t.clientX,t.clientY))}onPointerUp(t){if(this.mode!=="region"||!this.dragStart)return;t.preventDefault(),t.stopPropagation();let e=this.dragStart;this.dragStart=null;let i=Math.abs(t.clientX-e.x),o=Math.abs(t.clientY-e.y);if(i<X||o<X){this.regionBox&&(this.regionBox.style.display="none");let a=document.elementFromPoint(t.clientX,t.clientY);a&&a!==document.documentElement&&a!==document.body?this.handleElementClick(a):this.teardown();return}let s=this.normalizeRect(e.x,e.y,t.clientX,t.clientY);this.regionScroll={x:window.scrollX,y:window.scrollY},this.showAnnotationBar(s)}normalizeRect(t,e,i,o){let s=Math.min(t,i),a=Math.min(e,o);return{x:s,y:a,width:Math.abs(i-t),height:Math.abs(o-e)}}drawRegionRect(t,e,i,o){if(!this.overlay)return;let s=this.normalizeRect(t,e,i,o);this.regionBox||(this.regionBox=document.createElement("div"),this.regionBox.style.cssText=`\n position: fixed;\n border: 2px solid rgba(99, 102, 241, 0.9);\n border-radius: 4px;\n pointer-events: none;\n background: rgba(99, 102, 241, 0.1);\n box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.25), 0 0 16px rgba(99, 102, 241, 0.45);\n z-index: 2147483647;\n `,this.regionDimLabel=document.createElement("div"),this.regionDimLabel.style.cssText=`\n position: absolute;\n right: 0;\n bottom: -22px;\n padding: 2px 6px;\n background: rgba(99, 102, 241, 0.95);\n color: #fff;\n font: 11px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;\n border-radius: 4px;\n white-space: nowrap;\n box-shadow: 0 2px 6px rgba(0,0,0,0.35);\n `,this.regionBox.appendChild(this.regionDimLabel),this.overlay.appendChild(this.regionBox)),this.regionBox.style.left=`${s.x}px`,this.regionBox.style.top=`${s.y}px`,this.regionBox.style.width=`${s.width}px`,this.regionBox.style.height=`${s.height}px`,this.regionBox.style.display="block",this.regionDimLabel&&(this.regionDimLabel.textContent=`${Math.round(s.width)} \\xD7 ${Math.round(s.height)}`)}showAnnotationBar(t){if(!this.shadow)return;this.annotationBar||(this.annotationBar=document.createElement("div"),this.annotationBar.style.cssText=`\n position: fixed;\n display: flex;\n flex-direction: column;\n gap: 6px;\n width: 280px;\n max-width: 90vw;\n padding: 10px;\n background: rgba(15, 17, 23, 0.97);\n border: 1px solid rgba(255, 255, 255, 0.12);\n border-radius: 10px;\n box-shadow: 0 10px 30px rgba(0, 0, 0, 0.6);\n z-index: 2147483647;\n font: 12px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;\n color: #f3f4f6;\n `,this.shadow.appendChild(this.annotationBar));let e=this.annotationBar;e.innerHTML="";let i=this.selectRegionElements(t),o=Math.min(i.length,M),s=document.createElement("div");s.textContent="Describe what to do with this region:",s.style.cssText="font-weight: 600; color: rgba(243,244,246,0.9);",e.appendChild(s);let a=document.createElement("div");a.textContent=i.length===0?"No elements in the selection \\u2014 try a larger box":`${o} element${o===1?"":"s"} selected${i.length>M?` (capped at ${M})`:""}`,a.style.cssText=`font-size: 11px; color: ${i.length===0?"rgba(251,191,36,0.9)":"rgba(129,140,248,0.95)"};`,e.appendChild(a);let d=document.createElement("textarea");d.placeholder="e.g. make this a card",d.style.cssText=`\n width: 100%;\n min-height: 60px;\n resize: vertical;\n box-sizing: border-box;\n padding: 6px 8px;\n background: rgba(255,255,255,0.06);\n color: #f3f4f6;\n border: 1px solid rgba(255,255,255,0.14);\n border-radius: 6px;\n outline: none;\n font: inherit;\n `,d.addEventListener("keydown",g=>{(g.metaKey||g.ctrlKey)&&g.key==="Enter"&&(g.preventDefault(),g.stopPropagation(),this.sendRegion(t,d.value))}),e.appendChild(d);let r=document.createElement("div");r.style.cssText="display: flex; gap: 6px; align-items: center; justify-content: flex-end;",e.appendChild(r);let h=document.createElement("span");h.textContent=`${/Mac|iPhone|iPad/.test(navigator.platform)?"\\u2318":"Ctrl"}\\u21B5 Send \\xB7 Esc Cancel`,h.style.cssText="margin-right: auto; font-size: 10px; color: rgba(243,244,246,0.4);",r.appendChild(h);let l=document.createElement("button");l.textContent="Cancel",l.style.cssText=`\n padding: 5px 12px; border-radius: 6px; cursor: pointer;\n background: rgba(255,255,255,0.08); color: #f3f4f6;\n border: 1px solid rgba(255,255,255,0.12);\n `,l.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.teardown()});let c=document.createElement("button");c.textContent="Send",c.style.cssText=`\n padding: 5px 12px; border-radius: 6px; cursor: pointer;\n background: rgba(99, 102, 241, 0.9); color: #fff;\n border: 1px solid rgba(99, 102, 241, 1); font-weight: 600;\n `,c.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation();let q=d.value;this.sendRegion(t,q)}),r.appendChild(l),r.appendChild(c);let u=280,m=200,x=t.x+t.width+8,w=t.y;x+u>window.innerWidth&&(x=t.x-u-8),x<4&&(x=4),w+m>window.innerHeight&&(w=Math.max(4,window.innerHeight-m-4)),e.style.left=`${x}px`,e.style.top=`${w}px`,e.style.display="flex",setTimeout(()=>d.focus(),0)}async sendRegion(t,e){if(this.host){this.host.style.pointerEvents="none";try{let i=window.scrollX-(this.regionScroll?.x??window.scrollX),o=window.scrollY-(this.regionScroll?.y??window.scrollY),s={x:t.x+i,y:t.y+o,width:t.width,height:t.height},a=await this.extractRegionPayload(s,e);window.parent.postMessage({source:"jerico-inspect",type:"result",nonce:this.nonce,payload:a},this.allowedOrigin)}catch(i){console.error("[JERICO-INSPECT] Failed to extract region:",i)}finally{this.teardown()}}}selectRegionElements(t){let e=t.x+t.width,i=t.y+t.height,o=Array.from(document.querySelectorAll("*")),s=[];for(let r of o){if(r.id==="__jerico-inspect-host")continue;let h=r.tagName.toLowerCase();if(h==="html"||h==="body")continue;let l=r.getBoundingClientRect();if(l.width<=0||l.height<=0)continue;let c=window.getComputedStyle(r);if(c.visibility==="hidden"||c.visibility==="collapse"||c.opacity==="0")continue;let u=r.parentElement,m=!1;for(;u&&u.tagName.toLowerCase()!=="body";){let w=window.getComputedStyle(u);if(w.visibility==="hidden"||w.visibility==="collapse"||w.opacity==="0"){m=!0;break}u=u.parentElement}m||!(l.left<e&&l.right>t.x&&l.top<i&&l.bottom>t.y)||s.push({el:r,r:l})}let a=s.filter(({r})=>{let h=r.width>t.width*j,l=r.height>t.height*j;return!(h&&l)}),d=new Set(a.map(r=>r.el));return a.filter(({el:r})=>{let h=Array.from(r.children).filter(c=>d.has(c)),l="";for(let c of Array.from(r.childNodes))c.nodeType===3&&(l+=c.textContent||"");return l=l.trim(),!(h.length===1&&l.length===0)})}async extractRegionPayload(t,e){let i=this.sanitizeAnnotation(e),a=this.selectRegionElements(t).slice(0,M).map(({el:r,r:h})=>{let l="";try{l=P(r)}catch{l=r.tagName.toLowerCase()+(r.id?`#${r.id}`:"")}l=z(l);let c=r.getAttribute("role"),u=O(r);return u.length>Y&&(u=u.slice(0,Y)+" (truncated)"),{selector:l,tagName:r.tagName.toLowerCase(),role:c&&c.length<=64?f(c):null,htmlSnippet:u,rectViewport:{x:Math.round(h.left),y:Math.round(h.top),width:Math.round(h.width),height:Math.round(h.height)}}}),d={x:t.x+window.scrollX,y:t.y+window.scrollY,width:t.width,height:t.height};return{kind:"region",rectViewport:{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)},rectPage:d,annotation:i,elements:a,devicePixelRatio:window.devicePixelRatio||1}}sanitizeAnnotation(t){return(t||"").split("\\0").join("").replace(/JERICO_DONE_[A-Z0-9_-]*/gi,"").replace(/\\[BRIDGE-(ORCH|INSPECT)\\][^\\n]*/gi,"").slice(0,2e3)}async onClick(t){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let e=this.currentEl;if(!e){this.teardown();return}await this.handleElementClick(e)}async handleElementClick(t){this.host&&(this.host.style.pointerEvents="none",this.host.style.cursor="default");try{let e=await this.extractPayload(t);window.parent.postMessage({source:"jerico-inspect",type:"result",nonce:this.nonce,payload:e},this.allowedOrigin)}catch(e){console.error("[JERICO-INSPECT] Failed to extract element:",e)}finally{this.teardown()}}async extractPayload(t){let e="";try{e=P(t)}catch{e=t.tagName.toLowerCase(),t.id&&(e+=`#${t.id}`)}e=z(e);let i=rt(t),o=st(t),s=O(t),a=(t.innerText||t.textContent||"").trim().slice(0,200),d=U(t)?"[redacted]":f(a),r=t.getBoundingClientRect(),h={x:r.left,y:r.top,width:r.width,height:r.height},l={x:r.left+window.scrollX,y:r.top+window.scrollY,width:r.width,height:r.height},c=at(t),u=c&&f(c);return{selector:e,tagName:t.tagName.toLowerCase(),id:t.id?y(t.id)?"[redacted]":f(t.id):"",classes:Array.from(t.classList).filter(m=>!y(m)).map(f),htmlSnippet:s,computedStyles:i,attributes:o,textSnippet:d,rectViewport:h,rectPage:l,devicePixelRatio:window.devicePixelRatio||1,sourceFile:u}}},S=window;S.__jericoInspect&&S.__jericoInspect.destroy();S.__jericoInspect=new B;S.__jericoInspect.init();})();\n';if(e&&e.length>0)return e;let t=typeof __dirname<"u"?__dirname:qs.default.dirname(process.execPath),r=[qs.default.resolve(t,"..","..","inspect-runtime","dist","jerico-inspect.js"),qs.default.resolve(t,"..","inspect-runtime","dist","jerico-inspect.js"),qs.default.resolve(t,"inspect-runtime","dist","jerico-inspect.js"),qs.default.resolve(process.cwd(),"packages","inspect-runtime","dist","jerico-inspect.js")];for(let n of r)try{if(hw.default.existsSync(n))return hw.default.readFileSync(n,"utf-8")}catch{}return""}var mw=null;function hA(){return mw===null&&(mw=CG()),mw}var Hs=new Map;function gA(e){let t=e.toLowerCase();return t==="localhost"||t==="[::1]"||t==="::1"||t==="0.0.0.0"||t==="127.0.0.1"||t.startsWith("127.")?"127.0.0.1":t}function yA(e,t){let r;try{r=new URL(e)}catch{return!1}let n=`${gA(r.hostname)}:${r.port||(r.protocol==="https:"?443:80)}`;return t.some(o=>{try{let i=new URL(o);return`${gA(i.hostname)}:${i.port||(i.protocol==="https:"?443:80)}`===n}catch{return!1}})}function AG(e){let[t,...r]=e.split(";").map(o=>o.trim()),n=[t];for(let o of r){let i=o.toLowerCase();if(i!=="secure"){if(i.startsWith("domain=")){n.push("Domain=127.0.0.1");continue}n.push(o)}}return n.join("; ")}function NG(e){let t=e.replace(/<meta\b[^>]*\bhttp-equiv\s*=\s*["']?content-security-policy["']?[^>]*>/gi,"");return t=t.replace(/<base\b[^>]*\bhref\s*=\s*["'][^"']*["'][^>]*>/gi,""),t.includes("</head>")?t.replace("</head>",`${fw}
374
+ %O`,r)})};function OR(e){let t;if(/HPE_INVALID/.test(e))return t=502,t;if(/HPM_ERR_INVALID_MULTIPART_/.test(e))return t=400,t;switch(e){case"ECONNRESET":case"ENOTFOUND":case"ECONNREFUSED":case"ETIMEDOUT":t=504;break;default:t=500;break}return t}function Hb(e){return e?.replace(/[<>]/g,t=>encodeURIComponent(t))??""}function HH(e){return e&&typeof e.writeHead=="function"}function VH(e){return e&&typeof e.write=="function"&&!("writeHead"in e)}var RR=(e,t)=>{e.on("error",(r,n,o,i)=>{if(!n||!o)throw r;if(HH(o)){if(!o.headersSent){let a=OR(r.code);o.writeHead(a)}let s=n.headers&&n.headers.host;o.end(`Error occurred while trying to proxy: ${Hb(s)}${Hb(n.url)}`)}else VH(o)&&o.destroy()})};var DR=require("node:url");var GH={info:()=>{},warn:()=>{},error:()=>{}};function Up(e){return e.logger||GH}var CR=require("url");function AR({protocol:e,host:t,port:r,path:n}){let o=t?.includes(":")?`[${t}]`:t,i=`${e||"undefined:"}//${o||"[::]"}`,s=new CR.URL(i);return r&&(s.port=r),n&&(s.pathname=n),s}function NR(e){return Object.keys(e||{})?.[0]?.split(":")[1]}var jR=(e,t)=>{let r=Up(t);e.on("error",(n,o,i,s)=>{let c=`${o?.headers?.host}${o?.url}`,l=`${s?.href}`;r.error("[HPM] Error occurred while proxying request %s to %s [%s] (%s)",c,l,n.code||n,"https://nodejs.org/api/errors.html#errors_common_system_errors")}),e.on("proxyRes",(n,o,i)=>{let s=o.originalUrl??`${o.baseUrl||""}${o.url}`,a;try{let u=NR(n.req?.agent?.sockets),{protocol:d,host:p,path:f}=n.req;a=AR({protocol:d,host:p,port:u,path:f})}catch(u){console.error("[HPM] Unexpected error while creating target URL",u),a=new DR.URL(t.target),a.pathname=n.req.path}let c=a.toString(),l=`[HPM] ${o.method} ${s} -> ${c} [${n.statusCode}]`;r.info(l)}),e.on("open",n=>{r.info("[HPM] Client connected: %o",n.address())}),e.on("close",(n,o,i)=>{r.info("[HPM] Client disconnected: %o",o.address())})};function Ls(e){return e.name||"[anonymous Function]"}var WH=Be.extend("proxy-events-plugin"),zR=(e,t)=>{if(!t.on)return;let r;for(r in t.on)if(Object.prototype.hasOwnProperty.call(t.on,r)){let n=t.on[r];if(!n)continue;WH(`register event handler: "${r}" -> "${Ls(n)}"`),e.on(r,n)}};function MR(e){let t=e.on?.error?[]:[RR],r=e.ejectPlugins?[]:[PR,zR,jR,...t],n=e.plugins??[];return[...r,...n]}var lw=z(ZR(),1),rA=z(QC(),1);function nA(e="/",t,r){if(eA(e))return oA(e,t);if(tA(e))return iA(e,t);if(Array.isArray(e)){if(e.every(eA))return vG(e,t);if(e.every(tA))return _G(e,t);throw new fn('[HPM] Invalid pathFilter. Plain paths (e.g. "/api") can not be mixed with globs (e.g. "/api/**"). Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"].',"HPM_INVALID_PATH_FILTER_ARRAY_CONFIG")}if(typeof e=="function"){let n=uw(t);return!!e(n,r)}throw new fn('[HPM] Invalid pathFilter. Expecting something like: "/api" or ["/api", "/ajax"]',"HPM_INVALID_PATH_FILTER_CONFIG")}function oA(e,t){return uw(t)?.indexOf(e)===0}function iA(e,t){let r=uw(t),n=(0,rA.default)([r],e);return n&&n.length>0}function _G(e,t){return iA(e,t)}function vG(e,t){let r=!1;for(let n of e)if(oA(n,t)){r=!0;break}return r}function uw(e){return e&&new URL(e,"http://0.0.0.0").pathname}function eA(e){return typeof e=="string"&&!(0,lw.default)(e)}function tA(e){return(0,lw.default)(e)}function Bs(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}var sA=Be.extend("path-rewriter");function aA(e){let t;if(!bG(e))return;if(typeof e=="function")return e;return t=wG(e),r;function r(n){let o=n;for(let i of t)if(i.regex.test(n)){o=o.replace(i.regex,i.value),sA('rewriting path from "%s" to "%s"',n,o);break}return o}}function bG(e){if(typeof e=="function")return!0;if(Bs(e))return Object.keys(e).length!==0;if(e==null)return!1;throw new fn("[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function","HPM_INVALID_PATH_REWRITER_CONFIG")}function wG(e){let t=[];if(Bs(e))for(let[r,n]of Object.entries(e))t.push({regex:new RegExp(r),value:n}),sA('rewrite rule created: "%s" ~> "%s"',r,n);return t}var dw=Be.extend("router");async function cA(e,t,r){let n,o=r.router;return Bs(o)?n=kG(e,o):typeof o=="function"&&(n=await o(e,t,r)),n}function kG(e,t){let r,n=e.headers.host??"",o=e.url??"";for(let[i,s]of Object.entries(t))if(lA(i)){if(xG(i)){let[a,c]=SG(i);if(n===a&&o.startsWith(c)){r=s,dw('match: "%s" -> "%s"',i,r);break}}else if(o.startsWith(i)){r=s,dw('match: "%s" -> "%s"',i,r);break}}else if(i===n){r=s,dw('match: "%s" -> "%s"',n,r);break}return r}function lA(e){return e.indexOf("/")>-1}function xG(e){return lA(e)&&!e.startsWith("/")}function SG(e){let t=e.indexOf("/");return[e.slice(0,t),e.slice(t)]}var dA=Be.extend("ipv6");function pA(e){e.target=uA(e.target,"target"),e.forward=uA(e.forward,"forward")}function uA(e,t){let r=$G(e);if(r&&IG(r.hostname)){let n=TG(EG(r.hostname));dA('normalized IPv6 "%s" %s',t,e);let o=r.username||r.password?`${r.username}:${r.password}`:void 0;return{hostname:n,auth:o,pathname:r.pathname,port:r.port,protocol:r.protocol,search:r.search}}return e}function $G(e){if(typeof e=="string")return new URL(e);if(e instanceof URL)return e}function IG(e){return e.startsWith("[")&&e.endsWith("]")}function EG(e){return e.replace(/^\[|\]$/g,"")}function TG(e){return e==="::"?(dA("normalizing hostname unspecified IPv6 address (::) to loopback (::1)"),"::1"):e}var Gp=class{wsInternalSubscribedServers=new WeakSet;activeServers=new Set;proxyOptions;proxy;pathRewriter;logger;constructor(t){mR(t),this.proxyOptions=t,this.logger=Up(t),Be("create proxy server"),this.proxy=fR({}),this.registerPlugins(this.proxy,this.proxyOptions),this.pathRewriter=aA(this.proxyOptions.pathRewrite),this.middleware.upgrade=(r,n,o)=>{let i=this.#e(r);i&&!this.wsInternalSubscribedServers.has(i)&&this.handleUpgrade(r,n,o)}}#e(t){return t.socket?.server}middleware=(async(t,r,n)=>{if(this.shouldProxy(this.proxyOptions.pathFilter,t)){let i;try{if(i=await this.prepareProxyRequest(t,r),!i.target&&!i.forward)throw new Error("Must provide a proper URL as target")}catch(s){n?.(s);return}try{Be("proxy request to target: %O",i.target),await this.proxy.web(t,r,i)}catch(s){this.proxy.emit("error",s,t,r,i.target),n?.(s)}}else n?.();let o=this.#e(t);o&&!this.activeServers.has(o)&&(Be("registering server close listener"),this.activeServers.add(o),o.on("close",()=>{if(Be("server close signal received."),this.activeServers.delete(o),this.activeServers.size>0){Be(`proxy server not closed: ${this.activeServers.size} server(s) still active`);return}else Be("closing proxy server"),this.proxy.close(()=>Be("proxy server closed"))})),this.proxyOptions.ws===!0&&o&&this.catchUpgradeRequest(o)});registerPlugins(t,r){MR(r).forEach(o=>{Be(`register plugin: "${Ls(o)}"`),o(t,r)})}catchUpgradeRequest=t=>{this.wsInternalSubscribedServers.has(t)||(Be("subscribing to server upgrade event"),t.on("upgrade",this.handleUpgrade),this.wsInternalSubscribedServers.add(t))};handleUpgrade=async(t,r,n)=>{try{if(this.shouldProxy(this.proxyOptions.pathFilter,t)){let o=await this.prepareProxyRequest(t,void 0);await this.proxy.ws(t,r,o,n),Be("server upgrade event received. Proxying WebSocket")}}catch(o){this.proxy.emit("error",o,t,r)}};shouldProxy=(t,r)=>{try{return nA(t,r.url,r)}catch(n){return Be("Error: matchPathFilter() called with request url: ",`"${r.url}"`),this.logger.error(n),!1}};prepareProxyRequest=async(t,r)=>{let n=Object.assign({},this.proxyOptions);return await this.applyRouter(t,r,n),pA(n),await this.applyPathRewrite(t,r,this.pathRewriter,n),n};applyRouter=async(t,r,n)=>{let o;n.router&&(o=await cA(t,r,n),o&&(Be('router new target: "%s"',o),n.target=o))};applyPathRewrite=async(t,r,n,o)=>{if(t.url&&n){let i=await n(t.url,t,r,o);typeof i=="string"?(Be("pathRewrite new path: %s",i),t.url=i):Be("pathRewrite: no rewritten path found: %s",t.url)}}};function fA(e){let{middleware:t}=new Gp(e);return t}var To=z(require("node:zlib"),1);var Zs=Be.extend("response-interceptor");function pw(e){return async function(r,n,o){Zs("intercept proxy response");let i=r,s=[],a=0,c=mA(r.statusCode,n.method)?void 0:r.headers["content-encoding"],l=PG(r,c);l.on("data",u=>{let d=Buffer.isBuffer(u)?u:Buffer.from(u);s.push(d),a+=d.length}),l.on("end",async()=>{let u=Buffer.concat(s,a);if(s.length=0,a=0,OG(r,o),mA(r.statusCode,n.method)){o.end();return}Zs("call interceptor function: %s",Ls(e));let d=Buffer.from(await e(u,i,n,o));Zs("set content-length: %s",Buffer.byteLength(d)),o.removeHeader("trailer"),o.removeHeader("transfer-encoding"),o.setHeader("content-length",Buffer.byteLength(d)),Zs("write intercepted response"),o.write(d),o.end()}),l.on("error",u=>{s.length=0,a=0,o.end(`Error fetching proxied request: ${u.message}`)})}}function mA(e,t){return t?.toUpperCase()==="HEAD"||e!==void 0&&(e>=100&&e<200||e===204||e===304)}function PG(e,t){let r=e,n;switch(t){case"gzip":n=To.createGunzip();break;case"br":n=To.createBrotliDecompress();break;case"deflate":n=To.createInflate();break;case"zstd":n=To.createZstdDecompress();break;default:break}return n&&(Zs("decompress proxy response with 'content-encoding': %s",t),r.pipe(n),r=n),r}function OG(e,t){if(Zs("copy original response headers"),e.statusCode&&(t.statusCode=e.statusCode),e.statusMessage&&(t.statusMessage=e.statusMessage),t.setHeader){let r=Object.keys(e.headers);r=r.filter(n=>!["content-encoding","transfer-encoding","trailer"].includes(n)),r.forEach(n=>{let o=e.headers[n];n==="set-cookie"&&o&&(o=Array.isArray(o)?o:[o],o=o.map(i=>i.replace(/Domain=[^;]+?/i,""))),t.setHeader(n,o)})}else"headers"in t&&(t.headers=e.headers)}var fw='<script src="/__jerico/inspect.js"></script>',RG=16;function CG(){let t=typeof __dirname<"u"?__dirname:qs.default.dirname(process.execPath),r=[qs.default.resolve(t,"..","..","inspect-runtime","dist","jerico-inspect.js"),qs.default.resolve(t,"..","inspect-runtime","dist","jerico-inspect.js"),qs.default.resolve(t,"inspect-runtime","dist","jerico-inspect.js"),qs.default.resolve(process.cwd(),"packages","inspect-runtime","dist","jerico-inspect.js")];for(let n of r)try{if(hw.default.existsSync(n))return hw.default.readFileSync(n,"utf-8")}catch{}return""}var mw=null;function hA(){return mw===null&&(mw=CG()),mw}var Hs=new Map;function gA(e){let t=e.toLowerCase();return t==="localhost"||t==="[::1]"||t==="::1"||t==="0.0.0.0"||t==="127.0.0.1"||t.startsWith("127.")?"127.0.0.1":t}function yA(e,t){let r;try{r=new URL(e)}catch{return!1}let n=`${gA(r.hostname)}:${r.port||(r.protocol==="https:"?443:80)}`;return t.some(o=>{try{let i=new URL(o);return`${gA(i.hostname)}:${i.port||(i.protocol==="https:"?443:80)}`===n}catch{return!1}})}function AG(e){let[t,...r]=e.split(";").map(o=>o.trim()),n=[t];for(let o of r){let i=o.toLowerCase();if(i!=="secure"){if(i.startsWith("domain=")){n.push("Domain=127.0.0.1");continue}n.push(o)}}return n.join("; ")}function NG(e){let t=e.replace(/<meta\b[^>]*\bhttp-equiv\s*=\s*["']?content-security-policy["']?[^>]*>/gi,"");return t=t.replace(/<base\b[^>]*\bhref\s*=\s*["'][^"']*["'][^>]*>/gi,""),t.includes("</head>")?t.replace("</head>",`${fw}
375
375
  </head>`):t.includes("</body>")?t.replace("</body>",`${fw}
376
376
  </body>`):fw+t}function DG(e,t,r){if(!String(t.headers["content-type"]??"").toLowerCase().includes("text/html")||(r.url?r.url.split("?")[0]:"")==="/__jerico/inspect.js")return e;try{let i=e.toString("utf-8");return Buffer.from(NG(i),"utf-8")}catch{return e}}function vA(e,t,r=[]){if(Hs.has(e)&&Wp(e),Hs.size>=RG)return Promise.resolve({ok:!1,error:"concurrent-proxy-limit-reached"});if(yA(t,r))return Promise.resolve({ok:!1,error:"refused-self-origin"});let n;try{n=new URL(t)}catch{return Promise.resolve({ok:!1,error:"invalid-dev-url"})}let i=`${n.hostname==="localhost"?"127.0.0.1":n.hostname}:${n.port||(n.protocol==="https:"?443:80)}`,s=`${n.protocol}//${i}`,a=u=>yA(u,r),c=fA({target:s,changeOrigin:!0,ws:!0,secure:!1,selfHandleResponse:!0,on:{proxyReq:u=>{u.setHeader("accept-encoding","identity")},proxyRes:pw((u,d,p,f)=>{let m=f;if((p.url?p.url.split("?")[0]:"")==="/__jerico/inspect.js"){let E=Buffer.from(hA(),"utf-8");return E.length===0?(m.statusCode=500,m.setHeader("content-type","text/plain"),Promise.resolve(Buffer.from("inspect runtime unavailable"))):(m.statusCode=200,m.setHeader("content-type","application/javascript"),Promise.resolve(E))}let g=d.statusCode??0;if(g>=300&&g<400){let E=d.headers.location;if(typeof E=="string"&&a(E))return m.statusCode=403,m.removeHeader("location"),m.setHeader("content-type","text/plain"),Promise.resolve(Buffer.from("preview proxy refused redirect to a blocked origin"))}let b=String(d.headers["content-type"]??"").toLowerCase().includes("text/html");delete d.headers["content-security-policy"],delete d.headers["content-security-policy-report-only"],delete d.headers["x-frame-options"];let x=d.headers["set-cookie"];if(Array.isArray(x)&&x.length>0&&(d.headers["set-cookie"]=x.map(AG)),!b)return Promise.resolve(u);let P=DG(u,d,p);return delete d.headers["content-length"],delete d.headers["content-encoding"],Promise.resolve(P)})}}),l=_A.default.createServer((u,d)=>{if((u.url?u.url.split("?")[0]:"")==="/__jerico/inspect.js")try{let f=Buffer.from(hA(),"utf-8");if(f.length===0)throw new Error("inspect runtime empty");d.setHeader("content-type","application/javascript"),d.setHeader("content-length",String(f.length)),d.end(f);return}catch(f){d.statusCode=500,d.end("inspect runtime missing"),console.error("[proxy] inspect.js serve failed",{paneId:e,error:String(f)});return}c(u,d,f=>{if(f){d.statusCode=502,d.end("preview proxy upstream unavailable"),console.warn("[proxy] upstream error",{paneId:e,error:String(f)});return}d.statusCode=404,d.end()})});return l.on("upgrade",(u,d,p)=>{c.upgrade(u,d,p)}),new Promise(u=>{l.on("error",d=>{console.error("[proxy] server error",{paneId:e,error:String(d)}),u({ok:!1,error:"proxy-server-error"})}),l.listen(0,"127.0.0.1",()=>{let d=l.address();if(!d||typeof d=="string"){l.close(),u({ok:!1,error:"no-ephemeral-port"});return}let p=d.port;Hs.set(e,{server:l,port:p,devUrl:t,targetHost:i,middleware:c}),console.log("[proxy] started",{paneId:e,port:p,target:s}),u({ok:!0,proxyUrl:`http://127.0.0.1:${p}/`})})})}function Wp(e){let t=Hs.get(e);if(!t)return!1;Hs.delete(e);try{t.server.close(()=>{}),t.server.unref()}catch(r){console.warn("[proxy] close error",{paneId:e,error:String(r)})}return console.log("[proxy] stopped",{paneId:e,port:t.port}),!0}function bA(){let e=[...Hs.keys()];for(let t of e)Wp(t);console.log("[proxy] teardown_all",{count:e.length})}var Jp=z(require("node:fs")),_i=z(require("node:path")),$A=require("node:child_process"),gw=2560,jG=4e3,wA=500,zG=4,MG=32,LG=new Set(["node_modules",".git",".hg",".svn","dist","build","out",".next",".nuxt",".turbo",".cache","coverage","target","vendor",".venv","venv","__pycache__",".idea",".DS_Store"]),yi=new Map;function kA(e){let t=yi.get(e);return t!==void 0&&(yi.delete(e),yi.set(e,t)),t}function xA(e,t){for(yi.set(e,t);yi.size>MG;){let r=yi.keys().next().value;if(r===void 0)break;yi.delete(r)}}function yw(e,t){let r={...process.env,GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_SYSTEM:"/dev/null",GIT_PAGER:"cat"},n=(0,$A.spawnSync)("git",["--no-pager","-C",e,...t],{encoding:"utf-8",timeout:15e3,maxBuffer:8*1024*1024,env:r});return n.status!==0||n.error?null:n.stdout}function UG(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}K`:`${(e/(1024*1024)).toFixed(1)}M`}function IA(e,t){try{return Jp.statSync(_i.join(e,t)).size}catch{return 0}}function FG(e){let t=yw(e,["rev-parse","HEAD"]);if(t===null)return null;let r=yw(e,["ls-files","-c","-o","--exclude-standard"]);if(r===null)return null;let n=yw(e,["status","--porcelain=v1","-z","--untracked-files=all"])??"",o=new Map,i=n.split("\0");for(let l=0;l<i.length;l++){let u=i[l];if(!u||u.length<4)continue;let d=u[0]??" ",p=u[1]??" ",f=u.slice(3);(d==="R"||d==="C")&&l++;let m=d==="?"&&p==="?"?"?":p!==" "?p:d;["M","A","D","R","C","U","?"].includes(m)&&o.set(f,m)}let s=r.split(`
377
377
  `).map(l=>l.trim()).filter(l=>l.length>0),c=s.slice(0,jG).map(l=>({path:l,size:IA(e,l),status:o.get(l)}));return{head:t.trim(),entries:c,total:s.length}}function BG(e){let t=[],r=(n,o)=>{if(o>zG||t.length>=wA)return;let i;try{i=Jp.readdirSync(n,{withFileTypes:!0})}catch{return}for(let s of i){if(t.length>=wA)return;if(s.name.startsWith(".")&&s.name!==".env.example"||LG.has(s.name))continue;let a=_i.join(n,s.name),c=_i.relative(e,a).split(_i.sep).join("/");s.isDirectory()?r(a,o+1):s.isFile()&&t.push({path:c,size:IA(e,c)})}};return r(e,0),t.sort((n,o)=>n.path.localeCompare(o.path)),t}function SA(e,t,r,n){let o=[];o.push(`root: ${e} (${r} files, ${n==="git"?"git ls-files":"walk fallback"})`);for(let h of t){let g=h.path.split("/").length-1,_=h.path.slice(h.path.lastIndexOf("/")+1),b=h.status?` [${h.status}]`:"";o.push(`${" ".repeat(g)}${_} (${UG(h.size)})${b}`)}r>t.length&&o.push(`[\u2026 capped at ${t.length} of ${r} files \u2026]`);let i=o.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bridge-agent",
3
- "version": "0.21.0",
3
+ "version": "0.21.1",
4
4
  "description": "Bridge local agent — connects your AI tools to Jerico",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
Binary file