@phpsandbox/sdk 0.0.48 → 0.0.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  var PHPSandbox=(()=>{var Ue=Object.defineProperty;var Et=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var Tt=Object.prototype.hasOwnProperty;var Ze=r=>{throw TypeError(r)};var It=(r,e)=>{for(var t in e)Ue(r,t,{get:e[t],enumerable:!0})},Pt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of St(e))!Tt.call(r,i)&&i!==t&&Ue(r,i,{get:()=>e[i],enumerable:!(n=Et(e,i))||n.enumerable});return r};var Ct=r=>Pt(Ue({},"__esModule",{value:!0}),r);var Le=(r,e,t)=>e.has(r)||Ze("Cannot "+t);var le=(r,e,t)=>(Le(r,e,"read from private field"),t?t.call(r):e.get(r)),F=(r,e,t)=>e.has(r)?Ze("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Me=(r,e,t,n)=>(Le(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),E=(r,e,t)=>(Le(r,e,"access private method"),t);var yn={};It(yn,{ApiError:()=>Se,Beacon:()=>ke,BeaconConnectionError:()=>v,BeaconError:()=>_,BeaconTimeoutError:()=>ae,Client:()=>Ie,CommandError:()=>pe,ErrorEvent:()=>b,FileChangeType:()=>nt,FileType:()=>tt,Filesystem:()=>G,FilesystemError:()=>ue,FilesystemErrorType:()=>it,LspConnection:()=>he,Navigator:()=>O,NotebookApi:()=>Te,NotebookInitError:()=>Ee,NotebookInstance:()=>k,NotebookMail:()=>Ae,NotebookMailApi:()=>De,NotebookPreview:()=>Re,NotebookPreviewApi:()=>Ce,NotebookSecretApi:()=>Pe,NotebookSecrets:()=>Ne,NotebookState:()=>rt,NotebookUnavailableError:()=>x,PHPSandbox:()=>Je,PHPSandboxError:()=>Be,PromiseTimeoutError:()=>S,RateLimitError:()=>U,SendTimeoutError:()=>L,Transport:()=>B,createBeacon:()=>Xe,isBeaconSupported:()=>fn,notebookBuiltinServices:()=>st,notebookKnownServices:()=>Rt,once:()=>H,timeout:()=>$});var b=class extends Error{constructor(t,n,i={}){super(n);this.code=t;this.message=n;this.raw=i}},U=class extends b{constructor(e,t={}){super(429,e,t)}},Be=class extends b{};var et="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var f=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=et[t[r]&63];return e};var tt=(i=>(i[i.Unknown=0]="Unknown",i[i.File=1]="File",i[i.Directory=2]="Directory",i[i.SymbolicLink=64]="SymbolicLink",i))(tt||{}),nt=(n=>(n[n.UPDATED=1]="UPDATED",n[n.ADDED=2]="ADDED",n[n.DELETED=3]="DELETED",n))(nt||{}),it=(s=>(s.Unavailable="Unavailable",s.NoPermissions="NoPermissions",s.FileExists="FileExists",s.FileNotFound="FileNotFound",s.FileIsADirectory="FileIsADirectory",s.FileNotADirectory="FileNotADirectory",s))(it||{}),ue=class extends b{constructor(t,n){super(t.code,t.message);this.name=n}},Oe=class{constructor(e,t,n){this.path=e;this.okra=t;this.disposable=n}dispose(){this.okra.invoke("fs.unwatch",{path:this.path}),this.disposable.dispose()}},G=class{constructor(e){this.okra=e;this.watches=new Map;this.watchOkraConnection()}watchOkraConnection(){this.okra.onDidConnect(()=>{for(let{path:e,options:t,onDidChange:n}of this.watches.values())this.watch(e,t,n)})}info(e){return this.okra.invoke("fs.info",{path:e})}write(e,t){return this.okra.invoke("fs.write",{path:e,contents:t})}find(e,t={useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1}){return this.okra.invoke("fs.find",{query:e,options:Object.assign(t,{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1})})}search(e,t,n){e.id||(e.id=f());let i={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,s=async c=>{c===!1&&a.dispose(),n&&await Promise.resolve(n(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${o}`,s);return this.okra.invoke("fs.textSearch",{query:e,options:{...i,...t}}).finally(()=>a.dispose())}mkdir(e){return this.okra.invoke("fs.mkdir",{path:e})}move(e,t){return this.okra.invoke("fs.move",{from:e,to:t})}remove(e,t){return this.okra.invoke("fs.remove",{path:e,type:t})}async readFile(e,t){try{let n=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return n instanceof Uint8Array?n:typeof n=="string"?new TextEncoder().encode(n):n}catch(n){this.handleError(n)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(n=>this.handleError(n))}writeFile(e,t,n){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:n}).catch(i=>this.handleError(i))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,n){return this.okra.invoke("fs.rename",{from:e,to:t,options:n}).catch(i=>this.handleError(i))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(n=>this.handleError(n))}copy(e,t,n){return this.okra.invoke("fs.copy",{source:e,destination:t,options:n}).catch(i=>this.handleError(i))}readDirectory(e,t=[],n=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:n}).catch(i=>this.handleError(i))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,n){let i=this.okra.listen(`fs.watch.${e}`,n),o={dispose:()=>{i.dispose(),this.okra.invoke("fs.unwatch",{path:e})}},s=new Oe(e,this.okra,o);return this.watches.set(e,{options:t,path:e,onDidChange:n}),this.okra.invoke("fs.watch",{path:e,options:t}).then(()=>s)}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e,t,n){let i=f(),o=!!e,s=[];return this.okra.listen(`fs.download.${i}`,o?e:a=>{s.push(a)}),this.okra.invoke("fs.download",{id:i,exclude:t,include:n}).then(()=>new Blob(s,{type:"application/octet-stream"}))}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e instanceof b&&"name"in e.raw?new ue(e,e.raw.name):e}};var S=class extends Error{constructor(t,n){super(t);this.time=n}},L=class r extends S{static fromPromiseTimeoutError(e){return new r(e.message,e.time)}},x=class extends Error{constructor(t="Notebook is no longer available",n={}){super(t);this.raw=n;this.name="NotebookUnavailableError"}};var $=(r,e)=>{let t;return Promise.race([r,new Promise((n,i)=>t=setTimeout(i,e,new S("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},H=r=>{let e=null;return()=>e||(e=r())};var Dt=8,Nt=/[\x00-\x1f\x7f]/,W=class{constructor(e){this.okra=e}list(){return this.okra.invoke("terminal.list")}start(){return this.okra.invoke("terminal.start")}create(e){return this.okra.invoke("terminal.create",e)}onStarted(e){this.okra.listen("terminal.started",e)}resize(e,t){return this.okra.invoke("terminal.resize",{id:e,width:t[0],height:t[1]})}onOutput(e,t){this.okra.listen(`terminal.output.${e}`,t)}input(e,t){return Promise.resolve(this.okra.send("terminal.input",{id:e,input:t}))}listen(e,t){return this.okra.listen(e,t)}async attach(e,t){let n=this.processHandle(e,t?.abortSignal),i=await this.okra.invoke("terminal.attach",{id:e,replayHistory:t?.replayHistory},{abortSignal:t?.abortSignal});return i?{...n.process,...i}:(n.dispose(),!1)}async spawn(e,t,n){let i=n?.id||f(),o=this.processHandle(i,n?.abortSignal),{abortSignal:s,...a}=n??{},c=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:i,...a}},{abortSignal:s});return{...o.process,...c}}processHandle(e,t){let n=new Set,i=()=>{for(let m of n)m.dispose();n.clear()},o="",s,a=()=>{if(s&&(clearTimeout(s),s=void 0),o==="")return;let m=o;o="",this.input(e,m)},c=()=>{s||(s=setTimeout(a,Dt))},h=m=>{if(o+=m,Nt.test(m)){a();return}c()},p=()=>{a(),i()},l=new WritableStream({write:h,close:p,abort:p}),d=null,y=new ReadableStream({start:m=>{d=m,n.add(this.listen(`terminal.output.${e}`,_e=>{d?.enqueue(_e.output)}))},cancel:()=>{d=null,p()}}),u=new Promise(m=>{n.add(this.listen(`terminal.close.${e}`,_e=>{if(d)try{d.close()}catch{}p(),m(_e.exitCode)}))}),w=H(()=>(p(),this.okra.invoke("terminal.close",{id:e}))),kt=m=>{this.okra.invoke("terminal.resize",{id:e,width:m.cols,height:m.rows})};return t&&t.addEventListener("abort",w),{process:{exit:u,input:l,output:y,kill:w,resize:kt},dispose:p}}};var rt=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(rt||{}),K=class{constructor(e){this.okra=e}start(){return this.okra.invoke("container.start")}stop(){return this.okra.invoke("container.stop")}state(){return this.okra.invoke("container.state")}openedPorts(){return this.okra.invoke("container.opened-ports")}setPhp(e){return this.okra.invoke("container.set-php",{version:e})}enableTelemetry(e){return this.okra.invoke("container.stream-telemetry",{features:Array.from(e)})}stopTelemetry(){return this.okra.invoke("container.stop-telemetry")}listen(e,t){return this.okra.listen(e,t)}onPort(e){let t=[];return this.listen("container.ports",n=>{for(let i of n)t.some(o=>o.port===i.port)||e(i,"open");for(let i of t)n.some(o=>o.port===i.port)||e(i,"close");t=n})}};var z=class{constructor(e){this.okra=e}logout(){return this.okra.invoke("auth.logout")}login(e){return this.okra.invoke("auth.login",{newConnectionData:e})}};var Q=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,n){this.okra.listen(`${t}.${e}`,i=>n(i))}onClose(e,t){this.listen(e,"lsp.closed",n=>t(n.code,n.reason))}onError(e,t){this.listen(e,"lsp.error",n=>t(n.message))}onClientDisconnect(e){this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){this.listen(e,"lsp.response",n=>t(JSON.stringify(n)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return he.create(e,this)}whenSocketConnected(){return this.okra.whenConnected()}},he=class r{constructor(e,t){this.id=e;this.lsp=t}send(e){return this.lsp.message(this.id,e)}onMessage(e){this.lsp.onResponse(this.id,e)}onError(e){this.lsp.onError(this.id,e)}onClose(e){this.lsp.onClose(this.id,e)}dispose(){this.lsp.close(this.id)}start(){this.lsp.start(this.id)}onClientDisconnect(e){this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,t){return new r(e,t)}};var q=class{constructor(e){this.okra=e}invoke(e,t={},n={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:n})}dumpAutoload(){return this.okra.invoke("composer.dump-autoload")}install(e={}){return this.invoke("install",{},e)}update(e,t={}){return this.invoke("update",e,t)}require(e,t={}){return this.invoke("require",e,t)}remove(e,t={}){return this.invoke("remove",e,t)}stream(e){return this.okra.listen("composer.log",e)}packages(){return this.okra.invoke("composer.packages")}};var V=class{constructor(e){this.okra=e}stream(e){return this.okra.listen("notebook.log",e)}listen(e,t){this.okra.listen(e,t)}};var j=class{constructor(e){this.okra=e}maintenanceInfo(){return this.okra.invoke("laravel.maintenance.info",{})}toggleMaintenance(e){return this.okra.invoke("laravel.maintenance.toggle",e)}};var X=class{constructor(e){this.okra=e}eval(e,t="",n={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:n})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}start(){return this.okra.invoke("repl.start")}resize(e,t){return this.okra.invoke("repl.resize",{cols:e,rows:t})}listen(e,t){this.okra.listen(e,t)}onOutput(e){this.okra.listen("repl.output",e)}};function ot(r,e=[],t){let n=Array.isArray(e)?e:[],i=Array.isArray(e)?t:e;return{command:Array.isArray(r)?r:n.length>0?[r,...n]:r,opts:i}}var pe=class extends Error{constructor(t,n){super(t);this.output=t;this.exitCode=n}},Fe=class{constructor(e,t){this.output=e;this.exitCode=t}throw(){if(this.exitCode!==0)throw new pe(this.output,this.exitCode);return this}},J=class{constructor(e){this.okra=e}onOutput(e,t){this.okra.listen(`shell.output.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}async exec(e,t=[],n){let i=ot(e,t,n),{abortSignal:o,...s}=i.opts??{},a=await this.okra.invoke("shell.exec",{command:i.command,opts:Object.keys(s).length>0?s:void 0},{abortSignal:o});return new Fe(a.output,a.exitCode)}execStream(e,t=[],n){let i=ot(e,t,n),o=i.opts?.id||f(),s=new Set,a=null,c=!1,h=()=>{for(let u of s)u.dispose();s.clear()},p=()=>{if(!c&&(c=!0,h(),a))try{a.close()}catch{}},l=u=>{c||(c=!0,h(),a&&a.error(u))},d=new ReadableStream({start:u=>{a=u,s.add(this.listen(`shell.output.${o}`,w=>{a?.enqueue(w.output)}))},cancel:()=>{c=!0,h()}}),y=this.exec(i.command,{...i.opts,id:o}).then(u=>(p(),u)).catch(u=>{throw l(u),u});return{output:d,result:y}}};var st=["redis"],Rt=["start","nginx",...st],Y=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,t){return this.okra.invoke("service.run",{name:e,command:t})}stop(e){return this.okra.invoke("service.stop",{name:e})}onLog(e,t){return this.okra.listen(`service.log.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}logs(e,t={}){return t.follow?this.followLogs(e,t):this.okra.invoke("service.logs",{name:e,tail:t.tail}).then(n=>{if(!("output"in n))throw new Error(`Unexpected service.logs response for ${e}`);return n.output})}followLogs(e,t){let n=t.id||f(),i=new Set,o=null,s=!1,a=()=>{for(let d of i)d.dispose();i.clear()},c=()=>{if(!s&&(s=!0,a(),o))try{o.close()}catch{}},h=d=>{s||(s=!0,a(),o&&o.error(d))},p=H(()=>(c(),this.okra.invoke("service.stop-logs",{id:n}))),l=new ReadableStream({start:d=>{o=d,i.add(this.onLog(n,y=>{o?.enqueue(y.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:n}).catch(y=>{h(y)})},cancel:()=>{p()}});return{id:n,output:l,stop:p}}};var Z=class{constructor(e){this.okra=e}get(){return this.okra.invoke("config.get")}update(e){return this.okra.invoke("config.update",{config:e})}setPorts(e){return this.okra.invoke("config.set-ports",{ports:e})}};function at(r){let e=r.length,t=0,n=0;for(;n<e;){let i=r.charCodeAt(n++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&n<e){let o=r.charCodeAt(n);(o&64512)===56320&&(++n,i=((i&1023)<<10)+(o&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function At(r,e,t){let n=r.length,i=t,o=0;for(;o<n;){let s=r.charCodeAt(o++);if((s&4294967168)===0){e[i++]=s;continue}else if((s&4294965248)===0)e[i++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<n){let a=r.charCodeAt(o);(a&64512)===56320&&(++o,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[i++]=s>>12&15|224,e[i++]=s>>6&63|128):(e[i++]=s>>18&7|240,e[i++]=s>>12&63|128,e[i++]=s>>6&63|128)}e[i++]=s&63|128}}var _t=new TextEncoder,Ut=50;function Lt(r,e,t){_t.encodeInto(r,e.subarray(t))}function ct(r,e,t){r.length>Ut?Lt(r,e,t):At(r,e,t)}var Mt=4096;function Ge(r,e,t){let n=e,i=n+t,o=[],s="";for(;n<i;){let a=r[n++];if((a&128)===0)o.push(a);else if((a&224)===192){let c=r[n++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){let c=r[n++]&63,h=r[n++]&63;o.push((a&31)<<12|c<<6|h)}else if((a&248)===240){let c=r[n++]&63,h=r[n++]&63,p=r[n++]&63,l=(a&7)<<18|c<<12|h<<6|p;l>65535&&(l-=65536,o.push(l>>>10&1023|55296),l=56320|l&1023),o.push(l)}else o.push(a);o.length>=Mt&&(s+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(s+=String.fromCharCode(...o)),s}var Bt=new TextDecoder,Ot=200;function Ft(r,e,t){let n=r.subarray(e,e+t);return Bt.decode(n)}function lt(r,e,t){return t>Ot?Ft(r,e,t):Ge(r,e,t)}var C=class{constructor(e,t){this.type=e,this.data=t}};var g=class r extends Error{constructor(e){super(e);let t=Object.create(r.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:r.name})}};function ut(r,e,t){let n=t/4294967296,i=t;r.setUint32(e,n),r.setUint32(e+4,i)}function de(r,e,t){let n=Math.floor(t/4294967296),i=t;r.setUint32(e,n),r.setUint32(e+4,i)}function ge(r,e){let t=r.getInt32(e),n=r.getUint32(e+4);return t*4294967296+n}function ht(r,e){let t=r.getUint32(e),n=r.getUint32(e+4);return t*4294967296+n}var Gt=-1,$t=4294967296-1,Ht=17179869184-1;function Wt({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Ht)if(e===0&&r<=$t){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{let t=r/4294967296,n=r&4294967295,i=new Uint8Array(8),o=new DataView(i.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,n),i}else{let t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),de(n,4,r),t}}function Kt(r){let e=r.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,i=Math.floor(n/1e9);return{sec:t+i,nsec:n-i*1e9}}function zt(r){if(r instanceof Date){let e=Kt(r);return Wt(e)}else return null}function Qt(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),n=e.getUint32(4),i=(t&3)*4294967296+n,o=t>>>2;return{sec:i,nsec:o}}case 12:{let t=ge(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new g(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function qt(r){let e=Qt(r);return new Date(e.sec*1e3+e.nsec/1e6)}var pt={type:Gt,encode:zt,decode:qt};var T=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(pt)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let i=-1-e;this.builtInEncoders[i]=t,this.builtInDecoders[i]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let i=this.builtInEncoders[n];if(i!=null){let o=i(e,t);if(o!=null){let s=-1-n;return new C(s,o)}}}for(let n=0;n<this.encoders.length;n++){let i=this.encoders[n];if(i!=null){let o=i(e,t);if(o!=null){let s=n;return new C(s,o)}}}return e instanceof C?e:null}decode(e,t,n){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,n):new C(t,e)}};T.defaultCodec=new T;function Vt(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function ee(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Vt(r)?new Uint8Array(r):Uint8Array.from(r)}var jt=100,Xt=2048,me=class r{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??T.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??jt,this.initialBufferSize=e?.initialBufferSize??Xt,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new r({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),n=new Uint8Array(t),i=new DataView(t);n.set(this.bytes),this.view=i,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let n=at(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),ct(e,this.bytes,this.pos),this.pos+=n}encodeObject(e,t){let n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let n=ee(e);this.writeU8a(n)}encodeArray(e,t){let n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let i of e)this.doEncode(i,t+1)}countWithoutUndefined(e,t){let n=0;for(let i of t)e[i]!==void 0&&n++;return n}encodeMap(e,t){let n=Object.keys(e);this.sortKeys&&n.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(let o of n){let s=e[o];this.ignoreUndefined&&s===void 0||(this.encodeString(o),this.doEncode(s,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let n=e.data(this.pos+6),i=n.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(n);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),ut(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),de(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function $e(r,e){return new me(e).encodeSharedRef(r)}function fe(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var Jt=16,Yt=16,be=class{constructor(e=Jt,t=Yt){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let i=this.caches[n-1];e:for(let o of i){let s=o.bytes;for(let a=0;a<n;a++)if(s[a]!==e[t+a])continue e;return o.str}return null}store(e,t){let n=this.caches[e.length-1],i={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)}decode(e,t,n){let i=this.find(e,t,n);if(i!=null)return this.hit++,i;this.miss++;let o=Ge(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o}};var He="array",ie="map_key",gt="map_value",Zt=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new g("The type of key must be string or number but "+typeof r)},We=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=He,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=ie,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===He){let n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===ie||e.type===gt){let n=e;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},ne=-1,Ke=new DataView(new ArrayBuffer(0)),en=new Uint8Array(Ke.buffer);try{Ke.getInt8(0)}catch(r){if(!(r instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var dt=new RangeError("Insufficient data"),tn=new be,ve=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=Ke,this.bytes=en,this.headByte=ne,this.stack=new We,this.entered=!1,this.extensionCodec=e?.extensionCodec??T.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:tn,this.mapKeyConverter=e?.mapKeyConverter??Zt}clone(){return new r({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=ne,this.stack.reset()}setBuffer(e){let t=ee(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ne&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),n=ee(e),i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),t=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:i,pos:o,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${fe(i)} at ${s} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,i=-1;for await(let o of e){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),n&&(i=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(s){if(!(s instanceof RangeError))throw s}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e<160){let i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else{let i=e-160;t=this.decodeString(i,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(e===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(e===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(e===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(e===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(e===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(e===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(e===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new g(`Unrecognized type byte: ${fe(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let i=n.top();if(i.type===He)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,n.release(i);else continue e;else if(i.type===ie){if(t==="__proto__")throw new g("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=gt;continue e}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,n.release(i);else{i.key=null,i.type=ie;continue e}}return t}}readHeadByte(){return this.headByte===ne&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ne}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new g(`Unrecognized array type byte: ${fe(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new g(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new g(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new g(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw dt;let n=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,n,e):i=lt(this.bytes,n,e),this.pos+=t+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ie:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new g(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw dt;let n=this.pos+t,i=this.bytes.subarray(n,n+e);return this.pos+=t+e,i}decodeExtension(e,t){if(e>this.maxExtLength)throw new g(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=ht(this.view,this.pos);return this.pos+=8,e}readI64(){let e=ge(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function ze(r,e){return new ve(e).decode(r)}var ye=class{constructor(e){this.error=e}},nn=r=>new Promise(e=>{setTimeout(e,r)}),rn=(r,e)=>{let t=e.randomize?Math.random()+1:1,n=Math.max(e.minTimeout,1)*Math.pow(e.factor,r-1);return Math.round(Math.min(t*n,e.maxTimeout))};async function re(r,e={}){let t={retries:e.retries??10,minTimeout:e.minTimeout??1e3,maxTimeout:e.maxTimeout??1/0,factor:e.factor??2,randomize:e.randomize??!0},n=o=>{throw new ye(o??new Error("Aborted"))},i;for(let o=1;o<=t.retries+1;o++)try{return await r(n,o)}catch(s){if(s instanceof ye)throw s.error;if(i=s,o>t.retries)throw s;await e.onRetry?.(s,o),await nn(rn(o,t))}throw i}var Qe=function(r,e){return Qe=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])},Qe(r,e)};function mt(r,e){Qe(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function on(r){var e=typeof Symbol=="function"&&r[Symbol.iterator],t=0;return e?e.call(r):{next:function(){return r&&t>=r.length&&(r=void 0),{value:r&&r[t++],done:!r}}}}function sn(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function an(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(sn(arguments[e]));return r}var ft=(function(){function r(e,t){this.target=t,this.type=e}return r})(),cn=(function(r){mt(e,r);function e(t,n){var i=r.call(this,"error",n)||this;return i.message=t.message,i.error=t,i}return e})(ft),ln=(function(r){mt(e,r);function e(t,n,i){t===void 0&&(t=1e3),n===void 0&&(n="");var o=r.call(this,"close",i)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return e})(ft);var un=function(){if(typeof WebSocket<"u")return WebSocket},hn=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},D={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},pn=(function(){function r(e,t,n){var i=this;n===void 0&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(o){i._debug("open event");var s=i._options.minUptime,a=s===void 0?D.minUptime:s;clearTimeout(i._connectTimeout),i._uptimeTimeout=setTimeout(function(){return i._acceptOpen()},a),i._ws.binaryType=i._binaryType,i._messageQueue.forEach(function(c){return i._ws.send(c)}),i._messageQueue=[],i.onopen&&i.onopen(o),i._listeners.open.forEach(function(c){return i._callEventListener(o,c)})},this._handleMessage=function(o){i._debug("message event"),i.onmessage&&i.onmessage(o),i._listeners.message.forEach(function(s){return i._callEventListener(o,s)})},this._handleError=function(o){i._debug("error event",o.message),i._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),i.onerror&&i.onerror(o),i._debug("exec error listeners"),i._listeners.error.forEach(function(s){return i._callEventListener(o,s)}),i._connect()},this._handleClose=function(o){i._debug("close event"),i._clearTimeouts(),i._shouldReconnect&&i._connect(),i.onclose&&i.onclose(o),i._listeners.close.forEach(function(s){return i._callEventListener(o,s)})},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(r,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(r,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CONNECTING",{get:function(){return r.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"OPEN",{get:function(){return r.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CLOSING",{get:function(){return r.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CLOSED",{get:function(){return r.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"bufferedAmount",{get:function(){var e=this._messageQueue.reduce(function(t,n){return typeof n=="string"?t+=n.length:n instanceof Blob?t+=n.size:t+=n.byteLength,t},0);return e+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?r.CLOSED:r.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),r.prototype.close=function(e,t){if(e===void 0&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(e,t)},r.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,t),this._connect())},r.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=t===void 0?D.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},r.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},r.prototype.dispatchEvent=function(e){var t,n,i=this._listeners[e.type];if(i)try{for(var o=on(i),s=o.next();!s.done;s=o.next()){var a=s.value;this._callEventListener(e,a)}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0},r.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(n){return n!==t}))},r.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,an(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=t===void 0?D.reconnectionDelayGrowFactor:t,i=e.minReconnectionDelay,o=i===void 0?D.minReconnectionDelay:i,s=e.maxReconnectionDelay,a=s===void 0?D.maxReconnectionDelay:s,c=0;return this._retryCount>0&&(c=o*Math.pow(n,this._retryCount-1),c>a&&(c=a)),this._debug("next delay",c),c},r.prototype._wait=function(){var e=this;return new Promise(function(t){setTimeout(t,e._getNextDelay())})},r.prototype._getNextUrl=function(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){var t=e();if(typeof t=="string")return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},r.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var t=this._options,n=t.maxRetries,i=n===void 0?D.maxRetries:n,o=t.connectionTimeout,s=o===void 0?D.connectionTimeout:o,a=t.WebSocket,c=a===void 0?un():a;if(this._retryCount>=i){this._debug("max retries reached",this._retryCount,">=",i);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!hn(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(h){e._closeCalled||(e._debug("connect",{url:h,protocols:e._protocols}),e._ws=e._protocols?new c(h,e._protocols):new c(h),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},s))})}},r.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new cn(Error("TIMEOUT"),this))},r.prototype._disconnect=function(e,t){if(e===void 0&&(e=1e3),this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new ln(e,t,this))}catch{}}},r.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},r.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},r.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},r.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},r.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},r})(),bt=pn;var dn=r=>{if(typeof r=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[r]??`STATE_${r}`},gn=r=>{try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return r}},vt=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return;let e=r,t=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!t)return;let n=typeof e.name=="string"&&e.name?e.name:void 0;return n?`${n}: ${t}`:t},oe=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return String(r);let e=r,t=[],n=vt(e);n&&t.push(n);let i=vt(e.error);i&&i!==n&&t.push(`error=${i}`),typeof e.type=="string"&&e.type&&t.push(`type=${e.type}`),typeof e.code=="number"&&t.push(`code=${e.code}`),typeof e.reason=="string"&&e.reason&&e.reason!==n&&t.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&t.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&t.push(`url=${gn(o.url)}`);let s=dn(o.readyState);s&&t.push(`readyState=${s}`)}return t.length>0?t.join(" | "):"Unknown websocket event"};var M=null;typeof WebSocket<"u"?M=WebSocket:typeof MozWebSocket<"u"?M=MozWebSocket:typeof global<"u"?M=global.WebSocket||global.MozWebSocket:typeof window<"u"?M=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(M=self.WebSocket||self.MozWebSocket);var yt=M;var we=class{constructor(){this.disposables=new Map}add(e,t){this.disposables.has(e)&&(console.warn(`Disposable with key "${e}" already exists. Disposing the old one.`),this.disposables.get(e)?.dispose()),typeof t=="function"&&(t=t()),this.disposables.set(e,t)}dispose(){this.disposables.forEach(e=>e.dispose()),this.disposables.clear()}};var qe=class extends Error{constructor(e="WebSocket connection timeout"){super(e),this.name="ConnectionTimeoutError"}},xe=class extends Error{constructor(t,n){super(t);this.originalError=n;this.name="ConnectionFailedError"}},N=class extends Error{constructor(t,n){super(t);this.data=n;this.name="InvalidMessageError"}},R=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},I,Ve,je,B=class{constructor(e,t,n={}){this.eventEmitter=t;this.options=n;F(this,I);this.clientId="";this.closed=!1;this.disposables=new we;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.connectionStats={connectTime:0,reconnectCount:0,lastPingTime:0,lastPongTime:0,avgResponseTime:0,totalMessages:0,totalErrors:0,connectionStartTime:0};this.messageQueue=[];this.MAX_QUEUE_SIZE=100;this.QUEUE_TIMEOUT=3e4;this.incomingMessageChain=Promise.resolve();this.validateConfiguration(n),this.url=new URL(e),this.PING_INTERVAL=n.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=n.connectWaitTimeout??3e4,this.connectionStats.connectionStartTime=Date.now();let i=n.startClosed!==!1;this.rws=new bt(this.url.toString(),[],{WebSocket:n.webSocket??globalThis.WebSocket??yt,connectionTimeout:n.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:n.maxRetries??50,startClosed:i}),this.log("debug","Transport initialized",{url:this.url.toString(),options:n}),this.registerWatchers(),this.setupConnectionHealthMonitoring(),this.startPeriodicMaintenance()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new R("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new R("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new R("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new R("maxRetries must be between 0 and 100")}log(e,t,n){if(this.options.debug){let i=new Date().toISOString(),o=n?JSON.stringify(n,null,2):"";console[e](`[Transport ${i}] ${t}${o?`
2
- `+o:""}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):E(this,I,Ve).call(this)}id(){return this.clientId}async registerWatchers(){let e=t=>{this.incomingMessageChain=this.incomingMessageChain.catch(()=>{}).then(()=>this.processIncomingMessage(t)).catch(n=>{this.connectionStats.totalErrors++,this.log("error","Failed to process queued WebSocket frame",{error:n instanceof Error?n.message:String(n)}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:n,rawMessage:t.data,timestamp:Date.now()})})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async processIncomingMessage(e){if(!(e.data instanceof Blob)){let i=new Error("Unexpected message type: "+typeof e.data);this.connectionStats.totalErrors++,this.log("error","Unexpected WebSocket message type",{error:i.message,messageType:typeof e.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:i,rawMessage:e.data,timestamp:Date.now()});return}let t=await e.data.arrayBuffer();if(t.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}let n;try{n=ze(t)}catch(i){this.connectionStats.totalErrors++,this.log("error","Failed to decode WebSocket frame",{error:i instanceof Error?i.message:String(i),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:i,rawMessage:t,timestamp:Date.now()});return}try{await this.handleRawMessage(n)}catch(i){this.connectionStats.totalErrors++,this.log("error","Failed to process WebSocket frame",{error:i instanceof Error?i.message:String(i),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:i,rawMessage:t,timestamp:Date.now()})}}async handleRawMessage(e){if(this.closed){this.log("debug","Ignoring message received after transport was closed");return}if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:t,event:n,as:i}=e;if(!n||typeof n!="string")throw new N("Message missing event field",e);if(this.log("debug","Processing message",{event:n,hasData:!!t}),n==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(n==="Events.BootError"){let o=new x(t?.message||"Notebook is no longer available",t||{});this.log("error","Boot error received",{data:t}),this.terminate(o,4e3,o.message);return}if(n==="response"){let{responseEvent:o,data:s}=t;if(!o)throw new N("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,s);return}if(n==="error"){let{errorEvent:o,data:s}=t;if(!o)throw new N("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:s}),await this.handleMessage(o,s);return}await this.handleMessage(n,t,i)}catch(t){this.connectionStats.totalErrors++,t instanceof N?this.log("error","Invalid message format",{error:t.message,data:t.data,totalErrors:this.connectionStats.totalErrors}):this.log("error","Failed to parse message",{ev:e,error:t instanceof Error?t.message:String(t),totalErrors:this.connectionStats.totalErrors}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:t,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,t,n){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,t.id);return}e&&this.eventEmitter.emit(n||e,t)}listen(e,t,n){return this.eventEmitter.listen(e,t)}onDidBootError(e){this.eventEmitter.listen("transport.boot_error",t=>{e(t.error)})}removeListener(e,t){this.eventEmitter.removeListener(e,t)}listenOnce(e,t,n){this.eventEmitter.once(e,t,n),this.disposables.add(`once_${e}_${f()}`,{dispose:()=>{this.eventEmitter.removeListener(e,t)}})}emit(e,...t){this.eventEmitter.emit(e,...t)}get isConnected(){return this.status==="OPEN"}get isConnecting(){return this.status==="CONNECTING"}get isDisconnected(){return this.status==="CLOSED"}get isClosed(){return this.closed}getTerminalError(){return this.terminalError}get status(){return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[this.rws.readyState]}async call(e,t={},n={}){if(this.terminalError)throw this.terminalError;this.clearOldQueuedMessages();let i=n.responseEvent||`${e}_${f()}_response`,o=`${i}_error`,s,a=()=>{s&&(this.rws.removeEventListener("close",s),this.rws.removeEventListener("error",s)),this.eventEmitter.removeListener(i),this.eventEmitter.removeListener(o)},c=async(p,l)=>{if(this.terminalError){l(this.terminalError);return}let d=new DOMException("Request aborted","AbortError");if(n.abortSignal?.aborted&&l(d),n.abortSignal&&n.abortSignal.addEventListener("abort",()=>{l(d)}),!this.isConnected&&!this.isClosed){if(this.log("debug","Connection not available, queuing message",{action:e}),this.messageQueue.length>=this.MAX_QUEUE_SIZE){let u=this.messageQueue.shift();u&&u.reject(new Error("Message queue full, oldest message dropped"))}this.messageQueue.push({action:e,data:t,options:n,resolve:p,reject:l,timestamp:Date.now()});return}let y=Date.now();this.listenOnce(i,u=>{let w=Date.now()-y;this.connectionStats.avgResponseTime=(this.connectionStats.avgResponseTime+w)/2,this.connectionStats.totalMessages++,this.log("debug","Message response received",{action:e,responseTime:w,avgResponseTime:this.connectionStats.avgResponseTime}),p(u)}),this.listenOnce(o,u=>{this.connectionStats.totalErrors++,this.log("error","Message error received",{action:e,error:u}),l(new b(u.code,u.message,u))}),s=u=>{if(u.code===1008&&(u.reason||"").includes("rate limit")){l(new U(u.reason||"Rate limit exceeded",u));return}let w=oe(u);l(this.terminalError||new xe(`Connection lost to the notebook during request: ${w}`,u))},this.rws.addEventListener("close",s),this.rws.addEventListener("error",s);try{this.rws.send(this.pack({action:e,data:t,errorEvent:o,responseEvent:i})),this.log("debug","Message sent",{action:e,data:t})}catch(u){throw this.log("error","Failed to send message",{action:e,error:u}),u}},h=async()=>{await E(this,I,Ve).call(this);let p=new Promise(c).finally(a);return n.timeout?$(p,n.timeout).catch(l=>{throw l instanceof S?L.fromPromiseTimeoutError(l):l}).finally(a):p};return this.sendWithRetry(async()=>await h(),n.retries||10)}send(e,t={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:t})),this.connectionStats.totalMessages++,this.log("debug","One-way message sent",{action:e,data:t}),!0}catch(n){return this.connectionStats.totalErrors++,this.log("error","Failed to send one-way message",{action:e,error:n}),!1}}pack(e){return new Blob([$e(e)])}sendWithRetry(e,t=10){return re(async(n,i)=>{try{return await e()}catch(o){if(o instanceof b||o instanceof U||o instanceof R||o instanceof N||o instanceof x||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:i}),n(o);return}throw o instanceof L&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:i,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:i,error:o instanceof Error?o.message:String(o),nextDelay:this.getBackoffDelay(i-1)}),o}},{retries:t,onRetry:(n,i)=>{this.log("warn","Send operation retry",{attempt:i,maxRetries:t,error:n instanceof Error?n.message:String(n)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},n={}){return n.responseEvent||(n.responseEvent=`${e}_${f()}`),this.call("invoke",{action:e,data:t},n)}reconnect(){if(this.terminalError)throw this.terminalError;if(this.closed)throw new Error("Cannot reconnect a closed transport. The transport has been permanently closed.");this.log("info","Reconnecting transport"),this.connectPromise=null,this.rws.reconnect()}disconnect(){if(this.closed){console.trace("Transport is already closed, cannot disconnect again");return}this.close()}terminate(e,t=4e3,n=e.message){this.terminalError=e,e instanceof x&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,n)}close(e,t){if(this.closed)return;this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null;let n=this.messageQueue.length,i=this.terminalError||new Error("Connection closed while message was queued");this.messageQueue.forEach(o=>{o.reject(i)}),this.messageQueue=[],n>0&&this.log("debug",`Rejected ${n} queued messages due to connection close`),this.disposables.dispose();try{this.rws.close(e,t)}catch(o){this.log("error","Error closing WebSocket",{error:o instanceof Error?o.message:String(o)})}this.eventEmitter.emit("transport.closed",{code:e,reason:t,metrics:this.getConnectionMetrics(),timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}onDidConnect(e){this.rws.addEventListener("open",e),this.disposables.add("connect",{dispose:()=>{this.rws.removeEventListener("open",e)}})}onDidClose(e){this.rws.addEventListener("close",e),this.disposables.add("close",{dispose:()=>{this.rws.removeEventListener("close",e)}})}setupConnectionHealthMonitoring(){this.rws.addEventListener("open",()=>{this.connectionStats.connectTime=Date.now(),this.connectionStats.reconnectCount++,this.log("info","Connection established",{reconnectCount:this.connectionStats.reconnectCount,timeSinceStart:Date.now()-this.connectionStats.connectionStartTime}),this.processMessageQueue()}),this.rws.addEventListener("close",e=>{this.log("warn","Connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.handleConnectionClose(e.code)}),this.rws.addEventListener("error",e=>{this.connectionStats.totalErrors++;let t=oe(e);this.log("error","Connection error",{error:t,rawError:e,totalErrors:this.connectionStats.totalErrors})})}handleConnectionClose(e){switch(e){case 1e3:return this.log("info","Normal connection closure"),"stop";case 1001:return this.log("info","Connection going away, will reconnect"),"reconnect";case 1006:return this.log("warn","Abnormal connection closure, will retry"),"retry";case 1008:return this.log("error","Connection closed due to policy violation"),this.clearOldQueuedMessages(),"stop";case 4e3:return this.log("info","Connection closed due to terminal notebook error"),"stop";default:return this.log("warn",`Unknown close code: ${e}, will reconnect`),"reconnect"}}processMessageQueue(){if(this.messageQueue.length===0)return;this.log("debug",`Processing ${this.messageQueue.length} queued messages`);let e=[...this.messageQueue];this.messageQueue=[];for(let t of e){if(Date.now()-t.timestamp>this.QUEUE_TIMEOUT){t.reject(new Error("Queued message timed out"));continue}this.call(t.action,t.data,t.options).then(t.resolve).catch(t.reject)}}clearOldQueuedMessages(){let e=Date.now(),t=this.messageQueue.length;this.messageQueue=this.messageQueue.filter(n=>{let i=e-n.timestamp>this.QUEUE_TIMEOUT;return i&&n.reject(new Error("Queued message expired")),!i}),t!==this.messageQueue.length&&this.log("debug",`Cleared ${t-this.messageQueue.length} expired messages`)}getBackoffDelay(e){return Math.min(1e3*Math.pow(2,e),3e4)+Math.random()*1e3}getConnectionMetrics(){let e=Date.now(),t=this.connectionStats.connectTime>0?e-this.connectionStats.connectTime:0;return{status:this.status,clientId:this.clientId,isConnected:this.isConnected,isConnecting:this.isConnecting,connectionStats:{...this.connectionStats,connectionDuration:t,uptime:e-this.connectionStats.connectionStartTime,messagesPerSecond:t>0?(this.connectionStats.totalMessages/(t/1e3)).toFixed(2):"0",errorRate:this.connectionStats.totalMessages>0?(this.connectionStats.totalErrors/this.connectionStats.totalMessages*100).toFixed(2)+"%":"0%",timeSinceLastPing:this.connectionStats.lastPingTime>0?e-this.connectionStats.lastPingTime:0,timeSinceLastPong:this.connectionStats.lastPongTime>0?e-this.connectionStats.lastPongTime:0},messageQueue:{length:this.messageQueue.length,maxSize:this.MAX_QUEUE_SIZE,oldestMessageAge:this.messageQueue.length>0?e-Math.min(...this.messageQueue.map(n=>n.timestamp)):0},config:{pingInterval:this.PING_INTERVAL,queueTimeout:this.QUEUE_TIMEOUT,url:this.url.toString()}}}getHealthStatus(){let t=this.getConnectionMetrics().connectionStats;return!this.isConnected||t.timeSinceLastPong>this.PING_INTERVAL*2||Number.parseFloat(t.errorRate)>50?"unhealthy":t.avgResponseTime>5e3||Number.parseFloat(t.errorRate)>10||t.timeSinceLastPong>this.PING_INTERVAL*1.5?"degraded":"healthy"}resetStats(){this.connectionStats={connectTime:Date.now(),reconnectCount:0,lastPingTime:0,lastPongTime:0,avgResponseTime:0,totalMessages:0,totalErrors:0,connectionStartTime:Date.now()},this.log("debug","Connection statistics reset")}async runDiagnostics(){let e=this.getConnectionMetrics(),t=this.getHealthStatus(),n=[],i=[];return this.isConnected||(n.push("Connection is not established"),i.push("Check network connectivity and server availability")),e.connectionStats.timeSinceLastPong>this.PING_INTERVAL*2&&(n.push("No pong received recently - connection may be stale"),i.push("Consider forcing a reconnection")),Number.parseFloat(e.connectionStats.errorRate)>10&&(n.push(`High error rate: ${e.connectionStats.errorRate}`),i.push("Check server logs and network stability")),e.messageQueue.length>this.MAX_QUEUE_SIZE*.8&&(n.push("Message queue is nearly full"),i.push("Check connection stability and consider reducing message frequency")),e.connectionStats.avgResponseTime>5e3&&(n.push("High average response time"),i.push("Check network latency and server performance")),this.log("info","Connection diagnostics completed",{status:t,issueCount:n.length,recommendationCount:i.length}),{status:t,metrics:e,issues:n,recommendations:i}}startPeriodicMaintenance(){this.disposables.add("maintenance",()=>{let e=setInterval(()=>{if(this.clearOldQueuedMessages(),this.options.debug){let t=this.getHealthStatus(),n=this.getConnectionMetrics();this.log("debug","Periodic health check",{health:t,messageCount:n.connectionStats.totalMessages,errorCount:n.connectionStats.totalErrors,queueLength:n.messageQueue.length})}},3e5);return{dispose:()=>{clearInterval(e)}}})}};I=new WeakSet,Ve=function(){return this.terminalError?Promise.reject(this.terminalError):this.isConnected?Promise.resolve():this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((e,t)=>{if(this.isConnected){e(),E(this,I,je).call(this);return}let n,i=0,o=()=>{this.rws.removeEventListener("open",s),this.rws.removeEventListener("error",a),this.rws.removeEventListener("close",c),clearTimeout(n)},s=()=>{o(),this.connectPromise=null,e(),E(this,I,je).call(this)},a=h=>{i+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:i,error:oe(h)})},c=h=>{let p=oe(h);if("code"in h&&(h.code===1008||h.code===4e3)){o(),this.connectPromise=null,t(new xe(`WebSocket connection failed: ${p}`,h));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:p})};this.rws.addEventListener("open",s),this.rws.addEventListener("error",a),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),n=setTimeout(()=>{o(),this.connectPromise=null,t(new qe(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},je=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.connectionStats.lastPingTime=Date.now(),this.log("debug","Sending periodic ping");let t=Date.now();await this.invoke("ping"),this.connectionStats.lastPongTime=Date.now();let n=this.connectionStats.lastPongTime-t;this.log("debug","Ping successful",{pingTime:n})}catch(t){this.log("error","Ping failed",{error:t instanceof Error?t.message:String(t)}),Date.now()-this.connectionStats.lastPongTime>this.PING_INTERVAL*3&&(this.log("warn","Connection appears dead, forcing reconnection"),this.rws.reconnect())}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};function wt(r){return{all:r=r||new Map,on:function(e,t){var n=r.get(e);n?n.push(t):r.set(e,[t])},off:function(e,t){var n=r.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var n=r.get(e);n&&n.slice().map(function(i){i(t)}),(n=r.get("*"))&&n.slice().map(function(i){i(e,t)})}}}function mn(r){let e=wt(r);return e.once=(t,n)=>{e.on(t,n),e.on(t,e.off.bind(e,t,n))},e}var A=class r{constructor(){this.emitter=mn()}listen(e,t){let n=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:n}}emit(e,t){this.emitter.emit(e,t)}once(e,t){this.emitter.once(e,t)}static make(){return new r}static refresh(){return new r}removeListener(e,t){this.emitter.off(e,t)}static createInstance(){return new r}inspect(){return this.emitter.all}};var se=class{constructor(e){this.okra=e}checkpoint(e,t,n="main",i=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:n,allowEmpty:i})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,n="main",i,o="both",s=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:n,token:i,direction:o,force:s})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}diff(e){return this.okra.invoke("git.diff",e)}merge(e){return this.okra.invoke("git.merge",e)}conflicts(){return this.okra.invoke("git.conflicts",{})}abortMerge(){return this.okra.invoke("git.resolve",{action:"abort"})}continueMerge(e,t){return this.okra.invoke("git.resolve",{action:"continue",author:e,message:t})}review(){return this.okra.invoke("git.review",{})}stage(e={all:!0}){return this.okra.invoke("git.stage",e)}unstage(e={all:!0}){return this.okra.invoke("git.unstage",e)}revert(e){return this.okra.invoke("git.revert",e)}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}};var O=class{constructor(e,t,n){this.onEvent=e;this.onceEvent=t;this.beacon=n;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=n,this.setupUrlChangeListener(),this.urlHistory.push(n.iframe.src),this.updateNavigationState()}visit(e){if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState(),this.emitHistoryChange(e,"push")}setupUrlChangeListener(){this.beacon.on("urlChange",e=>{this.addToHistory(e.newUrl)})}addToHistory(e){this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState()}updateNavigationState(){let e=this._canGoBack,t=this._canGoForward;this._canGoBack=this.currentIndex>0,this._canGoForward=this.currentIndex<this.urlHistory.length-1,(e!==this._canGoBack||t!==this._canGoForward)&&this.emitNavigationStateChange()}emitNavigationStateChange(){this.beacon&&this.beacon.emit&&this.beacon.emit("navigationStateChange",{canGoBack:this._canGoBack,canGoForward:this._canGoForward,currentIndex:this.currentIndex,historyLength:this.urlHistory.length,timestamp:Date.now()})}get canGoBack(){return this._canGoBack}get canGoForward(){return this._canGoForward}async goBack(){if(!this.canGoBack)return{success:!1,error:"Cannot go back - no previous history"};this.currentIndex--,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"back"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async goForward(){if(!this.canGoForward)return{success:!1,error:"Cannot go forward - no forward history"};this.currentIndex++,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"forward"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async reload(){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){let e=this.urlHistory[this.currentIndex];if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"reload")}}getCurrentUrl(){return this.currentIndex>=0&&this.currentIndex<this.urlHistory.length?new URL(this.urlHistory[this.currentIndex]):new URL("about:blank")}getHistory(){return[...this.urlHistory]}getCurrentIndex(){return this.currentIndex}canGoBackSync(){return this.currentIndex>0}canGoForwardSync(){return this.currentIndex<this.urlHistory.length-1}emitHistoryChange(e,t){this.beacon&&this.beacon.emit&&this.beacon.emit("historyChange",{url:e,state:null,direction:t,timestamp:Date.now()})}async pushState(e){this.visit(e)}async replaceState(e){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){if(this.urlHistory[this.currentIndex]=e,!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"replace")}else this.visit(e)}async getHistoryLength(){return this.urlHistory.length}async getHistoryState(){return null}async getHistoryInfo(){return{length:this.urlHistory.length,state:null,url:this.urlHistory[this.currentIndex]||"",canGoBack:this.canGoBack,canGoForward:this.canGoForward}}on(e,t){return this.onEvent(e,t)}once(e,t){this.onceEvent(e,t)}};function xt(){if(typeof window>"u")throw new Error("Beacon SDK can only be used in a browser environment")}var _=class extends Error{constructor(t,n){super(t);this.code=n;this.name="BeaconError"}},ae=class extends _{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},v=class extends _{constructor(e){super(`Beacon connection error: ${e}`),this.code="CONNECTION_ERROR"}},ke=class{constructor(e,t={}){this.messageHandlers=new Map;this.isBeaconReady=!1;this.readyPromise=null;this.isStarted=!1;this.disposables=[];this.messageChannel=null;this.port=null;this.channelEstablished=!1;xt(),this.iframe=e;let n={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...n,...t.retry},...t},this.eventEmitter=A.make(),this.setupMessageChannel(),this.navigator=new O(this.eventEmitter.listen.bind(this.eventEmitter),this.eventEmitter.once.bind(this.eventEmitter),this)}setupMessageChannel(){let e=t=>{try{if(t.source!==this.iframe.contentWindow)return;let n=t.data;if(!n||typeof n!="object"||!n.type)return;n.type==="beacon:ready-for-channel"&&this.establishChannel().catch(i=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",i)}),n.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",n.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(n){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",n)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new v("Iframe contentWindow not available");this.messageChannel=new MessageChannel,this.port=this.messageChannel.port1,this.port.onmessage=t=>{this.handleBeaconMessage(t.data)},this.port.onmessageerror=t=>{this.options.debug&&console.error("[Beacon SDK] Port message error:",t)},this.port.start();let e={type:"beacon:establish-channel",timestamp:Date.now(),id:this.generateId()};return this.iframe.contentWindow.postMessage(e,"*",[this.messageChannel.port2]),this.options.debug&&console.log("[Beacon SDK] Channel establishment message sent"),new Promise((t,n)=>{let i=setTimeout(()=>{n(new v("Channel establishment timeout"))},this.options.timeout),o=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(i),t()):setTimeout(o,100)};o()})}handleBeaconMessage(e){this.options.debug&&console.log("[Beacon SDK] Received message:",e.type,e.payload);let t=e.type.replace("beacon:","");this.emit(t,e.payload);let n=this.messageHandlers.get(e.type);n&&n.forEach(i=>{try{i(e.payload)}catch(o){this.options.debug&&console.error("[Beacon SDK] Message handler error:",o)}})}waitForBeaconReady(){return re(async()=>new Promise((e,t)=>{if(this.isBeaconReady&&this.channelEstablished){e();return}let n=this.options.timeout,i=setTimeout(()=>{t(new ae("beacon ready",n))},n),o=this.on("ready",()=>{clearTimeout(i),o.dispose(),e()})}),{retries:this.options.retry?.retries||3,minTimeout:this.options.retry?.minTimeout||1e3,maxTimeout:this.options.retry?.maxTimeout||5e3,factor:this.options.retry?.factor||2,randomize:this.options.retry?.randomize||!0,onRetry:(e,t)=>{if(this.options.debug){let n=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,n)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new v("MessagePort not available - channel not established");let n={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(n),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",n.type,n.payload)}catch(i){throw new v(`Failed to send message via port: ${i instanceof Error?i.message:String(i)}`)}}async sendAndWaitFor(e,t,n={},i){return await this.ready(),re(async o=>new Promise((s,a)=>{let c=i||this.options.timeout,h=setTimeout(()=>{p.dispose();let l=new ae(e,c);a(l)},c),p=this.eventEmitter.listen(t,l=>{clearTimeout(h),p.dispose(),s(l)});try{this.sendMessage(e,n)}catch(l){clearTimeout(h),p.dispose(),l instanceof v?a(l):o(l)}}),{retries:this.options.retry?.retries||3,minTimeout:this.options.retry?.minTimeout||1e3,maxTimeout:this.options.retry?.maxTimeout||5e3,factor:this.options.retry?.factor||2,randomize:this.options.retry?.randomize||!0,onRetry:(o,s)=>{if(this.options.debug){let a=o instanceof Error?o.message:String(o);console.warn(`[Beacon SDK] Retry attempt ${s} for ${e}:`,a)}}})}generateId(){return`sdk_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}emit(e,t){this.eventEmitter.emit(e,t)}start(){return this.isStarted?this.readyPromise||Promise.resolve():(this.isStarted=!0,this.readyPromise=this.waitForBeaconReady(),this.readyPromise)}async ready(){if(!this.isStarted)throw new _("Beacon has not been started. Call start() first.");if(!this.readyPromise)throw new _("Beacon ready promise is not available");return $(this.readyPromise,this.options.timeout)}get isReady(){return this.isBeaconReady}on(e,t){return this.eventEmitter.listen(e,t)}once(e,t){this.eventEmitter.once(e,t)}async ping(){try{return await this.sendAndWaitFor("ping","pong",{timestamp:Date.now()}),!0}catch(e){return this.options.debug&&console.warn("[Beacon SDK] Ping failed:",e),!1}}async getDebugInfo(){return this.sendAndWaitFor("getDebugInfo","debugInfo")}async getConsoleEvents(){return this.sendAndWaitFor("getConsoleEvents","consoleEvents")}async getErrorEvents(){return this.sendAndWaitFor("getErrorEvents","errorEvents")}async clearConsole(){await this.ready(),this.sendMessage("clearConsole")}async clearErrors(){await this.ready(),this.sendMessage("clearErrors")}async executeCode(e){return this.sendAndWaitFor("executeCode","codeExecutionResult",{code:e})}async inspectElement(e){return this.sendAndWaitFor("inspectElement","elementInspectionResult",{selector:e})}async fetch(e){return this.sendAndWaitFor("fetch","fetchResult",e)}async captureScreenshot(e={}){let t=e.mediaTimeoutMs??e.timeout??3e4,n=e.transportTimeoutMs??t+5e3;return this.sendAndWaitFor("captureScreenshot","screenshotResult",e,n)}async debug(e,t){let n=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==n&&(this.navigator.visit(n),await this.ready()),t&&await this.wait(t);let i=(e.options?.timeout||3e4)+5e3;return this.sendAndWaitFor("debug","debugResult",e,i)}async wait(e){return new Promise(t=>setTimeout(t,e*1e3))}navigate(e){if(!this.iframe)throw new v("Iframe not available");try{let t=new URL(e,this.iframe.src||window.location.origin);this.iframe.src=t.href,this.isBeaconReady=!1,this.channelEstablished=!1,this.port&&(this.port.close(),this.port=null),this.messageChannel&&(this.messageChannel=null),this.isStarted&&(this.readyPromise=this.waitForBeaconReady())}catch{throw new v(`Invalid URL: ${e}`)}}get url(){return this.iframe.src}get element(){return this.iframe}dispose(){this.port&&(this.port.close(),this.port=null),this.messageChannel&&(this.messageChannel=null),this.disposables.forEach(e=>e.dispose()),this.disposables=[],this.messageHandlers.clear(),this.isBeaconReady=!1,this.channelEstablished=!1,this.isStarted=!1,this.readyPromise=null}};function Xe(r,e){return new ke(r,e)}function fn(){try{return xt(),!0}catch{return!1}}function bn(r){return Array.isArray(r)?r:Object.entries(r).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var Ee=class extends Error{constructor(t,n={}){super(t);this.message=t;this.data=n;this.name="NotebookInitError"}},Se=class extends Error{constructor(t,n){super(`PHPSandbox API Error: ${t.status} ${t.statusText} - ${n}`);this.response=t;this.body=n;this.status=t.status}},Te=class{constructor(e){this.client=e;this.secrets=new Pe(e),this.preview=new Ce(e),this.mail=new De(e)}async create(e,t={},n=!0){let i=await this.client.post("/notebook",{template:e,...t}),o=new k(i.data,this.client);return n?this.init(o):o}async get(e){let t=await this.client.get(`/notebook/${e}`);return new k(t.data,this.client)}async update(e,t={}){let n=await this.client.put(`/notebook/${e}`,t);return new k(n.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e,t={}){let n=await this.client.post(`/notebook/${e}/fork`,t);return this.init(new k(n.data,this.client))}async open(e){let t=await this.client.get(`/notebook/${e}`);return new k(t.data,this.client)}openFromData(e){return this.init(new k(e,this.client))}async init(e){return await e.ready(),e}},Ie=class{constructor(e,t="https://api.phpsandbox.io/v1",n={}){this.fetch=globalThis.fetch;this.notebook=new Te(this),this.options=Object.assign({startClosed:!0},n),this.baseUrl=t,n.fetch&&(this.fetch=n.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get(e){return this.makeRequest("GET",e)}post(e,t){return this.makeRequest("POST",e,{body:t?JSON.stringify(t):void 0})}delete(e){return this.makeRequest("DELETE",e)}put(e,t){return this.makeRequest("PUT",e,{body:t?JSON.stringify(t):void 0})}async makeRequest(e,t,n){let i=await this.fetch(new Request(new URL(`v1/${t.replace(/^\//,"")}`,this.baseUrl),{method:e,...n,headers:this.headers}));if(!i.ok)throw new Se(i,await i.text());if(i.status===204)return{data:void 0};let o=await i.text();return{data:o===""?void 0:JSON.parse(o)}}},Je=class extends Ie{},Pe=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,n){let i=typeof n=="string"?{name:t,value:n}:{name:t,...n};return(await this.client.put(`/notebook/${e}/secrets`,i)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:bn(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},Ce=class{constructor(e){this.client=e}async get(e){return(await this.client.get(`/notebook/${e}/preview`)).data}async setPassword(e,t){return(await this.client.put(`/notebook/${e}/preview`,t)).data}async disable(e){await this.client.delete(`/notebook/${e}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${e}/preview/session`)).data}async createHandoff(e,t){return(await this.client.post(`/notebook/${e}/preview/handoff`,t)).data}},De=class{constructor(e){this.client=e}async status(e){return(await this.client.get(`/notebook/${e}/mail`)).data}async enable(e){return(await this.client.put(`/notebook/${e}/mail`)).data}async disable(e){await this.client.delete(`/notebook/${e}/mail`)}async list(e,t={}){return(await this.client.get(`/notebook/${e}/mails${vn(t)}`)).data}async get(e,t){return(await this.client.get(`/notebook/${e}/mails/${encodeURIComponent(t)}`)).data}async delete(e,t){await this.client.delete(`/notebook/${e}/mails/${encodeURIComponent(t)}`)}},P,ce,Ye,k=class{constructor(e,t){this.data=e;this.client=t;F(this,ce);this.initialized=!1;F(this,P);this.disposables=[];this.emitter=A.createInstance(),this.socket=new B(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),Me(this,P,E(this,ce,Ye).call(this)),this.file=new G(this),this.terminal=new W(this),this.auth=new z(this),this.lsp=new Q(this),this.composer=new q(this),this.log=new V(this),this.repl=new X(this),this.container=new K(this),this.laravel=new j(this),this.shell=new J(this),this.git=new se(this),this.services=new Y(this),this.config=new Z(this),this.secrets=new Ne(t,this.data.id),this.preview=new Re(t,this.data.id),this.mail=new Ae(t,this.data.id)}async ready(){let e=this.socket.getTerminalError();if(e)throw e;return(async()=>(this.client.options.startClosed&&!this.socket.isConnected&&await this.socket.connect(),le(this,P)))()}fork(e={}){return this.client.notebook.fork(this.data.id,e)}delete(){return this.client.notebook.delete(this.data.id).then(()=>{this.socket.terminate(new x("Notebook has been deleted.",{id:this.data.id}))})}stop(){return this.container.stop()}restart(){return this.container.start()}invoke(e,t={},n={}){return this.socket.invoke(e,t||{},n)}send(e,t={}){return this.socket.send(e,t||{})}ping(){return this.invoke("ping")}listen(e,t){let n=this.emitter.listen(e,t);return this.disposables.push(n),n}dispose(){this.disposables.forEach(e=>e.dispose()),!this.socket.isClosed&&this.socket.disconnect()}connected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,n)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidClose(()=>n(new Error("Connection closed"))),this.socket.onDidBootError(i=>n(i))}catch(i){n(i)}})}whenConnected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,n)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidBootError(i=>n(i))}catch(i){n(i)}})}watchConnection(){this.socket.onDidConnect(()=>{this.socket.emit("okra.connected"),this.client.options.telemetry&&this.container.enableTelemetry(this.client.options.telemetry)}),this.socket.onDidClose(()=>{this.socket.emit("okra.disconnected"),this.initialized=!1}),this.socket.onDidBootError(e=>{this.socket.emit("okra.boot_error",e),this.socket.emit("okra.disconnected"),this.initialized=!1})}onDidConnect(e){this.socket.removeListener("okra.connected",e);let t=this.socket.listen("okra.connected",e);return this.disposables.push(t),t}onDidDisconnect(e){let t=this.socket.listen("okra.disconnected",e);return this.disposables.push(t),t}onDidBootError(e){let t=this.socket.listen("okra.boot_error",e);return this.disposables.push(t),t}update(){return this.invoke("notebook.update")}onDidInitialize(e){return this.listen("notebook.initialized",e)}async reconnect(){let e=this.whenConnected();return this.socket.reconnect(),this.initialized=!1,await e,E(this,ce,Ye).call(this),this.ready().then(()=>this)}async beacon(e,t){let n=await this.ready();return e.src=n.data.previewUrl,Xe(e,t)}};P=new WeakMap,ce=new WeakSet,Ye=function(){return Me(this,P,new Promise((e,t)=>{let n=this.onDidInitialize(o=>{if(i.dispose(),n.dispose(),this.initialized=o,o.type==="error"){t(new Ee(o.message,o.data));return}e(o)}),i=this.onDidBootError(o=>{n.dispose(),i.dispose(),t(o)})})),le(this,P).catch(()=>{}),le(this,P)};var Ne=class{constructor(e,t){this.client=e;this.notebookId=t}list(){return this.client.notebook.secrets.list(this.notebookId)}set(e,t){return this.client.notebook.secrets.set(this.notebookId,e,t)}setMany(e){return this.client.notebook.secrets.setMany(this.notebookId,e)}delete(e){return this.client.notebook.secrets.delete(this.notebookId,e)}},Re=class{constructor(e,t){this.client=e;this.notebookId=t}get(){return this.client.notebook.preview.get(this.notebookId)}setPassword(e){return this.client.notebook.preview.setPassword(this.notebookId,e)}disable(){return this.client.notebook.preview.disable(this.notebookId)}createSession(){return this.client.notebook.preview.createSession(this.notebookId)}createHandoff(e){return this.client.notebook.preview.createHandoff(this.notebookId,e)}},Ae=class{constructor(e,t){this.client=e;this.notebookId=t}status(){return this.client.notebook.mail.status(this.notebookId)}enable(){return this.client.notebook.mail.enable(this.notebookId)}disable(){return this.client.notebook.mail.disable(this.notebookId)}list(e={}){return this.client.notebook.mail.list(this.notebookId,e)}get(e){return this.client.notebook.mail.get(this.notebookId,e)}delete(e){return this.client.notebook.mail.delete(this.notebookId,e)}};function vn(r){let e=new URLSearchParams;for(let[n,i]of Object.entries(r))(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&e.set(n,String(i));let t=e.toString();return t===""?"":`?${t}`}return Ct(yn);})();
2
+ `+o:""}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):E(this,I,Ve).call(this)}id(){return this.clientId}async registerWatchers(){let e=t=>{this.incomingMessageChain=this.incomingMessageChain.catch(()=>{}).then(()=>this.processIncomingMessage(t)).catch(n=>{this.connectionStats.totalErrors++,this.log("error","Failed to process queued WebSocket frame",{error:n instanceof Error?n.message:String(n)}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:n,rawMessage:t.data,timestamp:Date.now()})})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async processIncomingMessage(e){if(!(e.data instanceof Blob)){let i=new Error("Unexpected message type: "+typeof e.data);this.connectionStats.totalErrors++,this.log("error","Unexpected WebSocket message type",{error:i.message,messageType:typeof e.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:i,rawMessage:e.data,timestamp:Date.now()});return}let t=await e.data.arrayBuffer();if(t.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}let n;try{n=ze(t)}catch(i){this.connectionStats.totalErrors++,this.log("error","Failed to decode WebSocket frame",{error:i instanceof Error?i.message:String(i),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:i,rawMessage:t,timestamp:Date.now()});return}try{await this.handleRawMessage(n)}catch(i){this.connectionStats.totalErrors++,this.log("error","Failed to process WebSocket frame",{error:i instanceof Error?i.message:String(i),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:i,rawMessage:t,timestamp:Date.now()})}}async handleRawMessage(e){if(this.closed){this.log("debug","Ignoring message received after transport was closed");return}if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:t,event:n,as:i}=e;if(!n||typeof n!="string")throw new N("Message missing event field",e);if(this.log("debug","Processing message",{event:n,hasData:!!t}),n==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(n==="Events.BootError"){let o=new x(t?.message||"Notebook is no longer available",t||{});this.log("error","Boot error received",{data:t}),this.terminate(o,4e3,o.message);return}if(n==="response"){let{responseEvent:o,data:s}=t;if(!o)throw new N("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,s);return}if(n==="error"){let{errorEvent:o,data:s}=t;if(!o)throw new N("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:s}),await this.handleMessage(o,s);return}await this.handleMessage(n,t,i)}catch(t){this.connectionStats.totalErrors++,t instanceof N?this.log("error","Invalid message format",{error:t.message,data:t.data,totalErrors:this.connectionStats.totalErrors}):this.log("error","Failed to parse message",{ev:e,error:t instanceof Error?t.message:String(t),totalErrors:this.connectionStats.totalErrors}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:t,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,t,n){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,t.id);return}e&&this.eventEmitter.emit(n||e,t)}listen(e,t,n){return this.eventEmitter.listen(e,t)}onDidBootError(e){this.eventEmitter.listen("transport.boot_error",t=>{e(t.error)})}removeListener(e,t){this.eventEmitter.removeListener(e,t)}listenOnce(e,t,n){this.eventEmitter.once(e,t,n),this.disposables.add(`once_${e}_${f()}`,{dispose:()=>{this.eventEmitter.removeListener(e,t)}})}emit(e,...t){this.eventEmitter.emit(e,...t)}get isConnected(){return this.status==="OPEN"}get isConnecting(){return this.status==="CONNECTING"}get isDisconnected(){return this.status==="CLOSED"}get isClosed(){return this.closed}getTerminalError(){return this.terminalError}get status(){return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[this.rws.readyState]}async call(e,t={},n={}){if(this.terminalError)throw this.terminalError;this.clearOldQueuedMessages();let i=n.responseEvent||`${e}_${f()}_response`,o=`${i}_error`,s,a=()=>{s&&(this.rws.removeEventListener("close",s),this.rws.removeEventListener("error",s)),this.eventEmitter.removeListener(i),this.eventEmitter.removeListener(o)},c=async(p,l)=>{if(this.terminalError){l(this.terminalError);return}let d=new DOMException("Request aborted","AbortError");if(n.abortSignal?.aborted&&l(d),n.abortSignal&&n.abortSignal.addEventListener("abort",()=>{l(d)}),!this.isConnected&&!this.isClosed){if(this.log("debug","Connection not available, queuing message",{action:e}),this.messageQueue.length>=this.MAX_QUEUE_SIZE){let u=this.messageQueue.shift();u&&u.reject(new Error("Message queue full, oldest message dropped"))}this.messageQueue.push({action:e,data:t,options:n,resolve:p,reject:l,timestamp:Date.now()});return}let y=Date.now();this.listenOnce(i,u=>{let w=Date.now()-y;this.connectionStats.avgResponseTime=(this.connectionStats.avgResponseTime+w)/2,this.connectionStats.totalMessages++,this.log("debug","Message response received",{action:e,responseTime:w,avgResponseTime:this.connectionStats.avgResponseTime}),p(u)}),this.listenOnce(o,u=>{this.connectionStats.totalErrors++,this.log("error","Message error received",{action:e,error:u}),l(new b(u.code,u.message,u))}),s=u=>{if(u.code===1008&&(u.reason||"").includes("rate limit")){l(new U(u.reason||"Rate limit exceeded",u));return}let w=oe(u);l(this.terminalError||new xe(`Connection lost to the notebook during request: ${w}`,u))},this.rws.addEventListener("close",s),this.rws.addEventListener("error",s);try{this.rws.send(this.pack({action:e,data:t,errorEvent:o,responseEvent:i})),this.log("debug","Message sent",{action:e,data:t})}catch(u){throw this.log("error","Failed to send message",{action:e,error:u}),u}},h=async()=>{await E(this,I,Ve).call(this);let p=new Promise(c).finally(a);return n.timeout?$(p,n.timeout).catch(l=>{throw l instanceof S?L.fromPromiseTimeoutError(l):l}).finally(a):p};return this.sendWithRetry(async()=>await h(),n.retries||10)}send(e,t={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:t})),this.connectionStats.totalMessages++,this.log("debug","One-way message sent",{action:e,data:t}),!0}catch(n){return this.connectionStats.totalErrors++,this.log("error","Failed to send one-way message",{action:e,error:n}),!1}}pack(e){return new Blob([$e(e)])}sendWithRetry(e,t=10){return re(async(n,i)=>{try{return await e()}catch(o){if(o instanceof b||o instanceof U||o instanceof R||o instanceof N||o instanceof x||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:i}),n(o);return}throw o instanceof L&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:i,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:i,error:o instanceof Error?o.message:String(o),nextDelay:this.getBackoffDelay(i-1)}),o}},{retries:t,onRetry:(n,i)=>{this.log("warn","Send operation retry",{attempt:i,maxRetries:t,error:n instanceof Error?n.message:String(n)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},n={}){return n.responseEvent||(n.responseEvent=`${e}_${f()}`),this.call("invoke",{action:e,data:t},n)}reconnect(){if(this.terminalError)throw this.terminalError;if(this.closed)throw new Error("Cannot reconnect a closed transport. The transport has been permanently closed.");this.log("info","Reconnecting transport"),this.connectPromise=null,this.rws.reconnect()}disconnect(){if(this.closed){console.trace("Transport is already closed, cannot disconnect again");return}this.close()}terminate(e,t=4e3,n=e.message){this.terminalError=e,e instanceof x&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,n)}close(e,t){if(this.closed)return;this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null;let n=this.messageQueue.length,i=this.terminalError||new Error("Connection closed while message was queued");this.messageQueue.forEach(o=>{o.reject(i)}),this.messageQueue=[],n>0&&this.log("debug",`Rejected ${n} queued messages due to connection close`),this.disposables.dispose();try{this.rws.close(e,t)}catch(o){this.log("error","Error closing WebSocket",{error:o instanceof Error?o.message:String(o)})}this.eventEmitter.emit("transport.closed",{code:e,reason:t,metrics:this.getConnectionMetrics(),timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}onDidConnect(e){this.rws.addEventListener("open",e),this.disposables.add("connect",{dispose:()=>{this.rws.removeEventListener("open",e)}})}onDidClose(e){this.rws.addEventListener("close",e),this.disposables.add("close",{dispose:()=>{this.rws.removeEventListener("close",e)}})}setupConnectionHealthMonitoring(){this.rws.addEventListener("open",()=>{this.connectionStats.connectTime=Date.now(),this.connectionStats.reconnectCount++,this.log("info","Connection established",{reconnectCount:this.connectionStats.reconnectCount,timeSinceStart:Date.now()-this.connectionStats.connectionStartTime}),this.processMessageQueue()}),this.rws.addEventListener("close",e=>{this.log("warn","Connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.handleConnectionClose(e.code)}),this.rws.addEventListener("error",e=>{this.connectionStats.totalErrors++;let t=oe(e);this.log("error","Connection error",{error:t,rawError:e,totalErrors:this.connectionStats.totalErrors})})}handleConnectionClose(e){switch(e){case 1e3:return this.log("info","Normal connection closure"),"stop";case 1001:return this.log("info","Connection going away, will reconnect"),"reconnect";case 1006:return this.log("warn","Abnormal connection closure, will retry"),"retry";case 1008:return this.log("error","Connection closed due to policy violation"),this.clearOldQueuedMessages(),"stop";case 4e3:return this.log("info","Connection closed due to terminal notebook error"),"stop";default:return this.log("warn",`Unknown close code: ${e}, will reconnect`),"reconnect"}}processMessageQueue(){if(this.messageQueue.length===0)return;this.log("debug",`Processing ${this.messageQueue.length} queued messages`);let e=[...this.messageQueue];this.messageQueue=[];for(let t of e){if(Date.now()-t.timestamp>this.QUEUE_TIMEOUT){t.reject(new Error("Queued message timed out"));continue}this.call(t.action,t.data,t.options).then(t.resolve).catch(t.reject)}}clearOldQueuedMessages(){let e=Date.now(),t=this.messageQueue.length;this.messageQueue=this.messageQueue.filter(n=>{let i=e-n.timestamp>this.QUEUE_TIMEOUT;return i&&n.reject(new Error("Queued message expired")),!i}),t!==this.messageQueue.length&&this.log("debug",`Cleared ${t-this.messageQueue.length} expired messages`)}getBackoffDelay(e){return Math.min(1e3*Math.pow(2,e),3e4)+Math.random()*1e3}getConnectionMetrics(){let e=Date.now(),t=this.connectionStats.connectTime>0?e-this.connectionStats.connectTime:0;return{status:this.status,clientId:this.clientId,isConnected:this.isConnected,isConnecting:this.isConnecting,connectionStats:{...this.connectionStats,connectionDuration:t,uptime:e-this.connectionStats.connectionStartTime,messagesPerSecond:t>0?(this.connectionStats.totalMessages/(t/1e3)).toFixed(2):"0",errorRate:this.connectionStats.totalMessages>0?(this.connectionStats.totalErrors/this.connectionStats.totalMessages*100).toFixed(2)+"%":"0%",timeSinceLastPing:this.connectionStats.lastPingTime>0?e-this.connectionStats.lastPingTime:0,timeSinceLastPong:this.connectionStats.lastPongTime>0?e-this.connectionStats.lastPongTime:0},messageQueue:{length:this.messageQueue.length,maxSize:this.MAX_QUEUE_SIZE,oldestMessageAge:this.messageQueue.length>0?e-Math.min(...this.messageQueue.map(n=>n.timestamp)):0},config:{pingInterval:this.PING_INTERVAL,queueTimeout:this.QUEUE_TIMEOUT,url:this.url.toString()}}}getHealthStatus(){let t=this.getConnectionMetrics().connectionStats;return!this.isConnected||t.timeSinceLastPong>this.PING_INTERVAL*2||Number.parseFloat(t.errorRate)>50?"unhealthy":t.avgResponseTime>5e3||Number.parseFloat(t.errorRate)>10||t.timeSinceLastPong>this.PING_INTERVAL*1.5?"degraded":"healthy"}resetStats(){this.connectionStats={connectTime:Date.now(),reconnectCount:0,lastPingTime:0,lastPongTime:0,avgResponseTime:0,totalMessages:0,totalErrors:0,connectionStartTime:Date.now()},this.log("debug","Connection statistics reset")}async runDiagnostics(){let e=this.getConnectionMetrics(),t=this.getHealthStatus(),n=[],i=[];return this.isConnected||(n.push("Connection is not established"),i.push("Check network connectivity and server availability")),e.connectionStats.timeSinceLastPong>this.PING_INTERVAL*2&&(n.push("No pong received recently - connection may be stale"),i.push("Consider forcing a reconnection")),Number.parseFloat(e.connectionStats.errorRate)>10&&(n.push(`High error rate: ${e.connectionStats.errorRate}`),i.push("Check server logs and network stability")),e.messageQueue.length>this.MAX_QUEUE_SIZE*.8&&(n.push("Message queue is nearly full"),i.push("Check connection stability and consider reducing message frequency")),e.connectionStats.avgResponseTime>5e3&&(n.push("High average response time"),i.push("Check network latency and server performance")),this.log("info","Connection diagnostics completed",{status:t,issueCount:n.length,recommendationCount:i.length}),{status:t,metrics:e,issues:n,recommendations:i}}startPeriodicMaintenance(){this.disposables.add("maintenance",()=>{let e=setInterval(()=>{if(this.clearOldQueuedMessages(),this.options.debug){let t=this.getHealthStatus(),n=this.getConnectionMetrics();this.log("debug","Periodic health check",{health:t,messageCount:n.connectionStats.totalMessages,errorCount:n.connectionStats.totalErrors,queueLength:n.messageQueue.length})}},3e5);return{dispose:()=>{clearInterval(e)}}})}};I=new WeakSet,Ve=function(){return this.terminalError?Promise.reject(this.terminalError):this.isConnected?Promise.resolve():this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((e,t)=>{if(this.isConnected){e(),E(this,I,je).call(this);return}let n,i=0,o=()=>{this.rws.removeEventListener("open",s),this.rws.removeEventListener("error",a),this.rws.removeEventListener("close",c),clearTimeout(n)},s=()=>{o(),this.connectPromise=null,e(),E(this,I,je).call(this)},a=h=>{i+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:i,error:oe(h)})},c=h=>{let p=oe(h);if("code"in h&&(h.code===1008||h.code===4e3)){o(),this.connectPromise=null,t(new xe(`WebSocket connection failed: ${p}`,h));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:p})};this.rws.addEventListener("open",s),this.rws.addEventListener("error",a),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),n=setTimeout(()=>{o(),this.connectPromise=null,t(new qe(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},je=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.connectionStats.lastPingTime=Date.now(),this.log("debug","Sending periodic ping");let t=Date.now();await this.invoke("ping"),this.connectionStats.lastPongTime=Date.now();let n=this.connectionStats.lastPongTime-t;this.log("debug","Ping successful",{pingTime:n})}catch(t){this.log("error","Ping failed",{error:t instanceof Error?t.message:String(t)}),Date.now()-this.connectionStats.lastPongTime>this.PING_INTERVAL*3&&(this.log("warn","Connection appears dead, forcing reconnection"),this.rws.reconnect())}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};function wt(r){return{all:r=r||new Map,on:function(e,t){var n=r.get(e);n?n.push(t):r.set(e,[t])},off:function(e,t){var n=r.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var n=r.get(e);n&&n.slice().map(function(i){i(t)}),(n=r.get("*"))&&n.slice().map(function(i){i(e,t)})}}}function mn(r){let e=wt(r);return e.once=(t,n)=>{e.on(t,n),e.on(t,e.off.bind(e,t,n))},e}var A=class r{constructor(){this.emitter=mn()}listen(e,t){let n=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:n}}emit(e,t){this.emitter.emit(e,t)}once(e,t){this.emitter.once(e,t)}static make(){return new r}static refresh(){return new r}removeListener(e,t){this.emitter.off(e,t)}static createInstance(){return new r}inspect(){return this.emitter.all}};var se=class{constructor(e){this.okra=e}checkpoint(e,t,n="main",i=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:n,allowEmpty:i})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,n="main",i,o="both",s=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:n,token:i,direction:o,force:s})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}diff(e){return this.okra.invoke("git.diff",e)}merge(e){return this.okra.invoke("git.merge",e)}conflicts(){return this.okra.invoke("git.conflicts",{})}abortMerge(){return this.okra.invoke("git.resolve",{action:"abort"})}continueMerge(e,t){return this.okra.invoke("git.resolve",{action:"continue",author:e,message:t})}review(){return this.okra.invoke("git.review",{})}stage(e={all:!0}){return this.okra.invoke("git.stage",e)}unstage(e={all:!0}){return this.okra.invoke("git.unstage",e)}revert(e){return this.okra.invoke("git.revert",e)}credentials(){return this.okra.gitCredentials()}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}};var O=class{constructor(e,t,n){this.onEvent=e;this.onceEvent=t;this.beacon=n;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=n,this.setupUrlChangeListener(),this.urlHistory.push(n.iframe.src),this.updateNavigationState()}visit(e){if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState(),this.emitHistoryChange(e,"push")}setupUrlChangeListener(){this.beacon.on("urlChange",e=>{this.addToHistory(e.newUrl)})}addToHistory(e){this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState()}updateNavigationState(){let e=this._canGoBack,t=this._canGoForward;this._canGoBack=this.currentIndex>0,this._canGoForward=this.currentIndex<this.urlHistory.length-1,(e!==this._canGoBack||t!==this._canGoForward)&&this.emitNavigationStateChange()}emitNavigationStateChange(){this.beacon&&this.beacon.emit&&this.beacon.emit("navigationStateChange",{canGoBack:this._canGoBack,canGoForward:this._canGoForward,currentIndex:this.currentIndex,historyLength:this.urlHistory.length,timestamp:Date.now()})}get canGoBack(){return this._canGoBack}get canGoForward(){return this._canGoForward}async goBack(){if(!this.canGoBack)return{success:!1,error:"Cannot go back - no previous history"};this.currentIndex--,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"back"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async goForward(){if(!this.canGoForward)return{success:!1,error:"Cannot go forward - no forward history"};this.currentIndex++,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"forward"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async reload(){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){let e=this.urlHistory[this.currentIndex];if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"reload")}}getCurrentUrl(){return this.currentIndex>=0&&this.currentIndex<this.urlHistory.length?new URL(this.urlHistory[this.currentIndex]):new URL("about:blank")}getHistory(){return[...this.urlHistory]}getCurrentIndex(){return this.currentIndex}canGoBackSync(){return this.currentIndex>0}canGoForwardSync(){return this.currentIndex<this.urlHistory.length-1}emitHistoryChange(e,t){this.beacon&&this.beacon.emit&&this.beacon.emit("historyChange",{url:e,state:null,direction:t,timestamp:Date.now()})}async pushState(e){this.visit(e)}async replaceState(e){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){if(this.urlHistory[this.currentIndex]=e,!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"replace")}else this.visit(e)}async getHistoryLength(){return this.urlHistory.length}async getHistoryState(){return null}async getHistoryInfo(){return{length:this.urlHistory.length,state:null,url:this.urlHistory[this.currentIndex]||"",canGoBack:this.canGoBack,canGoForward:this.canGoForward}}on(e,t){return this.onEvent(e,t)}once(e,t){this.onceEvent(e,t)}};function xt(){if(typeof window>"u")throw new Error("Beacon SDK can only be used in a browser environment")}var _=class extends Error{constructor(t,n){super(t);this.code=n;this.name="BeaconError"}},ae=class extends _{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},v=class extends _{constructor(e){super(`Beacon connection error: ${e}`),this.code="CONNECTION_ERROR"}},ke=class{constructor(e,t={}){this.messageHandlers=new Map;this.isBeaconReady=!1;this.readyPromise=null;this.isStarted=!1;this.disposables=[];this.messageChannel=null;this.port=null;this.channelEstablished=!1;xt(),this.iframe=e;let n={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...n,...t.retry},...t},this.eventEmitter=A.make(),this.setupMessageChannel(),this.navigator=new O(this.eventEmitter.listen.bind(this.eventEmitter),this.eventEmitter.once.bind(this.eventEmitter),this)}setupMessageChannel(){let e=t=>{try{if(t.source!==this.iframe.contentWindow)return;let n=t.data;if(!n||typeof n!="object"||!n.type)return;n.type==="beacon:ready-for-channel"&&this.establishChannel().catch(i=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",i)}),n.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",n.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(n){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",n)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new v("Iframe contentWindow not available");this.messageChannel=new MessageChannel,this.port=this.messageChannel.port1,this.port.onmessage=t=>{this.handleBeaconMessage(t.data)},this.port.onmessageerror=t=>{this.options.debug&&console.error("[Beacon SDK] Port message error:",t)},this.port.start();let e={type:"beacon:establish-channel",timestamp:Date.now(),id:this.generateId()};return this.iframe.contentWindow.postMessage(e,"*",[this.messageChannel.port2]),this.options.debug&&console.log("[Beacon SDK] Channel establishment message sent"),new Promise((t,n)=>{let i=setTimeout(()=>{n(new v("Channel establishment timeout"))},this.options.timeout),o=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(i),t()):setTimeout(o,100)};o()})}handleBeaconMessage(e){this.options.debug&&console.log("[Beacon SDK] Received message:",e.type,e.payload);let t=e.type.replace("beacon:","");this.emit(t,e.payload);let n=this.messageHandlers.get(e.type);n&&n.forEach(i=>{try{i(e.payload)}catch(o){this.options.debug&&console.error("[Beacon SDK] Message handler error:",o)}})}waitForBeaconReady(){return re(async()=>new Promise((e,t)=>{if(this.isBeaconReady&&this.channelEstablished){e();return}let n=this.options.timeout,i=setTimeout(()=>{t(new ae("beacon ready",n))},n),o=this.on("ready",()=>{clearTimeout(i),o.dispose(),e()})}),{retries:this.options.retry?.retries||3,minTimeout:this.options.retry?.minTimeout||1e3,maxTimeout:this.options.retry?.maxTimeout||5e3,factor:this.options.retry?.factor||2,randomize:this.options.retry?.randomize||!0,onRetry:(e,t)=>{if(this.options.debug){let n=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,n)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new v("MessagePort not available - channel not established");let n={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(n),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",n.type,n.payload)}catch(i){throw new v(`Failed to send message via port: ${i instanceof Error?i.message:String(i)}`)}}async sendAndWaitFor(e,t,n={},i){return await this.ready(),re(async o=>new Promise((s,a)=>{let c=i||this.options.timeout,h=setTimeout(()=>{p.dispose();let l=new ae(e,c);a(l)},c),p=this.eventEmitter.listen(t,l=>{clearTimeout(h),p.dispose(),s(l)});try{this.sendMessage(e,n)}catch(l){clearTimeout(h),p.dispose(),l instanceof v?a(l):o(l)}}),{retries:this.options.retry?.retries||3,minTimeout:this.options.retry?.minTimeout||1e3,maxTimeout:this.options.retry?.maxTimeout||5e3,factor:this.options.retry?.factor||2,randomize:this.options.retry?.randomize||!0,onRetry:(o,s)=>{if(this.options.debug){let a=o instanceof Error?o.message:String(o);console.warn(`[Beacon SDK] Retry attempt ${s} for ${e}:`,a)}}})}generateId(){return`sdk_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}emit(e,t){this.eventEmitter.emit(e,t)}start(){return this.isStarted?this.readyPromise||Promise.resolve():(this.isStarted=!0,this.readyPromise=this.waitForBeaconReady(),this.readyPromise)}async ready(){if(!this.isStarted)throw new _("Beacon has not been started. Call start() first.");if(!this.readyPromise)throw new _("Beacon ready promise is not available");return $(this.readyPromise,this.options.timeout)}get isReady(){return this.isBeaconReady}on(e,t){return this.eventEmitter.listen(e,t)}once(e,t){this.eventEmitter.once(e,t)}async ping(){try{return await this.sendAndWaitFor("ping","pong",{timestamp:Date.now()}),!0}catch(e){return this.options.debug&&console.warn("[Beacon SDK] Ping failed:",e),!1}}async getDebugInfo(){return this.sendAndWaitFor("getDebugInfo","debugInfo")}async getConsoleEvents(){return this.sendAndWaitFor("getConsoleEvents","consoleEvents")}async getErrorEvents(){return this.sendAndWaitFor("getErrorEvents","errorEvents")}async clearConsole(){await this.ready(),this.sendMessage("clearConsole")}async clearErrors(){await this.ready(),this.sendMessage("clearErrors")}async executeCode(e){return this.sendAndWaitFor("executeCode","codeExecutionResult",{code:e})}async inspectElement(e){return this.sendAndWaitFor("inspectElement","elementInspectionResult",{selector:e})}async fetch(e){return this.sendAndWaitFor("fetch","fetchResult",e)}async captureScreenshot(e={}){let t=e.mediaTimeoutMs??e.timeout??3e4,n=e.transportTimeoutMs??t+5e3;return this.sendAndWaitFor("captureScreenshot","screenshotResult",e,n)}async debug(e,t){let n=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==n&&(this.navigator.visit(n),await this.ready()),t&&await this.wait(t);let i=(e.options?.timeout||3e4)+5e3;return this.sendAndWaitFor("debug","debugResult",e,i)}async wait(e){return new Promise(t=>setTimeout(t,e*1e3))}navigate(e){if(!this.iframe)throw new v("Iframe not available");try{let t=new URL(e,this.iframe.src||window.location.origin);this.iframe.src=t.href,this.isBeaconReady=!1,this.channelEstablished=!1,this.port&&(this.port.close(),this.port=null),this.messageChannel&&(this.messageChannel=null),this.isStarted&&(this.readyPromise=this.waitForBeaconReady())}catch{throw new v(`Invalid URL: ${e}`)}}get url(){return this.iframe.src}get element(){return this.iframe}dispose(){this.port&&(this.port.close(),this.port=null),this.messageChannel&&(this.messageChannel=null),this.disposables.forEach(e=>e.dispose()),this.disposables=[],this.messageHandlers.clear(),this.isBeaconReady=!1,this.channelEstablished=!1,this.isStarted=!1,this.readyPromise=null}};function Xe(r,e){return new ke(r,e)}function fn(){try{return xt(),!0}catch{return!1}}function bn(r){return Array.isArray(r)?r:Object.entries(r).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var Ee=class extends Error{constructor(t,n={}){super(t);this.message=t;this.data=n;this.name="NotebookInitError"}},Se=class extends Error{constructor(t,n){super(`PHPSandbox API Error: ${t.status} ${t.statusText} - ${n}`);this.response=t;this.body=n;this.status=t.status}},Te=class{constructor(e){this.client=e;this.secrets=new Pe(e),this.preview=new Ce(e),this.mail=new De(e)}async create(e,t={},n=!0){let i=await this.client.post("/notebook",{template:e,...t}),o=new k(i.data,this.client);return n?this.init(o):o}async get(e){let t=await this.client.get(`/notebook/${e}`);return new k(t.data,this.client)}async update(e,t={}){let n=await this.client.put(`/notebook/${e}`,t);return new k(n.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e,t={}){let n=await this.client.post(`/notebook/${e}/fork`,t);return this.init(new k(n.data,this.client))}async gitCredentials(e){return(await this.client.post(`/notebook/${e}/git/credentials`)).data}async open(e){let t=await this.client.get(`/notebook/${e}`);return new k(t.data,this.client)}openFromData(e){return this.init(new k(e,this.client))}async init(e){return await e.ready(),e}},Ie=class{constructor(e,t="https://api.phpsandbox.io/v1",n={}){this.fetch=globalThis.fetch;this.notebook=new Te(this),this.options=Object.assign({startClosed:!0},n),this.baseUrl=t,n.fetch&&(this.fetch=n.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get(e){return this.makeRequest("GET",e)}post(e,t){return this.makeRequest("POST",e,{body:t?JSON.stringify(t):void 0})}delete(e){return this.makeRequest("DELETE",e)}put(e,t){return this.makeRequest("PUT",e,{body:t?JSON.stringify(t):void 0})}async makeRequest(e,t,n){let i=await this.fetch(new Request(new URL(`v1/${t.replace(/^\//,"")}`,this.baseUrl),{method:e,...n,headers:this.headers}));if(!i.ok)throw new Se(i,await i.text());if(i.status===204)return{data:void 0};let o=await i.text();return{data:o===""?void 0:JSON.parse(o)}}},Je=class extends Ie{},Pe=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,n){let i=typeof n=="string"?{name:t,value:n}:{name:t,...n};return(await this.client.put(`/notebook/${e}/secrets`,i)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:bn(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},Ce=class{constructor(e){this.client=e}async get(e){return(await this.client.get(`/notebook/${e}/preview`)).data}async setPassword(e,t){return(await this.client.put(`/notebook/${e}/preview`,t)).data}async disable(e){await this.client.delete(`/notebook/${e}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${e}/preview/session`)).data}async createHandoff(e,t){return(await this.client.post(`/notebook/${e}/preview/handoff`,t)).data}},De=class{constructor(e){this.client=e}async status(e){return(await this.client.get(`/notebook/${e}/mail`)).data}async enable(e){return(await this.client.put(`/notebook/${e}/mail`)).data}async disable(e){await this.client.delete(`/notebook/${e}/mail`)}async list(e,t={}){return(await this.client.get(`/notebook/${e}/mails${vn(t)}`)).data}async get(e,t){return(await this.client.get(`/notebook/${e}/mails/${encodeURIComponent(t)}`)).data}async delete(e,t){await this.client.delete(`/notebook/${e}/mails/${encodeURIComponent(t)}`)}},P,ce,Ye,k=class{constructor(e,t){this.data=e;this.client=t;F(this,ce);this.initialized=!1;F(this,P);this.disposables=[];this.emitter=A.createInstance(),this.socket=new B(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),Me(this,P,E(this,ce,Ye).call(this)),this.file=new G(this),this.terminal=new W(this),this.auth=new z(this),this.lsp=new Q(this),this.composer=new q(this),this.log=new V(this),this.repl=new X(this),this.container=new K(this),this.laravel=new j(this),this.shell=new J(this),this.git=new se(this),this.services=new Y(this),this.config=new Z(this),this.secrets=new Ne(t,this.data.id),this.preview=new Re(t,this.data.id),this.mail=new Ae(t,this.data.id)}async ready(){let e=this.socket.getTerminalError();if(e)throw e;return(async()=>(this.client.options.startClosed&&!this.socket.isConnected&&await this.socket.connect(),le(this,P)))()}fork(e={}){return this.client.notebook.fork(this.data.id,e)}gitCredentials(){return this.client.notebook.gitCredentials(this.data.id)}delete(){return this.client.notebook.delete(this.data.id).then(()=>{this.socket.terminate(new x("Notebook has been deleted.",{id:this.data.id}))})}stop(){return this.container.stop()}restart(){return this.container.start()}invoke(e,t={},n={}){return this.socket.invoke(e,t||{},n)}send(e,t={}){return this.socket.send(e,t||{})}ping(){return this.invoke("ping")}listen(e,t){let n=this.emitter.listen(e,t);return this.disposables.push(n),n}dispose(){this.disposables.forEach(e=>e.dispose()),!this.socket.isClosed&&this.socket.disconnect()}connected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,n)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidClose(()=>n(new Error("Connection closed"))),this.socket.onDidBootError(i=>n(i))}catch(i){n(i)}})}whenConnected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,n)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidBootError(i=>n(i))}catch(i){n(i)}})}watchConnection(){this.socket.onDidConnect(()=>{this.socket.emit("okra.connected"),this.client.options.telemetry&&this.container.enableTelemetry(this.client.options.telemetry)}),this.socket.onDidClose(()=>{this.socket.emit("okra.disconnected"),this.initialized=!1}),this.socket.onDidBootError(e=>{this.socket.emit("okra.boot_error",e),this.socket.emit("okra.disconnected"),this.initialized=!1})}onDidConnect(e){this.socket.removeListener("okra.connected",e);let t=this.socket.listen("okra.connected",e);return this.disposables.push(t),t}onDidDisconnect(e){let t=this.socket.listen("okra.disconnected",e);return this.disposables.push(t),t}onDidBootError(e){let t=this.socket.listen("okra.boot_error",e);return this.disposables.push(t),t}update(){return this.invoke("notebook.update")}onDidInitialize(e){return this.listen("notebook.initialized",e)}async reconnect(){let e=this.whenConnected();return this.socket.reconnect(),this.initialized=!1,await e,E(this,ce,Ye).call(this),this.ready().then(()=>this)}async beacon(e,t){let n=await this.ready();return e.src=n.data.previewUrl,Xe(e,t)}};P=new WeakMap,ce=new WeakSet,Ye=function(){return Me(this,P,new Promise((e,t)=>{let n=this.onDidInitialize(o=>{if(i.dispose(),n.dispose(),this.initialized=o,o.type==="error"){t(new Ee(o.message,o.data));return}e(o)}),i=this.onDidBootError(o=>{n.dispose(),i.dispose(),t(o)})})),le(this,P).catch(()=>{}),le(this,P)};var Ne=class{constructor(e,t){this.client=e;this.notebookId=t}list(){return this.client.notebook.secrets.list(this.notebookId)}set(e,t){return this.client.notebook.secrets.set(this.notebookId,e,t)}setMany(e){return this.client.notebook.secrets.setMany(this.notebookId,e)}delete(e){return this.client.notebook.secrets.delete(this.notebookId,e)}},Re=class{constructor(e,t){this.client=e;this.notebookId=t}get(){return this.client.notebook.preview.get(this.notebookId)}setPassword(e){return this.client.notebook.preview.setPassword(this.notebookId,e)}disable(){return this.client.notebook.preview.disable(this.notebookId)}createSession(){return this.client.notebook.preview.createSession(this.notebookId)}createHandoff(e){return this.client.notebook.preview.createHandoff(this.notebookId,e)}},Ae=class{constructor(e,t){this.client=e;this.notebookId=t}status(){return this.client.notebook.mail.status(this.notebookId)}enable(){return this.client.notebook.mail.enable(this.notebookId)}disable(){return this.client.notebook.mail.disable(this.notebookId)}list(e={}){return this.client.notebook.mail.list(this.notebookId,e)}get(e){return this.client.notebook.mail.get(this.notebookId,e)}delete(e){return this.client.notebook.mail.delete(this.notebookId,e)}};function vn(r){let e=new URLSearchParams;for(let[n,i]of Object.entries(r))(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&e.set(n,String(i));let t=e.toString();return t===""?"":`?${t}`}return Ct(yn);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  reconnecting-websocket/dist/reconnecting-websocket-mjs.js: