@volter/browser-substrate 0.1.115 → 0.1.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/cli/package-packs.js +4 -4
  2. package/dist/cli/package-packs.js.map +1 -1
  3. package/dist/shell/assets/browser-opfs-filesystem-worker-CivfnvV7.js +3 -0
  4. package/dist/shell/assets/{browser-sandbox-bridge-CmMlTDpO.js → browser-sandbox-bridge-BOyO6Vq0.js} +2 -2
  5. package/dist/shell/assets/filesystem-host-B-fDKRNE.js +3 -0
  6. package/dist/shell/assets/{filesystem-host-D98WfBoD.js → filesystem-host-Cngy2ePX.js} +1 -1
  7. package/dist/shell/assets/filesystem-worker-BQAYsjDk.js +5 -0
  8. package/dist/shell/assets/{fork-worker-hBikLg_q.js → fork-worker-BOu5dHuR.js} +1 -1
  9. package/dist/shell/assets/{node-execution-worker-714dbca4282e90ae.js → node-execution-worker-e4ab9bf7f09262f8.js} +2 -2
  10. package/dist/shell/assets/{sandbox-qgjYY5Gr.js → sandbox-C41DorhH.js} +1 -1
  11. package/dist/shell/assets/{shell-C0qfPTpQ.js → shell-CdIq-SFl.js} +4 -4
  12. package/dist/shell/assets/worker-BCIFrV5h.js +816 -0
  13. package/dist/shell/assets/worker-program-worker-BEQYJYct.js +27 -0
  14. package/dist/shell/index.html +2 -2
  15. package/dist/shell/node-execution-worker.js +25 -9
  16. package/dist/shell/python-execution-worker.js +24 -8
  17. package/dist/shell/python-runtime-snapshot.bin +0 -0
  18. package/dist/shell/python-runtime-snapshot.json +1 -1
  19. package/dist/shell/sandbox.html +2 -2
  20. package/package.json +1 -1
  21. package/dist/shell/assets/browser-opfs-filesystem-worker-TLQsaODy.js +0 -3
  22. package/dist/shell/assets/filesystem-host-EfkgP9Jh.js +0 -3
  23. package/dist/shell/assets/filesystem-worker-51BLqPs5.js +0 -5
  24. package/dist/shell/assets/worker-BZ-Txq9L.js +0 -816
  25. package/dist/shell/assets/worker-program-worker-B_u8gbzh.js +0 -27
@@ -1,4 +1,4 @@
1
- import"./page-workers-BUcWBF51.js";import{i as Kr,T as Qr,a5 as Cc,a2 as Ec,a3 as Rc,h as po,a6 as Ic,a7 as Ke,a8 as yr,a9 as rt,aa as Zt,b as zn,ab as us,c as Zi,ac as Oc,ad as Mc,ae as Nc,u as kc,a as Ac,af as bt,ag as Tc,ah as mo,M as Pc}from"./browser-sandbox-bridge-CmMlTDpO.js";class pn{adapter;objects=new Map;contexts=new Map;groups=new Map;sessions=new Map;prefix=globalThis.crypto.randomUUID();sequence=0;constructor(t){this.adapter=t}forSession(t){let r=this.sessions.get(t);return r||(r=new pn(this.adapter),this.sessions.set(t,r)),r}releaseSession(t){this.sessions.get(t)?.clear(),this.sessions.delete(t)}groupFor(t){for(const[r,i]of this.groups)if(i.has(t))return r}clear(){this.objects.clear(),this.groups.clear(),this.contexts.clear();for(const t of this.sessions.values())t.clear()}contextOf(t){return this.contexts.get(t)}serialize(t,r=!1,i,n){if(t===void 0)return{type:"undefined"};if(t===null)return{type:"object",subtype:"null",value:null};if(typeof t=="number"){const d=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":void 0;return d?{type:"number",unserializableValue:d}:{type:"number",value:t}}if(typeof t=="bigint")return{type:"bigint",unserializableValue:`${t}n`};if(typeof t=="string"||typeof t=="boolean")return{type:typeof t,value:t};if(typeof t=="symbol")return{type:"symbol",description:String(t)};if(r)return{type:typeof t,value:JSON.parse(JSON.stringify(t))};const u=`${this.prefix}:${++this.sequence}`;if(this.objects.set(u,t),n!==void 0&&this.contexts.set(u,n),i){const d=this.groups.get(i)??new Set;d.add(u),this.groups.set(i,d)}const c=this.adapter.describe(t);return{type:typeof t,...c,description:c.description??c.className,objectId:u}}argument(t){if(t.objectId){if(!this.objects.has(t.objectId))throw new Error(`Could not find object with given id ${t.objectId}`);return this.objects.get(t.objectId)}if(t.unserializableValue){switch(t.unserializableValue){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;case"-0":return-0}if(/^-?\d+n$/.test(t.unserializableValue))return BigInt(t.unserializableValue.slice(0,-1));throw new Error("Invalid unserializable value")}return t.value}async execute(t){if(t.sessionId!==void 0){const{sessionId:u,...c}=t;return this.forSession(u).execute(c)}const r=t.params??{},i=u=>({id:t.id,result:u}),n=typeof r.objectGroup=="string"?r.objectGroup:typeof r.objectId=="string"?this.groupFor(r.objectId):void 0;switch(t.method){case"Runtime.evaluate":{const u=typeof r.contextId=="number"?r.contextId:void 0;let c=this.adapter.evaluate(String(r.expression??""),u);return r.awaitPromise&&(c=await c),i({result:this.serialize(c,r.returnByValue===!0,n,u)})}case"Runtime.callFunctionOn":{const u=typeof r.executionContextId=="number"?r.executionContextId:typeof r.objectId=="string"?this.contextOf(r.objectId):void 0,c=typeof r.objectId=="string"?this.argument({objectId:r.objectId}):this.adapter.globalObject(u),d=Array.isArray(r.arguments)?r.arguments.map(g=>this.argument(g)):[];let o=this.adapter.invoke(String(r.functionDeclaration??"() => undefined"),c,d,u);return r.awaitPromise&&(o=await o),i({result:this.serialize(o,r.returnByValue===!0,n,u)})}case"Runtime.getProperties":{const u=this.argument({objectId:String(r.objectId??"")}),c=this.contextOf(String(r.objectId??"")),d=this.adapter.properties(u).map(({name:o,descriptor:g})=>({name:o,configurable:g.configurable??!1,enumerable:g.enumerable??!1,isOwn:!0,..."value"in g?{value:this.serialize(g.value,!1,n,c),writable:g.writable??!1}:{...g.get?{get:this.serialize(g.get,!1,n,c)}:{},...g.set?{set:this.serialize(g.set,!1,n,c)}:{}}}));return i({result:d,internalProperties:[]})}case"Runtime.releaseObject":{const u=String(r.objectId??"");this.objects.delete(u),this.contexts.delete(u);for(const c of this.groups.values())c.delete(u);return i({})}case"Runtime.releaseObjectGroup":{const u=this.groups.get(String(r.objectGroup??""));for(const c of u??[])this.objects.delete(c),this.contexts.delete(c);return this.groups.delete(String(r.objectGroup??"")),i({})}default:return}}}class Dc{backendIds=new WeakMap;backendNodes=new Map;sessions=new Map;sequence=0;backend(t){const r=this.backendIds.get(t);if(r!==void 0)return r;const i=++this.sequence;return this.backendIds.set(t,i),this.backendNodes.set(i,t),i}expose(t,r){let i=this.sessions.get(t);i||(i={ids:new WeakMap,nodes:new Map},this.sessions.set(t,i));const n=i.ids.get(r);if(n!==void 0)return n;const u=++this.sequence;return i.ids.set(r,u),i.nodes.set(u,r),this.backend(r),u}get(t,r){return this.sessions.get(t)?.nodes.get(r)}getBackend(t){return this.backendNodes.get(t)}releaseSession(t){this.sessions.delete(t)}clear(){this.sessions.clear(),this.backendNodes.clear(),this.backendIds=new WeakMap}}const Lc=4096,_c=200,Qa=128*1024,go=2e3,Fc=20,Uc=64,wt=2048,yo=64*1024,Fr=4096,qn=8e6;let es;const Za=new Set;Object.defineProperty(globalThis,"__substrateDocumentStart",{configurable:!0,value:e=>{for(const t of Za)try{t(e)}catch{}}});function $c(e){es=e}class Bc{preview;virtualPort;scriptSource;constructor(t,r){this.preview=t,this.virtualPort=r}connectProtocol(t,r){if(!es)throw new Error("This page lends no protocol surface: none is registered.");const{window:i}=this.context();return es(t,r,{window:i,documentStart:n=>{Za.add(n)},validateDocument:bo,urls:{toSurface:n=>this.surfaceUrl(n),fromSurface:n=>this.guestUrl(n),hostToSurface:n=>n==="localhost"||n==="127.0.0.1"||n===location.hostname?location.hostname:void 0,hostFromSurface:n=>n===location.hostname?"localhost":n},navigation:{navigate:n=>this.navigate(n),reload:()=>this.reload()},capture:n=>this.captureProtocolImage(n)})}guestUrl(t){let r;try{r=new URL(t)}catch{return t}if(r.origin!==location.origin)return t;const i=/^\/__virtual__\/([0-9]+)(\/.*)?$/u.exec(r.pathname),n=i?i[1]:String(this.virtualPort),u=i?i[2]??"/":r.pathname;return`http://localhost:${n}${u}${r.search}${r.hash}`}surfaceUrl(t){let r;try{r=new URL(t)}catch{return}if(r.origin===location.origin)return t;const i=r.hostname==="localhost"||r.hostname==="127.0.0.1"||r.hostname==="[::1]";if(r.protocol!=="http:"&&r.protocol!=="https:"||!i)return;const n=Number(r.port||(r.protocol==="https:"?443:80)),u=`${r.pathname}${r.search}${r.hash}`;return n===this.virtualPort?`${location.origin}${u}`:`${location.origin}/__virtual__/${n}${u}`}async captureProtocolImage(t){const r=t.format??"png";if(r!=="png"&&r!=="jpeg"&&r!=="webp")throw new Error("Unsupported preview image format.");if(t.fromSurface===!1)throw new Error("Preview capture cannot capture native surfaces.");const i=Number(t.quality??80);if(!Number.isFinite(i)||i<0||i>100)throw new Error("Invalid image quality.");const n=t.clip,u=await this.screenshot({fullPage:n!==void 0||t.captureBeyondViewport===!0});if(u.format!=="png")throw new Error("Preview could not produce PNG pixels.");const c=n?.x??0,d=n?.y??0,o=n?.width??u.width,g=n?.height??u.height,s=n?.scale??1;if(![c,d,o,g,s].every(Number.isFinite)||c<0||d<0||o<=0||g<=0||s<=0)throw new Error("Invalid preview capture clip.");if(c+o>u.width||d+g>u.height)throw new Error("Requested clip exceeds the bounded inspector capture.");const m=Math.min(1,Number(t.maxWidth??o)/o,Number(t.maxHeight??g)/g);if(!Number.isFinite(m)||m<=0)throw new Error("Invalid preview capture dimensions.");const l=Math.max(1,Math.round(o*s*m)),a=Math.max(1,Math.round(g*s*m));if(l>Fr||a>Fr||l*a>qn)throw new Error("Requested image exceeds the inspector capture limits.");const h=await wo(u.dataUrl),f=document.createElement("canvas");f.width=l,f.height=a;const y=f.getContext("2d");if(!y)throw new Error("Canvas rendering is unavailable.");y.drawImage(h,c,d,o,g,0,0,l,a);const R=f.toDataURL(`image/${r}`,i/100);if(!R.startsWith(`data:image/${r};`))throw new Error("Requested image encoder is unavailable.");const{window:x}=this.context();return{data:R.slice(R.indexOf(",")+1),deviceWidth:x.innerWidth,deviceHeight:x.innerHeight,scrollOffsetX:x.scrollX,scrollOffsetY:x.scrollY,timestamp:Date.now()/1e3}}loaded(){this.context(),this.scriptSource!==void 0&&this.installScript(this.scriptSource)}async execute(t){if(!Number.isSafeInteger(t.id)||t.id<1)throw new Error("Invalid preview command identifier.");switch(t.operation){case"snapshot":return this.snapshot();case"query":return this.query(t.selector);case"screenshot":return this.screenshot(t.fullPage===void 0?{}:{fullPage:t.fullPage});case"navigate":return this.navigate(t.url);case"reload":return this.reload();case"network-idle":return this.networkIdle(t.idleMs,t.timeoutMs);case"set-script":return this.setScript(t.source);case"evaluate":{if(typeof t.source!="string"||t.source.length>yo)throw new Error("Preview evaluation exceeds 64 KiB.");const{window:r}=this.context(),n=await new r.Function("args","preview",`return (async () => { ${t.source}
1
+ import"./page-workers-BUcWBF51.js";import{i as Kr,T as Qr,a5 as Cc,a2 as Ec,a3 as Rc,h as po,a6 as Ic,a7 as Ke,a8 as yr,a9 as rt,aa as Zt,b as zn,ab as us,c as Zi,ac as Oc,ad as Mc,ae as Nc,u as kc,a as Ac,af as bt,ag as Tc,ah as mo,M as Pc}from"./browser-sandbox-bridge-BOyO6Vq0.js";class pn{adapter;objects=new Map;contexts=new Map;groups=new Map;sessions=new Map;prefix=globalThis.crypto.randomUUID();sequence=0;constructor(t){this.adapter=t}forSession(t){let r=this.sessions.get(t);return r||(r=new pn(this.adapter),this.sessions.set(t,r)),r}releaseSession(t){this.sessions.get(t)?.clear(),this.sessions.delete(t)}groupFor(t){for(const[r,i]of this.groups)if(i.has(t))return r}clear(){this.objects.clear(),this.groups.clear(),this.contexts.clear();for(const t of this.sessions.values())t.clear()}contextOf(t){return this.contexts.get(t)}serialize(t,r=!1,i,n){if(t===void 0)return{type:"undefined"};if(t===null)return{type:"object",subtype:"null",value:null};if(typeof t=="number"){const d=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":void 0;return d?{type:"number",unserializableValue:d}:{type:"number",value:t}}if(typeof t=="bigint")return{type:"bigint",unserializableValue:`${t}n`};if(typeof t=="string"||typeof t=="boolean")return{type:typeof t,value:t};if(typeof t=="symbol")return{type:"symbol",description:String(t)};if(r)return{type:typeof t,value:JSON.parse(JSON.stringify(t))};const u=`${this.prefix}:${++this.sequence}`;if(this.objects.set(u,t),n!==void 0&&this.contexts.set(u,n),i){const d=this.groups.get(i)??new Set;d.add(u),this.groups.set(i,d)}const c=this.adapter.describe(t);return{type:typeof t,...c,description:c.description??c.className,objectId:u}}argument(t){if(t.objectId){if(!this.objects.has(t.objectId))throw new Error(`Could not find object with given id ${t.objectId}`);return this.objects.get(t.objectId)}if(t.unserializableValue){switch(t.unserializableValue){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;case"-0":return-0}if(/^-?\d+n$/.test(t.unserializableValue))return BigInt(t.unserializableValue.slice(0,-1));throw new Error("Invalid unserializable value")}return t.value}async execute(t){if(t.sessionId!==void 0){const{sessionId:u,...c}=t;return this.forSession(u).execute(c)}const r=t.params??{},i=u=>({id:t.id,result:u}),n=typeof r.objectGroup=="string"?r.objectGroup:typeof r.objectId=="string"?this.groupFor(r.objectId):void 0;switch(t.method){case"Runtime.evaluate":{const u=typeof r.contextId=="number"?r.contextId:void 0;let c=this.adapter.evaluate(String(r.expression??""),u);return r.awaitPromise&&(c=await c),i({result:this.serialize(c,r.returnByValue===!0,n,u)})}case"Runtime.callFunctionOn":{const u=typeof r.executionContextId=="number"?r.executionContextId:typeof r.objectId=="string"?this.contextOf(r.objectId):void 0,c=typeof r.objectId=="string"?this.argument({objectId:r.objectId}):this.adapter.globalObject(u),d=Array.isArray(r.arguments)?r.arguments.map(g=>this.argument(g)):[];let o=this.adapter.invoke(String(r.functionDeclaration??"() => undefined"),c,d,u);return r.awaitPromise&&(o=await o),i({result:this.serialize(o,r.returnByValue===!0,n,u)})}case"Runtime.getProperties":{const u=this.argument({objectId:String(r.objectId??"")}),c=this.contextOf(String(r.objectId??"")),d=this.adapter.properties(u).map(({name:o,descriptor:g})=>({name:o,configurable:g.configurable??!1,enumerable:g.enumerable??!1,isOwn:!0,..."value"in g?{value:this.serialize(g.value,!1,n,c),writable:g.writable??!1}:{...g.get?{get:this.serialize(g.get,!1,n,c)}:{},...g.set?{set:this.serialize(g.set,!1,n,c)}:{}}}));return i({result:d,internalProperties:[]})}case"Runtime.releaseObject":{const u=String(r.objectId??"");this.objects.delete(u),this.contexts.delete(u);for(const c of this.groups.values())c.delete(u);return i({})}case"Runtime.releaseObjectGroup":{const u=this.groups.get(String(r.objectGroup??""));for(const c of u??[])this.objects.delete(c),this.contexts.delete(c);return this.groups.delete(String(r.objectGroup??"")),i({})}default:return}}}class Dc{backendIds=new WeakMap;backendNodes=new Map;sessions=new Map;sequence=0;backend(t){const r=this.backendIds.get(t);if(r!==void 0)return r;const i=++this.sequence;return this.backendIds.set(t,i),this.backendNodes.set(i,t),i}expose(t,r){let i=this.sessions.get(t);i||(i={ids:new WeakMap,nodes:new Map},this.sessions.set(t,i));const n=i.ids.get(r);if(n!==void 0)return n;const u=++this.sequence;return i.ids.set(r,u),i.nodes.set(u,r),this.backend(r),u}get(t,r){return this.sessions.get(t)?.nodes.get(r)}getBackend(t){return this.backendNodes.get(t)}releaseSession(t){this.sessions.delete(t)}clear(){this.sessions.clear(),this.backendNodes.clear(),this.backendIds=new WeakMap}}const Lc=4096,_c=200,Qa=128*1024,go=2e3,Fc=20,Uc=64,wt=2048,yo=64*1024,Fr=4096,qn=8e6;let es;const Za=new Set;Object.defineProperty(globalThis,"__substrateDocumentStart",{configurable:!0,value:e=>{for(const t of Za)try{t(e)}catch{}}});function $c(e){es=e}class Bc{preview;virtualPort;scriptSource;constructor(t,r){this.preview=t,this.virtualPort=r}connectProtocol(t,r){if(!es)throw new Error("This page lends no protocol surface: none is registered.");const{window:i}=this.context();return es(t,r,{window:i,documentStart:n=>{Za.add(n)},validateDocument:bo,urls:{toSurface:n=>this.surfaceUrl(n),fromSurface:n=>this.guestUrl(n),hostToSurface:n=>n==="localhost"||n==="127.0.0.1"||n===location.hostname?location.hostname:void 0,hostFromSurface:n=>n===location.hostname?"localhost":n},navigation:{navigate:n=>this.navigate(n),reload:()=>this.reload()},capture:n=>this.captureProtocolImage(n)})}guestUrl(t){let r;try{r=new URL(t)}catch{return t}if(r.origin!==location.origin)return t;const i=/^\/__virtual__\/([0-9]+)(\/.*)?$/u.exec(r.pathname),n=i?i[1]:String(this.virtualPort),u=i?i[2]??"/":r.pathname;return`http://localhost:${n}${u}${r.search}${r.hash}`}surfaceUrl(t){let r;try{r=new URL(t)}catch{return}if(r.origin===location.origin)return t;const i=r.hostname==="localhost"||r.hostname==="127.0.0.1"||r.hostname==="[::1]";if(r.protocol!=="http:"&&r.protocol!=="https:"||!i)return;const n=Number(r.port||(r.protocol==="https:"?443:80)),u=`${r.pathname}${r.search}${r.hash}`;return n===this.virtualPort?`${location.origin}${u}`:`${location.origin}/__virtual__/${n}${u}`}async captureProtocolImage(t){const r=t.format??"png";if(r!=="png"&&r!=="jpeg"&&r!=="webp")throw new Error("Unsupported preview image format.");if(t.fromSurface===!1)throw new Error("Preview capture cannot capture native surfaces.");const i=Number(t.quality??80);if(!Number.isFinite(i)||i<0||i>100)throw new Error("Invalid image quality.");const n=t.clip,u=await this.screenshot({fullPage:n!==void 0||t.captureBeyondViewport===!0});if(u.format!=="png")throw new Error("Preview could not produce PNG pixels.");const c=n?.x??0,d=n?.y??0,o=n?.width??u.width,g=n?.height??u.height,s=n?.scale??1;if(![c,d,o,g,s].every(Number.isFinite)||c<0||d<0||o<=0||g<=0||s<=0)throw new Error("Invalid preview capture clip.");if(c+o>u.width||d+g>u.height)throw new Error("Requested clip exceeds the bounded inspector capture.");const m=Math.min(1,Number(t.maxWidth??o)/o,Number(t.maxHeight??g)/g);if(!Number.isFinite(m)||m<=0)throw new Error("Invalid preview capture dimensions.");const l=Math.max(1,Math.round(o*s*m)),a=Math.max(1,Math.round(g*s*m));if(l>Fr||a>Fr||l*a>qn)throw new Error("Requested image exceeds the inspector capture limits.");const h=await wo(u.dataUrl),f=document.createElement("canvas");f.width=l,f.height=a;const y=f.getContext("2d");if(!y)throw new Error("Canvas rendering is unavailable.");y.drawImage(h,c,d,o,g,0,0,l,a);const R=f.toDataURL(`image/${r}`,i/100);if(!R.startsWith(`data:image/${r};`))throw new Error("Requested image encoder is unavailable.");const{window:x}=this.context();return{data:R.slice(R.indexOf(",")+1),deviceWidth:x.innerWidth,deviceHeight:x.innerHeight,scrollOffsetX:x.scrollX,scrollOffsetY:x.scrollY,timestamp:Date.now()/1e3}}loaded(){this.context(),this.scriptSource!==void 0&&this.installScript(this.scriptSource)}async execute(t){if(!Number.isSafeInteger(t.id)||t.id<1)throw new Error("Invalid preview command identifier.");switch(t.operation){case"snapshot":return this.snapshot();case"query":return this.query(t.selector);case"screenshot":return this.screenshot(t.fullPage===void 0?{}:{fullPage:t.fullPage});case"navigate":return this.navigate(t.url);case"reload":return this.reload();case"network-idle":return this.networkIdle(t.idleMs,t.timeoutMs);case"set-script":return this.setScript(t.source);case"evaluate":{if(typeof t.source!="string"||t.source.length>yo)throw new Error("Preview evaluation exceeds 64 KiB.");const{window:r}=this.context(),n=await new r.Function("args","preview",`return (async () => { ${t.source}
2
2
  })();`)(t.args,{screenshot:c=>this.screenshot(c)}),u=JSON.stringify(n??null);if(u.length>1024*1024)throw new Error("Preview evaluation result exceeds 1 MiB.");return JSON.parse(u)}}}snapshot(){const{document:t,window:r}=this.context(),i=t.documentElement,n=t.body,u=Math.max(i.scrollWidth,i.clientWidth,n?.scrollWidth??0,n?.clientWidth??0),c=Math.max(i.scrollHeight,i.clientHeight,n?.scrollHeight??0,n?.clientHeight??0);return{url:r.location.href,title:t.title.slice(0,4096),readyState:t.readyState,text:(n?.innerText??"").slice(0,Qa),viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},document:{width:u,height:c,scrollX:r.scrollX,scrollY:r.scrollY,overflowX:u>r.innerWidth,overflowY:c>r.innerHeight},accessibility:jc(t)}}query(t){if(typeof t!="string"||t.length===0||t.length>Lc)throw new Error("Preview selector must contain 1..4096 characters.");const{document:r,window:i}=this.context();let n;try{n=r.querySelectorAll(t)}catch{throw new Error("Preview selector is invalid.")}return[...n].slice(0,_c).map(u=>Wc(u,i))}async screenshot(t={}){if(t.fullPage!==void 0&&typeof t.fullPage!="boolean")throw new Error("Invalid fullPage screenshot option.");const{document:r,window:i}=this.context(),n=r.documentElement;let u=Math.min(Fr,Math.max(1,t.fullPage===!1?i.innerWidth:n.scrollWidth,i.innerWidth)),c=Math.min(Fr,Math.max(1,t.fullPage===!1?i.innerHeight:n.scrollHeight,i.innerHeight));const d=u*c;if(d>qn){const a=Math.sqrt(qn/d);u=Math.max(1,Math.floor(u*a)),c=Math.max(1,Math.floor(c*a))}const o=Gc(n);t.fullPage===!1&&(o.style.transform=`translate(${-i.scrollX}px, ${-i.scrollY}px)`,o.style.transformOrigin="top left");const g=new XMLSerializer().serializeToString(o);if(g.length>32*1024*1024)throw new Error("Screenshot DOM exceeds 32 MiB.");const s=`<svg xmlns="http://www.w3.org/2000/svg" width="${u}" height="${c}"><foreignObject width="100%" height="100%">${g}</foreignObject></svg>`,m=Hn(s),l="DOM reconstruction; images the page may not read, external fonts, embedded media and native compositor effects are omitted";try{const a=await wo(m),h=r.createElement("canvas");h.width=u,h.height=c;const f=h.getContext("2d");if(!f)throw new Error("Canvas rendering is unavailable.");const y=w=>w==="rgba(0, 0, 0, 0)"||w==="transparent",R=i.getComputedStyle(n).backgroundColor,x=y(R)?i.getComputedStyle(r.body??n).backgroundColor:R;f.fillStyle=y(x)?"#ffffff":x,f.fillRect(0,0,u,c),f.drawImage(a,0,0,u,c);try{return{dataUrl:h.toDataURL("image/png"),format:"png",width:u,height:c,fidelity:l}}catch{return{dataUrl:Hn(s),format:"svg",width:u,height:c,fidelity:l}}}catch{return{dataUrl:Hn(s),format:"svg",width:u,height:c,fidelity:l}}}async navigate(t){if(typeof t!="string"||t.length===0||t.length>16384)throw new Error("Preview navigation target is invalid.");const r=this.preview.src||`${location.origin}/`,i=/^\/__virtual__\/([0-9]+)\//u.exec(r.startsWith("about:")?"":new URL(r).pathname),n=new URL(i?`/__virtual__/${i[1]}/`:"/",location.origin),u=t.startsWith("/")?new URL(t.slice(1),n):new URL(t,r),c=/^\/__virtual__\/[0-9]+\//u.test(u.pathname);if(u.origin!==location.origin||!(u.pathname.startsWith(n.pathname)||c))throw new Error("Preview navigation cannot leave its virtual application.");return await this.load(u.href),{url:this.context().window.location.href}}async reload(){const t=this.preview.contentWindow;let r=this.preview.src;try{r=t?.location.href||r}catch{}return await this.load(r,()=>{try{t.location.reload()}catch{this.preview.src=r}}),{url:this.context().window.location.href}}async networkIdle(t=500,r=1e4){if(!Number.isSafeInteger(t)||t<0||t>5e3||!Number.isSafeInteger(r)||r<1||r>3e4)throw new Error("Preview network-idle bounds are invalid.");const i=Date.now()+r;for(;Date.now()<i;){const n=this.context().window.__browserRuntimeNetworkState,u=n?.lastChanged??0,c=Date.now()-u;if((n?.pending??0)===0&&c>=t)return{idleForMs:c};await Xc(Math.min(50,Math.max(1,i-Date.now())))}throw new Error("Preview did not reach network idle before the timeout.")}setScript(t){if(t!==void 0&&(typeof t!="string"||t.length>yo))throw new Error("Preview instrumentation exceeds 64 KiB.");return this.scriptSource=t,t!==void 0&&this.installScript(t),{installed:t!==void 0}}installScript(t){const{document:r}=this.context();r.querySelectorAll("script[data-browser-runtime-instrumentation]").forEach(n=>n.remove());const i=r.createElement("script");i.dataset.browserRuntimeInstrumentation="",i.textContent=t,(r.head??r.documentElement).append(i)}load(t,r=()=>{this.preview.src=t}){return new Promise((i,n)=>{const u=setTimeout(()=>d(new Error("Preview navigation timed out.")),15e3),c=()=>d(),d=o=>{clearTimeout(u),this.preview.removeEventListener("load",c),o?n(o):i()};this.preview.addEventListener("load",c,{once:!0}),r()})}context(){const t=this.preview.contentWindow,r=this.preview.contentDocument;if(!t||!r)throw new Error("Generated preview is unavailable.");return bo(r),{document:r,window:t}}}function bo(e){if(e.querySelector('meta[name="browser-substrate-host"]'))throw new Error("Preview routing failed: a host document was returned instead of the generated app.")}function Wc(e,t){const r=e,i=e.getBoundingClientRect(),n=t.getComputedStyle(e),u={};for(const c of[...e.attributes].slice(0,Uc))u[c.name]=c.value.slice(0,wt);return{tag:e.tagName.toLowerCase(),...e.id?{id:e.id.slice(0,wt)}:{},classes:[...e.classList].slice(0,64),...ts(e)?{role:ts(e)}:{},...rs(e)?{name:rs(e)}:{},text:(r.innerText??e.textContent??"").trim().slice(0,Qa),visible:n.display!=="none"&&n.visibility!=="hidden"&&Number.parseFloat(n.opacity||"1")>0&&i.width>0&&i.height>0,box:Vc(i),attributes:u}}function jc(e){const t=[...e.querySelectorAll("a,button,input,select,textarea,summary,[role],[aria-label],h1,h2,h3,h4,h5,h6,main,nav,aside,header,footer,form,table")];let r=go;const i=new Set(t.slice(0,go)),n=[],u=new Map;for(const d of i){const o=zc(d,i);if(!o)n.push(d);else{const g=u.get(o)??[];g.push(d),u.set(o,g)}}const c=(d,o)=>{if(r--<=0||o>Fc)return;const g=ts(d);if(!g)return;const s=(u.get(d)??[]).map(h=>c(h,o+1)).filter(h=>!!h),m=Hc(d.getAttribute("aria-checked")??(d.tagName==="INPUT"&&new Set(["checkbox","radio"]).has(d.type)?String(d.checked):null)),l=el(d.getAttribute("aria-expanded")),a=/^h[1-6]$/iu.test(d.tagName)?Number(d.tagName.slice(1)):void 0;return{role:g,name:rs(d),tag:d.tagName.toLowerCase(),...d.disabled===!0||d.getAttribute("aria-disabled")==="true"?{disabled:!0}:{},...m!==void 0?{checked:m}:{},...l!==void 0?{expanded:l}:{},...a!==void 0?{level:a}:{},...s.length>0?{children:s}:{}}};return n.map(d=>c(d,0)).filter(d=>!!d)}function zc(e,t){let r=e.parentElement;for(;r;){if(t.has(r))return r;r=r.parentElement}}function ts(e){const t=e.getAttribute("role");if(t)return t.split(/\s+/u)[0]??"";const r=e.tagName.toLowerCase();return/^h[1-6]$/u.test(r)?"heading":{a:e.hasAttribute("href")?"link":"generic",button:"button",input:qc(e),select:"combobox",textarea:"textbox",summary:"button",main:"main",nav:"navigation",aside:"complementary",header:"banner",footer:"contentinfo",form:"form",table:"table"}[r]??""}function qc(e){return e.type==="checkbox"?"checkbox":e.type==="radio"?"radio":e.type==="range"?"slider":e.type==="button"||e.type==="submit"||e.type==="reset"?"button":"textbox"}function rs(e){const t=e.getAttribute("aria-label");if(t)return t.slice(0,wt);const r=e.getAttribute("aria-labelledby");if(r){const n=r.split(/\s+/u).map(u=>e.ownerDocument.getElementById(u)?.textContent?.trim()??"").filter(Boolean).join(" ");if(n)return n.slice(0,wt)}if(e.tagName==="IMG"&&e.alt)return e.alt.slice(0,wt);if(e.tagName==="INPUT"){const n=e,u=n.labels?.[0]?.textContent?.trim();if(u)return u.slice(0,wt);if(n.value&&new Set(["button","submit","reset"]).has(n.type))return n.value.slice(0,wt);if(n.placeholder)return n.placeholder.slice(0,wt)}const i=e.getAttribute("title");return i?i.slice(0,wt):(e.textContent??"").trim().replace(/\s+/gu," ").slice(0,wt)}function el(e){if(e==="true")return!0;if(e==="false")return!1}function Hc(e){return e==="mixed"?"mixed":el(e)}function Vc(e){return{x:e.x,y:e.y,width:e.width,height:e.height}}function wo(e){return new Promise((t,r)=>{const i=new Image;i.onload=()=>t(i),i.onerror=()=>r(new Error("The serialized preview could not be rendered.")),i.src=e})}function Hn(e){return`data:image/svg+xml;base64,${Kr(new TextEncoder().encode(e))}`}function Gc(e){const t=e.ownerDocument;let r=0;const i=(n,u)=>{if(n.nodeType===3)return t.createTextNode(n.nodeValue??"");if(n.nodeType!==1)return;const c=n,d=c.localName;if(/^(script|object|embed|video|audio|source|link|template|noscript)$/u.test(d))return;if(++r>5e3)throw new Error("Screenshot DOM exceeds 5000 elements.");if(d==="style")return u||/@import|url\s*\(/iu.test(c.textContent??"")?void 0:c.cloneNode(!0);const o=c.ownerDocument.defaultView.getComputedStyle(c),g=Array.from(o).map(a=>{const h=o.getPropertyValue(a);return/url\s*\(/iu.test(h)?"":`${a}:${h};`}).join("");if(d==="iframe"){let a=null;try{a=c.contentDocument}catch{a=null}const h=a?.documentElement?i(a.documentElement,!0):void 0;if(!h)return;const f=t.createElement("div");return f.setAttribute("style",`${g}overflow:hidden;contain:paint;${o.display==="inline"?"display:inline-block;":""}`),f.append(h),f}if(d==="canvas"){const a=c;try{const h=t.createElement("img");return h.src=a.toDataURL("image/png"),h.width=a.width,h.height=a.height,h.setAttribute("style",g),h}catch{return}}const s=c.cloneNode(!1);if(s.setAttribute("style",g),d==="input")s.setAttribute("value",c.value),s.toggleAttribute("checked",c.checked);else{if(d==="textarea")return s.textContent=c.value,s;if(d==="option")s.toggleAttribute("selected",c.selected);else if(d==="img"){const a=c;if(s.removeAttribute("srcset"),!(s.getAttribute("src")??"").startsWith("data:")&&(s.removeAttribute("src"),a.complete&&a.naturalWidth))try{const h=t.createElement("canvas");h.width=a.naturalWidth,h.height=a.naturalHeight,h.getContext("2d")?.drawImage(a,0,0),s.setAttribute("src",h.toDataURL("image/png"))}catch{}}}const m=c.shadowRoot,l=m?m.childNodes:d==="slot"&&c.getRootNode()!==c.ownerDocument?c.assignedNodes({flatten:!0}):c.childNodes;for(const a of l){const h=i(a,u||m!==null);h&&s.appendChild(h)}return s};return i(e,!1)}function Xc(e){return new Promise(t=>setTimeout(t,e))}const er=new URLSearchParams(location.search),tl=new URL(er.get("parentOrigin")||"").origin,ur=er.get("nonce")||"",pt=Number.parseInt(er.get("port")||"",10),vo=pt===0,Ct=document.querySelector("#generated-preview"),ns=new Bc(Ct,pt);let $t;window.addEventListener("pagehide",()=>{$t?.close(),Ye("protocol-disconnect")});const ds=1e4,Ur=new Map,cr=new Map,So=64*1024,Jc=8*1024*1024,Yc=64*1024*1024,xo=(e,t)=>`${location.origin}${e===pt||e===0?"":`/__virtual__/${e}`}${t}`,rl=er.get("clear")==="1"||er.get("clear")==="reuse",Kc=er.get("clear")==="reuse";if(!ur||!rl&&(!Number.isSafeInteger(pt)||pt<0||pt>65535))throw new Error("Invalid sandbox bootstrap parameters.");const Qc="<script>(function(s){try{var h=parent.__substrateDocumentStart;if(h)h(window)}catch(e){}if(s)s.remove()})(document.currentScript)<\/script>";async function Zc(){localStorage.clear(),sessionStorage.clear();for(const i of await indexedDB.databases())i.name&&indexedDB.deleteDatabase(i.name);for(const i of await caches.keys())await caches.delete(i);const e=globalThis.cookieStore;if(e)for(const i of await e.getAll())await e.delete({name:i.name,...i.path?{path:i.path}:{},...i.domain?{domain:i.domain}:{}});const t=await navigator.storage.getDirectory();for await(const i of t.keys())await t.removeEntry(i,{recursive:!0});const r=`${location.origin}/__sw__.js`;for(const i of await navigator.serviceWorker.getRegistrations()){const n=(i.active??i.waiting??i.installing)?.scriptURL;Kc&&i.scope===`${location.origin}/`&&n===r||await i.unregister()}}function Ye(e,t){window.parent.postMessage({channel:Qr,nonce:ur,type:e,payload:t},tl)}async function eu(){const e=await navigator.serviceWorker.register("/__sw__.js",{scope:"/",updateViaCache:"none"});await e.update();const t=e.installing||e.waiting||e.active;if(!t)throw new Error("Sandbox service worker registration failed.");return t.state!=="activated"&&await tu(t,"activated"),t}function tu(e,t){return new Promise((r,i)=>{const n=globalThis.setTimeout(()=>c(new Error(`Sandbox service worker did not reach ${t}.`)),ds),u=()=>{e.state===t?c():e.state==="redundant"&&c(new Error("Sandbox service worker became redundant during startup."))},c=d=>{globalThis.clearTimeout(n),e.removeEventListener("statechange",u),d?i(d):r()};e.addEventListener("statechange",u),u()})}function ru(e){return navigator.serviceWorker.controller===e?Promise.resolve():new Promise((t,r)=>{const i=globalThis.setTimeout(()=>u(new Error("Sandbox service worker did not take control.")),ds),n=()=>{navigator.serviceWorker.controller===e&&u()},u=c=>{globalThis.clearTimeout(i),navigator.serviceWorker.removeEventListener("controllerchange",n),c?r(c):t()};navigator.serviceWorker.addEventListener("controllerchange",n),n()})}function Co(){try{ns.loaded(),Ye("preview-load")}catch(e){$t?.close(),$t=void 0,Ye("error",{message:e instanceof Error?e.message:String(e)})}}function Eo(e){return e==="document"||e==="iframe"||e==="frame"}function $r(e,t){return t?[{type:"stream-start",id:e,data:{statusCode:204,statusMessage:"No Content",headers:{}}},{type:"stream-end",id:e}]:[{type:"response",id:e,data:{statusCode:204,statusMessage:"No Content",headers:{},bodyBase64:""}}]}async function nu(){const e=await eu();let t;const r=new Cc(await Ec(`sandbox:${pt}`).then(d=>(Rc(window,d),d)));async function i(d){if((d?.type==="stream-pull"||d?.type==="stream-cancel")&&Number.isSafeInteger(d.id)&&cr.has(d.id)){const a=cr.get(d.id);if(d.type==="stream-cancel"){cr.delete(d.id);return}const h=a.shift();h&&t.postMessage({type:"stream-chunk",id:d.id,data:{chunkBase64:Kr(h)}}),a.length||(cr.delete(d.id),t.postMessage({type:"stream-end",id:d.id}));return}d?.type==="stream-cancel"&&Number.isSafeInteger(d.id)&&r.forget(d.id),r.request(d);const o=d?.data,g=$t?.network;if(d?.type!=="request"||!g||!o||!o.destination||!Number.isSafeInteger(d.id)||typeof o.url!="string"||typeof o.method!="string"||!Number.isSafeInteger(o.port)){Ye("request",d);return}const s=d.id,m=xo(o.port,o.url);let l;try{l=await g.request(String(s),{url:m,method:o.method,headers:Object.entries(o.headers??{}),destination:o.destination,...o.body&&o.body.byteLength?{body:new Uint8Array(o.body)}:{}})}catch{Ye("request",d);return}if(l.type==="fulfill"){const a={};for(const[f,y]of l.headers)a[f]=a[f]===void 0?y:`${a[f]}, ${y}`;l={...l,body:Ic(l.body,a,void 0)};const h=l.headers.filter(([f])=>f.toLowerCase()==="set-cookie").map(([,f])=>f);if(r.answer({type:"response",id:s,data:{headers:h.length?{"set-cookie":h}:{}}}),o.flowControl){const f=[];for(let y=0;y<l.body.byteLength;y+=So)f.push(l.body.subarray(y,y+So));t.postMessage({type:"stream-start",id:s,data:{statusCode:l.status,statusMessage:l.statusText,headers:a}}),f.length?cr.set(s,f):t.postMessage({type:"stream-end",id:s})}else o.streaming?(t.postMessage({type:"stream-start",id:s,data:{statusCode:l.status,statusMessage:l.statusText,headers:a}}),l.body.byteLength&&t.postMessage({type:"stream-chunk",id:s,data:{chunkBase64:Kr(l.body)}}),t.postMessage({type:"stream-end",id:s})):t.postMessage({type:"response",id:s,data:{statusCode:l.status,statusMessage:l.statusText,headers:a,bodyBase64:Kr(l.body)}});return}if(l.type==="fail"){if(r.forget(s),Eo(o.destination))for(const a of $r(s,!!(o.streaming||o.flowControl)))t.postMessage(a);else t.postMessage({type:o.streaming?"stream-error":"response",id:s,error:l.reason});return}if(l.url)try{const a=new URL(l.url),h=Number(a.port||(a.protocol==="https:"?443:80));if(a.pathname.startsWith("/__virtual__/")){const f=/^\/__virtual__\/([0-9]+)(\/.*)?$/u.exec(a.pathname);f&&(o.port=Number(f[1]),o.url=`${f[2]??"/"}${a.search}`)}else a.origin===location.origin?(o.port=pt,o.url=`${a.pathname}${a.search}`):(o.port=h,o.url=`${a.pathname}${a.search}`)}catch{}l.method&&(o.method=l.method),l.headers&&(o.headers=Object.fromEntries(l.headers)),l.postData&&(o.body=l.postData.slice().buffer),Ur.set(s,{url:xo(o.port,o.url),chunks:[],size:0,document:Eo(o.destination),streaming:!!(o.streaming||o.flowControl),flowControl:!!o.flowControl}),Ye("request",d)}function n(d){return/is not listening/u.test(String(d))?"net::ERR_CONNECTION_REFUSED":"net::ERR_FAILED"}function u(d){const o=d,g=$t?.network;if(!o||!Number.isSafeInteger(o.id)||!Ur.has(o.id))return;const s=Ur.get(o.id),m=String(o.id),l=y=>Object.fromEntries(Object.entries(y??{}).map(([R,x])=>[R,Array.isArray(x)?x.join(", "):String(x)])),a=()=>{Ur.delete(o.id)};if(o.error||o.type==="stream-error")return g?.failed(m,n(o.error)),a(),s.download?[]:s.document?$r(o.id,s.streaming):void 0;const h=()=>s.download?Yc:Jc,f=()=>{s.download&&s.flowControl&&Ye("request",{type:"stream-pull",id:o.id})};if(o.type==="response"){g?.responded(m,{status:o.data?.statusCode??200,statusText:o.data?.statusMessage??"",headers:l(o.data?.headers),url:s.url})&&(s.download=!0);const R=o.data?.bodyBase64?po(o.data.bodyBase64):new Uint8Array;if(g?.finished(m,R.byteLength<=h()?R:void 0),a(),s.download)return $r(o.id,!1)}else if(o.type==="stream-start"){if(g?.responded(m,{status:o.data?.statusCode??200,statusText:o.data?.statusMessage??"",headers:l(o.data?.headers),url:s.url}))return s.download=!0,f(),$r(o.id,!0)}else if(o.type==="stream-chunk"&&o.data?.chunkBase64){const y=po(o.data.chunkBase64);if(s.size+=y.byteLength,s.size<=h()&&s.chunks.push(y),s.download)return f(),[]}else if(o.type==="stream-end"){let y;if(s.size<=h()){y=new Uint8Array(s.size);let R=0;for(const x of s.chunks)y.set(x,R),R+=x.byteLength}if(g?.finished(m,y),a(),s.download)return[]}}async function c(){const d=new MessageChannel;t=d.port1,r.reset();const o=new Promise((g,s)=>{const m=globalThis.setTimeout(()=>s(new Error("Sandbox service worker bridge timed out.")),ds);d.port1.onmessage=l=>{if(l.data?.type==="bridge-ready"){globalThis.clearTimeout(m),g();return}i(l.data)}});e.postMessage({type:"init",data:{ownDocuments:[location.pathname,"/node-host.html","/python-host.html"],documentPrelude:Qc}},[d.port2]),await o,vo||e.postMessage({type:"server-registered",data:{port:pt,hostname:"0.0.0.0",primary:!0}})}window.addEventListener("message",d=>{if(d.origin===tl&&d.source===window.parent){const o=d.data;if(o.channel===Qr&&o.nonce===ur&&o.type==="protocol-connect"){const g=o.payload?.id,s=d.ports[0];if(!s||d.ports.length!==1||typeof g!="string"||!/^[a-zA-Z0-9_-]{1,128}$/u.test(g)){for(const m of d.ports)m.close();return}try{$t?.close(),$t=ns.connectProtocol(s,g),s.postMessage({type:"protocol-ready",id:g})}catch(m){s.postMessage({type:"close",code:1011,reason:m instanceof Error?m.message:String(m)}),s.close()}return}if(o.channel===Qr&&o.nonce===ur&&o.type==="response"){const g=o.payload?.type;if(typeof g=="string"&&g.startsWith("websocket-"))Ct.contentWindow?.postMessage(o.payload,location.origin);else{r.answer(o.payload);for(const s of u(o.payload)??[o.payload])t.postMessage(s)}}if(o.channel===Qr&&o.nonce===ur&&o.type==="command"){const g=o.payload;ns.execute(g).then(s=>Ye("command-result",{id:g.id,result:s}),s=>Ye("command-result",{id:g?.id,error:s instanceof Error?s.message:String(s)}))}d.data?.channel==="vite-hmr"&&Ct.contentWindow?.postMessage(d.data,location.origin);return}if(d.source===Ct.contentWindow&&d.data?.type==="browser-agent-preview-load")Co();else if(d.source===Ct.contentWindow&&d.data?.type==="browser-agent-rendered")Ye("rendered",{revision:String(d.data.revision)});else if(d.source===Ct.contentWindow&&d.data?.type==="browser-agent-observation")Ye("observation",d.data.observation);else if(d.source===Ct.contentWindow&&typeof d.data?.type=="string"&&d.data.type.startsWith("websocket-")){const o=d.data;o.data?.port===0&&(o.data.port=pt),Ye("request",d.data)}}),navigator.serviceWorker.addEventListener("message",d=>{d.data?.type==="sw-needs-init"&&c().catch(o=>Ye("error",{message:o instanceof Error?o.message:String(o)}))}),await c(),await ru(e),Ct.addEventListener("load",Co),Ct.src=vo?"about:blank":`${location.origin}/`,Ye("ready",{documentId:crypto.randomUUID(),url:`${location.origin}/__virtual__/${pt}/`})}rl?Zc().then(()=>Ye("cleared"),e=>Ye("error",{message:e instanceof Error?e.message:String(e)})):nu().catch(e=>Ye("error",{message:e instanceof Error?e.message:String(e)}));var sn={},iu=Object.defineProperty,su=(e,t,r)=>t in e?iu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,X=(e,t,r)=>su(e,typeof t!="symbol"?t+"":t,r),Ro,ou=Object.defineProperty,au=(e,t,r)=>t in e?ou(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Io=(e,t,r)=>au(e,typeof t!="symbol"?t+"":t,r),He=(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(He||{});const Oo={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument","firstChild","lastChild","nextSibling","previousSibling"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Mo={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Br={},nl={},lu=()=>!!globalThis.Zone;function fs(e){if(Br[e])return Br[e];const t=globalThis[e],r=t.prototype,i=e in Oo?Oo[e]:void 0,n=!!(i&&i.every(d=>{var o,g;return!!((g=(o=Object.getOwnPropertyDescriptor(r,d))==null?void 0:o.get)!=null&&g.toString().includes("[native code]"))})),u=e in Mo?Mo[e]:void 0,c=!!(u&&u.every(d=>{var o;return typeof r[d]=="function"&&((o=r[d])==null?void 0:o.toString().includes("[native code]"))}));if(n&&c&&!lu())return Br[e]=t.prototype,t.prototype;try{const d=document.createElement("iframe");d.style.display="none",document.body.appendChild(d);const o=d.contentWindow;if(!o)return t.prototype;const g=o[e].prototype;if(!g)return d.remove(),r;const s=navigator.userAgent;return s.includes("Safari")&&!s.includes("Chrome")?(d.classList.add("rr-block"),d.setAttribute("__rrwebUntaintedMutationObserver",""),nl[e]=()=>d.remove()):d.remove(),Br[e]=g}catch{return r}}const Vn={};function ot(e,t,r){var i,n;const u=(i=Vn[e])==null?void 0:i[r];if(u)return u.call(t);const c=fs(e),d=(n=Object.getOwnPropertyDescriptor(c,r))==null?void 0:n.get;return d?((Vn[e]||(Vn[e]={}))[r]=d,d.call(t)):t[r]}const Gn={};function il(e,t,r){const i=`${e}.${String(r)}`;if(Gn[i])return Gn[i].bind(t);const u=fs(e)[r];return typeof u!="function"?t[r]:(Gn[i]=u,u.bind(t))}function cu(e){return ot("Node",e,"ownerDocument")}function uu(e){return ot("Node",e,"childNodes")}function du(e){return ot("Node",e,"parentNode")}function fu(e){return ot("Node",e,"parentElement")}function hu(e){return ot("Node",e,"textContent")}function pu(e){return ot("Node",e,"firstChild")}function mu(e){return ot("Node",e,"lastChild")}function gu(e){return ot("Node",e,"nextSibling")}function yu(e){return ot("Node",e,"previousSibling")}function bu(e,t){return il("Node",e,"contains")(t)}function wu(e){return il("Node",e,"getRootNode")()}function vu(e){return!e||!("host"in e)?null:ot("ShadowRoot",e,"host")}function Su(e){return e.styleSheets}function xu(e){return!e||!("shadowRoot"in e)?null:ot("Element",e,"shadowRoot")}function Cu(e,t){return ot("Element",e,"querySelector")(t)}function Eu(e,t){return ot("Element",e,"querySelectorAll")(t)}function Ru(){return[fs("MutationObserver").constructor,nl.MutationObserver??(()=>{})]}let sl=Date.now;/[1-9][0-9]{12}/.test(Date.now().toString())||(sl=()=>new Date().getTime());function Iu(e,t,r){try{if(!(t in e))return()=>{};const i=e[t],n=r(i);return typeof n=="function"&&(n.prototype=n.prototype||{},Object.defineProperties(n,{__rrweb_original__:{enumerable:!1,value:i}})),e[t]=n,()=>{e[t]=i}}catch{return()=>{}}}const Ze={ownerDocument:cu,childNodes:uu,parentNode:du,parentElement:fu,textContent:hu,firstChild:pu,lastChild:mu,nextSibling:gu,previousSibling:yu,contains:bu,getRootNode:wu,host:vu,styleSheets:Su,shadowRoot:xu,querySelector:Cu,querySelectorAll:Eu,nowTimestamp:sl,mutationObserverCtor:Ru,patch:Iu};function ol(e){return e.nodeType===e.ELEMENT_NODE}function dr(e){const t=e&&"host"in e&&"mode"in e&&Ze.host(e)||null;return!!(t&&"shadowRoot"in t&&Ze.shadowRoot(t)===e)}function fr(e){return Object.prototype.toString.call(e)==="[object ShadowRoot]"}function Ou(e){return e.includes(" background-clip: text;")&&!e.includes(" -webkit-background-clip: text;")&&(e=e.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),e}function Mu(e){const{cssText:t}=e;if(t.split('"').length<3)return t;const r=["@import",`url(${JSON.stringify(e.href)})`];return e.layerName===""?r.push("layer"):e.layerName&&r.push(`layer(${e.layerName})`),e.supportsText&&r.push(`supports(${e.supportsText})`),e.media.length&&r.push(e.media.mediaText),r.join(" ")+";"}function is(e){try{const t=e.rules||e.cssRules;if(!t)return null;let r=e.href;!r&&e.ownerNode&&(r=e.ownerNode.baseURI);const i=Array.from(t,n=>al(n,r)).join("");return Ou(i)}catch{return null}}function al(e,t){if(ku(e)){let r;try{r=is(e.styleSheet)||Mu(e)}catch{r=e.cssText}return e.styleSheet.href?ln(r,e.styleSheet.href):r}else{let r=e.cssText;return Au(e)&&e.selectorText.includes(":")&&(r=Nu(r)),t?ln(r,t):r}}function Nu(e){const t=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return e.replace(t,"$1\\$2")}function ku(e){return"styleSheet"in e}function Au(e){return"selectorText"in e}class ll{constructor(){Io(this,"idNodeMap",new Map),Io(this,"nodeMetaMap",new WeakMap)}getId(t){var r;return t?((r=this.getMeta(t))==null?void 0:r.id)??-1:-1}getNode(t){return this.idNodeMap.get(t)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(t){return this.nodeMetaMap.get(t)||null}removeNodeFromMap(t){const r=this.getId(t);this.idNodeMap.delete(r),t.childNodes&&t.childNodes.forEach(i=>this.removeNodeFromMap(i))}has(t){return this.idNodeMap.has(t)}hasNode(t){return this.nodeMetaMap.has(t)}add(t,r){const i=r.id;this.idNodeMap.set(i,t),this.nodeMetaMap.set(t,r)}replace(t,r){const i=this.getNode(t);if(i){const n=this.nodeMetaMap.get(i);n&&this.nodeMetaMap.set(r,n)}this.idNodeMap.set(t,r)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function Tu(){return new ll}function on({element:e,maskInputOptions:t,tagName:r,type:i,value:n,maskInputFn:u}){let c=n||"";const d=i&&Nt(i);return(t[r.toLowerCase()]||d&&t[d])&&(u?c=u(c,e):c="*".repeat(c.length)),c}function Nt(e){return e.toLowerCase()}const No="__rrweb_original__";function Pu(e){const t=e.getContext("2d");if(!t)return!0;const r=50;for(let i=0;i<e.width;i+=r)for(let n=0;n<e.height;n+=r){const u=t.getImageData,c=No in u?u[No]:u;if(new Uint32Array(c.call(t,i,n,Math.min(r,e.width-i),Math.min(r,e.height-n)).data.buffer).some(o=>o!==0))return!1}return!0}function an(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?Nt(t):null}function cl(e,t){let r;try{r=new URL(e,t??window.location.href)}catch{return null}const i=/\.([0-9a-z]+)(?:$)/i,n=r.pathname.match(i);return n?.[1]??null}function Du(e){let t="";return e.indexOf("//")>-1?t=e.split("/").slice(0,3).join("/"):t=e.split("/")[0],t=t.split("?")[0],t}const Lu=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,_u=/^(?:[a-z+]+:)?\/\//i,Fu=/^www\..*/i,Uu=/^(data:)([^,]*),(.*)/i;function ln(e,t){return(e||"").replace(Lu,(r,i,n,u,c,d)=>{const o=n||c||d,g=i||u||"";if(!o)return r;if(_u.test(o)||Fu.test(o))return`url(${g}${o}${g})`;if(Uu.test(o))return`url(${g}${o}${g})`;if(o[0]==="/")return`url(${g}${Du(t)+o}${g})`;const s=o.split("#")[0],m=o.substring(s.length),l=t.split("#")[0].split("/"),a=s.split("/");l.pop();for(const h of a)h!=="."&&(h===".."?l.pop():l.push(h));return`url(${g}${l.join("/")}${m}${g})`})}function Wr(e,t=!1){return t?e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,""):e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"").replace(/0px/g,"0")}function $u(e,t,r=!1){const i=Array.from(t.childNodes),n=[];let u=0;if(i.length>1&&e&&typeof e=="string"){let c=Wr(e,r);const d=c.length/e.length;for(let o=1;o<i.length;o++)if(i[o].textContent&&typeof i[o].textContent=="string"){const g=Wr(i[o].textContent,r),s=100;let m=3;for(;m<g.length&&(g[m].match(/[a-zA-Z0-9]/)||g.indexOf(g.substring(0,m),1)!==-1);m++);for(;m<g.length;m++){let l=g.substring(0,m),a=c.split(l),h=-1;if(a.length===2)h=a[0].length;else if(a.length>2&&a[0]===""&&i[o-1].textContent!=="")h=c.indexOf(l,1);else if(a.length===1){if(l=l.substring(0,l.length-1),a=c.split(l),a.length<=1)return n.push(e),n;m=s+1}else m===g.length-1&&(h=c.indexOf(l));if(a.length>=2&&m>s){const f=i[o-1].textContent;if(f&&typeof f=="string"){const y=Wr(f).length;h=c.indexOf(l,y)}h===-1&&(h=a[0].length)}if(h!==-1){let f=Math.floor(h/d);for(;f>0&&f<e.length;){if(u+=1,u>50*i.length)return n.push(e),n;const y=Wr(e.substring(0,f),r);if(y.length===h){n.push(e.substring(0,f)),e=e.substring(f),c=c.substring(h);break}else y.length<h?f+=Math.max(1,Math.floor((h-y.length)/d)):f-=Math.max(1,Math.floor((y.length-h)*d))}break}}}}return n.push(e),n}function Bu(e,t){return $u(e,t).join("/* rr_split */")}let Wu=1;const ju=new RegExp("[^a-z0-9-_:]"),cn=-2;function ul(){return Wu++}function zu(e){if(e instanceof HTMLFormElement)return"form";const t=Nt(e.tagName);return ju.test(t)?"div":t}let Gt,ko;const qu=/^[^ \t\n\r\u000c]+/,Hu=/^[, \t\n\r\u000c]+/;function Vu(e,t){if(t.trim()==="")return t;let r=0;function i(u){let c;const d=u.exec(t.substring(r));return d?(c=d[0],r+=c.length,c):""}const n=[];for(;i(Hu),!(r>=t.length);){let u=i(qu);if(u.slice(-1)===",")u=Yt(e,u.substring(0,u.length-1)),n.push(u);else{let c="";u=Yt(e,u);let d=!1;for(;;){const o=t.charAt(r);if(o===""){n.push((u+c).trim());break}else if(d)o===")"&&(d=!1);else if(o===","){r+=1,n.push((u+c).trim());break}else o==="("&&(d=!0);c+=o,r+=1}}}return n.join(", ")}const Ao=new WeakMap;function Yt(e,t){return!t||t.trim()===""?t:hs(e,t)}function Gu(e){return!!(e.tagName==="svg"||e.ownerSVGElement)}function hs(e,t){let r=Ao.get(e);if(r||(r=e.createElement("a"),Ao.set(e,r)),!t)t="";else if(t.startsWith("blob:")||t.startsWith("data:"))return t;return r.setAttribute("href",t),r.href}function dl(e,t,r,i){return i&&(r==="src"||r==="href"&&!(t==="use"&&i[0]==="#")||r==="xlink:href"&&i[0]!=="#"||r==="background"&&["table","td","th"].includes(t)?Yt(e,i):r==="srcset"?Vu(e,i):r==="style"?ln(i,hs(e)):t==="object"&&r==="data"?Yt(e,i):i)}function fl(e,t,r){return["video","audio"].includes(e)&&Nt(t)==="autoplay"}function Xu(e,t,r){try{if(typeof t=="string"){if(e.classList.contains(t))return!0}else for(let i=e.classList.length;i--;){const n=e.classList[i];if(t.test(n))return!0}if(r)return e.matches(r)}catch{}return!1}function un(e,t,r){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return r?un(Ze.parentNode(e),t,r):!1;for(let i=e.classList.length;i--;){const n=e.classList[i];if(t.test(n))return!0}return r?un(Ze.parentNode(e),t,r):!1}function hl(e,t,r,i){let n;if(ol(e)){if(n=e,!Ze.childNodes(n).length)return!1}else{if(Ze.parentElement(e)===null)return!1;n=Ze.parentElement(e)}try{if(typeof t=="string"){if(i){if(n.closest(`.${t}`))return!0}else if(n.classList.contains(t))return!0}else if(un(n,t,i))return!0;if(r){if(i){if(n.closest(r))return!0}else if(n.matches(r))return!0}}catch{}return!1}function Ju(e,t,r){const i=e.contentWindow;if(!i)return;let n=!1,u;try{u=i.document.readyState}catch{return}if(u!=="complete"){const d=setTimeout(()=>{n||(t(),n=!0)},r);e.addEventListener("load",()=>{clearTimeout(d),n=!0,t()});return}const c="about:blank";if(i.location.href!==c||e.src===c||e.src==="")return setTimeout(t,0),e.addEventListener("load",t);e.addEventListener("load",t)}function Yu(e,t,r){let i=!1,n;try{n=e.sheet}catch{return}if(n)return;const u=setTimeout(()=>{i||(t(),i=!0)},r);e.addEventListener("load",()=>{clearTimeout(u),i=!0,t()})}function Ku(e,t){const{doc:r,mirror:i,blockClass:n,blockSelector:u,needsMask:c,inlineStylesheet:d,maskInputOptions:o={},maskTextFn:g,maskInputFn:s,dataURLOptions:m={},inlineImages:l,recordCanvas:a,keepIframeSrcFn:h,newlyAddedElement:f=!1,cssCaptured:y=!1}=t,R=Qu(r,i);switch(e.nodeType){case e.DOCUMENT_NODE:return e.compatMode!=="CSS1Compat"?{type:He.Document,childNodes:[],compatMode:e.compatMode}:{type:He.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:He.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:R};case e.ELEMENT_NODE:return ed(e,{doc:r,blockClass:n,blockSelector:u,inlineStylesheet:d,maskInputOptions:o,maskInputFn:s,dataURLOptions:m,inlineImages:l,recordCanvas:a,keepIframeSrcFn:h,newlyAddedElement:f,rootId:R});case e.TEXT_NODE:return Zu(e,{doc:r,needsMask:c,maskTextFn:g,rootId:R,cssCaptured:y});case e.CDATA_SECTION_NODE:return{type:He.CDATA,textContent:"",rootId:R};case e.COMMENT_NODE:return{type:He.Comment,textContent:Ze.textContent(e)||"",rootId:R};default:return!1}}function Qu(e,t){if(!t.hasNode(e))return;const r=t.getId(e);return r===1?void 0:r}function Zu(e,t){const{needsMask:r,maskTextFn:i,rootId:n,cssCaptured:u}=t,c=Ze.parentNode(e),d=c&&c.tagName;let o="";const g=d==="STYLE"?!0:void 0,s=d==="SCRIPT"?!0:void 0;return s?o="SCRIPT_PLACEHOLDER":u||(o=Ze.textContent(e),g&&o&&(o=ln(o,hs(t.doc)))),!g&&!s&&o&&r&&(o=i?i(o,Ze.parentElement(e)):o.replace(/[\S]/g,"*")),{type:He.Text,textContent:o||"",rootId:n}}function ed(e,t){const{doc:r,blockClass:i,blockSelector:n,inlineStylesheet:u,maskInputOptions:c={},maskInputFn:d,dataURLOptions:o={},inlineImages:g,recordCanvas:s,keepIframeSrcFn:m,newlyAddedElement:l=!1,rootId:a}=t,h=Xu(e,i,n),f=zu(e);let y={};const R=e.attributes.length;for(let w=0;w<R;w++){const S=e.attributes[w];fl(f,S.name,S.value)||(y[S.name]=dl(r,f,Nt(S.name),S.value))}if(f==="link"&&u){const w=Array.from(r.styleSheets).find(v=>v.href===e.href);let S=null;w&&(S=is(w)),S&&(delete y.rel,delete y.href,y._cssText=S)}if(f==="style"&&e.sheet){let w=is(e.sheet);w&&(e.childNodes.length>1&&(w=Bu(w,e)),y._cssText=w)}if(["input","textarea","select"].includes(f)){const w=e.value,S=e.checked;y.type!=="radio"&&y.type!=="checkbox"&&y.type!=="submit"&&y.type!=="button"&&w?y.value=on({element:e,type:an(e),tagName:f,value:w,maskInputOptions:c,maskInputFn:d}):S&&(y.checked=S)}if(f==="option"&&(e.selected&&!c.select?y.selected=!0:delete y.selected),f==="dialog"&&e.open&&(y.rr_open_mode=e.matches("dialog:modal")?"modal":"non-modal"),f==="canvas"&&s){if(e.__context==="2d")Pu(e)||(y.rr_dataURL=e.toDataURL(o.type,o.quality));else if(!("__context"in e)){const w=e.toDataURL(o.type,o.quality),S=r.createElement("canvas");S.width=e.width,S.height=e.height;const v=S.toDataURL(o.type,o.quality);w!==v&&(y.rr_dataURL=w)}}if(f==="img"&&g){Gt||(Gt=r.createElement("canvas"),ko=Gt.getContext("2d"));const w=e,S=w.currentSrc||w.getAttribute("src")||"<unknown-src>",v=w.crossOrigin,E=()=>{w.removeEventListener("load",E);try{Gt.width=w.naturalWidth,Gt.height=w.naturalHeight,ko.drawImage(w,0,0),y.rr_dataURL=Gt.toDataURL(o.type,o.quality)}catch(O){if(w.crossOrigin!=="anonymous"){w.crossOrigin="anonymous",w.complete&&w.naturalWidth!==0?E():w.addEventListener("load",E);return}else console.warn(`Cannot inline img src=${S}! Error: ${O}`)}w.crossOrigin==="anonymous"&&(v?y.crossOrigin=v:w.removeAttribute("crossorigin"))};w.complete&&w.naturalWidth!==0?E():w.addEventListener("load",E)}if(["audio","video"].includes(f)){const w=y;w.rr_mediaState=e.paused?"paused":"played",w.rr_mediaCurrentTime=e.currentTime,w.rr_mediaPlaybackRate=e.playbackRate,w.rr_mediaMuted=e.muted,w.rr_mediaLoop=e.loop,w.rr_mediaVolume=e.volume}if(l||(e.scrollLeft&&(y.rr_scrollLeft=e.scrollLeft),e.scrollTop&&(y.rr_scrollTop=e.scrollTop)),h){const{width:w,height:S}=e.getBoundingClientRect();y={class:y.class,rr_width:`${w}px`,rr_height:`${S}px`}}f==="iframe"&&!m(y.src)&&(e.contentDocument||(y.rr_src=y.src),delete y.src);let x;try{customElements.get(f)&&(x=!0)}catch{}return{type:He.Element,tagName:f,attributes:y,childNodes:[],isSVG:Gu(e)||void 0,needBlock:h,rootId:a,isCustom:x}}function De(e){return e==null?"":e.toLowerCase()}function pl(e){return e===!0||e==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:e==="all",headMetaDescKeywords:e==="all",headTitleMutations:e==="all"}:e||{}}function td(e,t){if(t.comment&&e.type===He.Comment)return!0;if(e.type===He.Element){if(t.script&&(e.tagName==="script"||e.tagName==="link"&&(e.attributes.rel==="preload"&&e.attributes.as==="script"||e.attributes.rel==="modulepreload")||e.tagName==="link"&&e.attributes.rel==="prefetch"&&typeof e.attributes.href=="string"&&cl(e.attributes.href)==="js"))return!0;if(t.headFavicon&&(e.tagName==="link"&&e.attributes.rel==="shortcut icon"||e.tagName==="meta"&&(De(e.attributes.name).match(/^msapplication-tile(image|color)$/)||De(e.attributes.name)==="application-name"||De(e.attributes.rel)==="icon"||De(e.attributes.rel)==="apple-touch-icon"||De(e.attributes.rel)==="shortcut icon")))return!0;if(e.tagName==="meta"){if(t.headMetaDescKeywords&&De(e.attributes.name).match(/^description|keywords$/))return!0;if(t.headMetaSocial&&(De(e.attributes.property).match(/^(og|twitter|fb):/)||De(e.attributes.name).match(/^(og|twitter):/)||De(e.attributes.name)==="pinterest"))return!0;if(t.headMetaRobots&&(De(e.attributes.name)==="robots"||De(e.attributes.name)==="googlebot"||De(e.attributes.name)==="bingbot"))return!0;if(t.headMetaHttpEquiv&&e.attributes["http-equiv"]!==void 0)return!0;if(t.headMetaAuthorship&&(De(e.attributes.name)==="author"||De(e.attributes.name)==="generator"||De(e.attributes.name)==="framework"||De(e.attributes.name)==="publisher"||De(e.attributes.name)==="progid"||De(e.attributes.property).match(/^article:/)||De(e.attributes.property).match(/^product:/)))return!0;if(t.headMetaVerification&&(De(e.attributes.name)==="google-site-verification"||De(e.attributes.name)==="yandex-verification"||De(e.attributes.name)==="csrf-token"||De(e.attributes.name)==="p:domain_verify"||De(e.attributes.name)==="verify-v1"||De(e.attributes.name)==="verification"||De(e.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Kt(e,t){const{doc:r,mirror:i,blockClass:n,blockSelector:u,maskTextClass:c,maskTextSelector:d,skipChild:o=!1,inlineStylesheet:g=!0,maskInputOptions:s={},maskTextFn:m,maskInputFn:l,slimDOMOptions:a,dataURLOptions:h={},inlineImages:f=!1,recordCanvas:y=!1,onSerialize:R,onIframeLoad:x,iframeLoadTimeout:w=5e3,onStylesheetLoad:S,stylesheetLoadTimeout:v=5e3,keepIframeSrcFn:E=()=>!1,newlyAddedElement:O=!1,cssCaptured:A=!1}=t;let{needsMask:k}=t,{preserveWhiteSpace:N=!0}=t;k||(k=hl(e,c,d,k===void 0));const _=Ku(e,{doc:r,mirror:i,blockClass:n,blockSelector:u,needsMask:k,inlineStylesheet:g,maskInputOptions:s,maskTextFn:m,maskInputFn:l,dataURLOptions:h,inlineImages:f,recordCanvas:y,keepIframeSrcFn:E,newlyAddedElement:O,cssCaptured:A});if(!_)return console.warn(e,"not serialized"),null;let z;i.hasNode(e)?z=i.getId(e):td(_,a)||!N&&_.type===He.Text&&!_.textContent.replace(/^\s+|\s+$/gm,"").length?z=cn:z=ul();const T=Object.assign(_,{id:z});if(i.add(e,T),z===cn)return null;R&&R(e);let ye=!o;if(T.type===He.Element){ye=ye&&!T.needBlock,delete T.needBlock;const se=Ze.shadowRoot(e);se&&fr(se)&&(T.isShadowHost=!0)}if((T.type===He.Document||T.type===He.Element)&&ye){a.headWhitespace&&T.type===He.Element&&T.tagName==="head"&&(N=!1);const se={doc:r,mirror:i,blockClass:n,blockSelector:u,needsMask:k,maskTextClass:c,maskTextSelector:d,skipChild:o,inlineStylesheet:g,maskInputOptions:s,maskTextFn:m,maskInputFn:l,slimDOMOptions:a,dataURLOptions:h,inlineImages:f,recordCanvas:y,preserveWhiteSpace:N,onSerialize:R,onIframeLoad:x,iframeLoadTimeout:w,onStylesheetLoad:S,stylesheetLoadTimeout:v,keepIframeSrcFn:E,cssCaptured:!1};if(!(T.type===He.Element&&T.tagName==="textarea"&&T.attributes.value!==void 0)){T.type===He.Element&&T.attributes._cssText!==void 0&&typeof T.attributes._cssText=="string"&&(se.cssCaptured=!0);for(const pe of Array.from(Ze.childNodes(e))){const Ie=Kt(pe,se);Ie&&T.childNodes.push(Ie)}}let ie=null;if(ol(e)&&(ie=Ze.shadowRoot(e)))for(const pe of Array.from(Ze.childNodes(ie))){const Ie=Kt(pe,se);Ie&&(fr(ie)&&(Ie.isShadow=!0),T.childNodes.push(Ie))}}const be=Ze.parentNode(e);return be&&dr(be)&&fr(be)&&(T.isShadow=!0),T.type===He.Element&&T.tagName==="iframe"&&Ju(e,()=>{const se=e.contentDocument;if(se&&x){const ie=Kt(se,{doc:se,mirror:i,blockClass:n,blockSelector:u,needsMask:k,maskTextClass:c,maskTextSelector:d,skipChild:!1,inlineStylesheet:g,maskInputOptions:s,maskTextFn:m,maskInputFn:l,slimDOMOptions:a,dataURLOptions:h,inlineImages:f,recordCanvas:y,preserveWhiteSpace:N,onSerialize:R,onIframeLoad:x,iframeLoadTimeout:w,onStylesheetLoad:S,stylesheetLoadTimeout:v,keepIframeSrcFn:E});ie&&x(e,ie)}},w),T.type===He.Element&&T.tagName==="link"&&typeof T.attributes.rel=="string"&&(T.attributes.rel==="stylesheet"||T.attributes.rel==="preload"&&typeof T.attributes.href=="string"&&cl(T.attributes.href)==="css")&&Yu(e,()=>{if(S){const se=Kt(e,{doc:r,mirror:i,blockClass:n,blockSelector:u,needsMask:k,maskTextClass:c,maskTextSelector:d,skipChild:!1,inlineStylesheet:g,maskInputOptions:s,maskTextFn:m,maskInputFn:l,slimDOMOptions:a,dataURLOptions:h,inlineImages:f,recordCanvas:y,preserveWhiteSpace:N,onSerialize:R,onIframeLoad:x,iframeLoadTimeout:w,onStylesheetLoad:S,stylesheetLoadTimeout:v,keepIframeSrcFn:E});se&&S(e,se)}},v),T}function rd(e,t){const{mirror:r=new ll,blockClass:i="rr-block",blockSelector:n=null,maskTextClass:u="rr-mask",maskTextSelector:c=null,inlineStylesheet:d=!0,inlineImages:o=!1,recordCanvas:g=!1,maskAllInputs:s=!1,maskTextFn:m,maskInputFn:l,slimDOM:a=!1,dataURLOptions:h,preserveWhiteSpace:f,onSerialize:y,onIframeLoad:R,iframeLoadTimeout:x,onStylesheetLoad:w,stylesheetLoadTimeout:S,keepIframeSrcFn:v=()=>!1}=t,E=s===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:s===!1?{password:!0}:s,O=pl(a);return Kt(e,{doc:e,mirror:r,blockClass:i,blockSelector:n,maskTextClass:u,maskTextSelector:c,skipChild:!1,inlineStylesheet:d,maskInputOptions:E,maskTextFn:m,maskInputFn:l,slimDOMOptions:O,dataURLOptions:h,inlineImages:o,recordCanvas:g,preserveWhiteSpace:f,onSerialize:y,onIframeLoad:R,iframeLoadTimeout:x,onStylesheetLoad:w,stylesheetLoadTimeout:S,keepIframeSrcFn:v,newlyAddedElement:!1})}function nd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function id(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function i(){return this instanceof i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(i){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(r,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}),r}var jr={exports:{}},To;function sd(){if(To)return jr.exports;To=1;var e=String,t=function(){return{isColorSupported:!1,reset:e,bold:e,dim:e,italic:e,underline:e,inverse:e,hidden:e,strikethrough:e,black:e,red:e,green:e,yellow:e,blue:e,magenta:e,cyan:e,white:e,gray:e,bgBlack:e,bgRed:e,bgGreen:e,bgYellow:e,bgBlue:e,bgMagenta:e,bgCyan:e,bgWhite:e}};return jr.exports=t(),jr.exports.createColors=t,jr.exports}const od={},ad=Object.freeze(Object.defineProperty({__proto__:null,default:od},Symbol.toStringTag,{value:"Module"})),mt=id(ad);var Xn,Po;function ps(){if(Po)return Xn;Po=1;let e=sd(),t=mt;class r extends Error{constructor(n,u,c,d,o,g){super(n),this.name="CssSyntaxError",this.reason=n,o&&(this.file=o),d&&(this.source=d),g&&(this.plugin=g),typeof u<"u"&&typeof c<"u"&&(typeof u=="number"?(this.line=u,this.column=c):(this.line=u.line,this.column=u.column,this.endLine=c.line,this.endColumn=c.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,r)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",typeof this.line<"u"&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(n){if(!this.source)return"";let u=this.source;n==null&&(n=e.isColorSupported),t&&n&&(u=t(u));let c=u.split(/\r?\n/),d=Math.max(this.line-3,0),o=Math.min(this.line+2,c.length),g=String(o).length,s,m;if(n){let{bold:l,gray:a,red:h}=e.createColors(!0);s=f=>l(h(f)),m=f=>a(f)}else s=m=l=>l;return c.slice(d,o).map((l,a)=>{let h=d+1+a,f=" "+(" "+h).slice(-g)+" | ";if(h===this.line){let y=m(f.replace(/\d/g," "))+l.slice(0,this.column-1).replace(/[^\t]/g," ");return s(">")+m(f)+l+`
3
3
  `+y+s("^")}return" "+m(f)+l}).join(`
4
4
  `)}toString(){let n=this.showSourceCode();return n&&(n=`
@@ -1,4 +1,4 @@
1
- import{p as kf}from"./page-workers-BUcWBF51.js";import{b as kj,D as Aj,u as V8,a as Z8,F as Y8,c as Cj,d as Tj,M as y6,e as vN,r as g2,f as $j,w as Nj,g as Rj,h as Ka,B as Af,i as Ts,j as fa,k as mf,S as xN,O as SN,l as EN,m as kN,o as b6,n as AN,v as CN,p as TN,q as up,s as $N,t as Oj,x as $1,y as _j,z as y2,A as X8,C as Ij,E as Mj,G as Dj,H as Lj,I as Pj,J as Uj,K as Fj,L as Bj,N as zj,P as pg,Q as K8,R as NN,T as jj,U as RN,V as N1,W as Wj,X as Hj,Y as qj,Z as Gj,_ as mg,$ as Q8,a0 as Vj,a1 as Zj,a2 as Yj,a3 as Xj,a4 as Kj}from"./browser-sandbox-bridge-CmMlTDpO.js";import{C as Qj}from"./cross-origin-container-protocol-hIp9vH-t.js";const Jj=1,eW="blender",tW="Blender",rW="5.2.0",nW="wali",sW={url:"/blender/5.2.0/fbe62287-54323db8/blender.wasm",integrity:"sha256-VDI9uO1b2cxjqRRUwLf8HJw7N3ZkWfY0aSDog1XmCxA=",upstream:"https://projects.blender.org/blender/blender",license:"GPL-2.0-or-later",redistribution:"cleared"},iW="blender",aW={start:["blender","--version"]},oW={home:"${HOME}/.blender",privateFiles:[]},lW={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",BLENDER_SYSTEM_RESOURCES:"/opt/programs/blender/5.2.0",BLENDER_SYSTEM_SCRIPTS:"/opt/programs/blender/5.2.0/scripts",BLENDER_SYSTEM_DATAFILES:"/opt/programs/blender/5.2.0/datafiles",BLENDER_SYSTEM_PYTHON:"/opt/programs/blender/5.2.0/python",PYTHONPATH:"/opt/programs/blender/5.2.0/python/lib/numpy313.zip:/opt/programs/blender/5.2.0/python/lib/wheels313.zip",TMPDIR:"/tmp",VGAI_PRESENTER_ROOT:"/tmp/vgai-presenter",VGAI_EXPORT_BUFFER_PATH:"/tmp/vgai-presenter/arena.bin",OPENIMAGEIO_THREADS:"1"},cW={capabilities:["filesystem.project","threads.pthread"],programs:["wali"],workers:16},uW={input:"bytes"},fW={allowedHosts:[]},dW=[],hW={url:"/blender/5.2.0/fbe62287-c897ea1a/blender-resources.zip",integrity:"sha256-vwqwbrnOvoIQu3366ENlAGa/fLJ15nfoTqA36XDsFrI=",root:"/opt/programs/blender/5.2.0"},pW={url:"/blender/5.2.0/fbe62287-f3551ac5/blender-three.mjs",integrity:"sha256-81Uaxf5dret1seLjYQHEvuFGK/dUU6hBZkW71fyTng8=",bytes:6110908},mW={schemaVersion:Jj,id:eW,displayName:tW,version:rW,engine:nW,artifact:sW,executable:iW,actions:aW,storage:oW,environment:lW,requirements:cW,terminal:uW,network:fW,openUrls:dW,resources:hW,presenter:pW},gW=1,yW="codex",bW="Codex CLI",wW="0.151.0",vW="wali",xW={url:"/codex/0.151.0/78c29080-7b58fe3e/codex.wasm",integrity:"sha256-e1j+PgqECkgNTy8lOtcWzoLVRNd2ez2sbULSE7E29GM=",upstream:"https://github.com/openai/codex",license:"Apache-2.0",redistribution:"cleared"},SW="codex",EW={start:["codex","--model","gpt-5.4","--sandbox","danger-full-access"],login:["codex","login","--device-auth"],logout:["codex","logout"]},kW={home:"${HOME}/.codex",privateFiles:[{path:"${HOME}/.codex/auth.json",vault:"codex-cli-auth",clearOnActions:["logout"]},{path:"${HOME}/.codex/config.toml",vault:"codex-cli-config",defaultContent:`cli_auth_credentials_store = "file"
1
+ import{p as kf}from"./page-workers-BUcWBF51.js";import{b as kj,D as Aj,u as V8,a as Z8,F as Y8,c as Cj,d as Tj,M as y6,e as vN,r as g2,f as $j,w as Nj,g as Rj,h as Ka,B as Af,i as Ts,j as fa,k as mf,S as xN,O as SN,l as EN,m as kN,o as b6,n as AN,v as CN,p as TN,q as up,s as $N,t as Oj,x as $1,y as _j,z as y2,A as X8,C as Ij,E as Mj,G as Dj,H as Lj,I as Pj,J as Uj,K as Fj,L as Bj,N as zj,P as pg,Q as K8,R as NN,T as jj,U as RN,V as N1,W as Wj,X as Hj,Y as qj,Z as Gj,_ as mg,$ as Q8,a0 as Vj,a1 as Zj,a2 as Yj,a3 as Xj,a4 as Kj}from"./browser-sandbox-bridge-BOyO6Vq0.js";import{C as Qj}from"./cross-origin-container-protocol-hIp9vH-t.js";const Jj=1,eW="blender",tW="Blender",rW="5.2.0",nW="wali",sW={url:"/blender/5.2.0/fbe62287-54323db8/blender.wasm",integrity:"sha256-VDI9uO1b2cxjqRRUwLf8HJw7N3ZkWfY0aSDog1XmCxA=",upstream:"https://projects.blender.org/blender/blender",license:"GPL-2.0-or-later",redistribution:"cleared"},iW="blender",aW={start:["blender","--version"]},oW={home:"${HOME}/.blender",privateFiles:[]},lW={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",BLENDER_SYSTEM_RESOURCES:"/opt/programs/blender/5.2.0",BLENDER_SYSTEM_SCRIPTS:"/opt/programs/blender/5.2.0/scripts",BLENDER_SYSTEM_DATAFILES:"/opt/programs/blender/5.2.0/datafiles",BLENDER_SYSTEM_PYTHON:"/opt/programs/blender/5.2.0/python",PYTHONPATH:"/opt/programs/blender/5.2.0/python/lib/numpy313.zip:/opt/programs/blender/5.2.0/python/lib/wheels313.zip",TMPDIR:"/tmp",VGAI_PRESENTER_ROOT:"/tmp/vgai-presenter",VGAI_EXPORT_BUFFER_PATH:"/tmp/vgai-presenter/arena.bin",OPENIMAGEIO_THREADS:"1"},cW={capabilities:["filesystem.project","threads.pthread"],programs:["wali"],workers:16},uW={input:"bytes"},fW={allowedHosts:[]},dW=[],hW={url:"/blender/5.2.0/fbe62287-c897ea1a/blender-resources.zip",integrity:"sha256-vwqwbrnOvoIQu3366ENlAGa/fLJ15nfoTqA36XDsFrI=",root:"/opt/programs/blender/5.2.0"},pW={url:"/blender/5.2.0/fbe62287-f3551ac5/blender-three.mjs",integrity:"sha256-81Uaxf5dret1seLjYQHEvuFGK/dUU6hBZkW71fyTng8=",bytes:6110908},mW={schemaVersion:Jj,id:eW,displayName:tW,version:rW,engine:nW,artifact:sW,executable:iW,actions:aW,storage:oW,environment:lW,requirements:cW,terminal:uW,network:fW,openUrls:dW,resources:hW,presenter:pW},gW=1,yW="codex",bW="Codex CLI",wW="0.151.0",vW="wali",xW={url:"/codex/0.151.0/78c29080-7b58fe3e/codex.wasm",integrity:"sha256-e1j+PgqECkgNTy8lOtcWzoLVRNd2ez2sbULSE7E29GM=",upstream:"https://github.com/openai/codex",license:"Apache-2.0",redistribution:"cleared"},SW="codex",EW={start:["codex","--model","gpt-5.4","--sandbox","danger-full-access"],login:["codex","login","--device-auth"],logout:["codex","logout"]},kW={home:"${HOME}/.codex",privateFiles:[{path:"${HOME}/.codex/auth.json",vault:"codex-cli-auth",clearOnActions:["logout"]},{path:"${HOME}/.codex/config.toml",vault:"codex-cli-config",defaultContent:`cli_auth_credentials_store = "file"
2
2
  `}]},AW={HOME:"${HOME}",CODEX_HOME:"${HOME}/.codex",PATH:"/usr/local/bin:/usr/bin:/bin",TERM:"xterm-256color",TOKIO_WORKER_THREADS:"1"},CW={capabilities:["browser.open-url","filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],programs:["git","node","npm","vite","wali"],workers:32},TW={input:"bytes"},$W={relayPath:"/api/wali/tcp",allowedHosts:["api.openai.com","auth.openai.com","chat.openai.com","chatgpt.com"]},NW=[{protocol:"https:",hostname:"auth.openai.com",pathname:"/codex/device"}],RW={schemaVersion:gW,id:yW,displayName:bW,version:wW,engine:vW,artifact:xW,executable:SW,actions:EW,storage:kW,environment:AW,requirements:CW,terminal:TW,network:$W,openUrls:NW},OW=1,_W="ffprobe",IW="ffprobe",MW="9.0.1",DW="wali",LW={url:"/ffprobe/9.0.1/bf1b838f-99dc0c0c/ffprobe.wasm",integrity:"sha256-mdwMDDTRcYQdFSAqcerAR08HkUxL4mdjCF4OkEcusPI=",upstream:"https://github.com/FFmpeg/FFmpeg",license:"LGPL-2.1-or-later",redistribution:"cleared"},PW="ffprobe",UW={start:["ffprobe","-version"]},FW={home:"${HOME}/.ffmpeg",privateFiles:[]},BW={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin"},zW={capabilities:["filesystem.project","media.webcodecs","threads.pthread"],programs:["wali"],workers:32},jW={input:"bytes"},WW={allowedHosts:[]},HW=[],qW={schemaVersion:OW,id:_W,displayName:IW,version:MW,engine:DW,artifact:LW,executable:PW,actions:UW,storage:FW,environment:BW,requirements:zW,terminal:jW,network:WW,openUrls:HW},GW=1,VW="ffmpeg",ZW="FFmpeg",YW="9.0.1",XW="wali",KW={url:"/ffmpeg/9.0.1/bf1b838f-91cb6c14/ffmpeg.wasm",integrity:"sha256-kctsFB9F1jrSTZKAU2TwLVuC3MUao3GhTph/ILE0Wv4=",upstream:"https://github.com/FFmpeg/FFmpeg",license:"LGPL-2.1-or-later",redistribution:"cleared"},QW="ffmpeg",JW={start:["ffmpeg","-version"]},eH={home:"${HOME}/.ffmpeg",privateFiles:[]},tH={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin"},rH={capabilities:["filesystem.project","media.webcodecs","threads.pthread"],programs:["wali"],workers:32},nH={input:"bytes"},sH={allowedHosts:[]},iH=[],aH={schemaVersion:GW,id:VW,displayName:ZW,version:YW,engine:XW,artifact:KW,executable:QW,actions:JW,storage:eH,environment:tH,requirements:rH,terminal:nH,network:sH,openUrls:iH},oH=1,lH="git",cH="Git",uH="2.55.0",fH="wali",dH={url:"/git/2.55.0/457fdb04-a140f348/git.wasm",integrity:"sha256-oUDzSHWZCggKhKYaxX6eqSTnuNefDdOhtCQhOc3WqOQ=",upstream:"https://www.kernel.org/pub/software/scm/git/",license:"GPL-2.0-only",redistribution:"cleared"},hH="git",pH={start:["git","--version"]},mH={home:"${HOME}/.config/git",privateFiles:[]},gH={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",GIT_EXEC_PATH:"/opt/programs/git/2.55.0/git-core",GIT_TEMPLATE_DIR:"/opt/programs/git/2.55.0/git-core/templates"},yH={capabilities:["filesystem.project","process.spawn","threads.pthread"],programs:["wali"],workers:32},bH={input:"bytes"},wH={allowedHosts:[]},vH=[],xH={url:"/git/2.55.0/457fdb04-e085996d/git-resources.zip",integrity:"sha256-YN1v7wT9s96XxkR4V0rVij7Jz/cB2FZwk4FtrTJyZKs=",root:"/opt/programs/git/2.55.0/git-core"},SH={schemaVersion:oH,id:lH,displayName:cH,version:uH,engine:fH,artifact:dH,executable:hH,actions:pH,storage:mH,environment:gH,requirements:yH,terminal:bH,network:wH,openUrls:vH,resources:xH},EH=1,kH="gitlens",AH="GitLens",CH="2026.9.190513",TH="node",$H={url:"/gitlens/2026.9.190513/b90b6934-9461a1f3/gitlens.zip",integrity:"sha256-lGGh80wH0+azA7pfqu8eFb95WbTHzSYDA8zTjwzAn6E=",upstream:"https://github.com/gitkraken/vscode-gitlens",license:"MIT",redistribution:"cleared"},NH="gitlens",RH={start:["-e","process.stdout.write('gitlens placed')"]},OH={home:"${HOME}/.openvscode-server",privateFiles:[]},_H={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",GITLENS_ROOT:"/opt/programs/gitlens/2026.9.190513"},IH={capabilities:["filesystem.project"],programs:["node","git"]},MH={input:"bytes"},DH={allowedHosts:["api.github.com","api.gitkraken.dev","configs.gitkraken.dev","github.com","gitkraken.com","gitkraken.dev","slack.gitkraken.com"]},LH=[],PH={url:"/gitlens/2026.9.190513/b90b6934-61608219/gitlens-resources.zip",integrity:"sha256-YWCCGc7mnBZTQ2ze9bnAy8NDEYXCqinw2BINaNUkYrA=",root:"/opt/programs/gitlens/2026.9.190513"},UH={schemaVersion:EH,id:kH,displayName:AH,version:CH,engine:TH,artifact:$H,executable:NH,actions:RH,storage:OH,environment:_H,requirements:IH,terminal:MH,network:DH,openUrls:LH,resources:PH},FH=1,BH="grok",zH="Grok CLI",jH="1.0.10",WH="wali",HH={url:"/grok/1.0.10/9684fa3c-894eeadb/xai-grok-pager.wasm",integrity:"sha256-iU7q28AqktlhlVc8mG+AQDI/UScbz+88wTMwJgmSScI=",upstream:"https://github.com/xai-org/grok-build",license:"Apache-2.0",redistribution:"cleared"},qH="grok",GH={start:["grok"],login:["grok","login","--device-auth"],logout:["grok","logout"]},VH={home:"${HOME}/.grok",privateFiles:[{path:"${HOME}/.grok/auth.json",vault:"grok-cli-auth",clearOnActions:["logout"]},{path:"${HOME}/.grok/config.toml",vault:"grok-cli-config"}]},ZH={HOME:"${HOME}",GROK_HOME:"${HOME}/.grok",PATH:"/usr/local/bin:/usr/bin:/bin",TERM:"xterm-256color",GROK_MEMTRACE:"0",GROK_WORKER_THREADS:"1",GROK_TELEMETRY_ENABLED:"false",GROK_OTEL_FILTER:"off"},YH={capabilities:["browser.open-url","filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],programs:["git","node","npm","vite","wali"],workers:64},XH={input:"kitty-key-events"},KH={relayPath:"/api/wali/tcp",allowedHosts:["api.x.ai","assets.grok.com","auth.x.ai","cli-chat-proxy.grok.com","code.grok.com","grok.com","storage.googleapis.com","x.ai"]},QH=[{protocol:"https:",hostname:"accounts.x.ai",pathname:"/oauth2/device"}],JH={schemaVersion:FH,id:BH,displayName:zH,version:jH,engine:WH,artifact:HH,executable:qH,actions:GH,storage:VH,environment:ZH,requirements:YH,terminal:XH,network:KH,openUrls:QH},eq=1,tq="openvscode-server",rq="OpenVSCode Server",nq="1.109.5",sq="node",iq={url:"/openvscode-server/1.109.5/07258626-29f7eb3e/openvscode-server.zip",integrity:"sha256-KffrPuEdRoxlP1byAy38mDQV8PrdponITCcwMRXzSR4=",upstream:"https://github.com/gitpod-io/openvscode-server",license:"MIT",redistribution:"cleared"},aq="openvscode-server",oq={start:["/opt/programs/openvscode-server/1.109.5/out/server-main.js","--host","127.0.0.1","--port","0","--without-connection-token","--server-data-dir","/home/user/.openvscode-server","--default-folder","/workspace","--disable-telemetry"]},lq={home:"${HOME}/.openvscode-server",privateFiles:[]},cq={HOME:"${HOME}",SHELL:"/bin/sh",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VSCODE_CWD:"/opt/programs/openvscode-server/1.109.5"},uq={capabilities:["filesystem.project"],programs:["node","git","sh"]},fq={input:"bytes"},dq={allowedHosts:["open-vsx.org"],httpTransportPolicy:{url:"/openvscode-server/1.109.5/07258626-2e53744a/http-transport-policy.json",integrity:"sha256-LlN0SrN32XKdawOsvZn40BSBC8HRWLtjGiIoFakTrcw="}},hq=[],pq={url:"/openvscode-server/1.109.5/07258626-28b7a378/openvscode-server-resources.zip",integrity:"sha256-KLejeHRuJD73HKrGt7UbFCi6+0vzYFqXxZ3udAk2RjI=",root:"/opt/programs/openvscode-server/1.109.5"},mq={schemaVersion:eq,id:tq,displayName:rq,version:nq,engine:sq,artifact:iq,executable:aq,actions:oq,storage:lq,environment:cq,requirements:uq,terminal:fq,network:dq,openUrls:hq,resources:pq},gq=1,yq="pi",bq="Pi",wq="0.87.1",vq="node",xq={url:"/pi/0.87.1/f07218c4-66de9250/pi.zip",integrity:"sha256-Zt6SUNC6igr4EhkUVV79dm+AGwlIvwbiBOLv5lFPVt4=",upstream:"https://github.com/earendil-works/pi",license:"MIT",redistribution:"cleared"},Sq="pi",Eq={start:["/opt/programs/pi/0.87.1/node_modules/@earendil-works/pi-coding-agent/dist/cli.js"]},kq={home:"${HOME}/.pi",privateFiles:[]},Aq={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",PI_ROOT:"/opt/programs/pi/0.87.1"},Cq={capabilities:["filesystem.project"],programs:["node","sh"]},Tq={input:"bytes"},$q={allowedHosts:[]},Nq=[],Rq={url:"/pi/0.87.1/f07218c4-22a14a3e/pi-resources.zip",integrity:"sha256-IqFKPoZ5lLwimkJdQ2YwV4XGFR72LXhULTr+M5laULc=",root:"/opt/programs/pi/0.87.1"},Oq={schemaVersion:gq,id:yq,displayName:bq,version:wq,engine:vq,artifact:xq,executable:Sq,actions:Eq,storage:kq,environment:Aq,requirements:Cq,terminal:Tq,network:$q,openUrls:Nq,resources:Rq},_q=1,Iq="supercode",Mq="Volter Harness",Dq="0.4.57",Lq="wali",Pq={url:"/supercode/0.4.57/74e379df-7c2abf71/supercode.wasm",integrity:"sha256-fCq/cV9phC80o3L8gSbiopN/Bm73jU0fTe9HbG/O228=",upstream:"https://github.com/volter-ai/supercode",license:"MIT",redistribution:"cleared"},Uq="supercode",Fq={start:["supercode","chat"],loader:["supercode","harness","serve"],login:["supercode","login"],logout:["supercode","logout"]},Bq={home:"${HOME}/.config/supercode",privateFiles:[{path:"${HOME}/.config/supercode/config.toml",vault:"supercode-config",clearOnActions:["logout"]},{path:"${HOME}/.config/supercode/credentials.toml",vault:"supercode-credentials",clearOnActions:["logout"]}]},zq={HOME:"${HOME}",XDG_CONFIG_HOME:"${HOME}/.config",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",TERM:"xterm-256color"},jq={capabilities:["filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],programs:["git","node","npm","vite","wali"],workers:32},Wq={input:"canonical-lines"},Hq={relayPath:"/api/wali/tcp",allowedHosts:["openrouter.ai"]},qq=[],Gq={schemaVersion:_q,id:Iq,displayName:Mq,version:Dq,engine:Lq,artifact:Pq,executable:Uq,actions:Fq,storage:Bq,environment:zq,requirements:jq,terminal:Wq,network:Hq,openUrls:qq},Vq=1,Zq="supercode",Yq="Volter Harness",Xq="0.4.68",Kq="wali",Qq={url:"/supercode/0.4.68/6d1f3f0c-f0db006e/supercode.wasm",integrity:"sha256-8NsAbubpTiLpW9dd+HxTZ8JBeu/WoBemO39ypduNCvY=",upstream:"https://github.com/volter-ai/supercode",license:"MIT",redistribution:"cleared"},Jq="supercode",eG={start:["supercode","chat"],loader:["supercode","harness","serve"],login:["supercode","login"],logout:["supercode","logout"]},tG={home:"${HOME}/.config/supercode",privateFiles:[{path:"${HOME}/.config/supercode/config.toml",vault:"supercode-config",clearOnActions:["logout"]},{path:"${HOME}/.config/supercode/credentials.toml",vault:"supercode-credentials",clearOnActions:["logout"]}]},rG={HOME:"${HOME}",XDG_CONFIG_HOME:"${HOME}/.config",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",TERM:"xterm-256color"},nG={capabilities:["filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"],programs:["git","node","npm","vite","wali"],workers:32},sG={input:"canonical-lines"},iG={relayPath:"/api/wali/tcp",allowedHosts:["openrouter.ai"]},aG=[],oG={schemaVersion:Vq,id:Zq,displayName:Yq,version:Xq,engine:Kq,artifact:Qq,executable:Jq,actions:eG,storage:tG,environment:rG,requirements:nG,terminal:sG,network:iG,openUrls:aG},lG=1,cG="valkey",uG="Valkey",fG="9.1.1",dG="node",hG={url:"/valkey/9.1.1/60e471da-75f33eaf/valkey.zip",integrity:"sha256-dfM+r67meqtqcDFtNGcbbUM3j0MtLWjlMbBIzKK3nuo=",upstream:"https://github.com/michaelkremenetsky/valkey-wasm",license:"BSD-3-Clause",redistribution:"cleared"},pG="valkey-server",mG={start:["/opt/programs/valkey/9.1.1/bin/valkey-server.mjs","--port","6379"]},gG={home:"${HOME}/.valkey",privateFiles:[]},yG={HOME:"${HOME}",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VALKEY_HOME:"/opt/programs/valkey/9.1.1"},bG={capabilities:[],programs:["node"]},wG={input:"bytes"},vG={allowedHosts:[]},xG=[],SG={url:"/valkey/9.1.1/60e471da-21e19cf0/valkey-resources.zip",integrity:"sha256-IeGc8BrPH6eiUs5aWSgeEeqZqbCvWIjOH99Ma8Ey4zQ=",root:"/opt/programs/valkey/9.1.1"},EG={schemaVersion:lG,id:cG,displayName:uG,version:fG,engine:dG,artifact:hG,executable:pG,actions:mG,storage:gG,environment:yG,requirements:bG,terminal:wG,network:vG,openUrls:xG,resources:SG},kG=1,AG="volter-game-editor-workbench",CG="Volter Game Editor workbench",TG="0.5.65",$G="node",NG={url:"/volter-game-editor-workbench/0.5.65/9ef15b1f-af68aba2/volter-game-editor-workbench.zip",integrity:"sha256-r2iroutlBhAOQAGDPXBiHohurp6nIhIlmnFwytapcks=",upstream:"https://github.com/volter-ai/code-oss",license:"MIT",redistribution:"cleared"},RG="code-server-oss",OG={start:["/opt/programs/volter-game-editor-workbench/0.5.65/vscode-reh-web-darwin-arm64/out/server-main.js","--host","127.0.0.1","--port","0","--without-connection-token"]},_G={home:"${HOME}/.vscode-server-oss",privateFiles:[]},IG={HOME:"${HOME}",SHELL:"/bin/sh",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VSCODE_CWD:"/opt/programs/volter-game-editor-workbench/0.5.65/vscode-reh-web-darwin-arm64",VOLTER_EDITOR_WORKBENCH_ROOT:"/opt/programs/volter-game-editor-workbench/0.5.65"},MG={capabilities:["filesystem.project"],programs:["node","git","sh"]},DG={input:"bytes"},LG={allowedHosts:[]},PG=[],UG={url:"/volter-game-editor-workbench/0.5.65/9ef15b1f-b499f656/volter-game-editor-workbench-resources.zip",integrity:"sha256-tJn2VgJZ6imhm71f7DXpoZEn57IuvI/9UrRcqoCoebk=",root:"/opt/programs/volter-game-editor-workbench/0.5.65"},FG={schemaVersion:kG,id:AG,displayName:CG,version:TG,engine:$G,artifact:NG,executable:RG,actions:OG,storage:_G,environment:IG,requirements:MG,terminal:DG,network:LG,openUrls:PG,resources:UG},BG=1,zG="volter-model-editor-workbench",jG="Volter Model Editor workbench",WG="0.5.132",HG="node",qG={url:"/volter-model-editor-workbench/0.5.132/f16dc165-b5a7f34d/volter-model-editor-workbench.zip",integrity:"sha256-tafzTfd6HeArQI5SH7Xsh6bAxrLD3m37TxNGYDNx1kQ=",upstream:"https://github.com/volter-ai/code-oss",license:"MIT",redistribution:"cleared"},GG="code-server-oss",VG={start:["/opt/programs/volter-model-editor-workbench/0.5.132/vscode-reh-web-darwin-arm64/out/server-main.js","--host","127.0.0.1","--port","0","--without-connection-token"]},ZG={home:"${HOME}/.vscode-server-oss",privateFiles:[]},YG={HOME:"${HOME}",SHELL:"/bin/sh",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VSCODE_CWD:"/opt/programs/volter-model-editor-workbench/0.5.132/vscode-reh-web-darwin-arm64",VOLTER_EDITOR_WORKBENCH_ROOT:"/opt/programs/volter-model-editor-workbench/0.5.132"},XG={capabilities:["filesystem.project"],programs:["node","git","sh"]},KG={input:"bytes"},QG={allowedHosts:[]},JG=[],eV={url:"/volter-model-editor-workbench/0.5.132/f16dc165-deec2a31/volter-model-editor-workbench-resources.zip",integrity:"sha256-3uwqMWo8vZU943GXyQtzt1HfojJDWx3ahVnL8RhN2Ko=",root:"/opt/programs/volter-model-editor-workbench/0.5.132"},tV={schemaVersion:BG,id:zG,displayName:jG,version:WG,engine:HG,artifact:qG,executable:GG,actions:VG,storage:ZG,environment:YG,requirements:XG,terminal:KG,network:QG,openUrls:JG,resources:eV},rV=1,nV="volter-model-editor-workbench",sV="Volter Model Editor workbench",iV="0.5.79",aV="node",oV={url:"/volter-model-editor-workbench/0.5.79/f16dc165-30e6a114/volter-model-editor-workbench.zip",integrity:"sha256-MOahFNbINNMkJE/4tqIHfqLWVuB2s/UmSdszMnXNals=",upstream:"https://github.com/volter-ai/code-oss",license:"MIT",redistribution:"cleared"},lV="code-server-oss",cV={start:["/opt/programs/volter-model-editor-workbench/0.5.79/vscode-reh-web-darwin-arm64/out/server-main.js","--host","127.0.0.1","--port","0","--without-connection-token"]},uV={home:"${HOME}/.vscode-server-oss",privateFiles:[]},fV={HOME:"${HOME}",SHELL:"/bin/sh",PATH:"/opt/programs/bin:/usr/local/bin:/usr/bin:/bin",VSCODE_CWD:"/opt/programs/volter-model-editor-workbench/0.5.79/vscode-reh-web-darwin-arm64",VOLTER_EDITOR_WORKBENCH_ROOT:"/opt/programs/volter-model-editor-workbench/0.5.79"},dV={capabilities:["filesystem.project"],programs:["node","git","sh"]},hV={input:"bytes"},pV={allowedHosts:[]},mV=[],gV={url:"/volter-model-editor-workbench/0.5.79/f16dc165-d9e4a705/volter-model-editor-workbench-resources.zip",integrity:"sha256-2eSnBVad4zRhJUCx9+1b9oJvyuzONmWIkYdba71cNlo=",root:"/opt/programs/volter-model-editor-workbench/0.5.79"},yV={schemaVersion:rV,id:nV,displayName:sV,version:iV,engine:aV,artifact:oV,executable:lV,actions:cV,storage:uV,environment:fV,requirements:dV,terminal:hV,network:pV,openUrls:mV,resources:gV};class bV{host;hooks;timeoutMs;pages=new Map;stopped=!1;retired=new Set;constructor(t,r,n){this.host=t,this.hooks=r,this.timeoutMs=n}context(t){return this.pages.get(t)?.contextId}opener(t){return this.pages.get(t)?.openerId}openerMark(t){return this.pages.get(t)?.openerMark}ownMark(t){return this.pages.get(t)?.ownMark}owner(t){return this.pages.get(t)?.owner}acceptsSurface(t){if(this.retired.has(t))return!1;const r=this.pages.get(t);return!r||!r.controller.signal.aborted&&!r.closing&&!this.stopped&&(!r.contextId||this.hooks.contextExists(r.contextId))}async create(t,r,n,s,i){if(this.stopped)throw new Error("Browser host is closing");for(const p of Object.keys(r))if(!["url","browserContextId"].includes(p))throw new Error(`Unsupported page option: ${p}`);if(typeof r.url!="string")throw new Error("url must be a string");if(r.browserContextId!==void 0&&typeof r.browserContextId!="string")throw new Error("browserContextId must be a string");const a=r.browserContextId;if(a!==void 0&&!this.hooks.contextExists(a))throw new Error("No browser context with given id");const o={id:crypto.randomUUID().replaceAll("-",""),contextId:a,...n?{openerId:n}:{},...s?{openerMark:s}:{},...i?{ownMark:i}:{},owner:t,controller:new AbortController,ready:!1,settled:!1};this.pages.set(o.id,o);const l=setTimeout(()=>o.controller.abort(new Error("Page creation timed out")),this.timeoutMs);let c=()=>{};const u=new Promise((p,m)=>{c=()=>{this.hooks.disconnectSurface(o.id),m(o.controller.signal.reason)},o.controller.signal.addEventListener("abort",c,{once:!0})}),d=Promise.resolve().then(()=>this.host.createPage({id:o.id,url:r.url,...a!==void 0?{browserContextId:a}:{}},o.controller.signal)).then(async()=>{if(o.settled=!0,!this.acceptsSurface(o.id)||!this.hooks.surfaceExists(o.id)){const p=o.controller.signal.reason??new Error("Host did not register a live page surface");throw o.controller.abort(p),await this.closeEntry(o),p}return o.ready=!0,o.id},async p=>{throw o.settled=!0,o.controller.abort(p),await this.closeEntry(o),p});try{return await Promise.race([d,u])}finally{clearTimeout(l),o.controller.signal.removeEventListener("abort",c)}}closeEntry(t){return t.closing||(t.closing=Promise.resolve().then(()=>this.host.closePage(t.id)).then(()=>{this.hooks.disconnectSurface(t.id),this.retired.add(t.id),this.pages.delete(t.id)},r=>{throw t.closing=void 0,r})),t.closing}async closeTarget(t){const r=this.pages.get(t);if(!r?.ready||!this.hooks.surfaceExists(t))throw new Error("No managed page with given id");await this.closeEntry(r)}disconnect(t){for(const r of this.pages.values())r.owner===t&&!r.ready&&r.controller.abort(new Error("Page creator disconnected"))}async disposeContext(t){const r=[];for(const n of this.pages.values())n.contextId===t&&(n.ready||n.controller.abort(new Error("Browser context disposed")),n.settled&&r.push(this.closeEntry(n)));await Promise.all(r)}async close(){this.stopped=!0;const t=[];for(const r of this.pages.values())r.ready||r.controller.abort(new Error("Browser host is closing")),r.settled&&t.push(this.closeEntry(r));await Promise.all(t)}}class wV{host;timeoutMs;contexts=new Map;closed=!1;constructor(t,r){this.host=t,this.timeoutMs=r}ids(){return[...this.contexts.values()].filter(t=>t.ready&&!t.disposal).map(t=>t.id)}async create(t,r){if(this.closed)throw new Error("Browser host is closing");const n=new Set(["disposeOnDetach","proxyServer","proxyBypassList","originsWithUniversalNetworkAccess"]);for(const d of Object.keys(r))if(!n.has(d))throw new Error(`Unsupported context option: ${d}`);if(r.disposeOnDetach!==void 0&&typeof r.disposeOnDetach!="boolean")throw new Error("disposeOnDetach must be boolean");for(const d of["proxyServer","proxyBypassList"])if(r[d]!==void 0&&typeof r[d]!="string")throw new Error(`${d} must be a string`);const s=r.originsWithUniversalNetworkAccess;if(s!==void 0&&(!Array.isArray(s)||!s.every(d=>typeof d=="string")))throw new Error("originsWithUniversalNetworkAccess must be a string array");const i={id:crypto.randomUUID().replaceAll("-",""),owner:t,disposeOnDetach:r.disposeOnDetach===!0,controller:new AbortController,ready:!1,settled:!1};this.contexts.set(i.id,i);const a=setTimeout(()=>i.controller.abort(new Error("Context creation timed out")),this.timeoutMs),l=Promise.resolve().then(()=>this.host.createContext({id:i.id,...r.proxyServer!==void 0?{proxyServer:r.proxyServer}:{},...r.proxyBypassList!==void 0?{proxyBypassList:r.proxyBypassList}:{},...s!==void 0?{originsWithUniversalNetworkAccess:s}:{}},i.controller.signal)).then(async()=>{if(i.settled=!0,i.controller.signal.aborted||this.closed)throw await this.disposeEntry(i),i.controller.signal.reason??new Error("Browser host is closing");return i.ready=!0,i.id},async d=>{throw i.settled=!0,await this.disposeEntry(i),d});let c=()=>{};const u=new Promise((d,p)=>{c=()=>p(i.controller.signal.reason),i.controller.signal.addEventListener("abort",c,{once:!0})});try{return await Promise.race([l,u])}finally{clearTimeout(a),i.controller.signal.removeEventListener("abort",c)}}disposeEntry(t){return t.disposal||(t.disposal=Promise.resolve().then(()=>this.host.disposeContext(t.id)).then(()=>{this.contexts.delete(t.id)},r=>{throw t.disposal=void 0,r})),t.disposal}async dispose(t){const r=this.contexts.get(t);if(!r?.ready)throw new Error("No browser context with given id");await this.disposeEntry(r)}async disconnect(t){const r=[];for(const n of this.contexts.values())n.owner===t&&(n.ready?n.disposeOnDetach&&r.push(this.disposeEntry(n)):n.controller.abort(new Error("Context creator disconnected")));await Promise.all(r)}async close(){this.closed=!0;for(const t of this.contexts.values())t.ready||t.controller.abort(new Error("Browser host is closing"));await Promise.all([...this.contexts.values()].filter(t=>t.settled).map(t=>this.disposeEntry(t)))}}const vV={adapters:{accessibility:"optional",capture:"optional",browserContexts:"optional-host-owned-storage-isolation",browserPages:"optional-host-owned-page-lifecycle",rrwebCast:"optional",surface:"same-origin DOM"},commands:{hostContext:["Target.createBrowserContext","Target.disposeBrowserContext"],hostPage:["Target.createTarget","Target.closeTarget"],browser:["Browser.cancelDownload","Browser.getBrowserCommandLine","Browser.getVersion","Browser.setDownloadBehavior","Browser.grantPermissions","Browser.resetPermissions","Storage.clearCookies","Storage.getCookies","Storage.setCookies","Target.activateTarget","Target.attachToTarget","Target.attachToBrowserTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getBrowserContexts","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"],surface:["Accessibility.disable","Browser.cancelDownload","Browser.grantPermissions","Browser.resetPermissions","Browser.setDownloadBehavior","Accessibility.enable","Accessibility.getChildAXNodes","Accessibility.getFullAXTree","Accessibility.getPartialAXTree","Accessibility.getRootAXNode","Accessibility.queryAXTree","DOM.describeNode","DOM.disable","DOM.enable","DOM.focus","DOM.getBoxModel","DOM.getContentQuads","DOM.getDocument","DOM.querySelector","DOM.querySelectorAll","DOM.requestNode","DOM.requestChildNodes","DOM.resolveNode","DOM.scrollIntoViewIfNeeded","DOM.setFileInputFiles","Emulation.clearDeviceMetricsOverride","Emulation.clearGeolocationOverride","Audits.disable","Audits.enable","Performance.disable","Performance.enable","Performance.getMetrics","Emulation.setDeviceMetricsOverride","Emulation.setEmulatedMedia","Emulation.setFocusEmulationEnabled","Emulation.setGeolocationOverride","Emulation.setLocaleOverride","Emulation.setTouchEmulationEnabled","Emulation.setUserAgentOverride","Fetch.continueRequest","Fetch.disable","Fetch.enable","Fetch.failRequest","Fetch.fulfillRequest","Input.dispatchDragEvent","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.dispatchTouchEvent","Input.emulateTouchFromMouseEvent","Input.imeSetComposition","Input.insertText","Input.setInterceptDrags","Log.disable","Log.enable","Network.disable","Network.enable","Network.getResponseBody","Network.setCacheDisabled","Network.setExtraHTTPHeaders","Page.addScriptToEvaluateOnNewDocument","Page.bringToFront","Page.captureScreenshot","Page.close","Page.createIsolatedWorld","Page.deleteCookie","Page.disable","Page.enable","Page.getFrameTree","Page.handleJavaScriptDialog","Page.getLayoutMetrics","Page.getNavigationHistory","Page.getResourceTree","Page.navigate","Page.navigateToHistoryEntry","Page.reload","Page.removeScriptToEvaluateOnNewDocument","Page.setFontFamilies","Page.setInterceptFileChooserDialog","Page.screencastFrameAck","Page.setLifecycleEventsEnabled","Page.setTouchEmulationEnabled","Page.startScreencast","Page.stopScreencast","Runtime.addBinding","Runtime.callFunctionOn","Runtime.disable","Runtime.enable","Runtime.evaluate","Runtime.getProperties","Runtime.releaseObject","Runtime.releaseObjectGroup","Runtime.runIfWaitingForDebugger","Schema.getDomains","Storage.clearCookies","Storage.getCookies","Storage.setCookies","Target.activateTarget","Target.setAutoAttach"],refused:["Browser.getWindowForTarget","Emulation.setDefaultBackgroundColorOverride","Emulation.setOrientationOverride","Emulation.setScriptExecutionDisabled","Emulation.setTimezoneOverride","Fetch.continueWithAuth","Network.clearBrowserCache","Network.emulateNetworkConditions","Network.loadNetworkResource","Network.setBypassServiceWorker","Page.setBypassCSP","Security.setIgnoreCertificateErrors"]},unimplemented:{domains:["CSS","Debugger","HeapProfiler","IO","Profiler","Tracing"],commands:["Browser.close","Browser.getWindowBounds","Browser.setDockTile","Browser.setWindowBounds","Console.enable","DOM.getFrameOwner","Page.printToPDF","Target.sendMessageToTarget"]},fidelity:{dialogs:"reported-and-dismissed-synchronously-while-Page-is-observed; accept refused",downloads:"anchor downloads (a[download], blob:, data:) intercepted by the surface and written through the host; downloads the host browser starts from an attachment navigation are its own",capture:"adapter-declared",deviceScaleFactor:"js-visible-only",history:"frame-scoped via the Navigation API; without it, agent-observed entries and traversal refused",pageClose:"host-hook-required",urls:"host-mapped; page script sees the frame's real location",userAgent:"js-visible-only; HTTP headers unchanged; navigator.platform only from the platform parameter",locale:"js-visible-only; Intl constructors, toLocale*String and navigator.language(s)",geolocation:"js-visible-only; navigator.geolocation answers only while geolocation is granted",permissions:"js-visible-only; navigator.permissions.query and Notification.permission; host prompts unchanged",touch:"js-visible-only; navigator.maxTouchPoints and ontouchstart",realmOverrides:"installed when a document finishes loading; scripts that run earlier see host values",cookies:"script-visible-only; HttpOnly cookies unreadable and unsettable; each surface reaches its own host and path",fileChooser:"click-and-showPicker-interception; files assigned only through a host file adapter",fontFamilies:"standard-applied; generic families resolved by host browser; forScripts ignored",screenSize:"js-visible-only",viewport:"frame-element-resized; a top-level surface accepts only its current size",input:"synthetic-isTrusted-false",dragAndDrop:"synthetic-DataTransfer; draggable-element drags only (no text-selection or file drags)",keyboardEditing:"text-controls-code-point-movement-and-deletion; no-platform-word-or-grapheme-segmentation",legacyTouchEmulation:"mouse-events-only",wheel:"synthetic-cancelable-event-and-scrollable-ancestor-default-action",network:"fetch-and-xhr-observation",interception:"fetch-and-xhr-only; synchronous XHR and response-stage interception unavailable; authentication challenges stay with the host browser",responseBodies:"fetch-and-xhr; 8-MiB-LRU; json/document XHR bodies unavailable",cacheDisabled:"fetch-requests-use-no-store; XHR, navigation and subresources keep the HTTP cache",rrweb:"side-channel"},protocol:{devtoolsProtocolPackage:"0.0.1702366",protocolVersion:"1.3"},version:1};function J8(e,t,r){const n=r.length>1?r.replace(/\/$/,""):r,s=/^wss?:\/\//u.test(t)?t:`ws://${t}`,i=s.replace(/^wss?:\/\//u,"");return n==="/json/version"?{status:200,body:{Browser:"AlmostCDP/0.1.0","Protocol-Version":"1.3","User-Agent":"AlmostCDP/0.1.0","V8-Version":"0","WebKit-Version":"0",webSocketDebuggerUrl:`${s}/devtools/browser/${e.browserId}`}}:n==="/json"||n==="/json/list"?{status:200,body:e.targets().map(a=>({description:"",devtoolsFrontendUrl:`/devtools/inspector.html?${s.startsWith("wss:")?"wss":"ws"}=${i}/devtools/page/${a.id}`,id:a.id,title:a.title,type:a.type,url:a.url,webSocketDebuggerUrl:`${s}/devtools/page/${a.id}`}))}:n==="/health"?{status:200,body:{ok:!0,surfaces:e.targets().length}}:n==="/compatibility"?{status:200,body:e.compatibility()}:{status:404,body:{error:"not found"}}}class xV{deliver;readyState=1;listeners={message:[],close:[]};constructor(t){this.deliver=t}send(t){this.readyState===1&&this.deliver({data:t})}close(){this.readyState===1&&(this.deliver({close:!0}),this.closed())}on(t,r){this.listeners[t].push(r)}received(t){if(this.readyState===1)for(const r of this.listeners.message)r(t)}closed(){if(this.readyState!==3){this.readyState=3;for(const t of this.listeners.close)t()}}}let SV=0;const ur=(e,t)=>{if((e.bufferedAmount??0)>8*1024*1024){e.close(1013,"Consumer too slow; reconnect for a fresh snapshot");return}e.readyState===1&&e.send(JSON.stringify(t))},Pb=e=>({attached:!1,browserContextId:e.contextId??"default",canAccessOpener:!1,targetId:e.description.id,title:e.description.title,type:e.description.type,url:e.description.url});function EV(e){const{browserId:t,surfaceToken:r}=e,n=new Map,s=new WeakMap,i=(L,G,q)=>G?q.parentId!==void 0&&L.sessions.get(G)===q.parentId:q.parentId===void 0,a=new Map,o=e.successionGraceMs??15e3,l=e.contextHost?new wV({createContext:(L,G)=>e.contextHost.createContext(L,G),disposeContext:async L=>{await c?.disposeContext(L),await e.contextHost.disposeContext(L)}},e.commandTimeoutMs??15e3):void 0,c=e.pageHost?new bV(e.pageHost,{contextExists:L=>l?.ids().includes(L)??!1,surfaceExists:L=>n.get(L)?.ws.readyState===1,disconnectSurface:L=>n.get(L)?.ws.close(1001,"Managed page closed")},e.commandTimeoutMs??15e3):void 0,u=new Set,d=L=>{const G=c?.opener(L.description.id);return{...Pb(L),...G?{openerId:G,canAccessOpener:c?.openerMark(L.description.id)!==void 0}:{}}},p=new Map,m=new Map,g=new Map,b=new Map,v=new Map,S=new Map,x=new Map,E=L=>({id:0,method:"Browser.setDownloadBehavior",params:{[Aj]:!0,behavior:L.behavior}});let A=0;const T=(L,G,q={})=>{const ee={id:G.id,result:q};G.sessionId&&(ee.sessionId=G.sessionId),ur(L.ws,ee)},D=(L,G,q=Z8(G.method))=>{const ee={error:q,id:G.id};G.sessionId&&(ee.sessionId=G.sessionId),ur(L.ws,ee)},I=(L,G,q)=>{const ee=globalThis.crypto.randomUUID().replaceAll("-","");L.sessions.set(ee,G.description.id),L.parents.set(ee,q??"");const z={method:"Target.attachedToTarget",...q?{sessionId:q}:{},params:{sessionId:ee,targetInfo:{...d(G),attached:!0},waitingForDebugger:!1}};return ur(L.ws,z),ee},U=(L,G,q)=>{const ee=G.params?.files;if(G.method==="DOM.setFileInputFiles"&&e.fileHost&&Array.isArray(ee)&&ee.length&&G.params?.[Y8]===void 0){const fe=e.fileHost,de=`files-${++SV}`;(async()=>{const ge=[];for(const Ne of ee){const Te=String(Ne),Pe=await fe.list?.(Te);if(!Pe){ge.push({path:Te});continue}const Le=Te.replace(/[\\/]+$/u,""),ct=Le.split(/[\\/]/u).pop()??Le;for(const We of Pe)ge.push({path:`${Le}/${We}`,relativePath:`${ct}/${We}`})}for(const[Ne,{path:Te,relativePath:Pe}]of ge.entries()){const Le=await fe.read(Te);ur(q.ws,{type:"stage-file",token:de,index:Ne,name:Le.name??Te.split(/[\\/]/u).pop()??Te,...Le.type?{mimeType:Le.type}:{},...Le.lastModified!==void 0?{lastModified:Le.lastModified}:{},...Pe?{relativePath:Pe}:{},dataBase64:Cj(Le.data)})}return ge.length})().then(ge=>U(L,{...G,params:{...G.params,files:[],[Y8]:{token:de,count:ge}}},q),ge=>D(L,G,{code:-32e3,message:ge instanceof Error?ge.message:String(ge)}));return}const z=G.sessionId??"direct",j=G.method.split(".")[0];let te;if(G.method===`${j}.enable`||G.method===`${j}.disable`){const fe=L.subscriptionChanges.get(z)??new Map;L.subscriptionChanges.set(z,fe);const de=fe.get(j)??{enabled:L.subscriptions.get(z)?.has(j)??!1,changes:[]};fe.set(j,de);const ge={enabled:G.method.endsWith(".enable")};de.changes.push(ge);const Ne=()=>{let Te=de.enabled;for(const Le of de.changes)Le.accepted!==!1&&(Te=Le.enabled);const Pe=L.subscriptions.get(z)??new Set;Te?Pe.add(j):Pe.delete(j),L.subscriptions.set(z,Pe)};Ne(),te=Te=>{if(L.subscriptionChanges.get(z)?.get(j)===de){for(ge.accepted=Te;de.changes[0]?.accepted!==void 0;){const Pe=de.changes.shift();Pe.accepted&&(de.enabled=Pe.enabled)}Ne(),de.changes.length||(fe.delete(j),fe.size||L.subscriptionChanges.delete(z))}}}if(G.method===`${j}.disable`&&[...u].some(de=>[...de.subscriptions].some(([ge,Ne])=>Ne.has(j)&&(ge==="direct"?de.directSurfaceId:de.sessions.get(ge))===q.description.id))&&j!=="Runtime"&&j!=="DOM"&&j!=="Fetch"){te?.(!0),T(L,G);return}let le;if(G.method.startsWith("Page.")&&["Page.startScreencast","Page.stopScreencast","Page.screencastFrameAck"].includes(G.method)){const fe=b.get(q.description.id);if(fe&&(fe.client!==L||fe.sessionId!==G.sessionId)){D(L,G,{code:-32e3,message:"Screencast belongs to another session"});return}if(G.method==="Page.startScreencast"){const de={client:L,sessionId:G.sessionId};b.set(q.description.id,de),le=ge=>{ge||b.get(q.description.id)!==de||(b.delete(q.description.id),ur(q.ws,{type:"command",relayId:`cleanup-${++A}`,message:{id:0,method:"Page.stopScreencast"}}))}}G.method==="Page.stopScreencast"&&(le=de=>{de&&b.get(q.description.id)===fe&&b.delete(q.description.id)})}const ne=`r${++A}`,me=setTimeout(()=>{m.delete(ne),te?.(!1),le?.(!1),D(L,G,{code:-32e3,message:"Surface command timed out"})},e.commandTimeoutMs??3e4);m.set(ne,{client:L,command:G,surface:q,timer:me,settleSubscription:te,settleCapture:le});const ve={message:{id:G.id,method:G.method,params:G.params,sessionId:`${L.id}:${z}`},relayId:ne,type:"command"};ur(q.ws,ve)},O=(L,G)=>{c?.disconnect(`${L.id}:${G}`),l?.disconnect(`${L.id}:${G}`).catch(()=>{});const q=L.sessions.get(G),ee=L.parents.get(G)??"";for(const[j,te]of[...L.parents])te===G&&O(L,j);L.parents.delete(G),L.automaticSessions.delete(G),L.autoAttach.delete(G),L.discover.delete(G),L.sessions.delete(G),L.subscriptions.delete(G),L.subscriptionChanges.delete(G),L.browserSessions.delete(G);const z=q?n.get(q):void 0;if(z){ur(z.ws,{type:"session-closed",sessionId:`${L.id}:${G}`});const j=b.get(q);j?.client===L&&j.sessionId===G&&(b.delete(q),ur(z.ws,{type:"command",relayId:`cleanup-${++A}`,message:{id:0,method:"Page.stopScreencast"}}))}for(const[j,te]of m)te.client!==L||te.command.sessionId!==G||(clearTimeout(te.timer),m.delete(j),D(L,te.command,{code:-32001,message:"Session detached"}));ur(L.ws,{...ee?{sessionId:ee}:{},method:"Target.detachedFromTarget",params:{sessionId:G,...q?{targetId:q}:{}}})},_=L=>{const G=typeof L=="string"?L:"default";if(!(G!=="default"&&!l?.ids().includes(G)))return[...n.values()].filter(q=>(q.contextId??"default")===G)},N=(L,G,q,ee=G.params)=>Promise.all(q.map(z=>new Promise(j=>{const te=`fan-${++A}`,le=setTimeout(()=>{m.delete(te),j({id:G.id,error:{code:-32e3,message:"Surface command timed out"}})},e.commandTimeoutMs??3e4);m.set(te,{client:L,command:G,surface:z,timer:le,resolve:j}),ur(z.ws,{type:"command",relayId:te,message:{id:G.id,method:G.method,params:ee}})}))),F=L=>{const G=L.find(q=>q.error);if(G)throw new Error(G.error.message)},P=(L,G)=>{const q=G.params??{},ee=j=>{G.method==="Target.getTargetInfo"&&typeof q.targetId!="string"?T(L,G,{targetInfo:d(j)}):U(L,G,j)};if(L.directSurfaceId){const j=n.get(L.directSurfaceId);if(!j)return D(L,G,{code:-32e3,message:"Target closed"});ee(j);return}if(G.sessionId&&!L.browserSessions.has(G.sessionId)){const j=L.sessions.get(G.sessionId),te=j?n.get(j):void 0;if(!te)return D(L,G,{code:-32001,message:"No session with given id"});if(G.method==="Target.setAutoAttach"){const le=G.sessionId;if(q.autoAttach===!0){L.autoAttach.add(le);for(const ne of n.values())i(L,le,ne)&&([...L.sessions].some(([me,ve])=>ve===ne.description.id&&L.parents.get(me)===le)||L.automaticSessions.add(I(L,ne,le)))}else{L.autoAttach.delete(le);for(const ne of[...L.automaticSessions])L.parents.get(ne)===le&&O(L,ne)}T(L,G);return}ee(te);return}const z=j=>{j.then(te=>T(L,G,te),te=>D(L,G,{code:-32e3,message:te instanceof Error?te.message:String(te)}))};switch(G.method){case"Target.createTarget":c?z(c.create(`${L.id}:${G.sessionId??""}`,q).then(j=>({targetId:j}))):D(L,G);break;case"Target.closeTarget":c?typeof q.targetId!="string"?D(L,G,{code:-32602,message:"targetId must be a string"}):z(c.closeTarget(q.targetId).then(()=>({success:!0}))):D(L,G);break;case"Target.getBrowserContexts":T(L,G,{browserContextIds:l?.ids()??[]});break;case"Target.createBrowserContext":l?z(l.create(`${L.id}:${G.sessionId??""}`,q).then(j=>({browserContextId:j}))):D(L,G);break;case"Target.disposeBrowserContext":l?typeof q.browserContextId!="string"?D(L,G,{code:-32602,message:"browserContextId must be a string"}):z(l.dispose(q.browserContextId).then(()=>({}))):D(L,G);break;case"Target.attachToBrowserTarget":{const j=globalThis.crypto.randomUUID().replaceAll("-","");L.browserSessions.add(j),L.parents.set(j,G.sessionId??""),T(L,G,{sessionId:j});break}case"Browser.getVersion":T(L,G,{jsVersion:"0",product:`Chrome/${/Chrome\/([\d.]+)/u.exec(globalThis.navigator?.userAgent??"")?.[1]??"136.0.0.0"}`,protocolVersion:"1.3",revision:"@almostcdp",userAgent:globalThis.navigator?.userAgent??"Mozilla/5.0 AlmostCDP/0.1.0"});break;case"Browser.getBrowserCommandLine":T(L,G,{arguments:[]});break;case"Browser.grantPermissions":case"Browser.resetPermissions":{const j=typeof q.browserContextId=="string"?q.browserContextId:"default",te=_(q.browserContextId);if(!te){D(L,G,{code:-32e3,message:"Failed to find browser context for id"});break}G.method==="Browser.resetPermissions"?v.delete(j):v.set(j,[...v.get(j)??[],q]),z(N(L,G,te).then(le=>(F(le),{})));break}case"Storage.getCookies":case"Storage.setCookies":case"Storage.clearCookies":{const j=_(q.browserContextId);if(!j){D(L,G,{code:-32e3,message:"Failed to find browser context for id"});break}const te=Array.isArray(q.cookies)?q.cookies:[],le=j.length?te.some(me=>me.httpOnly===!0)?"HttpOnly cookies are invisible to scripts and cannot be set from a DOM surface":void 0:"no surface of the context is open to reach its cookies";if(le){D(L,G,{code:-32e3,message:`${G.method} is unavailable on a DOM surface: ${le}`});break}const ne=G.method==="Storage.setCookies";z(N(L,G,j,ne?{...q,[Tj]:!0}:q).then(me=>{if(F(me),G.method==="Storage.getCookies"){const ve=new Map;for(const fe of me)for(const de of fe.result?.cookies??[])ve.set(`${String(de.name)}\0${String(de.domain)}\0${String(de.path)}`,de);return{cookies:[...ve.values()]}}if(ne){const ve=new Set(me.flatMap(de=>de.result?.applied??[])),fe=te.filter((de,ge)=>!ve.has(ge)).map(de=>String(de.domain??de.url??""));if(fe.length)throw new Error(`Storage.setCookies is unavailable on a DOM surface: no open surface of the context serves ${fe.join(", ")}`)}return{}}));break}case"Browser.setDownloadBehavior":{if(!e.downloadHost){D(L,G,{code:-32e3,message:"Download policy requires a host download adapter; a live DOM surface cannot enforce it"});break}const j=String(q.behavior??"");if(!["default","deny","allow","allowAndName"].includes(j)){D(L,G,{code:-32602,message:`Invalid download behavior: ${j}`});break}const te=typeof q.downloadPath=="string"&&q.downloadPath?q.downloadPath:void 0;if((j==="allow"||j==="allowAndName")&&!te){D(L,G,{code:-32602,message:"downloadPath is required for allow and allowAndName"});break}const le=_(q.browserContextId);if(!le){D(L,G,{code:-32e3,message:"Failed to find browser context for id"});break}const ne=typeof q.browserContextId=="string"?q.browserContextId:"default",me=(S.get(ne)?.listeners??[]).filter(fe=>fe.client!==L||fe.sessionId!==G.sessionId);q.eventsEnabled===!0&&me.push({client:L,sessionId:G.sessionId});const ve={behavior:j,downloadPath:te,listeners:me};S.set(ne,ve),z(N(L,G,le,E(ve).params).then(fe=>(F(fe),{})));break}case"Browser.cancelDownload":{if(!e.downloadHost){D(L,G,V8(G.method));break}const j=String(q.guid??""),te=n.get(x.get(j)??"");if(!te){D(L,G,{code:-32e3,message:`Browser.cancelDownload: no in-flight download with guid ${j}`});break}z(N(L,G,[te],{guid:j}).then(le=>(F(le),{})));break}case"Target.getTargets":T(L,G,{targetInfos:[...n.values()].map(Pb)});break;case"Target.getTargetInfo":{const j=typeof q.targetId=="string"?q.targetId:t;if(j===t){T(L,G,{targetInfo:{targetId:t,type:"browser",title:"",url:"",attached:!0,canAccessOpener:!1}});break}const te=j?n.get(j):void 0;te?T(L,G,{targetInfo:d(te)}):D(L,G,{code:-32e3,message:"No target with given id"});break}case"Target.setDiscoverTargets":{const j=G.sessionId??"",te=L.discover.has(j);if(q.discover===!0?L.discover.add(j):L.discover.delete(j),T(L,G),q.discover===!0&&!te)for(const le of n.values())ur(L.ws,{...j?{sessionId:j}:{},method:"Target.targetCreated",params:{targetInfo:d(le)}});break}case"Target.setAutoAttach":{const j=G.sessionId??"";if(q.autoAttach===!0?L.autoAttach.add(j):L.autoAttach.delete(j),q.autoAttach===!0)for(const te of n.values())i(L,j,te)&&([...L.sessions].some(([le,ne])=>ne===te.description.id&&L.parents.get(le)===j)||L.automaticSessions.add(I(L,te,G.sessionId)));else for(const te of[...L.automaticSessions])L.parents.get(te)===j&&O(L,te);T(L,G);break}case"Target.attachToTarget":{const j=String(q.targetId??""),te=n.get(j);if(!te)D(L,G,{code:-32e3,message:"No target with given id"});else{const le=I(L,te,G.sessionId);T(L,G,{sessionId:le})}break}case"Target.activateTarget":{const j=n.get(String(q.targetId??""));j?U(L,G,j):D(L,G,{code:-32e3,message:"No target with given id"});break}case"Target.detachFromTarget":{const j=String(q.sessionId??"");if(!L.sessions.get(j)&&!L.browserSessions.has(j)||L.parents.get(j)!==(G.sessionId??"")){D(L,G,{code:-32001,message:"No session with given id"});break}O(L,j),T(L,G);break}default:D(L,G,V8(G.method)??Z8(G.method))}},W=(L,G)=>{for(const[q,ee]of m)ee.surface===L&&(clearTimeout(ee.timer),m.delete(q),ee.resolve?ee.resolve({id:ee.command.id,error:{code:-32e3,message:G}}):D(ee.client,ee.command,{code:-32e3,message:G}))},K=L=>{const G=n.get(L);if(!G)return;const q=a.get(L);q?.suspended&&clearTimeout(q.suspended.timer),a.delete(L),n.delete(L),b.delete(L),W(G,"Target closed");for(const ee of p.get(L)??[])ee.close(1001,"Target closed");for(const ee of u){if(ee.directSurfaceId===L){ee.subscriptions.clear(),ee.subscriptionChanges.clear(),ee.ws.close(1001,"Target closed");continue}for(const[z,j]of[...ee.sessions])j===L&&O(ee,z);for(const z of ee.discover)ur(ee.ws,{...z?{sessionId:z}:{},method:"Target.targetDestroyed",params:{targetId:L}})}},Y=(L,G)=>{const q=n.get(L),ee=[];q.ws={readyState:1,send:z=>{ee.push(z)},close:()=>K(L),on:()=>{}},W(q,"Inspected target navigated or closed");for(const z of p.get(L)??[])z.close(1012,"Document replaced; reconnect");G.suspended={buffer:ee,timer:setTimeout(()=>K(L),o)}},V=(L,G,q="control")=>{const ee=new URL(G,"http://localhost");if(q==="view"&&!ee.pathname.startsWith("/casts/")){L.close(1008,"View-only access permits only casting");return}if(ee.pathname==="/__almostcdp/surface"){if(ee.searchParams.get("token")!==r){L.close(1008,"invalid surface token");return}let ne;const me=new Map;L.on("close",()=>{for(const ve of[...me.values()])ve.closed()}),L.on("message",ve=>{let fe;try{if(fe=JSON.parse(ve.toString()),!fe||typeof fe!="object")throw new Error("Invalid message")}catch{L.close(1003,"invalid JSON");return}if(fe.type==="hello"){if(!fe.surface||typeof fe.surface.title!="string"||typeof fe.surface.url!="string"||fe.surface.id!==void 0&&(typeof fe.surface.id!="string"||!/^[\w-]+$/.test(fe.surface.id))){L.close(1008,"invalid surface description");return}const de=fe.surface.id??ne??globalThis.crypto.randomUUID().replaceAll("-",""),ge=fe.succession?.token;if(fe.succession!==void 0&&(typeof ge!="string"||ge.length<16)){L.close(1008,"invalid succession token");return}const Ne=a.get(de);if(!ne&&Ne&&n.has(de)&&n.get(de).ws!==L){if(ge!==Ne.token){L.close(1008,"surface identity already registered");return}if(!Ne.suspended){const ht=n.get(de).ws;Y(de,Ne),ht.close(1e3,"Document replaced by its successor")}const Ge=n.get(de);clearTimeout(Ne.suspended.timer);const Ct=Ne.suspended.buffer;Ne.suspended=void 0,ne=de,Ge.ws=L,Ge.description.title=fe.surface.title,Ge.description.url=fe.surface.url,ur(L,{type:"resume",state:Ne.state,...Ne.loaderId?{loaderId:Ne.loaderId,navigationType:Ne.navigationType}:{}}),Ne.loaderId=void 0,Ne.navigationType=void 0;for(const ht of Ct)L.readyState===1&&L.send(ht);for(const ht of u){const Ee=new Set(ht.discover);for(const[De,$e]of ht.sessions)$e===de&&Ee.add(ht.parents.get(De)??"");for(const De of Ee)ur(ht.ws,{...De?{sessionId:De}:{},method:"Target.targetInfoChanged",params:{targetInfo:Pb(Ge)}})}return}if(ne&&ne!==de||n.has(de)&&n.get(de).ws!==L){L.close(1008,"surface identity already registered");return}const Te=s.get(L);if(c&&Te===void 0&&!c.acceptsSurface(de)){L.close(1008,"Page allocation is no longer active");return}ge!==void 0&&!ne&&(a.set(de,{token:ge,state:null}),ur(L,{type:"resume",state:null}));const Pe=n.has(de);ne=de;const Le={contextId:Te!==void 0?n.get(Te)?.contextId:c?.context(de),...Te!==void 0?{parentId:Te}:{},description:{id:de,title:fe.surface.title,type:fe.surface.type??"page",url:fe.surface.url},ws:L};n.set(de,Le);const ct=c?.openerMark(de),We=c?.ownMark(de);(ct||We)&&ur(L,{type:"opener",...ct?{mark:ct}:{},...We?{own:We}:{}});for(const Ge of u){const Ct=new Set(Ge.discover);if(Pe)for(const[ht,Ee]of Ge.sessions)Ee===de&&Ct.add(Ge.parents.get(ht)??"");for(const ht of Ct)ur(Ge.ws,{...ht?{sessionId:ht}:{},method:Pe?"Target.targetInfoChanged":"Target.targetCreated",params:{targetInfo:d(Le)}});if(!Pe)for(const ht of Ge.autoAttach)i(Ge,ht,Le)&&Ge.automaticSessions.add(I(Ge,Le,ht||void 0))}if(!Pe){const Ge=S.get(Le.contextId??"default");Ge&&Ge.behavior!=="default"&&ur(L,{type:"command",relayId:`cleanup-${++A}`,message:E(Ge)});for(const Ct of v.get(Le.contextId??"default")??[])ur(L,{type:"command",relayId:`cleanup-${++A}`,message:{id:0,method:"Browser.grantPermissions",params:Ct}})}return}if(fe.type==="succession-state"){const de=ne?a.get(ne):void 0;if(!de||n.get(ne)?.ws!==L)return;if(!fe.state||typeof fe.state!="object"||Array.isArray(fe.state)){L.close(1008,"invalid succession state");return}de.state=fe.state;return}if(fe.type==="response"){const de=m.get(fe.relayId);if(!de||de.surface.ws!==L)return;if(!fe.message||typeof fe.message!="object"){L.close(1008,"invalid response");return}m.delete(fe.relayId),clearTimeout(de.timer);const ge=a.get(de.surface.description.id);if(ge&&!fe.message.error&&(de.command.method==="Page.navigate"||de.command.method==="Page.reload")){const Te=fe.message.result?.loaderId;ge.loaderId=typeof Te=="string"?Te:void 0,ge.navigationType=de.command.method==="Page.reload"?"reload":"typed"}if(de.resolve){de.resolve(fe.message);return}de.settleSubscription?.(!fe.message.error),de.settleCapture?.(!fe.message.error);const Ne={...fe.message,id:de.command.id};de.command.sessionId&&(Ne.sessionId=de.command.sessionId),ur(de.client.ws,Ne);return}if(fe.type==="cast"&&ne){for(const de of p.get(ne)??[])ur(de,fe.event);return}if(fe.type==="sub"&&ne&&typeof fe.sub=="string"){const de=ne;let ge=me.get(fe.sub);if(fe.open===!0&&!ge){const Ne=fe.sub;ge=new xV(Te=>ur(L,{type:"sub",sub:Ne,...Te})),me.set(Ne,ge),s.set(ge,de),ge.on("close",()=>me.delete(Ne)),V(ge,`/__almostcdp/surface?token=${encodeURIComponent(r)}`)}typeof fe.data=="string"&&ge?.received(fe.data),fe.close===!0&&ge?.closed();return}if(fe.type==="close-window"&&ne){const de=ne;c?.closeTarget(de).catch(ge=>console.warn(`AlmostCDP: window.close() closed no page: ${ge instanceof Error?ge.message:String(ge)}`));return}if(fe.type==="open-window"&&ne){const de=ne;if(!c||typeof fe.url!="string")return;const ge=c.owner(de)??`popup:${de}`,Ne=n.get(de)?.contextId,Te=typeof fe.opener=="string"&&/^[\w-]{16,}$/u.test(fe.opener)?fe.opener:void 0,Pe=typeof fe.mark=="string"&&/^[\w-]{16,}$/u.test(fe.mark)?fe.mark:void 0;c.create(ge,{url:fe.url,...Ne&&Ne!=="default"?{browserContextId:Ne}:{}},de,Te,Pe).catch(Le=>console.warn(`AlmostCDP: window.open(${JSON.stringify(fe.url)}) opened no page: ${Le instanceof Error?Le.message:String(Le)}`));return}if(fe.type==="download"&&ne){const de=ne,ge=n.get(de)?.contextId,Ne=S.get(ge??"default"),Te=ct=>ur(L,{type:"download-written",...ct});if(!e.downloadHost||!Ne?.downloadPath||Ne.behavior!=="allow"&&Ne.behavior!=="allowAndName"||typeof fe.guid!="string"||typeof fe.data!="string"){Te({error:"downloads are not accepted for this context",guid:String(fe.guid)});return}const Pe=Ne.behavior==="allowAndName"?fe.guid:String(fe.suggestedFilename??"").replace(/[\\/]/g,"_")||fe.guid,Le=`${Ne.downloadPath.replace(/[\\/]+$/,"")}/${Pe}`;e.downloadHost.write(ge,Le,kj(fe.data)).then(()=>Te({filePath:Le,guid:fe.guid}),ct=>Te({error:ct instanceof Error?ct.message:String(ct),guid:fe.guid}));return}if(fe.type==="event"&&ne){if(!fe.message||typeof fe.message.method!="string"){L.close(1008,"invalid event");return}if(fe.message.method.startsWith("Browser.download")){const Le=fe.message.params??{},ct=String(Le.guid??"");fe.message.method==="Browser.downloadWillBegin"?x.set(ct,ne):(Le.state==="completed"||Le.state==="canceled")&&x.delete(ct);const We=S.get(n.get(ne)?.contextId??"default");for(const Ge of We?.listeners??[])ur(Ge.client.ws,{method:fe.message.method,params:Le,...Ge.sessionId?{sessionId:Ge.sessionId}:{}});return}if(fe.message.method==="Page.screencastFrame"){const Le=b.get(ne),{sessionId:ct,...We}=fe.message;Le&&ct===`${Le.client.id}:${Le.sessionId??"direct"}`&&ur(Le.client.ws,{...We,...Le.sessionId?{sessionId:Le.sessionId}:{}});return}const{sessionId:de,...ge}=fe.message,Ne=ge.method.split(".")[0],Te=["Runtime","Network","Log","DOM","Page","Accessibility"].includes(Ne),Pe=(Le,ct)=>(!de||de===`${Le.id}:${ct}`)&&(!Te||Le.subscriptions.get(ct)?.has(Ne));for(const Le of u){if(Le.directSurfaceId===ne&&Pe(Le,"direct")){ur(Le.ws,ge);continue}for(const[ct,We]of Le.sessions)We===ne&&Pe(Le,ct)&&ur(Le.ws,{...ge,sessionId:ct})}}}),L.on("close",()=>{if(!ne||n.get(ne)?.ws!==L)return;const ve=a.get(ne);ve?Y(ne,ve):K(ne)});return}const z=ee.pathname.match(/^\/devtools\/page\/([^/]+)$/),j=ee.pathname.match(/^\/devtools\/browser\/([^/]+)$/),te=ee.pathname.match(/^\/casts\/([^/]+)$/);if(te){const ne=te[1];if(!n.has(ne)){L.close(1013,"target not available");return}const me=p.get(ne)??new Set;me.add(L),p.set(ne,me),ur(n.get(ne).ws,{type:"cast-reset"}),L.on("message",ve=>{if(q==="view"){L.close(1008,"View-only access cannot send input");return}const fe=n.get(ne);if(!fe)return;let de;try{de=JSON.parse(ve.toString())}catch{L.close(1003,"invalid JSON");return}if(typeof de.method!="string"||!de.method.startsWith("Input.")){L.close(1008,"cast input must be a CDP Input command");return}const ge={message:{id:0,method:de.method,params:typeof de.params=="object"&&de.params?de.params:{}},relayId:`cast-${++A}`,type:"command"};ur(fe.ws,ge)}),L.on("close",()=>{me.delete(L),me.size||p.delete(ne)});return}if(!z&&(!j||j[1]!==t)){L.close(1008,"unknown endpoint");return}if(z&&!n.has(z[1])){L.close(1008,"unknown target");return}const le={id:globalThis.crypto.randomUUID(),autoAttach:new Set,automaticSessions:new Set,parents:new Map,browserSessions:new Set,subscriptions:new Map,subscriptionChanges:new Map,directSurfaceId:z?.[1],discover:new Set,sessions:new Map,ws:L};u.add(le),L.on("message",ne=>{let me;try{if(me=JSON.parse(ne.toString()),!me||!Number.isSafeInteger(me.id)||typeof me.method!="string"||me.params!==void 0&&(!me.params||typeof me.params!="object"||Array.isArray(me.params))||me.sessionId!==void 0&&typeof me.sessionId!="string")throw new Error("Invalid command")}catch{L.close(1003,"invalid JSON");return}g.set(me.method,(g.get(me.method)??0)+1),P(le,me)}),L.on("close",()=>{u.delete(le);for(const ne of S.values())ne.listeners=ne.listeners.filter(me=>me.client!==le);for(const ne of["",...le.browserSessions])c?.disconnect(`${le.id}:${ne}`),l?.disconnect(`${le.id}:${ne}`).catch(()=>{});for(const[ne,me]of le.sessions){const ve=n.get(me);ve&&ur(ve.ws,{type:"session-closed",sessionId:`${le.id}:${ne}`})}if(le.directSurfaceId){const ne=n.get(le.directSurfaceId);ne&&ur(ne.ws,{type:"session-closed",sessionId:`${le.id}:direct`})}for(const[ne,me]of b){if(me.client!==le)continue;b.delete(ne);const ve=n.get(ne);ve&&ur(ve.ws,{type:"command",relayId:`cleanup-${++A}`,message:{id:0,method:"Page.stopScreencast"}})}for(const[ne,me]of m)me.client===le&&(clearTimeout(me.timer),m.delete(ne))})};return{connect:V,targets:()=>[...n.values()].map(L=>({...L.description})),compatibility:()=>({manifest:vV,observedCommands:Object.fromEntries([...g].sort(([L],[G])=>L.localeCompare(G)))}),async close(){for(const q of m.values())clearTimeout(q.timer);m.clear();for(const q of u)q.ws.close(1001,"server closing");for(const q of n.values())q.ws.close(1001,"server closing");for(const q of p.values())for(const ee of q)ee.close(1001,"server closing");const G=(await Promise.allSettled([c?.close(),l?.close()])).filter(q=>q.status==="rejected");if(G.length===1)throw G[0].reason;if(G.length)throw new AggregateError(G.map(q=>q.reason),"Host cleanup failed")}}}const kV="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",AV=64*1024,Cf=new TextEncoder;function ON(e){const t=globalThis.crypto.randomUUID().replaceAll("-",""),r=OV(24),n=EV({...e,browserId:t,surfaceToken:r}),s=new Set;let i=!1;const a={browserId:t,targets:n.targets,compatibility:n.compatibility};return{browserId:t,serve:l=>{if(i){l.close();return}s.add(l),l.onClose(()=>s.delete(l));let c=new Uint8Array,u,d,p=!1;const m=(g,b,v=!1)=>{p=!0,c=new Uint8Array,TV(l,g,b,v)};l.onData(g=>{if(u){u(g);return}if(d){d.push(g);return}if(p)return;const b=Math.max(0,c.byteLength-3);c=b2(c,g);const v=RV(c,b);if(v<0){c.byteLength>AV&&(console.warn(`CDP endpoint: a connection sent ${c.byteLength} bytes with no HTTP request header; it is answered 431 and closed. It starts ${JSON.stringify(new TextDecoder().decode(c.subarray(0,32)))}.`),m(431,{error:"request header too large"}));return}const S=$V(new TextDecoder().decode(c.subarray(0,v))),x=c.subarray(v+4);if(!S){m(400,{error:"malformed request"});return}const E=e.authorize?e.authorize(S):"control";if(!E){m(401,{error:"unauthorized"});return}if((S.headers.upgrade??"").toLowerCase()==="websocket"){const D=S.headers["sec-websocket-key"];if(S.method!=="GET"||!D||S.headers["sec-websocket-version"]!=="13"||!/\bupgrade\b/i.test(S.headers.connection??"")){m(400,{error:"invalid WebSocket handshake"});return}d=x.byteLength?[x]:[],NV(D).then(I=>{l.write(Cf.encode(`HTTP/1.1 101 Switching Protocols\r
3
3
  Upgrade: websocket\r
4
4
  Connection: Upgrade\r
@@ -1877,7 +1877,7 @@ connection: close\r
1877
1877
  `,r=async(n,s)=>(s.onStderr?.(t),{stdout:"",stderr:t,exitCode:1});for(const n of PF)e.runtime.registerProgram(n,r,{descriptors:!0});return BF(e.runtime,e.home,e.roots)}function BF(e,t,r){const n=e.filesystem;let s="";const i=async()=>{const o=(await U0e(n,r)).sort().join(",");o!==s&&(s=o,await F0e(n,`${t}/.cache/ms-playwright`,o?o.split(","):[]))},a=setInterval(()=>{i().catch(o=>console.error("Chromium face placement failed:",o))},2e3);return i().catch(o=>console.error("Chromium face placement failed:",o)),()=>clearInterval(a)}function K0e(e){const t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",xml:"text/xml",csv:"text/csv",pdf:"application/pdf",zip:"application/zip",gz:"application/gzip",wasm:"application/wasm",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",mp4:"video/mp4",webm:"video/webm",woff:"font/woff",woff2:"font/woff2"}[t]??""}const uE="314.0.6",Q0e=`https://cdn.jsdelivr.net/pyodide/v${uE}/full/`,J0e="/python-runtime-snapshot.bin",eye="/python-runtime-snapshot.json",tye=[{file:"pyodide.mjs",integrity:"sha256-aeP2zOw+FLRl32C+V3ymL1NiUUBrmgDM4BnqxSUqJJU=",bytes:17931},{file:"pyodide.asm.mjs",integrity:"sha256-KsXro2XsEoOcdcA7ObO+HdY7eYhSzEYLAUtSI4vgQvc=",bytes:1250344},{file:"pyodide.asm.wasm",integrity:"sha256-OgoA3+qjSKwg+e8JkEIz0y0z9kQzlmLUrzaPiiAQ83o=",bytes:9598218},{file:"python_stdlib.zip",integrity:"sha256-gMW+a6v+AylwaXA0EMPClATc8lJdKxKHRrrlU2+Ugx8=",bytes:2545564},{file:"pyodide-lock.json",integrity:"sha256-P9rvCenjZcheACc3cg+NCrjyeMHCRKLd5qN2Y89IitQ=",bytes:114440}];function rye(e){const t=tye.find(r=>r.file===e);if(!t)throw new Error(`Pyodide ${uE} publishes no pinned ${e}.`);return t}async function nye(e){const t=new Uint8Array(await crypto.subtle.digest("SHA-256",e));let r="";for(const n of t)r+=String.fromCharCode(n);return`sha256-${btoa(r)}`}const sye="modulepreload",iye=function(e){return"/"+e},VT={},Eh=function(t,r,n){let s=Promise.resolve();if(r&&r.length>0){let l=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),o=a?.nonce||a?.getAttribute("nonce");s=l(r.map(c=>{if(c=iye(c),c in VT)return;VT[c]=!0;const u=c.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${d}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":sye,u||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),u)return new Promise((m,g)=>{p.addEventListener("load",m),p.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return s.then(a=>{for(const o of a||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})},ZT="/workspace",aye=/^(?:pyodide(?:\.asm)?\.(?:m?js|wasm)|python_stdlib\.zip|pyodide-lock\.json|repodata\.json)$/u;function oye(e,t,r){if(t!=="GET"&&t!=="HEAD")throw new Error("Managed Python artifacts require GET or HEAD.");if(e.protocol!=="https:"||e.username||e.password||e.hash||e.search)throw new Error("Managed Python artifact URL is invalid.");const n=e.hostname==="cdn.jsdelivr.net"&&e.pathname.startsWith(new URL(Q0e).pathname),s=e.pathname.slice(e.pathname.lastIndexOf("/")+1);if(!(r==="runtime"&&n&&aye.test(s)))throw(n||r==="package")&&Lc({door:"python package",subject:e.href,fix:"a Python project's packages cannot yet be carried as packs, so the tab cannot provide them."}),new Error(`Python ${r} artifact request is outside the managed allowlist.`)}const lye=3e4;class cye{filesystem;options;filesystemCommitTail=Promise.resolve();standby;standbyTimer;nativeFetch=globalThis.fetch.bind(globalThis);activeFetches=0;networkBytes=0;constructor(t,r){this.filesystem=t,this.options=r}run=async(t,r={})=>{if(Pc(r.filesystemPolicy,void 0),r.signal?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:130});const n=await uye(r);if(r.signal?.aborted)return{stdout:"",stderr:"",exitCode:130};const s=this.standby!==void 0,i=await this.takeWorker(),a=s?void 0:await this.runtimeSnapshot(),o=new MessageChannel,l=this.options.sharedMemoryChannels!==!1,c=l?`python:${crypto.randomUUID()}`:void 0,u=l?sR():void 0,d=u&&c?nR.attach(u.server,c):void 0,p=l?eR():void 0,m=p?JN.attach(p.server,this.filesystem,()=>this.persistFilesystem()):void 0,g=RN(this.filesystem);g&&await this.filesystem.flush?.();const b=await N1(this.filesystem,"/",g?{metadataRoots:["/workspace"]}:{});let v=b;const S=this.options.server.attach(o.port1,{base:()=>v,advance:T=>{v=I7(v,T)}});let x=Promise.resolve(),E="",A="";return new Promise(T=>{let D=!1,I;const U=N=>{D||(D=!0,I!==void 0&&clearTimeout(I),r.signal?.removeEventListener("abort",O),S(),i.terminate(),m?.(),d?.(),T(N))},O=()=>{i.postMessage({type:"shutdown"}),I=setTimeout(()=>U({stdout:E,stderr:A,exitCode:130}),12e3)};r.signal?.addEventListener("abort",O,{once:!0}),i.onmessage=N=>{const F=N.data;if(F.type==="stdout"){E+=F.chunk,r.onStdout?.(F.chunk);return}if(F.type==="stderr"){A+=F.chunk,r.onStderr?.(F.chunk);return}if(F.type==="network-request"){this.handleNetwork(i,F);return}if(!("patch"in F))return;const P=v;if(v=I7(P,F.patch),x=x.then(()=>this.applyResult(P,F.patch)),F.type==="commit"){x.then(()=>i.postMessage({type:"commit-ack",commitId:F.commitId}),W=>i.postMessage({type:"commit-ack",commitId:F.commitId,error:W instanceof Error?W.message:String(W)}));return}F.type==="result"&&x.then(()=>{D||U({stdout:E,stderr:F.error?`${A}${F.error}
1878
1878
  `:A,exitCode:F.exitCode})},W=>U({stdout:E,stderr:`${A}${String(W)}
1879
1879
  `,exitCode:1}))},i.onerror=N=>U({stdout:E,stderr:`${A}${N.message}
1880
- `,exitCode:1});const _={type:"run",argv:[...t],cwd:r.cwd??this.options.cwd??"/workspace",env:{...this.options.env,...r.env},filesystem:b,...g?{store:{projectId:g}}:{},stdinBase64:fye(n),...this.options.runtimeIndexUrl?{runtimeIndexUrl:this.options.runtimeIndexUrl}:{},...a?{runtimeSnapshot:a.slice(0)}:{},serverPort:o.port2,...u&&c?{fileLocks:{channel:u.client,owner:c}}:{},...p?{fileCoherence:p.client}:{},sharedMemoryChannels:l};i.postMessage(_,[_.serverPort,..._.runtimeSnapshot?[_.runtimeSnapshot]:[],..._.fileLocks?[_.fileLocks.channel.port]:[],..._.fileCoherence?[_.fileCoherence.port]:[]])})};snapshot;runtimeSnapshot(){const t=this.options.runtimeSnapshotUrl;return t?(this.snapshot??=(async()=>{try{const r=await this.nativeFetch(t,{cache:"no-cache",credentials:"same-origin"});if(!r.ok)return;const n=await r.json();if(n.format!==1||n.pyodide!==uE||n.engine!==rye("pyodide.asm.wasm").integrity)return;const s=await this.nativeFetch(new URL(J0e,t),{credentials:"same-origin"});if(!s.ok)return;const i=await s.arrayBuffer();return await nye(new Uint8Array(i))===n.integrity?i:void 0}catch{return}})(),this.snapshot):Promise.resolve(void 0)}createWorker(){return this.options.createWorker?this.options.createWorker():Promise.resolve(kf(new Worker(new URL("/assets/worker-BZ-Txq9L.js",import.meta.url),{type:"module",name:"browser-python"})))}takeWorker(){const t=this.standby;this.standby=void 0,this.standbyTimer!==void 0&&clearTimeout(this.standbyTimer);const r=t??this.createWorker(),n=this.createWorker().then(async s=>{s.onmessage=o=>{const l=o.data;l.type==="network-request"&&this.handleNetwork(s,l)};const a=(await this.runtimeSnapshot())?.slice(0);return s.postMessage({type:"prepare",...this.options.runtimeIndexUrl?{runtimeIndexUrl:this.options.runtimeIndexUrl}:{},...a?{runtimeSnapshot:a}:{}},a?[a]:[]),s});return n.catch(()=>{}),this.standby=n,this.standbyTimer=setTimeout(()=>{this.standby===n&&(this.standby=void 0,n.then(s=>s.terminate(),()=>{}))},lye),r}async applyResult(t,r){const n=this.filesystemCommitTail.then(async()=>{M1(this.filesystem,r,t),await this.options.onFilesystemCommit?.(this.filesystem)});this.filesystemCommitTail=n.catch(()=>{}),await n}async persistFilesystem(){const t=this.filesystemCommitTail.then(()=>this.options.onFilesystemCommit?.(this.filesystem));this.filesystemCommitTail=t.then(()=>{},()=>{}),await t}async handleNetwork(t,r){try{const n=new URL(r.url);if(n.protocol!=="https:"||n.username||n.password)throw new Error("Browser Python external requests require credential-free HTTPS URLs.");if(r.purpose==="program"){if(!this.options.network)throw new Error("Browser Python egress has no embedding grant.");this.options.network.authorize(n)}else oye(n,r.method,r.purpose);const s=this.options.network?.maxConnections??16,i=this.options.network?.maxBytes??64*1024*1024;if(this.activeFetches>=s)throw new Error("Browser Python egress connection limit exceeded.");this.consumeNetwork(r.body.byteLength,i),this.activeFetches+=1;let a;try{a=await this.nativeFetch(n,{method:r.method,headers:dye(r.headers),...r.body.byteLength>0?{body:r.body}:{},credentials:"omit",redirect:"error"})}finally{this.activeFetches-=1}const o=Number(a.headers.get("content-length"));if(Number.isFinite(o)&&o>=0&&o>i-this.networkBytes)throw new Error("Browser Python egress byte limit exceeded.");const l=await a.arrayBuffer();this.consumeNetwork(l.byteLength,i),t.postMessage({type:"network-response",requestId:r.requestId,status:a.status,statusText:a.statusText,headers:[...a.headers.entries()],body:l},[l])}catch(n){console.warn(`Browser Python request to ${r.url} failed: ${n instanceof Error?n.message:String(n)}`),t.postMessage({type:"network-error",requestId:r.requestId,error:n instanceof Error?n.message:String(n)})}}consumeNetwork(t,r){if(!Number.isSafeInteger(t)||t<0||this.networkBytes>r-t)throw new Error("Browser Python egress byte limit exceeded.");this.networkBytes+=t}}async function uye(e){const t=[];let r=0;if(e.stdin){const i=new TextEncoder().encode(e.stdin);t.push(i),r+=i.byteLength}if(e.stdinStream)for await(const i of e.stdinStream){const a=i.slice();if(r+=a.byteLength,r>16*1024*1024)throw new Error("Python stdin exceeds 16 MiB.");t.push(a)}const n=new Uint8Array(r);let s=0;for(const i of t)n.set(i,s),s+=i.byteLength;return n}function fye(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function dye(e){const t=new Headers;for(const[r,n]of e){const s=r.toLowerCase();["cookie","host","origin","referer"].includes(s)||s.startsWith("sec-")||s.startsWith("proxy-")||t.append(r,n)}return t}const YT=8,hye=64*1024,XT=16*1024*1024,pye=16*1024*1024,mye=1024*1024;class gye{filesystem;sync;backend;controllers=new Map;children=new Map;nextChildId=1;active=0;closed=!1;changeQueue=Promise.resolve();constructor(t,r,n){this.filesystem=t,this.sync=r,this.backend=n}handles(t){return t.type==="process-run"||t.type==="process-cancel"||t.type==="process-start"||t.type==="process-action"}handle(t){t.type==="process-cancel"?this.controllers.get(t.requestId)?.abort(new DOMException("Python subprocess cancelled.","AbortError")):t.type==="process-run"?this.run(t):t.type==="process-start"?this.start(t):this.act(t)}close(){if(!this.closed){this.closed=!0;for(const t of this.controllers.values())t.abort(new DOMException("Python server process exited.","AbortError"));this.controllers.clear();for(const t of this.children.values())t.stdin?.close(),t.controller.abort(new DOMException("Python server process exited.","AbortError"));this.children.clear()}}run(t){if(this.active>=YT){ci(t,{error:"Python subprocess concurrency exceeded."});return}this.active+=1;const r=new AbortController;this.controllers.set(t.requestId,r),this.runOnce(t,r.signal).finally(()=>{this.active-=1,this.controllers.delete(t.requestId)})}async runOnce(t,r){try{const n=this.requiredBackend();JT(t.command,t.cwd,t.env);const s=qv(t.stdinBase64);if(s.byteLength>XT)throw new Error("Python subprocess stdin exceeds 16 MiB.");const i=await n.run(t.command,{cwd:t.cwd,env:t.env,signal:r,...s.byteLength>0?{stdinStream:bye(s)}:{}});ci(t,{result:i,patch:await this.childChanges()})}catch(n){ci(t,{error:E1(n)})}}childChanges(){const t=this.changeQueue.then(async()=>{const r=this.sync.base(),n=D1(r,this.filesystem.toSnapshot()),s=[];for(const a of n.files){if(!QT(a.path))continue;if(a.type!=="file"||a.content!==void 0){s.push(a);continue}const{size:o,...l}=a;s.push({...l,content:e$(await this.filesystem.readFile(a.path))})}const i={files:s,removed:n.removed.filter(QT)};return this.sync.advance(i),i});return this.changeQueue=t.catch(()=>{}),t}start(t){try{const r=this.requiredBackend();if(this.closed)throw new Error("Python child-process host is closed.");if(this.active>=YT)throw new Error("Python subprocess concurrency exceeded.");JT(t.command,t.cwd,t.env);const n=this.nextChildId++,s=new AbortController,i=t.stdinPipe?new yye:void 0,a=t.stdoutPipe?new KT:void 0,o=t.stderrPipe&&!t.stderrToStdout?new KT:void 0,l={controller:s,stdin:i,stdout:a,stderr:o};let c=!1,u=!1;const d=(p,m)=>{if(p)try{p.write(new TextEncoder().encode(m))}catch(g){throw s.abort(g),g}};this.active+=1,l.completion=r.run(t.command,{cwd:t.cwd,env:t.env,signal:s.signal,...i?{stdinStream:i}:{},...a||t.stderrToStdout?{onStdout:p=>{c=!0,d(a,p)}}:{},...o||t.stderrToStdout?{onStderr:p=>{u=!0,d(t.stderrToStdout?a:o,p)}}:{}}).then(p=>(a&&p.stdout&&!c&&d(a,p.stdout),t.stderrToStdout&&p.stderr&&!u?d(a,p.stderr):o&&p.stderr&&!u&&d(o,p.stderr),{result:p}),p=>({error:E1(p)})).then(p=>(l.finished=p,a?.close(),o?.close(),this.active-=1,p)),this.children.set(n,l),ci(t,{childId:n})}catch(r){ci(t,{error:E1(r)})}}async act(t){try{const r=this.children.get(t.childId);if(!r)throw new Error("Unknown browser subprocess.");if(t.action==="poll"){ci(t,{returncode:r.finished?.result?.exitCode??null});return}if(t.action==="write"){if(!r.stdin)throw new Error("Browser subprocess stdin is not a pipe.");const s=qv(t.stdinBase64??"");if(s.byteLength>XT)throw new Error("Python subprocess stdin exceeds 16 MiB.");r.stdin.write(s),ci(t,{written:s.byteLength});return}if(t.action==="read"){const s=t.stream==="stdout"?r.stdout:t.stream==="stderr"?r.stderr:void 0;if(!s)throw new Error("Browser subprocess output is not a pipe.");const i=t.maximum??64*1024;if(!Number.isSafeInteger(i)||i<=0||i>mye)throw new Error("Invalid browser subprocess read size.");const a=await s.read(i);ci(t,{dataBase64:e$(a.bytes),eof:a.eof});return}if(t.action==="close"){r.stdin?.close(),ci(t,{});return}if(t.action==="terminate"){r.stdin?.close(),r.controller.abort(new DOMException("Python subprocess terminated.","AbortError")),ci(t,{});return}if(t.action==="release"){if(!r.finished)throw new Error("Cannot release a running browser subprocess.");this.children.delete(t.childId),ci(t,{});return}t.stdinBase64&&r.stdin?.write(qv(t.stdinBase64)),t.closeStdin&&r.stdin?.close();const n=await r.completion;ci(t,{...n,patch:await this.childChanges()})}catch(r){ci(t,{error:E1(r)})}}requiredBackend(){if(!this.backend)throw new Error("No browser child-process backend is configured.");return this.backend}}class yye{chunks=[];readers=[];closed=!1;[Symbol.asyncIterator](){return this}next(){const t=this.chunks.shift();return t?Promise.resolve({value:t,done:!1}):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise(r=>this.readers.push(r))}write(t){if(this.closed)throw new Error("write to closed browser subprocess stdin");const r=t.slice(),n=this.readers.shift();n?n({value:r,done:!1}):this.chunks.push(r)}close(){if(!this.closed){this.closed=!0;for(const t of this.readers.splice(0))t({value:void 0,done:!0})}}}class KT{chunks=[];readers=[];length=0;closed=!1;write(t){if(!(this.closed||t.byteLength===0)){if(this.length+t.byteLength>pye)throw new Error("Python subprocess output pipe exceeded 16 MiB without being drained.");this.chunks.push(t.slice()),this.length+=t.byteLength,this.wake()}}close(){this.closed||(this.closed=!0,this.wake())}async read(t){for(;this.length===0&&!this.closed;)await new Promise(i=>this.readers.push(i));if(this.length===0)return{bytes:new Uint8Array,eof:!0};const r=Math.min(t,this.length),n=new Uint8Array(r);let s=0;for(;s<r;){const i=this.chunks[0],a=Math.min(i.byteLength,r-s);n.set(i.subarray(0,a),s),s+=a,this.length-=a,a===i.byteLength?this.chunks.shift():this.chunks[0]=i.subarray(a)}return{bytes:n,eof:this.closed&&this.length===0}}wake(){for(const t of this.readers.splice(0))t()}}function QT(e){return e===ZT||e.startsWith(`${ZT}/`)}function JT(e,t,r){if(!e||e.length>hye||!t.startsWith("/")||t.length>16384||Object.keys(r).length>256)throw new Error("Invalid Python subprocess request.")}function ci(e,t){const r=new Int32Array(e.control),n=new Uint8Array(e.response);let s=new TextEncoder().encode(JSON.stringify(t));s.byteLength>n.byteLength&&(s=new TextEncoder().encode(JSON.stringify({error:"Python subprocess response exceeds 16 MiB."}))),n.set(s),Atomics.store(r,1,s.byteLength),Atomics.store(r,0,1),Atomics.notify(r,0)}function qv(e){const t=atob(e);return Uint8Array.from(t,r=>r.charCodeAt(0))}function e$(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function*bye(e){yield e}function E1(e){return e instanceof Error?e.message:String(e)}const Gv=32,t$=16*1024*1024,r$=32*1024*1024,zF=100,jF=32*1024,e6=3e4,wye=1024*1024,WF=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;class vye{filesystem;bridge;processHost;webSocketRegistry;nextWebSocketConnection=1;streamingServers=new Map;constructor(t,r,n,s){this.filesystem=t,this.bridge=r,this.processHost=n,this.webSocketRegistry=s}handleStreamingRequest(t,r,n,s,i,a){return this.streamingServers.get(t)?.(r,n,s,i,a)??Promise.resolve(!1)}attach(t,r){const n=new Set,s=new Map,i=new Map;let a=1;const o=new gye(this.filesystem,r,this.processHost),l=new Map,c=new Map;let u=!1;const d=b=>{u||t.postMessage(b)},p=(b,v,S,x,E)=>{if(u)return Promise.reject(new Error("Python server process exited."));if(s.size+i.size>=Gv)return Promise.resolve(tf(503,"Service Unavailable",`Python server request concurrency exceeded.
1880
+ `,exitCode:1});const _={type:"run",argv:[...t],cwd:r.cwd??this.options.cwd??"/workspace",env:{...this.options.env,...r.env},filesystem:b,...g?{store:{projectId:g}}:{},stdinBase64:fye(n),...this.options.runtimeIndexUrl?{runtimeIndexUrl:this.options.runtimeIndexUrl}:{},...a?{runtimeSnapshot:a.slice(0)}:{},serverPort:o.port2,...u&&c?{fileLocks:{channel:u.client,owner:c}}:{},...p?{fileCoherence:p.client}:{},sharedMemoryChannels:l};i.postMessage(_,[_.serverPort,..._.runtimeSnapshot?[_.runtimeSnapshot]:[],..._.fileLocks?[_.fileLocks.channel.port]:[],..._.fileCoherence?[_.fileCoherence.port]:[]])})};snapshot;runtimeSnapshot(){const t=this.options.runtimeSnapshotUrl;return t?(this.snapshot??=(async()=>{try{const r=await this.nativeFetch(t,{cache:"no-cache",credentials:"same-origin"});if(!r.ok)return;const n=await r.json();if(n.format!==1||n.pyodide!==uE||n.engine!==rye("pyodide.asm.wasm").integrity)return;const s=await this.nativeFetch(new URL(J0e,t),{credentials:"same-origin"});if(!s.ok)return;const i=await s.arrayBuffer();return await nye(new Uint8Array(i))===n.integrity?i:void 0}catch{return}})(),this.snapshot):Promise.resolve(void 0)}createWorker(){return this.options.createWorker?this.options.createWorker():Promise.resolve(kf(new Worker(new URL("/assets/worker-BCIFrV5h.js",import.meta.url),{type:"module",name:"browser-python"})))}takeWorker(){const t=this.standby;this.standby=void 0,this.standbyTimer!==void 0&&clearTimeout(this.standbyTimer);const r=t??this.createWorker(),n=this.createWorker().then(async s=>{s.onmessage=o=>{const l=o.data;l.type==="network-request"&&this.handleNetwork(s,l)};const a=(await this.runtimeSnapshot())?.slice(0);return s.postMessage({type:"prepare",...this.options.runtimeIndexUrl?{runtimeIndexUrl:this.options.runtimeIndexUrl}:{},...a?{runtimeSnapshot:a}:{}},a?[a]:[]),s});return n.catch(()=>{}),this.standby=n,this.standbyTimer=setTimeout(()=>{this.standby===n&&(this.standby=void 0,n.then(s=>s.terminate(),()=>{}))},lye),r}async applyResult(t,r){const n=this.filesystemCommitTail.then(async()=>{M1(this.filesystem,r,t),await this.options.onFilesystemCommit?.(this.filesystem)});this.filesystemCommitTail=n.catch(()=>{}),await n}async persistFilesystem(){const t=this.filesystemCommitTail.then(()=>this.options.onFilesystemCommit?.(this.filesystem));this.filesystemCommitTail=t.then(()=>{},()=>{}),await t}async handleNetwork(t,r){try{const n=new URL(r.url);if(n.protocol!=="https:"||n.username||n.password)throw new Error("Browser Python external requests require credential-free HTTPS URLs.");if(r.purpose==="program"){if(!this.options.network)throw new Error("Browser Python egress has no embedding grant.");this.options.network.authorize(n)}else oye(n,r.method,r.purpose);const s=this.options.network?.maxConnections??16,i=this.options.network?.maxBytes??64*1024*1024;if(this.activeFetches>=s)throw new Error("Browser Python egress connection limit exceeded.");this.consumeNetwork(r.body.byteLength,i),this.activeFetches+=1;let a;try{a=await this.nativeFetch(n,{method:r.method,headers:dye(r.headers),...r.body.byteLength>0?{body:r.body}:{},credentials:"omit",redirect:"error"})}finally{this.activeFetches-=1}const o=Number(a.headers.get("content-length"));if(Number.isFinite(o)&&o>=0&&o>i-this.networkBytes)throw new Error("Browser Python egress byte limit exceeded.");const l=await a.arrayBuffer();this.consumeNetwork(l.byteLength,i),t.postMessage({type:"network-response",requestId:r.requestId,status:a.status,statusText:a.statusText,headers:[...a.headers.entries()],body:l},[l])}catch(n){console.warn(`Browser Python request to ${r.url} failed: ${n instanceof Error?n.message:String(n)}`),t.postMessage({type:"network-error",requestId:r.requestId,error:n instanceof Error?n.message:String(n)})}}consumeNetwork(t,r){if(!Number.isSafeInteger(t)||t<0||this.networkBytes>r-t)throw new Error("Browser Python egress byte limit exceeded.");this.networkBytes+=t}}async function uye(e){const t=[];let r=0;if(e.stdin){const i=new TextEncoder().encode(e.stdin);t.push(i),r+=i.byteLength}if(e.stdinStream)for await(const i of e.stdinStream){const a=i.slice();if(r+=a.byteLength,r>16*1024*1024)throw new Error("Python stdin exceeds 16 MiB.");t.push(a)}const n=new Uint8Array(r);let s=0;for(const i of t)n.set(i,s),s+=i.byteLength;return n}function fye(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function dye(e){const t=new Headers;for(const[r,n]of e){const s=r.toLowerCase();["cookie","host","origin","referer"].includes(s)||s.startsWith("sec-")||s.startsWith("proxy-")||t.append(r,n)}return t}const YT=8,hye=64*1024,XT=16*1024*1024,pye=16*1024*1024,mye=1024*1024;class gye{filesystem;sync;backend;controllers=new Map;children=new Map;nextChildId=1;active=0;closed=!1;changeQueue=Promise.resolve();constructor(t,r,n){this.filesystem=t,this.sync=r,this.backend=n}handles(t){return t.type==="process-run"||t.type==="process-cancel"||t.type==="process-start"||t.type==="process-action"}handle(t){t.type==="process-cancel"?this.controllers.get(t.requestId)?.abort(new DOMException("Python subprocess cancelled.","AbortError")):t.type==="process-run"?this.run(t):t.type==="process-start"?this.start(t):this.act(t)}close(){if(!this.closed){this.closed=!0;for(const t of this.controllers.values())t.abort(new DOMException("Python server process exited.","AbortError"));this.controllers.clear();for(const t of this.children.values())t.stdin?.close(),t.controller.abort(new DOMException("Python server process exited.","AbortError"));this.children.clear()}}run(t){if(this.active>=YT){ci(t,{error:"Python subprocess concurrency exceeded."});return}this.active+=1;const r=new AbortController;this.controllers.set(t.requestId,r),this.runOnce(t,r.signal).finally(()=>{this.active-=1,this.controllers.delete(t.requestId)})}async runOnce(t,r){try{const n=this.requiredBackend();JT(t.command,t.cwd,t.env);const s=qv(t.stdinBase64);if(s.byteLength>XT)throw new Error("Python subprocess stdin exceeds 16 MiB.");const i=await n.run(t.command,{cwd:t.cwd,env:t.env,signal:r,...s.byteLength>0?{stdinStream:bye(s)}:{}});ci(t,{result:i,patch:await this.childChanges()})}catch(n){ci(t,{error:E1(n)})}}childChanges(){const t=this.changeQueue.then(async()=>{const r=this.sync.base(),n=D1(r,this.filesystem.toSnapshot()),s=[];for(const a of n.files){if(!QT(a.path))continue;if(a.type!=="file"||a.content!==void 0){s.push(a);continue}const{size:o,...l}=a;s.push({...l,content:e$(await this.filesystem.readFile(a.path))})}const i={files:s,removed:n.removed.filter(QT)};return this.sync.advance(i),i});return this.changeQueue=t.catch(()=>{}),t}start(t){try{const r=this.requiredBackend();if(this.closed)throw new Error("Python child-process host is closed.");if(this.active>=YT)throw new Error("Python subprocess concurrency exceeded.");JT(t.command,t.cwd,t.env);const n=this.nextChildId++,s=new AbortController,i=t.stdinPipe?new yye:void 0,a=t.stdoutPipe?new KT:void 0,o=t.stderrPipe&&!t.stderrToStdout?new KT:void 0,l={controller:s,stdin:i,stdout:a,stderr:o};let c=!1,u=!1;const d=(p,m)=>{if(p)try{p.write(new TextEncoder().encode(m))}catch(g){throw s.abort(g),g}};this.active+=1,l.completion=r.run(t.command,{cwd:t.cwd,env:t.env,signal:s.signal,...i?{stdinStream:i}:{},...a||t.stderrToStdout?{onStdout:p=>{c=!0,d(a,p)}}:{},...o||t.stderrToStdout?{onStderr:p=>{u=!0,d(t.stderrToStdout?a:o,p)}}:{}}).then(p=>(a&&p.stdout&&!c&&d(a,p.stdout),t.stderrToStdout&&p.stderr&&!u?d(a,p.stderr):o&&p.stderr&&!u&&d(o,p.stderr),{result:p}),p=>({error:E1(p)})).then(p=>(l.finished=p,a?.close(),o?.close(),this.active-=1,p)),this.children.set(n,l),ci(t,{childId:n})}catch(r){ci(t,{error:E1(r)})}}async act(t){try{const r=this.children.get(t.childId);if(!r)throw new Error("Unknown browser subprocess.");if(t.action==="poll"){ci(t,{returncode:r.finished?.result?.exitCode??null});return}if(t.action==="write"){if(!r.stdin)throw new Error("Browser subprocess stdin is not a pipe.");const s=qv(t.stdinBase64??"");if(s.byteLength>XT)throw new Error("Python subprocess stdin exceeds 16 MiB.");r.stdin.write(s),ci(t,{written:s.byteLength});return}if(t.action==="read"){const s=t.stream==="stdout"?r.stdout:t.stream==="stderr"?r.stderr:void 0;if(!s)throw new Error("Browser subprocess output is not a pipe.");const i=t.maximum??64*1024;if(!Number.isSafeInteger(i)||i<=0||i>mye)throw new Error("Invalid browser subprocess read size.");const a=await s.read(i);ci(t,{dataBase64:e$(a.bytes),eof:a.eof});return}if(t.action==="close"){r.stdin?.close(),ci(t,{});return}if(t.action==="terminate"){r.stdin?.close(),r.controller.abort(new DOMException("Python subprocess terminated.","AbortError")),ci(t,{});return}if(t.action==="release"){if(!r.finished)throw new Error("Cannot release a running browser subprocess.");this.children.delete(t.childId),ci(t,{});return}t.stdinBase64&&r.stdin?.write(qv(t.stdinBase64)),t.closeStdin&&r.stdin?.close();const n=await r.completion;ci(t,{...n,patch:await this.childChanges()})}catch(r){ci(t,{error:E1(r)})}}requiredBackend(){if(!this.backend)throw new Error("No browser child-process backend is configured.");return this.backend}}class yye{chunks=[];readers=[];closed=!1;[Symbol.asyncIterator](){return this}next(){const t=this.chunks.shift();return t?Promise.resolve({value:t,done:!1}):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise(r=>this.readers.push(r))}write(t){if(this.closed)throw new Error("write to closed browser subprocess stdin");const r=t.slice(),n=this.readers.shift();n?n({value:r,done:!1}):this.chunks.push(r)}close(){if(!this.closed){this.closed=!0;for(const t of this.readers.splice(0))t({value:void 0,done:!0})}}}class KT{chunks=[];readers=[];length=0;closed=!1;write(t){if(!(this.closed||t.byteLength===0)){if(this.length+t.byteLength>pye)throw new Error("Python subprocess output pipe exceeded 16 MiB without being drained.");this.chunks.push(t.slice()),this.length+=t.byteLength,this.wake()}}close(){this.closed||(this.closed=!0,this.wake())}async read(t){for(;this.length===0&&!this.closed;)await new Promise(i=>this.readers.push(i));if(this.length===0)return{bytes:new Uint8Array,eof:!0};const r=Math.min(t,this.length),n=new Uint8Array(r);let s=0;for(;s<r;){const i=this.chunks[0],a=Math.min(i.byteLength,r-s);n.set(i.subarray(0,a),s),s+=a,this.length-=a,a===i.byteLength?this.chunks.shift():this.chunks[0]=i.subarray(a)}return{bytes:n,eof:this.closed&&this.length===0}}wake(){for(const t of this.readers.splice(0))t()}}function QT(e){return e===ZT||e.startsWith(`${ZT}/`)}function JT(e,t,r){if(!e||e.length>hye||!t.startsWith("/")||t.length>16384||Object.keys(r).length>256)throw new Error("Invalid Python subprocess request.")}function ci(e,t){const r=new Int32Array(e.control),n=new Uint8Array(e.response);let s=new TextEncoder().encode(JSON.stringify(t));s.byteLength>n.byteLength&&(s=new TextEncoder().encode(JSON.stringify({error:"Python subprocess response exceeds 16 MiB."}))),n.set(s),Atomics.store(r,1,s.byteLength),Atomics.store(r,0,1),Atomics.notify(r,0)}function qv(e){const t=atob(e);return Uint8Array.from(t,r=>r.charCodeAt(0))}function e$(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function*bye(e){yield e}function E1(e){return e instanceof Error?e.message:String(e)}const Gv=32,t$=16*1024*1024,r$=32*1024*1024,zF=100,jF=32*1024,e6=3e4,wye=1024*1024,WF=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;class vye{filesystem;bridge;processHost;webSocketRegistry;nextWebSocketConnection=1;streamingServers=new Map;constructor(t,r,n,s){this.filesystem=t,this.bridge=r,this.processHost=n,this.webSocketRegistry=s}handleStreamingRequest(t,r,n,s,i,a){return this.streamingServers.get(t)?.(r,n,s,i,a)??Promise.resolve(!1)}attach(t,r){const n=new Set,s=new Map,i=new Map;let a=1;const o=new gye(this.filesystem,r,this.processHost),l=new Map,c=new Map;let u=!1;const d=b=>{u||t.postMessage(b)},p=(b,v,S,x,E)=>{if(u)return Promise.reject(new Error("Python server process exited."));if(s.size+i.size>=Gv)return Promise.resolve(tf(503,"Service Unavailable",`Python server request concurrency exceeded.
1881
1881
  `));const A=s$(E);if(A.byteLength>t$)return Promise.resolve(tf(413,"Payload Too Large",`Request body exceeds 16 MiB.
1882
1882
  `));a$(x);const T=a++;return new Promise((D,I)=>{const U=window.setTimeout(()=>{s.delete(T),I(new Error("Python server request timed out."))},e6);s.set(T,{resolve:D,reject:I,timeout:U}),d({type:"http-request",requestId:T,application:b,method:v,url:S,headers:x,bodyBase64:l$(A)})})},m=(b,v,S,x,E)=>{if(u)return Promise.reject(new Error("Python server process exited."));if(s.size+i.size>=Gv)return Promise.reject(new Error("Python server request concurrency exceeded."));const A=s$(x);if(A.byteLength>t$)return Promise.reject(new Error("Request body exceeds 16 MiB."));a$(S);const T=a++;return new Promise((D,I)=>{const U=window.setTimeout(()=>{const O=i.get(T);O&&(i.delete(T),O.started?(O.callbacks.end(),O.resolve(!0)):O.reject(new Error("Python streaming response timed out.")))},e6);i.set(T,{callbacks:E,resolve:D,reject:I,timeout:U,bytes:0,started:!1}),d({type:"http-request",requestId:T,application:"asgi",method:b,url:v,headers:S,bodyBase64:l$(A),streaming:!0})})},g=(b,v,S)=>{if(u)throw new Error("Python server process exited.");if(l.size>=Gv)throw new Error("Python WebSocket concurrency exceeded.");const x=this.nextWebSocketConnection++;return l.set(x,{handlers:S,protocols:v}),d({type:"websocket-open",connectionId:x,path:b,protocols:[...v]}),{send:E=>{if(!l.has(x))throw new Error("Python WebSocket is closed.");i$(E),d({type:"websocket-message",connectionId:x,data:E.kind==="text"?E:{kind:"binary",base64:$N(E)}})},close:(E=1e3,A="")=>{l.has(x)&&d({type:"websocket-close",connectionId:x,code:E,reason:A})},abort:()=>{l.delete(x)&&d({type:"websocket-close",connectionId:x,code:1006,reason:""})}}};return t.onmessage=b=>{const v=b.data;if(v.type==="websocket-opened"){const x=l.get(v.connectionId);if(!x)return;v.protocol&&!x.protocols.includes(v.protocol)?(x.handlers.error("Python ASGI app selected an unrequested WebSocket protocol."),x.handlers.close(1002,"Invalid subprotocol",!1),l.delete(v.connectionId)):x.handlers.open(v.protocol);return}if(v.type==="websocket-message"){const x=l.get(v.connectionId);if(!x)return;try{i$(v.data),x.handlers.message(v.data)}catch(E){x.handlers.error(E instanceof Error?E.message:String(E)),x.handlers.close(1009,"Frame too large",!1),l.delete(v.connectionId)}return}if(v.type==="websocket-close"){const x=l.get(v.connectionId);if(!x)return;l.delete(v.connectionId);try{xye(v.code,v.reason),x.handlers.close(v.code,v.reason,v.clean)}catch(E){x.handlers.error(E instanceof Error?E.message:String(E)),x.handlers.close(1002,"Invalid close frame",!1)}return}if(v.type==="websocket-error"){const x=l.get(v.connectionId);if(!x)return;x.handlers.error(v.error);return}if(o.handles(v)){o.handle(v);return}if(v.type==="http-stream-start"){const x=i.get(v.requestId);if(!x)return;try{o$(v.statusCode,v.statusMessage,v.headers),x.callbacks.start(v.statusCode,v.statusMessage,v.headers),x.started=!0,n$(x,v.requestId,i)}catch(E){Vv(v.requestId,x,i,E)}return}if(v.type==="http-stream-chunk"){const x=i.get(v.requestId);if(!x)return;try{if(!x.started)throw new Error("Python stream emitted a body before response start.");const E=c$(v.bodyBase64);if(x.bytes+=E.byteLength,x.bytes>r$)throw new Error("Python server response exceeds 32 MiB.");x.callbacks.chunk(E),n$(x,v.requestId,i)}catch(E){Vv(v.requestId,x,i,E)}return}if(v.type==="http-stream-end"){const x=i.get(v.requestId);if(!x)return;i.delete(v.requestId),clearTimeout(x.timeout),x.started?(x.callbacks.end(),x.resolve(!0)):x.reject(new Error("Python stream ended before response start."));return}if(v.type==="http-stream-error"){const x=i.get(v.requestId);if(!x)return;Vv(v.requestId,x,i,new Error(v.error));return}if(v.type==="http-response"){const x=s.get(v.requestId);if(!x)return;s.delete(v.requestId),clearTimeout(x.timeout);try{if(v.error)throw new Error(v.error);const E=c$(v.bodyBase64);if(E.byteLength>r$)throw new Error("Python server response exceeds 32 MiB.");o$(v.statusCode,v.statusMessage,v.headers),x.resolve({statusCode:v.statusCode,statusMessage:v.statusMessage,headers:v.headers,body:E})}catch(E){x.reject(E)}return}let S=0;if(!Aye(v.port)||this.bridge.getServerPorts().includes(v.port))S=-98;else try{const x=v.server==="static"?(A,T)=>Promise.resolve(this.handleStatic(HF(v.root),A,T)):(A,T,D,I)=>p(v.server,A,T,D,I),E={listening:!0,address:()=>({port:v.port,address:"0.0.0.0",family:"IPv4"}),handleRequest:x};this.bridge.registerServer(E,v.port),n.add(v.port),v.server==="asgi"&&(this.streamingServers.set(v.port,m),this.webSocketRegistry&&c.set(v.port,this.webSocketRegistry.register(v.port,{open:(A,T,D)=>g(A,T,D)})))}catch{c.get(v.port)?.(),c.delete(v.port),this.streamingServers.delete(v.port),this.bridge.unregisterServer(v.port),S=-98}d({type:"ack",requestId:v.requestId,result:S})},t.start(),()=>{if(!u){u=!0;for(const b of n)this.bridge.unregisterServer(b);for(const b of n)this.streamingServers.delete(b);for(const b of c.values())b();c.clear(),n.clear();for(const b of s.values())clearTimeout(b.timeout),b.reject(new Error("Python server process exited."));s.clear();for(const b of i.values())clearTimeout(b.timeout),b.started?(b.callbacks.end(),b.resolve(!0)):b.reject(new Error("Python server process exited."));i.clear();for(const b of l.values())b.handlers.error("Python server process exited."),b.handlers.close(1011,"Python server process exited",!1);l.clear(),o.close(),t.close()}}}async handleStatic(t,r,n){if(r!=="GET"&&r!=="HEAD")return tf(405,"Method Not Allowed",`Method not allowed
1883
1883
  `);let s;try{s=Sye(t,n)}catch{return tf(400,"Bad Request",`Bad request
@@ -1886,8 +1886,8 @@ connection: close\r
1886
1886
  `);const i=r==="HEAD"?new Uint8Array:await this.filesystem.readFile(s);return{statusCode:200,statusMessage:"OK",headers:{"content-type":kye(s),"content-length":String(this.filesystem.statSync(s).size),"cache-control":"no-store"},body:i}}}function n$(e,t,r){clearTimeout(e.timeout),e.timeout=window.setTimeout(()=>{r.has(t)&&(r.delete(t),e.started?(e.callbacks.end(),e.resolve(!0)):e.reject(new Error("Python streaming response timed out.")))},e6)}function Vv(e,t,r,n){r.delete(e),clearTimeout(t.timeout),t.started?(t.callbacks.end(),t.resolve(!0)):t.reject(n)}function s$(e){if(e==null)return new Uint8Array;if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return Uint8Array.from(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));throw new Error("Unsupported Python request body.")}function i$(e){if((e.kind==="text"?new TextEncoder().encode(e.text).byteLength:up(e).byteLength)>wye)throw new Error("Python WebSocket frame exceeds 1 MiB.")}function xye(e,t){if(!Number.isInteger(e)||e<1e3||e>4999||[1004,1005,1006,1015].includes(e))throw new Error("Invalid Python WebSocket close code.");if(new TextEncoder().encode(t).byteLength>123)throw new Error("Python WebSocket close reason is too large.")}function a$(e){const t=Object.entries(e);if(t.length>zF)throw new Error("Python request has too many headers.");let r=0;for(const[n,s]of t){if(!WF.test(n)||/[\u0000\r\n]/u.test(s))throw new Error("Malformed Python request header.");r+=n.length+s.length}if(r>jF)throw new Error("Python request headers are too large.")}function o$(e,t,r){if(!Number.isInteger(e)||e<100||e>599||/[\u0000\r\n]/u.test(t))throw new Error("Malformed Python response status.");const n=Object.entries(r);if(n.length>zF)throw new Error("Python response has too many headers.");let s=0;for(const[i,a]of n){const o=Array.isArray(a)?a:[a];if(!WF.test(i)||o.some(l=>/[\u0000\r\n]/u.test(l)))throw new Error("Malformed Python response header.");s+=i.length+o.reduce((l,c)=>l+c.length,0)}if(s>jF)throw new Error("Python response headers are too large.")}function Sye(e,t){const r=decodeURIComponent(new URL(t,"http://localhost").pathname);if(r.includes("\0"))throw new Error("Invalid path");const n=HF(`${e}/${r}`);if(n!==e&&!n.startsWith(`${e}/`))throw new Error("Path escapes root");return n}function HF(e){const t=[];for(const r of e.replaceAll("\\","/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Eye(e,t,r){const n=`<!doctype html><title>Directory listing for ${Zv(e)}</title><h1>Directory listing for ${Zv(e)}</h1><ul>${t.sort().map(i=>`<li><a href="${encodeURIComponent(i)}">${Zv(i)}</a></li>`).join("")}</ul>`,s=new TextEncoder().encode(n);return{statusCode:200,statusMessage:"OK",headers:{"content-type":"text/html; charset=utf-8","content-length":String(s.byteLength),"cache-control":"no-store"},body:r?new Uint8Array:s}}function tf(e,t,r){const n=new TextEncoder().encode(r);return{statusCode:e,statusMessage:t,headers:{"content-type":"text/plain; charset=utf-8","content-length":String(n.byteLength),"cache-control":"no-store"},body:n}}function kye(e){const t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".css":"text/css; charset=utf-8",".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".png":"image/png",".svg":"image/svg+xml",".txt":"text/plain; charset=utf-8",".wasm":"application/wasm"}[t]??"application/octet-stream"}function Zv(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function Aye(e){return Number.isSafeInteger(e)&&e>0&&e<=65535}function l$(e){let t="";for(let r=0;r<e.byteLength;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function c$(e){const t=atob(e);return Uint8Array.from(t,r=>r.charCodeAt(0))}function Yg(e){const t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function xc(e){return e==="/"?"":e}async function Cye(e,t){try{return await Tye(e,t)}catch{return}}async function Tye(e,t){if(t.some(m=>m.path!=="/"&&(m.mode===void 0||m.mtimeMs===void 0)))return;const r=t.filter(m=>m.type==="file"&&m.content===void 0);if(r.length===0)return;const n=[],s=[],i=[];let a=0;for(const m of r){if(!e.existsSync(m.path)){s.push(m.path);continue}const g=await e.readFile(m.path);n.push(m),i.push(g),a+=g.byteLength}const o=new SharedArrayBuffer(a),l=new Uint8Array(o),c=new Map,u=new Map,d=m=>{for(let g=m;g!=="/";g=Yg(g)){const b=Yg(g),v=xc(b),S=u.get(v)??new Set,x=g.slice(v.length+1);if(S.has(x))return;S.add(x),u.set(v,S)}};let p=0;n.forEach((m,g)=>{const b=i[g];l.set(b,p),c.set(m.path,{type:"file",mode:m.mode,mtimeMs:m.mtimeMs,offset:p,length:b.byteLength}),d(m.path),p+=b.byteLength});for(const m of t)m.type!=="directory"||m.path==="/"||(c.set(m.path,{type:"directory",mode:m.mode,mtimeMs:m.mtimeMs,offset:0,length:0}),d(m.path));return{index:Wj(c,u),bytes:o,...s.length>0?{vanished:s}:{}}}function qF(e,t){const r=new xN(e.index),n=new Hj(r),s=new SN(r),i={childrenOf:o=>[...s.get(xc(o))??[]].sort(),descendants(o){const l=[],c=u=>{const d=n.get(u);d&&l.push([u,d]);for(const p of s.get(xc(u))??[])c(`${xc(u)}/${p}`)};return c(o),l}};if(e.store!==void 0){const o=e.roots?.[0]??"/",l=e.storeRoot??o,c=d=>l+d.slice(o==="/"?0:o.length),u=d=>{const p=n.get(d);throw!p||p.type==="directory"?new Error(`The shared layer holds no file at ${d}.`):new Error(`${d} is in the store ${e.store}, which this realm did not open.`)};return{entries:n,read:d=>u(d).read(c(d)),readRange:(d,p,m)=>u(d).readRange(c(d),p,m),readsByRange:()=>!0,...i}}if(!e.bytes)throw new Error("A shared layer holds neither its bytes nor a store of them.");const a=new Uint8Array(e.bytes);return{entries:n,read(o){const l=n.get(o);if(!l||l.type==="directory")throw new Error(`The shared layer holds no file at ${o}.`);return a.slice(l.offset,l.offset+l.length)},view(o){const l=n.get(o);if(!l||l.type==="directory")throw new Error(`The shared layer holds no file at ${o}.`);return a.subarray(l.offset,l.offset+l.length)},readRange(o,l,c){const u=n.get(o);if(!u||u.type==="directory")throw new Error(`The shared layer holds no file at ${o}.`);const d=Math.min(Math.max(0,l),u.length);return a.slice(u.offset+d,u.offset+Math.min(u.length,d+Math.max(0,c)))},childrenOf:o=>[...s.get(xc(o))??[]].sort(),descendants(o){const l=[],c=u=>{const d=n.get(u);d&&l.push([u,d]);for(const p of s.get(xc(u))??[])c(`${xc(u)}/${p}`)};return c(o),l}}}function $ye(e){const t=[];for(const[r,n]of qF(e).entries)t.push(n.type==="directory"?{path:r,type:"directory",mode:n.mode,mtimeMs:n.mtimeMs}:{path:r,type:"file",size:n.length,mode:n.mode,mtimeMs:n.mtimeMs});return t}function Nye(e){if(e.length===1)return e[0];const t=(a,o)=>{if(a===0)return!1;for(let l=Yg(o);;l=Yg(l)){for(let c=0;c<a;c+=1){const u=e[c].entries.get(l);if(u&&u.type!=="directory")return!0}if(l==="/")return!1}},r=a=>{for(let o=0;o<e.length;o+=1)if(e[o].entries.has(a)&&!t(o,a))return o;return-1},n=a=>e[r(a)],s={get:a=>n(a)?.entries.get(a),has:a=>r(a)>=0,get size(){let a=0;for(const o of s)a+=1;return a},*[Symbol.iterator](){const a=new Set;for(let o=0;o<e.length;o+=1)for(const[l,c]of e[o].entries)a.has(l)||r(l)!==o||(a.add(l),yield[l,c])},*entries(){yield*s[Symbol.iterator]()},*keys(){for(const[a]of s)yield a},*values(){for(const[,a]of s)yield a},forEach(a){for(const[o,l]of s)a(l,o,s)}},i=a=>{const o=n(a)?.entries.get(a);return o&&o.type!=="directory"?[]:e.filter((l,c)=>{const u=l.entries.get(a);return(!u||u.type==="directory")&&!t(c,a)})};return{entries:s,read:a=>{const o=n(a);if(!o)throw new Error(`No lower tree holds ${a}.`);return o.read(a)},view:a=>{const o=n(a);if(!o)throw new Error(`No lower tree holds ${a}.`);return o.view?o.view(a):o.read(a)},readRange:(a,o,l)=>{const c=n(a);if(!c)throw new Error(`No lower tree holds ${a}.`);if(c.readRange)return c.readRange(a,o,l);const u=c.read(a),d=Math.min(Math.max(0,o),u.byteLength);return u.slice(d,Math.min(u.byteLength,d+Math.max(0,l)))},readsByRange:a=>n(a)?.readsByRange?.(a)??!1,childrenOf:a=>[...new Set(i(a).flatMap(o=>o.childrenOf(a)))].sort(),descendants:a=>{const o=[],l=new Set;for(const u of e)for(const[d]of u.descendants(a)){if(l.has(d))continue;l.add(d);const p=s.get(d);p&&o.push([d,p])}const c=o.findIndex(([u])=>u===a);return c>0&&o.unshift(...o.splice(c,1)),o}}}function Rye(e,t,r){const n=[...(t??[]).map(s=>qF(s))];return n.length===0?void 0:Nye(n)}function Oye(e,t){if(t.length===0)return e;const r=n=>t.some(s=>s==="/"||n===s||n.startsWith(`${s}/`));return{...e,files:e.files.filter(n=>!r(n.path)),removed:e.removed.filter(n=>!r(n))}}const Yv=0,k1=1,_ye=2,u$=3,Iye=4,Mye=5,A1=6,Dye=256*1024;class Lye{buffer;control;bytes;constructor(t=Dye,r){if(!Number.isSafeInteger(t)||t<2)throw new Error("WALI stdin capacity must be at least two bytes.");if(this.buffer=r??new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT*A1+t),this.buffer.byteLength!==Int32Array.BYTES_PER_ELEMENT*A1+t)throw new Error("WALI stdin shared buffer has an invalid size.");this.control=new Int32Array(this.buffer,0,A1),this.bytes=new Uint8Array(this.buffer,Int32Array.BYTES_PER_ELEMENT*A1)}write(t){const r=typeof t=="string"?new TextEncoder().encode(t):t;if(r.byteLength===0)return!0;const n=Atomics.load(this.control,Yv),s=Atomics.load(this.control,k1);if(r.byteLength>d$(n,s,this.bytes.byteLength))return!1;for(let i=0;i<r.byteLength;i+=1)this.bytes[(s+i)%this.bytes.byteLength]=r[i];return Atomics.store(this.control,k1,(s+r.byteLength)%this.bytes.byteLength),this.wake(),!0}free(){return d$(Atomics.load(this.control,Yv),Atomics.load(this.control,k1),this.bytes.byteLength)}resize(t,r){Atomics.store(this.control,Mye,f$(t)),Atomics.store(this.control,Iye,f$(r)),this.wake()}close(){Atomics.store(this.control,_ye,1),this.wake()}get availableBytes(){return GF(Atomics.load(this.control,Yv),Atomics.load(this.control,k1),this.bytes.byteLength)}wake(){Atomics.add(this.control,u$,1),Atomics.notify(this.control,u$)}}function f$(e){return Number.isFinite(e)?Math.min(65535,Math.max(1,Math.floor(e))):0}function GF(e,t,r){return t>=e?t-e:r-e+t}function d$(e,t,r){return r-GF(e,t,r)-1}const h$=24,VF=12,ZF=4,Xg=e=>1n<<BigInt(e-1);Xg(9)|Xg(19);const Pye=new Set([17,18,19,20,21,22,23,28]),Uye=e=>!Pye.has(e);function Fye(){return new SharedArrayBuffer((ZF+64*VF)*4)}class Bye{buffer;words;constructor(t){this.buffer=t,this.words=new Int32Array(t)}offset(t){return ZF+(t-1)*VF}locked(t){for(;Atomics.compareExchange(this.words,0,0,1)!==0;)Atomics.wait(this.words,0,1);try{return t()}finally{Atomics.store(this.words,0,0),Atomics.notify(this.words,0)}}changed(){Atomics.add(this.words,1,1),Atomics.notify(this.words,1)}action(t,r){return this.locked(()=>{const n=this.offset(t),s=new Uint8Array(this.buffer,(n+1)*4,h$),i=Uint8Array.from(s);return r&&(s.set(r),new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,!0)<=1&&Atomics.exchange(this.words,n,0)!==0&&Atomics.sub(this.words,2,1),this.changed()),i})}raise(t,r=0,n=0){return this.locked(()=>{const s=this.offset(t),i=Atomics.load(this.words,s+1)>>>0;return i<=1?i===1?"ignored":"default":(Atomics.load(this.words,s)!==0||(Atomics.store(this.words,s+7,r),Atomics.store(this.words,s+8,n),Atomics.store(this.words,s,1),Atomics.add(this.words,2,1),this.changed()),"handled")})}anyPending(){return Atomics.load(this.words,2)!==0}pending(){if(Atomics.load(this.words,2)===0)return 0n;let t=0n;for(let r=1;r<=64;r++)Atomics.load(this.words,this.offset(r))&&(t|=Xg(r));return t}take(t){if((this.pending()&~t)!==0n)return this.locked(()=>{for(let r=1;r<=64;r++){const n=this.offset(r);if((t&Xg(r))!==0n||Atomics.load(this.words,n)===0)continue;Atomics.store(this.words,n,0),Atomics.sub(this.words,2,1);const s=Uint8Array.from(new Uint8Array(this.buffer,(n+1)*4,h$));return(new DataView(s.buffer).getBigUint64(4,!0)&0x80000000n)!==0n&&Atomics.store(this.words,n+1,0),{signal:r,action:s,pid:Atomics.load(this.words,n+7),status:Atomics.load(this.words,n+8)}}})}}const p$=0,m$=1,Wc=2,YF=3,XF=4,KF=5,QF=6;function zye(e){const t=fE(e),r=e.role==="reader"?YF:XF;Atomics.sub(t,r,1)<=1&&Atomics.store(t,r,0),Atomics.add(t,e.role==="reader"?QF:KF,1),Atomics.notify(t,Wc)}function jye(e,t){if(e.role!=="reader")return-9n;const r=fE(e),n=JF(e),s=Atomics.load(r,Wc);if(s===0)return Atomics.load(r,XF)===0?new Uint8Array:-11n;const i=Math.min(Math.max(0,t),s),a=Atomics.load(r,p$),o=Math.min(i,n.byteLength-a),l=new Uint8Array(i);return l.set(n.subarray(a,a+o)),o<i&&l.set(n.subarray(0,i-o),o),Atomics.store(r,p$,(a+i)%n.byteLength),Atomics.sub(r,Wc,i),i>0&&Atomics.add(r,QF,1),Atomics.notify(r,Wc),l}async function Xv(e,t){if(e.role!=="writer")throw new Error("Cannot write through a shared-pipe reader.");const r=fE(e),n=JF(e);let s=0;for(;s<t.byteLength;){if(Atomics.load(r,YF)===0)return;const i=Atomics.load(r,Wc),a=n.byteLength-i;if(a===0){await new Promise(c=>setTimeout(c,1));continue}const o=Atomics.load(r,m$),l=Math.min(t.byteLength-s,a,n.byteLength-o);n.set(t.subarray(s,s+l),o),Atomics.store(r,m$,(o+l)%n.byteLength),Atomics.add(r,Wc,l),Atomics.add(r,KF,1),Atomics.notify(r,Wc),s+=l}}const g$=new WeakMap;function fE(e){const t=e.controlOffset??0;let r=g$.get(e.control);r||(r=new Map,g$.set(e.control,r));let n=r.get(t);return n||(n=new Int32Array(e.control,t,8),r.set(t,n)),n}function JF(e){const t=e.payloadOffset??0,r=e.payloadLength??e.payload.byteLength-t;return new Uint8Array(e.payload,t,r)}function y$(e,t,r){const n=new TextEncoder().encode(JSON.stringify(t));if(n.byteLength>e.response.byteLength)throw new Error(`Browser child filesystem patch is ${n.byteLength} bytes; limit is ${e.response.byteLength}.`);new Uint8Array(e.response).set(n);const s=new Int32Array(e.control);Atomics.store(s,1,r|0),Atomics.store(s,2,n.byteLength),Atomics.store(s,0,1),Atomics.notify(s,0)}const b$=new WeakMap;let w$,v$;function Wye(e,t){if(!Number.isSafeInteger(t)||t<0||t>=65536)return 0;let r=e===w$?v$:b$.get(e);r||(r={table:new Int32Array(e.table),descriptions:new Int32Array(e.descriptions)},b$.set(e,r)),w$=e,v$=r;const n=Atomics.load(r.table,t);return Atomics.load(r.descriptions,n*3)}function Hye(e,t){return Wye(e,t)!==0}const x$=new Map,Kv=(e,t)=>t?`${e}
1887
1887
  ${t}`:void 0;async function qye(e,t){if(!t){await e;return}if(t.aborted)return;let r=()=>{};const n=new Promise(s=>{r=()=>s()});t.addEventListener("abort",r,{once:!0});try{await Promise.race([e,n])}finally{t.removeEventListener("abort",r)}}const Gye=new Map;class Vye{filesystem;program;capabilities=Object.freeze({filesystemPolicy:!0});worker;pending;stdin;terminalSize={columns:80,rows:24};nextId=1;forkWorkers=new Map;childControllers=new Map;openUrlHandler;urlScanTail="";openedUrls=new Set;processPorts=[];threadOutputPorts=[];filesystemUpdatePort;traceId=crypto.randomUUID();preparing=!1;applyingFilesystem=!1;constructor(t,r){this.filesystem=t,this.program=r}hostRoots=[];withoutHostTrees(t){return Oye(t,this.hostRoots)}async run(t,r={}){if(r.filesystemPolicy!==void 0&&(r={...r,filesystemPolicy:ss(r.filesystemPolicy)}),this.pending||this.preparing)throw new Error("The browser WALI program is already running.");if(r.signal?.aborted)throw r.signal.reason;this.worker??=this.createWorker(),this.preparing=!0,console.log("[wali-boot]",JSON.stringify({stage:"prepare",run:this.traceId,argv:t,at:Date.now()}));try{const n=RN(this.filesystem);n&&await this.filesystem.flush?.(),console.log("[wali-boot]",JSON.stringify({stage:"flushed",run:this.traceId,at:Date.now()}));const s=this.unreadRoots();let i=await N1(this.filesystem,"/",n?{metadataRoots:[...qj,...s]}:{metadataRoots:["/"]});const a=n?void 0:await Cye(this.filesystem,i.files.filter(D=>!dc(D.path,s)));if(!n&&!a&&(i=await N1(this.filesystem,"/",s.length>0?{metadataRoots:s}:{})),a?.vanished){const D=new Set(a.vanished);i={files:i.files.filter(I=>!D.has(I.path))},delete a.vanished}const o=this.program.layers??[];if(o.length>0){const D=new Set(i.files.map(I=>I.path));i={files:[...i.files,...o.flatMap($ye).filter(I=>!D.has(I.path))]}}const l=[...a?[a]:[],...o];this.hostRoots=[...o.flatMap(D=>D.roots??[]),...this.program.privateRoots??[]].map(D=>D==="/"?D:D.replace(/\/+$/u,"")||"/");const c={files:i.files.filter(D=>D.type==="directory"||!dc(D.path,s))},u=this.program.prepareFilesystem?await this.program.prepareFilesystem(i):i,d=Gye.get(Kv(this.program.url,this.program.integrity)??"");if(d&&await qye(d.catch(()=>{}),r.signal),r.signal?.aborted)throw r.signal.reason;const p=this.nextId++,m=`wali:${crypto.randomUUID()}`,g=sR(),b=nR.attach(g.server,m),v=eR(),S=this.program.coherenceFilesystem??this.filesystem,x=JN.attach(v.server,S,()=>this.program.onFilesystemCommit?.(this.filesystem),D=>{const I=this.pending;if(!I||I.id!==p)return;const U=hR(S,D);I.filesystemBase.apply(U?{files:[U],removed:[]}:{files:[],removed:[D]})});this.urlScanTail="",this.openedUrls.clear();const E=new Lye,A=r.terminal??this.terminalSize;E.resize(A.columns,A.rows),this.stdin=E;const T=Fye();return await new Promise((D,I)=>{const U=()=>r.signal?.reason??new DOMException("The WALI process was interrupted.","AbortError"),O=()=>{const j=r.signal?.reason;j&&typeof j=="object"&&(j.handled=!1),this.resetWorker(),this.finishPending(),I(U())},_=j=>j===9?!1:new Bye(T).raise(j)!=="default"||!Uye(j),N=()=>{const j=r.signal?.reason;if(!_(Yye(j))){O();return}j&&typeof j=="object"&&(j.handled=!0,j.redeliver=te=>{this.pending&&!_(te)&&O()})};r.signal?.addEventListener("abort",N,{once:!0});let F=()=>{};const P=this.program.loopback?new MessageChannel:void 0;P&&(F=this.program.loopback.attach(P.port1));let W;const K=new Promise(j=>{W=j});this.pending={id:p,filesystemBase:new CX(c,l.some(j=>!j.store)?(j=>te=>j.entries.has(te)?j.read(te):void 0)(Rye(void 0,l.filter(j=>!j.store))):void 0),filesystemQueue:Promise.resolve(),resolve:D,reject:I,options:r,removeAbortListener:()=>r.signal?.removeEventListener("abort",N),stdout:"",stderr:"",releaseLoopback:F,releaseFileLocks:b,releaseFileCoherence:x,releaseFilesystemChanges:()=>{},changedPaths:new Set,importSequence:0,importingFilesystem:!1,filesystemFinalized:!1,filesystemFinalization:K,resolveFilesystemFinalization:W};const Y={type:"run",...r[zd]?{pid:r[zd].pid,parentPid:r[zd].parentPid,childPidAllocator:r[zd].childPidAllocator}:{},id:p,...r.descriptorTable?{descriptorTable:r.descriptorTable}:{},url:this.program.url,...this.program.integrity?{integrity:this.program.integrity}:{},...(()=>{const j=Kv(this.program.url,this.program.integrity),te=j?x$.get(j):void 0;return te?{compiled:te}:{}})(),...r.executablePath?{executablePath:r.executablePath}:{},argv:[...t],cwd:r.cwd??this.program.cwd??"/",env:{...r.env,...this.program.env},threadPoolSize:this.program.threadPoolSize??18,...this.program.codec?{codec:this.program.codec}:{},...r.filesystemPolicy?{filesystemPolicy:r.filesystemPolicy}:{},...this.program.spawn?.capabilities?.filesystemPolicy===!0?{childFilesystemPolicyVersion:1}:{},...this.program.network.allowedHosts.length>0||P?{network:{...this.program.network.relayUrl?{relayUrl:this.program.network.relayUrl}:{},allowedHosts:[...this.program.network.allowedHosts],maxConnections:this.program.network.maxConnections,maxBytes:this.program.network.maxBytes}}:{},...P?{loopbackPort:P.port2}:{},stdin:E.buffer,terminal:r.terminal!==void 0,filesystem:u,...n?{store:{projectId:n}}:{},...l.length>0?{layers:l}:{},...this.program.privateRoots?.length?{privateRoots:[...this.program.privateRoots]}:{},fileLocks:{channel:g.client,owner:m},fileCoherence:v.client,signalState:T},V=Array.from({length:Y.threadPoolSize},()=>new MessageChannel);this.processPorts=V.map(j=>j.port1);for(const j of this.processPorts)j.onmessage=te=>{const le=this.pending;!le||le.id!==p||(te.data.type==="spawn"?this.spawnChild({...te.data,id:p,type:"spawn"},le):this.childControllers.get(te.data.pid)?.abort(new DOMException(`Signal ${te.data.signal}`,"AbortError")))},j.start();Y.browserProcessPorts=V.map(j=>j.port2);const L=Array.from({length:Y.threadPoolSize},()=>new MessageChannel);this.threadOutputPorts=L.map(j=>j.port1);for(const j of this.threadOutputPorts)j.onmessage=te=>{try{const le=this.pending;if(!le||le.id!==p)return;if(te.data.type==="error"){this.emitStderr(le,`
1888
1888
  WALI pthread ${te.data.tid??"unknown"} error: ${te.data.message}
1889
- `);return}if(te.data.type==="diagnostic"){le.options.onDiagnostic?.(te.data.message);return}te.data.type==="stdout"?this.emitStdout(le,te.data.bytes):this.emitStderr(le,new TextDecoder().decode(te.data.bytes))}finally{if(te.data.type!=="error"&&te.data.type!=="diagnostic"&&te.data.ack){const le=new Int32Array(te.data.ack);Atomics.store(le,0,1),Atomics.notify(le,0)}}},j.start();Y.threadOutputPorts=L.map(j=>j.port2);const G=new MessageChannel;this.filesystemUpdatePort=G.port1,this.filesystemUpdatePort.onmessage=j=>{const te=this.pending;if(te?.id===p){if(j.data.type==="mailbox"){te.mailbox={control:new Int32Array(j.data.buffer,0,2),buffer:j.data.buffer,doorbell:new Int32Array(j.data.doorbell)};return}if(j.data.type==="port-closed"){const le=te.importOnPort;delete te.importOnPort,le&&(le.sequence??0)>j.data.taken&&te.mailbox&&(te.filesystemQueue=te.filesystemQueue.then(()=>this.sendImport(te,le)).catch(ne=>{this.pending===te&&(this.finishPending(),this.resetWorker(),te.reject(ne))}));return}(j.data.type==="imported"||j.data.type==="import-error")&&delete te.importOnPort,te.filesystemQueue=te.filesystemQueue.then(()=>this.applyLiveFilesystemPatch(p,j.data))}},this.filesystemUpdatePort.start();const q=j=>{const te=this.pending;!te||te.id!==p||this.applyingFilesystem||(te.changedPaths.add(j),this.scheduleFilesystemImport(te))};this.filesystem.on("change",q),this.filesystem.on("delete",q),this.pending.releaseFilesystemChanges=()=>{this.filesystem.off("change",q),this.filesystem.off("delete",q)},Y.filesystemUpdatePort=G.port2,console.log("[wali-boot]",JSON.stringify({stage:"dispatch",run:this.traceId,at:Date.now()})),this.worker.postMessage(Y,[...Y.descriptorTable?[Y.descriptorTable.port]:[],...Y.browserProcessPorts,...Y.threadOutputPorts,Y.filesystemUpdatePort,Y.fileLocks.channel.port,Y.fileCoherence.port,...Y.loopbackPort?[Y.loopbackPort]:[]]);const ee=Kye(r.descriptorTable);if(!(ee!==void 0&&Hye(ee,0)))if(r.stdin!==void 0){const j=r.stdin;this.forwardStdin(p,E,(async function*(){yield j})())}else r.stdinStream&&this.forwardStdin(p,E,r.stdinStream)})}finally{this.preparing=!1}}async forwardStdin(t,r,n){const s=new TextEncoder;try{for await(const i of n){const a=typeof i=="string"?s.encode(i):i;let o=0;for(;this.pending?.id===t&&o<a.byteLength;){const l=r.free();if(l>0){const c=Math.min(l,a.byteLength-o);r.write(a.subarray(o,o+c)),o+=c}else await new Promise(c=>setTimeout(c,1))}if(this.pending?.id!==t)return}this.pending?.id===t&&r.close()}catch(i){const a=this.pending;if(!a||a.id!==t)return;this.resetWorker(),this.finishPending(),a.reject(i)}}get running(){return this.pending!==void 0||this.preparing}sendInput(t){return this.stdin?.write(t)??!1}resize(t,r){this.terminalSize={columns:t,rows:r},this.stdin?.resize(t,r)}setOpenUrlHandler(t){this.openUrlHandler=t}terminate(){this.pending?.reject(new DOMException("The WALI program was terminated.","AbortError")),this.finishPending(),this.worker?.terminate()}createWorker(){const t=kf(new Worker(new URL("/assets/worker-program-worker-B_u8gbzh.js",import.meta.url),{type:"module",name:"browser-wali-program"}));return t.addEventListener("message",r=>{this.handleMessage(r.data).catch(n=>{this.pending?.id===r.data.id&&(this.pending.reject(n),this.finishPending(),this.resetWorker())})}),t.addEventListener("error",r=>{this.pending?.reject(r.error??new Error(r.message)),this.finishPending(),this.resetWorker()}),t}async handleMessage(t){if(t.type==="compiled"){const i=Kv(this.program.url,this.program.integrity);i&&x$.set(i,t.compiled);return}const r=this.pending;if(!r||t.id!==r.id)return;if(t.type==="stdout"){this.emitStdout(r,t.chunk);return}if(t.type==="stderr"){this.emitStderr(r,t.chunk);return}if(t.type==="diagnostic"){r.options.onDiagnostic?.(t.message);return}if(t.type==="fork"){this.forkChild(t);return}if(t.type==="spawn"){this.spawnChild(t,r);return}if(t.type==="kill"){const i=this.childControllers.get(t.pid);if(!i)return;i.signal.aborted?i.signal.reason?.redeliver?.(t.signal):i.abort(Zye(t.signal,`Signal ${t.signal}`));return}console.log("[wali-boot]",JSON.stringify({stage:"result-received",run:this.traceId,at:Date.now()}));const n=this.program.sanitizeFilesystem?await this.program.sanitizeFilesystem(t.filesystem):t.filesystem;if(t.filesystemFinalized&&await r.filesystemFinalization,await r.filesystemQueue,console.log("[wali-boot]",JSON.stringify({stage:"filesystem-settled",run:this.traceId,at:Date.now()})),this.pending!==r)return;const s=t.filesystemFinalized?{files:[],removed:[]}:this.withoutHostTrees(D1(r.filesystemBase,n,{written:!0}));t.filesystemFinalized||M1(this.filesystem,s,r.filesystemBase);try{await this.program.onFilesystemCommit?.(this.filesystem,s)}catch(i){this.finishPending(),r.reject(new Error(`WALI filesystem durability barrier failed: ${i instanceof Error?i.message:String(i)}`));return}if(this.finishPending(),console.log("[wali-boot]",JSON.stringify({stage:"done",run:this.traceId,at:Date.now()})),t.result)r.resolve({...t.result,stdout:r.stdout,stderr:r.stderr});else{const i=t.error??"The browser WALI program failed.",a=r.stderr.trimEnd();r.reject(new Error(a?`${a}
1890
- ${i}`:i))}}forkChild(t){const r=kf(new Worker(new URL("/assets/fork-worker-hBikLg_q.js",import.meta.url),{type:"module",name:`wali-fork-${t.pid}`}));this.forkWorkers.set(t.pid,r);const n=()=>{r.terminate(),this.forkWorkers.delete(t.pid)};r.addEventListener("message",s=>{if(s.data.type==="fork-done"){n();return}this.handleMessage(s.data).catch(i=>{this.pending?.reject(i),this.finishPending(),this.resetWorker()})}),r.addEventListener("error",s=>{this.pending?.reject(s.error??new Error(s.message)),this.finishPending(),this.resetWorker()}),r.postMessage(t,[t.descriptorTable.port,...t.descriptorTable.releasePort?[t.descriptorTable.releasePort]:[],t.forkState.memory])}async spawnChild(t,r){const n=this.program.spawn,s=new AbortController;this.childControllers.set(t.pid,s);const i=A=>console.log("[wali-boot]",JSON.stringify({stage:A,run:this.traceId,child:t.pid,at:Date.now()}));i("spawn-received");const a=t.descriptorTable?.releasePort,o=t.descriptorTable&&{port:t.descriptorTable.port,control:t.descriptorTable.control,payload:t.descriptorTable.payload,...t.descriptorTable.sharedPipes?{sharedPipes:t.descriptorTable.sharedPipes}:{}};let l;const c=()=>l??=a?new Promise(A=>{a.onmessage=()=>{a.close(),A()},a.postMessage(!0)}):Promise.resolve();let u=Promise.resolve(),d=Promise.resolve(),p=!1,m=!1;const g=()=>N1(this.filesystem,"/",{metadataRoots:["/"]}),b=async A=>{const T=D1(A,await g()),D=new Map(A.files.map(_=>[_.path,_])),I=[],U=this.unreadRoots(),O=new Set(T.removed.filter(_=>!dc(_,U)));for(const _ of T.files){if(_.type!=="directory"&&dc(_.path,U))continue;const N=D.get(_.path);if(!(_.type==="file"&&(!N||N.type!=="file"||N.size!==_.size||N.mtimeMs!==_.mtimeMs))){I.push(_);continue}const P=await Q8(this.filesystem,_.path);P?I.push(P):N&&O.add(_.path)}return{files:I,removed:[...O]}};let v=await g();i("spawn-snapshot");const S=A=>{p=!0,t.stdout?u=u.then(()=>Xv(t.stdout,new TextEncoder().encode(A))):this.emitStdout(r,A)},x=A=>{p=!0,u=u.then(()=>Xv(t.stdout,A))},E=A=>{m=!0,t.stderr?d=d.then(()=>Xv(t.stderr,new TextEncoder().encode(A))):this.emitStderr(r,A)};try{if(!n)throw new Error("No browser child-process backend is configured.");const A=r.options.filesystemPolicy?i0(r.options.filesystemPolicy,t.filesystemPolicy):t.filesystemPolicy===void 0?void 0:ss(t.filesystemPolicy);Pc(A,n.capabilities);const T=this.withoutHostTrees(this.program.sanitizeFilesystemPatch?await this.program.sanitizeFilesystemPatch(t.filesystemPatch):t.filesystemPatch);M1(this.filesystem,T,r.filesystemBase),r.filesystemBase.apply(T),v=await g(),i("spawn-patched");const D=t.stdin?Qye(t.stdin,s.signal):void 0,I=Xye(t),U=await n.run(I.command,{[zd]:{pid:t.pid,parentPid:t.parentPid,childPidAllocator:t.childPidAllocator},...A?{filesystemPolicy:A}:{},...o?{descriptorTable:o}:{},cwd:t.cwd,...I.executablePath?{executablePath:I.executablePath}:{},env:t.inheritEnvironment?{...r.options.env,...this.program.env}:t.env,...D?{stdinStream:D}:{},signal:s.signal,...t.stdout?{onStdoutBytes:x}:{},onStdout:S,onStderr:E});U.stdout&&!p&&S(U.stdout),U.stderr&&!m&&E(U.stderr),i("spawn-ran"),await Promise.all([u,d]),await c(),y$(t,await b(v),U.exitCode),i("spawn-returned")}catch(A){const T=`${A instanceof Error?A.message:String(A)}
1889
+ `);return}if(te.data.type==="diagnostic"){le.options.onDiagnostic?.(te.data.message);return}te.data.type==="stdout"?this.emitStdout(le,te.data.bytes):this.emitStderr(le,new TextDecoder().decode(te.data.bytes))}finally{if(te.data.type!=="error"&&te.data.type!=="diagnostic"&&te.data.ack){const le=new Int32Array(te.data.ack);Atomics.store(le,0,1),Atomics.notify(le,0)}}},j.start();Y.threadOutputPorts=L.map(j=>j.port2);const G=new MessageChannel;this.filesystemUpdatePort=G.port1,this.filesystemUpdatePort.onmessage=j=>{const te=this.pending;if(te?.id===p){if(j.data.type==="mailbox"){te.mailbox={control:new Int32Array(j.data.buffer,0,2),buffer:j.data.buffer,doorbell:new Int32Array(j.data.doorbell)};return}if(j.data.type==="port-closed"){const le=te.importOnPort;delete te.importOnPort,le&&(le.sequence??0)>j.data.taken&&te.mailbox&&(te.filesystemQueue=te.filesystemQueue.then(()=>this.sendImport(te,le)).catch(ne=>{this.pending===te&&(this.finishPending(),this.resetWorker(),te.reject(ne))}));return}(j.data.type==="imported"||j.data.type==="import-error")&&delete te.importOnPort,te.filesystemQueue=te.filesystemQueue.then(()=>this.applyLiveFilesystemPatch(p,j.data))}},this.filesystemUpdatePort.start();const q=j=>{const te=this.pending;!te||te.id!==p||this.applyingFilesystem||(te.changedPaths.add(j),this.scheduleFilesystemImport(te))};this.filesystem.on("change",q),this.filesystem.on("delete",q),this.pending.releaseFilesystemChanges=()=>{this.filesystem.off("change",q),this.filesystem.off("delete",q)},Y.filesystemUpdatePort=G.port2,console.log("[wali-boot]",JSON.stringify({stage:"dispatch",run:this.traceId,at:Date.now()})),this.worker.postMessage(Y,[...Y.descriptorTable?[Y.descriptorTable.port]:[],...Y.browserProcessPorts,...Y.threadOutputPorts,Y.filesystemUpdatePort,Y.fileLocks.channel.port,Y.fileCoherence.port,...Y.loopbackPort?[Y.loopbackPort]:[]]);const ee=Kye(r.descriptorTable);if(!(ee!==void 0&&Hye(ee,0)))if(r.stdin!==void 0){const j=r.stdin;this.forwardStdin(p,E,(async function*(){yield j})())}else r.stdinStream&&this.forwardStdin(p,E,r.stdinStream)})}finally{this.preparing=!1}}async forwardStdin(t,r,n){const s=new TextEncoder;try{for await(const i of n){const a=typeof i=="string"?s.encode(i):i;let o=0;for(;this.pending?.id===t&&o<a.byteLength;){const l=r.free();if(l>0){const c=Math.min(l,a.byteLength-o);r.write(a.subarray(o,o+c)),o+=c}else await new Promise(c=>setTimeout(c,1))}if(this.pending?.id!==t)return}this.pending?.id===t&&r.close()}catch(i){const a=this.pending;if(!a||a.id!==t)return;this.resetWorker(),this.finishPending(),a.reject(i)}}get running(){return this.pending!==void 0||this.preparing}sendInput(t){return this.stdin?.write(t)??!1}resize(t,r){this.terminalSize={columns:t,rows:r},this.stdin?.resize(t,r)}setOpenUrlHandler(t){this.openUrlHandler=t}terminate(){this.pending?.reject(new DOMException("The WALI program was terminated.","AbortError")),this.finishPending(),this.worker?.terminate()}createWorker(){const t=kf(new Worker(new URL("/assets/worker-program-worker-BEQYJYct.js",import.meta.url),{type:"module",name:"browser-wali-program"}));return t.addEventListener("message",r=>{this.handleMessage(r.data).catch(n=>{this.pending?.id===r.data.id&&(this.pending.reject(n),this.finishPending(),this.resetWorker())})}),t.addEventListener("error",r=>{this.pending?.reject(r.error??new Error(r.message)),this.finishPending(),this.resetWorker()}),t}async handleMessage(t){if(t.type==="compiled"){const i=Kv(this.program.url,this.program.integrity);i&&x$.set(i,t.compiled);return}const r=this.pending;if(!r||t.id!==r.id)return;if(t.type==="stdout"){this.emitStdout(r,t.chunk);return}if(t.type==="stderr"){this.emitStderr(r,t.chunk);return}if(t.type==="diagnostic"){r.options.onDiagnostic?.(t.message);return}if(t.type==="fork"){this.forkChild(t);return}if(t.type==="spawn"){this.spawnChild(t,r);return}if(t.type==="kill"){const i=this.childControllers.get(t.pid);if(!i)return;i.signal.aborted?i.signal.reason?.redeliver?.(t.signal):i.abort(Zye(t.signal,`Signal ${t.signal}`));return}console.log("[wali-boot]",JSON.stringify({stage:"result-received",run:this.traceId,at:Date.now()}));const n=this.program.sanitizeFilesystem?await this.program.sanitizeFilesystem(t.filesystem):t.filesystem;if(t.filesystemFinalized&&await r.filesystemFinalization,await r.filesystemQueue,console.log("[wali-boot]",JSON.stringify({stage:"filesystem-settled",run:this.traceId,at:Date.now()})),this.pending!==r)return;const s=t.filesystemFinalized?{files:[],removed:[]}:this.withoutHostTrees(D1(r.filesystemBase,n,{written:!0}));t.filesystemFinalized||M1(this.filesystem,s,r.filesystemBase);try{await this.program.onFilesystemCommit?.(this.filesystem,s)}catch(i){this.finishPending(),r.reject(new Error(`WALI filesystem durability barrier failed: ${i instanceof Error?i.message:String(i)}`));return}if(this.finishPending(),console.log("[wali-boot]",JSON.stringify({stage:"done",run:this.traceId,at:Date.now()})),t.result)r.resolve({...t.result,stdout:r.stdout,stderr:r.stderr});else{const i=t.error??"The browser WALI program failed.",a=r.stderr.trimEnd();r.reject(new Error(a?`${a}
1890
+ ${i}`:i))}}forkChild(t){const r=kf(new Worker(new URL("/assets/fork-worker-BOu5dHuR.js",import.meta.url),{type:"module",name:`wali-fork-${t.pid}`}));this.forkWorkers.set(t.pid,r);const n=()=>{r.terminate(),this.forkWorkers.delete(t.pid)};r.addEventListener("message",s=>{if(s.data.type==="fork-done"){n();return}this.handleMessage(s.data).catch(i=>{this.pending?.reject(i),this.finishPending(),this.resetWorker()})}),r.addEventListener("error",s=>{this.pending?.reject(s.error??new Error(s.message)),this.finishPending(),this.resetWorker()}),r.postMessage(t,[t.descriptorTable.port,...t.descriptorTable.releasePort?[t.descriptorTable.releasePort]:[],t.forkState.memory])}async spawnChild(t,r){const n=this.program.spawn,s=new AbortController;this.childControllers.set(t.pid,s);const i=A=>console.log("[wali-boot]",JSON.stringify({stage:A,run:this.traceId,child:t.pid,at:Date.now()}));i("spawn-received");const a=t.descriptorTable?.releasePort,o=t.descriptorTable&&{port:t.descriptorTable.port,control:t.descriptorTable.control,payload:t.descriptorTable.payload,...t.descriptorTable.sharedPipes?{sharedPipes:t.descriptorTable.sharedPipes}:{}};let l;const c=()=>l??=a?new Promise(A=>{a.onmessage=()=>{a.close(),A()},a.postMessage(!0)}):Promise.resolve();let u=Promise.resolve(),d=Promise.resolve(),p=!1,m=!1;const g=()=>N1(this.filesystem,"/",{metadataRoots:["/"]}),b=async A=>{const T=D1(A,await g()),D=new Map(A.files.map(_=>[_.path,_])),I=[],U=this.unreadRoots(),O=new Set(T.removed.filter(_=>!dc(_,U)));for(const _ of T.files){if(_.type!=="directory"&&dc(_.path,U))continue;const N=D.get(_.path);if(!(_.type==="file"&&(!N||N.type!=="file"||N.size!==_.size||N.mtimeMs!==_.mtimeMs))){I.push(_);continue}const P=await Q8(this.filesystem,_.path);P?I.push(P):N&&O.add(_.path)}return{files:I,removed:[...O]}};let v=await g();i("spawn-snapshot");const S=A=>{p=!0,t.stdout?u=u.then(()=>Xv(t.stdout,new TextEncoder().encode(A))):this.emitStdout(r,A)},x=A=>{p=!0,u=u.then(()=>Xv(t.stdout,A))},E=A=>{m=!0,t.stderr?d=d.then(()=>Xv(t.stderr,new TextEncoder().encode(A))):this.emitStderr(r,A)};try{if(!n)throw new Error("No browser child-process backend is configured.");const A=r.options.filesystemPolicy?i0(r.options.filesystemPolicy,t.filesystemPolicy):t.filesystemPolicy===void 0?void 0:ss(t.filesystemPolicy);Pc(A,n.capabilities);const T=this.withoutHostTrees(this.program.sanitizeFilesystemPatch?await this.program.sanitizeFilesystemPatch(t.filesystemPatch):t.filesystemPatch);M1(this.filesystem,T,r.filesystemBase),r.filesystemBase.apply(T),v=await g(),i("spawn-patched");const D=t.stdin?Qye(t.stdin,s.signal):void 0,I=Xye(t),U=await n.run(I.command,{[zd]:{pid:t.pid,parentPid:t.parentPid,childPidAllocator:t.childPidAllocator},...A?{filesystemPolicy:A}:{},...o?{descriptorTable:o}:{},cwd:t.cwd,...I.executablePath?{executablePath:I.executablePath}:{},env:t.inheritEnvironment?{...r.options.env,...this.program.env}:t.env,...D?{stdinStream:D}:{},signal:s.signal,...t.stdout?{onStdoutBytes:x}:{},onStdout:S,onStderr:E});U.stdout&&!p&&S(U.stdout),U.stderr&&!m&&E(U.stderr),i("spawn-ran"),await Promise.all([u,d]),await c(),y$(t,await b(v),U.exitCode),i("spawn-returned")}catch(A){const T=`${A instanceof Error?A.message:String(A)}
1891
1891
  `;E(T),await d,await c(),y$(t,await b(v),s.signal.aborted?130:127)}finally{s.abort(new DOMException("Browser child process completed.","AbortError")),this.childControllers.delete(t.pid),Qv(t.stdin),Qv(t.stdout),Qv(t.stderr)}}async applyLiveFilesystemPatch(t,r){const n=this.pending;if(!(!n||n.id!==t)){if(r.type==="finalized"){n.filesystemFinalized=!0,n.changedPaths.clear(),n.releaseFilesystemChanges(),n.resolveFilesystemFinalization();return}if(r.type==="checkpoint"){const s=new Int32Array(r.control);Atomics.store(s,0,1),Atomics.notify(s,0);return}if(r.type==="imported"){n.filesystemBase.apply(r.patch),n.importingFilesystem=!1,this.scheduleFilesystemImport(n);return}try{if(r.type==="import-error")throw new Error(r.message);if(r.type==="mailbox"||r.type==="port-closed")return;const s=this.withoutHostTrees(this.program.sanitizeFilesystemPatch?await this.program.sanitizeFilesystemPatch(Vm(r.patch)):r.patch);this.applyingFilesystem=!0;try{M1(this.filesystem,s,n.filesystemBase)}finally{this.applyingFilesystem=!1}n.filesystemBase.apply(s)}catch(s){if(this.pending?.id!==t)return;this.finishPending(),this.resetWorker(),n.reject(new Error(`WALI filesystem update could not be applied: ${s instanceof Error?s.message:String(s)}`));return}try{r.type==="filesystem"&&await this.program.onFilesystemCommit?.(this.filesystem,Vm(r.patch))}catch(s){if(this.pending?.id!==t)return;this.finishPending(),this.resetWorker(),n.reject(new Error(`WALI filesystem durability barrier failed: ${s instanceof Error?s.message:String(s)}`))}}}unreadRoots(){return[Gj,mg,...this.program.excludedImagePaths?.()??[]]}sendImport(t,r){r={...r,sequence:r.sequence??++t.importSequence};const n=t.mailbox;if(!n){t.importOnPort=r,this.filesystemUpdatePort?.postMessage(r);return}const s=new TextEncoder().encode(JSON.stringify({...r,patch:Vm(r.patch),...r.base?{base:Vm(r.base)}:{}})),i=8+s.byteLength,a=n.buffer;if(i>n.buffer.byteLength){if(!a.grow||i>(a.maxByteLength??0))throw new Error(`A filesystem import of ${s.byteLength} bytes does not fit the program's mailbox.`);a.grow(i)}new Uint8Array(n.buffer,8,s.byteLength).set(s),Atomics.store(n.control,1,s.byteLength),Atomics.store(n.control,0,1),Atomics.add(n.doorbell,0,1),Atomics.notify(n.doorbell,0)}scheduleFilesystemImport(t){t.filesystemFinalized||t.importingFilesystem||t.changedPaths.size===0||this.pending!==t||(t.importingFilesystem=!0,t.filesystemQueue=t.filesystemQueue.then(async()=>{if(this.pending!==t)return;const r=new Set([...t.changedPaths].filter(o=>!dc(o,this.hostRoots)));t.changedPaths.clear();const n=this.unreadRoots(),s=t.filesystemBase.only([...r].filter(o=>!dc(o,n)||t.filesystemBase.byPath.get(o)?.type==="directory")),i={files:[]};for(const o of r){if(dc(o,n)&&!(this.filesystem.existsSync(o)&&this.filesystem.statSync(o).isDirectory()))continue;const l=await Q8(this.filesystem,o);l&&i.files.push(l)}if(this.pending!==t)return;const a=D1(s,i);if(a.files.length===0&&a.removed.length===0){t.importingFilesystem=!1,this.scheduleFilesystemImport(t);return}this.sendImport(t,{type:"import",patch:a,base:s})}).catch(r=>{this.pending===t&&(this.finishPending(),this.resetWorker(),t.reject(r))}))}finishPending(){this.pending?.resolveFilesystemFinalization(),this.pending?.removeAbortListener(),this.pending?.releaseLoopback(),this.pending?.releaseFileLocks(),this.pending?.releaseFileCoherence(),this.pending?.releaseFilesystemChanges(),this.pending=void 0,this.stdin?.close(),this.stdin=void 0;for(const t of this.processPorts)t.close();this.processPorts=[];for(const t of this.threadOutputPorts)t.close();this.threadOutputPorts=[],this.filesystemUpdatePort?.close(),this.filesystemUpdatePort=void 0}emitStdout(t,r){const n=typeof r=="string"?r:new TextDecoder().decode(r);t.stdout+=n,this.scanOpenUrls(n),typeof r!="string"&&t.options.onStdoutBytes?t.options.onStdoutBytes(r):t.options.onStdout?.(n)}emitStderr(t,r){t.stderr+=r,this.scanOpenUrls(r),t.options.onStderr?.(r)}scanOpenUrls(t){if(!this.openUrlHandler)return;const r=`${this.urlScanTail}${t}`;for(const n of r.matchAll(/https?:\/\/[^\s<>'"`]+/gu)){const s=n[0].replace(/[),.;]+$/u,"");this.openedUrls.has(s)||(this.openedUrls.add(s),this.openUrlHandler(s))}this.urlScanTail=r.slice(-2048)}resetWorker(){for(const t of this.forkWorkers.values())t.terminate();this.forkWorkers.clear();for(const t of this.childControllers.values())t.abort();this.childControllers.clear(),this.worker?.terminate(),this.worker=this.createWorker()}}function Zye(e,t){return Object.assign(new DOMException(t,"AbortError"),{signal:e})}function Yye(e){const t=e?.signal;return typeof t=="number"&&Number.isInteger(t)&&t>0&&t<=64?t:9}function Xye(e){const[t="",...r]=e.argv,n=e.executablePath||t,s=n.slice(n.lastIndexOf("/")+1);if(["bash","sh","zsh"].includes(s)){const i=r.findIndex(o=>o==="-c"||o.endsWith("lc")||o.endsWith("ilc"));if((i>=0?r[i+1]:void 0)?.includes("__grok_user_cmd")){const o=r.indexOf("--",i+2);if(o>=0&&r[o+1])return{command:r[o+1]}}return{command:[s,...r].map(S$).join(" ")}}return{command:e.argv.map(S$).join(" "),...e.executablePath?{executablePath:e.executablePath}:{}}}function S$(e){return/^[A-Za-z0-9_./:+,@%=-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}function Kye(e){return e?.sharedPipes}function Qv(e){e&&zye(e)}async function*Qye(e,t){for(;!t.aborted;){const r=jye(e,65536);if(r instanceof Uint8Array){if(r.byteLength===0)break;yield r;continue}if(r!==-11n)throw new Error(`Browser child stdin failed with ${r}.`);await new Promise(n=>setTimeout(n,1))}if(t.aborted)throw t.reason}function dc(e,t){return t.some(r=>r==="/"||e===r||e.startsWith(`${r}/`))}function Ph(){return typeof performance>"u"?Date.now():performance.timeOrigin+performance.now()}new TextEncoder().encode("\0supercode-wali-symlink-v1\0");new TextDecoder("utf-8",{fatal:!0});const Jye="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",t6=64*1024,Uf=1024*1024,ebe=Uf*2+t6,Uh=new TextEncoder;class tbe{options;handshake;key=Ts(eB(16));buffer=new Uint8Array;fragmentedOpcode;fragmentChunks=[];fragmentBytes=0;state="handshake";sentClose=!1;constructor(t){this.options=t;const r=t.protocols.length>0?`Sec-WebSocket-Protocol: ${t.protocols.join(", ")}\r
1892
1892
  `:"";this.handshake=Uh.encode(`GET ${t.path} HTTP/1.1\r
1893
1893
  Host: localhost:${t.port}\r