@phpsandbox/sdk 0.0.32 → 0.0.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/dist/browser/phpsandbox-sdk.esm.js +49 -7
- package/dist/browser/phpsandbox-sdk.esm.js.map +2 -2
- package/dist/browser/phpsandbox-sdk.esm.min.js +2 -2
- package/dist/browser/phpsandbox-sdk.esm.min.js.map +3 -3
- package/dist/browser/phpsandbox-sdk.iife.js +49 -7
- package/dist/browser/phpsandbox-sdk.iife.js.map +2 -2
- package/dist/browser/phpsandbox-sdk.iife.min.js +2 -2
- package/dist/browser/phpsandbox-sdk.iife.min.js.map +3 -3
- package/dist/index.d.ts +14 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/socket/index.d.ts +1 -0
- package/dist/socket/index.d.ts.map +1 -1
- package/dist/socket/index.js +31 -3
- package/dist/socket/index.js.map +1 -1
- package/dist/terminal.d.ts.map +1 -1
- package/dist/terminal.js +16 -3
- package/dist/terminal.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var vt=Object.create;var $e=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var We=r=>{throw TypeError(r)};var ne=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var kt=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xt(e))!Et.call(r,n)&&n!==t&&$e(r,n,{get:()=>e[n],enumerable:!(i=yt(e,n))||i.enumerable});return r};var Ge=(r,e,t)=>(t=r!=null?vt(wt(r)):{},kt(e||!r||!r.__esModule?$e(t,"default",{value:r,enumerable:!0}):t,r));var ge=(r,e,t)=>e.has(r)||We("Cannot "+t);var be=(r,e,t)=>(ge(r,e,"read from private field"),t?t.call(r):e.get(r)),M=(r,e,t)=>e.has(r)?We("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ve=(r,e,t,i)=>(ge(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),w=(r,e,t)=>(ge(r,e,"access private method"),t);var rt=ne((wn,nt)=>{function b(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}nt.exports=b;b.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};b.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};b.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},t),this._options.unref&&this._timer.unref(),!0};b.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};b.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};b.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};b.prototype.start=b.prototype.try;b.prototype.errors=function(){return this._errors};b.prototype.attempts=function(){return this._attempts};b.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,i=0;i<this._errors.length;i++){var n=this._errors[i],s=n.message,o=(r[s]||0)+1;r[s]=o,o>=t&&(e=n,t=o)}return e}});var st=ne(_=>{var jt=rt();_.operation=function(r){var e=_.timeouts(r);return new jt(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};_.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],n=0;n<e.retries;n++)i.push(this.createTimeout(n,e));return r&&r.forever&&!i.length&&i.push(this.createTimeout(n,e)),i.sort(function(s,o){return s-o}),i};_.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,i=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return i=Math.min(i,e.maxTimeout),i};_.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var i in r)typeof r[i]=="function"&&t.push(i)}for(var n=0;n<t.length;n++){var s=t[n],o=r[s];r[s]=function(c){var p=_.operation(e),u=Array.prototype.slice.call(arguments,1),l=u.pop();u.push(function(d){p.retry(d)||(d&&(arguments[0]=p.mainError()),l.apply(this,arguments))}),p.attempt(function(){c.apply(r,u)})}.bind(r,o),r[s].options=e}}});var at=ne((kn,ot)=>{ot.exports=st()});var De=ne((Sn,ct)=>{var ei=at();function ti(r,e){function t(i,n){var s=e||{},o;"randomize"in s||(s.randomize=!0),o=ei.operation(s);function a(u){n(u||new Error("Aborted"))}function c(u,l){if(u.bail){a(u);return}o.retry(u)?s.onRetry&&s.onRetry(u,l):n(o.mainError())}function p(u){var l;try{l=r(a,u)}catch(d){c(d,u);return}Promise.resolve(l).then(i).catch(function(v){c(v,u)})}o.attempt(p)}return new Promise(t)}ct.exports=ti});var y=class extends Error{constructor(t,i,n={}){super(i);this.code=t;this.message=i;this.raw=n}},N=class extends y{constructor(e,t={}){super(429,e,t)}},qe=class extends y{};var Qe="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var g=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Qe[t[r]&63];return e};var St=(n=>(n[n.Unknown=0]="Unknown",n[n.File=1]="File",n[n.Directory=2]="Directory",n[n.SymbolicLink=64]="SymbolicLink",n))(St||{}),Tt=(i=>(i[i.UPDATED=1]="UPDATED",i[i.ADDED=2]="ADDED",i[i.DELETED=3]="DELETED",i))(Tt||{}),It=(o=>(o.Unavailable="Unavailable",o.NoPermissions="NoPermissions",o.FileExists="FileExists",o.FileNotFound="FileNotFound",o.FileIsADirectory="FileIsADirectory",o.FileNotADirectory="FileNotADirectory",o))(It||{}),ye=class extends y{constructor(t,i){super(t.code,t.message);this.name=i}},xe=class{constructor(e,t,i){this.path=e;this.okra=t;this.disposable=i}dispose(){this.okra.invoke("fs.unwatch",{path:this.path}),this.disposable.dispose()}},re=class{constructor(e){this.okra=e;this.watches=new Map;this.watchOkraConnection()}watchOkraConnection(){this.okra.onDidConnect(()=>{for(let{path:e,options:t,onDidChange:i}of this.watches.values())this.watch(e,t,i)})}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,i){e.id||(e.id=g());let n={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}},s=e.id,o=async c=>{c===!1&&a.dispose(),i&&await Promise.resolve(i(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${s}`,o);return this.okra.invoke("fs.textSearch",{query:e,options:{...n,...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 i=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return i instanceof Uint8Array?i:typeof i=="string"?new TextEncoder().encode(i):i}catch(i){this.handleError(i)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(i=>this.handleError(i))}writeFile(e,t,i){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:i}).catch(n=>this.handleError(n))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,i){return this.okra.invoke("fs.rename",{from:e,to:t,options:i}).catch(n=>this.handleError(n))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(i=>this.handleError(i))}copy(e,t,i){return this.okra.invoke("fs.copy",{source:e,destination:t,options:i}).catch(n=>this.handleError(n))}readDirectory(e,t=[],i=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:i}).catch(n=>this.handleError(n))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,i){let n=this.okra.listen(`fs.watch.${e}`,i),s={dispose:()=>{n.dispose(),this.okra.invoke("fs.unwatch",{path:e})}},o=new xe(e,this.okra,s);return this.watches.set(e,{options:t,path:e,onDidChange:i}),this.okra.invoke("fs.watch",{path:e,options:t}).then(()=>o)}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e,t,i){let n=g(),s=!!e,o=[];return this.okra.listen(`fs.download.${n}`,s?e:a=>{o.push(a)}),this.okra.invoke("fs.download",{id:n,exclude:t,include:i}).then(()=>new Blob(o,{type:"application/octet-stream"}))}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e instanceof y&&"name"in e.raw?new ye(e,e.raw.name):e}};var I=class extends Error{constructor(t,i){super(t);this.time=i}},O=class r extends I{static fromPromiseTimeoutError(e){return new r(e.message,e.time)}},E=class extends Error{constructor(t="Notebook is no longer available",i={}){super(t);this.raw=i;this.name="NotebookUnavailableError"}};var se=(r,e)=>{let t;return Promise.race([r,new Promise((i,n)=>t=setTimeout(n,e,new I("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},oe=r=>{let e=null;return()=>e||(e=r())};var F=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 this.okra.invoke("terminal.input",{id:e,input:t})}listen(e,t){return this.okra.listen(e,t)}async spawn(e,t,i){let n=i?.id||g(),s=new Set,o=()=>{for(let m of s)m.dispose();s.clear()},a=new WritableStream({write:m=>{this.input(n,m)},close:o}),c=new ReadableStream({start:m=>{s.add(this.listen(`terminal.output.${n}`,fe=>{m.enqueue(fe.output)}))},cancel:o}),p=new Promise(m=>{s.add(this.listen(`terminal.close.${n}`,fe=>{o(),m(fe.exitCode)}))}),u=oe(()=>(o(),this.okra.invoke("terminal.close",{id:n}))),l=m=>{this.okra.invoke("terminal.resize",{id:n,width:m.cols,height:m.rows})},{abortSignal:d,...v}=i??{};d&&d.addEventListener("abort",u);let h=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:n,...v}},{abortSignal:d});return{exit:p,input:a,output:c,kill:u,resize:l,...h}}};var Ct=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(Ct||{}),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",i=>{for(let n of i)t.some(s=>s.port===n.port)||e(n,"open");for(let n of t)i.some(s=>s.port===n.port)||e(n,"close");t=i})}};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 H=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,i){this.okra.listen(`${t}.${e}`,n=>i(n))}onClose(e,t){this.listen(e,"lsp.closed",i=>t(i.code,i.reason))}onError(e,t){this.listen(e,"lsp.error",i=>t(i.message))}onClientDisconnect(e){this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){this.listen(e,"lsp.response",i=>t(JSON.stringify(i)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return we.create(e,this)}whenSocketConnected(){return this.okra.whenConnected()}},we=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 $=class{constructor(e){this.okra=e}invoke(e,t={},i={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:i})}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 W=class{constructor(e){this.okra=e}stream(e){return this.okra.listen("notebook.log",e)}listen(e,t){this.okra.listen(e,t)}};var G=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 q=class{constructor(e){this.okra=e}eval(e,t="",i={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:i})}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 Ve(r,e=[],t){let i=Array.isArray(e)?e:[],n=Array.isArray(e)?t:e;return{command:Array.isArray(r)?r:i.length>0?[r,...i]:r,opts:n}}var Ee=class extends Error{constructor(t,i){super(t);this.output=t;this.exitCode=i}},ke=class{constructor(e,t){this.output=e;this.exitCode=t}throw(){if(this.exitCode!==0)throw new Ee(this.output,this.exitCode);return this}},Q=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=[],i){let n=Ve(e,t,i),{abortSignal:s,...o}=n.opts??{},a=await this.okra.invoke("shell.exec",{command:n.command,opts:Object.keys(o).length>0?o:void 0},{abortSignal:s});return new ke(a.output,a.exitCode)}execStream(e,t=[],i){let n=Ve(e,t,i),s=n.opts?.id||g(),o=new Set,a=null,c=!1,p=()=>{for(let h of o)h.dispose();o.clear()},u=()=>{if(!c&&(c=!0,p(),a))try{a.close()}catch{}},l=h=>{c||(c=!0,p(),a&&a.error(h))},d=new ReadableStream({start:h=>{a=h,o.add(this.listen(`shell.output.${s}`,m=>{a?.enqueue(m.output)}))},cancel:()=>{c=!0,p()}}),v=this.exec(n.command,{...n.opts,id:s}).then(h=>(u(),h)).catch(h=>{throw l(h),h});return{output:d,result:v}}};var _t=["redis"],Mi=["start","nginx",..._t],V=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(i=>{if(!("output"in i))throw new Error(`Unexpected service.logs response for ${e}`);return i.output})}followLogs(e,t){let i=t.id||g(),n=new Set,s=null,o=!1,a=()=>{for(let d of n)d.dispose();n.clear()},c=()=>{if(!o&&(o=!0,a(),s))try{s.close()}catch{}},p=d=>{o||(o=!0,a(),s&&s.error(d))},u=oe(()=>(c(),this.okra.invoke("service.stop-logs",{id:i}))),l=new ReadableStream({start:d=>{s=d,n.add(this.onLog(i,v=>{s?.enqueue(v.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:i}).catch(v=>{p(v)})},cancel:()=>{u()}});return{id:i,output:l,stop:u}}};function Xe(r){let e=r.length,t=0,i=0;for(;i<e;){let n=r.charCodeAt(i++);if((n&4294967168)===0){t++;continue}else if((n&4294965248)===0)t+=2;else{if(n>=55296&&n<=56319&&i<e){let s=r.charCodeAt(i);(s&64512)===56320&&(++i,n=((n&1023)<<10)+(s&1023)+65536)}(n&4294901760)===0?t+=3:t+=4}}return t}function Pt(r,e,t){let i=r.length,n=t,s=0;for(;s<i;){let o=r.charCodeAt(s++);if((o&4294967168)===0){e[n++]=o;continue}else if((o&4294965248)===0)e[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<i){let a=r.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[n++]=o>>12&15|224,e[n++]=o>>6&63|128):(e[n++]=o>>18&7|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128)}e[n++]=o&63|128}}var Dt=new TextEncoder,At=50;function Rt(r,e,t){Dt.encodeInto(r,e.subarray(t))}function Je(r,e,t){r.length>At?Rt(r,e,t):Pt(r,e,t)}var Nt=4096;function Se(r,e,t){let i=e,n=i+t,s=[],o="";for(;i<n;){let a=r[i++];if((a&128)===0)s.push(a);else if((a&224)===192){let c=r[i++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){let c=r[i++]&63,p=r[i++]&63;s.push((a&31)<<12|c<<6|p)}else if((a&248)===240){let c=r[i++]&63,p=r[i++]&63,u=r[i++]&63,l=(a&7)<<18|c<<12|p<<6|u;l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|l&1023),s.push(l)}else s.push(a);s.length>=Nt&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}var Ut=new TextDecoder,Lt=200;function Bt(r,e,t){let i=r.subarray(e,e+t);return Ut.decode(i)}function Ye(r,e,t){return t>Lt?Bt(r,e,t):Se(r,e,t)}var C=class{constructor(e,t){this.type=e,this.data=t}};var f=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 Ze(r,e,t){let i=t/4294967296,n=t;r.setUint32(e,i),r.setUint32(e+4,n)}function ae(r,e,t){let i=Math.floor(t/4294967296),n=t;r.setUint32(e,i),r.setUint32(e+4,n)}function ce(r,e){let t=r.getInt32(e),i=r.getUint32(e+4);return t*4294967296+i}function je(r,e){let t=r.getUint32(e),i=r.getUint32(e+4);return t*4294967296+i}var Mt=-1,Ot=4294967296-1,Ft=17179869184-1;function Kt({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Ft)if(e===0&&r<=Ot){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{let t=r/4294967296,i=r&4294967295,n=new Uint8Array(8),s=new DataView(n.buffer);return s.setUint32(0,e<<2|t&3),s.setUint32(4,i),n}else{let t=new Uint8Array(12),i=new DataView(t.buffer);return i.setUint32(0,e),ae(i,4,r),t}}function zt(r){let e=r.getTime(),t=Math.floor(e/1e3),i=(e-t*1e3)*1e6,n=Math.floor(i/1e9);return{sec:t+n,nsec:i-n*1e9}}function Ht(r){if(r instanceof Date){let e=zt(r);return Kt(e)}else return null}function $t(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),i=e.getUint32(4),n=(t&3)*4294967296+i,s=t>>>2;return{sec:n,nsec:s}}case 12:{let t=ce(e,4),i=e.getUint32(0);return{sec:t,nsec:i}}default:throw new f(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function Wt(r){let e=$t(r);return new Date(e.sec*1e3+e.nsec/1e6)}var et={type:Mt,encode:Ht,decode:Wt};var k=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(et)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{let n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){let n=this.builtInEncoders[i];if(n!=null){let s=n(e,t);if(s!=null){let o=-1-i;return new C(o,s)}}}for(let i=0;i<this.encoders.length;i++){let n=this.encoders[i];if(n!=null){let s=n(e,t);if(s!=null){let o=i;return new C(o,s)}}}return e instanceof C?e:null}decode(e,t,i){let n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,i):new C(t,e)}};k.defaultCodec=new k;function Gt(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function X(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Gt(r)?new Uint8Array(r):Uint8Array.from(r)}var qt=100,Qt=2048,le=class r{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??k.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??qt,this.initialBufferSize=e?.initialBufferSize??Qt,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),i=new Uint8Array(t),n=new DataView(t);i.set(this.bytes),this.view=n,this.bytes=i}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 i=Xe(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),Je(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,t){let i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);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 i=X(e);this.writeU8a(i)}encodeArray(e,t){let i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(let n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let i=0;for(let n of t)e[n]!==void 0&&i++;return i}encodeMap(e,t){let i=Object.keys(e);this.sortKeys&&i.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let s of i){let o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let i=e.data(this.pos+6),n=i.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(i);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),Ze(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ae(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 Te(r,e){return new le(e).encodeSharedRef(r)}function ue(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var Vt=16,Xt=16,he=class{constructor(e=Vt,t=Xt){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){let n=this.caches[i-1];e:for(let s of n){let o=s.bytes;for(let a=0;a<i;a++)if(o[a]!==e[t+a])continue e;return s.str}return null}store(e,t){let i=this.caches[e.length-1],n={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=n:i.push(n)}decode(e,t,i){let n=this.find(e,t,i);if(n!=null)return this.hit++,n;this.miss++;let s=Se(e,t,i),o=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(o,s),s}};var Ie="array",Z="map_key",it="map_value",Jt=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new f("The type of key must be string or number but "+typeof r)},Ce=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=Ie,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=Z,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===Ie){let i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Z||e.type===it){let i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Y=-1,_e=new DataView(new ArrayBuffer(0)),Yt=new Uint8Array(_e.buffer);try{_e.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 tt=new RangeError("Insufficient data"),Zt=new he,pe=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=_e,this.bytes=Yt,this.headByte=Y,this.stack=new Ce,this.entered=!1,this.extensionCodec=e?.extensionCodec??k.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:Zt,this.mapKeyConverter=e?.mapKeyConverter??Jt}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=Y,this.stack.reset()}setBuffer(e){let t=X(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Y&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),i=X(e),n=new Uint8Array(t.length+i.length);n.set(t),n.set(i,t.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} 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,i;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=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 i}let{headByte:n,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${ue(n)} at ${o} (${s} 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 i=t,n=-1;for await(let s of e){if(t&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),i&&(n=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(o){if(!(o instanceof RangeError))throw o}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 n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{let n=e-160;t=this.decodeString(n,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 n=this.lookU8();t=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();t=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();t=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){let n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();t=this.decodeBinary(n,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 n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();t=this.decodeExtension(n,4)}else throw new f(`Unrecognized type byte: ${ue(e)}`);this.complete();let i=this.stack;for(;i.length>0;){let n=i.top();if(n.type===Ie)if(n.array[n.position]=t,n.position++,n.position===n.size)t=n.array,i.release(n);else continue e;else if(n.type===Z){if(t==="__proto__")throw new f("The key __proto__ is not allowed");n.key=this.mapKeyConverter(t),n.type=it;continue e}else if(n.map[n.key]=t,n.readCount++,n.readCount===n.size)t=n.map,i.release(n);else{n.key=null,n.type=Z;continue e}}return t}}readHeadByte(){return this.headByte===Y&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Y}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 f(`Unrecognized array type byte: ${ue(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new f(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new f(`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 f(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw tt;let i=this.pos+t,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,i,e):n=Ye(this.bytes,i,e),this.pos+=t+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Z:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new f(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw tt;let i=this.pos+t,n=this.bytes.subarray(i,i+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new f(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let i=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,i,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=je(this.view,this.pos);return this.pos+=8,e}readI64(){let e=ce(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 Pe(r,e){return new pe(e).decode(r)}var dt=Ge(De(),1);var Ae=function(r,e){return Ae=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])},Ae(r,e)};function lt(r,e){Ae(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function ii(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 ni(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return s}function ri(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(ni(arguments[e]));return r}var ut=(function(){function r(e,t){this.target=t,this.type=e}return r})(),si=(function(r){lt(e,r);function e(t,i){var n=r.call(this,"error",i)||this;return n.message=t.message,n.error=t,n}return e})(ut),oi=(function(r){lt(e,r);function e(t,i,n){t===void 0&&(t=1e3),i===void 0&&(i="");var s=r.call(this,"close",n)||this;return s.wasClean=!0,s.code=t,s.reason=i,s}return e})(ut);var ai=function(){if(typeof WebSocket<"u")return WebSocket},ci=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},P={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},li=(function(){function r(e,t,i){var n=this;i===void 0&&(i={}),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(s){n._debug("open event");var o=n._options.minUptime,a=o===void 0?P.minUptime:o;clearTimeout(n._connectTimeout),n._uptimeTimeout=setTimeout(function(){return n._acceptOpen()},a),n._ws.binaryType=n._binaryType,n._messageQueue.forEach(function(c){return n._ws.send(c)}),n._messageQueue=[],n.onopen&&n.onopen(s),n._listeners.open.forEach(function(c){return n._callEventListener(s,c)})},this._handleMessage=function(s){n._debug("message event"),n.onmessage&&n.onmessage(s),n._listeners.message.forEach(function(o){return n._callEventListener(s,o)})},this._handleError=function(s){n._debug("error event",s.message),n._disconnect(void 0,s.message==="TIMEOUT"?"timeout":void 0),n.onerror&&n.onerror(s),n._debug("exec error listeners"),n._listeners.error.forEach(function(o){return n._callEventListener(s,o)}),n._connect()},this._handleClose=function(s){n._debug("close event"),n._clearTimeouts(),n._shouldReconnect&&n._connect(),n.onclose&&n.onclose(s),n._listeners.close.forEach(function(o){return n._callEventListener(s,o)})},this._url=e,this._protocols=t,this._options=i,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,i){return typeof i=="string"?t+=i.length:i instanceof Blob?t+=i.size:t+=i.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,i=t===void 0?P.maxEnqueuedMessages:t;this._messageQueue.length<i&&(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,i,n=this._listeners[e.type];if(n)try{for(var s=ii(n),o=s.next();!o.done;o=s.next()){var a=o.value;this._callEventListener(e,a)}}catch(c){t={error:c}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}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(i){return i!==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,ri(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,i=t===void 0?P.reconnectionDelayGrowFactor:t,n=e.minReconnectionDelay,s=n===void 0?P.minReconnectionDelay:n,o=e.maxReconnectionDelay,a=o===void 0?P.maxReconnectionDelay:o,c=0;return this._retryCount>0&&(c=s*Math.pow(i,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,i=t.maxRetries,n=i===void 0?P.maxRetries:i,s=t.connectionTimeout,o=s===void 0?P.connectionTimeout:s,a=t.WebSocket,c=a===void 0?ai():a;if(this._retryCount>=n){this._debug("max retries reached",this._retryCount,">=",n);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!ci(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(p){e._closeCalled||(e._debug("connect",{url:p,protocols:e._protocols}),e._ws=e._protocols?new c(p,e._protocols):new c(p),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},o))})}},r.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new si(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 oi(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})(),ht=li;var U=null;typeof WebSocket<"u"?U=WebSocket:typeof MozWebSocket<"u"?U=MozWebSocket:typeof global<"u"?U=global.WebSocket||global.MozWebSocket:typeof window<"u"?U=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(U=self.WebSocket||self.MozWebSocket);var pt=U;var de=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 D=class extends Error{constructor(t,i){super(t);this.data=i;this.name="InvalidMessageError"}},L=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},S,Re,Ne,j=class{constructor(e,t,i={}){this.eventEmitter=t;this.options=i;M(this,S);this.clientId="";this.closed=!1;this.disposables=new de;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.rateLimiter={requests:[],maxRequests:50,windowMs:1e3};this.validateConfiguration(i),this.url=new URL(e),this.PING_INTERVAL=i.pingInterval??3e4,this.connectionStats.connectionStartTime=Date.now();let n=i.startClosed!==!1;this.rws=new ht(this.url.toString(),[],{WebSocket:globalThis.WebSocket??pt,connectionTimeout:i.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:i.maxRetries??50,startClosed:n}),this.log("debug","Transport initialized",{url:this.url.toString(),options:i}),this.registerWatchers(),this.setupConnectionHealthMonitoring(),this.startPeriodicMaintenance()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new L("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new L("connectionTimeout must be between 100ms and 30000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new L("maxRetries must be between 0 and 100")}log(e,t,i){if(this.options.debug){let n=new Date().toISOString(),s=i?JSON.stringify(i,null,2):"";console[e](`[Transport ${n}] ${t}${s?`
|
|
2
|
-
`+s:""}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):w(this,S,Re).call(this)}id(){return this.clientId}async registerWatchers(){let e=t=>{if(!(t.data instanceof Blob))throw new Error("Unexpected message type: "+typeof t.data);t.data.arrayBuffer().then(i=>{if(i.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}try{this.handleRawMessage(Pe(i))}catch(n){this.connectionStats.totalErrors++,this.log("error","Failed to decode WebSocket frame",{error:n instanceof Error?n.message:String(n),byteLength:i.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:n,rawMessage:i,timestamp:Date.now()})}})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async handleRawMessage(e){if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:t,event:i,as:n}=e;if(!i||typeof i!="string")throw new D("Message missing event field",e);if(this.log("debug","Processing message",{event:i,hasData:!!t}),i==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(i==="Events.BootError"){let s=new E(t?.message||"Notebook is no longer available",t||{});this.log("error","Boot error received",{data:t}),this.terminate(s,4e3,s.message);return}if(i==="response"){let{responseEvent:s,data:o}=t;if(!s)throw new D("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:s}),await this.handleMessage(s,o);return}if(i==="error"){let{errorEvent:s,data:o}=t;if(!s)throw new D("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:s,errorData:o}),await this.handleMessage(s,o);return}await this.handleMessage(i,t,n)}catch(t){this.connectionStats.totalErrors++,t instanceof D?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,i){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,t.id);return}e&&this.eventEmitter.emit(i||e,t)}listen(e,t,i){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,i){this.eventEmitter.once(e,t,i),this.disposables.add(`once_${e}_${g()}`,{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={},i={}){if(this.terminalError)throw this.terminalError;if(this.isRateLimited())throw new N("Rate limit exceeded - too many requests");this.clearOldQueuedMessages();let n=i.responseEvent||`${e}_${g()}_response`,s=`${n}_error`,o,a=()=>{o&&(this.rws.removeEventListener("close",o),this.rws.removeEventListener("error",o)),this.eventEmitter.removeListener(n),this.eventEmitter.removeListener(s)},c=async(u,l)=>{if(this.terminalError){l(this.terminalError);return}let d=new DOMException("Request aborted","AbortError");if(i.abortSignal?.aborted&&l(d),i.abortSignal&&i.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 h=this.messageQueue.shift();h&&h.reject(new Error("Message queue full, oldest message dropped"))}this.messageQueue.push({action:e,data:t,options:i,resolve:u,reject:l,timestamp:Date.now()});return}let v=Date.now();this.listenOnce(n,h=>{let m=Date.now()-v;this.connectionStats.avgResponseTime=(this.connectionStats.avgResponseTime+m)/2,this.connectionStats.totalMessages++,this.log("debug","Message response received",{action:e,responseTime:m,avgResponseTime:this.connectionStats.avgResponseTime}),u(h)}),this.listenOnce(s,h=>{this.connectionStats.totalErrors++,this.log("error","Message error received",{action:e,error:h}),l(new y(h.code,h.message,h))}),o=h=>{if(h.code===1008&&(h.reason||"").includes("rate limit")){l(new N(h.reason||"Rate limit exceeded",h));return}l(this.terminalError||new Error(`Connection lost to the notebook during request: ${h.reason||"Unknown reason"}`))},this.rws.addEventListener("close",o),this.rws.addEventListener("error",o);try{this.rws.send(this.pack({action:e,data:t,errorEvent:s,responseEvent:n})),this.log("debug","Message sent",{action:e,data:t})}catch(h){throw this.log("error","Failed to send message",{action:e,error:h}),h}},p=async()=>{await w(this,S,Re).call(this);let u=new Promise(c).finally(a);return i.timeout?se(u,i.timeout).catch(l=>{throw l instanceof I?O.fromPromiseTimeoutError(l):l}).finally(a):u};return this.sendWithRetry(async()=>await p(),i.retries||10)}pack(e){return new Blob([Te(e)])}sendWithRetry(e,t=10){return(0,dt.default)(async(i,n)=>{try{return await e()}catch(s){if(s instanceof y||s instanceof N||s instanceof L||s instanceof D||s instanceof E||s instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:s.message,attempt:n}),i(s);return}throw s instanceof O&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:n,timeout:s.time})),this.log("debug","Retrying send operation",{attempt:n,error:s instanceof Error?s.message:String(s),nextDelay:this.getBackoffDelay(n-1)}),s}},{retries:t,onRetry:(i,n)=>{this.log("warn","Send operation retry",{attempt:n,maxRetries:t,error:i instanceof Error?i.message:String(i)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},i={}){return i.responseEvent||(i.responseEvent=`${e}_${g()}`),this.call("invoke",{action:e,data:t},i)}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,i=e.message){this.terminalError=e,e instanceof E&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,i)}close(e,t){if(this.closed)return;this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null;let i=this.messageQueue.length,n=this.terminalError||new Error("Connection closed while message was queued");this.messageQueue.forEach(s=>{s.reject(n)}),this.messageQueue=[],i>0&&this.log("debug",`Rejected ${i} queued messages due to connection close`),this.rateLimiter.requests=[],this.disposables.dispose();try{this.rws.close(e,t)}catch(s){this.log("error","Error closing WebSocket",{error:s instanceof Error?s.message:String(s)})}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++,this.log("error","Connection error",{error: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(i=>{let n=e-i.timestamp>this.QUEUE_TIMEOUT;return n&&i.reject(new Error("Queued message expired")),!n}),t!==this.messageQueue.length&&this.log("debug",`Cleared ${t-this.messageQueue.length} expired messages`)}isRateLimited(){let e=Date.now();return this.rateLimiter.requests=this.rateLimiter.requests.filter(t=>e-t<this.rateLimiter.windowMs),this.rateLimiter.requests.length>=this.rateLimiter.maxRequests?!0:(this.rateLimiter.requests.push(e),!1)}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(i=>i.timestamp)):0},rateLimiter:{currentRequests:this.rateLimiter.requests.length,maxRequests:this.rateLimiter.maxRequests,windowMs:this.rateLimiter.windowMs,isLimited:this.isRateLimited()},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(),i=[],n=[];return this.isConnected||(i.push("Connection is not established"),n.push("Check network connectivity and server availability")),e.connectionStats.timeSinceLastPong>this.PING_INTERVAL*2&&(i.push("No pong received recently - connection may be stale"),n.push("Consider forcing a reconnection")),Number.parseFloat(e.connectionStats.errorRate)>10&&(i.push(`High error rate: ${e.connectionStats.errorRate}`),n.push("Check server logs and network stability")),e.messageQueue.length>this.MAX_QUEUE_SIZE*.8&&(i.push("Message queue is nearly full"),n.push("Check connection stability and consider reducing message frequency")),e.connectionStats.avgResponseTime>5e3&&(i.push("High average response time"),n.push("Check network latency and server performance")),e.rateLimiter.isLimited&&(i.push("Rate limiting is active"),n.push("Reduce request frequency or increase rate limit")),this.log("info","Connection diagnostics completed",{status:t,issueCount:i.length,recommendationCount:n.length}),{status:t,metrics:e,issues:i,recommendations:n}}startPeriodicMaintenance(){this.disposables.add("maintenance",()=>{let e=setInterval(()=>{this.clearOldQueuedMessages();let t=Date.now();if(this.rateLimiter.requests=this.rateLimiter.requests.filter(i=>t-i<this.rateLimiter.windowMs),this.options.debug){let i=this.getHealthStatus(),n=this.getConnectionMetrics();this.log("debug","Periodic health check",{health:i,messageCount:n.connectionStats.totalMessages,errorCount:n.connectionStats.totalErrors,queueLength:n.messageQueue.length})}},3e5);return{dispose:()=>{clearInterval(e)}}})}};S=new WeakSet,Re=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(),w(this,S,Ne).call(this);return}this.rws.readyState===3&&this.rws.reconnect();let i,n=()=>{this.rws.removeEventListener("open",n),this.rws.removeEventListener("error",s),clearTimeout(i),this.connectPromise=null,e(),w(this,S,Ne).call(this)},s=o=>{this.rws.removeEventListener("open",n),this.rws.removeEventListener("error",s),clearTimeout(i),this.connectPromise=null,t(new Error(`WebSocket connection failed: ${o}`))};i=setTimeout(()=>{this.rws.removeEventListener("open",n),this.rws.removeEventListener("error",s),this.connectPromise=null,t(new Error("WebSocket connection timeout"))},1e4),this.rws.addEventListener("open",n),this.rws.addEventListener("error",s)}),this.connectPromise)},Ne=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 i=this.connectionStats.lastPongTime-t;this.log("debug","Ping successful",{pingTime:i})}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 mt(r){return{all:r=r||new Map,on:function(e,t){var i=r.get(e);i?i.push(t):r.set(e,[t])},off:function(e,t){var i=r.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var i=r.get(e);i&&i.slice().map(function(n){n(t)}),(i=r.get("*"))&&i.slice().map(function(n){n(e,t)})}}}function ui(r){let e=mt(r);return e.once=(t,i)=>{e.on(t,i),e.on(t,e.off.bind(e,t,i))},e}var A=class r{constructor(){this.emitter=ui()}listen(e,t){let i=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:i}}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 ee=class{constructor(e){this.okra=e}checkpoint(e,t,i="main",n=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:i,allowEmpty:n})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,i="main",n,s="both",o=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:i,token:n,direction:s,force:o})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}};var Ue=Ge(De(),1);var te=class{constructor(e,t,i){this.onEvent=e;this.onceEvent=t;this.beacon=i;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=i,this.setupUrlChangeListener(),this.urlHistory.push(i.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 ft(){if(typeof window>"u")throw new Error("Beacon SDK can only be used in a browser environment")}var B=class extends Error{constructor(t,i){super(t);this.code=i;this.name="BeaconError"}},me=class extends B{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},x=class extends B{constructor(e){super(`Beacon connection error: ${e}`),this.code="CONNECTION_ERROR"}},Le=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;ft(),this.iframe=e;let i={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...i,...t.retry},...t},this.eventEmitter=A.make(),this.setupMessageChannel(),this.navigator=new te(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 i=t.data;if(!i||typeof i!="object"||!i.type)return;i.type==="beacon:ready-for-channel"&&this.establishChannel().catch(n=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",n)}),i.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",i.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(i){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",i)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new x("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,i)=>{let n=setTimeout(()=>{i(new x("Channel establishment timeout"))},this.options.timeout),s=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(n),t()):setTimeout(s,100)};s()})}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 i=this.messageHandlers.get(e.type);i&&i.forEach(n=>{try{n(e.payload)}catch(s){this.options.debug&&console.error("[Beacon SDK] Message handler error:",s)}})}waitForBeaconReady(){return(0,Ue.default)(async()=>new Promise((e,t)=>{if(this.isBeaconReady&&this.channelEstablished){e();return}let i=this.options.timeout,n=setTimeout(()=>{t(new me("beacon ready",i))},i),s=this.on("ready",()=>{clearTimeout(n),s.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 i=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,i)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new x("MessagePort not available - channel not established");let i={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(i),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",i.type,i.payload)}catch(n){throw new x(`Failed to send message via port: ${n instanceof Error?n.message:String(n)}`)}}async sendAndWaitFor(e,t,i={},n){return await this.ready(),(0,Ue.default)(async s=>new Promise((o,a)=>{let c=n||this.options.timeout,p=setTimeout(()=>{u.dispose();let l=new me(e,c);a(l)},c),u=this.eventEmitter.listen(t,l=>{clearTimeout(p),u.dispose(),o(l)});try{this.sendMessage(e,i)}catch(l){clearTimeout(p),u.dispose(),l instanceof x?a(l):s(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:(s,o)=>{if(this.options.debug){let a=s instanceof Error?s.message:String(s);console.warn(`[Beacon SDK] Retry attempt ${o} 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 B("Beacon has not been started. Call start() first.");if(!this.readyPromise)throw new B("Beacon ready promise is not available");return se(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 debug(e,t){let i=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==i&&(this.navigator.visit(i),await this.ready()),t&&await this.wait(t);let n=(e.options?.timeout||3e4)+5e3;return this.sendAndWaitFor("debug","debugResult",e,n)}async wait(e){return new Promise(t=>setTimeout(t,e*1e3))}navigate(e){if(!this.iframe)throw new x("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 x(`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 gt(r,e){return new Le(r,e)}function Yn(){try{return ft(),!0}catch{return!1}}function hi(r){return Array.isArray(r)?r:Object.entries(r).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var Be=class extends Error{constructor(t,i={}){super(t);this.message=t;this.data=i;this.name="NotebookInitError"}},Me=class extends Error{constructor(t,i){super(`PHPSandbox API Error: ${t.status} ${t.statusText} - ${i}`);this.response=t;this.body=i;this.status=t.status}},Oe=class{constructor(e){this.client=e;this.secrets=new Ke(e)}async create(e,t={},i=!0){let n=await this.client.post("/notebook",{template:e,...t}),s=new T(n.data,this.client);return i?this.init(s):s}async get(e){let t=await this.client.get(`/notebook/${e}`);return new T(t.data,this.client)}async update(e,t={}){let i=await this.client.put(`/notebook/${e}`,t);return new T(i.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e){let t=await this.client.post(`/notebook/${e}/fork`);return this.init(new T(t.data,this.client))}async open(e){let t=await this.client.get(`/notebook/${e}`);return new T(t.data,this.client)}openFromData(e){return this.init(new T(e,this.client))}async init(e){return await e.ready(),e}},Fe=class{constructor(e,t="https://api.phpsandbox.io/v1",i={}){this.fetch=globalThis.fetch;this.notebook=new Oe(this),this.options=Object.assign({startClosed:!0},i),this.baseUrl=t,i.fetch&&(this.fetch=i.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,i){let n=await this.fetch(new Request(new URL(`v1/${t.replace(/^\//,"")}`,this.baseUrl),{method:e,...i,headers:this.headers}));if(!n.ok)throw new Me(n,await n.text());if(n.status===204)return{data:void 0};let s=await n.text();return{data:s===""?void 0:JSON.parse(s)}}},bt=class extends Fe{},Ke=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,i){let n=typeof i=="string"?{name:t,value:i}:{name:t,...i};return(await this.client.put(`/notebook/${e}/secrets`,n)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:hi(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},R,ie,ze,T=class{constructor(e,t){this.data=e;this.client=t;M(this,ie);this.initialized=!1;M(this,R);this.disposables=[];this.emitter=A.createInstance(),this.socket=new j(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed}),this.watchConnection(),ve(this,R,w(this,ie,ze).call(this)),this.file=new re(this),this.terminal=new F(this),this.auth=new z(this),this.lsp=new H(this),this.composer=new $(this),this.log=new W(this),this.repl=new q(this),this.container=new K(this),this.laravel=new G(this),this.shell=new Q(this),this.git=new ee(this),this.services=new V(this),this.secrets=new He(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(),be(this,R)))()}fork(){return this.client.notebook.fork(this.data.id)}delete(){return this.client.notebook.delete(this.data.id).then(()=>{this.socket.terminate(new E("Notebook has been deleted.",{id:this.data.id}))})}stop(){return this.container.stop()}restart(){return this.container.start()}invoke(e,t={},i={}){return this.socket.invoke(e,t||{},i)}ping(){return this.invoke("ping")}listen(e,t){let i=this.emitter.listen(e,t);return this.disposables.push(i),i}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,i)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidClose(()=>i(new Error("Connection closed"))),this.socket.onDidBootError(n=>i(n))}catch(n){i(n)}})}whenConnected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,i)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidBootError(n=>i(n))}catch(n){i(n)}})}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,w(this,ie,ze).call(this),this.ready().then(()=>this)}async beacon(e,t){let i=await this.ready();return e.src=i.data.previewUrl,gt(e,t)}};R=new WeakMap,ie=new WeakSet,ze=function(){return ve(this,R,new Promise((e,t)=>{let i=this.onDidInitialize(s=>{if(n.dispose(),i.dispose(),this.initialized=s,s.type==="error"){t(new Be(s.message,s.data));return}e(s)}),n=this.onDidBootError(s=>{i.dispose(),n.dispose(),t(s)})})),be(this,R)};var He=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)}};export{Me as ApiError,Le as Beacon,x as BeaconConnectionError,B as BeaconError,me as BeaconTimeoutError,Fe as Client,Ee as CommandError,y as ErrorEvent,Tt as FileChangeType,St as FileType,re as Filesystem,ye as FilesystemError,It as FilesystemErrorType,we as LspConnection,te as Navigator,Oe as NotebookApi,Be as NotebookInitError,T as NotebookInstance,Ke as NotebookSecretApi,He as NotebookSecrets,Ct as NotebookState,E as NotebookUnavailableError,bt as PHPSandbox,qe as PHPSandboxError,I as PromiseTimeoutError,N as RateLimitError,O as SendTimeoutError,j as Transport,gt as createBeacon,Yn as isBeaconSupported,_t as notebookBuiltinServices,Mi as notebookKnownServices,oe as once,se as timeout};
|
|
1
|
+
var yt=Object.create;var $e=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var Et=Object.getPrototypeOf,kt=Object.prototype.hasOwnProperty;var Ge=n=>{throw TypeError(n)};var ne=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var St=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wt(e))!kt.call(n,r)&&r!==t&&$e(n,r,{get:()=>e[r],enumerable:!(i=xt(e,r))||i.enumerable});return n};var qe=(n,e,t)=>(t=n!=null?yt(Et(n)):{},St(e||!n||!n.__esModule?$e(t,"default",{value:n,enumerable:!0}):t,n));var ve=(n,e,t)=>e.has(n)||Ge("Cannot "+t);var se=(n,e,t)=>(ve(n,e,"read from private field"),t?t.call(n):e.get(n)),O=(n,e,t)=>e.has(n)?Ge("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),ye=(n,e,t,i)=>(ve(n,e,"write to private field"),i?i.call(n,t):e.set(n,t),t),w=(n,e,t)=>(ve(n,e,"access private method"),t);var st=ne((wr,nt)=>{function b(n,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}nt.exports=b;b.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};b.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};b.prototype.retry=function(n){if(this._timeout&&clearTimeout(this._timeout),!n)return!1;var e=new Date().getTime();if(n&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(n),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},t),this._options.unref&&this._timer.unref(),!0};b.prototype.attempt=function(n,e){this._fn=n,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};b.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};b.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};b.prototype.start=b.prototype.try;b.prototype.errors=function(){return this._errors};b.prototype.attempts=function(){return this._attempts};b.prototype.mainError=function(){if(this._errors.length===0)return null;for(var n={},e=null,t=0,i=0;i<this._errors.length;i++){var r=this._errors[i],s=r.message,o=(n[s]||0)+1;n[s]=o,o>=t&&(e=r,t=o)}return e}});var ot=ne(D=>{var ei=st();D.operation=function(n){var e=D.timeouts(n);return new ei(e,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};D.timeouts=function(n){if(n instanceof Array)return[].concat(n);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in n)e[t]=n[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],r=0;r<e.retries;r++)i.push(this.createTimeout(r,e));return n&&n.forever&&!i.length&&i.push(this.createTimeout(r,e)),i.sort(function(s,o){return s-o}),i};D.createTimeout=function(n,e){var t=e.randomize?Math.random()+1:1,i=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,n));return i=Math.min(i,e.maxTimeout),i};D.wrap=function(n,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var i in n)typeof n[i]=="function"&&t.push(i)}for(var r=0;r<t.length;r++){var s=t[r],o=n[s];n[s]=function(c){var p=D.operation(e),u=Array.prototype.slice.call(arguments,1),l=u.pop();u.push(function(d){p.retry(d)||(d&&(arguments[0]=p.mainError()),l.apply(this,arguments))}),p.attempt(function(){c.apply(n,u)})}.bind(n,o),n[s].options=e}}});var ct=ne((kr,at)=>{at.exports=ot()});var Ae=ne((Sr,lt)=>{var ti=ct();function ii(n,e){function t(i,r){var s=e||{},o;"randomize"in s||(s.randomize=!0),o=ti.operation(s);function a(u){r(u||new Error("Aborted"))}function c(u,l){if(u.bail){a(u);return}o.retry(u)?s.onRetry&&s.onRetry(u,l):r(o.mainError())}function p(u){var l;try{l=n(a,u)}catch(d){c(d,u);return}Promise.resolve(l).then(i).catch(function(f){c(f,u)})}o.attempt(p)}return new Promise(t)}lt.exports=ii});var y=class extends Error{constructor(t,i,r={}){super(i);this.code=t;this.message=i;this.raw=r}},U=class extends y{constructor(e,t={}){super(429,e,t)}},Qe=class extends y{};var Ve="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var g=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=Ve[t[n]&63];return e};var Tt=(r=>(r[r.Unknown=0]="Unknown",r[r.File=1]="File",r[r.Directory=2]="Directory",r[r.SymbolicLink=64]="SymbolicLink",r))(Tt||{}),It=(i=>(i[i.UPDATED=1]="UPDATED",i[i.ADDED=2]="ADDED",i[i.DELETED=3]="DELETED",i))(It||{}),Ct=(o=>(o.Unavailable="Unavailable",o.NoPermissions="NoPermissions",o.FileExists="FileExists",o.FileNotFound="FileNotFound",o.FileIsADirectory="FileIsADirectory",o.FileNotADirectory="FileNotADirectory",o))(Ct||{}),xe=class extends y{constructor(t,i){super(t.code,t.message);this.name=i}},we=class{constructor(e,t,i){this.path=e;this.okra=t;this.disposable=i}dispose(){this.okra.invoke("fs.unwatch",{path:this.path}),this.disposable.dispose()}},oe=class{constructor(e){this.okra=e;this.watches=new Map;this.watchOkraConnection()}watchOkraConnection(){this.okra.onDidConnect(()=>{for(let{path:e,options:t,onDidChange:i}of this.watches.values())this.watch(e,t,i)})}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,i){e.id||(e.id=g());let r={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}},s=e.id,o=async c=>{c===!1&&a.dispose(),i&&await Promise.resolve(i(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${s}`,o);return this.okra.invoke("fs.textSearch",{query:e,options:{...r,...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 i=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return i instanceof Uint8Array?i:typeof i=="string"?new TextEncoder().encode(i):i}catch(i){this.handleError(i)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(i=>this.handleError(i))}writeFile(e,t,i){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:i}).catch(r=>this.handleError(r))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,i){return this.okra.invoke("fs.rename",{from:e,to:t,options:i}).catch(r=>this.handleError(r))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(i=>this.handleError(i))}copy(e,t,i){return this.okra.invoke("fs.copy",{source:e,destination:t,options:i}).catch(r=>this.handleError(r))}readDirectory(e,t=[],i=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:i}).catch(r=>this.handleError(r))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,i){let r=this.okra.listen(`fs.watch.${e}`,i),s={dispose:()=>{r.dispose(),this.okra.invoke("fs.unwatch",{path:e})}},o=new we(e,this.okra,s);return this.watches.set(e,{options:t,path:e,onDidChange:i}),this.okra.invoke("fs.watch",{path:e,options:t}).then(()=>o)}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e,t,i){let r=g(),s=!!e,o=[];return this.okra.listen(`fs.download.${r}`,s?e:a=>{o.push(a)}),this.okra.invoke("fs.download",{id:r,exclude:t,include:i}).then(()=>new Blob(o,{type:"application/octet-stream"}))}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e instanceof y&&"name"in e.raw?new xe(e,e.raw.name):e}};var C=class extends Error{constructor(t,i){super(t);this.time=i}},F=class n extends C{static fromPromiseTimeoutError(e){return new n(e.message,e.time)}},E=class extends Error{constructor(t="Notebook is no longer available",i={}){super(t);this.raw=i;this.name="NotebookUnavailableError"}};var ae=(n,e)=>{let t;return Promise.race([n,new Promise((i,r)=>t=setTimeout(r,e,new C("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},ce=n=>{let e=null;return()=>e||(e=n())};var K=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 this.okra.invoke("terminal.input",{id:e,input:t})}listen(e,t){return this.okra.listen(e,t)}async spawn(e,t,i){let r=i?.id||g(),s=new Set,o=()=>{for(let v of s)v.dispose();s.clear()},a=new WritableStream({write:v=>{this.input(r,v)},close:o}),c=null,p=new ReadableStream({start:v=>{c=v,s.add(this.listen(`terminal.output.${r}`,be=>{c?.enqueue(be.output)}))},cancel:()=>{c=null,o()}}),u=new Promise(v=>{s.add(this.listen(`terminal.close.${r}`,be=>{if(c)try{c.close()}catch{}o(),v(be.exitCode)}))}),l=ce(()=>(o(),this.okra.invoke("terminal.close",{id:r}))),d=v=>{this.okra.invoke("terminal.resize",{id:r,width:v.cols,height:v.rows})},{abortSignal:f,...h}=i??{};f&&f.addEventListener("abort",l);let N=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:r,...h}},{abortSignal:f});return{exit:u,input:a,output:p,kill:l,resize:d,...N}}};var _t=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(_t||{}),z=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",i=>{for(let r of i)t.some(s=>s.port===r.port)||e(r,"open");for(let r of t)i.some(s=>s.port===r.port)||e(r,"close");t=i})}};var H=class{constructor(e){this.okra=e}logout(){return this.okra.invoke("auth.logout")}login(e){return this.okra.invoke("auth.login",{newConnectionData:e})}};var W=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,i){this.okra.listen(`${t}.${e}`,r=>i(r))}onClose(e,t){this.listen(e,"lsp.closed",i=>t(i.code,i.reason))}onError(e,t){this.listen(e,"lsp.error",i=>t(i.message))}onClientDisconnect(e){this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){this.listen(e,"lsp.response",i=>t(JSON.stringify(i)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return Ee.create(e,this)}whenSocketConnected(){return this.okra.whenConnected()}},Ee=class n{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 n(e,t)}};var $=class{constructor(e){this.okra=e}invoke(e,t={},i={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:i})}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 G=class{constructor(e){this.okra=e}stream(e){return this.okra.listen("notebook.log",e)}listen(e,t){this.okra.listen(e,t)}};var q=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 Q=class{constructor(e){this.okra=e}eval(e,t="",i={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:i})}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 Xe(n,e=[],t){let i=Array.isArray(e)?e:[],r=Array.isArray(e)?t:e;return{command:Array.isArray(n)?n:i.length>0?[n,...i]:n,opts:r}}var ke=class extends Error{constructor(t,i){super(t);this.output=t;this.exitCode=i}},Se=class{constructor(e,t){this.output=e;this.exitCode=t}throw(){if(this.exitCode!==0)throw new ke(this.output,this.exitCode);return this}},V=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=[],i){let r=Xe(e,t,i),{abortSignal:s,...o}=r.opts??{},a=await this.okra.invoke("shell.exec",{command:r.command,opts:Object.keys(o).length>0?o:void 0},{abortSignal:s});return new Se(a.output,a.exitCode)}execStream(e,t=[],i){let r=Xe(e,t,i),s=r.opts?.id||g(),o=new Set,a=null,c=!1,p=()=>{for(let h of o)h.dispose();o.clear()},u=()=>{if(!c&&(c=!0,p(),a))try{a.close()}catch{}},l=h=>{c||(c=!0,p(),a&&a.error(h))},d=new ReadableStream({start:h=>{a=h,o.add(this.listen(`shell.output.${s}`,N=>{a?.enqueue(N.output)}))},cancel:()=>{c=!0,p()}}),f=this.exec(r.command,{...r.opts,id:s}).then(h=>(u(),h)).catch(h=>{throw l(h),h});return{output:d,result:f}}};var Dt=["redis"],Oi=["start","nginx",...Dt],X=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(i=>{if(!("output"in i))throw new Error(`Unexpected service.logs response for ${e}`);return i.output})}followLogs(e,t){let i=t.id||g(),r=new Set,s=null,o=!1,a=()=>{for(let d of r)d.dispose();r.clear()},c=()=>{if(!o&&(o=!0,a(),s))try{s.close()}catch{}},p=d=>{o||(o=!0,a(),s&&s.error(d))},u=ce(()=>(c(),this.okra.invoke("service.stop-logs",{id:i}))),l=new ReadableStream({start:d=>{s=d,r.add(this.onLog(i,f=>{s?.enqueue(f.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:i}).catch(f=>{p(f)})},cancel:()=>{u()}});return{id:i,output:l,stop:u}}};function Je(n){let e=n.length,t=0,i=0;for(;i<e;){let r=n.charCodeAt(i++);if((r&4294967168)===0){t++;continue}else if((r&4294965248)===0)t+=2;else{if(r>=55296&&r<=56319&&i<e){let s=n.charCodeAt(i);(s&64512)===56320&&(++i,r=((r&1023)<<10)+(s&1023)+65536)}(r&4294901760)===0?t+=3:t+=4}}return t}function Pt(n,e,t){let i=n.length,r=t,s=0;for(;s<i;){let o=n.charCodeAt(s++);if((o&4294967168)===0){e[r++]=o;continue}else if((o&4294965248)===0)e[r++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<i){let a=n.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[r++]=o>>12&15|224,e[r++]=o>>6&63|128):(e[r++]=o>>18&7|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128)}e[r++]=o&63|128}}var At=new TextEncoder,Rt=50;function Nt(n,e,t){At.encodeInto(n,e.subarray(t))}function Ye(n,e,t){n.length>Rt?Nt(n,e,t):Pt(n,e,t)}var Ut=4096;function Te(n,e,t){let i=e,r=i+t,s=[],o="";for(;i<r;){let a=n[i++];if((a&128)===0)s.push(a);else if((a&224)===192){let c=n[i++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){let c=n[i++]&63,p=n[i++]&63;s.push((a&31)<<12|c<<6|p)}else if((a&248)===240){let c=n[i++]&63,p=n[i++]&63,u=n[i++]&63,l=(a&7)<<18|c<<12|p<<6|u;l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|l&1023),s.push(l)}else s.push(a);s.length>=Ut&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}var Lt=new TextDecoder,Bt=200;function Mt(n,e,t){let i=n.subarray(e,e+t);return Lt.decode(i)}function Ze(n,e,t){return t>Bt?Mt(n,e,t):Te(n,e,t)}var _=class{constructor(e,t){this.type=e,this.data=t}};var m=class n extends Error{constructor(e){super(e);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function je(n,e,t){let i=t/4294967296,r=t;n.setUint32(e,i),n.setUint32(e+4,r)}function le(n,e,t){let i=Math.floor(t/4294967296),r=t;n.setUint32(e,i),n.setUint32(e+4,r)}function ue(n,e){let t=n.getInt32(e),i=n.getUint32(e+4);return t*4294967296+i}function et(n,e){let t=n.getUint32(e),i=n.getUint32(e+4);return t*4294967296+i}var Ot=-1,Ft=4294967296-1,Kt=17179869184-1;function zt({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=Kt)if(e===0&&n<=Ft){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,i=n&4294967295,r=new Uint8Array(8),s=new DataView(r.buffer);return s.setUint32(0,e<<2|t&3),s.setUint32(4,i),r}else{let t=new Uint8Array(12),i=new DataView(t.buffer);return i.setUint32(0,e),le(i,4,n),t}}function Ht(n){let e=n.getTime(),t=Math.floor(e/1e3),i=(e-t*1e3)*1e6,r=Math.floor(i/1e9);return{sec:t+r,nsec:i-r*1e9}}function Wt(n){if(n instanceof Date){let e=Ht(n);return zt(e)}else return null}function $t(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),i=e.getUint32(4),r=(t&3)*4294967296+i,s=t>>>2;return{sec:r,nsec:s}}case 12:{let t=ue(e,4),i=e.getUint32(0);return{sec:t,nsec:i}}default:throw new m(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function Gt(n){let e=$t(n);return new Date(e.sec*1e3+e.nsec/1e6)}var tt={type:Ot,encode:Wt,decode:Gt};var k=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(tt)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){let r=this.builtInEncoders[i];if(r!=null){let s=r(e,t);if(s!=null){let o=-1-i;return new _(o,s)}}}for(let i=0;i<this.encoders.length;i++){let r=this.encoders[i];if(r!=null){let s=r(e,t);if(s!=null){let o=i;return new _(o,s)}}}return e instanceof _?e:null}decode(e,t,i){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,i):new _(t,e)}};k.defaultCodec=new k;function qt(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function J(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):qt(n)?new Uint8Array(n):Uint8Array.from(n)}var Qt=100,Vt=2048,he=class n{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??k.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Qt,this.initialBufferSize=e?.initialBufferSize??Vt,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 n({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),i=new Uint8Array(t),r=new DataView(t);i.set(this.bytes),this.view=r,this.bytes=i}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 i=Je(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),Ye(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,t){let i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);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 i=J(e);this.writeU8a(i)}encodeArray(e,t){let i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(let r of e)this.doEncode(r,t+1)}countWithoutUndefined(e,t){let i=0;for(let r of t)e[r]!==void 0&&i++;return i}encodeMap(e,t){let i=Object.keys(e);this.sortKeys&&i.sort();let r=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else if(r<4294967296)this.writeU8(223),this.writeU32(r);else throw new Error(`Too large map object: ${r}`);for(let s of i){let o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let i=e.data(this.pos+6),r=i.length;if(r>=4294967296)throw new Error(`Too large extension object: ${r}`);this.writeU8(201),this.writeU32(r),this.writeI8(e.type),this.writeU8a(i);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),je(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),le(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 Ie(n,e){return new he(e).encodeSharedRef(n)}function pe(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}var Xt=16,Jt=16,de=class{constructor(e=Xt,t=Jt){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){let r=this.caches[i-1];e:for(let s of r){let o=s.bytes;for(let a=0;a<i;a++)if(o[a]!==e[t+a])continue e;return s.str}return null}store(e,t){let i=this.caches[e.length-1],r={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=r:i.push(r)}decode(e,t,i){let r=this.find(e,t,i);if(r!=null)return this.hit++,r;this.miss++;let s=Te(e,t,i),o=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(o,s),s}};var Ce="array",j="map_key",rt="map_value",Yt=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new m("The type of key must be string or number but "+typeof n)},_e=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=Ce,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=j,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===Ce){let i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===j||e.type===rt){let i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Z=-1,De=new DataView(new ArrayBuffer(0)),Zt=new Uint8Array(De.buffer);try{De.getInt8(0)}catch(n){if(!(n 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 it=new RangeError("Insufficient data"),jt=new de,me=class n{constructor(e){this.totalPos=0,this.pos=0,this.view=De,this.bytes=Zt,this.headByte=Z,this.stack=new _e,this.entered=!1,this.extensionCodec=e?.extensionCodec??k.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:jt,this.mapKeyConverter=e?.mapKeyConverter??Yt}clone(){return new n({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=Z,this.stack.reset()}setBuffer(e){let t=J(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Z&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),i=J(e),r=new Uint8Array(t.length+i.length);r.set(t),r.set(i,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} 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,i;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=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 i}let{headByte:r,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${pe(r)} at ${o} (${s} 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 i=t,r=-1;for await(let s of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),i&&(r=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(o){if(!(o instanceof RangeError))throw o}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 r=e-128;if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e<160){let r=e-144;if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else{let r=e-160;t=this.decodeString(r,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 r=this.lookU8();t=this.decodeString(r,1)}else if(e===218){let r=this.lookU16();t=this.decodeString(r,2)}else if(e===219){let r=this.lookU32();t=this.decodeString(r,4)}else if(e===220){let r=this.readU16();if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else if(e===221){let r=this.readU32();if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else if(e===222){let r=this.readU16();if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e===223){let r=this.readU32();if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e===196){let r=this.lookU8();t=this.decodeBinary(r,1)}else if(e===197){let r=this.lookU16();t=this.decodeBinary(r,2)}else if(e===198){let r=this.lookU32();t=this.decodeBinary(r,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 r=this.lookU8();t=this.decodeExtension(r,1)}else if(e===200){let r=this.lookU16();t=this.decodeExtension(r,2)}else if(e===201){let r=this.lookU32();t=this.decodeExtension(r,4)}else throw new m(`Unrecognized type byte: ${pe(e)}`);this.complete();let i=this.stack;for(;i.length>0;){let r=i.top();if(r.type===Ce)if(r.array[r.position]=t,r.position++,r.position===r.size)t=r.array,i.release(r);else continue e;else if(r.type===j){if(t==="__proto__")throw new m("The key __proto__ is not allowed");r.key=this.mapKeyConverter(t),r.type=rt;continue e}else if(r.map[r.key]=t,r.readCount++,r.readCount===r.size)t=r.map,i.release(r);else{r.key=null,r.type=j;continue e}}return t}}readHeadByte(){return this.headByte===Z&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Z}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 m(`Unrecognized array type byte: ${pe(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new m(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new m(`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 m(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw it;let i=this.pos+t,r;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?r=this.keyDecoder.decode(this.bytes,i,e):r=Ze(this.bytes,i,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===j:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new m(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw it;let i=this.pos+t,r=this.bytes.subarray(i,i+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new m(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let i=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,i,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=et(this.view,this.pos);return this.pos+=8,e}readI64(){let e=ue(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 Pe(n,e){return new me(e).decode(n)}var mt=qe(Ae(),1);var Re=function(n,e){return Re=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var r in i)i.hasOwnProperty(r)&&(t[r]=i[r])},Re(n,e)};function ut(n,e){Re(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function ri(n){var e=typeof Symbol=="function"&&n[Symbol.iterator],t=0;return e?e.call(n):{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}}}function ni(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return s}function si(){for(var n=[],e=0;e<arguments.length;e++)n=n.concat(ni(arguments[e]));return n}var ht=(function(){function n(e,t){this.target=t,this.type=e}return n})(),oi=(function(n){ut(e,n);function e(t,i){var r=n.call(this,"error",i)||this;return r.message=t.message,r.error=t,r}return e})(ht),ai=(function(n){ut(e,n);function e(t,i,r){t===void 0&&(t=1e3),i===void 0&&(i="");var s=n.call(this,"close",r)||this;return s.wasClean=!0,s.code=t,s.reason=i,s}return e})(ht);var ci=function(){if(typeof WebSocket<"u")return WebSocket},li=function(n){return typeof n<"u"&&!!n&&n.CLOSING===2},P={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},ui=(function(){function n(e,t,i){var r=this;i===void 0&&(i={}),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(s){r._debug("open event");var o=r._options.minUptime,a=o===void 0?P.minUptime:o;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout(function(){return r._acceptOpen()},a),r._ws.binaryType=r._binaryType,r._messageQueue.forEach(function(c){return r._ws.send(c)}),r._messageQueue=[],r.onopen&&r.onopen(s),r._listeners.open.forEach(function(c){return r._callEventListener(s,c)})},this._handleMessage=function(s){r._debug("message event"),r.onmessage&&r.onmessage(s),r._listeners.message.forEach(function(o){return r._callEventListener(s,o)})},this._handleError=function(s){r._debug("error event",s.message),r._disconnect(void 0,s.message==="TIMEOUT"?"timeout":void 0),r.onerror&&r.onerror(s),r._debug("exec error listeners"),r._listeners.error.forEach(function(o){return r._callEventListener(s,o)}),r._connect()},this._handleClose=function(s){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(s),r._listeners.close.forEach(function(o){return r._callEventListener(s,o)})},this._url=e,this._protocols=t,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(n,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(n,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(n,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(n,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"CONNECTING",{get:function(){return n.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"OPEN",{get:function(){return n.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"CLOSING",{get:function(){return n.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"CLOSED",{get:function(){return n.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(n.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(n.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"bufferedAmount",{get:function(){var e=this._messageQueue.reduce(function(t,i){return typeof i=="string"?t+=i.length:i instanceof Blob?t+=i.size:t+=i.byteLength,t},0);return e+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?n.CLOSED:n.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),n.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)},n.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())},n.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,i=t===void 0?P.maxEnqueuedMessages:t;this._messageQueue.length<i&&(this._debug("enqueue",e),this._messageQueue.push(e))}},n.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},n.prototype.dispatchEvent=function(e){var t,i,r=this._listeners[e.type];if(r)try{for(var s=ri(r),o=s.next();!o.done;o=s.next()){var a=o.value;this._callEventListener(e,a)}}catch(c){t={error:c}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(t)throw t.error}}return!0},n.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(i){return i!==t}))},n.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,si(["RWS>"],e))},n.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,i=t===void 0?P.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,s=r===void 0?P.minReconnectionDelay:r,o=e.maxReconnectionDelay,a=o===void 0?P.maxReconnectionDelay:o,c=0;return this._retryCount>0&&(c=s*Math.pow(i,this._retryCount-1),c>a&&(c=a)),this._debug("next delay",c),c},n.prototype._wait=function(){var e=this;return new Promise(function(t){setTimeout(t,e._getNextDelay())})},n.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")},n.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var t=this._options,i=t.maxRetries,r=i===void 0?P.maxRetries:i,s=t.connectionTimeout,o=s===void 0?P.connectionTimeout:s,a=t.WebSocket,c=a===void 0?ci():a;if(this._retryCount>=r){this._debug("max retries reached",this._retryCount,">=",r);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!li(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(p){e._closeCalled||(e._debug("connect",{url:p,protocols:e._protocols}),e._ws=e._protocols?new c(p,e._protocols):new c(p),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},o))})}},n.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new oi(Error("TIMEOUT"),this))},n.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 ai(e,t,this))}catch{}}},n.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},n.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},n.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))},n.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))},n.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},n})(),pt=ui;var L=null;typeof WebSocket<"u"?L=WebSocket:typeof MozWebSocket<"u"?L=MozWebSocket:typeof global<"u"?L=global.WebSocket||global.MozWebSocket:typeof window<"u"?L=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(L=self.WebSocket||self.MozWebSocket);var dt=L;var fe=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 A=class extends Error{constructor(t,i){super(t);this.data=i;this.name="InvalidMessageError"}},B=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},S,Ne,Ue,ee=class{constructor(e,t,i={}){this.eventEmitter=t;this.options=i;O(this,S);this.clientId="";this.closed=!1;this.disposables=new fe;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.rateLimiter={requests:[],maxRequests:50,windowMs:1e3};this.validateConfiguration(i),this.url=new URL(e),this.PING_INTERVAL=i.pingInterval??3e4,this.connectionStats.connectionStartTime=Date.now();let r=i.startClosed!==!1;this.rws=new pt(this.url.toString(),[],{WebSocket:i.webSocket??globalThis.WebSocket??dt,connectionTimeout:i.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:i.maxRetries??50,startClosed:r}),this.log("debug","Transport initialized",{url:this.url.toString(),options:i}),this.registerWatchers(),this.setupConnectionHealthMonitoring(),this.startPeriodicMaintenance()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new B("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new B("connectionTimeout must be between 100ms and 30000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new B("maxRetries must be between 0 and 100")}log(e,t,i){if(this.options.debug){let r=new Date().toISOString(),s=i?JSON.stringify(i,null,2):"";console[e](`[Transport ${r}] ${t}${s?`
|
|
2
|
+
`+s:""}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):w(this,S,Ne).call(this)}id(){return this.clientId}async registerWatchers(){let e=t=>{if(!(t.data instanceof Blob)){let i=new Error("Unexpected message type: "+typeof t.data);this.connectionStats.totalErrors++,this.log("error","Unexpected WebSocket message type",{error:i.message,messageType:typeof t.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:i,rawMessage:t.data,timestamp:Date.now()});return}t.data.arrayBuffer().then(i=>{if(i.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}try{this.handleRawMessage(Pe(i)).catch(r=>{this.connectionStats.totalErrors++,this.log("error","Failed to process WebSocket frame",{error:r instanceof Error?r.message:String(r),byteLength:i.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:r,rawMessage:i,timestamp:Date.now()})})}catch(r){this.connectionStats.totalErrors++,this.log("error","Failed to decode WebSocket frame",{error:r instanceof Error?r.message:String(r),byteLength:i.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:r,rawMessage:i,timestamp:Date.now()})}})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}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:i,as:r}=e;if(!i||typeof i!="string")throw new A("Message missing event field",e);if(this.log("debug","Processing message",{event:i,hasData:!!t}),i==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(i==="Events.BootError"){let s=new E(t?.message||"Notebook is no longer available",t||{});this.log("error","Boot error received",{data:t}),this.terminate(s,4e3,s.message);return}if(i==="response"){let{responseEvent:s,data:o}=t;if(!s)throw new A("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:s}),await this.handleMessage(s,o);return}if(i==="error"){let{errorEvent:s,data:o}=t;if(!s)throw new A("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:s,errorData:o}),await this.handleMessage(s,o);return}await this.handleMessage(i,t,r)}catch(t){this.connectionStats.totalErrors++,t instanceof A?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,i){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,t.id);return}e&&this.eventEmitter.emit(i||e,t)}listen(e,t,i){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,i){this.eventEmitter.once(e,t,i),this.disposables.add(`once_${e}_${g()}`,{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={},i={}){if(this.terminalError)throw this.terminalError;if(this.isRateLimited())throw new U("Rate limit exceeded - too many requests");this.clearOldQueuedMessages();let r=i.responseEvent||`${e}_${g()}_response`,s=`${r}_error`,o,a=()=>{o&&(this.rws.removeEventListener("close",o),this.rws.removeEventListener("error",o)),this.eventEmitter.removeListener(r),this.eventEmitter.removeListener(s)},c=async(u,l)=>{if(this.terminalError){l(this.terminalError);return}let d=new DOMException("Request aborted","AbortError");if(i.abortSignal?.aborted&&l(d),i.abortSignal&&i.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 h=this.messageQueue.shift();h&&h.reject(new Error("Message queue full, oldest message dropped"))}this.messageQueue.push({action:e,data:t,options:i,resolve:u,reject:l,timestamp:Date.now()});return}let f=Date.now();this.listenOnce(r,h=>{let N=Date.now()-f;this.connectionStats.avgResponseTime=(this.connectionStats.avgResponseTime+N)/2,this.connectionStats.totalMessages++,this.log("debug","Message response received",{action:e,responseTime:N,avgResponseTime:this.connectionStats.avgResponseTime}),u(h)}),this.listenOnce(s,h=>{this.connectionStats.totalErrors++,this.log("error","Message error received",{action:e,error:h}),l(new y(h.code,h.message,h))}),o=h=>{if(h.code===1008&&(h.reason||"").includes("rate limit")){l(new U(h.reason||"Rate limit exceeded",h));return}l(this.terminalError||new Error(`Connection lost to the notebook during request: ${h.reason||"Unknown reason"}`))},this.rws.addEventListener("close",o),this.rws.addEventListener("error",o);try{this.rws.send(this.pack({action:e,data:t,errorEvent:s,responseEvent:r})),this.log("debug","Message sent",{action:e,data:t})}catch(h){throw this.log("error","Failed to send message",{action:e,error:h}),h}},p=async()=>{await w(this,S,Ne).call(this);let u=new Promise(c).finally(a);return i.timeout?ae(u,i.timeout).catch(l=>{throw l instanceof C?F.fromPromiseTimeoutError(l):l}).finally(a):u};return this.sendWithRetry(async()=>await p(),i.retries||10)}pack(e){return new Blob([Ie(e)])}sendWithRetry(e,t=10){return(0,mt.default)(async(i,r)=>{try{return await e()}catch(s){if(s instanceof y||s instanceof U||s instanceof B||s instanceof A||s instanceof E||s instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:s.message,attempt:r}),i(s);return}throw s instanceof F&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:r,timeout:s.time})),this.log("debug","Retrying send operation",{attempt:r,error:s instanceof Error?s.message:String(s),nextDelay:this.getBackoffDelay(r-1)}),s}},{retries:t,onRetry:(i,r)=>{this.log("warn","Send operation retry",{attempt:r,maxRetries:t,error:i instanceof Error?i.message:String(i)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},i={}){return i.responseEvent||(i.responseEvent=`${e}_${g()}`),this.call("invoke",{action:e,data:t},i)}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,i=e.message){this.terminalError=e,e instanceof E&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,i)}close(e,t){if(this.closed)return;this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null;let i=this.messageQueue.length,r=this.terminalError||new Error("Connection closed while message was queued");this.messageQueue.forEach(s=>{s.reject(r)}),this.messageQueue=[],i>0&&this.log("debug",`Rejected ${i} queued messages due to connection close`),this.rateLimiter.requests=[],this.disposables.dispose();try{this.rws.close(e,t)}catch(s){this.log("error","Error closing WebSocket",{error:s instanceof Error?s.message:String(s)})}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++,this.log("error","Connection error",{error: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(i=>{let r=e-i.timestamp>this.QUEUE_TIMEOUT;return r&&i.reject(new Error("Queued message expired")),!r}),t!==this.messageQueue.length&&this.log("debug",`Cleared ${t-this.messageQueue.length} expired messages`)}isRateLimited(){let e=Date.now();return this.rateLimiter.requests=this.rateLimiter.requests.filter(t=>e-t<this.rateLimiter.windowMs),this.rateLimiter.requests.length>=this.rateLimiter.maxRequests?!0:(this.rateLimiter.requests.push(e),!1)}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(i=>i.timestamp)):0},rateLimiter:{currentRequests:this.rateLimiter.requests.length,maxRequests:this.rateLimiter.maxRequests,windowMs:this.rateLimiter.windowMs,isLimited:this.isRateLimited()},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(),i=[],r=[];return this.isConnected||(i.push("Connection is not established"),r.push("Check network connectivity and server availability")),e.connectionStats.timeSinceLastPong>this.PING_INTERVAL*2&&(i.push("No pong received recently - connection may be stale"),r.push("Consider forcing a reconnection")),Number.parseFloat(e.connectionStats.errorRate)>10&&(i.push(`High error rate: ${e.connectionStats.errorRate}`),r.push("Check server logs and network stability")),e.messageQueue.length>this.MAX_QUEUE_SIZE*.8&&(i.push("Message queue is nearly full"),r.push("Check connection stability and consider reducing message frequency")),e.connectionStats.avgResponseTime>5e3&&(i.push("High average response time"),r.push("Check network latency and server performance")),e.rateLimiter.isLimited&&(i.push("Rate limiting is active"),r.push("Reduce request frequency or increase rate limit")),this.log("info","Connection diagnostics completed",{status:t,issueCount:i.length,recommendationCount:r.length}),{status:t,metrics:e,issues:i,recommendations:r}}startPeriodicMaintenance(){this.disposables.add("maintenance",()=>{let e=setInterval(()=>{this.clearOldQueuedMessages();let t=Date.now();if(this.rateLimiter.requests=this.rateLimiter.requests.filter(i=>t-i<this.rateLimiter.windowMs),this.options.debug){let i=this.getHealthStatus(),r=this.getConnectionMetrics();this.log("debug","Periodic health check",{health:i,messageCount:r.connectionStats.totalMessages,errorCount:r.connectionStats.totalErrors,queueLength:r.messageQueue.length})}},3e5);return{dispose:()=>{clearInterval(e)}}})}};S=new WeakSet,Ne=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(),w(this,S,Ue).call(this);return}this.rws.readyState===3&&this.rws.reconnect();let i,r=()=>{this.rws.removeEventListener("open",r),this.rws.removeEventListener("error",s),clearTimeout(i),this.connectPromise=null,e(),w(this,S,Ue).call(this)},s=o=>{this.rws.removeEventListener("open",r),this.rws.removeEventListener("error",s),clearTimeout(i),this.connectPromise=null,t(new Error(`WebSocket connection failed: ${o}`))};i=setTimeout(()=>{this.rws.removeEventListener("open",r),this.rws.removeEventListener("error",s),this.connectPromise=null,t(new Error("WebSocket connection timeout"))},1e4),this.rws.addEventListener("open",r),this.rws.addEventListener("error",s)}),this.connectPromise)},Ue=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 i=this.connectionStats.lastPongTime-t;this.log("debug","Ping successful",{pingTime:i})}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 ft(n){return{all:n=n||new Map,on:function(e,t){var i=n.get(e);i?i.push(t):n.set(e,[t])},off:function(e,t){var i=n.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var i=n.get(e);i&&i.slice().map(function(r){r(t)}),(i=n.get("*"))&&i.slice().map(function(r){r(e,t)})}}}function hi(n){let e=ft(n);return e.once=(t,i)=>{e.on(t,i),e.on(t,e.off.bind(e,t,i))},e}var R=class n{constructor(){this.emitter=hi()}listen(e,t){let i=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:i}}emit(e,t){this.emitter.emit(e,t)}once(e,t){this.emitter.once(e,t)}static make(){return new n}static refresh(){return new n}removeListener(e,t){this.emitter.off(e,t)}static createInstance(){return new n}inspect(){return this.emitter.all}};var te=class{constructor(e){this.okra=e}checkpoint(e,t,i="main",r=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:i,allowEmpty:r})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,i="main",r,s="both",o=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:i,token:r,direction:s,force:o})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}};var Le=qe(Ae(),1);var ie=class{constructor(e,t,i){this.onEvent=e;this.onceEvent=t;this.beacon=i;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=i,this.setupUrlChangeListener(),this.urlHistory.push(i.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 gt(){if(typeof window>"u")throw new Error("Beacon SDK can only be used in a browser environment")}var M=class extends Error{constructor(t,i){super(t);this.code=i;this.name="BeaconError"}},ge=class extends M{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},x=class extends M{constructor(e){super(`Beacon connection error: ${e}`),this.code="CONNECTION_ERROR"}},Be=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;gt(),this.iframe=e;let i={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...i,...t.retry},...t},this.eventEmitter=R.make(),this.setupMessageChannel(),this.navigator=new ie(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 i=t.data;if(!i||typeof i!="object"||!i.type)return;i.type==="beacon:ready-for-channel"&&this.establishChannel().catch(r=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",r)}),i.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",i.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(i){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",i)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new x("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,i)=>{let r=setTimeout(()=>{i(new x("Channel establishment timeout"))},this.options.timeout),s=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(r),t()):setTimeout(s,100)};s()})}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 i=this.messageHandlers.get(e.type);i&&i.forEach(r=>{try{r(e.payload)}catch(s){this.options.debug&&console.error("[Beacon SDK] Message handler error:",s)}})}waitForBeaconReady(){return(0,Le.default)(async()=>new Promise((e,t)=>{if(this.isBeaconReady&&this.channelEstablished){e();return}let i=this.options.timeout,r=setTimeout(()=>{t(new ge("beacon ready",i))},i),s=this.on("ready",()=>{clearTimeout(r),s.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 i=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,i)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new x("MessagePort not available - channel not established");let i={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(i),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",i.type,i.payload)}catch(r){throw new x(`Failed to send message via port: ${r instanceof Error?r.message:String(r)}`)}}async sendAndWaitFor(e,t,i={},r){return await this.ready(),(0,Le.default)(async s=>new Promise((o,a)=>{let c=r||this.options.timeout,p=setTimeout(()=>{u.dispose();let l=new ge(e,c);a(l)},c),u=this.eventEmitter.listen(t,l=>{clearTimeout(p),u.dispose(),o(l)});try{this.sendMessage(e,i)}catch(l){clearTimeout(p),u.dispose(),l instanceof x?a(l):s(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:(s,o)=>{if(this.options.debug){let a=s instanceof Error?s.message:String(s);console.warn(`[Beacon SDK] Retry attempt ${o} 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 M("Beacon has not been started. Call start() first.");if(!this.readyPromise)throw new M("Beacon ready promise is not available");return ae(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 debug(e,t){let i=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==i&&(this.navigator.visit(i),await this.ready()),t&&await this.wait(t);let r=(e.options?.timeout||3e4)+5e3;return this.sendAndWaitFor("debug","debugResult",e,r)}async wait(e){return new Promise(t=>setTimeout(t,e*1e3))}navigate(e){if(!this.iframe)throw new x("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 x(`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 bt(n,e){return new Be(n,e)}function Yr(){try{return gt(),!0}catch{return!1}}function pi(n){return Array.isArray(n)?n:Object.entries(n).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var Me=class extends Error{constructor(t,i={}){super(t);this.message=t;this.data=i;this.name="NotebookInitError"}},Oe=class extends Error{constructor(t,i){super(`PHPSandbox API Error: ${t.status} ${t.statusText} - ${i}`);this.response=t;this.body=i;this.status=t.status}},Fe=class{constructor(e){this.client=e;this.secrets=new ze(e)}async create(e,t={},i=!0){let r=await this.client.post("/notebook",{template:e,...t}),s=new T(r.data,this.client);return i?this.init(s):s}async get(e){let t=await this.client.get(`/notebook/${e}`);return new T(t.data,this.client)}async update(e,t={}){let i=await this.client.put(`/notebook/${e}`,t);return new T(i.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e){let t=await this.client.post(`/notebook/${e}/fork`);return this.init(new T(t.data,this.client))}async open(e){let t=await this.client.get(`/notebook/${e}`);return new T(t.data,this.client)}openFromData(e){return this.init(new T(e,this.client))}async init(e){return await e.ready(),e}},Ke=class{constructor(e,t="https://api.phpsandbox.io/v1",i={}){this.fetch=globalThis.fetch;this.notebook=new Fe(this),this.options=Object.assign({startClosed:!0},i),this.baseUrl=t,i.fetch&&(this.fetch=i.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,i){let r=await this.fetch(new Request(new URL(`v1/${t.replace(/^\//,"")}`,this.baseUrl),{method:e,...i,headers:this.headers}));if(!r.ok)throw new Oe(r,await r.text());if(r.status===204)return{data:void 0};let s=await r.text();return{data:s===""?void 0:JSON.parse(s)}}},vt=class extends Ke{},ze=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,i){let r=typeof i=="string"?{name:t,value:i}:{name:t,...i};return(await this.client.put(`/notebook/${e}/secrets`,r)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:pi(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},I,re,He,T=class{constructor(e,t){this.data=e;this.client=t;O(this,re);this.initialized=!1;O(this,I);this.disposables=[];this.emitter=R.createInstance(),this.socket=new ee(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),ye(this,I,w(this,re,He).call(this)),this.file=new oe(this),this.terminal=new K(this),this.auth=new H(this),this.lsp=new W(this),this.composer=new $(this),this.log=new G(this),this.repl=new Q(this),this.container=new z(this),this.laravel=new q(this),this.shell=new V(this),this.git=new te(this),this.services=new X(this),this.secrets=new We(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(),se(this,I)))()}fork(){return this.client.notebook.fork(this.data.id)}delete(){return this.client.notebook.delete(this.data.id).then(()=>{this.socket.terminate(new E("Notebook has been deleted.",{id:this.data.id}))})}stop(){return this.container.stop()}restart(){return this.container.start()}invoke(e,t={},i={}){return this.socket.invoke(e,t||{},i)}ping(){return this.invoke("ping")}listen(e,t){let i=this.emitter.listen(e,t);return this.disposables.push(i),i}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,i)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidClose(()=>i(new Error("Connection closed"))),this.socket.onDidBootError(r=>i(r))}catch(r){i(r)}})}whenConnected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,i)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidBootError(r=>i(r))}catch(r){i(r)}})}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,w(this,re,He).call(this),this.ready().then(()=>this)}async beacon(e,t){let i=await this.ready();return e.src=i.data.previewUrl,bt(e,t)}};I=new WeakMap,re=new WeakSet,He=function(){return ye(this,I,new Promise((e,t)=>{let i=this.onDidInitialize(s=>{if(r.dispose(),i.dispose(),this.initialized=s,s.type==="error"){t(new Me(s.message,s.data));return}e(s)}),r=this.onDidBootError(s=>{i.dispose(),r.dispose(),t(s)})})),se(this,I).catch(()=>{}),se(this,I)};var We=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)}};export{Oe as ApiError,Be as Beacon,x as BeaconConnectionError,M as BeaconError,ge as BeaconTimeoutError,Ke as Client,ke as CommandError,y as ErrorEvent,It as FileChangeType,Tt as FileType,oe as Filesystem,xe as FilesystemError,Ct as FilesystemErrorType,Ee as LspConnection,ie as Navigator,Fe as NotebookApi,Me as NotebookInitError,T as NotebookInstance,ze as NotebookSecretApi,We as NotebookSecrets,_t as NotebookState,E as NotebookUnavailableError,vt as PHPSandbox,Qe as PHPSandboxError,C as PromiseTimeoutError,U as RateLimitError,F as SendTimeoutError,ee as Transport,bt as createBeacon,Yr as isBeaconSupported,Dt as notebookBuiltinServices,Oi as notebookKnownServices,ce as once,ae as timeout};
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
reconnecting-websocket/dist/reconnecting-websocket-mjs.js:
|