@volter/browser-substrate 0.1.101 → 0.1.103

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.
@@ -1,237 +0,0 @@
1
- import{p as dt}from"./page-workers-BUcWBF51.js";const fs=r=>({code:-32601,message:`'${r}' wasn't found`,data:"AlmostCDP does not implement this command for the connected surface"}),ps=r=>({code:-32602,message:r}),ws={fromSurface:r=>r,toSurface:r=>r},ke=(r,e)=>e&&r.fromSurface(e),lt=r=>{if(r!==void 0)try{return new URL(r).hostname}catch{return}},Nt=(r,e)=>{const t=e.startsWith("."),n=t?e.slice(1):e,s=r.hostToSurface?r.hostToSurface(n):lt(r.toSurface(`http://${n}/`));return s===void 0?void 0:`${t?".":""}${s}`},Ht=(r,e)=>{const t=e.startsWith("."),n=t?e.slice(1):e,s=r.hostFromSurface?r.hostFromSurface(n):lt(r.fromSurface(`http://${n}/`))??n;return`${t?".":""}${s}`},ms=(r,e)=>{try{return new URL(ke(r,e)).origin}catch{return""}};class fe extends Error{error;constructor(e){super(e.message),this.error=e}}const D=(r,e)=>new fe({code:-32e3,message:`${r} is unavailable on a DOM surface: ${e}`}),ae=r=>new fe({code:-32602,message:r});class Wt{restores=[];define(e,t,n){const s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(e,t,{configurable:!0,...n}),this.restores.push(()=>{s?Object.defineProperty(e,t,s):delete e[t]})}getter(e,t,n){this.define(e,t,{enumerable:!0,get:n})}value(e,t,n){this.define(e,t,{enumerable:!1,value:n,writable:!0})}restore(){for(const e of this.restores.reverse())try{e()}catch{}this.restores=[]}forget(){this.restores=[]}}const Dt=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t},Ne=r=>{let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(e)},He="almostcdpFanOut",qt=r=>typeof r=="string"&&r?r[0].toUpperCase()+r.slice(1).toLowerCase():void 0;function ys({target:r,urls:e}){const t=()=>r.cookieStore,n=()=>r.location.hostname,s=d=>{const l=n();return d.startsWith(".")?l===d.slice(1)||l.endsWith(d):l===d},o=async()=>{const d=t();return d?d.getAll():r.document.cookie.split(";").map(l=>l.trim()).filter(Boolean).map(l=>{const f=l.indexOf("=");return f<0?{name:"",value:l}:{name:l.slice(0,f),value:l.slice(f+1)}})},i=d=>{const l=r.location.protocol==="https:",f=typeof d.expires=="number"?d.expires/1e3:-1;return{domain:Ht(e,d.domain?`.${d.domain.replace(/^\./,"")}`:n()),expires:f,httpOnly:!1,name:d.name,path:d.path??"/",priority:"Medium",...d.sameSite?{sameSite:qt(d.sameSite)}:{},secure:d.secure??!1,session:f===-1,size:d.name.length+d.value.length,sourcePort:Number(r.location.port||(l?443:80)),sourceScheme:l?"Secure":"NonSecure",value:d.value}},a=()=>{const d=r.location.pathname.split("/").filter(Boolean);return["/",...d.map((l,f)=>`/${d.slice(0,f+1).join("/")}`)]},c=async d=>{const l=t();if(l&&d.path!==void 0){await l.delete({name:d.name,path:d.path,...d.domain?{domain:d.domain}:{},...d.partitioned?{partitioned:!0}:{}});return}const f=n().split("."),h=[void 0,...f.slice(0,-1).map((p,w)=>f.slice(w).join("."))];for(const p of a())for(const w of h)r.document.cookie=`${d.name}=; Path=${p}${w?`; Domain=${w}`:""}; Expires=Thu, 01 Jan 1970 00:00:00 GMT`},u=d=>{let l;if(typeof d.domain=="string"&&d.domain&&(l=Nt(e,d.domain),l===void 0))return!1;let f=typeof d.path=="string"&&d.path?d.path:void 0;if(!l&&typeof d.url=="string"){const b=e.toSurface(d.url);if(b===void 0)return!1;const S=new URL(b);l=S.hostname,f??=S.pathname.slice(0,S.pathname.lastIndexOf("/")+1)||"/"}if(!l)throw ae("Cookie should have a url or a domain");if(!s(l))return!1;const h=String(d.name??""),p=String(d.value??""),w=typeof d.expires=="number"&&d.expires>0?d.expires:void 0,m=[`${h}=${p}`,`Path=${f??"/"}`,...l.startsWith(".")?[`Domain=${l.slice(1)}`]:[],...w!==void 0?[`Expires=${new Date(w*1e3).toUTCString()}`]:[],...d.secure===!0?["Secure"]:[],...typeof d.sameSite=="string"?[`SameSite=${d.sameSite}`]:[],...d.partitionKey?["Partitioned"]:[]];r.document.cookie=m.join("; ");const y=f===void 0||r.location.pathname.startsWith(f),g=w===void 0||w*1e3>Date.now();if(y&&g&&!r.document.cookie.split(";").some(b=>b.trim()===`${h}=${p}`))throw D("Storage.setCookies",`the host browser rejected cookie "${h}"`);return!0};return{async handle(d,l){switch(d){case"Storage.getCookies":return{cookies:(await o()).map(i)};case"Storage.setCookies":{const f=Array.isArray(l.cookies)?l.cookies:[];if(f.some(p=>p.httpOnly===!0))throw D(d,"HttpOnly cookies are invisible to scripts and cannot be set from a DOM surface");const h=[];if(f.forEach((p,w)=>{u(p)&&h.push(w)}),l[He]!==!0&&h.length!==f.length)throw D(d,`this surface serves ${n()}, not every cookie's domain`);return l[He]===!0?{applied:h}:{}}case"Storage.clearCookies":for(const f of await o())await c(f);return{};case"Page.deleteCookie":{const f=e.toSurface(String(l.url??""));if(f===void 0)throw new fe({code:-32e3,message:`Page.deleteCookie: ${String(l.url??"")} is not served by this surface`});const h=new URL(f);if(!s(h.hostname))throw D(d,`this surface serves ${n()}, not ${h.hostname}`);for(const p of await o())p.name===l.cookieName&&await c(p);return{}}default:return}}}}const Ut="almostcdpDownloadPolicy";function gs({target:r,sendEvent:e,frameId:t,urls:n},s){let o="default",i;const a=new Map,c=(l,f,h=0,p)=>{a.delete(l),e("Browser.downloadProgress",{guid:l,receivedBytes:h,state:f,totalBytes:h,...p?{filePath:p}:{}})},u=l=>l.protocol==="blob:"||l.protocol==="data:"||l.origin===r.location.origin,d=l=>{if(o==="default"||l.defaultPrevented)return;const f=l.target,h=f?.nodeType===1?f.closest("a[href][download]"):null;if(!h)return;l.preventDefault();const p=r.crypto.randomUUID(),w=new URL(h.href),m=h.download||decodeURIComponent(w.pathname.split("/").filter(Boolean).pop()??"")||"download";if(e("Browser.downloadWillBegin",{frameId:t,guid:p,suggestedFilename:m,url:ke(n,h.href)}),o==="deny"||!u(w)){c(p,"canceled");return}const y=new AbortController;a.set(p,{abort:y}),r.fetch(h.href,{signal:y.signal}).then(g=>{if(!g.ok&&w.protocol!=="blob:"&&w.protocol!=="data:")throw new Error(`HTTP ${g.status}`);return g.arrayBuffer()}).then(g=>{const b=a.get(p);if(!b||y.signal.aborted)return;const S=new Uint8Array(g);b.bytes=S.byteLength,s.send({data:Ne(S),guid:p,suggestedFilename:m,type:"download"})}).catch(()=>{a.has(p)&&c(p,"canceled")})};return{attachment(l,f){if(o==="default")return;const h=r.crypto.randomUUID();return e("Browser.downloadWillBegin",{frameId:t,guid:h,suggestedFilename:f,url:ke(n,l)}),o==="deny"?(c(h,"canceled"),()=>{}):(a.set(h,{abort:new AbortController}),p=>{const w=a.get(h);if(!(!w||w.abort.signal.aborted)){if(!p){c(h,"canceled");return}w.bytes=p.byteLength,s.send({data:Ne(p),guid:h,suggestedFilename:f,type:"download"})}})},written(l){const f=a.get(l.guid);f&&(l.error?c(l.guid,"canceled"):c(l.guid,"completed",f.bytes??0,l.filePath))},install(){i=r.document,i.addEventListener("click",d,!0)},reopened(){i?.addEventListener("click",d,!0)},uninstall(){i?.removeEventListener("click",d,!0)},handle(l,f){switch(l){case"Browser.setDownloadBehavior":{if(f[Ut]!==!0)throw D(l,"download policy is set on the browser session, whose download host writes the files");const h=String(f.behavior??"");if(!["default","deny","allow","allowAndName"].includes(h))throw ae(`Invalid download behavior: ${h}`);return o=h,{}}case"Browser.cancelDownload":{const h=String(f.guid??""),p=a.get(h);if(!p)throw new fe({code:-32e3,message:`Browser.cancelDownload: no in-flight download with guid ${h}`});return p.abort.abort(),c(h,"canceled",p.bytes??0),{}}default:return}}}}const zt="almostcdpFiles",ye=r=>r?.localName==="input"&&r.type==="file";function bs({target:r,sendEvent:e,frameId:t},n){const s=new Wt,o=new Map;let i=!1,a;const c=new WeakMap,u=h=>{e("Page.fileChooserOpened",{backendNodeId:n.backendNodeId(h),frameId:c.get(h.ownerDocument)??t,mode:h.multiple||h.webkitdirectory?"selectMultiple":"selectSingle"})},d=h=>{const p=h.target;!i||!ye(p)||p.disabled||(h.preventDefault(),u(p))},l=new WeakSet,f=h=>{if(l.has(h))return;l.add(h);const p=h.HTMLInputElement,w=p.prototype.showPicker;typeof w=="function"&&s.value(p.prototype,"showPicker",function(){if(i&&this.type==="file"){u(this);return}return w.call(this)});const m=p.prototype.click;s.value(p.prototype,"click",function(){if(i&&ye(this)&&!this.isConnected&&!this.disabled){u(this);return}return m.call(this)})};return{stage(h){if(!o.has(h.token))for(o.set(h.token,[]);o.size>8;)o.delete(o.keys().next().value);const p=new r.File([new r.Uint8Array(Dt(h.dataBase64))],h.name,{...typeof h.lastModified=="number"?{lastModified:h.lastModified}:{},type:h.mimeType??""});typeof h.relativePath=="string"&&Object.defineProperty(p,"webkitRelativePath",{configurable:!0,value:h.relativePath}),o.get(h.token)[h.index]=p},install(){s.forget(),a=r.document,a.addEventListener("click",d,!0),f(a.defaultView??r)},frameLoaded(h,p){try{c.set(h.document,p),h.document.addEventListener("click",d,!0),f(h)}catch{}},reopened(){a?.addEventListener("click",d,!0)},uninstall(){a?.removeEventListener("click",d,!0),s.restore()},async handle(h,p,w){switch(h){case"Page.setInterceptFileChooserDialog":return i=p.enabled===!0,{};case"DOM.setFileInputFiles":{const m=p[zt],y=m&&typeof m.token=="string"?o.get(m.token)??[]:void 0;if(m&&typeof m.token=="string"&&o.delete(m.token),y&&(y.length!==Number(m.count)||y.some(E=>!E)))throw ae("The files the server read did not all reach the page");if(!y&&!n.files)throw D(h,"client file paths are readable only through a host file adapter");const g=n.node(p,w);if(!ye(g))throw ae("Node is not a file input element");const b=new r.DataTransfer;for(const E of y??[])b.items.add(E);const S=!y&&Array.isArray(p.files)?p.files.map(String):[];for(const E of S){const v=await n.files.read(E),R=v.data instanceof Uint8Array?new r.Uint8Array(v.data):v.data;b.items.add(new r.File([R],v.name??E.split(/[\\/]/).pop()??E,{lastModified:v.lastModified,type:v.type??""}))}return g.files=b.files,g.dispatchEvent(new r.Event("input",{bubbles:!0,composed:!0})),g.dispatchEvent(new r.Event("change",{bubbles:!0})),{}}default:return}}}}const Vt={CSS:"no style-engine inspection backend; stylesheets and rule usage belong to the host browser",Debugger:"no script debugger backend; scripts run in the host browser's engine",HeapProfiler:"no heap inspection or garbage-collection backend",IO:"no protocol stream backend; nothing produces stream handles",Profiler:"no CPU profiling or coverage backend",Tracing:"no tracing backend"},Gt={"Browser.cancelDownload":"downloads are not modelled without a host download adapter","Browser.close":"the browser belongs to the embedding host","Browser.getWindowBounds":"a surface has no browser window","Browser.getWindowForTarget":"a surface has no browser window","Browser.setDockTile":"a surface has no browser window","Browser.setWindowBounds":"a surface has no browser window","Console.enable":"console messages are reported through Runtime and Log","DOM.getFrameOwner":"child frames are not modelled","Emulation.setDefaultBackgroundColorOverride":"the page background is painted by the host browser's compositor","Emulation.setScriptExecutionDisabled":"script execution is controlled by the host browser","Emulation.setTimezoneOverride":"the time zone of Date and Intl is fixed by the host browser's realm","Network.clearBrowserCache":"the HTTP cache belongs to the host browser","Network.emulateNetworkConditions":"network conditions are applied by the host browser's network stack","Network.loadNetworkResource":"resources outside the page's own fetch are loaded by the host browser","Network.setBypassServiceWorker":"service-worker routing belongs to the host browser","Page.printToPDF":"no print or PDF backend","Page.setBypassCSP":"Content-Security-Policy is enforced by the host browser","Security.setIgnoreCertificateErrors":"certificate validation belongs to the host browser","Target.sendMessageToTarget":"sessions are flattened; nested message routing is not modelled"},vs=r=>{const e=Gt[r]??Vt[r.split(".")[0]];return e===void 0?void 0:{code:-32e3,message:`${r} is unavailable on a DOM surface: ${e}`}};class Ss extends EventTarget{port;readyState=1;constructor(e){super(),this.port=e,e.addEventListener("message",this.receive),e.addEventListener("messageerror",this.failed),e.start()}receive=e=>{const t=e.data;if(t?.type==="close"){this.finish();return}if(t?.type!=="data"||typeof t.data!="string"){this.close(1003,"Invalid transport envelope");return}this.dispatchEvent(new MessageEvent("message",{data:t.data}))};failed=()=>{this.close(1003,"MessagePort decode failure")};finish(){this.readyState!==3&&(this.readyState=3,this.port.removeEventListener("message",this.receive),this.port.removeEventListener("messageerror",this.failed),this.port.close(),this.dispatchEvent(new Event("close")))}send(e){if(this.readyState!==1)throw new Error("MessagePort transport is closed");this.port.postMessage({type:"data",data:e})}close(e=1e3,t="Transport closed"){this.readyState!==3&&(this.port.postMessage({type:"close",code:e,reason:t}),this.finish())}on(e,t){this.addEventListener(e,n=>{e==="message"?t(n.data):t()})}}const ce=new WeakMap;function ks(r,e){return ce.get(r)?.registrations.get(e)?.server}function ee(r,e,t){const n=ce.get(r)?.registrations.get(e);return t===void 0||n?.server===t?n:void 0}function Xt(r,e,t){ee(r,e)===t&&r.unregisterServer(e)}function ht(r,e){let t=ce.get(r);if(!t){t={listeners:new Set,registrations:new Map},ce.set(r,t);const n=r.registerServer.bind(r),s=r.unregisterServer.bind(r);r.registerServer=(o,i,a)=>{const c=r.getServerPorts().includes(i),u=o.handleRequest.bind(o);if(o.handleRequest=(d,l,f,h)=>{const p=Object.keys(f).some(w=>w.toLowerCase()==="host");return u(d,l,p?f:{...f,host:`${a&&a!=="0.0.0.0"&&a!=="::"?a:"127.0.0.1"}:${i}`},h)},n(o,i,a),t.registrations.set(i,{server:o}),!c){const d={port:i,type:"open",...r.getServerUrl?{url:r.getServerUrl(i)}:{}};for(const l of t.listeners)try{l(d)}catch(f){console.error("Port registration observer failed.",f)}}},r.unregisterServer=o=>{const i=r.getServerPorts().includes(o);if(s(o),t.registrations.delete(o),i){const a={port:o,type:"close"};for(const c of t.listeners)try{c(a)}catch(u){console.error("Port release observer failed.",u)}}}}return t.listeners.add(e),()=>t.listeners.delete(e)}class Q{filesystem;static attached=new WeakMap;metadata=new Jt;changeListeners=new Set;originals;nativeMetadata;constructor(e){this.filesystem=e,this.originals={statSync:e.statSync.bind(e),lstatSync:e.lstatSync.bind(e),writeFileSync:e.writeFileSync.bind(e),mkdirSync:e.mkdirSync.bind(e),unlinkSync:e.unlinkSync.bind(e),rmdirSync:e.rmdirSync.bind(e),renameSync:e.renameSync.bind(e),toSnapshot:e.toSnapshot.bind(e),...e.chmodSync?{chmodSync:e.chmodSync.bind(e)}:{},...e.utimesSync?{utimesSync:e.utimesSync.bind(e)}:{}},this.nativeMetadata=!!(this.originals.chmodSync&&this.originals.utimesSync),this.nativeMetadata||this.restore(this.originals.toSnapshot()),this.install()}static attach(e){const t=this.attached.get(e);if(t)return t;const n=new Q(e);return this.attached.set(e,n),n}static for(e){return this.attached.get(e)}onChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}changed(e){for(const t of this.changeListeners)try{t(e)}catch(n){console.error("Filesystem metadata observer failed.",n)}}restore(e){this.metadata.clear();for(const t of e.files){const n=P(t.path),s=this.safeStat(n);this.metadata.set(n,{mode:ge(t.mode)?t.mode:s?.mode??(t.type==="directory"?493:420),mtimeMs:be(t.mtimeMs)?t.mtimeMs:s?.mtimeMs??Date.now()})}if(!this.metadata.has("/")){const t=this.safeStat("/");this.metadata.set("/",{mode:t?.mode??493,mtimeMs:t?.mtimeMs??Date.now()})}}applyChanges(e,t){const n=new Set(t.map(P));for(const s of t)this.deleteTree(P(s));for(const s of e.files){if(!ge(s.mode)||!be(s.mtimeMs))continue;const o=P(s.path),i=this.metadata.get(o);(!i||i.mode!==s.mode||i.mtimeMs!==s.mtimeMs)&&n.add(o),this.metadata.set(o,{mode:s.mode,mtimeMs:s.mtimeMs})}for(const s of n)this.changed(s)}chmodSync(e,t){const n=P(e);if(this.originals.statSync(n),!ge(t))throw new RangeError(`Invalid file mode for ${n}.`);this.originals.chmodSync?.(n,t);const s=this.ensure(n);s.mode=t,this.changed(n)}utimesSync(e,t,n){const s=P(e);this.originals.statSync(s);const o=n instanceof Date?n.getTime():n;if(!be(o))throw new RangeError(`Invalid modification time for ${s}.`);this.originals.utimesSync?.(s,t,n);const i=this.ensure(s);i.mtimeMs=o,this.changed(s)}install(){const e=this.filesystem;e.statSync=(t=>this.decorate(t,this.originals.statSync(t))),e.lstatSync=(t=>this.decorate(t,this.originals.lstatSync(t))),e.writeFileSync=((t,n)=>{const s=P(t),o=this.nativeMetadata?this.safeStat(s):this.metadata.get(s);this.originals.writeFileSync(t,n),this.metadata.set(s,{mode:o?.mode??420,mtimeMs:Date.now()}),this.ensureParents(s)}),e.mkdirSync=((t,n)=>{this.originals.mkdirSync(t,n);const s=P(t);this.ensureParents(`${s}/child`),this.ensure(s,493),this.changed(s)}),e.unlinkSync=(t=>{this.originals.unlinkSync(t),this.metadata.delete(P(t))}),e.rmdirSync=(t=>{this.originals.rmdirSync(t),this.deleteTree(P(t)),this.changed(P(t))}),e.renameSync=((t,n)=>{const s=P(t),o=P(n);if(this.originals.renameSync(t,n),s===o)return;this.deleteTree(o);const i=this.metadata.entriesUnder(s);for(const[a]of i)this.metadata.delete(a);for(const[a,c]of i)this.metadata.set(`${o}${a.slice(s.length)}`,c);this.ensureParents(o),this.changed(s),this.changed(o)}),e.chmodSync=(t,n)=>this.chmodSync(t,n),e.utimesSync=(t,n,s)=>this.utimesSync(t,n,s),e.toSnapshot=(()=>this.nativeMetadata?this.originals.toSnapshot():{files:this.originals.toSnapshot().files.map(t=>{const n=this.metadata.get(Qt(t.path)?t.path:P(t.path));return n?{...t,mode:n.mode,mtimeMs:n.mtimeMs}:t})})}decorate(e,t){if(this.nativeMetadata)return t;const n=this.ensure(P(e),t.mode,t.mtimeMs),s=new Date(n.mtimeMs);return{...t,mode:n.mode,mtimeMs:n.mtimeMs,mtime:s}}ensure(e,t,n){let s=this.metadata.get(e);if(!s){const o=this.safeStat(e);s={mode:t??o?.mode??(o?.isDirectory()?493:420),mtimeMs:n??o?.mtimeMs??Date.now()},this.metadata.set(e,s)}return s}ensureParents(e){const t=P(e).split("/").filter(Boolean);let n="";for(const s of t.slice(0,-1))n+=`/${s}`,this.filesystem.existsSync(n)&&this.ensure(n,493);this.ensure("/",493)}deleteTree(e){this.metadata.deleteTree(e)}safeStat(e){try{return this.originals.statSync(e)}catch{return}}}function Qt(r){return r.startsWith("/")&&(r==="/"||!r.endsWith("/"))&&!r.includes("//")&&!r.includes("/./")&&!r.includes("/../")&&!r.endsWith("/.")&&!r.endsWith("/..")}function P(r){if(r.startsWith("/")&&(r.length===1||!r.endsWith("/"))&&!r.includes("//")&&!r.includes("/./")&&!r.includes("/../")&&!r.endsWith("/.")&&!r.endsWith("/.."))return r;const e=[];for(const t of`/${r}`.split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}function ge(r){return Number.isSafeInteger(r)&&r>=0&&r<=4095}function be(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0}class Jt extends Map{children=new Map;set(e,t){super.set(e,t);let n=e;for(;n!=="/";){const s=ve(n);let o=this.children.get(s);if(o||(o=new Set,this.children.set(s,o)),o.has(n))break;o.add(n),n=s}return this}delete(e){const t=super.delete(e);return e!=="/"&&!this.children.has(e)&&this.children.get(ve(e))?.delete(e),t}clear(){super.clear(),this.children.clear()}deleteTree(e){for(const t of[...this.children.get(e)??[]])this.deleteTree(t);this.children.delete(e),this.delete(e),e!=="/"&&this.children.get(ve(e))?.delete(e)}entriesUnder(e){const t=[],n=s=>{const o=this.get(s);o&&t.push([s,o]);for(const i of this.children.get(s)??[])n(i)};return n(e),t}}function ve(r){const e=r.lastIndexOf("/");return e<=0?"/":r.slice(0,e)}function ut(r){if(r.length%4!==0)return;const e=r.endsWith("==")?2:r.endsWith("=")?1:0,t=r.length-e;for(let n=0;n<r.length;n+=1){const s=r.charCodeAt(n),o=n<t,i=s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===43||s===47;if(o?!i:s!==61)return}return r.length/4*3-e}function H(r){const e=r.toBase64;if(typeof e=="function")return e.call(r);let t="";for(let n=0;n<r.byteLength;n+=32768)t+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(t)}function ft(r){const e=Uint8Array.fromBase64;if(typeof e=="function")return e(r);const t=atob(r),n=new Uint8Array(t.length);for(let s=0;s<t.length;s+=1)n[s]=t.charCodeAt(s);return n}class Ee extends Error{constructor(){super("The workspace changed while saving its snapshot; retry after those writes finish."),this.name="BrowserFileSystemSnapshotChangedError"}}function Es(r,e=globalThis.location?.origin){const t=r;return t.storeOrigin===void 0||t.storeOrigin===e?t.projectId:void 0}async function Kt(r,e){if(r.readEntry){const o=await r.readEntry(e);if(!o||o.type==="directory")return o;const{bytes:i,...a}=o;return{...a,content:H(i)}}if(!r.existsSync(e))return;const t=r.statSync(e),n={path:e,mode:t.mode&4095,mtimeMs:t.mtimeMs};if(t.isDirectory())return{...n,type:"directory"};const s=await r.readFile(e);return{...n,type:"file",content:H(s)}}async function Yt(r,e="/",t={}){const n=a=>[...t.excludePaths??[]].some(c=>a===c||a.startsWith(`${c==="/"?"":c}/`));let s=!1;const o=a=>{(e==="/"||a===e||a.startsWith(`${e}/`)||e.startsWith(`${a==="/"?"":a}/`))&&!n(a)&&(s=!0)};let i;t.consistent&&(r.on("change",o),r.on("delete",o),i=Q.for(r)?.onChange(o));try{const a=[],c=[...t.metadataRoots??[],...t.excludePaths??[]];for(const u of r.toSnapshot(c.length>0?{withoutContentUnder:c}:void 0).files){if(e!=="/"&&u.path!==e&&!u.path.startsWith(`${e}/`)||n(u.path))continue;const d=t.metadataRoots?.some(f=>f==="/"||u.path===f||u.path.startsWith(`${f}/`));if(u.type==="directory"||u.content!==void 0||d){a.push({...u});continue}const l=await Kt(r,u.path);l&&a.push(l)}if(s)throw new Ee;return{files:a}}catch(a){throw s?new Ee:a}finally{t.consistent&&(r.off("change",o),r.off("delete",o),i?.())}}const Zt=4096,er=180,tr=3e3,We=1,De=400*24*60*60*1e3,qe=3e3,rr=/^\d{1,3}(?:\.\d{1,3}){3}$/u,sr=/^(?:localhost|(?:[a-z0-9-]+\.)+localhost|127(?:\.\d{1,3}){3}|\[::1\]|::1)$/iu;function Te(r){const e=r.trim().toLowerCase();if(e.startsWith("[")){const n=e.indexOf("]");return n===-1?e:e.slice(0,n+1)}const t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function nr(r){return rr.test(r)||r.startsWith("[")||r.includes(":")}function K(r,e){return r===e?!0:!nr(r)&&r.endsWith(`.${e}`)}function or(r){const e=r.split(/[?#]/u,1)[0];if(!e.startsWith("/"))return"/";const t=e.lastIndexOf("/");return t===0?"/":e.slice(0,t)}function Ue(r,e){const t=r.split(/[?#]/u,1)[0]||"/";return t===e?!0:t.startsWith(e)?e.endsWith("/")||t[e.length]==="/":!1}const ir=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];function ar(r){const e=r.split(/[\x09\x20-\x2f\x3b-\x40\x5b-\x60\x7b-\x7e]+/u).filter(Boolean);let t,n,s,o;for(const a of e){const c=t===void 0?/^(\d{1,2}):(\d{1,2}):(\d{1,2})(?:\D.*)?$/u.exec(a):null;if(c){t=[Number(c[1]),Number(c[2]),Number(c[3])];continue}const u=n===void 0?/^(\d{1,2})(?:\D.*)?$/u.exec(a):null;if(u){n=Number(u[1]);continue}if(s===void 0){const l=ir.indexOf(a.slice(0,3).toLowerCase());if(l!==-1){s=l;continue}}const d=o===void 0?/^(\d{2,4})(?:\D.*)?$/u.exec(a):null;if(d){o=Number(d[1]);continue}}if(o!==void 0&&o>=70&&o<=99&&(o+=1900),o!==void 0&&o>=0&&o<=69&&(o+=2e3),t===void 0||n===void 0||s===void 0||o===void 0||n<1||n>31||o<1601||t[0]>23||t[1]>59||t[2]>59)return;const i=Date.UTC(o,s,n,t[0],t[1],t[2]);if(new Date(i).getUTCDate()===n)return i}function cr(r){const[e,...t]=r.split(";"),n=e.indexOf("=");if(n===-1)return;const s=e.slice(0,n).trim(),o=e.slice(n+1).trim();if(!s||/[\x00-\x08\x0a-\x1f\x7f]/u.test(s+o))return;const i={name:s,value:o,secure:!1,httpOnly:!1,sameSite:"Default"};for(const a of t){const c=a.indexOf("="),u=(c===-1?a:a.slice(0,c)).trim().toLowerCase(),d=c===-1?"":a.slice(c+1).trim();if(u==="expires"){const l=ar(d);l!==void 0&&(i.expires=l)}else if(u==="max-age")/^-?\d+$/u.test(d)&&(i.maxAge=Number(d));else if(u==="domain")d&&(i.domain=d.replace(/^\./u,"").toLowerCase());else if(u==="path")d.startsWith("/")?i.path=d:delete i.path;else if(u==="secure")i.secure=!0;else if(u==="httponly")i.httpOnly=!0;else if(u==="samesite"){const l=d.toLowerCase();i.sameSite=l==="strict"?"Strict":l==="lax"?"Lax":l==="none"?"None":"Default"}}return i}function dr(r){const e=[];for(const[t,n]of Object.entries(r))if(!(t.toLowerCase()!=="set-cookie"||n===void 0)){if(Array.isArray(n)){e.push(...n.map(s=>String(s).trim()).filter(Boolean));continue}e.push(...String(n).split(/,(?=\s*[^\s=;,]+=)(?!\s*(?:expires|max-age|domain|path|samesite)=)/iu).map(s=>s.trim()).filter(Boolean))}return e}function de(r){return sr.test(Te(r))}class lr{cookies=[];now;listeners=new Set;lastCreation=0;constructor(e={}){this.now=e.now??(()=>Date.now())}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}storeResponse(e,t){let n=!1;for(const s of dr(t))n=this.store(e,s,!0)||n;n&&this.changed()}setFromDocument(e,t){this.store(e,String(t),!1)&&this.changed()}requestHeader(e){return this.serialize(e,!0)||void 0}documentCookie(e){return this.serialize(e,!1)}list(){return this.evictExpired(),this.cookies.map(e=>({...e}))}clear(){this.cookies.length!==0&&(this.cookies=[],this.changed())}snapshot(){return{version:We,cookies:this.list()}}restore(e){const t=e;if(!t||t.version!==We||!Array.isArray(t.cookies))return;const n=[];for(const s of t.cookies)!s||typeof s.name!="string"||typeof s.value!="string"||typeof s.domain!="string"||typeof s.path!="string"||n.push({name:s.name,value:s.value,domain:s.domain,path:s.path,...typeof s.expires=="number"?{expires:s.expires}:{},hostOnly:s.hostOnly!==!1,secure:s.secure===!0,httpOnly:s.httpOnly===!0,sameSite:s.sameSite==="Strict"||s.sameSite==="Lax"||s.sameSite==="None"?s.sameSite:"Default",creation:Number(s.creation)||0,lastAccess:Number(s.lastAccess)||0});this.cookies=n,this.lastCreation=n.reduce((s,o)=>Math.max(s,o.creation),0),this.evictExpired()}store(e,t,n){const s=cr(t);if(!s||s.name.length+s.value.length>Zt)return!1;const o=Te(e.host),i=e.secure??de(e.host),a=this.now();let c;s.maxAge!==void 0?c=s.maxAge<=0?0:a+s.maxAge*1e3:s.expires!==void 0&&(c=s.expires),c!==void 0&&c>a+De&&(c=a+De);let u=o,d=!0;if(s.domain!==void 0&&s.domain!==o){if(!K(o,s.domain)||!s.domain.includes(".")&&s.domain!=="localhost")return!1;u=s.domain,d=!1}else s.domain!==void 0&&(d=!1);if(s.secure&&!i||s.httpOnly&&!n||s.name.startsWith("__Secure-")&&!s.secure||s.name.startsWith("__Host-")&&(!s.secure||!d||s.path!=="/"))return!1;const l=s.path??or(e.path),f=this.cookies.findIndex(w=>w.name===s.name&&w.domain===u&&w.hostOnly===d&&w.path===l),h=f===-1?void 0:this.cookies[f];if(!n&&this.cookies.some(w=>w.httpOnly&&w.name===s.name&&(K(u,w.domain)||K(w.domain,u))&&Ue(l,w.path)))return!1;if(f!==-1&&this.cookies.splice(f,1),c!==void 0&&c<=a)return h!==void 0;const p=h?.creation??Math.max(a,this.lastCreation+.001);return this.lastCreation=Math.max(this.lastCreation,p),this.cookies.push({name:s.name,value:s.value,domain:u,path:l,...c!==void 0?{expires:c}:{},hostOnly:d,secure:s.secure,httpOnly:s.httpOnly,sameSite:s.sameSite,creation:p,lastAccess:a}),this.enforceLimits(u),!0}serialize(e,t){this.evictExpired();const n=Te(e.host),s=e.secure??de(e.host),o=this.now(),i=this.cookies.filter(a=>(a.hostOnly?n===a.domain:K(n,a.domain))&&Ue(e.path,a.path)&&(!a.secure||s)&&(t||!a.httpOnly));i.sort((a,c)=>c.path.length-a.path.length||a.creation-c.creation);for(const a of i)a.lastAccess=o;return i.map(a=>`${a.name}=${a.value}`).join("; ")}evictExpired(){const e=this.now(),t=this.cookies.length;this.cookies=this.cookies.filter(n=>n.expires===void 0||n.expires>e),this.cookies.length!==t&&this.changed()}enforceLimits(e){const t=(n,s)=>{if(n.length<=s)return;const o=new Set([...n].sort((i,a)=>i.lastAccess-a.lastAccess).slice(0,n.length-s));this.cookies=this.cookies.filter(i=>!o.has(i))};t(this.cookies.filter(n=>n.domain===e),er),t(this.cookies,tr)}changed(){for(const e of this.listeners)try{e()}catch(t){console.error("Cookie jar listener failed.",t)}}}const hr="browser-substrate-cookies",V="jars";function ur(){return new Promise((r,e)=>{const t=setTimeout(()=>e(new Error(`The cookie jar's database did not open in ${qe} ms.`)),qe),n=indexedDB.open(hr,1);n.onupgradeneeded=()=>{n.result.createObjectStore(V)},n.onsuccess=()=>{clearTimeout(t),r(n.result)},n.onerror=()=>{clearTimeout(t),e(n.error??new Error("The cookie jar's database did not open."))},n.onblocked=()=>{clearTimeout(t),e(new Error("The cookie jar's database is blocked by another tab."))}})}async function Ts(r,e={}){const t=new lr(e);let n;try{n=await ur();const o=await new Promise((i,a)=>{const c=n.transaction(V,"readonly").objectStore(V).get(r);c.onsuccess=()=>i(c.result),c.onerror=()=>a(c.error)});t.restore(o)}catch(o){return console.warn("The cookie jar is not kept across reloads:",o),t}let s=Promise.resolve();return t.onChange(()=>{const o=t.snapshot();s=s.then(()=>new Promise(i=>{try{const a=n.transaction(V,"readwrite");a.objectStore(V).put(o,r),a.oncomplete=()=>i(),a.onerror=a.onabort=()=>{console.warn("The cookie jar was not saved:",a.error),i()}}catch(a){console.warn("The cookie jar was not saved:",a),i()}}))}),t}const te="__browserRuntimeCookies";function Ps(r,e){const t=globalThis.isSecureContext===!0,n=o=>{const i=String(o?.host??"");return{host:i,path:String(o?.path??"/"),secure:t||de(i)}},s=Object.freeze({read:o=>e.documentCookie(n(o)),write:(o,i)=>e.setFromDocument(n(o),String(i))});return Object.defineProperty(r,te,{value:s,configurable:!0,enumerable:!1,writable:!1}),()=>{r[te]===s&&delete r[te]}}class xs{jar;secureContext;pending=new Map;constructor(e,t=globalThis.isSecureContext===!0){this.jar=e,this.secureContext=t}request(e){const t=e,n=t?.data;if(t?.type!=="request"||!Number.isSafeInteger(t.id)||!n||typeof n.url!="string"||!n.headers||typeof n.headers!="object"||Array.isArray(n.headers))return;const s={};for(const[u,d]of Object.entries(n.headers))u.toLowerCase()!=="cookie"&&(s[u]=d);const o=Object.keys(s).find(u=>u.toLowerCase()==="host"),i=o?s[o]:`localhost:${Number(n.port)}`,a={host:i,path:n.url,secure:this.secureContext||de(i)},c=this.jar.requestHeader(a);c&&(s.cookie=c),n.headers=s,this.pending.set(t.id,a)}answer(e){const t=e;if(!t||!Number.isSafeInteger(t.id))return;const n=t.id,s=this.pending.get(n);s&&((t.type==="response"||t.type==="stream-start")&&!t.error?(this.pending.delete(n),this.jar.storeResponse(s,t.data?.headers??{})):(t.type==="response"||t.type==="stream-error")&&this.pending.delete(n))}forget(e){this.pending.delete(e)}reset(){this.pending.clear()}}async function M(r,e){const t=typeof r=="function"?Promise.resolve().then(()=>(e.throwIfAborted(),r())):Promise.resolve(r);let n;const s=new Promise((o,i)=>{n=()=>i(e.reason??new DOMException("Browser operation was cancelled.","AbortError")),e.addEventListener("abort",n,{once:!0}),e.aborted&&n()});try{return await Promise.race([t,s])}finally{e.removeEventListener("abort",n)}}const Pe=65536,ze=16*1024*1024,fr=15e3;class As{bridge;drainTimeoutMs;entries=new Map;listeners=new Set;cleanupFailures=[];closing=new Set;reservedPorts=new Set;registering=new Map;disposed=!1;disposePromise;stopObservingPorts;constructor(e,t=fr){if(this.bridge=e,this.drainTimeoutMs=t,!Number.isSafeInteger(t)||t<1)throw new Error("Invalid Host Fetch-service drain timeout.");this.stopObservingPorts=ht(e,()=>{});const n=e.registerServer.bind(e);e.registerServer=(s,o,i)=>{if(this.reservedPorts.has(o)&&this.registering.get(o)!==s)throw new Error(`Virtual port ${o} is reserved by a Host Fetch service or failed cleanup.`);n(s,o,i)}}get(e){const t=this.entries.get(e);if(t&&ee(this.bridge,e,t.server)!==t.registration){t.closeService?.().catch(()=>{});return}return t}snapshot(){return[...this.entries.values()].filter(e=>e.initialized&&this.get(e.port)===e)}observe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}announce(e,t){for(const n of this.listeners)try{n(e,t)}catch(s){console.error("Host Fetch-service observer failed.",s)}}register(e){if(this.disposed)throw new Error("Host Fetch-service registry is disposed.");const{port:t}=e;if(!Number.isSafeInteger(t)||t<1||t>65535)throw new Error("Invalid Host Fetch-service port.");if(typeof e.fetch!="function")throw new Error("Host Fetch-service requires a Fetch handler.");const n=e.maxRequestBytes??ze;if(!Number.isSafeInteger(n)||n<1||n>ze)throw new Error("Invalid Host Fetch-service upload limit.");if(e.lifetime?.aborted)throw new Error("Host Fetch-service owner has stopped.");if(this.reservedPorts.has(t))throw new Error(`Virtual port ${t} is reserved by a Host Fetch service or failed cleanup.`);if(this.bridge.getServerPorts().includes(t))throw new Error(`Virtual port ${t} is already registered.`);const s=new AbortController;let o,i;const a=new Promise((w,m)=>{o=w,i=m});a.catch(()=>{});const c={listening:!0,address:()=>({port:t,address:"127.0.0.1",family:"IPv4"}),handleRequest:async()=>({statusCode:426,statusMessage:"Upgrade Required",headers:{"content-type":"text/plain","x-host-fetch-protocol":"flow-control-1-required"},body:new TextEncoder().encode("Host Fetch service requires flow-control protocol 1.")}),fetch:w=>this.invoke(t,c,w)};this.reservedPorts.add(t),this.registering.set(t,c);try{this.bridge.registerServer(c,t,"127.0.0.1")}catch(w){throw this.reservedPorts.delete(t),w}finally{this.registering.delete(t)}const u=ee(this.bridge,t,c);if(!u)throw this.reservedPorts.delete(t),new Error("Host Fetch-service port registration is not identity-observed.");const d={flowControl:1,maxRequestBytes:n,maxChunkBytes:Pe},l=e.lifetime,f=()=>{p().catch(()=>{})},h={port:t,fetch:e.fetch,ready:a,maxRequestBytes:n,signal:s.signal,initialized:!1,capability:d,controller:s,registration:u,server:c,removeLifetime:()=>l?.removeEventListener("abort",f),inflight:new Set,operationFailures:[],track(w,m=!1){this.inflight.add(w),w.then(()=>this.inflight.delete(w),y=>{this.inflight.delete(w),m&&this.operationFailures.push(y)})}},p=()=>{if(h.closePromise)return h.closePromise;h.removeLifetime(),s.abort(new Error("Host Fetch service stopped.")),i(s.signal.reason);const w=this.entries.get(t)===h;return w&&this.entries.delete(t),h.closePromise=(async()=>{let m;try{Xt(this.bridge,t,u)}catch(y){m=y}w&&this.announce(t,void 0);try{const y=Promise.allSettled([...h.inflight]);let g;try{await Promise.race([y,new Promise((b,S)=>{g=setTimeout(()=>S(new Error("Host Fetch-service active request did not drain.")),this.drainTimeoutMs)})])}finally{g!==void 0&&clearTimeout(g)}}catch(y){m=m===void 0?y:new AggregateError([m,y],"Host Fetch-service cleanup failed.")}if(h.operationFailures.length){const y=new AggregateError(h.operationFailures,"Host Fetch-service cleanup operation failed.");m=m===void 0?y:new AggregateError([m,y],"Host Fetch-service cleanup failed.")}if(m===void 0&&h.inflight.size===0)try{await e.close?.()}catch(y){m=m===void 0?y:new AggregateError([m,y],"Host Fetch-service cleanup failed.")}if(m!==void 0)throw m;this.reservedPorts.delete(t)})().catch(m=>{throw this.cleanupFailures.push(m),m}),this.closing.add(h.closePromise),h.closePromise.finally(()=>this.closing.delete(h.closePromise)).catch(()=>{}),h.closePromise};return h.closeService=p,this.entries.set(t,h),l?.addEventListener("abort",f,{once:!0}),l?.aborted?(f(),{port:t,ready:a,close:p}):(e.ready?e.ready.then(()=>{if(this.entries.get(t)!==h||s.signal.aborted||ee(this.bridge,t,c)!==u){i(new Error("Host Fetch-service registration closed before initialization completed."));return}h.initialized=!0,this.announce(t,d),o()},w=>{i(w),p().catch(()=>{})}):(h.initialized=!0,this.announce(t,d),o()),{port:t,ready:a,close:p})}async invoke(e,t,n){const s=this.entries.get(e);if(!s||s.server!==t||this.get(e)!==s)throw new Error(`No Host Fetch service is registered on port ${e}.`);const o=new AbortController;let i,a=!1;const c=()=>{if(o.signal.aborted)return;const d=s.signal.aborted?s.signal.reason:n.signal.reason;i&&!a&&s.track(i.cancel(d),!0),o.abort(d)},u=()=>{s.signal.removeEventListener("abort",c),n.signal.removeEventListener("abort",c)};s.signal.addEventListener("abort",c,{once:!0}),n.signal.addEventListener("abort",c,{once:!0}),(s.signal.aborted||n.signal.aborted)&&c();try{await M(s.ready,o.signal);const d=n.method,l=d==="GET"||d==="HEAD"?void 0:await M(n.arrayBuffer(),o.signal);if(l&&l.byteLength>s.maxRequestBytes)throw new Error(`Host Fetch-service upload exceeds ${s.maxRequestBytes} bytes.`);const f=Promise.resolve().then(()=>s.fetch(new Request(n.url,{method:d,headers:n.headers,...l&&l.byteLength>0?{body:l}:{},signal:o.signal})));s.track(f),s.track(f.then(async m=>{o.signal.aborted&&m instanceof Response&&await m.body?.cancel()},()=>{}),!0);const h=await M(f,o.signal);if(!(h instanceof Response))throw new Error("Host Fetch handler did not return a Response.");if(!h.body)return u(),h;i=h.body.getReader();const p=i;p.closed.then(()=>{a=!0},()=>{a=!0});const w=new ReadableStream({pull:async m=>{const y=p.read();s.track(y);try{const g=await M(y,o.signal);if(g.done){u(),m.close();return}if(!(g.value instanceof Uint8Array))throw new Error("Host Fetch-service producer did not yield bytes.");m.enqueue(g.value)}catch(g){throw u(),g}},cancel:async m=>{if(u(),o.signal.aborted||a)return;const y=p.cancel(m);s.track(y,!0),o.abort(m),await y}},{highWaterMark:0});return new Response(w,{status:h.status,statusText:h.statusText,headers:h.headers})}catch(d){throw u(),d}}dispose(){return this.disposePromise?this.disposePromise:(this.disposed=!0,this.disposePromise=(async()=>{const e=[];for(const t of[...this.entries.values()])try{await t.closeService?.()}catch(n){e.push(n)}for(const t of await Promise.allSettled([...this.closing]))t.status==="rejected"&&!e.includes(t.reason)&&e.push(t.reason);this.stopObservingPorts();for(const t of this.cleanupFailures)e.includes(t)||e.push(t);if(e.length)throw new AggregateError(e,"Host Fetch-service disposal failed.")})(),this.disposePromise)}}const pr="supercode-browser-agent",L="projects",Fe=1;async function Ve(){if(typeof navigator>"u"||!navigator.storage)return{persisted:!1};const r=await navigator.storage.persisted?.().catch(()=>!1)??!1,e=await navigator.storage.estimate?.().catch(()=>({}))??{};return{persisted:r,...e.usage!==void 0?{usage:e.usage}:{},...e.quota!==void 0?{quota:e.quota}:{}}}function pe(){return new Promise((r,e)=>{const t=indexedDB.open(pr,1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains(L)||t.result.createObjectStore(L)},t.onsuccess=()=>{t.result.onversionchange=()=>t.result.close(),r(t.result)},t.onerror=()=>e(t.error??new Error("Could not open the browser project database.")),t.onblocked=()=>e(new Error("Browser project storage is blocked by another open tab."))})}function N(r,e){return r.error??new Error(e)}async function pt(r,e){const t=await pe();try{return await new Promise((n,s)=>{const o=t.transaction(L,"readonly"),i=o.objectStore(L),a=i.get(r),c=i.get(e);let u,d;a.onsuccess=()=>{u=a.result},c.onsuccess=()=>{d=c.result},o.oncomplete=()=>n({primary:u,backup:d}),o.onerror=()=>s(N(o,"Browser project storage failed.")),o.onabort=()=>s(N(o,"Browser project storage was aborted."))})}finally{t.close()}}function xe(r){if(!r||typeof r!="object"||Array.isArray(r))return;const e=r;return e.storageVersion===Fe&&typeof e.checksum=="string"?e.checksum:void 0}async function wr(r,e,t,n,s){const o=await pe();try{await new Promise((i,a)=>{const c=o.transaction(L,"readwrite"),u=c.objectStore(L),d=u.get(r);let l=!1;d.onsuccess=()=>{if(s.known&&xe(d.result)!==s.revision){l=!0,u.put(n,t);return}d.result!==void 0&&u.put(d.result,e),u.put(n,r)},c.oncomplete=()=>l?a(new Error("Browser project storage changed in another tab; this tab did not overwrite it, and its latest save was preserved as a conflict copy.")):i(),c.onerror=()=>a(N(c,"Browser project storage failed.")),c.onabort=()=>a(N(c,"Browser project storage was aborted."))})}finally{o.close()}}async function mr(r,e){const t=await pe();try{await new Promise((n,s)=>{const o=t.transaction(L,"readwrite");o.objectStore(L).put(e,r),o.oncomplete=()=>n(),o.onerror=()=>s(N(o,"Browser project storage failed.")),o.onabort=()=>s(N(o,"Browser project storage was aborted."))})}finally{t.close()}}async function yr(...r){const e=await pe();try{await new Promise((t,n)=>{const s=e.transaction(L,"readwrite"),o=s.objectStore(L);for(const i of r)o.delete(i);s.oncomplete=()=>t(),s.onerror=()=>n(N(s,"Browser project storage failed.")),s.onabort=()=>n(N(s,"Browser project storage was aborted."))})}finally{e.close()}}async function wt(r){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r));let t="";for(const n of new Uint8Array(e))t+=String.fromCharCode(n);return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}async function gr(r){return{storageVersion:Fe,savedAt:Date.now(),checksum:await wt(JSON.stringify(r)),payload:r}}async function Ge(r,e){if(r&&typeof r=="object"&&!Array.isArray(r)&&r.storageVersion===Fe){const t=r;if(typeof t.checksum!="string"||t.payload===void 0||await wt(JSON.stringify(t.payload))!==t.checksum)throw new Error("Saved browser data failed its integrity check.");return e(t.payload)}return e(r)}async function br(r){if(!(typeof navigator>"u"||!navigator.storage?.estimate))try{const e=await navigator.storage.estimate();if(e.quota!==void 0&&e.usage!==void 0&&r>Math.max(0,e.quota-e.usage))throw new DOMException("The browser does not have enough storage quota for this project save.","QuotaExceededError")}catch(e){if(e instanceof DOMException&&e.name==="QuotaExceededError")throw e}}async function Cs(){if(typeof navigator>"u"||!navigator.storage)return{persisted:!1};const r=await Ve();return r.persisted?r:(await navigator.storage.persist?.().catch(()=>!1),Ve())}class vr{worker;pending=new Map;nextRequest=1;constructor(){this.worker=dt(new Worker(new URL("/assets/browser-opfs-storage-worker-Dwz_4ewA.js",import.meta.url),{type:"module",name:"browser-opfs-project-storage"})),this.worker.onmessage=e=>this.receive(e.data),this.worker.onerror=e=>this.rejectAll(new Error(e.message||"OPFS project worker failed.")),this.worker.onmessageerror=()=>this.rejectAll(new Error("OPFS project worker returned an invalid message."))}async readPair(e,t){const n=await this.request({operation:"read-pair",keys:[e,t]});return{primary:Xe(n?.[0]),backup:Xe(n?.[1])}}async rotate(e,t,n,s,o){await this.request({operation:"rotate",keys:[e,t,n],value:JSON.stringify(s),expected:o})}async replace(e,t){await this.request({operation:"replace",keys:[e],value:JSON.stringify(t)})}async delete(...e){await this.request({operation:"delete",keys:e})}dispose(){this.worker.terminate(),this.rejectAll(new Error("OPFS project storage was closed."))}request(e){const t=this.nextRequest++;return new Promise((n,s)=>{const o=window.setTimeout(()=>{this.pending.delete(t),s(new Error("OPFS project worker did not respond in time."))},15e3);this.pending.set(t,{resolve:n,reject:s,timeout:o}),this.worker.postMessage({id:t,...e})})}receive(e){const t=this.pending.get(e.id);t&&(this.pending.delete(e.id),window.clearTimeout(t.timeout),e.ok?t.resolve(e.values):t.reject(new Error(e.error||"OPFS project operation failed.")))}rejectAll(e){for(const t of this.pending.values())window.clearTimeout(t.timeout),t.reject(e);this.pending.clear()}}function Xe(r){return r===void 0?void 0:JSON.parse(r)}const mt=2019846480,le=6,C=6,q=3,re=0,G=1,$=2,yt=3,gt=4,bt=5,vt=0,St=1,kt=2,se=1,Et=2,Tt=4,ne=32,Ae=3,Ce=["file","directory","symlink"],Sr=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,kr=new TextEncoder,Er=new TextDecoder;function Pt(r){let e=2166136261;for(let t=0;t<r.length;t+=1)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function Rs(r,e){const t=[...r.keys()];for(const k of t)if(Sr.test(k))throw new Error("A path in the store is not well-formed UTF-16.");const n=new Map;for(let k=0;k<t.length;k+=1)n.set(t[k],k);for(const k of e.keys())n.has(k)||(n.set(k,t.length),t.push(k));const s=t.length,o=new Map,i=new Uint32Array(s);let a=0;for(let k=0;k<s;k+=1){const T=t[k];let A=!0;for(let j=0;j<T.length;j+=1)if(T.charCodeAt(j)>=128){A=!1;break}A||o.set(k,kr.encode(T)),i[k]=A?T.length:o.get(k).length,a+=i[k]}let c=0;for(const k of e.values())c+=k.size;let u=1;for(;u<s*2;)u<<=1;const d=le*4,l=Re(d+s*C*4,8),f=l+s*q*8,h=f+u*4,p=h+c*4,w=new SharedArrayBuffer(Re(p+a,8));new Uint32Array(w,0,le).set([mt,s,u,c,a,r.size]);const y=new Uint32Array(w,d,s*C),g=new Float64Array(w,l,s*q),b=new Uint32Array(w,f,u),S=new Uint32Array(w,h,c),E=new Uint8Array(w,p,a);let v=0,R=0;for(let k=0;k<s;k+=1){const T=t[k],A=k*C,j=o.get(k);if(j)E.set(j,v);else for(let O=0;O<T.length;O+=1)E[v+O]=T.charCodeAt(O);const x=i[k];y[A+re]=v,y[A+G]=x,v+=x;let F=j?0:ne;const B=r.get(T);if(B){F|=se|Ce.indexOf(B.type)<<Ae,B.pack&&(F|=Tt),y[A+yt]=B.mode;const O=k*q;g[O+vt]=B.mtimeMs,g[O+St]=B.offset,g[O+kt]=B.length}const z=e.get(T);if(z){F|=Et,y[A+gt]=R,y[A+bt]=z.size;for(const O of z){const $e=n.get(`${T}/${O}`);if($e===void 0)throw new Error(`The store's children name ${T}/${O}, which its index does not hold.`);S[R++]=$e}}y[A+$]=F;let J=Pt(T)&u-1;for(;b[J]!==0;)J=J+1&u-1;b[J]=k+1}if(R!==c)throw new Error("The shared index's children did not add up.");return w}function Re(r,e){return Math.ceil(r/e)*e}class Os{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(e){const t=new Uint32Array(e,0,le);if(t[0]!==mt)throw new Error("Not a shared store index.");const[,n,s,o,i,a]=t;this.buffer=e,this.count=n,this.entryCount=a;const c=le*4,u=Re(c+n*C*4,8),d=u+n*q*8,l=d+s*4,f=l+o*4;this.records=new Uint32Array(e,c,n*C),this.numbers=new Float64Array(e,u,n*q),this.table=new Uint32Array(e,d,s),this.childList=new Uint32Array(e,l,o),this.strings=new Uint8Array(e,f,i),this.mask=s-1}find(e){let t=Pt(e)&this.mask;for(;;){const n=this.table[t];if(n===0)return-1;if(this.pathIs(n-1,e))return n-1;t=t+1&this.mask}}entry(e){const t=e*C,n=this.records[t+$];if(!(n&se))return;const s=e*q,o={type:Ce[n>>>Ae&3],mode:this.records[t+yt],mtimeMs:this.numbers[s+vt],offset:this.numbers[s+St],length:this.numbers[s+kt]};return n&Tt&&(o.pack="packages"),o}typeAt(e){const t=this.records[e*C+$];return t&se?Ce[t>>>Ae&3]:void 0}hasEntry(e){return(this.records[e*C+$]&se)!==0}childNames(e){const t=e*C;if(!(this.records[t+$]&Et))return;const n=this.records[t+gt],s=this.records[t+G]+1,o=[];for(let i=0;i<this.records[t+bt];i+=1){const a=this.childList[n+i]*C;o.push(this.decode(this.records[a+re]+s,this.records[a+G]-s,(this.records[a+$]&ne)!==0))}return o}path(e){const t=e*C;return this.decode(this.records[t+re],this.records[t+G],(this.records[t+$]&ne)!==0)}decode(e,t,n){if(!n)return Er.decode(this.strings.slice(e,e+t));let s="";for(let o=e,i=e+t;o<i;o+=4096)s+=String.fromCharCode.apply(null,this.strings.subarray(o,Math.min(i,o+4096)));return s}pathIs(e,t){const n=e*C,s=this.records[n+re],o=this.records[n+G];if(!(this.records[n+$]&ne))return this.path(e)===t;if(o!==t.length)return!1;for(let i=0;i<o;i+=1)if(this.strings[s+i]!==t.charCodeAt(i))return!1;return!0}}const _=Symbol("deleted");function Tr(r,e){return r===e||!!r&&!!e&&r.type===e.type&&r.offset===e.offset&&r.length===e.length&&r.pack===e.pack&&r.mode===e.mode&&r.mtimeMs===e.mtimeMs&&r.capacity===e.capacity}class Ms{base;overlay=new Map;delta=0;constructor(e){this.base=e}get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===_?void 0:t;const n=this.base.find(e);return n<0?void 0:this.base.entry(n)}typeOf(e){const t=this.overlay.get(e);if(t!==void 0)return t===_?void 0:t.type;const n=this.base.find(e);return n<0?void 0:this.base.typeAt(n)}has(e){const t=this.overlay.get(e);if(t!==void 0)return t!==_;const n=this.base.find(e);return n>=0&&this.base.hasEntry(n)}set(e,t){this.has(e)||(this.delta+=1);const n=this.base.find(e);return n>=0&&Tr(this.base.entry(n),t)?this.overlay.delete(e):this.overlay.set(e,t),this}delete(e){if(!this.has(e))return!1;const t=this.base.find(e);return t>=0&&this.base.hasEntry(t)?this.overlay.set(e,_):this.overlay.delete(e),this.delta-=1,!0}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[e,t]of this.overlay)t!==_&&(yield[e,t]);for(let e=0;e<this.base.count;e+=1){if(!this.base.hasEntry(e))continue;const t=this.base.path(e);this.overlay.has(t)||(yield[t,this.base.entry(e)])}}*keys(){for(const[e]of this.entries())yield e}*values(){for(const[,e]of this.entries())yield e}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[n,s]of this.entries())e.call(t,s,n,this)}*changed(){for(const[e,t]of this.overlay)t!==_&&(yield[e,t])}*changes(){for(const[e,t]of this.overlay)yield[e,t===_?null:t]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return;const e=[];let t=0;for(const[n,s]of this.changes()){if(t+=n.length*2+128,t>8*1024*1024)return;e.push([n,s])}return e}}class _s{base;overlay=new Map;constructor(e){this.base=e}get(e){const t=this.overlay.get(e);if(t!==void 0)return t===_?void 0:t;const n=this.base.find(e),s=n<0?void 0:this.base.childNames(n);return s?new Set(s):void 0}mutable(e){const t=this.overlay.get(e);if(t!==void 0&&t!==_)return t;const n=new Set(t===_?[]:this.get(e)??[]);return this.overlay.set(e,n),n}delete(e){this.overlay.set(e,_)}}const Fs="/opt/.browser-packs",Ls="/opt/.tabnode";new TextEncoder;new TextDecoder("utf-8",{fatal:!0});const Qe="host-tree.",Bs=["/workspace","/home","/opt"],Oe=1e6,he=1024*1024*1024,Pr=4096,Je={readPair:pt,rotate:wr,replace:mr,delete:yr};let Me=Promise.resolve();const Ke=new Map;let Ye;async function xr(){if(typeof Worker>"u"||typeof navigator>"u"||!navigator.storage||!("getDirectory"in navigator.storage))return{backend:"indexeddb",storage:Je};const r=new vr;try{const{primary:e,backup:t}=Be("default"),n=await r.readPair(e,t);if(n.primary===void 0&&n.backup===void 0){const s=await pt(e,t);s.backup!==void 0&&await r.replace(t,s.backup),s.primary!==void 0&&await r.replace(e,s.primary)}return{backend:"opfs",storage:r}}catch(e){return r.dispose(),console.warn("OPFS project storage is unavailable; using IndexedDB for this page session.",e),{backend:"indexeddb",storage:Je}}}async function U(){return Ye??=xr(),Ye}async function Is(r){const{storage:e}=await U();return(await e.readPair(r,`${r}-backup`)).primary}async function js(r,e){const{storage:t}=await U();await t.replace(r,e)}async function $s(r){const{storage:e}=await U();await e.delete(r,`${r}-backup`)}async function Ns(){return(await U()).backend}function Ar(r){const e=Me.then(r,r);return Me=e.then(()=>{},()=>{}),e}function we(r){return typeof r!="string"||r.length===0||r.length>Pr||!r.startsWith("/")||r.includes("\0")||r.includes("//")?!1:r==="/"||r.slice(1).split("/").every(e=>e.length>0&&e!=="."&&e!=="..")}function ue(r){if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.files))throw new Error("Saved browser project has an invalid shape.");const e=r.files;if(e.length>Oe)throw new Error(`Saved browser project exceeds ${Oe} entries.`);const t=new Set;let n=0;for(const s of e){if(!s||typeof s!="object"||!we(s.path)||s.type!=="file"&&s.type!=="directory"||t.has(s.path))throw new Error("Saved browser project contains an invalid or duplicate entry.");if(t.add(s.path),s.mode!==void 0&&(!Number.isSafeInteger(s.mode)||s.mode<0||s.mode>4095))throw new Error("Saved browser project contains an invalid file mode.");if(s.mtimeMs!==void 0&&(!Number.isFinite(s.mtimeMs)||s.mtimeMs<0))throw new Error("Saved browser project contains an invalid modification time.");if(s.type==="directory"){if(s.content!==void 0)throw new Error("Saved browser project directory contains file data.");continue}const o=s.content,i=typeof o=="string"?ut(o):void 0;if(i===void 0)throw new Error("Saved browser project contains invalid file data.");if(n+=i,n>he)throw new Error(`Saved browser project exceeds ${he} bytes.`)}return xt(e),r}function xt(r){const e=new Map(r.map(t=>[t.path,t.type]));for(const t of r){if(t.path==="/"&&t.type!=="directory")throw new Error("Saved browser project root must be a directory.");let n=t.path;for(;n!=="/";)if(n=n.slice(0,n.lastIndexOf("/"))||"/",e.get(n)==="file")throw new Error(`Saved browser project has a file as a parent: ${n}`)}}async function Hs(r,e={}){await Me;const t=Le(e.projectId),n=Be(t),s=At(t),{storage:o}=await U(),i=await o.readPair(n.primary,n.backup);if(i.primary!==void 0)try{const c=await Ge(i.primary,ue);return s.known=!0,s.revision=xe(i.primary),c}catch(c){if(i.backup===void 0)throw c}else if(i.backup===void 0){s.known=!0,s.revision=void 0;return}const a=await Ge(i.backup,ue);return r?.("The latest browser save was invalid, so the previous verified save was restored."),await o.replace(n.primary,i.backup),s.known=!0,s.revision=xe(i.backup),a}async function Cr(r,e={}){const t=e.root??"/";if(!we(t))throw new Error("Browser project root is invalid.");const n=Le(e.projectId),s=Be(n),o=At(n),i=e.excludePaths?new Set(e.excludePaths):void 0;return Ar(async()=>{const a=ue(await Yt(r,t,{consistent:!0,...i?{excludePaths:i}:{}})),{storage:c}=await U(),u=await gr(a);await br(new TextEncoder().encode(JSON.stringify(u)).byteLength),await c.rotate(s.primary,s.backup,s.conflict,u,{known:o.known,...o.revision!==void 0?{revision:o.revision}:{}}),o.known=!0,o.revision=u.checksum})}function Le(r="default"){if(!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(r))throw new Error("Browser projectId must be 1..64 lowercase URL-safe characters.");if(r.startsWith(Qe))throw new Error(`Browser projectId may not begin ${Qe}: the origin's installed trees are named so.`);return r}function Be(r){return{primary:r,backup:`${r}-backup`,conflict:`${r}-conflict`}}function At(r){let e=Ke.get(r);return e||(e={known:!1,revision:void 0},Ke.set(r,e)),e}function Ws(r,e,t="/"){const n=ue(e).files;Rt(r,n,t,s=>ft(s.content||""))}function Ct(r){const e=r;if(!e||!Array.isArray(e.files)||!(e.pack instanceof ArrayBuffer))throw new Error("Invalid packed browser project.");if(e.files.length>Oe||e.pack.byteLength>he)throw new Error("Packed browser project exceeds its storage limits.");const t=new Set;let n=0;for(const s of e.files){if(!s||typeof s!="object"||!we(s.path)||t.has(s.path))throw new Error("Invalid or duplicate packed browser project entry.");if(s.type!=="file"&&s.type!=="directory")throw new Error("Invalid packed browser project entry type.");if(s.mode!==void 0&&(!Number.isSafeInteger(s.mode)||s.mode<0||s.mode>4095))throw new Error("Packed browser project contains an invalid file mode.");if(s.mtimeMs!==void 0&&(!Number.isFinite(s.mtimeMs)||s.mtimeMs<0))throw new Error("Packed browser project contains an invalid modification time.");if(t.add(s.path),s.type==="file"){const o=s.offset??0,i=s.length??0;if(!Number.isSafeInteger(o)||!Number.isSafeInteger(i)||o<0||i<0||o+i>e.pack.byteLength)throw new Error("A packed browser project entry points outside its buffer.");if(n+=i,n>he)throw new Error("Packed browser project expands beyond its storage limit.")}else if(s.offset!==void 0||s.length!==void 0)throw new Error("Packed browser project directory contains file data.")}return xt(e.files),e}function Ds(r,e,t="/"){const{files:n,pack:s}=Ct(e);Rt(r,n,t,o=>new Uint8Array(s,o.offset??0,o.length??0).slice())}function Rt(r,e,t,n){if(!we(t))throw new Error("Browser project restore root is invalid.");for(const i of e){if(t!=="/"&&i.path!==t&&!i.path.startsWith(`${t}/`))throw new Error(`Saved browser project entry is outside its restore root: ${i.path}`);if(i.path===t&&i.type!=="directory")throw new Error("Browser project restore root must be a directory.")}let s=t;for(;;){if(r.existsSync(s)){const i=r.lstatSync(s);if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Browser project restore has an unsafe destination: ${s}`)}if(s==="/")break;s=s.slice(0,s.lastIndexOf("/"))||"/"}const o=[...e].sort((i,a)=>Ze(i.path)-Ze(a.path)||i.path.localeCompare(a.path));r.existsSync(t)?Ot(r,t):t!=="/"&&r.mkdirSync(t,{recursive:!0});for(const i of o){if(i.path==="/")continue;if(i.type==="directory"){r.mkdirSync(i.path,{recursive:!0});continue}const a=i.path.slice(0,i.path.lastIndexOf("/"))||"/";r.mkdirSync(a,{recursive:!0}),r.writeFileSync(i.path,n(i))}for(const i of o)i.mode!==void 0&&r.chmodSync?.(i.path,i.mode),i.mtimeMs!==void 0&&r.utimesSync?.(i.path,new Date(i.mtimeMs),new Date(i.mtimeMs))}function Ot(r,e="/",t=new Set){for(const n of r.readdirSync(e)){const s=e==="/"?`/${n}`:`${e}/${n}`;if(t.has(s))continue;const o=r.lstatSync(s);o.isDirectory()&&!o.isSymbolicLink()?(Ot(r,s,t),r.readdirSync(s).length===0&&r.rmdirSync(s)):r.unlinkSync(s)}}function qs(r,e,t={}){let n,s=!1,o,i=!1,a;const c=async()=>{if(o)return o;const h=(async()=>{for(;s;){s=!1;try{await Cr(r,t)}catch(p){if(s=!0,p instanceof Ee){await new Promise(w=>globalThis.setTimeout(w,25));continue}throw e(p),p}}})();o=h;try{await h}finally{o===h&&(o=void 0),!s&&n!==void 0&&(window.clearTimeout(n),n=void 0)}},u=async()=>{n!==void 0&&window.clearTimeout(n),n=void 0,await c(),s&&await c()},d=()=>{i||(s=!0,n!==void 0&&window.clearTimeout(n),n=window.setTimeout(()=>{n=void 0,c().catch(()=>{})},250))},l=h=>{const p=t.root??"/",w=[...t.excludePaths??[]].some(m=>h===m||h.startsWith(`${m==="/"?"":m}/`));(p==="/"||h===p||h.startsWith(`${p}/`)||p.startsWith(`${h==="/"?"":h}/`))&&!w&&d()};r.on("change",l),r.on("delete",l);const f=Q.for(r)?.onChange(l);return{schedule:d,flush:u,dispose(){return a||(i=!0,r.off("change",l),r.off("delete",l),f?.(),a=u(),a)}}}function Ze(r){let e=1;for(let t=0;t<r.length;t+=1)r.charCodeAt(t)===47&&(e+=1);return e}async function Rr(r,e){if(!/^sha256-[A-Za-z0-9+/]{43}=$/u.test(e))throw new Error("Invalid artifact integrity metadata.");const t=new Uint8Array(await crypto.subtle.digest("SHA-256",r));let n="";for(const o of t)n+=String.fromCharCode(o);const s=`sha256-${btoa(n)}`;if(s!==e)throw new Error(`Artifact integrity mismatch: expected ${e}, received ${s}.`)}function Or(r){return typeof r.readFileSync=="function"}class Mt{filesystem;root;onError;worker;pending=new Map;originals;nextRequest=1;writeTail=Promise.resolve();mutationQueue=[];mutationFlushScheduled=!1;active=!1;disposed=!1;disposal;failure;handlePageHide=()=>{this.disposed||this.closeTransport(new Error("OPFS filesystem page was closed."))};handleVisibilityChange=()=>{if(document.visibilityState==="hidden"){for(const e of this.pending.values())this.clearPendingTimeout(e);return}for(const[e,t]of this.pending)this.armPendingTimeout(e,t)};constructor(e,t,n){this.filesystem=e,this.root=t,this.onError=n,this.worker=dt(new Worker(new URL("/assets/browser-opfs-filesystem-worker-k2CPzPBU.js",import.meta.url),{type:"module",name:"browser-opfs-live-filesystem"})),this.worker.onmessage=s=>this.receive(s.data),this.worker.onerror=s=>this.fail(new Error(s.message||"OPFS filesystem worker failed.")),this.worker.onmessageerror=()=>this.fail(new Error("OPFS filesystem worker returned an invalid message.")),document.addEventListener("visibilitychange",this.handleVisibilityChange),window.addEventListener("pagehide",this.handlePageHide),this.originals={writeFileSync:e.writeFileSync.bind(e),mkdirSync:e.mkdirSync.bind(e),unlinkSync:e.unlinkSync.bind(e),rmdirSync:e.rmdirSync.bind(e),renameSync:e.renameSync.bind(e),chmodSync:e.chmodSync.bind(e),utimesSync:e.utimesSync.bind(e)},this.installMutationHooks()}static supported(){const e=typeof FileSystemFileHandle>"u"?void 0:FileSystemFileHandle.prototype;return typeof Worker<"u"&&typeof navigator<"u"&&!!navigator.storage&&"getDirectory"in navigator.storage&&typeof e?.move=="function"}static async open(e,t,n={}){if(!this.supported())throw new Error("Direct OPFS filesystem storage is unavailable in this browser.");const s=I(n.root??"/");if(s!=="/workspace")throw new Error("The direct OPFS filesystem currently requires /workspace as its root.");const o=Le(n.projectId),i=new Mt(e,s,t);try{const a=await i.request({operation:"initialize",projectId:o});return{store:i,...a.initialized&&a.snapshot?{packed:Ct(a.snapshot)}:{}}}catch(a){throw i.closeTransport(a),a}}activate(){this.throwIfFailed(),this.active=!0}async replaceFromMemory(){this.throwIfFailed();const e=et(this.filesystem,this.root);this.enqueueReplacement(e),await this.writeTail}schedule(){}async flush(){this.throwIfFailed(),this.flushMutationQueue(),await this.writeTail,this.throwIfFailed(),await this.request({operation:"flush"})}dispose(){return this.disposal??=this.disposeStore(),this.disposal}async disposeStore(){if(this.disposed){if(this.failure)throw this.failure;return}this.active=!1,this.uninstallMutationHooks();try{await this.flush()}finally{this.closeTransport(new Error("OPFS filesystem storage was closed."))}}closeTransport(e){this.disposed=!0,this.active=!1,this.uninstallMutationHooks(),document.removeEventListener("visibilitychange",this.handleVisibilityChange),window.removeEventListener("pagehide",this.handlePageHide),this.worker.onmessage=null,this.worker.onerror=null,this.worker.onmessageerror=null,this.worker.terminate(),this.mutationQueue.length=0,this.rejectAll(e)}installMutationHooks(){this.filesystem.writeFileSync=((t,n)=>{this.originals.writeFileSync(t,n);const s=I(t);this.active&&W(this.root,s)&&this.enqueue({operation:"write",path:s,content:Uint8Array.from(this.filesystem.readFileSync(s)),...X(this.filesystem,s)})}),this.filesystem.mkdirSync=((t,n)=>{this.originals.mkdirSync(t,n);const s=I(t);this.active&&W(this.root,s)&&this.enqueue({operation:"mkdir",path:s,...X(this.filesystem,s)})}),this.filesystem.unlinkSync=(t=>{this.originals.unlinkSync(t),this.persistRemoval(I(t),!1)}),this.filesystem.rmdirSync=(t=>{this.originals.rmdirSync(t),this.persistRemoval(I(t),!0)}),this.filesystem.renameSync=((t,n)=>{const s=I(t),o=I(n);if(this.originals.renameSync(t,n),!this.active)return;const i=W(this.root,s),a=W(this.root,o);i&&a?this.enqueue({operation:"rename",path:s,destination:o}):(i||a)&&this.enqueueReplacement(et(this.filesystem,this.root))});const e=this.filesystem;e.chmodSync=(t,n)=>{this.originals.chmodSync(t,n),this.persistMetadata(I(t))},e.utimesSync=(t,n,s)=>{this.originals.utimesSync(t,n,s),this.persistMetadata(I(t))}}uninstallMutationHooks(){this.filesystem.writeFileSync=this.originals.writeFileSync,this.filesystem.mkdirSync=this.originals.mkdirSync,this.filesystem.unlinkSync=this.originals.unlinkSync,this.filesystem.rmdirSync=this.originals.rmdirSync,this.filesystem.renameSync=this.originals.renameSync,this.filesystem.chmodSync=this.originals.chmodSync,this.filesystem.utimesSync=this.originals.utimesSync}persistMetadata(e){!this.active||!W(this.root,e)||this.enqueue({operation:"metadata",path:e,...X(this.filesystem,e)})}persistRemoval(e,t){if(!(!this.active||!W(this.root,e))){if(e===this.root){this.enqueueReplacement({files:[],pack:new ArrayBuffer(0)});return}this.enqueue({operation:"remove",path:e,recursive:t})}}enqueue(e){this.failure||this.disposed||(this.mutationQueue.push(e),!this.mutationFlushScheduled&&(this.mutationFlushScheduled=!0,queueMicrotask(()=>this.flushMutationQueue())))}flushMutationQueue(){for(this.mutationFlushScheduled=!1;this.mutationQueue.length>0;){const e=this.mutationQueue.splice(0,128),t=this.writeTail.then(async()=>{this.throwIfFailed(),await this.request({operation:"batch",mutations:e})});this.writeTail=t,t.catch(n=>this.fail(n))}}enqueueReplacement(e){if(this.failure||this.disposed)return;this.flushMutationQueue();const t=this.writeTail.then(async()=>{this.throwIfFailed(),await this.request({operation:"replace",snapshot:e},[e.pack])});this.writeTail=t,t.catch(n=>this.fail(n))}request(e,t=[]){if(this.disposed)return Promise.reject(new Error("OPFS filesystem storage is closed."));const n=this.nextRequest++;return new Promise((s,o)=>{const i={operation:e.operation==="batch"?`batch of ${e.mutations?.length??0}`:e.operation,startedAt:Date.now(),resolve:s,reject:o,timeout:void 0,timeoutMilliseconds:e.operation==="initialize"||e.operation==="replace"||e.operation==="batch"?3e5:3e4};this.pending.set(n,i);try{this.armPendingTimeout(n,i),this.worker.postMessage({id:n,...e},t)}catch(a){this.fail(a)}})}receive(e){const t=this.pending.get(e.id);if(t)if(this.pending.delete(e.id),this.clearPendingTimeout(t),e.ok)t.resolve(e);else{const n=new Error(e.error||"OPFS filesystem operation failed.");e.errorStack&&(n.stack=e.errorStack),t.reject(n)}}armPendingTimeout(e,t){this.clearPendingTimeout(t),document.visibilityState!=="hidden"&&(t.timeout=window.setTimeout(()=>{this.pending.get(e)===t&&(t.timeout=void 0,this.fail(new Error(`OPFS filesystem worker did not answer ${t.operation} within ${Math.round((Date.now()-t.startedAt)/1e3)} s while the page was active.`)))},t.timeoutMilliseconds))}clearPendingTimeout(e){e.timeout!==void 0&&(window.clearTimeout(e.timeout),e.timeout=void 0)}fail(e){if(!this.failure){this.failure=e,this.closeTransport(e);try{this.onError(e)}catch(t){console.error("OPFS filesystem error observer failed.",t)}}}rejectAll(e){for(const t of this.pending.values())this.clearPendingTimeout(t),t.reject(e);this.pending.clear()}throwIfFailed(){if(this.failure)throw this.failure;if(this.disposed)throw new Error("OPFS filesystem storage is closed.")}}function et(r,e){const t=[];let n=0;const s=a=>{t.push({path:a,type:"directory",...X(r,a)});for(const c of r.readdirSync(a)){const u=a==="/"?`/${c}`:`${a}/${c}`,d=r.statSync(u);if(d.isDirectory())s(u);else if(d.isFile()){const l=r.readFileSync(u);t.push({path:u,type:"file",...X(r,u),offset:n,length:l.byteLength,bytes:l}),n+=l.byteLength}}};r.existsSync(e)&&s(e);const o=new Uint8Array(n),i=[];for(const a of t){a.bytes&&o.set(a.bytes,a.offset??0);const{bytes:c,...u}=a;i.push(u)}return{files:i,pack:o.buffer}}function I(r){if(r.startsWith("/")&&(r.length===1||!r.endsWith("/"))&&!r.includes("//")&&!r.includes("/./")&&!r.includes("/../")&&!r.endsWith("/.")&&!r.endsWith("/.."))return r;const e=[];for(const t of`/${r}`.split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}function W(r,e){return r==="/"||e===r||e.startsWith(`${r}/`)}function X(r,e){const t=r.statSync(e);return{mode:t.mode,mtimeMs:t.mtimeMs}}function Us(r){return"bytes"in r?r.bytes:ft(r.base64)}function zs(r){return"bytes"in r?H(r.bytes):r.base64}function Mr(r){return"bytes"in r?r.bytes.byteLength:ut(r.base64)}const _r=3e4;class Vs{endpoints=new Map;register(e,t){if(_t(e),this.endpoints.has(e))throw new Error("A virtual WebSocket endpoint is already registered on that port.");return this.endpoints.set(e,t),()=>{this.endpoints.get(e)===t&&this.endpoints.delete(e)}}endpoint(e){return this.endpoints.get(e)}}const tt=32*1024*1024;class Fr{registeredPort;registry;connector;sockets=new Map;closingAll=!1;constructor(e,t,n){this.registeredPort=e,this.registry=t,this.connector=n}open(e,t,n,s,o,i){if(this.closingAll)throw new Error("Virtual WebSockets are closing.");if(!Number.isSafeInteger(e)||e<1)throw new Error("Invalid virtual WebSocket identifier.");const a=this.sockets.get(e);if(a&&a.state===2&&this.terminate(e,a,1001,""),this.sockets.has(e))throw new Error("Invalid virtual WebSocket identifier.");if(_t(t),!this.registeredPort(t))throw new Error("No virtual server is listening on that WebSocket port.");if(!Lr(n))throw new Error("Invalid virtual WebSocket request target.");if(!Array.isArray(s)||s.length>16||new Set(s).size!==s.length||s.some(l=>typeof l!="string"||!Br(l)))throw new Error("Invalid virtual WebSocket protocol list.");const c={port:t,state:0,handlers:o,timeout:setTimeout(()=>{this.sockets.get(e)!==c||c.state!==0||this.terminate(e,c,1006,"","Virtual WebSocket connection timed out.")},_r)};this.sockets.set(e,c);const u=this.registry?.endpoint(t),d=u?l=>u.open(n,[...s],l):this.connector?l=>this.connector.open(t,n,[...s],l,jr(i?.host)?{host:i.host}:void 0):void 0;if(!d)throw clearTimeout(c.timeout),this.sockets.delete(e),new Error("The virtual WebSocket port has no engine connector.");try{const l=d({open:f=>{if(!(this.sockets.get(e)!==c||c.state!==0)){if(typeof f!="string"||f!==""&&!s.includes(f)){this.terminate(e,c,1006,"","The virtual server selected an unrequested WebSocket protocol.");return}clearTimeout(c.timeout),c.timeout=void 0,c.state=1,this.notify(()=>o.open(f))}},message:f=>{if(!(this.sockets.get(e)!==c||c.state!==1)){try{rt(f)}catch(h){this.terminate(e,c,1009,"Invalid server frame",h instanceof Error?h.message:String(h));return}this.notify(()=>o.message(f))}},close:(f,h,p)=>{this.retire(e,c)&&this.notify(()=>o.close(f,h,p))},error:f=>{this.sockets.get(e)===c&&this.terminate(e,c,1006,"",f)}});c.connection=l,this.sockets.get(e)!==c?this.abortConnection(c):c.closing&&this.requestClose(e,c)}catch(l){throw this.retire(e,c),this.abortConnection(c),l}}send(e,t){const n=this.sockets.get(e);if(!n||n.state!==1||!n.connection)throw new Error("Virtual WebSocket is not open.");rt(t);try{n.connection.send(t)}catch(s){throw this.terminate(e,n,1006,"",s instanceof Error?s.message:String(s)),s}}close(e,t=1e3,n=""){const s=this.sockets.get(e);s&&(Ir(t,n),!(s.state>=2)&&(s.state=2,s.closing={code:t,reason:n},clearTimeout(s.timeout),s.timeout=void 0,s.closeTimer=setTimeout(()=>{this.sockets.get(e)===s&&this.terminate(e,s,1006,"")},100),this.requestClose(e,s)))}abort(e,t=1006,n=""){const s=this.sockets.get(e);s&&this.terminate(e,s,t,n)}closeAll(){if(!this.closingAll){this.closingAll=!0;try{for(const[e,t]of[...this.sockets])this.terminate(e,t,1001,"Connection owner closed")}finally{this.closingAll=!1}}}closePort(e){for(const[t,n]of[...this.sockets])n.port===e&&this.terminate(t,n,1001,"Virtual server stopped")}requestClose(e,t){if(!(!t.connection||!t.closing))try{t.connection.close(t.closing.code,t.closing.reason)}catch(n){this.terminate(e,t,1006,"",n instanceof Error?n.message:String(n))}}retire(e,t){return this.sockets.get(e)!==t?!1:(this.sockets.delete(e),t.state=3,clearTimeout(t.timeout),clearTimeout(t.closeTimer),t.timeout=void 0,t.closeTimer=void 0,!0)}terminate(e,t,n,s,o){this.retire(e,t)&&(this.abortConnection(t),o!==void 0&&this.notify(()=>t.handlers.error(o)),this.notify(()=>t.handlers.close(n,s,!1)))}abortConnection(e){const t=e.connection;if(e.connection=void 0,!!t)try{t.abort?t.abort():t.close(1e3,"Connection cancelled")}catch(n){console.error("Virtual WebSocket transport cleanup failed.",n)}}notify(e){try{e()}catch(t){console.error("Virtual WebSocket observer failed.",t)}}}function _t(r){if(!Number.isSafeInteger(r)||r<1||r>65535)throw new Error("Invalid virtual WebSocket port.")}function Lr(r){if(typeof r!="string"||!r.startsWith("/")||r.startsWith("//")||r.length>16384||/[\\\u0000-\u001f\u007f]/u.test(r))return!1;try{return new URL(r,"https://virtual.invalid").origin==="https://virtual.invalid"}catch{return!1}}function Br(r){return r.length>0&&r.length<=128&&/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/u.test(r)}function rt(r){if(!r||typeof r!="object"||r.kind!=="text"&&r.kind!=="binary"||(r.kind==="text"?typeof r.text!="string":!("bytes"in r?r.bytes instanceof Uint8Array:typeof r.base64=="string")))throw new Error("Invalid virtual WebSocket frame.");if(r.kind==="binary"&&!("bytes"in r)&&r.base64.length>Math.ceil(tt/3)*4)throw new Error("Virtual WebSocket frame exceeds 32 MiB.");const e=r.kind==="text"?new TextEncoder().encode(r.text).byteLength:Mr(r);if(e===void 0)throw new Error("Invalid virtual WebSocket binary frame.");if(e>tt)throw new Error("Virtual WebSocket frame exceeds 32 MiB.")}function Ir(r,e){if(!Number.isSafeInteger(r)||r!==1e3&&(r<3e3||r>4999))throw new Error("Invalid virtual WebSocket close code.");if(typeof e!="string"||new TextEncoder().encode(e).byteLength>123)throw new Error("Virtual WebSocket close reason is invalid or too long.")}function jr(r){return typeof r=="string"&&r.length<=255&&/^(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::[0-9]{1,5})?$/iu.test(r)}const $r=1,st=1024*1024;class Nr{revision;rules;constructor(e=[],t=[]){const n=new Map;for(const o of e){Ft(o);for(const i of o.rules){const a=oe(i);if(n.has(a.id))throw new Error(`Duplicate HTTP transport rule: ${a.id}`);n.set(a.id,a)}}for(const o of t){if(!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(o.revision))throw new Error("HTTP transport overrides require a configuration revision.");if(+(o.add!==void 0)+ +(o.replace!==void 0)+ +(o.remove!==void 0)!==1)throw new Error("An HTTP transport override must add, replace or remove exactly one rule.");if(o.add){if(o.rule)throw new Error("An HTTP transport addition cannot also include a replacement.");const c=oe(o.add);if(n.has(c.id))throw new Error(`Duplicate HTTP transport rule: ${c.id}`);n.set(c.id,c);continue}const a=o.replace??o.remove;if(!n.has(a))throw new Error(`HTTP transport override target does not exist: ${a}`);if(n.delete(a),o.replace!==void 0){if(!o.rule)throw new Error(`HTTP transport replacement is missing its rule: ${a}`);const c=oe(o.rule);if(c.id!==a)throw new Error(`HTTP transport replacement must retain rule id: ${a}`);n.set(a,c)}else if(o.rule)throw new Error("An HTTP transport removal cannot include a replacement rule.")}const s=[...n.values()];Lt(s),this.rules=Object.freeze(s.map(o=>Object.freeze(o))),this.revision=(e.length===0?"builtin-empty-v1":e.map(o=>o.revision).join("+"))+t.map(o=>`+override.${o.revision}`).join("")}resolve(e){const t=Ie(e.method),n=je(e.headerNames),s=e.credentialMode??"omit",o=e.profile??"browser-compatible",i=this.rules.filter(u=>Wr(u,e.program,e.url,t,n,s,o));if(i.length===0){if(s!=="omit"||o!=="browser-compatible")throw zr("TRANSPORT_REQUIRED",`No HTTP transport rule satisfies ${o} with ${s} credentials.`);return{transport:"direct",profile:o,credentialMode:s,ruleId:"builtin.direct-browser-compatible",policyRevision:this.revision}}if(new Set(i.map(u=>`${u.transport}\0${u.profile}\0${u.credentialMode}`)).size!==1)throw new Error(`Conflicting HTTP transport rules matched: ${i.map(u=>u.id).join(", ")}`);const c=Ur(i);return{transport:c.transport,profile:c.profile,credentialMode:c.credentialMode,ruleId:c.id,policyRevision:this.revision}}}function Hr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("HTTP transport policy must be an object.");const e=r;return Ft(e),e}async function Gs(r,e,t=globalThis.fetch.bind(globalThis)){const n=new Map;for(const o of r){const i=o.network.httpTransportPolicy;if(!i)continue;const a=n.get(i.url);if(a&&a!==i.integrity)throw new Error(`HTTP transport policy URL has conflicting integrity pins: ${i.url}`);n.set(i.url,i.integrity)}const s=[];for(const[o,i]of n){const a=e(o),c=await t(a,{cache:"no-store",credentials:"omit",redirect:"error"});if(!c.ok||!c.body)throw new Error(`HTTP transport policy ${a} answered ${c.status}.`);const u=Number(c.headers.get("content-length"));if(Number.isFinite(u)&&u>st)throw new Error(`HTTP transport policy ${a} exceeds its byte limit.`);const d=c.body.getReader(),l=[];let f=0;try{for(;;){const m=await d.read();if(m.done)break;if(m.value.byteLength>st-f)throw new Error(`HTTP transport policy ${a} exceeds its byte limit.`);l.push(m.value),f+=m.value.byteLength}}catch(m){throw await d.cancel(m).catch(()=>{}),m}finally{d.releaseLock()}const h=new Uint8Array(f);let p=0;for(const m of l)h.set(m,p),p+=m.byteLength;await Rr(h.buffer,i);let w;try{w=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(h))}catch{throw new Error(`HTTP transport policy ${a} is not valid UTF-8 JSON.`)}s.push(Hr(w))}return s}function Ft(r){if(Object.keys(r).sort().join(",")!=="evidence,revision,rules,schemaVersion")throw new Error("HTTP transport policy has unknown or missing fields.");if(r.schemaVersion!==$r)throw new Error("Unsupported HTTP transport policy version.");if(!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(r.revision))throw new Error("Invalid HTTP transport policy revision.");if(!Array.isArray(r.rules)||r.rules.length>256)throw new Error("HTTP transport policy rules must be a bounded array.");if(!Array.isArray(r.evidence)||r.evidence.length>512)throw new Error("HTTP transport policy evidence must be a bounded array.");const t=r.rules.map(oe),n=new Set(t.map(s=>s.id));if(n.size!==t.length)throw new Error("HTTP transport policy rule IDs must be unique.");Lt(t);for(const s of r.evidence){if(!s||typeof s!="object"||!n.has(s.rule)||typeof s.observedAt!="string"||!/^\d{4}-\d{2}-\d{2}/u.test(s.observedAt)||typeof s.workflow!="string"||typeof s.browser!="string"||typeof s.observation!="string"||!s.request||typeof s.request.method!="string"||typeof s.request.path!="string"||!Array.isArray(s.request.headerNames))throw new Error("Invalid HTTP transport policy evidence.");Ie(s.request.method),je(s.request.headerNames)}for(const s of t)if(!r.evidence.some(o=>o.rule===s.id))throw new Error(`HTTP transport rule has no evidence: ${s.id}`)}function oe(r){if(Object.keys(r).some(i=>!["id","program","origin","pathPrefix","methods","requestHeaderNames","credentialMode","profile","transport"].includes(i)))throw new Error("HTTP transport rule has unknown fields.");if(!/^[A-Za-z0-9._-]{1,128}$/u.test(r.id)||!/^[A-Za-z0-9._+-]{1,64}$/u.test(r.program))throw new Error("Invalid HTTP transport rule identity.");const t=new URL(r.origin);if(t.protocol!=="https:"||t.origin!==r.origin||t.username||t.password)throw new Error(`HTTP transport rule requires an exact HTTPS origin: ${r.id}`);const n=r.pathPrefix??"/";if(!n.startsWith("/")||n.includes("?")||n.includes("#")||n.includes("\\")||n.includes(".."))throw new Error(`Invalid HTTP transport path prefix: ${r.id}`);const s=Object.freeze([...r.methods??[]].map(Ie).sort());if(new Set(s).size!==s.length)throw new Error(`Duplicate HTTP transport method: ${r.id}`);const o=r.requestHeaderNames===void 0?void 0:Object.freeze(je(r.requestHeaderNames));if(r.credentialMode!=="omit"&&r.credentialMode!=="explicit-guest")throw new Error(`Invalid HTTP credential mode: ${r.id}`);if(r.profile!=="browser-compatible"&&r.profile!=="server-http")throw new Error(`Invalid HTTP transport profile: ${r.id}`);if(r.transport!=="direct"&&r.transport!=="relay")throw new Error(`Invalid HTTP transport: ${r.id}`);if(r.transport==="direct"&&(r.profile!=="browser-compatible"||r.credentialMode!=="omit"))throw new Error(`Direct transport cannot satisfy server HTTP or guest credentials: ${r.id}`);return{...r,origin:t.origin,pathPrefix:n,methods:s,requestHeaderNames:o}}function Ie(r){const e=r.toUpperCase();if(!/^[A-Z!#$%&'*+.^_`|~-]{1,32}$/u.test(e)||e==="CONNECT"||e==="TRACE")throw new Error(`Invalid HTTP method: ${r}`);return e}function je(r){if(r.length>128)throw new Error("Too many HTTP header names.");const e=r.map(t=>t.toLowerCase()).sort();if(e.some(t=>!/^[!#$%&'*+.^_`|~0-9a-z-]{1,128}$/u.test(t))||new Set(e).size!==e.length)throw new Error("Invalid or duplicate HTTP header name.");return e}function Wr(r,e,t,n,s,o,i){return r.program!==e||r.origin!==t.origin||r.credentialMode!==o||r.profile!==i||!_e(r.pathPrefix,t.pathname)||r.methods.length>0&&!r.methods.includes(n)?!1:r.requestHeaderNames===void 0||s.every(a=>r.requestHeaderNames.includes(a))}function _e(r,e){if(r==="/")return!0;const t=r.endsWith("/")?r.slice(0,-1):r;return e===t||e.startsWith(`${t}/`)}function Lt(r){for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){const n=r[e],s=r[t];if(!(n.program!==s.program||n.origin!==s.origin||n.profile!==s.profile||n.credentialMode!==s.credentialMode||!Dr(n.pathPrefix,s.pathPrefix)||!qr(n.methods,s.methods))&&n.transport!==s.transport)throw new Error(`Conflicting HTTP transport rules overlap: ${n.id}, ${s.id}`)}}function Dr(r,e){return _e(r,e)||_e(e,r)}function qr(r,e){return r.length===0||e.length===0||r.some(t=>e.includes(t))}function Ur(r){return[...r].sort((e,t)=>t.pathPrefix.length-e.pathPrefix.length||+(t.methods.length>0)-+(e.methods.length>0)||+(t.requestHeaderNames!==void 0)-+(e.requestHeaderNames!==void 0)||e.id.localeCompare(t.id))[0]}function zr(r,e){return Object.assign(new Error(e),{code:r})}const me=Object.freeze({maxConcurrentProcesses:64,maxProcessOutputBytes:16*1024*1024,maxProcessRuntimeMs:0,maxVirtualPorts:64,maxFilesystemEntries:1e6,maxFilesystemBytes:1024*1024*1024,maxVirtualRequests:32,maxVirtualWebSockets:32,maxVirtualRequestBytes:16*1024*1024,maxVirtualResponseBytes:32*1024*1024,maxPreviewCommands:16,maxPreviewObservations:1e3,maxEgressConnections:16,maxEgressBytes:64*1024*1024});class Xs{limits;grants=new Map;httpPolicy;egressListeners=new Set;egressRevision=1;world;constructor(e={}){this.world=e.world,this.limits=Object.freeze(Vr({...me,...e.limits})),this.httpPolicy=new Nr(e.httpTransportPolicies,e.httpTransportOverrides);for(const t of e.egress??[])this.grantEgress(t)}setWorldAuthority(e){if(!e.id||typeof e.allowsEgress!="function")throw new Error("World network authority requires its identity and authorizer.");this.world=e,this.changed()}assertWorldEgress(e,t){this.world&&this.assertEgress(e,t,"https")}grantEgress(e){const t=Gr(e),n=it(t);return this.grants.set(n,t),this.changed(),()=>{this.grants.get(n)===t&&(this.grants.delete(n),this.changed())}}allowsEgress(e,t,n){let s;try{s=t instanceof URL?t:new URL(t)}catch{return!1}if(s.username||s.password||s.protocol!=="https:"&&s.protocol!=="tls:")return!1;const o=n??(s.protocol==="https:"?"https":"tls"),i=s.port?Number(s.port):443;return this.hasGrant(e,s.hostname,o,i)}assertEgress(e,t,n){if(!this.allowsEgress(e,t,n)){const s=t instanceof URL?t.hostname:Xr(t);throw new Error(`${e} may not reach ${s}: the tab's network is closed unless granted, by the World the tab is attached to or the page that embeds it. Grant ${e} egress to ${s} there to allow it.`)}}resolveHttpTransport(e){return this.assertEgress(e.program,e.url,"https"),this.httpPolicy.resolve(e)}onEgressChange(e){return this.egressListeners.add(e),()=>this.egressListeners.delete(e)}currentEgressRevision(){return this.egressRevision}changed(){this.egressRevision+=1;for(const e of[...this.egressListeners])e()}programNetwork(e,t){return{allowedHosts:t.filter(s=>this.hasGrant(e,s,"tls",443)),maxConnections:this.limits.maxEgressConnections,maxBytes:this.limits.maxEgressBytes}}profile(){return Object.freeze({version:1,...this.world?{world:this.world.id}:{},limits:this.limits,egress:Object.freeze([...this.grants.values()].map(e=>Object.freeze({...e,ports:Object.freeze([...e.ports])})))})}hasGrant(e,t,n,s){return!Bt(e)||!It(t)||!jt(s)?!1:this.world?this.world.allowsEgress(new URL(`https://${t}:${s}`)):this.grants.has(it({program:e,hostname:t.toLowerCase(),protocol:n,ports:[s]}))||[...this.grants.values()].some(o=>o.program===e&&o.hostname===t.toLowerCase()&&o.protocol===n&&o.ports.includes(s))}}const nt=new WeakMap;function Qs(r,e){const t=nt.get(r);if(t){if(t.maxFilesystemBytes!==e.maxFilesystemBytes||t.maxFilesystemEntries!==e.maxFilesystemEntries)throw new Error("Browser filesystem was already initialized with different quotas.");return}const n=Or(r)?e:{...e,maxFilesystemBytes:Number.POSITIVE_INFINITY};let s=Se(r);at(s,n);let o=!1,i=0;const a=()=>{i===0&&(o=!0)};r.on("change",a),r.on("delete",a),Q.for(r)?.onChange(a);const c=()=>{o&&(s=Se(r),o=!1)},u=g=>{i+=1;try{g()}catch(b){throw o=!0,b}finally{i-=1}},d=r.writeFileSync.bind(r),l=r.mkdirSync.bind(r),f=r.unlinkSync.bind(r),h=r.rmdirSync.bind(r),p=r.renameSync.bind(r),w=r.importTree?.bind(r);let m=!1;const y=()=>{if(m)throw new Error("Wait for the workspace import before editing files.");c()};r.writeFileSync=((g,b)=>{y();const S=r.existsSync(g),E=S&&r.statSync(g).isFile()?r.statSync(g).size:0,v=typeof b=="string"?new TextEncoder().encode(b).byteLength:b.byteLength;if(!S&&s.entries+1>n.maxFilesystemEntries||s.bytes-E+v>n.maxFilesystemBytes)throw new DOMException("Browser filesystem quota exceeded.","QuotaExceededError");u(()=>d(g,b)),s={entries:s.entries+(S?0:1),bytes:s.bytes-E+v}}),r.mkdirSync=((g,b)=>{y();const S=Qr(r,g,b?.recursive===!0);if(s.entries+S>n.maxFilesystemEntries)throw new DOMException("Browser filesystem entry quota exceeded.","QuotaExceededError");u(()=>l(g,b)),s={...s,entries:s.entries+S}}),r.unlinkSync=(g=>{y();const b=r.existsSync(g)&&r.statSync(g).isFile()?r.statSync(g).size:0;u(()=>f(g)),s={entries:Math.max(0,s.entries-1),bytes:Math.max(0,s.bytes-b)}}),r.rmdirSync=(g=>{y(),u(()=>h(g)),s={...s,entries:Math.max(0,s.entries-1)}}),r.renameSync=((g,b)=>{if(y(),Y(g)===Y(b)){u(()=>p(g,b));return}const S=r.existsSync(b)?$t(r,b):{entries:0,bytes:0};u(()=>p(g,b)),s={entries:Math.max(0,s.entries-S.entries),bytes:Math.max(0,s.bytes-S.bytes)}}),w&&(r.importTree=async g=>{y();const b=structuredClone(g);if(!b||typeof b.root!="string"||!b.root.startsWith("/")||Y(b.root)!==b.root||!Array.isArray(b.entries))throw new TypeError("Invalid browser filesystem import.");const S=new Map(r.toSnapshot().files.map(v=>[v.path,v.type==="file"?v.size??r.statSync(v.path).size:0]));if(b.replace)for(const v of S.keys())(b.root==="/"||v===b.root||v.startsWith(`${b.root}/`))&&S.delete(v);const E=new Set;for(const v of b.entries){if(!v||typeof v.path!="string"||!v.path.startsWith("/")||Y(v.path)!==v.path||E.has(v.path)||b.root!=="/"&&v.path!==b.root&&!v.path.startsWith(`${b.root}/`)||v.type!=="file"&&v.type!=="directory"||v.type==="file"&&!(v.bytes instanceof Uint8Array))throw new TypeError("Invalid browser filesystem import entry.");E.add(v.path),S.set(v.path,v.type==="file"?v.bytes.byteLength:0)}at({entries:S.size,bytes:[...S.values()].reduce((v,R)=>v+R,0)},n),m=!0;try{return await w(b)}finally{m=!1,s=Se(r),o=!1}}),nt.set(r,e)}function Y(r){const e=[];for(const t of r.split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}const ot=new WeakMap;function Js(r,e){const t=ot.get(r);if(t!==void 0){if(t!==e)throw new Error("Browser port table was already initialized with a different quota.");return}const n=r.registerServer.bind(r);r.registerServer=(s,o,i)=>{const a=r.getServerPorts();if(!a.includes(o)&&a.length>=e)throw new Error(`Browser virtual-port limit (${e}) exceeded.`);n(s,o,i)},ot.set(r,e)}function Vr(r){const e=(t,n,s)=>{const o=r[t];if(!Number.isSafeInteger(o)||o<n||o>s)throw new Error(`Browser runtime ${t} must be an integer from ${n} through ${s}.`)};return e("maxConcurrentProcesses",1,1024),e("maxProcessOutputBytes",1024,1024*1024*1024),e("maxProcessRuntimeMs",0,10080*60*1e3),e("maxVirtualPorts",1,1024),e("maxFilesystemEntries",1,1e6),e("maxFilesystemBytes",1024,2*1024*1024*1024),e("maxVirtualRequests",1,1024),e("maxVirtualWebSockets",1,1024),e("maxVirtualRequestBytes",1024,1024*1024*1024),e("maxVirtualResponseBytes",1024,1024*1024*1024),e("maxPreviewCommands",1,1024),e("maxPreviewObservations",1,1e5),e("maxEgressConnections",1,1024),e("maxEgressBytes",1024,1024*1024*1024),r}function Gr(r){if(!Bt(r.program)||!It(r.hostname)||r.protocol!=="https"&&r.protocol!=="tls")throw new Error("Browser egress grant is invalid.");const e=[...new Set(r.ports??[443])].sort((t,n)=>t-n);if(e.length===0||e.length>32||e.some(t=>!jt(t)))throw new Error("Browser egress grant ports are invalid.");return Object.freeze({program:r.program,hostname:r.hostname.toLowerCase(),protocol:r.protocol,ports:Object.freeze(e)})}function it(r){return`${r.program}\0${r.protocol}\0${r.hostname}\0${r.ports.join(",")}`}function Xr(r){try{return new URL(r).hostname}catch{return"an invalid target"}}function Bt(r){return/^[A-Za-z0-9._+-]{1,64}$/u.test(r)}function It(r){return r.length>0&&r.length<=253&&r===r.toLowerCase()&&r.split(".").every(e=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(e))}function jt(r){return Number.isSafeInteger(r)&&r>=1&&r<=65535}function Se(r){const e=r.usage?.();if(e)return e;const t=r.toSnapshot().files;let n=0;for(const s of t)s.type==="file"&&(n+=s.size??r.statSync(s.path).size);return{entries:t.length,bytes:n}}function $t(r,e){const t=r.statSync(e);if(!t.isDirectory())return{entries:1,bytes:t.size};let n=1,s=0;for(const o of r.readdirSync(e)){const i=$t(r,`${e==="/"?"":e}/${o}`);n+=i.entries,s+=i.bytes}return{entries:n,bytes:s}}function at(r,e){if(r.entries>e.maxFilesystemEntries||r.bytes>e.maxFilesystemBytes)throw new DOMException("Initial browser filesystem exceeds its configured quota.","QuotaExceededError")}function Qr(r,e,t){const n=e.split("/").filter(Boolean);if(!t)return r.existsSync(e)?0:1;let s="",o=0;for(const i of n)s+=`/${i}`,r.existsSync(s)||(o+=1);return o}class Jr{hub;send;limits;active=new Set;constructor(e,t,n=me){this.hub=e,this.send=t,this.limits=n}get openSockets(){return this.active.size}async handle(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Malformed virtual WebSocket message.");const t=e;if(!Number.isSafeInteger(t.id)||t.id<1||!t.data)throw new Error("Invalid virtual WebSocket message.");const n=t.id;if(t.type==="websocket-open"){if(this.active.size>=this.limits.maxVirtualWebSockets)throw new Error("Virtual WebSocket concurrency exceeded.");if(this.active.has(n))throw new Error("Duplicate virtual WebSocket identifier.");this.active.add(n);try{this.hub.open(n,t.data.port,t.data.path,t.data.protocols??[],{open:s=>this.send({type:"websocket-open",id:n,data:{protocol:s}}),message:s=>this.send({type:"websocket-message",id:n,data:{frame:s}}),close:(s,o,i)=>{this.active.delete(n),this.send({type:"websocket-close",id:n,data:{code:s,reason:o,clean:i}})},error:s=>this.send({type:"websocket-error",id:n,error:s})},typeof t.data.host=="string"?{host:t.data.host}:void 0)}catch(s){throw this.active.delete(n),s}return}if(!this.active.has(n))throw new Error("Unknown virtual WebSocket identifier.");if(t.type==="websocket-message"){if(!t.data.frame)throw new Error("Virtual WebSocket message has no frame.");this.hub.send(n,t.data.frame);return}if(t.type==="websocket-close"){this.hub.close(n,t.data.code,t.data.reason),this.active.delete(n);return}throw new Error("Unknown virtual WebSocket operation.")}closeAll(){for(const e of[...this.active]){try{this.hub.close(e,1001,"The preview went away.")}catch{}this.active.delete(e)}}}function Kr(r){const e=r?.type;return typeof e=="string"&&e.startsWith("websocket-")}const ie="supercode-sandbox-v1";function Yr(r,e){if(!r||typeof r!="object")return!1;const t=r;return t.channel===ie&&t.nonce===e&&typeof t.type=="string"}const Zr=16384,es=128,ts=65536,Z=15e3,rs=15e3,ss=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]),ns=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;function os(r,e,t=me){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed sandbox service-worker message.");const n=r,s=n.data;if(n.type!=="request"||!Number.isSafeInteger(n.id)||!s||!Number.isSafeInteger(s.port))throw new Error("Rejected an invalid virtual-server request.");if(!e(s.port))throw new Error(`Virtual port ${s.port} is not listening.`);const o=s.port;if(!s.method||!ss.has(s.method)||!s.url||s.url.length>Zr||!s.url.startsWith("/")||s.url.startsWith("//")||/[\\\u0000-\u001f\u007f]/u.test(s.url))throw new Error("Rejected an invalid virtual-server request target.");if(new URL(s.url,"https://virtual.invalid").origin!=="https://virtual.invalid")throw new Error("Rejected a cross-origin virtual-server request.");if(!s.headers||typeof s.headers!="object"||Array.isArray(s.headers))throw new Error("Rejected invalid virtual-server request headers.");const a=Object.entries(s.headers);if(a.length>es)throw new Error("Virtual-server request has too many headers.");let c=0;for(const[u,d]of a){if(!ns.test(u)||typeof d!="string"||/[\u0000\r\n]/u.test(d))throw new Error("Rejected malformed virtual-server request headers.");c+=u.length+d.length}if(c>ts)throw new Error("Virtual-server request headers are too large.");if(s.body!==void 0&&s.body!==null&&!(s.body instanceof ArrayBuffer))throw new Error("Rejected an invalid virtual-server request body.");if(s.body&&s.body.byteLength>t.maxVirtualRequestBytes)throw new Error(`Virtual-server request body exceeds ${t.maxVirtualRequestBytes} bytes.`);if(s.streaming!==void 0&&typeof s.streaming!="boolean")throw new Error("Rejected an invalid virtual-server streaming flag.");if(s.flowControl!==void 0&&s.flowControl!==1)throw new Error("Rejected an unsupported virtual-server flow-control protocol.");return{id:n.id,data:{port:o,method:s.method,url:s.url,headers:s.headers,...s.body?{body:s.body}:{},streaming:s.streaming===!0,flowControl:s.flowControl===1}}}function is(r,e){const n=Object.entries(r).find(([s])=>s.toLowerCase()===e.toLowerCase())?.[1];return Array.isArray(n)?n[0]:n}function as(r,e,t){if(!is(e,"content-type")?.toLowerCase().includes("text/html"))return r;let n=new TextDecoder().decode(r);for(const[s,o]of Object.entries(t??{}))n=n.replaceAll(s,o);return n=ds(n),new TextEncoder().encode(n)}const ct="data-browser-runtime-loopback",cs="__browser_runtime_virtual_host";function ds(r){if(r.includes(ct))return r;const e=`<script ${ct}>(function(){
2
- const clip=function(value,limit){return String(value===undefined?'undefined':value===null?'null':value instanceof Error?(value.stack||value.message):typeof value==='object'?function(){try{return JSON.stringify(value);}catch{return Object.prototype.toString.call(value);}}():value).slice(0,limit);};
3
- const observations=[];
4
- Object.defineProperty(window,'__browserRuntimePreviewObservations',{value:function(){return observations.slice();}});
5
- const report=function(observation){try{observations.push(observation);if(observations.length>200)observations.shift();window.dispatchEvent(new CustomEvent('browser-runtime-preview-observation',{detail:observation}));window.parent.postMessage({type:'browser-agent-observation',observation:observation},location.origin);}catch{}};
6
- const notifyPreviewLoad=function(){
7
- window.parent.postMessage({type:'browser-agent-preview-load'},location.origin);
8
- report({kind:'navigation',url:location.href,title:document.title.slice(0,4096),timestamp:Date.now()});
9
- };
10
- if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',notifyPreviewLoad,{once:true});else queueMicrotask(notifyPreviewLoad);
11
- ['debug','info','log','warn','error'].forEach(function(level){
12
- const original=console[level].bind(console);
13
- console[level]=function(){const args=Array.prototype.slice.call(arguments);original.apply(console,args);report({kind:'console',level:level,message:args.map(function(value){return clip(value,8192);}).join(' ').slice(0,32768),timestamp:Date.now()});};
14
- });
15
- window.addEventListener('error',function(event){report({kind:'exception',message:clip(event.message||event.error,32768),stack:event.error?.stack?clip(event.error.stack,65536):undefined,source:event.filename?clip(event.filename,16384):undefined,line:Number.isSafeInteger(event.lineno)?event.lineno:undefined,column:Number.isSafeInteger(event.colno)?event.colno:undefined,timestamp:Date.now()});});
16
- window.addEventListener('unhandledrejection',function(event){const reason=event.reason;report({kind:'unhandledrejection',message:clip(reason,32768),stack:reason?.stack?clip(reason.stack,65536):undefined,timestamp:Date.now()});});
17
- const networkState=window.__browserRuntimeNetworkState={pending:0,lastChanged:Date.now()};
18
- const networkBegin=function(){networkState.pending++;networkState.lastChanged=Date.now();};
19
- const networkEnd=function(){networkState.pending=Math.max(0,networkState.pending-1);networkState.lastChanged=Date.now();};
20
- const nativeFetch=window.fetch.bind(window);
21
- const virtualHostParameter=${JSON.stringify(cs)};
22
- const route=function(value){
23
- try {
24
- const url=new URL(String(value),location.href);
25
- if(url.protocol!=='http:'&&url.protocol!=='https:')return value;
26
- // a root-relative URL from inside a virtual document is the document's
27
- // own server's: the page under /__virtual__/<port>/ is that server's
28
- // root, so /api/x is its /api/x. The service worker routed these by the
29
- // request's referrer, which a document sent with no referrer never has.
30
- if(url.origin===location.origin){
31
- const own=/^[/]__virtual__[/]([0-9]+)(?=[/]|$)/.exec(location.pathname)||(function(){try{return /^[/]__virtual__[/]([0-9]+)(?=[/]|$)/.exec(window.parent.location.pathname);}catch(e){return null;}})();
32
- if(!own||url.pathname.startsWith('/__virtual__/')) return value;
33
- const routed=new URL(location.origin+'/__virtual__/'+own[1]+url.pathname+url.search);
34
- // The host this document is answered as is the session's, not this one
35
- // URL's: a page that answers as one host asked for its own assets as
36
- // another, and the server sent them down a different route entirely.
37
- const carried=new URLSearchParams(location.search).get(virtualHostParameter);
38
- if(carried&&!routed.searchParams.has(virtualHostParameter))routed.searchParams.set(virtualHostParameter,carried);
39
- routed.hash=url.hash;
40
- return routed.href;
41
- }
42
- const loopback=url.hostname==='localhost'||url.hostname.endsWith('.localhost')||url.hostname==='127.0.0.1'||url.hostname==='[::1]';
43
- if((url.protocol==='http:'||url.protocol==='https:')&&loopback){
44
- const port=url.port||String(url.protocol==='https:'?443:80);
45
- const routed=new URL(location.origin+'/__virtual__/'+port+url.pathname+url.search);
46
- routed.searchParams.set(virtualHostParameter,url.host);
47
- routed.hash=url.hash;
48
- return routed.href;
49
- }
50
- } catch {}
51
- return value;
52
- };
53
- // document.cookie is the tab's jar (ADR-0050): the host's cookies live there,
54
- // not in this origin's, and a server here set them through its answers. The
55
- // jar is offered by a same-origin ancestor, the page that holds the tab; a
56
- // frame of another origin cannot read it, and keeps the browser's own.
57
- (function(){
58
- let cookies=null;
59
- try{for(let owner=window.parent;;owner=owner.parent){const offered=owner[${JSON.stringify(te)}];if(offered&&typeof offered.read==='function'){cookies=offered;break;}if(owner===owner.parent)break;}}catch{}
60
- if(!cookies)return;
61
- const where=function(){
62
- const host=new URLSearchParams(location.search).get(virtualHostParameter)||location.host;
63
- const path=location.pathname.replace(/^[/]__virtual__[/][0-9]+(?=[/]|$)/,'')||'/';
64
- return {host:host,path:path};
65
- };
66
- Object.defineProperty(document,'cookie',{configurable:true,enumerable:true,get:function(){return cookies.read(where());},set:function(value){cookies.write(where(),String(value));}});
67
- })();
68
- window.fetch=function(input,init){
69
- if(input instanceof Request){
70
- const target=route(input.url);
71
- networkBegin();
72
- try{return nativeFetch(target===input.url?input:new Request(target,input),init).finally(networkEnd);}catch(error){networkEnd();throw error;}
73
- }
74
- networkBegin();
75
- try{return nativeFetch(route(input),init).finally(networkEnd);}catch(error){networkEnd();throw error;}
76
- };
77
- const nativeOpen=XMLHttpRequest.prototype.open;
78
- XMLHttpRequest.prototype.open=function(method,url){
79
- const args=Array.prototype.slice.call(arguments);
80
- args[1]=route(url);
81
- return nativeOpen.apply(this,args);
82
- };
83
- const nativeSend=XMLHttpRequest.prototype.send;
84
- XMLHttpRequest.prototype.send=function(){networkBegin();this.addEventListener('loadend',networkEnd,{once:true});try{return nativeSend.apply(this,arguments);}catch(error){networkEnd();throw error;}};
85
- // A beacon is a request too: vgai's editor sends its heartbeat with one, and
86
- // a root-relative beacon that is not routed reaches the page's origin, which
87
- // answers 405 once a second.
88
- if(typeof navigator.sendBeacon==='function'){
89
- const nativeSendBeacon=navigator.sendBeacon.bind(navigator);
90
- navigator.sendBeacon=function(url,data){return data===undefined?nativeSendBeacon(route(url)):nativeSendBeacon(route(url),data);};
91
- }
92
- // A worker a virtual document makes is that document's server's: its script
93
- // URL routed like any request, so the worker's own requests carry a referrer
94
- // that names the port and the service worker attributes them. Made from the
95
- // origin root, a worker's root-relative fetch reached the page's origin.
96
- // A blob has no script fetch carrying the virtual path. Keep its creator
97
- // identity for the service worker to query, including after SW restarts.
98
- // Keep URL names after revoke: an already-running worker still uses that URL.
99
- const createdObjectUrls=new Set();
100
- const nativeCreateObjectURL=URL.createObjectURL.bind(URL);
101
- URL.createObjectURL=function(value){const url=nativeCreateObjectURL(value);createdObjectUrls.add(url);return url;};
102
- if(navigator.serviceWorker)navigator.serviceWorker.addEventListener('message',function(event){
103
- if(event.data?.type!=='virtual-blob-owner'||!event.ports[0])return;
104
- const url=String(event.data.url||'').split('#')[0];
105
- event.ports[0].postMessage(createdObjectUrls.has(url));
106
- event.ports[0].close();
107
- });
108
- for(const name of ['Worker','SharedWorker']){
109
- const Native=window[name];
110
- if(typeof Native!=='function')continue;
111
- const Routed=function(url,options){return options===undefined?new Native(route(url)):new Native(route(url),options);};
112
- Routed.prototype=Native.prototype;
113
- window[name]=Routed;
114
- }
115
- if(typeof EventSource==='function'){
116
- const NativeEventSource=EventSource;
117
- window.EventSource=function(url,options){return new NativeEventSource(route(url),options);};
118
- window.EventSource.prototype=NativeEventSource.prototype;
119
- Object.defineProperties(window.EventSource,{CONNECTING:{value:0},OPEN:{value:1},CLOSED:{value:2}});
120
- }
121
- const NativeWebSocket=window.WebSocket;
122
- let virtualWebSocketSequence=0;
123
- // A document numbers its sockets from a base of its own: the document before
124
- // it in the frame may still hold sockets the host has not finished, and a
125
- // number shared with one of those is refused as a duplicate.
126
- const virtualWebSocketBase=Math.floor(Math.random()*2147483648)*1048576;
127
- const virtualWebSockets=new Map();
128
- const ownBytes=function(value){
129
- const view=value instanceof ArrayBuffer?new Uint8Array(value):new Uint8Array(value.buffer,value.byteOffset,value.byteLength);
130
- return view.slice();
131
- };
132
- const decodeBinary=function(value){
133
- if(typeof Uint8Array.fromBase64==='function')return Uint8Array.fromBase64(value);
134
- const binary=atob(value);
135
- const out=new Uint8Array(binary.length);
136
- for(let index=0;index<binary.length;index+=1)out[index]=binary.charCodeAt(index);
137
- return out;
138
- };
139
- const emitSocket=function(socket,type,event){
140
- socket.dispatchEvent(event);
141
- const handler=socket['on'+type];
142
- if(typeof handler==='function')handler.call(socket,event);
143
- };
144
- class VirtualWebSocket extends EventTarget{
145
- constructor(url,protocols){
146
- super();
147
- const parsed=new URL(String(url),location.href);
148
- this.url=parsed.href;
149
- this.readyState=0;
150
- this.bufferedAmount=0;
151
- this.extensions='';
152
- this.protocol='';
153
- this.binaryType='blob';
154
- this.onopen=this.onmessage=this.onerror=this.onclose=null;
155
- this.__id=virtualWebSocketBase+(++virtualWebSocketSequence);
156
- virtualWebSockets.set(this.__id,this);
157
- // A socket to the page's own host from a frame served under a virtual
158
- // port is a socket to that port: a dev server's HMR client computes its
159
- // URL from location, which names the page's origin, not the server's.
160
- // A document at the origin's root has no prefix to name its server: 0
161
- // says its own, and the sandbox that opened it fills the port in.
162
- const virtualMatch=/^[/]__virtual__[/]([0-9]+)(?=[/]|$)/.exec(location.pathname);
163
- const ownHost=parsed.host===location.host||(parsed.hostname===location.hostname&&parsed.port==='');
164
- const port=ownHost?(virtualMatch?Number(virtualMatch[1]):0):Number(parsed.port||((parsed.protocol==='wss:')?443:80));
165
- const selected=protocols===undefined?[]:(Array.isArray(protocols)?protocols:[protocols]);
166
- window.parent.postMessage({type:'websocket-open',id:this.__id,data:{port:port,host:parsed.host,path:parsed.pathname+parsed.search,protocols:selected.map(String)}},location.origin);
167
- }
168
- send(value){
169
- if(this.readyState!==1)throw new DOMException('WebSocket is not open.','InvalidStateError');
170
- if(value instanceof Blob){
171
- this.bufferedAmount+=value.size;
172
- void value.arrayBuffer().then((buffer)=>{this.bufferedAmount=Math.max(0,this.bufferedAmount-value.size);this.__send({kind:'binary',bytes:new Uint8Array(buffer)});});
173
- return;
174
- }
175
- // Bytes cross to the page as they are (a copy the socket owns), not as base64.
176
- const frame=typeof value==='string'?{kind:'text',text:value}:{kind:'binary',bytes:ownBytes(value)};
177
- this.__send(frame);
178
- }
179
- __send(frame){window.parent.postMessage({type:'websocket-message',id:this.__id,data:{frame:frame}},location.origin);}
180
- close(code,reason){
181
- if(this.readyState===2||this.readyState===3)return;
182
- this.readyState=2;
183
- window.parent.postMessage({type:'websocket-close',id:this.__id,data:{code:code===undefined?1000:code,reason:reason===undefined?'':String(reason)}},location.origin);
184
- }
185
- }
186
- Object.defineProperties(VirtualWebSocket,{CONNECTING:{value:0},OPEN:{value:1},CLOSING:{value:2},CLOSED:{value:3}});
187
- Object.defineProperties(VirtualWebSocket.prototype,{CONNECTING:{value:0},OPEN:{value:1},CLOSING:{value:2},CLOSED:{value:3}});
188
- window.addEventListener('message',function(event){
189
- if(event.source!==window.parent||event.origin!==location.origin||typeof event.data?.type!=='string'||!event.data.type.startsWith('websocket-'))return;
190
- const message=event.data;
191
- const socket=virtualWebSockets.get(message.id);
192
- if(!socket)return;
193
- if(message.type==='websocket-open'){
194
- socket.readyState=1;
195
- socket.protocol=String(message.data?.protocol||'');
196
- emitSocket(socket,'open',new Event('open'));
197
- }else if(message.type==='websocket-message'){
198
- const frame=message.data?.frame;
199
- let data=frame?.kind==='text'?String(frame.text):(frame?.bytes instanceof Uint8Array?frame.bytes:decodeBinary(String(frame?.base64||'')));
200
- if(data instanceof Uint8Array&&(data.byteOffset!==0||data.byteLength!==data.buffer.byteLength))data=data.slice();
201
- if(frame?.kind==='binary')data=socket.binaryType==='arraybuffer'?data.buffer:new Blob([data]);
202
- emitSocket(socket,'message',new MessageEvent('message',{data:data}));
203
- }else if(message.type==='websocket-close'){
204
- socket.readyState=3;
205
- virtualWebSockets.delete(message.id);
206
- emitSocket(socket,'close',new CloseEvent('close',{code:message.data?.code||1000,reason:String(message.data?.reason||''),wasClean:message.data?.clean!==false}));
207
- }else if(message.type==='websocket-error'){
208
- emitSocket(socket,'error',new ErrorEvent('error',{message:String(message.error||'Virtual WebSocket failed.')}));
209
- if(socket.readyState!==3){
210
- socket.readyState=3;
211
- virtualWebSockets.delete(message.id);
212
- emitSocket(socket,'close',new CloseEvent('close',{code:1006,reason:'',wasClean:false}));
213
- }
214
- }
215
- });
216
- // A document leaving the frame takes its sockets with it, as a browser
217
- // closes a page's sockets; the next document starts its numbering over.
218
- window.addEventListener('pagehide',function(){
219
- virtualWebSockets.forEach(function(socket){
220
- if(socket.readyState===0||socket.readyState===1)socket.close(1001,'Page hidden');
221
- });
222
- });
223
- window.WebSocket=function(url,protocols){
224
- const parsed=new URL(String(url),location.href);
225
- const local=(parsed.protocol==='ws:'||parsed.protocol==='wss:')&&(parsed.host===location.host||parsed.hostname==='localhost'||parsed.hostname.endsWith('.localhost')||parsed.hostname==='127.0.0.1'||parsed.hostname==='[::1]');
226
- // The host answers from the frame's parent. A document with no parent (the
227
- // app opened by its share link, a preview in a tab of its own) has no host
228
- // to answer: its messages would come back to itself, every frame an echo,
229
- // and its sockets go out as the browser's own.
230
- if(local&&window.parent!==window)return new VirtualWebSocket(parsed.href,protocols);
231
- return protocols===undefined?new NativeWebSocket(parsed.href):new NativeWebSocket(parsed.href,protocols);
232
- };
233
- window.WebSocket.prototype=VirtualWebSocket.prototype;
234
- Object.defineProperties(window.WebSocket,{CONNECTING:{value:0},OPEN:{value:1},CLOSING:{value:2},CLOSED:{value:3}});
235
- })();<\/script>`;return/<head(?:\s[^>]*)?>/iu.test(r)?r.replace(/<head(?:\s[^>]*)?>/iu,t=>`${t}
236
- ${e}`):`${e}
237
- ${r}`}class Ks{options;ready;initialPreviewReady;resolveReady;rejectReady;resolveInitialPreview;rejectInitialPreview;activeRequestIds=new Set;waitingRequests=[];activeWebSocketIds=new Set;activeCommands=new Map;observationBuffer=[];webSockets;socketRelay;stopObservingPorts;requestControllers=new Map;hostFlowRequests=new Map;stopObservingHostServices;readyTimer;initialPreviewTimer;readyFinished=!1;initialPreviewFinished=!1;bridgeConnected=!1;previewConnected=!1;announcedReady=!1;readinessWaiters=new Set;disposed=!1;nextCommandId=1;protocolChannel;cancelProtocolAttachment;protocolDocumentId;port;constructor(e){this.options=e,this.port=e.port,this.ready=new Promise((t,n)=>{this.resolveReady=t,this.rejectReady=n}),this.initialPreviewReady=new Promise((t,n)=>{this.resolveInitialPreview=t,this.rejectInitialPreview=n}),this.ready.catch(()=>{}),this.initialPreviewReady.catch(()=>{}),this.webSockets=new Fr(t=>this.options.bridge.getServerPorts().includes(t),this.options.webSocketRegistry,this.options.webSocketConnector),this.socketRelay=new Jr(this.webSockets,t=>this.send(t),this.limits),this.stopObservingPorts=ht(this.options.bridge,t=>{if(t.type==="close"){this.webSockets.closePort(t.port);for(const n of this.requestControllers.values())n.port===t.port&&n.controller.abort(new Error("The preview server stopped."))}}),this.stopObservingHostServices=e.hostFetchServices?.observe((t,n)=>{this.bridgeConnected&&this.send(n?{type:"server-registered",data:{port:t,hostname:"127.0.0.1",...n}}:this.options.bridge.getServerPorts().includes(t)?{type:"server-registered",data:{port:t,hostname:"127.0.0.1"}}:{type:"server-unregistered",data:{port:t}})})??(()=>{}),window.addEventListener("message",this.onMessage)}waitForReady(e=Z){if(this.assertActive(),!Number.isFinite(e)||e<=0)throw new Error("Invalid sandbox readiness timeout.");return this.bridgeConnected&&this.previewConnected?Promise.resolve():new Promise((t,n)=>{const s=a=>{globalThis.clearTimeout(i),this.readinessWaiters.delete(o),a?n(a):t()},o={resolve:()=>s(),reject:a=>s(a)},i=globalThis.setTimeout(()=>s(new Error("Sandbox preview connection timed out.")),e);this.readinessWaiters.add(o)})}setPort(e){if(this.assertActive(),!Number.isSafeInteger(e)||e<1||e>65535)throw new Error("Invalid virtual server port.");this.port=e,this.armStartupTimeouts()}snapshot(){return this.command({operation:"snapshot"})}query(e){return this.command({operation:"query",selector:e})}screenshot(e={}){return this.command({operation:"screenshot",...e})}navigate(e){return this.command({operation:"navigate",url:e})}reloadPreview(){return this.command({operation:"reload"})}waitForNetworkIdle(e={}){return this.command({operation:"network-idle",...e.idleMs!==void 0?{idleMs:e.idleMs}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{}},(e.timeoutMs??1e4)+1e3)}setPreviewScript(e){return this.command({operation:"set-script",...e!==void 0?{source:e}:{}})}evaluatePreview(e,t){return this.command({operation:"evaluate",source:e,...t!==void 0?{args:t}:{}})}observations(){return this.observationBuffer.slice()}clearObservations(){this.observationBuffer.length=0}async connectProtocol(e=globalThis.crypto.randomUUID(),t=Z){if(this.assertActive(),!/^[a-zA-Z0-9_-]{1,128}$/u.test(e))throw new Error("Invalid preview target identifier.");if(!Number.isFinite(t)||t<=0)throw new Error("Invalid protocol attachment timeout.");if(await this.waitForReady(t),this.assertActive(),this.cancelProtocolAttachment)throw new Error("A preview protocol attachment is already in flight.");this.protocolChannel?.finish("Preview protocol replaced");const n=this.options.preview.contentWindow;if(!n)throw new Error("The preview frame is no longer available.");const s=new MessageChannel;return new Promise((o,i)=>{const a=()=>{globalThis.clearTimeout(l),s.port1.removeEventListener("message",d),s.port1.removeEventListener("messageerror",u),this.cancelProtocolAttachment===c&&(this.cancelProtocolAttachment=void 0)},c=f=>{a(),s.port1.postMessage({type:"close",code:1001,reason:f.message}),s.port1.close(),s.port2.close(),i(f)},u=()=>c(new Error("Preview protocol acknowledgement could not be decoded.")),d=f=>{if(f.data?.type!=="protocol-ready"||f.data?.id!==e){c(new Error(f.data?.type==="close"?String(f.data.reason):"Invalid preview protocol acknowledgement."));return}a();let h;const p=new Promise(g=>{h=g});let w=!1;const m=g=>{g.data?.type==="close"&&y.finish(String(g.data.reason??"Preview protocol closed"),!0)},y={finish:(g,b=!1)=>{if(!w){if(w=!0,s.port1.removeEventListener("message",m),!b)try{s.port1.postMessage({type:"close",code:1001,reason:g})}catch{}this.protocolChannel===y&&(this.protocolChannel=void 0),h(g)}}};s.port1.addEventListener("message",m),this.protocolChannel=y,o({port:s.port1,closed:p})},l=globalThis.setTimeout(()=>c(new Error("Preview protocol attachment timed out.")),t);this.cancelProtocolAttachment=c,s.port1.addEventListener("message",d),s.port1.addEventListener("messageerror",u),s.port1.start();try{n.postMessage({channel:ie,nonce:this.options.nonce,type:"protocol-connect",payload:{id:e}},this.options.origin,[s.port2])}catch(f){c(f instanceof Error?f:new Error(String(f)))}})}resetProtocol(e){this.cancelProtocolAttachment?.(new Error(e)),this.protocolChannel?.finish(e)}dispose(){if(this.disposed)return;this.disposed=!0,this.resetProtocol("Preview bridge disposed"),window.removeEventListener("message",this.onMessage),this.stopObservingPorts(),this.stopObservingHostServices(),this.webSockets.closeAll();for(const t of this.requestControllers.values())t.controller.abort(new Error("The preview bridge was disposed."));for(const t of this.hostFlowRequests.values())t.closed=!0,t.reader&&t.track(t.reader.cancel(),!0),t.controller.abort(new Error("The preview bridge was disposed.")),t.wake?.();this.requestControllers.clear(),this.activeRequestIds.clear(),this.readyTimer!==void 0&&globalThis.clearTimeout(this.readyTimer),this.initialPreviewTimer!==void 0&&globalThis.clearTimeout(this.initialPreviewTimer);const e=new Error("Browser sandbox bridge was disposed.");this.readyFinished||(this.readyFinished=!0,this.rejectReady(e)),this.initialPreviewFinished||(this.initialPreviewFinished=!0,this.rejectInitialPreview(e));for(const t of this.readinessWaiters)t.reject(e);for(const t of this.activeCommands.values())globalThis.clearTimeout(t.timeout),t.reject(e);this.activeCommands.clear()}onMessage=e=>{if(this.disposed||e.source!==this.options.preview.contentWindow||e.origin!==this.options.origin||!Yr(e.data,this.options.nonce))return;const t=e.data;if(t.type==="request"){const n=t.payload?.type;if(n==="stream-pull"||n==="stream-cancel"){this.handleHostFlowControl(t.payload);return}const s=Kr(t.payload),o=!s&&ls(t.payload);(s?this.handleWebSocket(t.payload):this.handleRequest(t.payload)).then(()=>{o&&this.finishInitialPreview()}).catch(a=>{const c=t.payload?.id;this.send({type:s?"websocket-error":"response",id:c,error:a instanceof Error?a.message:String(a)})})}else if(t.type==="protocol-disconnect")this.resetProtocol("Preview document unloaded"),this.bridgeConnected=!1,this.previewConnected=!1;else if(t.type==="ready"){const n=t.payload?.documentId;typeof n=="string"&&n!==this.protocolDocumentId&&(this.protocolDocumentId!==void 0&&this.resetProtocol("Preview document replaced"),this.protocolDocumentId=n),this.bridgeConnected=!0;for(const s of this.options.hostFetchServices?.snapshot()??[])this.send({type:"server-registered",data:{port:s.port,hostname:"127.0.0.1",...s.capability}});this.readyFinished||(this.readyFinished=!0,this.readyTimer!==void 0&&globalThis.clearTimeout(this.readyTimer),this.resolveReady()),this.announceReady()}else if(t.type==="preview-load")this.finishInitialPreview();else if(t.type==="rendered"){const n=t.payload?.revision;typeof n=="string"&&n.length>0&&n.length<=128&&this.options.onRendered?.(n)}else if(t.type==="command-result")this.finishCommand(t.payload);else if(t.type==="observation"){const n=hs(t.payload);if(!n)return;this.observationBuffer.push(n),this.observationBuffer.length>this.limits.maxPreviewObservations&&this.observationBuffer.shift(),this.options.onObservation?.(n)}else if(t.type==="error"){const n=t.payload?.message||"Sandbox bridge failed.",s=new Error(n);for(const o of this.readinessWaiters)o.reject(s);this.readyFinished||(this.readyFinished=!0,this.readyTimer!==void 0&&globalThis.clearTimeout(this.readyTimer),this.rejectReady(s)),this.initialPreviewFinished||(this.initialPreviewFinished=!0,this.initialPreviewTimer!==void 0&&globalThis.clearTimeout(this.initialPreviewTimer),this.rejectInitialPreview(s));for(const o of this.activeCommands.values())globalThis.clearTimeout(o.timeout),o.reject(s);this.activeCommands.clear(),this.options.onError?.(s)}};async command(e,t=rs){if(this.assertActive(),await this.waitForReady(),this.assertActive(),this.activeCommands.size>=this.limits.maxPreviewCommands)throw new Error("Preview command concurrency exceeded.");const n=this.nextCommandId++,s={...e,id:n};return new Promise((o,i)=>{const a=globalThis.setTimeout(()=>{this.activeCommands.delete(n),i(new Error(`Preview command ${e.operation} timed out.`))},t);this.activeCommands.set(n,{resolve:c=>o(c),reject:i,timeout:a});try{const c=this.options.preview.contentWindow;if(!c)throw new Error("The preview frame is no longer available.");c.postMessage({channel:ie,nonce:this.options.nonce,type:"command",payload:s},this.options.origin)}catch(c){globalThis.clearTimeout(a),this.activeCommands.delete(n),i(c)}})}finishCommand(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(!Number.isSafeInteger(t.id))return;const n=this.activeCommands.get(t.id);n&&(this.activeCommands.delete(t.id),globalThis.clearTimeout(n.timeout),typeof t.error=="string"?n.reject(new Error(t.error)):n.resolve(t.result))}assertActive(){if(this.disposed)throw new Error("Browser sandbox bridge is disposed.")}get limits(){return this.options.policy?.limits??me}armStartupTimeouts(){!this.readyFinished&&this.readyTimer===void 0&&(this.readyTimer=globalThis.setTimeout(()=>{this.readyTimer=void 0,this.readyFinished=!0,this.rejectReady(new Error("Sandbox bridge handshake timed out."))},Z)),!this.initialPreviewFinished&&this.initialPreviewTimer===void 0&&(this.initialPreviewTimer=globalThis.setTimeout(()=>{this.initialPreviewTimer=void 0,this.initialPreviewFinished=!0,this.rejectInitialPreview(new Error("Generated preview startup timed out."))},Z))}finishInitialPreview(){this.disposed||this.previewConnected||(this.previewConnected=!0,this.initialPreviewTimer!==void 0&&globalThis.clearTimeout(this.initialPreviewTimer),this.initialPreviewFinished||(this.initialPreviewFinished=!0,this.resolveInitialPreview()),this.options.onPreviewLoad?.(),this.announceReady())}announceReady(){if(!(!this.bridgeConnected||!this.previewConnected)){for(const e of this.readinessWaiters)e.resolve();this.announcedReady||(this.announcedReady=!0,this.options.onReady?.())}}send(e){this.disposed||this.options.preview.contentWindow?.postMessage({channel:ie,nonce:this.options.nonce,type:"response",payload:e},this.options.origin)}handleHostFlowControl(e){if(!e||typeof e!="object")return;const t=e;if(!Number.isSafeInteger(t.id))return;const n=this.hostFlowRequests.get(t.id);if(!(!n||n.closed)){if(t.type==="stream-cancel")n.closed=!0,n.reader&&n.track(n.reader.cancel(),!0),n.controller.abort(new Error("The guest cancelled the Host Fetch response.")),n.wake?.();else if(t.type==="stream-pull"){if(n.credit)return;n.credit=!0,n.wake?.()}}}async handleHostFlowRequest(e,t){const n=this.options.hostFetchServices?.get(e.data.port);if(!n||!e.data.flowControl||!e.data.streaming)throw new Error("Host Fetch service requires flow-control protocol 1.");if((e.data.body?.byteLength??0)>n.maxRequestBytes)throw new Error(`Host Fetch-service upload exceeds ${n.maxRequestBytes} bytes.`);const s={port:n.port,controller:t,credit:!1,closed:!1,track:(a,c)=>n.track(a,c)};this.hostFlowRequests.set(e.id,s);let o;const i=()=>t.abort(n.signal.reason);n.signal.addEventListener("abort",i,{once:!0});try{n.signal.aborted&&i(),n.ready&&await M(n.ready,t.signal);const a=e.data.method,c=`http://127.0.0.1:${n.port}${e.data.url}`,u=Promise.resolve().then(()=>n.fetch(new Request(c,{method:a,headers:e.data.headers,...a==="GET"||a==="HEAD"||!e.data.body?{}:{body:e.data.body},signal:t.signal})));n.track(u),n.track(u.then(async w=>{t.signal.aborted&&w instanceof Response&&await w.body?.cancel()},()=>{}),!0);const d=await M(u,t.signal);if(!(d instanceof Response))throw new Error("Host Fetch handler did not return a Response.");if(t.signal.aborted){try{await d.body?.cancel(t.signal.reason)}catch(w){throw o=w,w}return}if(this.send({type:"stream-start",id:e.id,data:{statusCode:d.status,statusMessage:d.statusText,headers:Object.fromEntries(d.headers)}}),a==="HEAD"||d.status===204||d.status===205||d.status===304||!d.body){try{await d.body?.cancel()}catch(w){throw o=w,w}this.send({type:"stream-end",id:e.id});return}const l=d.body.getReader();s.reader=l;let f=0,h=!1;const p=async()=>(s.credit||(await M(new Promise(w=>{s.wake=w}),t.signal),delete s.wake),s.closed||t.signal.aborted?!1:(s.credit=!1,!0));try{for(;!s.closed&&!t.signal.aborted&&await p();){const w=l.read();n.track(w);const m=await M(w,t.signal);if(m.done){h=!0,this.send({type:"stream-end",id:e.id});return}if(!(m.value instanceof Uint8Array))throw new Error("Host Fetch-service producer did not yield bytes.");if(f+=m.value.byteLength,f>this.limits.maxVirtualResponseBytes)throw new Error("Host Fetch-service response exceeds its byte limit.");for(let y=0;(y<m.value.byteLength||y===0&&m.value.byteLength===0)&&!(y>0&&!await p()||s.closed||t.signal.aborted||(this.send({type:"stream-chunk",id:e.id,data:{chunkBase64:H(m.value.subarray(y,y+Pe))}}),m.value.byteLength===0));y+=Pe);}}finally{if(!h)try{await l.cancel()}catch(w){o=w}try{l.releaseLock()}catch(w){o===void 0&&(o=w)}if(o!==void 0)throw o}}catch(a){if(!s.closed&&!t.signal.aborted&&this.send({type:"stream-error",id:e.id,error:a instanceof Error?a.message:String(a)}),o!==void 0)throw a}finally{s.closed=!0,n.signal.removeEventListener("abort",i),this.hostFlowRequests.delete(e.id)}}async handleRequest(e){this.assertActive();const t=os(e,u=>this.options.bridge.getServerPorts().includes(u),this.limits);if(this.requestControllers.has(t.id))throw new Error("Duplicate virtual-server request identifier.");const n=this.options.hostFetchServices?.get(t.data.port),s=new AbortController;this.requestControllers.set(t.id,{port:t.data.port,controller:s});const o=s.signal,i=()=>s.abort(n?.signal.reason);n?.signal.addEventListener("abort",i,{once:!0}),n?.signal.aborted&&i();let a=!1,c=!0;try{for(;this.activeRequestIds.size>=this.limits.maxVirtualRequests;)await new Promise((y,g)=>{const b=()=>{o.removeEventListener("abort",S),y()},S=()=>{const E=this.waitingRequests.indexOf(b);E>=0&&this.waitingRequests.splice(E,1),o.removeEventListener("abort",S),g(o.reason)};if(o.aborted){g(o.reason);return}this.waitingRequests.push(b),o.addEventListener("abort",S,{once:!0})});if(o.throwIfAborted(),this.options.hostFetchServices?.get(t.data.port)!==n)throw new Error("Virtual-server registration changed while the request waited.");this.activeRequestIds.add(t.id),a=!0;const{method:u,url:d,headers:l,body:f,streaming:h}=t.data;if(n){const y=this.handleHostFlowRequest(t,s);n.track(y,!0),await y;return}if(t.data.flowControl)throw new Error("Flow-control protocol is not registered for this port.");if(h&&this.options.bridge.handleStreamingRequest){let y=0,g=!1,b=!1,S,E;const v=new Promise((x,F)=>{S=x,E=F});v.catch(()=>{});const R=new AbortController,k=()=>{R.signal.aborted||R.abort(o.reason)};o.addEventListener("abort",k,{once:!0});const T=x=>{c=!1,E(x),k()},A=this.options.bridge.handleStreamingRequest(t.data.port,u,d,l,f,{start:(x,F,B)=>{if(!(!c||o.aborted)){if(g){T(new Error("The preview response already started."));return}g=!0;try{this.send({type:"stream-start",id:t.id,data:{statusCode:x,statusMessage:F,headers:B}})}catch(z){T(z)}}},chunk:x=>{if(!(!c||o.aborted)){if(!g||b){T(new Error("The preview response is not accepting chunks."));return}if(y+=x.byteLength,y>this.limits.maxVirtualResponseBytes){T(new Error(`Virtual-server streaming response exceeds ${this.limits.maxVirtualResponseBytes} bytes.`));return}try{this.send({type:"stream-chunk",id:t.id,data:{chunkBase64:H(x)}})}catch(F){T(F)}}},end:()=>{if(!(!c||o.aborted||b)){if(!g){T(new Error("The preview response ended before its headers."));return}b=!0;try{this.send({type:"stream-end",id:t.id}),S()}catch(x){T(x)}}}},{signal:R.signal});if(await M(Promise.race([A,v.then(()=>!0)]),o)){await M(v,o);return}if(g||b||y>0)throw new Error("The preview streaming handler wrote a response before declining the request.")}const p=await M(()=>this.options.bridge.handleRequest(t.data.port,u,d,l,f),o),w=p.body instanceof Uint8Array?p.body:new Uint8Array;if(w.byteLength>this.limits.maxVirtualResponseBytes)throw new Error(`Virtual-server response body exceeds ${this.limits.maxVirtualResponseBytes} bytes.`);const m=as(w,p.headers,this.options.htmlModuleRewrites);if(m.byteLength>this.limits.maxVirtualResponseBytes)throw new Error("The rewritten preview response exceeds its byte limit.");if(h){this.send({type:"stream-start",id:t.id,data:{statusCode:p.statusCode,statusMessage:p.statusMessage,headers:p.headers}}),m.length>0&&this.send({type:"stream-chunk",id:t.id,data:{chunkBase64:H(m)}}),this.send({type:"stream-end",id:t.id});return}this.send({type:"response",id:t.id,data:{statusCode:p.statusCode,statusMessage:p.statusMessage,headers:p.headers,bodyBase64:H(m)}})}finally{c=!1,n?.signal.removeEventListener("abort",i),this.requestControllers.delete(t.id),a&&(this.activeRequestIds.delete(t.id),this.waitingRequests.shift()?.())}}async handleWebSocket(e){await this.socketRelay.handle(e)}}function ls(r){if(!r||typeof r!="object")return!1;const e=r;return e.type==="request"&&e.data?.method==="GET"&&e.data.url==="/"&&e.data.headers?.["sec-fetch-dest"]==="iframe"}function hs(r){if(!r||typeof r!="object"||Array.isArray(r))return;const e=r;if(!(!Number.isFinite(e.timestamp)||typeof e.kind!="string")){if(e.kind==="console")return!new Set(["debug","info","log","warn","error"]).has(String(e.level))||typeof e.message!="string"||e.message.length>32768?void 0:e;if(e.kind==="exception"||e.kind==="unhandledrejection")return typeof e.message!="string"||e.message.length>32768||e.stack!==void 0&&(typeof e.stack!="string"||e.stack.length>65536)||e.source!==void 0&&(typeof e.source!="string"||e.source.length>16384)?void 0:e;if(e.kind==="navigation")return typeof e.url!="string"||e.url.length>16384||typeof e.title!="string"||e.title.length>4096?void 0:e}}export{Kt as $,Mt as A,Q as B,Or as C,Ut as D,Ds as E,zt as F,Hs as G,Ws as H,qs as I,Ns as J,Cs as K,Ve as L,Ss as M,de as N,_s as O,ks as P,ds as Q,Ks as R,Os as S,ie as T,Es as U,Yt as V,Rs as W,Ms as X,Bs as Y,Fs as Z,Ls as _,fs as a,Gs as a0,As as a1,Ts as a2,Ps as a3,ze as a4,xs as a5,as as a6,D as a7,Wt as a8,ke as a9,ae as aa,fe as ab,bs as ac,gs as ad,ys as ae,ps as af,ws as ag,ms as ah,Dt as b,Ne as c,He as d,ee as e,$s as f,Is as g,ft as h,H as i,Ot as j,M as k,Qs as l,me as m,Fr as n,ht as o,tt as p,Us as q,Xt as r,zs as s,Vs as t,vs as u,Mr as v,js as w,Xs as x,Js as y,Le as z};