@volter/browser-substrate 0.1.103 → 0.1.105

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/catalog/demand-input.json +133 -0
  2. package/dist/boot-screen.d.ts +2 -0
  3. package/dist/boot-screen.d.ts.map +1 -1
  4. package/dist/boot-screen.js +1 -1
  5. package/dist/boot-screen.js.map +1 -1
  6. package/dist/cli/archive.d.ts +1 -0
  7. package/dist/cli/archive.d.ts.map +1 -1
  8. package/dist/cli/archive.js +4 -4
  9. package/dist/cli/archive.js.map +1 -1
  10. package/dist/cli/build.d.ts +5 -1
  11. package/dist/cli/build.d.ts.map +1 -1
  12. package/dist/cli/build.js +21 -2
  13. package/dist/cli/build.js.map +1 -1
  14. package/dist/cli/cache-root.d.ts +7 -0
  15. package/dist/cli/cache-root.d.ts.map +1 -0
  16. package/dist/cli/cache-root.js +24 -0
  17. package/dist/cli/cache-root.js.map +1 -0
  18. package/dist/cli/companions.d.ts +1 -1
  19. package/dist/cli/companions.d.ts.map +1 -1
  20. package/dist/cli/companions.js +30 -16
  21. package/dist/cli/companions.js.map +1 -1
  22. package/dist/cli/dependency-plan-build.d.ts +4 -0
  23. package/dist/cli/dependency-plan-build.d.ts.map +1 -1
  24. package/dist/cli/dependency-plan-build.js +111 -30
  25. package/dist/cli/dependency-plan-build.js.map +1 -1
  26. package/dist/cli/docker-build.d.ts +1 -0
  27. package/dist/cli/docker-build.d.ts.map +1 -1
  28. package/dist/cli/docker-build.js +4 -4
  29. package/dist/cli/docker-build.js.map +1 -1
  30. package/dist/cli/dry-run.d.ts +4 -4
  31. package/dist/cli/dry-run.d.ts.map +1 -1
  32. package/dist/cli/dry-run.js +10 -9
  33. package/dist/cli/dry-run.js.map +1 -1
  34. package/dist/cli/generated-code.d.ts +2 -1
  35. package/dist/cli/generated-code.d.ts.map +1 -1
  36. package/dist/cli/generated-code.js +46 -16
  37. package/dist/cli/generated-code.js.map +1 -1
  38. package/dist/cli/host-build.d.ts +1 -0
  39. package/dist/cli/host-build.d.ts.map +1 -1
  40. package/dist/cli/host-build.js +10 -9
  41. package/dist/cli/host-build.js.map +1 -1
  42. package/dist/cli/host-managers.d.ts +3 -1
  43. package/dist/cli/host-managers.d.ts.map +1 -1
  44. package/dist/cli/host-managers.js +7 -3
  45. package/dist/cli/host-managers.js.map +1 -1
  46. package/dist/cli/image-layers.d.ts.map +1 -1
  47. package/dist/cli/image-layers.js +5 -2
  48. package/dist/cli/image-layers.js.map +1 -1
  49. package/dist/cli/main.d.ts +5 -1
  50. package/dist/cli/main.d.ts.map +1 -1
  51. package/dist/cli/main.js +97 -34
  52. package/dist/cli/main.js.map +1 -1
  53. package/dist/cli/pack-publication.d.ts +2 -2
  54. package/dist/cli/pack-publication.d.ts.map +1 -1
  55. package/dist/cli/pack-publication.js +3 -3
  56. package/dist/cli/pack-publication.js.map +1 -1
  57. package/dist/cli/package-pack.d.ts +1 -1
  58. package/dist/cli/package-pack.d.ts.map +1 -1
  59. package/dist/cli/package-pack.js +7 -4
  60. package/dist/cli/package-pack.js.map +1 -1
  61. package/dist/cli/package-packs.d.ts +1 -0
  62. package/dist/cli/package-packs.d.ts.map +1 -1
  63. package/dist/cli/package-packs.js +84 -14
  64. package/dist/cli/package-packs.js.map +1 -1
  65. package/dist/cli/plan-tarballs.d.ts +1 -0
  66. package/dist/cli/plan-tarballs.d.ts.map +1 -1
  67. package/dist/cli/plan-tarballs.js +6 -3
  68. package/dist/cli/plan-tarballs.js.map +1 -1
  69. package/dist/cli/preparation-memory.d.ts +17 -0
  70. package/dist/cli/preparation-memory.d.ts.map +1 -0
  71. package/dist/cli/preparation-memory.js +367 -0
  72. package/dist/cli/preparation-memory.js.map +1 -0
  73. package/dist/cli/project-build.d.ts +1 -0
  74. package/dist/cli/project-build.d.ts.map +1 -1
  75. package/dist/cli/project-build.js +100 -71
  76. package/dist/cli/project-build.js.map +1 -1
  77. package/dist/cli/provision-catalog.d.ts +49 -0
  78. package/dist/cli/provision-catalog.d.ts.map +1 -0
  79. package/dist/cli/provision-catalog.js +72 -0
  80. package/dist/cli/provision-catalog.js.map +1 -0
  81. package/dist/cli/provision-demand.d.ts +45 -0
  82. package/dist/cli/provision-demand.d.ts.map +1 -0
  83. package/dist/cli/provision-demand.js +208 -0
  84. package/dist/cli/provision-demand.js.map +1 -0
  85. package/dist/cli/rolldown-binding.d.ts +1 -1
  86. package/dist/cli/rolldown-binding.d.ts.map +1 -1
  87. package/dist/cli/rolldown-binding.js +8 -4
  88. package/dist/cli/rolldown-binding.js.map +1 -1
  89. package/dist/cli/serve.d.ts +3 -0
  90. package/dist/cli/serve.d.ts.map +1 -1
  91. package/dist/cli/serve.js +9 -2
  92. package/dist/cli/serve.js.map +1 -1
  93. package/dist/index.d.ts +2 -0
  94. package/dist/index.d.ts.map +1 -1
  95. package/dist/index.js +75 -31
  96. package/dist/index.js.map +1 -1
  97. package/dist/origin-reset.d.ts +4 -0
  98. package/dist/origin-reset.d.ts.map +1 -0
  99. package/dist/origin-reset.js +76 -0
  100. package/dist/origin-reset.js.map +1 -0
  101. package/dist/program-dom.d.ts +2 -0
  102. package/dist/program-dom.d.ts.map +1 -1
  103. package/dist/program-dom.js +11 -1
  104. package/dist/program-dom.js.map +1 -1
  105. package/dist/program-types.d.ts +2 -0
  106. package/dist/program-types.d.ts.map +1 -1
  107. package/dist/shell/assets/browser-opfs-filesystem-worker-CmF6UKMW.js +3 -0
  108. package/dist/shell/assets/browser-sandbox-bridge-C8nlSsT2.js +237 -0
  109. package/dist/shell/assets/{filesystem-host-DJbFuokb.js → filesystem-host-BzPlXSri.js} +1 -1
  110. package/dist/shell/assets/filesystem-host-Pq9IHKRx.js +3 -0
  111. package/dist/shell/assets/filesystem-worker-CC3pSXUP.js +5 -0
  112. package/dist/shell/assets/{fork-worker-BXY2kfdX.js → fork-worker-4YKQ4KTo.js} +1 -1
  113. package/dist/shell/assets/{node-execution-worker-7e8e0c5321ca0d10.js → node-execution-worker-3ddf5efbaa427e9d.js} +8 -8
  114. package/dist/shell/assets/{sandbox-bMeKqKBn.js → sandbox-mhFzIWaQ.js} +1 -1
  115. package/dist/shell/assets/{shell-DLIQ6jHu.js → shell-BZbhxnju.js} +763 -757
  116. package/dist/shell/assets/worker-BmHEnCyv.js +816 -0
  117. package/dist/shell/assets/{worker-program-worker-B4OcKVtV.js → worker-program-worker-DueMwljE.js} +10 -10
  118. package/dist/shell/brand/fonts/Geist-Variable.woff2 +0 -0
  119. package/dist/shell/brand/fonts/GeistMono-Variable.woff2 +0 -0
  120. package/dist/shell/brand/fonts/InstrumentSerif-Italic.woff2 +0 -0
  121. package/dist/shell/brand/fonts/InstrumentSerif-Regular.woff2 +0 -0
  122. package/dist/shell/brand/icons/app-window.svg +1 -0
  123. package/dist/shell/brand/icons/at-sign.svg +1 -0
  124. package/dist/shell/brand/icons/box.svg +1 -0
  125. package/dist/shell/brand/icons/chevron-right.svg +1 -0
  126. package/dist/shell/brand/icons/folder.svg +1 -0
  127. package/dist/shell/brand/icons/info.svg +1 -0
  128. package/dist/shell/brand/icons/key-round.svg +1 -0
  129. package/dist/shell/brand/icons/link.svg +1 -0
  130. package/dist/shell/brand/icons/monitor.svg +1 -0
  131. package/dist/shell/brand/icons/plus.svg +1 -0
  132. package/dist/shell/brand/icons/rotate-ccw.svg +1 -0
  133. package/dist/shell/brand/icons/share-2.svg +1 -0
  134. package/dist/shell/brand/icons/square-arrow-out-up-right.svg +1 -0
  135. package/dist/shell/brand/icons/terminal.svg +1 -0
  136. package/dist/shell/brand/icons/x.svg +1 -0
  137. package/dist/shell/brand/substrate.svg +1 -0
  138. package/dist/shell/brand/tokens.css +211 -0
  139. package/dist/shell/brand/wordmark.svg +1 -0
  140. package/dist/shell/index.html +5 -3
  141. package/dist/shell/node-execution-worker.js +16 -13
  142. package/dist/shell/node-host.html +2 -0
  143. package/dist/shell/python-execution-worker.js +15 -12
  144. package/dist/shell/python-host.html +2 -0
  145. package/dist/shell/python-runtime-snapshot.bin +0 -0
  146. package/dist/shell/python-runtime-snapshot.json +1 -1
  147. package/dist/shell/sandbox.html +4 -2
  148. package/dist/toolbar-styles.generated.d.ts +1 -1
  149. package/dist/toolbar-styles.generated.d.ts.map +1 -1
  150. package/dist/toolbar-styles.generated.js +1 -1
  151. package/dist/toolbar-styles.generated.js.map +1 -1
  152. package/dist/toolbar.d.ts.map +1 -1
  153. package/dist/toolbar.js +3 -1
  154. package/dist/toolbar.js.map +1 -1
  155. package/package.json +1 -1
  156. package/dist/shell/assets/browser-opfs-filesystem-worker-k2CPzPBU.js +0 -3
  157. package/dist/shell/assets/browser-sandbox-bridge-BJbQoc4f.js +0 -237
  158. package/dist/shell/assets/filesystem-host-yMcJuvmT.js +0 -3
  159. package/dist/shell/assets/filesystem-worker-BbsBhZ9p.js +0 -5
  160. package/dist/shell/assets/worker-Ce8bBwSJ.js +0 -816
@@ -0,0 +1,237 @@
1
+ import{p as lt}from"./page-workers-BUcWBF51.js";const ps=r=>({code:-32601,message:`'${r}' wasn't found`,data:"AlmostCDP does not implement this command for the connected surface"}),ws=r=>({code:-32602,message:r}),ms={fromSurface:r=>r,toSurface:r=>r},ke=(r,e)=>e&&r.fromSurface(e),ht=r=>{if(r!==void 0)try{return new URL(r).hostname}catch{return}},Ht=(r,e)=>{const t=e.startsWith("."),n=t?e.slice(1):e,s=r.hostToSurface?r.hostToSurface(n):ht(r.toSurface(`http://${n}/`));return s===void 0?void 0:`${t?".":""}${s}`},Wt=(r,e)=>{const t=e.startsWith("."),n=t?e.slice(1):e,s=r.hostFromSurface?r.hostFromSurface(n):ht(r.fromSurface(`http://${n}/`))??n;return`${t?".":""}${s}`},ys=(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 Dt{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 qt=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},He=r=>{let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(e)},We="almostcdpFanOut",Ut=r=>typeof r=="string"&&r?r[0].toUpperCase()+r.slice(1).toLowerCase():void 0;function gs({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:Wt(e,d.domain?`.${d.domain.replace(/^\./,"")}`:n()),expires:f,httpOnly:!1,name:d.name,path:d.path??"/",priority:"Medium",...d.sameSite?{sameSite:Ut(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=Ht(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[We]!==!0&&h.length!==f.length)throw D(d,`this surface serves ${n()}, not every cookie's domain`);return l[We]===!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 zt="almostcdpDownloadPolicy";function bs({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:He(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:He(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[zt]!==!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 Vt="almostcdpFiles",ye=r=>r?.localName==="input"&&r.type==="file";function vs({target:r,sendEvent:e,frameId:t},n){const s=new Dt,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(qt(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[Vt],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 Gt={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"},Xt={"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"},Ss=r=>{const e=Xt[r]??Gt[r.split(".")[0]];return e===void 0?void 0:{code:-32e3,message:`${r} is unavailable on a DOM surface: ${e}`}};class ks 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 Es(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 Qt(r,e,t){ee(r,e)===t&&r.unregisterServer(e)}function ut(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 Kt;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=typeof n=="number"?n:Number(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(Jt(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 Jt(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 Kt 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 ft(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 pt(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 Ts(r,e=globalThis.location?.origin){const t=r;return t.storeOrigin===void 0||t.storeOrigin===e?t.projectId:void 0}async function Yt(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 Zt(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 Yt(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 er=4096,tr=180,rr=3e3,De=1,qe=400*24*60*60*1e3,Ue=3e3,sr=/^\d{1,3}(?:\.\d{1,3}){3}$/u,nr=/^(?: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 or(r){return sr.test(r)||r.startsWith("[")||r.includes(":")}function K(r,e){return r===e?!0:!or(r)&&r.endsWith(`.${e}`)}function ir(r){const e=r.split(/[?#]/u,1)[0];if(!e.startsWith("/"))return"/";const t=e.lastIndexOf("/");return t===0?"/":e.slice(0,t)}function ze(r,e){const t=r.split(/[?#]/u,1)[0]||"/";return t===e?!0:t.startsWith(e)?e.endsWith("/")||t[e.length]==="/":!1}const ar=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];function cr(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=ar.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 dr(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=cr(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 lr(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 nr.test(Te(r))}const Pe=new WeakMap;class hr{cookies=[];now;listeners=new Set;lastCreation=0;async dispose(){this.listeners.clear(),await Pe.get(this)?.(),Pe.delete(this)}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 lr(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:De,cookies:this.list()}}restore(e){const t=e;if(!t||t.version!==De||!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=dr(t);if(!s||s.name.length+s.value.length>er)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+qe&&(c=a+qe);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??ir(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))&&ze(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))&&ze(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),tr),t(this.cookies,rr)}changed(){for(const e of this.listeners)try{e()}catch(t){console.error("Cookie jar listener failed.",t)}}}const ur="browser-substrate-cookies",V="jars";function fr(){return new Promise((r,e)=>{const t=setTimeout(()=>e(new Error(`The cookie jar's database did not open in ${Ue} ms.`)),Ue),n=indexedDB.open(ur,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 Ps(r,e={}){const t=new hr(e);let n;try{n=await fr();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 Pe.set(t,async()=>{try{await s}finally{n?.close()}}),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 xs(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 As{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 xe=65536,Ve=16*1024*1024,pr=15e3;class Cs{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=pr){if(this.bridge=e,this.drainTimeoutMs=t,!Number.isSafeInteger(t)||t<1)throw new Error("Invalid Host Fetch-service drain timeout.");this.stopObservingPorts=ut(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??Ve;if(!Number.isSafeInteger(n)||n<1||n>Ve)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:xe},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{Qt(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 wr="supercode-browser-agent",L="projects",Le=1;async function Ge(){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(wr,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 wt(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 Ae(r){if(!r||typeof r!="object"||Array.isArray(r))return;const e=r;return e.storageVersion===Le&&typeof e.checksum=="string"?e.checksum:void 0}async function mr(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&&Ae(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 yr(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 gr(...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 mt(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 br(r){return{storageVersion:Le,savedAt:Date.now(),checksum:await mt(JSON.stringify(r)),payload:r}}async function Xe(r,e){if(r&&typeof r=="object"&&!Array.isArray(r)&&r.storageVersion===Le){const t=r;if(typeof t.checksum!="string"||t.payload===void 0||await mt(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 vr(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 Rs(){if(typeof navigator>"u"||!navigator.storage)return{persisted:!1};const r=await Ge();return r.persisted?r:(await navigator.storage.persist?.().catch(()=>!1),Ge())}class Sr{worker;pending=new Map;nextRequest=1;constructor(){this.worker=lt(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:Qe(n?.[0]),backup:Qe(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 Qe(r){return r===void 0?void 0:JSON.parse(r)}const yt=2019846480,le=6,C=6,q=3,re=0,G=1,$=2,gt=3,bt=4,vt=5,St=0,kt=1,Et=2,se=1,Tt=2,Pt=4,ne=32,Ce=3,Re=["file","directory","symlink"],kr=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,Er=new TextEncoder,Tr=new TextDecoder;function xt(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 Os(r,e){const t=[...r.keys()];for(const k of t)if(kr.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,Er.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=Oe(d+s*C*4,8),f=l+s*q*8,h=f+u*4,p=h+c*4,w=new SharedArrayBuffer(Oe(p+a,8));new Uint32Array(w,0,le).set([yt,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|Re.indexOf(B.type)<<Ce,B.pack&&(F|=Pt),y[A+gt]=B.mode;const O=k*q;g[O+St]=B.mtimeMs,g[O+kt]=B.offset,g[O+Et]=B.length}const z=e.get(T);if(z){F|=Tt,y[A+bt]=R,y[A+vt]=z.size;for(const O of z){const Ne=n.get(`${T}/${O}`);if(Ne===void 0)throw new Error(`The store's children name ${T}/${O}, which its index does not hold.`);S[R++]=Ne}}y[A+$]=F;let J=xt(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 Oe(r,e){return Math.ceil(r/e)*e}class Ms{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(e){const t=new Uint32Array(e,0,le);if(t[0]!==yt)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=Oe(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=xt(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:Re[n>>>Ce&3],mode:this.records[t+gt],mtimeMs:this.numbers[s+St],offset:this.numbers[s+kt],length:this.numbers[s+Et]};return n&Pt&&(o.pack="packages"),o}typeAt(e){const t=this.records[e*C+$];return t&se?Re[t>>>Ce&3]:void 0}hasEntry(e){return(this.records[e*C+$]&se)!==0}childNames(e){const t=e*C;if(!(this.records[t+$]&Tt))return;const n=this.records[t+bt],s=this.records[t+G]+1,o=[];for(let i=0;i<this.records[t+vt];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 Tr.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 Pr(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 _s{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&&Pr(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 Fs{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 Ls="/opt/.browser-packs",Bs="/opt/.tabnode";new TextEncoder;new TextDecoder("utf-8",{fatal:!0});const Je="host-tree.",Is=["/workspace","/home","/opt"],Me=1e6,he=1024*1024*1024,xr=4096,Ke={readPair:wt,rotate:mr,replace:yr,delete:gr};let _e=Promise.resolve();const Ye=new Map;let Ze;async function Ar(){if(typeof Worker>"u"||typeof navigator>"u"||!navigator.storage||!("getDirectory"in navigator.storage))return{backend:"indexeddb",storage:Ke};const r=new Sr;try{const{primary:e,backup:t}=Ie("default"),n=await r.readPair(e,t);if(n.primary===void 0&&n.backup===void 0){const s=await wt(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:Ke}}}async function U(){return Ze??=Ar(),Ze}async function js(r){const{storage:e}=await U();return(await e.readPair(r,`${r}-backup`)).primary}async function $s(r,e){const{storage:t}=await U();await t.replace(r,e)}async function Ns(r){const{storage:e}=await U();await e.delete(r,`${r}-backup`)}async function Hs(){return(await U()).backend}function Cr(r){const e=_e.then(r,r);return _e=e.then(()=>{},()=>{}),e}function we(r){return typeof r!="string"||r.length===0||r.length>xr||!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>Me)throw new Error(`Saved browser project exceeds ${Me} 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"?ft(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 At(e),r}function At(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 Ws(r,e={}){await _e;const t=Be(e.projectId),n=Ie(t),s=Ct(t),{storage:o}=await U(),i=await o.readPair(n.primary,n.backup);if(i.primary!==void 0)try{const c=await Xe(i.primary,ue);return s.known=!0,s.revision=Ae(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 Xe(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=Ae(i.backup),a}async function Rr(r,e={}){const t=e.root??"/";if(!we(t))throw new Error("Browser project root is invalid.");const n=Be(e.projectId),s=Ie(n),o=Ct(n),i=e.excludePaths?new Set(e.excludePaths):void 0;return Cr(async()=>{const a=ue(await Zt(r,t,{consistent:!0,...i?{excludePaths:i}:{}})),{storage:c}=await U(),u=await br(a);await vr(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 Be(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(Je))throw new Error(`Browser projectId may not begin ${Je}: the origin's installed trees are named so.`);return r}function Ie(r){return{primary:r,backup:`${r}-backup`,conflict:`${r}-conflict`}}function Ct(r){let e=Ye.get(r);return e||(e={known:!1,revision:void 0},Ye.set(r,e)),e}function Ds(r,e,t="/"){const n=ue(e).files;Ot(r,n,t,s=>pt(s.content||""))}function Rt(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>Me||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 At(e.files),e}function qs(r,e,t="/"){const{files:n,pack:s}=Rt(e);Ot(r,n,t,o=>new Uint8Array(s,o.offset??0,o.length??0).slice())}function Ot(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)=>et(i.path)-et(a.path)||i.path.localeCompare(a.path));r.existsSync(t)?Mt(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 Mt(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()?(Mt(r,s,t),r.readdirSync(s).length===0&&r.rmdirSync(s)):r.unlinkSync(s)}}function Us(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 Rr(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 et(r){let e=1;for(let t=0;t<r.length;t+=1)r.charCodeAt(t)===47&&(e+=1);return e}async function Or(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 Mr(r){return typeof r.readFileSync=="function"}class _t{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=lt(new Worker(new URL("/assets/browser-opfs-filesystem-worker-CmF6UKMW.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=Be(n.projectId),i=new _t(e,s,t);try{const a=await i.request({operation:"initialize",projectId:o});return{store:i,...a.initialized&&a.snapshot?{packed:Rt(a.snapshot)}:{}}}catch(a){throw i.closeTransport(a),a}}activate(){this.throwIfFailed(),this.active=!0}async replaceFromMemory(){this.throwIfFailed();const e=tt(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(tt(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 tt(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 zs(r){return"bytes"in r?r.bytes:pt(r.base64)}function Vs(r){return"bytes"in r?H(r.bytes):r.base64}function _r(r){return"bytes"in r?r.bytes.byteLength:ft(r.base64)}const Fr=3e4;class Gs{endpoints=new Map;register(e,t){if(Ft(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 rt=32*1024*1024;class Lr{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(Ft(t),!this.registeredPort(t))throw new Error("No virtual server is listening on that WebSocket port.");if(!Br(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"||!Ir(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.")},Fr)};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,$r(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{st(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.");st(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&&(jr(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 Ft(r){if(!Number.isSafeInteger(r)||r<1||r>65535)throw new Error("Invalid virtual WebSocket port.")}function Br(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 Ir(r){return r.length>0&&r.length<=128&&/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/u.test(r)}function st(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(rt/3)*4)throw new Error("Virtual WebSocket frame exceeds 32 MiB.");const e=r.kind==="text"?new TextEncoder().encode(r.text).byteLength:_r(r);if(e===void 0)throw new Error("Invalid virtual WebSocket binary frame.");if(e>rt)throw new Error("Virtual WebSocket frame exceeds 32 MiB.")}function jr(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 $r(r){return typeof r=="string"&&r.length<=255&&/^(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::[0-9]{1,5})?$/iu.test(r)}const Nr=1,nt=1024*1024;class Hr{revision;rules;constructor(e=[],t=[]){const n=new Map;for(const o of e){Lt(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()];Bt(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=je(e.method),n=$e(e.headerNames),s=e.credentialMode??"omit",o=e.profile??"browser-compatible",i=this.rules.filter(u=>Dr(u,e.program,e.url,t,n,s,o));if(i.length===0){if(s!=="omit"||o!=="browser-compatible")throw Vr("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=zr(i);return{transport:c.transport,profile:c.profile,credentialMode:c.credentialMode,ruleId:c.id,policyRevision:this.revision}}}function Wr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("HTTP transport policy must be an object.");const e=r;return Lt(e),e}async function Xs(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>nt)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>nt-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 Or(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(Wr(w))}return s}function Lt(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!==Nr)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.");Bt(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.");je(s.request.method),$e(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(je).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($e(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 je(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 $e(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 Dr(r,e,t,n,s,o,i){return r.program!==e||r.origin!==t.origin||r.credentialMode!==o||r.profile!==i||!Fe(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 Fe(r,e){if(r==="/")return!0;const t=r.endsWith("/")?r.slice(0,-1):r;return e===t||e.startsWith(`${t}/`)}function Bt(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||!qr(n.pathPrefix,s.pathPrefix)||!Ur(n.methods,s.methods))&&n.transport!==s.transport)throw new Error(`Conflicting HTTP transport rules overlap: ${n.id}, ${s.id}`)}}function qr(r,e){return Fe(r,e)||Fe(e,r)}function Ur(r,e){return r.length===0||e.length===0||r.some(t=>e.includes(t))}function zr(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 Vr(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 Qs{limits;grants=new Map;httpPolicy;egressListeners=new Set;egressRevision=1;world;constructor(e={}){this.world=e.world,this.limits=Object.freeze(Gr({...me,...e.limits})),this.httpPolicy=new Hr(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=Xr(e),n=at(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:Qr(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!It(e)||!jt(t)||!$t(s)?!1:this.world?this.world.allowsEgress(new URL(`https://${t}:${s}`)):this.grants.has(at({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 ot=new WeakMap;function Js(r,e){const t=ot.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=Mr(r)?e:{...e,maxFilesystemBytes:Number.POSITIVE_INFINITY};let s=Se(r);ct(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=Jr(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)?Nt(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)}ct({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}}),ot.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 it=new WeakMap;function Ks(r,e){const t=it.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)},it.set(r,e)}function Gr(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 Xr(r){if(!It(r.program)||!jt(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=>!$t(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 at(r){return`${r.program}\0${r.protocol}\0${r.hostname}\0${r.ports.join(",")}`}function Qr(r){try{return new URL(r).hostname}catch{return"an invalid target"}}function It(r){return/^[A-Za-z0-9._+-]{1,64}$/u.test(r)}function jt(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 $t(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 Nt(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=Nt(r,`${e==="/"?"":e}/${o}`);n+=i.entries,s+=i.bytes}return{entries:n,bytes:s}}function ct(r,e){if(r.entries>e.maxFilesystemEntries||r.bytes>e.maxFilesystemBytes)throw new DOMException("Initial browser filesystem exceeds its configured quota.","QuotaExceededError")}function Jr(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 Kr{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 Yr(r){const e=r?.type;return typeof e=="string"&&e.startsWith("websocket-")}const ie="supercode-sandbox-v1";function Zr(r,e){if(!r||typeof r!="object")return!1;const t=r;return t.channel===ie&&t.nonce===e&&typeof t.type=="string"}const es=16384,ts=128,rs=65536,Z=15e3,ss=15e3,ns=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]),os=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;function is(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||!ns.has(s.method)||!s.url||s.url.length>es||!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>ts)throw new Error("Virtual-server request has too many headers.");let c=0;for(const[u,d]of a){if(!os.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>rs)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 as(r,e){const n=Object.entries(r).find(([s])=>s.toLowerCase()===e.toLowerCase())?.[1];return Array.isArray(n)?n[0]:n}function cs(r,e,t){if(!as(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=ls(n),new TextEncoder().encode(n)}const dt="data-browser-runtime-loopback",ds="__browser_runtime_virtual_host";function ls(r){if(r.includes(dt))return r;const e=`<script ${dt}>(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(ds)};
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 Ys{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 Lr(t=>this.options.bridge.getServerPorts().includes(t),this.options.webSocketRegistry,this.options.webSocketConnector),this.socketRelay=new Kr(this.webSockets,t=>this.send(t),this.limits),this.stopObservingPorts=ut(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||!Zr(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=Yr(t.payload),o=!s&&hs(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=us(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=ss){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+xe))}}),m.value.byteLength===0));y+=xe);}}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=is(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=cs(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 hs(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 us(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{Yt as $,_t as A,Q as B,Mr as C,zt as D,qs as E,Vt as F,Ws as G,Ds as H,Us as I,Hs as J,Rs as K,Ge as L,ks as M,de as N,Fs as O,Es as P,ls as Q,Ys as R,Ms as S,ie as T,Ts as U,Zt as V,Os as W,_s as X,Is as Y,Ls as Z,Bs as _,ps as a,Xs as a0,Cs as a1,Ps as a2,xs as a3,Ve as a4,As as a5,cs as a6,D as a7,Dt as a8,ke as a9,ae as aa,fe as ab,vs as ac,bs as ad,gs as ae,ws as af,ms as ag,ys as ah,qt as b,He as c,We as d,ee as e,Ns as f,js as g,pt as h,H as i,Mt as j,M as k,Js as l,me as m,Lr as n,ut as o,rt as p,zs as q,Qt as r,Vs as s,Gs as t,Ss as u,_r as v,$s as w,Qs as x,Ks as y,Be as z};
@@ -1 +1 @@
1
- import{o as ie,a as ce,S as C,l as q,B as ae,W as fe,b as le,c as de,d as ue,e as he,F as a,f as U,g as v,h as ee,i as pe,j as te,k as me}from"./worker-program-worker-B4OcKVtV.js";let f=new C,H,Z,I,re;const g=new Map;let ge=1,_,G,P;const $=new TextEncoder,M=new TextDecoder;let L=!1,N,K=0;const k=[],F=new Set;let E,x,O=0,J=!1,z=!1,B=0,W,R=[],D=!1;const A=Symbol("retry");function Le(){W?.()}function Ie(){z=!1,B=0,W=void 0,L=!1,N=void 0,k.length=0,F.clear(),E=void 0,x=void 0,V=void 0,O=0,D=!1,f=new C,Z=void 0,g.clear()}function Pe(e){L=!0,N=new Int32Array(e),K=Atomics.load(N,0)}async function ke(e){const t={data:e};k.length=0,F.clear(),x=void 0,V=void 0,E=void 0,O=0,D=!1,z=!1,B=0,W=void 0,R=(e.privateRoots??[]).map(Se);{_=void 0,G=void 0;const o=await ie(e.layers);if(e.store){if(H=await ce({navigator:globalThis.navigator},e.store.projectId),!H)throw new Error("The project's store is not there to read.");f=C.fromStore(q(H,e.layers,o),e.snapshot)}else e.layers?f=C.fromStore(q(void 0,e.layers,o),e.snapshot):f=C.fromSnapshot(e.snapshot);P=(s,r)=>te(f,s,r);const n=t.data.fileLocks?new ae(t.data.fileLocks.channel):void 0;if(I=e.sharedPipes,re=e.memory,Z=new fe({...I?{descriptors:new de(new he(I.descriptions),I.table)}:{},filesystem:f,...e.filesystemPolicy?{filesystemPolicy:e.filesystemPolicy}:{},cwd:t.data.cwd,stdin:new Uint8Array,executablePath:t.data.executablePath,memory:()=>t.data.memory,emit:()=>-9n,descriptorMaximum:19999,pid:t.data.pid,...R.length?{privateRoots:R,privateTreeAdoptable:()=>g.size===0,onDiagnostic:s=>console.warn(s)}:{},...n&&t.data.fileLocks?{fileLocks:t.data.fileCoherence?new le(n,new ue(t.data.fileCoherence),f):n,lockOwner:t.data.fileLocks.owner}:{}}),t.data.updatePort){let s;const r=t.data.updatePort;r.start();const i=new Set,c=()=>{s&&clearTimeout(s),s=void 0;const d=f.takeChangedPaths();if(R.length>0)for(const m of d)R.some(w=>Ae(m,w))&&d.delete(m);if(d.size===0)return;for(const m of d)i.add(m);const u=[],S=[];for(const m of d){const w=f.writtenEntry(m,!0);w?u.push(w):S.push(m)}(u.length>0||S.length>0)&&(r.postMessage({type:"filesystem",patch:{files:u,removed:S}},u.flatMap(m=>m.bytes?[m.bytes.buffer]:[])),l=!0)};let l=!1;G=()=>{if(c(),!l)return;const d=new Int32Array(new SharedArrayBuffer(4));if(r.postMessage({type:"checkpoint",control:d.buffer}),Atomics.wait(d,0,0,3e4),Atomics.load(d,0)!==1)throw new Error("WALI filesystem spawn checkpoint failed.");l=!1};let p=!1,h=!1;if(_=()=>{h||(c(),O=0,h=!0,D=!0,r.postMessage({type:"finalized"}))},P=(d,u)=>{if(h)throw new Error("The WALI filesystem is finalized.");c(),p=!0;try{let S=u;if(u){const m=new Map(u.files.map(w=>[w.path,w]));for(const w of[...d.files.map(j=>j.path),...d.removed]){if(i.has(w))continue;const j=me(f,w);j?m.set(w,j):m.delete(w)}S={files:[...m.values()]}}te(f,d,S),f.takeChangedPaths(),r.postMessage({type:"imported",patch:d})}finally{p=!1}},L){x=c,W=()=>{z=!0,r.postMessage({type:"port-closed",taken:B})};const d=new SharedArrayBuffer(1<<20,{maxByteLength:1<<30});E={control:new Int32Array(d,0,2),buffer:d},r.postMessage({type:"mailbox",buffer:d,doorbell:N.buffer}),V=u=>r.postMessage({type:"import-error",message:u instanceof Error?u.message:String(u)})}r.onmessage=d=>{if(!(d.data.type!=="import"||h||z)){B=d.data.sequence??B;try{P(d.data.patch,d.data.base)}catch(u){r.postMessage({type:"import-error",message:u instanceof Error?u.message:String(u)})}}},f.setMutationHandler(()=>{if(!(p||h)){if(L){O===0&&(O=performance.now());return}s??=setTimeout(c,0)}})}}}function ye(e){const t=new Int32Array(e.control),o=new Uint8Array(e.payload),n={process:e.process??0};if(k.push({control:t,payload:o,state:n}),e.releasePort){const s=e.releasePort;s.onmessage=()=>{g.get(n.process)?.descriptors.descriptors.exit(),g.delete(n.process),s.postMessage(!0),s.close()},s.start()}if(n.process!==0&&e.sharedPipes){const s=g.get(n.process).descriptors.descriptors;s.sharedEntries=new Int32Array(e.sharedPipes.table),s.entries.forEach((r,i)=>{r&&Atomics.store(s.sharedEntries,i,r.description)})}return e.port.onmessage=s=>{if(typeof s.data!="number"&&"kind"in s.data){ye({...s.data,process:s.data.process??n.process});return}if(typeof s.data!="number"){const r=g.get(n.process);if(!r)throw new Error("Unknown inherited descriptor table");r.memory=s.data.memory;return}we(t,o,n,s.data)},e.port.start(),k[k.length-1]}async function we(e,t,o,n){if(Atomics.load(e,0)!==n)return;let s=-38,r=new Uint8Array;try{const i=Atomics.load(e,1);if(i===a.SyscallBinary){const u=ne(t,o);if(u===A)return;const S=BigInt(u instanceof Promise?await u:u);if(Atomics.compareExchange(e,0,n,-n)!==n)return;(o.view??=new DataView(t.buffer,t.byteOffset,t.byteLength)).setBigInt64(0,S,!0),Atomics.store(e,2,0),Atomics.store(e,4,8),Atomics.store(e,0,n+1),Atomics.notify(e,0);return}const c=oe(i,t,o);if(c){if(c.output.byteLength>t.byteLength)throw Object.assign(new Error("EMSGSIZE"),{code:"EMSGSIZE"});if(Atomics.compareExchange(e,0,n,-n)!==n)return;t.set(c.output),Atomics.store(e,2,c.result),Atomics.store(e,4,c.output.byteLength),Atomics.store(e,0,n+1),Atomics.notify(e,0);return}const l=Atomics.load(e,3),p=l>0?JSON.parse(M.decode(t.slice(0,l))):{},h=se(i,p,o);if(h===A)return;const d=h instanceof Promise?await h:h;r=d===void 0?new Uint8Array:$.encode(JSON.stringify(d)),s=0}catch(i){s=Y(i)}r.byteLength>t.byteLength&&(s=-90,r=new Uint8Array),Atomics.compareExchange(e,0,n,-n)===n&&(r.byteLength>0&&t.set(r),Atomics.store(e,2,s),Atomics.store(e,4,r.byteLength),Atomics.store(e,0,n+1),Atomics.notify(e,0))}function T(){return Z}function se(e,t,o){const n=o.process===0?T():g.get(o.process)?.descriptors;if(e===a.GetCwd)return n?.currentWorkingDirectory();if(e===a.CopyForExec||e===a.CopyForFork){if(!n)throw new Error("Missing parent descriptor table");const r={descriptors:n[e===a.CopyForFork?"copyForFork":"copyForExec"](()=>{if(!r.memory)throw new Error("Child memory is not attached");return r.memory},Array.isArray(t.stdio)?t.stdio.map(y):void 0)},i=ge++;return g.set(i,r),{process:i}}if(e===a.CloseProcess){n?.descriptors.exit(),o.process!==0&&g.delete(o.process);return}const s=()=>b(t.path);if(e===a.PrepareSpawn){G?.();return}if(e===a.ImportPeerPatch){P(t.patch);return}if(e===a.Exists)return f.existsSync(s());if(e===a.Stat||e===a.Lstat){const r=e===a.Lstat?f.lstatSync(s()):f.statSync(s());return{file:r.isFile(),directory:r.isDirectory(),symbolicLink:r.isSymbolicLink?.(),size:r.size,mode:r.mode,mtimeMs:r.mtimeMs,atimeMs:r.atimeMs,ctimeMs:r.ctimeMs,nlink:r.nlink,uid:r.uid,gid:r.gid,dev:r.dev,ino:r.ino,rdev:r.rdev,blksize:r.blksize,blocks:r.blocks}}if(e===a.ReadFile)return{content:U(f.readFileSync(s()))};if(e===a.WriteFile){f.writeFileSync(s(),v(b(t.content)));return}if(e===a.ReadRange){const r=y(t.offset),i=y(t.length),c=f.readRangeSync?f.readRangeSync(s(),r,i):f.readFileSync(s()).subarray(r,r+i);return{content:U(c)}}if(e===a.WriteRange){const r=y(t.offset),i=v(b(t.content));if(f.writeRangeSync)f.writeRangeSync(s(),r,i);else{const c=f.existsSync(s())?f.readFileSync(s()):new Uint8Array,l=new Uint8Array(Math.max(c.byteLength,r+i.byteLength));l.set(c),l.set(i,r),f.writeFileSync(s(),l)}return}if(e===a.Mkdir){f.mkdirSync(s(),{recursive:t.recursive===!0});return}if(e===a.Readdir)return f.readdirSync(s());if(e===a.Unlink){f.unlinkSync(s());return}if(e===a.Rmdir){f.rmdirSync(s());return}if(e===a.Rename){f.renameSync(b(t.from),b(t.to));return}if(e===a.Snapshot)return f.toSnapshot();if(e===a.SnapshotSize||e===a.FinalSnapshotSize)return e===a.FinalSnapshotSize&&_?.(),o.snapshot=$.encode(JSON.stringify(f.toSnapshot())),{length:o.snapshot.byteLength};if(e===a.SnapshotChunk){const r=y(t.offset),i=y(t.length);if(!o.snapshot||r<0||i<0||i>ee||r+i>o.snapshot.byteLength)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});const c=U(o.snapshot.subarray(r,r+i));return r+i===o.snapshot.byteLength&&delete o.snapshot,{content:c}}if(e===a.ReplaceSnapshot){f.replaceSnapshot(t.snapshot);return}if(e===a.ReplaceSnapshotStart||e===a.ImportPeerPatchStart){const r=y(t.length);if(r<=0||r>256*1024*1024)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});o.replacement={bytes:new Uint8Array(r),offset:0,peerPatch:e===a.ImportPeerPatchStart};return}if(e===a.ReplaceSnapshotChunk||e===a.ImportPeerPatchChunk){const r=y(t.offset),i=v(b(t.content)),c=o.replacement;if(!c||c.peerPatch!==(e===a.ImportPeerPatchChunk)||r!==c.offset||i.byteLength>ee||r+i.byteLength>c.bytes.byteLength)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});if(c.bytes.set(i,r),c.offset+=i.byteLength,c.offset===c.bytes.byteLength){delete o.replacement;const l=JSON.parse(M.decode(c.bytes));c.peerPatch?P(l):f.replaceSnapshot(l)}return}if(e===a.Syscall){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const r=b(t.name),i=X(o,n)[r];if(!i)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});const c=Array.isArray(t.args)?t.args.map(p=>BigInt(b(p))):[],l=Q(r,i,c);return l===A?A:l instanceof Promise?l.then(p=>({result:String(p)})):{result:String(l)}}if(e===a.ReadForMapping){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const r=n.readForMapping(y(t.fd),y(t.offset),y(t.length));return r?{content:U(r)}:{}}if(e===a.MappingPath){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const r=n.mappingPath(y(t.fd));return r?{path:r}:{}}if(e===a.WriteForMapping){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});return{written:n.writeForMapping(b(t.path),y(t.offset),v(b(t.content)))}}throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"})}function X(e,t){const o=t.descriptors,n=e.handlers;if(n&&n.table===t&&n.entries===o.sharedEntries.buffer)return n.imports;const s=I&&new pe(()=>e.process===0?re:g.get(e.process).memory,{...I,table:o.sharedEntries.buffer},o),r=s?s.imports(t.imports()):t.imports();return e.handlers={table:t,entries:o.sharedEntries.buffer,imports:r},r}function ne(e,t){const o=t.process===0?T():g.get(t.process)?.descriptors;if(!o)throw Object.assign(new Error("EIO"),{code:"EIO"});const n=t.view??=new DataView(e.buffer,e.byteOffset,e.byteLength),s=e[0],r=M.decode(e.slice(8+s*8,8+s*8+e[1])),i=[];for(let l=0;l<s;l+=1)i.push(n.getBigInt64(8+l*8,!0));const c=X(t,o)[r];if(!c)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});return Q(r,c,i)}function Q(e,t,o){let n;if(e==="SYS_flock"){const s=Number(o[1]??0);(s&4)===0&&(s&8)===0&&(n=[...o],n[1]=BigInt(s|4))}else if(e==="SYS_fcntl"){const s=Number(o[1]??0);(s===7||s===38)&&(n=[...o],n[1]=BigInt(s===7?6:37))}if(!n)return t(...o)??0;if(L){const s=t(...n)??0;return BigInt(s)===-11n?A:s}return be(t,n)}async function be(e,t){for(;;){const o=e(...t)??0;if(BigInt(o)!==-11n)return o;await new Promise(n=>setTimeout(n,5))}}function b(e){if(typeof e!="string")throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});return e}function y(e){if(typeof e!="number"||!Number.isSafeInteger(e))throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});return e}function Y(e){const t=e instanceof Error?e.message:String(e),o=typeof e=="object"&&e!==null&&"code"in e?String(e.code):/\b(E[A-Z]+)\b/u.exec(t)?.[1]??"EIO";return-({ENOENT:2,EBADF:9,EACCES:13,EEXIST:17,ENOTDIR:20,EISDIR:21,EINVAL:22,EMFILE:24,ENOSPC:28,ESPIPE:29,ERANGE:34,ENOSYS:38,ENOTEMPTY:39,EMSGSIZE:90}[o]??5)}function Ee(e){const{control:t,payload:o,state:n}=e,s=Atomics.load(t,0);if(s<=0||(s&1)===0)return!1;let r=-38,i=new Uint8Array,c,l;try{const p=Atomics.load(t,1);if(p===a.SyscallBinary){const h=ne(o,n);if(h===A)return F.add(e),!1;if(h instanceof Promise)throw new Error("EIO: an asynchronous syscall on the main thread");c=BigInt(h)}else if((l=oe(p,o,n))!==void 0)i=l.output;else{const h=Atomics.load(t,3),d=h>0?JSON.parse(M.decode(o.slice(0,h))):{},u=se(p,d,n);if(u===A)return F.add(e),!1;if(u instanceof Promise)throw new Error("EIO: an asynchronous operation on the main thread");i=u===void 0?new Uint8Array:$.encode(JSON.stringify(u))}r=l?.result??0}catch(p){r=Y(p),c=void 0}return F.delete(e),i.byteLength>o.byteLength&&(r=-90,i=new Uint8Array),Atomics.compareExchange(t,0,s,-s)!==s||(c!==void 0?((n.view??=new DataView(o.buffer,o.byteOffset,o.byteLength)).setBigInt64(0,c,!0),i=new Uint8Array(8)):i.byteLength>0&&o.set(i),Atomics.store(t,2,r),Atomics.store(t,4,c!==void 0?8:i.byteLength),Atomics.store(t,0,s+1),Atomics.notify(t,0)),!0}function Fe(){return L?Atomics.load(N,0)!==K||F.size>0:!1}function Ne(e=!1){if(!(!L||J)){J=!0;try{if(K=Atomics.load(N,0),E&&!D&&Atomics.load(E.control,0)===1)try{const t=Atomics.load(E.control,1),o=JSON.parse(M.decode(new Uint8Array(E.buffer,8,t).slice()));Atomics.store(E.control,0,0),o.type==="import"&&P(o.patch,o.base)}catch(t){Atomics.store(E.control,0,0),V?.(t)}for(const t of k)Ee(t);x&&O!==0&&e&&(O=0,x())}finally{J=!1}}}let V;function oe(e,t,o){if(e!==a.ReadForMappingBinary&&e!==a.WriteForMappingBinary)return;const n=o.process===0?T():g.get(o.process)?.descriptors;if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const s=o.view??=new DataView(t.buffer,t.byteOffset,t.byteLength);if(e===a.ReadForMappingBinary){const p=Math.min(s.getInt32(16,!0),t.byteLength),h=n.readForMapping(s.getInt32(0,!0),s.getFloat64(8,!0),p);return h?{result:0,output:h}:{result:1,output:new Uint8Array}}const r=s.getUint32(8,!0),i=s.getUint32(12,!0),c=M.decode(t.slice(16,16+r)),l=n.writeForMapping(c,s.getFloat64(0,!0),t.slice(16+r,16+r+i));return{result:0,output:new Uint8Array([l?1:0])}}function Se(e){return`/${e.split("/").filter(Boolean).join("/")}`}function Ae(e,t){return t==="/"||e===t||e.startsWith(`${t}/`)}function Me(e,t,o){try{const n=e.state,s=n.process===0?T():g.get(n.process)?.descriptors;if(!s)throw Object.assign(new Error("EIO"),{code:"EIO"});const r=X(n,s)[t];if(!r)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});const i=Q(t,r,o);if(i===A)return;if(i instanceof Promise)throw new Error("EIO: an asynchronous syscall on the main thread");return BigInt(i)}catch(n){return{failed:Y(n)}}}function Re(e){const t=e.state,o=t.process===0?T():g.get(t.process)?.descriptors;if(!o)throw Object.assign(new Error("EIO"),{code:"EIO"});const n=t.direct;if(n&&n.table===o)return n.handlers;const s={imports:o.imports(),errno:Y,owns:r=>o.ownsFile(r)};return t.direct={table:o,handlers:s},s}export{ye as attachChannel,Le as closeHostPort,Re as handlersNow,Pe as hostInThread,Fe as hostWaiting,ke as initializeHost,Ne as pumpHost,Ie as resetHost,Ee as serveNow,Me as syscallNow,Ae as underRoot};
1
+ import{o as ie,a as ce,S as C,l as q,B as ae,W as fe,b as le,c as de,d as ue,e as he,F as a,f as U,g as v,h as ee,i as pe,j as te,k as me}from"./worker-program-worker-DueMwljE.js";let f=new C,H,Z,I,re;const g=new Map;let ge=1,_,G,P;const $=new TextEncoder,M=new TextDecoder;let L=!1,N,K=0;const k=[],F=new Set;let E,x,O=0,J=!1,z=!1,B=0,W,R=[],D=!1;const A=Symbol("retry");function Le(){W?.()}function Ie(){z=!1,B=0,W=void 0,L=!1,N=void 0,k.length=0,F.clear(),E=void 0,x=void 0,V=void 0,O=0,D=!1,f=new C,Z=void 0,g.clear()}function Pe(e){L=!0,N=new Int32Array(e),K=Atomics.load(N,0)}async function ke(e){const t={data:e};k.length=0,F.clear(),x=void 0,V=void 0,E=void 0,O=0,D=!1,z=!1,B=0,W=void 0,R=(e.privateRoots??[]).map(Se);{_=void 0,G=void 0;const o=await ie(e.layers);if(e.store){if(H=await ce({navigator:globalThis.navigator},e.store.projectId),!H)throw new Error("The project's store is not there to read.");f=C.fromStore(q(H,e.layers,o),e.snapshot)}else e.layers?f=C.fromStore(q(void 0,e.layers,o),e.snapshot):f=C.fromSnapshot(e.snapshot);P=(s,r)=>te(f,s,r);const n=t.data.fileLocks?new ae(t.data.fileLocks.channel):void 0;if(I=e.sharedPipes,re=e.memory,Z=new fe({...I?{descriptors:new de(new he(I.descriptions),I.table)}:{},filesystem:f,...e.filesystemPolicy?{filesystemPolicy:e.filesystemPolicy}:{},cwd:t.data.cwd,stdin:new Uint8Array,executablePath:t.data.executablePath,memory:()=>t.data.memory,emit:()=>-9n,descriptorMaximum:19999,pid:t.data.pid,...R.length?{privateRoots:R,privateTreeAdoptable:()=>g.size===0,onDiagnostic:s=>console.warn(s)}:{},...n&&t.data.fileLocks?{fileLocks:t.data.fileCoherence?new le(n,new ue(t.data.fileCoherence),f):n,lockOwner:t.data.fileLocks.owner}:{}}),t.data.updatePort){let s;const r=t.data.updatePort;r.start();const i=new Set,c=()=>{s&&clearTimeout(s),s=void 0;const d=f.takeChangedPaths();if(R.length>0)for(const m of d)R.some(w=>Ae(m,w))&&d.delete(m);if(d.size===0)return;for(const m of d)i.add(m);const u=[],S=[];for(const m of d){const w=f.writtenEntry(m,!0);w?u.push(w):S.push(m)}(u.length>0||S.length>0)&&(r.postMessage({type:"filesystem",patch:{files:u,removed:S}},u.flatMap(m=>m.bytes?[m.bytes.buffer]:[])),l=!0)};let l=!1;G=()=>{if(c(),!l)return;const d=new Int32Array(new SharedArrayBuffer(4));if(r.postMessage({type:"checkpoint",control:d.buffer}),Atomics.wait(d,0,0,3e4),Atomics.load(d,0)!==1)throw new Error("WALI filesystem spawn checkpoint failed.");l=!1};let p=!1,h=!1;if(_=()=>{h||(c(),O=0,h=!0,D=!0,r.postMessage({type:"finalized"}))},P=(d,u)=>{if(h)throw new Error("The WALI filesystem is finalized.");c(),p=!0;try{let S=u;if(u){const m=new Map(u.files.map(w=>[w.path,w]));for(const w of[...d.files.map(j=>j.path),...d.removed]){if(i.has(w))continue;const j=me(f,w);j?m.set(w,j):m.delete(w)}S={files:[...m.values()]}}te(f,d,S),f.takeChangedPaths(),r.postMessage({type:"imported",patch:d})}finally{p=!1}},L){x=c,W=()=>{z=!0,r.postMessage({type:"port-closed",taken:B})};const d=new SharedArrayBuffer(1<<20,{maxByteLength:1<<30});E={control:new Int32Array(d,0,2),buffer:d},r.postMessage({type:"mailbox",buffer:d,doorbell:N.buffer}),V=u=>r.postMessage({type:"import-error",message:u instanceof Error?u.message:String(u)})}r.onmessage=d=>{if(!(d.data.type!=="import"||h||z)){B=d.data.sequence??B;try{P(d.data.patch,d.data.base)}catch(u){r.postMessage({type:"import-error",message:u instanceof Error?u.message:String(u)})}}},f.setMutationHandler(()=>{if(!(p||h)){if(L){O===0&&(O=performance.now());return}s??=setTimeout(c,0)}})}}}function ye(e){const t=new Int32Array(e.control),o=new Uint8Array(e.payload),n={process:e.process??0};if(k.push({control:t,payload:o,state:n}),e.releasePort){const s=e.releasePort;s.onmessage=()=>{g.get(n.process)?.descriptors.descriptors.exit(),g.delete(n.process),s.postMessage(!0),s.close()},s.start()}if(n.process!==0&&e.sharedPipes){const s=g.get(n.process).descriptors.descriptors;s.sharedEntries=new Int32Array(e.sharedPipes.table),s.entries.forEach((r,i)=>{r&&Atomics.store(s.sharedEntries,i,r.description)})}return e.port.onmessage=s=>{if(typeof s.data!="number"&&"kind"in s.data){ye({...s.data,process:s.data.process??n.process});return}if(typeof s.data!="number"){const r=g.get(n.process);if(!r)throw new Error("Unknown inherited descriptor table");r.memory=s.data.memory;return}we(t,o,n,s.data)},e.port.start(),k[k.length-1]}async function we(e,t,o,n){if(Atomics.load(e,0)!==n)return;let s=-38,r=new Uint8Array;try{const i=Atomics.load(e,1);if(i===a.SyscallBinary){const u=ne(t,o);if(u===A)return;const S=BigInt(u instanceof Promise?await u:u);if(Atomics.compareExchange(e,0,n,-n)!==n)return;(o.view??=new DataView(t.buffer,t.byteOffset,t.byteLength)).setBigInt64(0,S,!0),Atomics.store(e,2,0),Atomics.store(e,4,8),Atomics.store(e,0,n+1),Atomics.notify(e,0);return}const c=oe(i,t,o);if(c){if(c.output.byteLength>t.byteLength)throw Object.assign(new Error("EMSGSIZE"),{code:"EMSGSIZE"});if(Atomics.compareExchange(e,0,n,-n)!==n)return;t.set(c.output),Atomics.store(e,2,c.result),Atomics.store(e,4,c.output.byteLength),Atomics.store(e,0,n+1),Atomics.notify(e,0);return}const l=Atomics.load(e,3),p=l>0?JSON.parse(M.decode(t.slice(0,l))):{},h=se(i,p,o);if(h===A)return;const d=h instanceof Promise?await h:h;r=d===void 0?new Uint8Array:$.encode(JSON.stringify(d)),s=0}catch(i){s=Y(i)}r.byteLength>t.byteLength&&(s=-90,r=new Uint8Array),Atomics.compareExchange(e,0,n,-n)===n&&(r.byteLength>0&&t.set(r),Atomics.store(e,2,s),Atomics.store(e,4,r.byteLength),Atomics.store(e,0,n+1),Atomics.notify(e,0))}function T(){return Z}function se(e,t,o){const n=o.process===0?T():g.get(o.process)?.descriptors;if(e===a.GetCwd)return n?.currentWorkingDirectory();if(e===a.CopyForExec||e===a.CopyForFork){if(!n)throw new Error("Missing parent descriptor table");const r={descriptors:n[e===a.CopyForFork?"copyForFork":"copyForExec"](()=>{if(!r.memory)throw new Error("Child memory is not attached");return r.memory},Array.isArray(t.stdio)?t.stdio.map(y):void 0)},i=ge++;return g.set(i,r),{process:i}}if(e===a.CloseProcess){n?.descriptors.exit(),o.process!==0&&g.delete(o.process);return}const s=()=>b(t.path);if(e===a.PrepareSpawn){G?.();return}if(e===a.ImportPeerPatch){P(t.patch);return}if(e===a.Exists)return f.existsSync(s());if(e===a.Stat||e===a.Lstat){const r=e===a.Lstat?f.lstatSync(s()):f.statSync(s());return{file:r.isFile(),directory:r.isDirectory(),symbolicLink:r.isSymbolicLink?.(),size:r.size,mode:r.mode,mtimeMs:r.mtimeMs,atimeMs:r.atimeMs,ctimeMs:r.ctimeMs,nlink:r.nlink,uid:r.uid,gid:r.gid,dev:r.dev,ino:r.ino,rdev:r.rdev,blksize:r.blksize,blocks:r.blocks}}if(e===a.ReadFile)return{content:U(f.readFileSync(s()))};if(e===a.WriteFile){f.writeFileSync(s(),v(b(t.content)));return}if(e===a.ReadRange){const r=y(t.offset),i=y(t.length),c=f.readRangeSync?f.readRangeSync(s(),r,i):f.readFileSync(s()).subarray(r,r+i);return{content:U(c)}}if(e===a.WriteRange){const r=y(t.offset),i=v(b(t.content));if(f.writeRangeSync)f.writeRangeSync(s(),r,i);else{const c=f.existsSync(s())?f.readFileSync(s()):new Uint8Array,l=new Uint8Array(Math.max(c.byteLength,r+i.byteLength));l.set(c),l.set(i,r),f.writeFileSync(s(),l)}return}if(e===a.Mkdir){f.mkdirSync(s(),{recursive:t.recursive===!0});return}if(e===a.Readdir)return f.readdirSync(s());if(e===a.Unlink){f.unlinkSync(s());return}if(e===a.Rmdir){f.rmdirSync(s());return}if(e===a.Rename){f.renameSync(b(t.from),b(t.to));return}if(e===a.Snapshot)return f.toSnapshot();if(e===a.SnapshotSize||e===a.FinalSnapshotSize)return e===a.FinalSnapshotSize&&_?.(),o.snapshot=$.encode(JSON.stringify(f.toSnapshot())),{length:o.snapshot.byteLength};if(e===a.SnapshotChunk){const r=y(t.offset),i=y(t.length);if(!o.snapshot||r<0||i<0||i>ee||r+i>o.snapshot.byteLength)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});const c=U(o.snapshot.subarray(r,r+i));return r+i===o.snapshot.byteLength&&delete o.snapshot,{content:c}}if(e===a.ReplaceSnapshot){f.replaceSnapshot(t.snapshot);return}if(e===a.ReplaceSnapshotStart||e===a.ImportPeerPatchStart){const r=y(t.length);if(r<=0||r>256*1024*1024)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});o.replacement={bytes:new Uint8Array(r),offset:0,peerPatch:e===a.ImportPeerPatchStart};return}if(e===a.ReplaceSnapshotChunk||e===a.ImportPeerPatchChunk){const r=y(t.offset),i=v(b(t.content)),c=o.replacement;if(!c||c.peerPatch!==(e===a.ImportPeerPatchChunk)||r!==c.offset||i.byteLength>ee||r+i.byteLength>c.bytes.byteLength)throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});if(c.bytes.set(i,r),c.offset+=i.byteLength,c.offset===c.bytes.byteLength){delete o.replacement;const l=JSON.parse(M.decode(c.bytes));c.peerPatch?P(l):f.replaceSnapshot(l)}return}if(e===a.Syscall){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const r=b(t.name),i=X(o,n)[r];if(!i)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});const c=Array.isArray(t.args)?t.args.map(p=>BigInt(b(p))):[],l=Q(r,i,c);return l===A?A:l instanceof Promise?l.then(p=>({result:String(p)})):{result:String(l)}}if(e===a.ReadForMapping){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const r=n.readForMapping(y(t.fd),y(t.offset),y(t.length));return r?{content:U(r)}:{}}if(e===a.MappingPath){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const r=n.mappingPath(y(t.fd));return r?{path:r}:{}}if(e===a.WriteForMapping){if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});return{written:n.writeForMapping(b(t.path),y(t.offset),v(b(t.content)))}}throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"})}function X(e,t){const o=t.descriptors,n=e.handlers;if(n&&n.table===t&&n.entries===o.sharedEntries.buffer)return n.imports;const s=I&&new pe(()=>e.process===0?re:g.get(e.process).memory,{...I,table:o.sharedEntries.buffer},o),r=s?s.imports(t.imports()):t.imports();return e.handlers={table:t,entries:o.sharedEntries.buffer,imports:r},r}function ne(e,t){const o=t.process===0?T():g.get(t.process)?.descriptors;if(!o)throw Object.assign(new Error("EIO"),{code:"EIO"});const n=t.view??=new DataView(e.buffer,e.byteOffset,e.byteLength),s=e[0],r=M.decode(e.slice(8+s*8,8+s*8+e[1])),i=[];for(let l=0;l<s;l+=1)i.push(n.getBigInt64(8+l*8,!0));const c=X(t,o)[r];if(!c)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});return Q(r,c,i)}function Q(e,t,o){let n;if(e==="SYS_flock"){const s=Number(o[1]??0);(s&4)===0&&(s&8)===0&&(n=[...o],n[1]=BigInt(s|4))}else if(e==="SYS_fcntl"){const s=Number(o[1]??0);(s===7||s===38)&&(n=[...o],n[1]=BigInt(s===7?6:37))}if(!n)return t(...o)??0;if(L){const s=t(...n)??0;return BigInt(s)===-11n?A:s}return be(t,n)}async function be(e,t){for(;;){const o=e(...t)??0;if(BigInt(o)!==-11n)return o;await new Promise(n=>setTimeout(n,5))}}function b(e){if(typeof e!="string")throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});return e}function y(e){if(typeof e!="number"||!Number.isSafeInteger(e))throw Object.assign(new Error("EINVAL"),{code:"EINVAL"});return e}function Y(e){const t=e instanceof Error?e.message:String(e),o=typeof e=="object"&&e!==null&&"code"in e?String(e.code):/\b(E[A-Z]+)\b/u.exec(t)?.[1]??"EIO";return-({ENOENT:2,EBADF:9,EACCES:13,EEXIST:17,ENOTDIR:20,EISDIR:21,EINVAL:22,EMFILE:24,ENOSPC:28,ESPIPE:29,ERANGE:34,ENOSYS:38,ENOTEMPTY:39,EMSGSIZE:90}[o]??5)}function Ee(e){const{control:t,payload:o,state:n}=e,s=Atomics.load(t,0);if(s<=0||(s&1)===0)return!1;let r=-38,i=new Uint8Array,c,l;try{const p=Atomics.load(t,1);if(p===a.SyscallBinary){const h=ne(o,n);if(h===A)return F.add(e),!1;if(h instanceof Promise)throw new Error("EIO: an asynchronous syscall on the main thread");c=BigInt(h)}else if((l=oe(p,o,n))!==void 0)i=l.output;else{const h=Atomics.load(t,3),d=h>0?JSON.parse(M.decode(o.slice(0,h))):{},u=se(p,d,n);if(u===A)return F.add(e),!1;if(u instanceof Promise)throw new Error("EIO: an asynchronous operation on the main thread");i=u===void 0?new Uint8Array:$.encode(JSON.stringify(u))}r=l?.result??0}catch(p){r=Y(p),c=void 0}return F.delete(e),i.byteLength>o.byteLength&&(r=-90,i=new Uint8Array),Atomics.compareExchange(t,0,s,-s)!==s||(c!==void 0?((n.view??=new DataView(o.buffer,o.byteOffset,o.byteLength)).setBigInt64(0,c,!0),i=new Uint8Array(8)):i.byteLength>0&&o.set(i),Atomics.store(t,2,r),Atomics.store(t,4,c!==void 0?8:i.byteLength),Atomics.store(t,0,s+1),Atomics.notify(t,0)),!0}function Fe(){return L?Atomics.load(N,0)!==K||F.size>0:!1}function Ne(e=!1){if(!(!L||J)){J=!0;try{if(K=Atomics.load(N,0),E&&!D&&Atomics.load(E.control,0)===1)try{const t=Atomics.load(E.control,1),o=JSON.parse(M.decode(new Uint8Array(E.buffer,8,t).slice()));Atomics.store(E.control,0,0),o.type==="import"&&P(o.patch,o.base)}catch(t){Atomics.store(E.control,0,0),V?.(t)}for(const t of k)Ee(t);x&&O!==0&&e&&(O=0,x())}finally{J=!1}}}let V;function oe(e,t,o){if(e!==a.ReadForMappingBinary&&e!==a.WriteForMappingBinary)return;const n=o.process===0?T():g.get(o.process)?.descriptors;if(!n)throw Object.assign(new Error("EIO"),{code:"EIO"});const s=o.view??=new DataView(t.buffer,t.byteOffset,t.byteLength);if(e===a.ReadForMappingBinary){const p=Math.min(s.getInt32(16,!0),t.byteLength),h=n.readForMapping(s.getInt32(0,!0),s.getFloat64(8,!0),p);return h?{result:0,output:h}:{result:1,output:new Uint8Array}}const r=s.getUint32(8,!0),i=s.getUint32(12,!0),c=M.decode(t.slice(16,16+r)),l=n.writeForMapping(c,s.getFloat64(0,!0),t.slice(16+r,16+r+i));return{result:0,output:new Uint8Array([l?1:0])}}function Se(e){return`/${e.split("/").filter(Boolean).join("/")}`}function Ae(e,t){return t==="/"||e===t||e.startsWith(`${t}/`)}function Me(e,t,o){try{const n=e.state,s=n.process===0?T():g.get(n.process)?.descriptors;if(!s)throw Object.assign(new Error("EIO"),{code:"EIO"});const r=X(n,s)[t];if(!r)throw Object.assign(new Error("ENOSYS"),{code:"ENOSYS"});const i=Q(t,r,o);if(i===A)return;if(i instanceof Promise)throw new Error("EIO: an asynchronous syscall on the main thread");return BigInt(i)}catch(n){return{failed:Y(n)}}}function Re(e){const t=e.state,o=t.process===0?T():g.get(t.process)?.descriptors;if(!o)throw Object.assign(new Error("EIO"),{code:"EIO"});const n=t.direct;if(n&&n.table===o)return n.handlers;const s={imports:o.imports(),errno:Y,owns:r=>o.ownsFile(r)};return t.direct={table:o,handlers:s},s}export{ye as attachChannel,Le as closeHostPort,Re as handlersNow,Pe as hostInThread,Fe as hostWaiting,ke as initializeHost,Ne as pumpHost,Ie as resetHost,Ee as serveNow,Me as syscallNow,Ae as underRoot};