@phpsandbox/sdk 0.1.11 → 0.1.13
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 +1 -0
- package/dist/browser/phpsandbox-sdk.esm.js +7 -0
- package/dist/browser/phpsandbox-sdk.esm.min.js +2 -2
- package/dist/browser/phpsandbox-sdk.iife.js +7 -0
- package/dist/browser/phpsandbox-sdk.iife.min.js +2 -2
- package/dist/ports.d.ts +1 -0
- package/dist/ports.js +3 -0
- package/dist/runtime/rest.js +1 -0
- package/dist/runtime.d.ts +4 -0
- package/dist/runtime.js +3 -0
- package/docs/api-summary.md +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -195,6 +195,7 @@ await reader.cancel();
|
|
|
195
195
|
|
|
196
196
|
```ts
|
|
197
197
|
const currentPorts = await notebook.runtime.ports.list();
|
|
198
|
+
const futurePort = await notebook.runtime.ports.resolve(4848);
|
|
198
199
|
const currentMetrics = await notebook.runtime.metrics.current();
|
|
199
200
|
|
|
200
201
|
for await (const sample of notebook.runtime.metrics.watch({ signal })) {
|
|
@@ -1187,6 +1187,9 @@ var Ports = class {
|
|
|
1187
1187
|
list() {
|
|
1188
1188
|
return this.okra.invoke("container.opened-ports");
|
|
1189
1189
|
}
|
|
1190
|
+
resolve(port) {
|
|
1191
|
+
return this.okra.invoke("container.resolve-port", { port });
|
|
1192
|
+
}
|
|
1190
1193
|
watch(options = {}) {
|
|
1191
1194
|
return watchRuntimeTelemetry(this.okra, this.telemetry, "ports", "container.ports", (ports) => ports, options);
|
|
1192
1195
|
}
|
|
@@ -1219,6 +1222,9 @@ var RuntimePorts = class {
|
|
|
1219
1222
|
list() {
|
|
1220
1223
|
return this.ports.list();
|
|
1221
1224
|
}
|
|
1225
|
+
resolve(port) {
|
|
1226
|
+
return this.ports.resolve(port);
|
|
1227
|
+
}
|
|
1222
1228
|
watch(options = {}) {
|
|
1223
1229
|
return this.ports.watch(options);
|
|
1224
1230
|
}
|
|
@@ -19464,6 +19470,7 @@ var restActionRoutes = {
|
|
|
19464
19470
|
"container.stop": { method: "POST", path: "/runtime/container/stop" },
|
|
19465
19471
|
"container.set-php": { method: "PUT", path: "/runtime/container/php" },
|
|
19466
19472
|
"container.opened-ports": { method: "GET", path: "/runtime/container/ports" },
|
|
19473
|
+
"container.resolve-port": { method: "POST", path: "/runtime/container/ports/resolve" },
|
|
19467
19474
|
"container.stats": { method: "GET", path: "/runtime/container/stats" },
|
|
19468
19475
|
"terminal.list": { method: "GET", path: "/runtime/terminals" },
|
|
19469
19476
|
"shell.exec": { method: "POST", path: "/runtime/executions" },
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var rf=Object.defineProperty;var Pl=r=>{throw TypeError(r)};var te=(r,e)=>{for(var n in e)rf(r,n,{get:e[n],enumerable:!0})};var Zi=(r,e,n)=>e.has(r)||Pl("Cannot "+n);var Ie=(r,e,n)=>(Zi(r,e,"read from private field"),n?n.call(r):e.get(r)),St=(r,e,n)=>e.has(r)?Pl("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,n),Er=(r,e,n,i)=>(Zi(r,e,"write to private field"),i?i.call(r,n):e.set(r,n),n),pe=(r,e,n)=>(Zi(r,e,"access private method"),n);var nf=["ActionNotFound","AuthenticationRequired","BadGateway","BadRequest","Conflict","FileAlreadyExists","FileIsDirectory","FileNotDirectory","FileNotFound","FilesystemUnavailable","InternalError","InvalidArgument","InvalidConfiguration","InvalidRequest","InvalidResponse","InvalidServiceCommand","MethodNotAllowed","NotebookInitializationFailed","NotebookUnavailable","NotFound","PayloadTooLarge","PermissionDenied","RateLimited","RequestFailed","RuntimeOperationFailed","ServiceNotFound","ServiceUnavailable","UnprocessableEntity","ValidationFailed","WorkspaceUnavailable"],J=class extends Error{constructor(e,n){super(e),this.name=new.target.name,this.cause=n}},F=class r extends J{constructor(e,n){super(e,n.cause),this.source=n.source,this.status=n.status,this.code=n.code,this.details=n.details}static is(e,n){return e instanceof r&&(n===void 0||e.code===n)}static isValidation(e){return r.is(e,"ValidationFailed")&&cf(e.details)!==void 0}is(e){return this.code===e}},O=class r extends J{constructor(n,i,t){super(n,t);this.code=i}static is(n,i){return n instanceof r&&(i===void 0||n.code===i)}is(n){return this.code===n}};function me(r,e,n){let i=Li(e),t=af(i?.status),o=zl(i?.code),a=zl(i?.message);if(t===void 0||!of(o)||a===void 0)throw new O("PHPSandbox returned an invalid error response.","InvalidResponse",n??e);return new F(a,{source:r,status:t,code:o,details:i?.details,cause:n})}function of(r){return typeof r=="string"&&nf.includes(r)}function af(r){return typeof r=="number"&&Number.isInteger(r)&&r>0?r:void 0}function zl(r){return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function Li(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0}function sf(r){let e=Li(r);if(e===void 0)return;let n=Object.entries(e);if(n.every(([,i])=>Array.isArray(i)&&i.every(t=>typeof t=="string")))return Object.fromEntries(n)}function cf(r){let e=Li(r),n=sf(e?.errors);return n===void 0?void 0:{errors:n}}var Fe=class extends Error{constructor(n,i){super(n);this.time=i}},It=class r extends O{constructor(n,i,t){super(n,"SendTimeout",t);this.time=i}static fromPromiseTimeoutError(n){return new r(n.message,n.time,n)}};var El="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var N=(r=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=El[n[r]&63];return e};var Tl=(t=>(t[t.Unknown=0]="Unknown",t[t.File=1]="File",t[t.Directory=2]="Directory",t[t.SymbolicLink=64]="SymbolicLink",t))(Tl||{}),Dl=(i=>(i[i.UPDATED=2]="UPDATED",i[i.ADDED=4]="ADDED",i[i.DELETED=8]="DELETED",i))(Dl||{}),Ul=(i=>(i[i.UPDATED=1]="UPDATED",i[i.ADDED=2]="ADDED",i[i.DELETED=3]="DELETED",i))(Ul||{}),Fi=class{constructor(e,n){this.disposable=e;this.onDispose=n;this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposable.dispose(),this.onDispose())}},Tr=class{constructor(e,n=i=>e.onDidConnect(i)){this.okra=e;this.watches=new Map;this.registerReconnectHandler(n)}registerReconnectHandler(e){e!==null&&e(()=>{for(let{path:n,options:i}of this.watches.values())this.okra.invoke("fs.watch",{path:n,options:i}).catch(()=>{})})}async write(e,n,i={}){let t={overwrite:!0,create:!0,unlock:!1,atomic:!1,...i},o=typeof n=="string"?new TextEncoder().encode(n):n;if(this.okra.runtimeTransport==="rest"){let c=o instanceof Uint8Array?o:await lf(o);await this.okra.invoke("fs.writeFile",{path:e,contents:c,options:t}).catch(u=>this.handleError(u));return}let a=N(),s=this.okra.invoke("fs.writeStream",{id:a,path:e,options:t});s.catch(()=>{});try{for await(let u of uf(o))if(!await this.okra.invoke("fs.writeChunk",{id:a,contents:u}))throw new Error(`File write stream ${a} is not available`);if(!await this.okra.invoke("fs.endWrite",{id:a}))throw new Error(`File write stream ${a} could not be completed`);await s}catch(c){throw await this.okra.invoke("fs.abortWrite",{id:a}).catch(()=>!1),await s.catch(()=>!1),c}}async read(e){try{let n=await this.okra.invoke("fs.readFile",{path:e});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}catch(n){this.handleError(n)}}async readText(e){return new TextDecoder().decode(await this.read(e))}async readLines(e,n){try{let i=await this.okra.invoke("fs.readFile",{path:e,lineRange:{lineStart:n.start,lineEnd:n.end}});if(typeof i=="string"||i instanceof Uint8Array)throw new Error(`Unexpected ranged file response for ${e}`);return{start:i.lineStart,end:i.lineEnd,content:i.content,...i.error===null?{}:{warning:i.error}}}catch(i){this.handleError(i)}}readStream(e){if(this.okra.runtimeTransport==="rest")return new ReadableStream({start:async o=>{try{o.enqueue(await this.read(e)),o.close()}catch(a){o.error(a)}}});let n=N(),i=null,t=!1;return new ReadableStream({start:o=>{i=this.okra.listen(`fs.read.${n}`,a=>{o.enqueue(a.data)}),this.okra.invoke("fs.readStream",{id:n,path:e}).then(()=>{t||(t=!0,i?.dispose(),o.close())}).catch(a=>{t||(t=!0,i?.dispose(),o.error(a))})},cancel:async()=>{t||(t=!0,i?.dispose(),await this.okra.invoke("fs.cancelRead",{id:n}).catch(()=>!1))}})}follow(e,n={}){if(this.okra.runtimeTransport==="rest")return new ReadableStream({start(u){u.error(new J("Following files requires the realtime transport."))}});let i=N(),t=null,o=null,a=!1,s=!1,c=async()=>{s||(s=!0,t?.dispose(),t=null,o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,a&&await this.okra.invoke("fs.cancelFollow",{id:i}).catch(()=>!1))};return new ReadableStream({start:u=>{if(t=this.okra.listen(`fs.follow.${i}`,l=>{s||u.enqueue(l.data)}),n.signal){if(o=()=>{c().finally(()=>u.error(n.signal?.reason??new Error("Aborted")))},n.signal.aborted){o();return}n.signal.addEventListener("abort",o,{once:!0})}a=!0,this.okra.invoke("fs.follow",{id:i,path:e,lines:n.lines??10}).then(()=>{s||(s=!0,t?.dispose(),o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,u.close())}).catch(l=>{s||(s=!0,t?.dispose(),o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,u.error(l))})},cancel:c})}find(e,n={useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1}){return this.okra.invoke("fs.find",{query:e,options:{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1,...n}})}search(e,n,i){e.id||(e.id=N());let t={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,a=async c=>{c===!1&&s.dispose(),i&&await Promise.resolve(i(c))===!1&&s.dispose()},s=this.okra.listen(`fs.text.search.${o}`,a);return this.okra.invoke("fs.textSearch",{query:e,options:{...t,...n}}).finally(()=>s.dispose())}tail(e,n={}){return this.okra.invoke("fs.tail",{path:e,lines:n.lines??10}).then(({content:i})=>i).catch(i=>this.handleError(i))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(n=>this.handleError(n))}move(e,n,i={}){return this.okra.invoke("fs.rename",{from:e,to:n,options:{overwrite:!1,...i}}).catch(t=>this.handleError(t))}remove(e,n={}){return this.okra.invoke("fs.delete",{path:e,options:{recursive:!1,useTrash:!1,atomic:!1,...n}}).catch(i=>this.handleError(i))}copy(e,n,i={}){return this.okra.invoke("fs.copy",{source:e,destination:n,options:{overwrite:!1,...i}}).catch(t=>this.handleError(t))}list(e,n={}){return this.okra.invoke("fs.readDirectory",{path:e,include:n.include??[],exclude:n.exclude??[]}).catch(i=>this.handleError(i))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(n=>this.handleError(n))}watch(e,n,i){let t=this.okra.listen(`fs.watch.${e}`,i),o={dispose:()=>{t.dispose(),this.okra.invoke("fs.unwatch",{path:e}).catch(()=>{})}},a=new Fi(o,()=>{this.watches.get(e)?.onDidChange===i&&this.watches.delete(e)});return this.watches.set(e,{options:n,path:e,onDidChange:i}),this.okra.invoke("fs.watch",{path:e,options:n}).then(()=>a).catch(s=>{throw a.dispose(),s})}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e={}){let n=N(),i=!!e.onChunk,t=[],o=this.okra.listen(`fs.download.${n}`,i?e.onChunk:a=>{t.push(a)});return this.okra.invoke("fs.download",{id:n,exclude:e.exclude,include:e.include}).then(()=>new Blob(t,{type:"application/octet-stream"})).finally(()=>o.dispose())}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e}};async function*uf(r){if(r instanceof Uint8Array){yield r;return}yield*r}async function lf(r){let e=[],n=0;for await(let o of r)e.push(o),n+=o.byteLength;let i=new Uint8Array(n),t=0;for(let o of e)i.set(o,t),t+=o.byteLength;return i}var Ol=(r,e)=>{let n;return Promise.race([r,new Promise((i,t)=>n=setTimeout(t,e,new Fe("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(n))},Dr=r=>{let e=null;return()=>e||(e=r())};var df=8,pf=/[\x00-\x1f\x7f]/,Pt=class{constructor(e){this.okra=e}list(){return this.okra.invoke("terminal.list")}async create(e={}){let n=e.id??N(),i=this.processHandle(n,e.abortSignal),t=typeof e.command=="string"&&e.args?.length?[e.command,...e.args]:e.command,{abortSignal:o,args:a,...s}=e;try{let c=await this.okra.invoke("terminal.create",{...s,id:n,kind:e.kind??"bash",size:e.size??[80,24],command:t},{abortSignal:o});return{...i.process,...c}}catch(c){throw i.dispose(),c}}async attach(e,n){let i=this.processHandle(e,n?.abortSignal);try{let t=await this.okra.invoke("terminal.attach",{id:e,replayHistory:n?.replayHistory},{abortSignal:n?.abortSignal});return t?{...i.process,...t}:(i.dispose(),!1)}catch(t){throw i.dispose(),t}}processHandle(e,n){let i=new Set,t,o=()=>{t&&(n?.removeEventListener("abort",t),t=void 0);for(let Z of i)Z.dispose();i.clear()},a="",s,c=()=>{if(s&&(clearTimeout(s),s=void 0),a==="")return;let Z=a;a="",this.okra.send("terminal.input",{id:e,input:Z})},u=()=>{s||(s=setTimeout(c,df))},l=Z=>{let j=typeof Z=="string"?Z:new TextDecoder().decode(Z);if(a+=j,pf.test(j)){c();return}u()},m=()=>{c(),o()},g=new WritableStream({write:l,close:m,abort:m}),f=null,$=new ReadableStream({start:Z=>{f=Z,i.add(this.okra.listen(`terminal.output.${e}`,j=>{f?.enqueue(j.output)}))},cancel:()=>{f=null,m()}}),S=new Promise(Z=>{i.add(this.okra.listen(`terminal.close.${e}`,j=>{if(f)try{f.close()}catch{}m(),Z(j.exitCode)}))}),z=Dr(()=>(m(),this.okra.invoke("terminal.close",{id:e}))),wt=Z=>{this.okra.invoke("terminal.resize",{id:e,width:Z.cols,height:Z.rows})};return n&&!n.aborted&&(t=()=>{z()},n.addEventListener("abort",t,{once:!0})),{process:{wait:()=>S,input:g,output:$,kill:z,resize:wt},dispose:m}}};var zt=class{constructor(e){this.okra=e}login(e){let n=new URL(e).searchParams.get("ticket");if(n===null||n==="")throw new TypeError("The notebook connection does not contain a runtime ticket.");return this.okra.invoke("auth.login",{runtimeTicket:n})}};var Et=class{constructor(e){this.okra=e}message(e,n){return this.okra.invoke("lsp.message",{id:e,message:n})}listen(e,n,i){return this.okra.listen(`${n}.${e}`,t=>i(t))}onClose(e,n){return this.listen(e,"lsp.closed",i=>n(i.code,i.reason))}onError(e,n){return this.listen(e,"lsp.error",i=>n(i.message))}onClientDisconnect(e){return this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,n){return this.listen(e,"lsp.response",i=>n(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 Ur.create(e,this)}whenSocketConnected(){return this.okra.connected()}},Ur=class r{constructor(e,n){this.id=e;this.lsp=n}send(e){return this.lsp.message(this.id,e)}onMessage(e){return this.lsp.onResponse(this.id,e)}onError(e){return this.lsp.onError(this.id,e)}onClose(e){return this.lsp.onClose(this.id,e)}dispose(){this.lsp.close(this.id)}start(){this.lsp.start(this.id)}onClientDisconnect(e){return this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,n){return new r(e,n)}};function mf(r,e=[],n){let i=Array.isArray(e)?e:[],t=Array.isArray(e)?n:e;return{command:Array.isArray(r)?r:i.length>0?[r,...i]:r,opts:{tty:!1,...t}}}var ce=class{constructor(){this.controller=null;this.closed=!1;this.stream=new ReadableStream({start:e=>{this.controller=e},cancel:()=>{this.closed=!0,this.controller=null}})}enqueue(e){this.closed||this.controller?.enqueue(e)}close(){this.closed||(this.closed=!0,this.controller?.close(),this.controller=null)}fail(e){this.closed||(this.closed=!0,this.controller?.error(e),this.controller=null)}},Mi=class{constructor(e,n,i,t){this.id=e;this.okra=n;let o=new ce,a=new ce,s=new ce;this.output=o.stream,this.stdout=a.stream,this.stderr=s.stream,this.stdin=new WritableStream({write:async $=>{let S=typeof $=="string"?$:new TextDecoder().decode($);if(!await this.okra.invoke("shell.input",{id:this.id,input:S}))throw new Error(`Process ${this.id} is not accepting input`)}});let c=new TextEncoder,u=this.okra.listen(`shell.output.${this.id}`,$=>{let S=c.encode($.output),z=$.source??"output";o.enqueue({source:z,data:S}),z==="stderr"?s.enqueue(S):a.enqueue(S)}),l=()=>{u?.dispose(),u=null,o.close(),a.close(),s.close()},m=$=>{u?.dispose(),u=null,o.fail($),a.fail($),s.fail($)},{abortSignal:g,...f}=t;this.completion=this.okra.invoke("shell.exec",{command:i,opts:{...f,id:this.id}},{abortSignal:g}).then($=>(l(),$)).catch($=>{throw m($),$})}wait(){return this.completion}async kill(){await this.okra.invoke("shell.kill",{id:this.id})}},Tt=class{constructor(e){this.okra=e}run(e,n=[],i){let t=mf(e,n,i),o=t.opts?.id??N();return new Mi(o,this.okra,t.command,{...t.opts,id:o})}};var Bi=class{constructor(e,n){this.client=e;this.notebookId=n}async set(e){return(await this.client.put(`/notebook/${this.notebookId}/composer/credentials`,e)).data}async remove(e,n){let i=new URLSearchParams({type:e});n&&i.set("url",n),await this.client.delete(`/notebook/${this.notebookId}/composer/credentials?${i.toString()}`)}},Gi=class{constructor(e,n,i,t,o){this.id=e;this.okra=n;let a=new ce,s=new ce,c=new ce;this.output=a.stream,this.stdout=s.stream,this.stderr=c.stream;let u=new TextEncoder,l=this.okra.listen(`composer.output.${this.id}`,f=>{let $=u.encode(f.output),S=f.source??"output";a.enqueue({source:S,data:$}),S==="stderr"?c.enqueue($):s.enqueue($)}),m=()=>{l?.dispose(),l=null,a.close(),s.close(),c.close()},g=f=>{l?.dispose(),l=null,a.fail(f),s.fail(f),c.fail(f)};this.completion=this.okra.invoke("composer.invoke",{id:e,command:i,args:t,options:o}).then(f=>(m(),f)).catch(f=>{throw g(f),f})}wait(){return this.completion}async kill(){await this.okra.invoke("composer.kill",{id:this.id})}},Dt=class{constructor(e,n){this.okra=e;this.credentials=new Bi(n,e.data.id)}run(e,n={},i={}){return new Gi(N(),this.okra,e,n,i)}packages(){return this.okra.invoke("composer.packages")}};var Or=class{constructor(e){this.okra=e;this.references=new Map;this.synchronization=Promise.resolve();e.runtimeTransport==="realtime"&&e.onDidConnect(()=>{this.references.size>0&&this.synchronize()})}async acquire(e){this.references.set(e,(this.references.get(e)??0)+1);try{await this.synchronize()}catch(i){throw this.removeReference(e),i}let n=!1;return async()=>{n||(n=!0,this.removeReference(e),await this.synchronize())}}removeReference(e){let n=this.references.get(e)??0;n<=1?this.references.delete(e):this.references.set(e,n-1)}synchronize(){return this.synchronization=this.synchronization.catch(()=>{}).then(async()=>{let e=Array.from(this.references.keys());e.length===0?await this.okra.invoke("container.stop-telemetry"):await this.okra.invoke("container.stream-telemetry",{features:e})}),this.synchronization}};function Me(r,e,n,i,t,o={}){let a=null,s=null,c=!1,u=null,l=async()=>{c||(c=!0,a?.dispose(),a=null,u&&o.signal&&o.signal.removeEventListener("abort",u),u=null,await s?.(),s=null)};return new ReadableStream({start(m){if(a=r.listen(i,g=>{c||m.enqueue(t(g))}),o.signal){if(u=()=>{l().finally(()=>m.error(o.signal?.reason??new Error("Aborted")))},o.signal.aborted){u();return}o.signal.addEventListener("abort",u,{once:!0})}e.acquire(n).then(async g=>{if(c){await g();return}s=g}).catch(g=>{c||(c=!0,a?.dispose(),u&&o.signal&&o.signal.removeEventListener("abort",u),u=null,m.error(g))})},cancel:l})}var Ut=class{constructor(e,n){this.okra=e;this.telemetry=n}follow(e={}){return Me(this.okra,this.telemetry,"logs","notebook.log",n=>({timestamp:new Date().toISOString(),source:"runtime",message:n}),e)}};var Ot=class{constructor(e,n){this.okra=e;this.telemetry=n}current(){return this.okra.invoke("container.stats")}watch(e={}){return Me(this.okra,this.telemetry,"stats","container.stats",n=>n,e)}};var Rt=class{constructor(e,n){this.okra=e;this.telemetry=n}list(){return this.okra.invoke("container.opened-ports")}watch(e={}){return Me(this.okra,this.telemetry,"ports","container.ports",n=>n,e)}};var Wi=class{constructor(e){this.metrics=e}current(){return this.metrics.current()}watch(e={}){return this.metrics.watch(e)}},Ji=class{constructor(e){this.logs=e}follow(e={}){return this.logs.follow(e)}},Vi=class{constructor(e){this.ports=e}list(){return this.ports.list()}watch(e={}){return this.ports.watch(e)}},Nt=class{constructor(e){this.notebook=e;let n=new Or(e);this.metrics=new Wi(new Ot(e,n)),this.logs=new Ji(new Ut(e,n)),this.ports=new Vi(new Rt(e,n))}setPhpVersion(e){return this.notebook.invoke("container.set-php",{version:e})}};var jt=class{constructor(e){this.okra=e}eval(e,n="",i={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:n,repl:i})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}resize(e,n){return this.okra.invoke("repl.resize",{cols:e,rows:n})}listen(e,n){return this.okra.listen(e,n)}onOutput(e){return this.okra.listen("repl.output",e)}};var Rl=["redis"],ff=["start","nginx",...Rl],At=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,n){return this.okra.invoke("service.run",{name:e,command:n})}stop(e){return this.okra.invoke("service.stop",{name:e})}logs(e,n={}){return n.follow?this.followLogs(e,n):this.okra.invoke("service.logs",{name:e,tail:n.tail}).then(i=>{if(!("output"in i))throw new Error(`Unexpected service.logs response for ${e}`);return i.output})}followLogs(e,n){let i=n.id||N(),t=new Set,o=null,a=!1,s=()=>{for(let m of t)m.dispose();t.clear()},c=()=>{if(!a&&(a=!0,s(),o))try{o.close()}catch{}},u=m=>{a||(a=!0,s(),o&&o.error(m))},l=Dr(()=>(c(),this.okra.invoke("service.stop-logs",{id:i})));return new ReadableStream({start:m=>{o=m,t.add(this.okra.listen(`service.log.${i}`,g=>{o?.enqueue(g.output)})),this.okra.invoke("service.logs",{name:e,tail:n.tail,follow:!0,id:i}).catch(g=>{u(g)})},cancel:()=>l().then(()=>{})})}};var Ct=class{constructor(e){this.okra=e}get(){return this.okra.invoke("config.get")}update(e){return this.okra.invoke("config.update",{config:e})}setPorts(e){return this.okra.invoke("config.set-ports",{ports:e})}};function Nl(r){let e=r.length,n=0,i=0;for(;i<e;){let t=r.charCodeAt(i++);if((t&4294967168)===0){n++;continue}else if((t&4294965248)===0)n+=2;else{if(t>=55296&&t<=56319&&i<e){let o=r.charCodeAt(i);(o&64512)===56320&&(++i,t=((t&1023)<<10)+(o&1023)+65536)}(t&4294901760)===0?n+=3:n+=4}}return n}function gf(r,e,n){let i=r.length,t=n,o=0;for(;o<i;){let a=r.charCodeAt(o++);if((a&4294967168)===0){e[t++]=a;continue}else if((a&4294965248)===0)e[t++]=a>>6&31|192;else{if(a>=55296&&a<=56319&&o<i){let s=r.charCodeAt(o);(s&64512)===56320&&(++o,a=((a&1023)<<10)+(s&1023)+65536)}(a&4294901760)===0?(e[t++]=a>>12&15|224,e[t++]=a>>6&63|128):(e[t++]=a>>18&7|240,e[t++]=a>>12&63|128,e[t++]=a>>6&63|128)}e[t++]=a&63|128}}var hf=new TextEncoder,vf=50;function bf(r,e,n){hf.encodeInto(r,e.subarray(n))}function jl(r,e,n){r.length>vf?bf(r,e,n):gf(r,e,n)}var yf=4096;function Ki(r,e,n){let i=e,t=i+n,o=[],a="";for(;i<t;){let s=r[i++];if((s&128)===0)o.push(s);else if((s&224)===192){let c=r[i++]&63;o.push((s&31)<<6|c)}else if((s&240)===224){let c=r[i++]&63,u=r[i++]&63;o.push((s&31)<<12|c<<6|u)}else if((s&248)===240){let c=r[i++]&63,u=r[i++]&63,l=r[i++]&63,m=(s&7)<<18|c<<12|u<<6|l;m>65535&&(m-=65536,o.push(m>>>10&1023|55296),m=56320|m&1023),o.push(m)}else o.push(s);o.length>=yf&&(a+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(a+=String.fromCharCode(...o)),a}var xf=new TextDecoder,$f=200;function kf(r,e,n){let i=r.subarray(e,e+n);return xf.decode(i)}function Al(r,e,n){return n>$f?kf(r,e,n):Ki(r,e,n)}var Pe=class{constructor(e,n){this.type=e,this.data=n}};var V=class r extends Error{constructor(e){super(e);let n=Object.create(r.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:r.name})}};function Cl(r,e,n){let i=n/4294967296,t=n;r.setUint32(e,i),r.setUint32(e+4,t)}function Rr(r,e,n){let i=Math.floor(n/4294967296),t=n;r.setUint32(e,i),r.setUint32(e+4,t)}function Nr(r,e){let n=r.getInt32(e),i=r.getUint32(e+4);return n*4294967296+i}function Zl(r,e){let n=r.getUint32(e),i=r.getUint32(e+4);return n*4294967296+i}var _f=-1,wf=4294967296-1,Sf=17179869184-1;function If({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Sf)if(e===0&&r<=wf){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,r),n}else{let n=r/4294967296,i=r&4294967295,t=new Uint8Array(8),o=new DataView(t.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,i),t}else{let n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,e),Rr(i,4,r),n}}function Pf(r){let e=r.getTime(),n=Math.floor(e/1e3),i=(e-n*1e3)*1e6,t=Math.floor(i/1e9);return{sec:n+t,nsec:i-t*1e9}}function zf(r){if(r instanceof Date){let e=Pf(r);return If(e)}else return null}function Ef(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 n=e.getUint32(0),i=e.getUint32(4),t=(n&3)*4294967296+i,o=n>>>2;return{sec:t,nsec:o}}case 12:{let n=Nr(e,4),i=e.getUint32(0);return{sec:n,nsec:i}}default:throw new V(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function Tf(r){let e=Ef(r);return new Date(e.sec*1e3+e.nsec/1e6)}var Ll={type:_f,encode:zf,decode:Tf};var fe=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Ll)}register({type:e,encode:n,decode:i}){if(e>=0)this.encoders[e]=n,this.decoders[e]=i;else{let t=-1-e;this.builtInEncoders[t]=n,this.builtInDecoders[t]=i}}tryToEncode(e,n){for(let i=0;i<this.builtInEncoders.length;i++){let t=this.builtInEncoders[i];if(t!=null){let o=t(e,n);if(o!=null){let a=-1-i;return new Pe(a,o)}}}for(let i=0;i<this.encoders.length;i++){let t=this.encoders[i];if(t!=null){let o=t(e,n);if(o!=null){let a=i;return new Pe(a,o)}}}return e instanceof Pe?e:null}decode(e,n,i){let t=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return t?t(e,n,i):new Pe(n,e)}};fe.defaultCodec=new fe;function Df(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function Zt(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Df(r)?new Uint8Array(r):Uint8Array.from(r)}var Uf=100,Of=2048,jr=class r{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??fe.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Uf,this.initialBufferSize=e?.initialBufferSize??Of,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,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);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,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){let n=new ArrayBuffer(e),i=new Uint8Array(n),t=new DataView(n);i.set(this.bytes),this.view=t,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=Nl(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),jl(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,n){let i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let i=Zt(e);this.writeU8a(i)}encodeArray(e,n){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 t of e)this.doEncode(t,n+1)}countWithoutUndefined(e,n){let i=0;for(let t of n)e[t]!==void 0&&i++;return i}encodeMap(e,n){let i=Object.keys(e);this.sortKeys&&i.sort();let t=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(t<16)this.writeU8(128+t);else if(t<65536)this.writeU8(222),this.writeU16(t);else if(t<4294967296)this.writeU8(223),this.writeU32(t);else throw new Error(`Too large map object: ${t}`);for(let o of i){let a=e[o];this.ignoreUndefined&&a===void 0||(this.encodeString(o),this.doEncode(a,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let i=e.data(this.pos+6),t=i.length;if(t>=4294967296)throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t),this.writeI8(e.type),this.writeU8a(i);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}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),Cl(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Rr(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 qi(r,e){return new jr(e).encodeSharedRef(r)}function Ar(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var Rf=16,Nf=16,Cr=class{constructor(e=Rf,n=Nf){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,i){let t=this.caches[i-1];e:for(let o of t){let a=o.bytes;for(let s=0;s<i;s++)if(a[s]!==e[n+s])continue e;return o.str}return null}store(e,n){let i=this.caches[e.length-1],t={bytes:e,str:n};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=t:i.push(t)}decode(e,n,i){let t=this.find(e,n,i);if(t!=null)return this.hit++,t;this.miss++;let o=Ki(e,n,i),a=Uint8Array.prototype.slice.call(e,n,n+i);return this.store(a,o),o}};var Hi="array",Mt="map_key",Ml="map_value",jf=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new V("The type of key must be string or number but "+typeof r)},Xi=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=Hi,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=Mt,n.readCount=0,n.size=e,n.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===Hi){let i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Mt||e.type===Ml){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}},Ft=-1,Yi=new DataView(new ArrayBuffer(0)),Af=new Uint8Array(Yi.buffer);try{Yi.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 Fl=new RangeError("Insufficient data"),Cf=new Cr,Zr=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=Yi,this.bytes=Af,this.headByte=Ft,this.stack=new Xi,this.entered=!1,this.extensionCodec=e?.extensionCodec??fe.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:Cf,this.mapKeyConverter=e?.mapKeyConverter??jf}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=Ft,this.stack.reset()}setBuffer(e){let n=Zt(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Ft&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),i=Zt(e),t=new Uint8Array(n.length+i.length);t.set(n),t.set(i,n.length),this.setBuffer(t)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:i}=this;return new RangeError(`Extra ${n.byteLength-i} of ${n.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 n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}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 n=!1,i;for await(let s of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{i=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}let{headByte:t,pos:o,totalPos:a}=this;throw new RangeError(`Insufficient data in parsing ${Ar(t)} at ${a} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let i=n,t=-1;for await(let o of e){if(n&&t===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(t=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--t!==0;);}catch(a){if(!(a instanceof RangeError))throw a}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let t=e-128;if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e<160){let t=e-144;if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else{let t=e-160;n=this.decodeString(t,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let t=this.lookU8();n=this.decodeString(t,1)}else if(e===218){let t=this.lookU16();n=this.decodeString(t,2)}else if(e===219){let t=this.lookU32();n=this.decodeString(t,4)}else if(e===220){let t=this.readU16();if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else if(e===221){let t=this.readU32();if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else if(e===222){let t=this.readU16();if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e===223){let t=this.readU32();if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e===196){let t=this.lookU8();n=this.decodeBinary(t,1)}else if(e===197){let t=this.lookU16();n=this.decodeBinary(t,2)}else if(e===198){let t=this.lookU32();n=this.decodeBinary(t,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let t=this.lookU8();n=this.decodeExtension(t,1)}else if(e===200){let t=this.lookU16();n=this.decodeExtension(t,2)}else if(e===201){let t=this.lookU32();n=this.decodeExtension(t,4)}else throw new V(`Unrecognized type byte: ${Ar(e)}`);this.complete();let i=this.stack;for(;i.length>0;){let t=i.top();if(t.type===Hi)if(t.array[t.position]=n,t.position++,t.position===t.size)n=t.array,i.release(t);else continue e;else if(t.type===Mt){if(n==="__proto__")throw new V("The key __proto__ is not allowed");t.key=this.mapKeyConverter(n),t.type=Ml;continue e}else if(t.map[t.key]=n,t.readCount++,t.readCount===t.size)n=t.map,i.release(t);else{t.key=null,t.type=Mt;continue e}}return n}}readHeadByte(){return this.headByte===Ft&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Ft}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 V(`Unrecognized array type byte: ${Ar(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new V(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new V(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new V(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Fl;let i=this.pos+n,t;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?t=this.keyDecoder.decode(this.bytes,i,e):t=Al(this.bytes,i,e),this.pos+=n+e,t}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Mt:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new V(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Fl;let i=this.pos+n,t=this.bytes.subarray(i,i+e);return this.pos+=n+e,t}decodeExtension(e,n){if(e>this.maxExtLength)throw new V(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let i=this.view.getInt8(this.pos+n),t=this.decodeBinary(e,n+1);return this.extensionCodec.decode(t,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=Zl(this.view,this.pos);return this.pos+=8,e}readI64(){let e=Nr(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 Qi(r,e){return new Zr(e).decode(r)}var Lr=class{constructor(e){this.error=e}},Zf=r=>new Promise(e=>{setTimeout(e,r)}),Lf=(r,e)=>{let n=e.randomize?Math.random()+1:1,i=Math.max(e.minTimeout,1)*Math.pow(e.factor,r-1);return Math.round(Math.min(n*i,e.maxTimeout))};async function Bl(r,e={}){let n={retries:e.retries??10,minTimeout:e.minTimeout??1e3,maxTimeout:e.maxTimeout??1/0,factor:e.factor??2,randomize:e.randomize??!0},i=o=>{throw new Lr(o??new Error("Aborted"))},t;for(let o=1;o<=n.retries+1;o++)try{return await r(i,o)}catch(a){if(a instanceof Lr)throw a.error;if(t=a,o>n.retries)throw a;await e.onRetry?.(a,o),await Zf(Lf(o,n))}throw t}var ro={};te(ro,{default:()=>to});var eo=function(r,e){return eo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var t in i)i.hasOwnProperty(t)&&(n[t]=i[t])},eo(r,e)};function Gl(r,e){eo(r,e);function n(){this.constructor=r}r.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Ff(r){var e=typeof Symbol=="function"&&r[Symbol.iterator],n=0;return e?e.call(r):{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}}}function Mf(r,e){var n=typeof Symbol=="function"&&r[Symbol.iterator];if(!n)return r;var i=n.call(r),t,o=[],a;try{for(;(e===void 0||e-- >0)&&!(t=i.next()).done;)o.push(t.value)}catch(s){a={error:s}}finally{try{t&&!t.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o}function Bf(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Mf(arguments[e]));return r}var Wl=(function(){function r(e,n){this.target=n,this.type=e}return r})(),Gf=(function(r){Gl(e,r);function e(n,i){var t=r.call(this,"error",i)||this;return t.message=n.message,t.error=n,t}return e})(Wl),Wf=(function(r){Gl(e,r);function e(n,i,t){n===void 0&&(n=1e3),i===void 0&&(i="");var o=r.call(this,"close",t)||this;return o.wasClean=!0,o.code=n,o.reason=i,o}return e})(Wl);var Jf=function(){if(typeof WebSocket<"u")return WebSocket},Vf=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},ze={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},Kf=(function(){function r(e,n,i){var t=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(o){t._debug("open event");var a=t._options.minUptime,s=a===void 0?ze.minUptime:a;clearTimeout(t._connectTimeout),t._uptimeTimeout=setTimeout(function(){return t._acceptOpen()},s),t._ws.binaryType=t._binaryType,t._messageQueue.forEach(function(c){return t._ws.send(c)}),t._messageQueue=[],t.onopen&&t.onopen(o),t._listeners.open.forEach(function(c){return t._callEventListener(o,c)})},this._handleMessage=function(o){t._debug("message event"),t.onmessage&&t.onmessage(o),t._listeners.message.forEach(function(a){return t._callEventListener(o,a)})},this._handleError=function(o){t._debug("error event",o.message),t._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),t.onerror&&t.onerror(o),t._debug("exec error listeners"),t._listeners.error.forEach(function(a){return t._callEventListener(o,a)}),t._connect()},this._handleClose=function(o){t._debug("close event"),t._clearTimeouts(),t._shouldReconnect&&t._connect(),t.onclose&&t.onclose(o),t._listeners.close.forEach(function(a){return t._callEventListener(o,a)})},this._url=e,this._protocols=n,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(n,i){return typeof i=="string"?n+=i.length:i instanceof Blob?n+=i.size:n+=i.byteLength,n},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,n){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,n)},r.prototype.reconnect=function(e,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,n),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 n=this._options.maxEnqueuedMessages,i=n===void 0?ze.maxEnqueuedMessages:n;this._messageQueue.length<i&&(this._debug("enqueue",e),this._messageQueue.push(e))}},r.prototype.addEventListener=function(e,n){this._listeners[e]&&this._listeners[e].push(n)},r.prototype.dispatchEvent=function(e){var n,i,t=this._listeners[e.type];if(t)try{for(var o=Ff(t),a=o.next();!a.done;a=o.next()){var s=a.value;this._callEventListener(e,s)}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return!0},r.prototype.removeEventListener=function(e,n){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(i){return i!==n}))},r.prototype._debug=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this._options.debug&&console.log.apply(console,Bf(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,n=e.reconnectionDelayGrowFactor,i=n===void 0?ze.reconnectionDelayGrowFactor:n,t=e.minReconnectionDelay,o=t===void 0?ze.minReconnectionDelay:t,a=e.maxReconnectionDelay,s=a===void 0?ze.maxReconnectionDelay:a,c=0;return this._retryCount>0&&(c=o*Math.pow(i,this._retryCount-1),c>s&&(c=s)),this._debug("next delay",c),c},r.prototype._wait=function(){var e=this;return new Promise(function(n){setTimeout(n,e._getNextDelay())})},r.prototype._getNextUrl=function(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){var n=e();if(typeof n=="string")return Promise.resolve(n);if(n.then)return n}throw Error("Invalid URL")},r.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var n=this._options,i=n.maxRetries,t=i===void 0?ze.maxRetries:i,o=n.connectionTimeout,a=o===void 0?ze.connectionTimeout:o,s=n.WebSocket,c=s===void 0?Jf():s;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!Vf(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(u){e._closeCalled||(e._debug("connect",{url:u,protocols:e._protocols}),e._ws=e._protocols?new c(u,e._protocols):new c(u),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},a))})}},r.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new Gf(Error("TIMEOUT"),this))},r.prototype._disconnect=function(e,n){if(e===void 0&&(e=1e3),this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(e,n),this._handleClose(new Wf(e,n,this))}catch{}}},r.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},r.prototype._callEventListener=function(e,n){"handleEvent"in n?n.handleEvent(e):n(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})(),to=Kf;var qf=r=>{if(typeof r=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[r]??`STATE_${r}`},Hf=r=>{try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return r}},Jl=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return;let e=r,n=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!n)return;let i=typeof e.name=="string"&&e.name?e.name:void 0;return i?`${i}: ${n}`:n},Fr=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return String(r);let e=r,n=[],i=Jl(e);i&&n.push(i);let t=Jl(e.error);t&&t!==i&&n.push(`error=${t}`),typeof e.type=="string"&&e.type&&n.push(`type=${e.type}`),typeof e.code=="number"&&n.push(`code=${e.code}`),typeof e.reason=="string"&&e.reason&&e.reason!==i&&n.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&n.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&n.push(`url=${Hf(o.url)}`);let a=qf(o.readyState);a&&n.push(`readyState=${a}`)}return n.length>0?n.join(" | "):"Unknown websocket event"};var Be=null;typeof WebSocket<"u"?Be=WebSocket:typeof MozWebSocket<"u"?Be=MozWebSocket:typeof global<"u"?Be=global.WebSocket||global.MozWebSocket:typeof window<"u"?Be=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(Be=self.WebSocket||self.MozWebSocket);var Vl=Be;var Mr=class{constructor(){this.disposables=new Map}add(e,n){this.disposables.has(e)&&(console.warn(`Disposable with key "${e}" already exists. Disposing the old one.`),this.disposables.get(e)?.dispose()),typeof n=="function"&&(n=n()),this.disposables.set(e,n)}dispose(){this.disposables.forEach(e=>e.dispose()),this.disposables.clear()}};var Xf=new Set(["url","action","event","responseEvent","errorEvent","hasData","code","attempt","maxRetries","timeout","errorCount","byteLength"]),Yf=to??ro;var no=class extends O{constructor(e="WebSocket connection timeout"){super(e,"ConnectionTimeout")}},Ge=class extends O{constructor(n,i){super(n,"ConnectionFailed",i);this.originalError=i}},Ee=class extends O{constructor(n,i){super(n,"InvalidResponse",i);this.data=i}},Te=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},ge,io,oo,Br=class{constructor(e,n,i={}){this.eventEmitter=n;this.options=i;St(this,ge);this.clientId="";this.closed=!1;this.disposables=new Mr;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.incomingMessageChain=Promise.resolve();this.validateConfiguration(i),this.url=typeof e=="string"?new URL(e):null;let t=typeof e=="string"?this.url.toString():async()=>new URL(await e()).toString();this.PING_INTERVAL=i.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=i.connectWaitTimeout??3e4,this.rws=new Yf(t,[],{WebSocket:i.webSocket??globalThis.WebSocket??Vl,connectionTimeout:i.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:i.maxRetries??50,startClosed:!0}),this.log("debug","Transport initialized",{url:this.url===null?"dynamic":eg(this.url),options:i}),this.registerWatchers()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new Te("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new Te("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new Te("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new Te("maxRetries must be between 0 and 100")}log(e,n,i){if(this.options.debug){let t=new Date().toISOString(),o=Qf(i),a=o?`
|
|
1
|
+
var rf=Object.defineProperty;var Pl=r=>{throw TypeError(r)};var te=(r,e)=>{for(var n in e)rf(r,n,{get:e[n],enumerable:!0})};var Zi=(r,e,n)=>e.has(r)||Pl("Cannot "+n);var Ie=(r,e,n)=>(Zi(r,e,"read from private field"),n?n.call(r):e.get(r)),St=(r,e,n)=>e.has(r)?Pl("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,n),Er=(r,e,n,i)=>(Zi(r,e,"write to private field"),i?i.call(r,n):e.set(r,n),n),pe=(r,e,n)=>(Zi(r,e,"access private method"),n);var nf=["ActionNotFound","AuthenticationRequired","BadGateway","BadRequest","Conflict","FileAlreadyExists","FileIsDirectory","FileNotDirectory","FileNotFound","FilesystemUnavailable","InternalError","InvalidArgument","InvalidConfiguration","InvalidRequest","InvalidResponse","InvalidServiceCommand","MethodNotAllowed","NotebookInitializationFailed","NotebookUnavailable","NotFound","PayloadTooLarge","PermissionDenied","RateLimited","RequestFailed","RuntimeOperationFailed","ServiceNotFound","ServiceUnavailable","UnprocessableEntity","ValidationFailed","WorkspaceUnavailable"],J=class extends Error{constructor(e,n){super(e),this.name=new.target.name,this.cause=n}},F=class r extends J{constructor(e,n){super(e,n.cause),this.source=n.source,this.status=n.status,this.code=n.code,this.details=n.details}static is(e,n){return e instanceof r&&(n===void 0||e.code===n)}static isValidation(e){return r.is(e,"ValidationFailed")&&cf(e.details)!==void 0}is(e){return this.code===e}},O=class r extends J{constructor(n,i,t){super(n,t);this.code=i}static is(n,i){return n instanceof r&&(i===void 0||n.code===i)}is(n){return this.code===n}};function me(r,e,n){let i=Li(e),t=af(i?.status),o=zl(i?.code),a=zl(i?.message);if(t===void 0||!of(o)||a===void 0)throw new O("PHPSandbox returned an invalid error response.","InvalidResponse",n??e);return new F(a,{source:r,status:t,code:o,details:i?.details,cause:n})}function of(r){return typeof r=="string"&&nf.includes(r)}function af(r){return typeof r=="number"&&Number.isInteger(r)&&r>0?r:void 0}function zl(r){return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function Li(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0}function sf(r){let e=Li(r);if(e===void 0)return;let n=Object.entries(e);if(n.every(([,i])=>Array.isArray(i)&&i.every(t=>typeof t=="string")))return Object.fromEntries(n)}function cf(r){let e=Li(r),n=sf(e?.errors);return n===void 0?void 0:{errors:n}}var Fe=class extends Error{constructor(n,i){super(n);this.time=i}},It=class r extends O{constructor(n,i,t){super(n,"SendTimeout",t);this.time=i}static fromPromiseTimeoutError(n){return new r(n.message,n.time,n)}};var El="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var N=(r=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=El[n[r]&63];return e};var Tl=(t=>(t[t.Unknown=0]="Unknown",t[t.File=1]="File",t[t.Directory=2]="Directory",t[t.SymbolicLink=64]="SymbolicLink",t))(Tl||{}),Dl=(i=>(i[i.UPDATED=2]="UPDATED",i[i.ADDED=4]="ADDED",i[i.DELETED=8]="DELETED",i))(Dl||{}),Ul=(i=>(i[i.UPDATED=1]="UPDATED",i[i.ADDED=2]="ADDED",i[i.DELETED=3]="DELETED",i))(Ul||{}),Fi=class{constructor(e,n){this.disposable=e;this.onDispose=n;this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposable.dispose(),this.onDispose())}},Tr=class{constructor(e,n=i=>e.onDidConnect(i)){this.okra=e;this.watches=new Map;this.registerReconnectHandler(n)}registerReconnectHandler(e){e!==null&&e(()=>{for(let{path:n,options:i}of this.watches.values())this.okra.invoke("fs.watch",{path:n,options:i}).catch(()=>{})})}async write(e,n,i={}){let t={overwrite:!0,create:!0,unlock:!1,atomic:!1,...i},o=typeof n=="string"?new TextEncoder().encode(n):n;if(this.okra.runtimeTransport==="rest"){let c=o instanceof Uint8Array?o:await lf(o);await this.okra.invoke("fs.writeFile",{path:e,contents:c,options:t}).catch(u=>this.handleError(u));return}let a=N(),s=this.okra.invoke("fs.writeStream",{id:a,path:e,options:t});s.catch(()=>{});try{for await(let u of uf(o))if(!await this.okra.invoke("fs.writeChunk",{id:a,contents:u}))throw new Error(`File write stream ${a} is not available`);if(!await this.okra.invoke("fs.endWrite",{id:a}))throw new Error(`File write stream ${a} could not be completed`);await s}catch(c){throw await this.okra.invoke("fs.abortWrite",{id:a}).catch(()=>!1),await s.catch(()=>!1),c}}async read(e){try{let n=await this.okra.invoke("fs.readFile",{path:e});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}catch(n){this.handleError(n)}}async readText(e){return new TextDecoder().decode(await this.read(e))}async readLines(e,n){try{let i=await this.okra.invoke("fs.readFile",{path:e,lineRange:{lineStart:n.start,lineEnd:n.end}});if(typeof i=="string"||i instanceof Uint8Array)throw new Error(`Unexpected ranged file response for ${e}`);return{start:i.lineStart,end:i.lineEnd,content:i.content,...i.error===null?{}:{warning:i.error}}}catch(i){this.handleError(i)}}readStream(e){if(this.okra.runtimeTransport==="rest")return new ReadableStream({start:async o=>{try{o.enqueue(await this.read(e)),o.close()}catch(a){o.error(a)}}});let n=N(),i=null,t=!1;return new ReadableStream({start:o=>{i=this.okra.listen(`fs.read.${n}`,a=>{o.enqueue(a.data)}),this.okra.invoke("fs.readStream",{id:n,path:e}).then(()=>{t||(t=!0,i?.dispose(),o.close())}).catch(a=>{t||(t=!0,i?.dispose(),o.error(a))})},cancel:async()=>{t||(t=!0,i?.dispose(),await this.okra.invoke("fs.cancelRead",{id:n}).catch(()=>!1))}})}follow(e,n={}){if(this.okra.runtimeTransport==="rest")return new ReadableStream({start(u){u.error(new J("Following files requires the realtime transport."))}});let i=N(),t=null,o=null,a=!1,s=!1,c=async()=>{s||(s=!0,t?.dispose(),t=null,o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,a&&await this.okra.invoke("fs.cancelFollow",{id:i}).catch(()=>!1))};return new ReadableStream({start:u=>{if(t=this.okra.listen(`fs.follow.${i}`,l=>{s||u.enqueue(l.data)}),n.signal){if(o=()=>{c().finally(()=>u.error(n.signal?.reason??new Error("Aborted")))},n.signal.aborted){o();return}n.signal.addEventListener("abort",o,{once:!0})}a=!0,this.okra.invoke("fs.follow",{id:i,path:e,lines:n.lines??10}).then(()=>{s||(s=!0,t?.dispose(),o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,u.close())}).catch(l=>{s||(s=!0,t?.dispose(),o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,u.error(l))})},cancel:c})}find(e,n={useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1}){return this.okra.invoke("fs.find",{query:e,options:{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1,...n}})}search(e,n,i){e.id||(e.id=N());let t={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,a=async c=>{c===!1&&s.dispose(),i&&await Promise.resolve(i(c))===!1&&s.dispose()},s=this.okra.listen(`fs.text.search.${o}`,a);return this.okra.invoke("fs.textSearch",{query:e,options:{...t,...n}}).finally(()=>s.dispose())}tail(e,n={}){return this.okra.invoke("fs.tail",{path:e,lines:n.lines??10}).then(({content:i})=>i).catch(i=>this.handleError(i))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(n=>this.handleError(n))}move(e,n,i={}){return this.okra.invoke("fs.rename",{from:e,to:n,options:{overwrite:!1,...i}}).catch(t=>this.handleError(t))}remove(e,n={}){return this.okra.invoke("fs.delete",{path:e,options:{recursive:!1,useTrash:!1,atomic:!1,...n}}).catch(i=>this.handleError(i))}copy(e,n,i={}){return this.okra.invoke("fs.copy",{source:e,destination:n,options:{overwrite:!1,...i}}).catch(t=>this.handleError(t))}list(e,n={}){return this.okra.invoke("fs.readDirectory",{path:e,include:n.include??[],exclude:n.exclude??[]}).catch(i=>this.handleError(i))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(n=>this.handleError(n))}watch(e,n,i){let t=this.okra.listen(`fs.watch.${e}`,i),o={dispose:()=>{t.dispose(),this.okra.invoke("fs.unwatch",{path:e}).catch(()=>{})}},a=new Fi(o,()=>{this.watches.get(e)?.onDidChange===i&&this.watches.delete(e)});return this.watches.set(e,{options:n,path:e,onDidChange:i}),this.okra.invoke("fs.watch",{path:e,options:n}).then(()=>a).catch(s=>{throw a.dispose(),s})}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e={}){let n=N(),i=!!e.onChunk,t=[],o=this.okra.listen(`fs.download.${n}`,i?e.onChunk:a=>{t.push(a)});return this.okra.invoke("fs.download",{id:n,exclude:e.exclude,include:e.include}).then(()=>new Blob(t,{type:"application/octet-stream"})).finally(()=>o.dispose())}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e}};async function*uf(r){if(r instanceof Uint8Array){yield r;return}yield*r}async function lf(r){let e=[],n=0;for await(let o of r)e.push(o),n+=o.byteLength;let i=new Uint8Array(n),t=0;for(let o of e)i.set(o,t),t+=o.byteLength;return i}var Ol=(r,e)=>{let n;return Promise.race([r,new Promise((i,t)=>n=setTimeout(t,e,new Fe("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(n))},Dr=r=>{let e=null;return()=>e||(e=r())};var df=8,pf=/[\x00-\x1f\x7f]/,Pt=class{constructor(e){this.okra=e}list(){return this.okra.invoke("terminal.list")}async create(e={}){let n=e.id??N(),i=this.processHandle(n,e.abortSignal),t=typeof e.command=="string"&&e.args?.length?[e.command,...e.args]:e.command,{abortSignal:o,args:a,...s}=e;try{let c=await this.okra.invoke("terminal.create",{...s,id:n,kind:e.kind??"bash",size:e.size??[80,24],command:t},{abortSignal:o});return{...i.process,...c}}catch(c){throw i.dispose(),c}}async attach(e,n){let i=this.processHandle(e,n?.abortSignal);try{let t=await this.okra.invoke("terminal.attach",{id:e,replayHistory:n?.replayHistory},{abortSignal:n?.abortSignal});return t?{...i.process,...t}:(i.dispose(),!1)}catch(t){throw i.dispose(),t}}processHandle(e,n){let i=new Set,t,o=()=>{t&&(n?.removeEventListener("abort",t),t=void 0);for(let Z of i)Z.dispose();i.clear()},a="",s,c=()=>{if(s&&(clearTimeout(s),s=void 0),a==="")return;let Z=a;a="",this.okra.send("terminal.input",{id:e,input:Z})},u=()=>{s||(s=setTimeout(c,df))},l=Z=>{let j=typeof Z=="string"?Z:new TextDecoder().decode(Z);if(a+=j,pf.test(j)){c();return}u()},m=()=>{c(),o()},g=new WritableStream({write:l,close:m,abort:m}),f=null,$=new ReadableStream({start:Z=>{f=Z,i.add(this.okra.listen(`terminal.output.${e}`,j=>{f?.enqueue(j.output)}))},cancel:()=>{f=null,m()}}),S=new Promise(Z=>{i.add(this.okra.listen(`terminal.close.${e}`,j=>{if(f)try{f.close()}catch{}m(),Z(j.exitCode)}))}),z=Dr(()=>(m(),this.okra.invoke("terminal.close",{id:e}))),wt=Z=>{this.okra.invoke("terminal.resize",{id:e,width:Z.cols,height:Z.rows})};return n&&!n.aborted&&(t=()=>{z()},n.addEventListener("abort",t,{once:!0})),{process:{wait:()=>S,input:g,output:$,kill:z,resize:wt},dispose:m}}};var zt=class{constructor(e){this.okra=e}login(e){let n=new URL(e).searchParams.get("ticket");if(n===null||n==="")throw new TypeError("The notebook connection does not contain a runtime ticket.");return this.okra.invoke("auth.login",{runtimeTicket:n})}};var Et=class{constructor(e){this.okra=e}message(e,n){return this.okra.invoke("lsp.message",{id:e,message:n})}listen(e,n,i){return this.okra.listen(`${n}.${e}`,t=>i(t))}onClose(e,n){return this.listen(e,"lsp.closed",i=>n(i.code,i.reason))}onError(e,n){return this.listen(e,"lsp.error",i=>n(i.message))}onClientDisconnect(e){return this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,n){return this.listen(e,"lsp.response",i=>n(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 Ur.create(e,this)}whenSocketConnected(){return this.okra.connected()}},Ur=class r{constructor(e,n){this.id=e;this.lsp=n}send(e){return this.lsp.message(this.id,e)}onMessage(e){return this.lsp.onResponse(this.id,e)}onError(e){return this.lsp.onError(this.id,e)}onClose(e){return this.lsp.onClose(this.id,e)}dispose(){this.lsp.close(this.id)}start(){this.lsp.start(this.id)}onClientDisconnect(e){return this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,n){return new r(e,n)}};function mf(r,e=[],n){let i=Array.isArray(e)?e:[],t=Array.isArray(e)?n:e;return{command:Array.isArray(r)?r:i.length>0?[r,...i]:r,opts:{tty:!1,...t}}}var ce=class{constructor(){this.controller=null;this.closed=!1;this.stream=new ReadableStream({start:e=>{this.controller=e},cancel:()=>{this.closed=!0,this.controller=null}})}enqueue(e){this.closed||this.controller?.enqueue(e)}close(){this.closed||(this.closed=!0,this.controller?.close(),this.controller=null)}fail(e){this.closed||(this.closed=!0,this.controller?.error(e),this.controller=null)}},Mi=class{constructor(e,n,i,t){this.id=e;this.okra=n;let o=new ce,a=new ce,s=new ce;this.output=o.stream,this.stdout=a.stream,this.stderr=s.stream,this.stdin=new WritableStream({write:async $=>{let S=typeof $=="string"?$:new TextDecoder().decode($);if(!await this.okra.invoke("shell.input",{id:this.id,input:S}))throw new Error(`Process ${this.id} is not accepting input`)}});let c=new TextEncoder,u=this.okra.listen(`shell.output.${this.id}`,$=>{let S=c.encode($.output),z=$.source??"output";o.enqueue({source:z,data:S}),z==="stderr"?s.enqueue(S):a.enqueue(S)}),l=()=>{u?.dispose(),u=null,o.close(),a.close(),s.close()},m=$=>{u?.dispose(),u=null,o.fail($),a.fail($),s.fail($)},{abortSignal:g,...f}=t;this.completion=this.okra.invoke("shell.exec",{command:i,opts:{...f,id:this.id}},{abortSignal:g}).then($=>(l(),$)).catch($=>{throw m($),$})}wait(){return this.completion}async kill(){await this.okra.invoke("shell.kill",{id:this.id})}},Tt=class{constructor(e){this.okra=e}run(e,n=[],i){let t=mf(e,n,i),o=t.opts?.id??N();return new Mi(o,this.okra,t.command,{...t.opts,id:o})}};var Bi=class{constructor(e,n){this.client=e;this.notebookId=n}async set(e){return(await this.client.put(`/notebook/${this.notebookId}/composer/credentials`,e)).data}async remove(e,n){let i=new URLSearchParams({type:e});n&&i.set("url",n),await this.client.delete(`/notebook/${this.notebookId}/composer/credentials?${i.toString()}`)}},Gi=class{constructor(e,n,i,t,o){this.id=e;this.okra=n;let a=new ce,s=new ce,c=new ce;this.output=a.stream,this.stdout=s.stream,this.stderr=c.stream;let u=new TextEncoder,l=this.okra.listen(`composer.output.${this.id}`,f=>{let $=u.encode(f.output),S=f.source??"output";a.enqueue({source:S,data:$}),S==="stderr"?c.enqueue($):s.enqueue($)}),m=()=>{l?.dispose(),l=null,a.close(),s.close(),c.close()},g=f=>{l?.dispose(),l=null,a.fail(f),s.fail(f),c.fail(f)};this.completion=this.okra.invoke("composer.invoke",{id:e,command:i,args:t,options:o}).then(f=>(m(),f)).catch(f=>{throw g(f),f})}wait(){return this.completion}async kill(){await this.okra.invoke("composer.kill",{id:this.id})}},Dt=class{constructor(e,n){this.okra=e;this.credentials=new Bi(n,e.data.id)}run(e,n={},i={}){return new Gi(N(),this.okra,e,n,i)}packages(){return this.okra.invoke("composer.packages")}};var Or=class{constructor(e){this.okra=e;this.references=new Map;this.synchronization=Promise.resolve();e.runtimeTransport==="realtime"&&e.onDidConnect(()=>{this.references.size>0&&this.synchronize()})}async acquire(e){this.references.set(e,(this.references.get(e)??0)+1);try{await this.synchronize()}catch(i){throw this.removeReference(e),i}let n=!1;return async()=>{n||(n=!0,this.removeReference(e),await this.synchronize())}}removeReference(e){let n=this.references.get(e)??0;n<=1?this.references.delete(e):this.references.set(e,n-1)}synchronize(){return this.synchronization=this.synchronization.catch(()=>{}).then(async()=>{let e=Array.from(this.references.keys());e.length===0?await this.okra.invoke("container.stop-telemetry"):await this.okra.invoke("container.stream-telemetry",{features:e})}),this.synchronization}};function Me(r,e,n,i,t,o={}){let a=null,s=null,c=!1,u=null,l=async()=>{c||(c=!0,a?.dispose(),a=null,u&&o.signal&&o.signal.removeEventListener("abort",u),u=null,await s?.(),s=null)};return new ReadableStream({start(m){if(a=r.listen(i,g=>{c||m.enqueue(t(g))}),o.signal){if(u=()=>{l().finally(()=>m.error(o.signal?.reason??new Error("Aborted")))},o.signal.aborted){u();return}o.signal.addEventListener("abort",u,{once:!0})}e.acquire(n).then(async g=>{if(c){await g();return}s=g}).catch(g=>{c||(c=!0,a?.dispose(),u&&o.signal&&o.signal.removeEventListener("abort",u),u=null,m.error(g))})},cancel:l})}var Ut=class{constructor(e,n){this.okra=e;this.telemetry=n}follow(e={}){return Me(this.okra,this.telemetry,"logs","notebook.log",n=>({timestamp:new Date().toISOString(),source:"runtime",message:n}),e)}};var Ot=class{constructor(e,n){this.okra=e;this.telemetry=n}current(){return this.okra.invoke("container.stats")}watch(e={}){return Me(this.okra,this.telemetry,"stats","container.stats",n=>n,e)}};var Rt=class{constructor(e,n){this.okra=e;this.telemetry=n}list(){return this.okra.invoke("container.opened-ports")}resolve(e){return this.okra.invoke("container.resolve-port",{port:e})}watch(e={}){return Me(this.okra,this.telemetry,"ports","container.ports",n=>n,e)}};var Wi=class{constructor(e){this.metrics=e}current(){return this.metrics.current()}watch(e={}){return this.metrics.watch(e)}},Ji=class{constructor(e){this.logs=e}follow(e={}){return this.logs.follow(e)}},Vi=class{constructor(e){this.ports=e}list(){return this.ports.list()}resolve(e){return this.ports.resolve(e)}watch(e={}){return this.ports.watch(e)}},Nt=class{constructor(e){this.notebook=e;let n=new Or(e);this.metrics=new Wi(new Ot(e,n)),this.logs=new Ji(new Ut(e,n)),this.ports=new Vi(new Rt(e,n))}setPhpVersion(e){return this.notebook.invoke("container.set-php",{version:e})}};var jt=class{constructor(e){this.okra=e}eval(e,n="",i={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:n,repl:i})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}resize(e,n){return this.okra.invoke("repl.resize",{cols:e,rows:n})}listen(e,n){return this.okra.listen(e,n)}onOutput(e){return this.okra.listen("repl.output",e)}};var Rl=["redis"],ff=["start","nginx",...Rl],At=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,n){return this.okra.invoke("service.run",{name:e,command:n})}stop(e){return this.okra.invoke("service.stop",{name:e})}logs(e,n={}){return n.follow?this.followLogs(e,n):this.okra.invoke("service.logs",{name:e,tail:n.tail}).then(i=>{if(!("output"in i))throw new Error(`Unexpected service.logs response for ${e}`);return i.output})}followLogs(e,n){let i=n.id||N(),t=new Set,o=null,a=!1,s=()=>{for(let m of t)m.dispose();t.clear()},c=()=>{if(!a&&(a=!0,s(),o))try{o.close()}catch{}},u=m=>{a||(a=!0,s(),o&&o.error(m))},l=Dr(()=>(c(),this.okra.invoke("service.stop-logs",{id:i})));return new ReadableStream({start:m=>{o=m,t.add(this.okra.listen(`service.log.${i}`,g=>{o?.enqueue(g.output)})),this.okra.invoke("service.logs",{name:e,tail:n.tail,follow:!0,id:i}).catch(g=>{u(g)})},cancel:()=>l().then(()=>{})})}};var Ct=class{constructor(e){this.okra=e}get(){return this.okra.invoke("config.get")}update(e){return this.okra.invoke("config.update",{config:e})}setPorts(e){return this.okra.invoke("config.set-ports",{ports:e})}};function Nl(r){let e=r.length,n=0,i=0;for(;i<e;){let t=r.charCodeAt(i++);if((t&4294967168)===0){n++;continue}else if((t&4294965248)===0)n+=2;else{if(t>=55296&&t<=56319&&i<e){let o=r.charCodeAt(i);(o&64512)===56320&&(++i,t=((t&1023)<<10)+(o&1023)+65536)}(t&4294901760)===0?n+=3:n+=4}}return n}function gf(r,e,n){let i=r.length,t=n,o=0;for(;o<i;){let a=r.charCodeAt(o++);if((a&4294967168)===0){e[t++]=a;continue}else if((a&4294965248)===0)e[t++]=a>>6&31|192;else{if(a>=55296&&a<=56319&&o<i){let s=r.charCodeAt(o);(s&64512)===56320&&(++o,a=((a&1023)<<10)+(s&1023)+65536)}(a&4294901760)===0?(e[t++]=a>>12&15|224,e[t++]=a>>6&63|128):(e[t++]=a>>18&7|240,e[t++]=a>>12&63|128,e[t++]=a>>6&63|128)}e[t++]=a&63|128}}var hf=new TextEncoder,vf=50;function bf(r,e,n){hf.encodeInto(r,e.subarray(n))}function jl(r,e,n){r.length>vf?bf(r,e,n):gf(r,e,n)}var yf=4096;function Ki(r,e,n){let i=e,t=i+n,o=[],a="";for(;i<t;){let s=r[i++];if((s&128)===0)o.push(s);else if((s&224)===192){let c=r[i++]&63;o.push((s&31)<<6|c)}else if((s&240)===224){let c=r[i++]&63,u=r[i++]&63;o.push((s&31)<<12|c<<6|u)}else if((s&248)===240){let c=r[i++]&63,u=r[i++]&63,l=r[i++]&63,m=(s&7)<<18|c<<12|u<<6|l;m>65535&&(m-=65536,o.push(m>>>10&1023|55296),m=56320|m&1023),o.push(m)}else o.push(s);o.length>=yf&&(a+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(a+=String.fromCharCode(...o)),a}var xf=new TextDecoder,$f=200;function kf(r,e,n){let i=r.subarray(e,e+n);return xf.decode(i)}function Al(r,e,n){return n>$f?kf(r,e,n):Ki(r,e,n)}var Pe=class{constructor(e,n){this.type=e,this.data=n}};var V=class r extends Error{constructor(e){super(e);let n=Object.create(r.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:r.name})}};function Cl(r,e,n){let i=n/4294967296,t=n;r.setUint32(e,i),r.setUint32(e+4,t)}function Rr(r,e,n){let i=Math.floor(n/4294967296),t=n;r.setUint32(e,i),r.setUint32(e+4,t)}function Nr(r,e){let n=r.getInt32(e),i=r.getUint32(e+4);return n*4294967296+i}function Zl(r,e){let n=r.getUint32(e),i=r.getUint32(e+4);return n*4294967296+i}var _f=-1,wf=4294967296-1,Sf=17179869184-1;function If({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Sf)if(e===0&&r<=wf){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,r),n}else{let n=r/4294967296,i=r&4294967295,t=new Uint8Array(8),o=new DataView(t.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,i),t}else{let n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,e),Rr(i,4,r),n}}function Pf(r){let e=r.getTime(),n=Math.floor(e/1e3),i=(e-n*1e3)*1e6,t=Math.floor(i/1e9);return{sec:n+t,nsec:i-t*1e9}}function zf(r){if(r instanceof Date){let e=Pf(r);return If(e)}else return null}function Ef(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 n=e.getUint32(0),i=e.getUint32(4),t=(n&3)*4294967296+i,o=n>>>2;return{sec:t,nsec:o}}case 12:{let n=Nr(e,4),i=e.getUint32(0);return{sec:n,nsec:i}}default:throw new V(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function Tf(r){let e=Ef(r);return new Date(e.sec*1e3+e.nsec/1e6)}var Ll={type:_f,encode:zf,decode:Tf};var fe=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Ll)}register({type:e,encode:n,decode:i}){if(e>=0)this.encoders[e]=n,this.decoders[e]=i;else{let t=-1-e;this.builtInEncoders[t]=n,this.builtInDecoders[t]=i}}tryToEncode(e,n){for(let i=0;i<this.builtInEncoders.length;i++){let t=this.builtInEncoders[i];if(t!=null){let o=t(e,n);if(o!=null){let a=-1-i;return new Pe(a,o)}}}for(let i=0;i<this.encoders.length;i++){let t=this.encoders[i];if(t!=null){let o=t(e,n);if(o!=null){let a=i;return new Pe(a,o)}}}return e instanceof Pe?e:null}decode(e,n,i){let t=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return t?t(e,n,i):new Pe(n,e)}};fe.defaultCodec=new fe;function Df(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function Zt(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Df(r)?new Uint8Array(r):Uint8Array.from(r)}var Uf=100,Of=2048,jr=class r{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??fe.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Uf,this.initialBufferSize=e?.initialBufferSize??Of,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,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);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,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){let n=new ArrayBuffer(e),i=new Uint8Array(n),t=new DataView(n);i.set(this.bytes),this.view=t,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=Nl(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),jl(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,n){let i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let i=Zt(e);this.writeU8a(i)}encodeArray(e,n){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 t of e)this.doEncode(t,n+1)}countWithoutUndefined(e,n){let i=0;for(let t of n)e[t]!==void 0&&i++;return i}encodeMap(e,n){let i=Object.keys(e);this.sortKeys&&i.sort();let t=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(t<16)this.writeU8(128+t);else if(t<65536)this.writeU8(222),this.writeU16(t);else if(t<4294967296)this.writeU8(223),this.writeU32(t);else throw new Error(`Too large map object: ${t}`);for(let o of i){let a=e[o];this.ignoreUndefined&&a===void 0||(this.encodeString(o),this.doEncode(a,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let i=e.data(this.pos+6),t=i.length;if(t>=4294967296)throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t),this.writeI8(e.type),this.writeU8a(i);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}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),Cl(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Rr(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 qi(r,e){return new jr(e).encodeSharedRef(r)}function Ar(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var Rf=16,Nf=16,Cr=class{constructor(e=Rf,n=Nf){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,i){let t=this.caches[i-1];e:for(let o of t){let a=o.bytes;for(let s=0;s<i;s++)if(a[s]!==e[n+s])continue e;return o.str}return null}store(e,n){let i=this.caches[e.length-1],t={bytes:e,str:n};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=t:i.push(t)}decode(e,n,i){let t=this.find(e,n,i);if(t!=null)return this.hit++,t;this.miss++;let o=Ki(e,n,i),a=Uint8Array.prototype.slice.call(e,n,n+i);return this.store(a,o),o}};var Hi="array",Mt="map_key",Ml="map_value",jf=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new V("The type of key must be string or number but "+typeof r)},Xi=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=Hi,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=Mt,n.readCount=0,n.size=e,n.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===Hi){let i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Mt||e.type===Ml){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}},Ft=-1,Yi=new DataView(new ArrayBuffer(0)),Af=new Uint8Array(Yi.buffer);try{Yi.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 Fl=new RangeError("Insufficient data"),Cf=new Cr,Zr=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=Yi,this.bytes=Af,this.headByte=Ft,this.stack=new Xi,this.entered=!1,this.extensionCodec=e?.extensionCodec??fe.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:Cf,this.mapKeyConverter=e?.mapKeyConverter??jf}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=Ft,this.stack.reset()}setBuffer(e){let n=Zt(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Ft&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),i=Zt(e),t=new Uint8Array(n.length+i.length);t.set(n),t.set(i,n.length),this.setBuffer(t)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:i}=this;return new RangeError(`Extra ${n.byteLength-i} of ${n.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 n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}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 n=!1,i;for await(let s of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{i=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}let{headByte:t,pos:o,totalPos:a}=this;throw new RangeError(`Insufficient data in parsing ${Ar(t)} at ${a} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let i=n,t=-1;for await(let o of e){if(n&&t===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(t=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--t!==0;);}catch(a){if(!(a instanceof RangeError))throw a}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let t=e-128;if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e<160){let t=e-144;if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else{let t=e-160;n=this.decodeString(t,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let t=this.lookU8();n=this.decodeString(t,1)}else if(e===218){let t=this.lookU16();n=this.decodeString(t,2)}else if(e===219){let t=this.lookU32();n=this.decodeString(t,4)}else if(e===220){let t=this.readU16();if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else if(e===221){let t=this.readU32();if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else if(e===222){let t=this.readU16();if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e===223){let t=this.readU32();if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e===196){let t=this.lookU8();n=this.decodeBinary(t,1)}else if(e===197){let t=this.lookU16();n=this.decodeBinary(t,2)}else if(e===198){let t=this.lookU32();n=this.decodeBinary(t,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let t=this.lookU8();n=this.decodeExtension(t,1)}else if(e===200){let t=this.lookU16();n=this.decodeExtension(t,2)}else if(e===201){let t=this.lookU32();n=this.decodeExtension(t,4)}else throw new V(`Unrecognized type byte: ${Ar(e)}`);this.complete();let i=this.stack;for(;i.length>0;){let t=i.top();if(t.type===Hi)if(t.array[t.position]=n,t.position++,t.position===t.size)n=t.array,i.release(t);else continue e;else if(t.type===Mt){if(n==="__proto__")throw new V("The key __proto__ is not allowed");t.key=this.mapKeyConverter(n),t.type=Ml;continue e}else if(t.map[t.key]=n,t.readCount++,t.readCount===t.size)n=t.map,i.release(t);else{t.key=null,t.type=Mt;continue e}}return n}}readHeadByte(){return this.headByte===Ft&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Ft}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 V(`Unrecognized array type byte: ${Ar(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new V(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new V(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new V(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Fl;let i=this.pos+n,t;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?t=this.keyDecoder.decode(this.bytes,i,e):t=Al(this.bytes,i,e),this.pos+=n+e,t}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Mt:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new V(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Fl;let i=this.pos+n,t=this.bytes.subarray(i,i+e);return this.pos+=n+e,t}decodeExtension(e,n){if(e>this.maxExtLength)throw new V(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let i=this.view.getInt8(this.pos+n),t=this.decodeBinary(e,n+1);return this.extensionCodec.decode(t,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=Zl(this.view,this.pos);return this.pos+=8,e}readI64(){let e=Nr(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 Qi(r,e){return new Zr(e).decode(r)}var Lr=class{constructor(e){this.error=e}},Zf=r=>new Promise(e=>{setTimeout(e,r)}),Lf=(r,e)=>{let n=e.randomize?Math.random()+1:1,i=Math.max(e.minTimeout,1)*Math.pow(e.factor,r-1);return Math.round(Math.min(n*i,e.maxTimeout))};async function Bl(r,e={}){let n={retries:e.retries??10,minTimeout:e.minTimeout??1e3,maxTimeout:e.maxTimeout??1/0,factor:e.factor??2,randomize:e.randomize??!0},i=o=>{throw new Lr(o??new Error("Aborted"))},t;for(let o=1;o<=n.retries+1;o++)try{return await r(i,o)}catch(a){if(a instanceof Lr)throw a.error;if(t=a,o>n.retries)throw a;await e.onRetry?.(a,o),await Zf(Lf(o,n))}throw t}var ro={};te(ro,{default:()=>to});var eo=function(r,e){return eo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var t in i)i.hasOwnProperty(t)&&(n[t]=i[t])},eo(r,e)};function Gl(r,e){eo(r,e);function n(){this.constructor=r}r.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Ff(r){var e=typeof Symbol=="function"&&r[Symbol.iterator],n=0;return e?e.call(r):{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}}}function Mf(r,e){var n=typeof Symbol=="function"&&r[Symbol.iterator];if(!n)return r;var i=n.call(r),t,o=[],a;try{for(;(e===void 0||e-- >0)&&!(t=i.next()).done;)o.push(t.value)}catch(s){a={error:s}}finally{try{t&&!t.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o}function Bf(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Mf(arguments[e]));return r}var Wl=(function(){function r(e,n){this.target=n,this.type=e}return r})(),Gf=(function(r){Gl(e,r);function e(n,i){var t=r.call(this,"error",i)||this;return t.message=n.message,t.error=n,t}return e})(Wl),Wf=(function(r){Gl(e,r);function e(n,i,t){n===void 0&&(n=1e3),i===void 0&&(i="");var o=r.call(this,"close",t)||this;return o.wasClean=!0,o.code=n,o.reason=i,o}return e})(Wl);var Jf=function(){if(typeof WebSocket<"u")return WebSocket},Vf=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},ze={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},Kf=(function(){function r(e,n,i){var t=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(o){t._debug("open event");var a=t._options.minUptime,s=a===void 0?ze.minUptime:a;clearTimeout(t._connectTimeout),t._uptimeTimeout=setTimeout(function(){return t._acceptOpen()},s),t._ws.binaryType=t._binaryType,t._messageQueue.forEach(function(c){return t._ws.send(c)}),t._messageQueue=[],t.onopen&&t.onopen(o),t._listeners.open.forEach(function(c){return t._callEventListener(o,c)})},this._handleMessage=function(o){t._debug("message event"),t.onmessage&&t.onmessage(o),t._listeners.message.forEach(function(a){return t._callEventListener(o,a)})},this._handleError=function(o){t._debug("error event",o.message),t._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),t.onerror&&t.onerror(o),t._debug("exec error listeners"),t._listeners.error.forEach(function(a){return t._callEventListener(o,a)}),t._connect()},this._handleClose=function(o){t._debug("close event"),t._clearTimeouts(),t._shouldReconnect&&t._connect(),t.onclose&&t.onclose(o),t._listeners.close.forEach(function(a){return t._callEventListener(o,a)})},this._url=e,this._protocols=n,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(n,i){return typeof i=="string"?n+=i.length:i instanceof Blob?n+=i.size:n+=i.byteLength,n},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,n){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,n)},r.prototype.reconnect=function(e,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,n),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 n=this._options.maxEnqueuedMessages,i=n===void 0?ze.maxEnqueuedMessages:n;this._messageQueue.length<i&&(this._debug("enqueue",e),this._messageQueue.push(e))}},r.prototype.addEventListener=function(e,n){this._listeners[e]&&this._listeners[e].push(n)},r.prototype.dispatchEvent=function(e){var n,i,t=this._listeners[e.type];if(t)try{for(var o=Ff(t),a=o.next();!a.done;a=o.next()){var s=a.value;this._callEventListener(e,s)}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return!0},r.prototype.removeEventListener=function(e,n){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(i){return i!==n}))},r.prototype._debug=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this._options.debug&&console.log.apply(console,Bf(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,n=e.reconnectionDelayGrowFactor,i=n===void 0?ze.reconnectionDelayGrowFactor:n,t=e.minReconnectionDelay,o=t===void 0?ze.minReconnectionDelay:t,a=e.maxReconnectionDelay,s=a===void 0?ze.maxReconnectionDelay:a,c=0;return this._retryCount>0&&(c=o*Math.pow(i,this._retryCount-1),c>s&&(c=s)),this._debug("next delay",c),c},r.prototype._wait=function(){var e=this;return new Promise(function(n){setTimeout(n,e._getNextDelay())})},r.prototype._getNextUrl=function(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){var n=e();if(typeof n=="string")return Promise.resolve(n);if(n.then)return n}throw Error("Invalid URL")},r.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var n=this._options,i=n.maxRetries,t=i===void 0?ze.maxRetries:i,o=n.connectionTimeout,a=o===void 0?ze.connectionTimeout:o,s=n.WebSocket,c=s===void 0?Jf():s;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!Vf(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(u){e._closeCalled||(e._debug("connect",{url:u,protocols:e._protocols}),e._ws=e._protocols?new c(u,e._protocols):new c(u),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},a))})}},r.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new Gf(Error("TIMEOUT"),this))},r.prototype._disconnect=function(e,n){if(e===void 0&&(e=1e3),this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(e,n),this._handleClose(new Wf(e,n,this))}catch{}}},r.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},r.prototype._callEventListener=function(e,n){"handleEvent"in n?n.handleEvent(e):n(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})(),to=Kf;var qf=r=>{if(typeof r=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[r]??`STATE_${r}`},Hf=r=>{try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return r}},Jl=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return;let e=r,n=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!n)return;let i=typeof e.name=="string"&&e.name?e.name:void 0;return i?`${i}: ${n}`:n},Fr=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return String(r);let e=r,n=[],i=Jl(e);i&&n.push(i);let t=Jl(e.error);t&&t!==i&&n.push(`error=${t}`),typeof e.type=="string"&&e.type&&n.push(`type=${e.type}`),typeof e.code=="number"&&n.push(`code=${e.code}`),typeof e.reason=="string"&&e.reason&&e.reason!==i&&n.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&n.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&n.push(`url=${Hf(o.url)}`);let a=qf(o.readyState);a&&n.push(`readyState=${a}`)}return n.length>0?n.join(" | "):"Unknown websocket event"};var Be=null;typeof WebSocket<"u"?Be=WebSocket:typeof MozWebSocket<"u"?Be=MozWebSocket:typeof global<"u"?Be=global.WebSocket||global.MozWebSocket:typeof window<"u"?Be=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(Be=self.WebSocket||self.MozWebSocket);var Vl=Be;var Mr=class{constructor(){this.disposables=new Map}add(e,n){this.disposables.has(e)&&(console.warn(`Disposable with key "${e}" already exists. Disposing the old one.`),this.disposables.get(e)?.dispose()),typeof n=="function"&&(n=n()),this.disposables.set(e,n)}dispose(){this.disposables.forEach(e=>e.dispose()),this.disposables.clear()}};var Xf=new Set(["url","action","event","responseEvent","errorEvent","hasData","code","attempt","maxRetries","timeout","errorCount","byteLength"]),Yf=to??ro;var no=class extends O{constructor(e="WebSocket connection timeout"){super(e,"ConnectionTimeout")}},Ge=class extends O{constructor(n,i){super(n,"ConnectionFailed",i);this.originalError=i}},Ee=class extends O{constructor(n,i){super(n,"InvalidResponse",i);this.data=i}},Te=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},ge,io,oo,Br=class{constructor(e,n,i={}){this.eventEmitter=n;this.options=i;St(this,ge);this.clientId="";this.closed=!1;this.disposables=new Mr;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.incomingMessageChain=Promise.resolve();this.validateConfiguration(i),this.url=typeof e=="string"?new URL(e):null;let t=typeof e=="string"?this.url.toString():async()=>new URL(await e()).toString();this.PING_INTERVAL=i.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=i.connectWaitTimeout??3e4,this.rws=new Yf(t,[],{WebSocket:i.webSocket??globalThis.WebSocket??Vl,connectionTimeout:i.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:i.maxRetries??50,startClosed:!0}),this.log("debug","Transport initialized",{url:this.url===null?"dynamic":eg(this.url),options:i}),this.registerWatchers()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new Te("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new Te("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new Te("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new Te("maxRetries must be between 0 and 100")}log(e,n,i){if(this.options.debug){let t=new Date().toISOString(),o=Qf(i),a=o?`
|
|
2
2
|
${JSON.stringify(o,null,2)}`:"";console[e](`[Transport ${t}] ${n}${a}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):pe(this,ge,io).call(this)}id(){return this.clientId}async registerWatchers(){let e=n=>{this.incomingMessageChain=this.incomingMessageChain.catch(()=>{}).then(()=>this.processIncomingMessage(n)).catch(i=>{this.log("error","Failed to process queued WebSocket frame",{error:i instanceof Error?i.message:String(i)}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:i,rawMessage:n.data,timestamp:Date.now()})})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async processIncomingMessage(e){let n;try{n=await this.toArrayBuffer(e.data)}catch(t){this.log("error","Unexpected WebSocket message type",{error:t instanceof Error?t.message:String(t),messageType:typeof e.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:t,rawMessage:e.data,timestamp:Date.now()});return}if(n.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}let i;try{i=Qi(n)}catch(t){this.log("error","Failed to decode WebSocket frame",{error:t instanceof Error?t.message:String(t),byteLength:n.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:t,rawMessage:n,timestamp:Date.now()});return}try{await this.handleRawMessage(i)}catch(t){this.log("error","Failed to process WebSocket frame",{error:t instanceof Error?t.message:String(t),byteLength:n.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:t,rawMessage:n,timestamp:Date.now()})}}async toArrayBuffer(e){if(e instanceof Blob)return e.arrayBuffer();if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer;throw new Error("Unexpected message type: "+typeof 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:n,event:i,as:t}=e;if(!i||typeof i!="string")throw new Ee("Message missing event field",e);if(this.log("debug","Processing message",{event:i,hasData:!!n}),i==="App.Actions.GetClientId"){this.clientId=n.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(i==="Events.BootError"){let o=n,a=new F(o?.message||"Notebook is no longer available",{source:"runtime",status:503,code:"NotebookUnavailable",details:o||{}});this.log("error","Boot error received",{data:n}),this.terminate(a,4e3,a.message);return}if(i==="response"){let{responseEvent:o,data:a}=n;if(!o)throw new Ee("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,a);return}if(i==="error"){let{errorEvent:o,data:a}=n;if(!o)throw new Ee("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:a}),await this.handleMessage(o,a);return}await this.handleMessage(i,n,t)}catch(n){n instanceof Ee?this.log("error","Invalid message format",{error:n.message,data:n.data}):this.log("error","Failed to parse message",{ev:e,error:n instanceof Error?n.message:String(n)}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:n,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,n,i){if(e==="App.Actions.GetClientId"){this.clientId=n.id,this.eventEmitter.emit(e,this.clientId);return}e&&this.eventEmitter.emit(i||e,n)}listen(e,n,i){return this.eventEmitter.listen(e,n)}onDidBootError(e){return this.eventEmitter.listen("transport.boot_error",n=>{e(n.error)})}removeListener(e,n){this.eventEmitter.removeListener(e,n)}listenOnce(e,n,i){return this.eventEmitter.once(e,n,i)}emit(e,...n){this.eventEmitter.emit(e,...n)}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,n={},i={}){if(this.terminalError)throw this.terminalError;let t=i.responseEvent||`${e}_${N()}_response`,o=`${t}_error`,a,s,c=()=>{a&&(this.rws.removeEventListener("close",a),this.rws.removeEventListener("error",a)),s&&(i.abortSignal?.removeEventListener("abort",s),s=void 0),this.eventEmitter.removeListener(t),this.eventEmitter.removeListener(o)},u=(g,f)=>{if(this.terminalError){f(this.terminalError);return}let $=new DOMException("Request aborted","AbortError");if(i.abortSignal?.aborted){f($);return}if(i.abortSignal&&(s=()=>{f($)},i.abortSignal.addEventListener("abort",s,{once:!0})),!this.isConnected||this.isClosed){f(new Ge(`Connection is not open while sending ${e}. Current status: ${this.status}`));return}this.listenOnce(t,S=>{this.log("debug","Message response received",{action:e}),g(S)}),this.listenOnce(o,S=>{this.log("error","Message error received",{action:e,error:S}),f(me("runtime",S))}),a=S=>{if(S.code===1008&&(S.reason||"").includes("rate limit")){f(new F(S.reason||"Rate limit exceeded",{source:"runtime",status:429,code:"RateLimited",cause:S}));return}let z=Fr(S);f(this.terminalError||new Ge(`Connection lost to the notebook during request: ${z}`,S))},this.rws.addEventListener("close",a),this.rws.addEventListener("error",a);try{this.rws.send(this.pack({action:e,data:n,errorEvent:o,responseEvent:t})),this.log("debug","Message sent",{action:e,data:n})}catch(S){this.log("error","Failed to send message",{action:e,error:S}),f(new Ge(`Failed to send runtime action ${e}.`,S))}},l=async()=>{if(i.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");if(await pe(this,ge,io).call(this),i.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");let g=new Promise(u).finally(c);return i.timeout?Ol(g,i.timeout).catch(f=>{throw f instanceof Fe?It.fromPromiseTimeoutError(f):f}).finally(c):g},m=i.retries===!1?0:i.retries??0;return this.sendWithRetry(async()=>await l(),m)}send(e,n={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:n})),this.log("debug","One-way message sent",{action:e,data:n}),!0}catch(i){return this.log("error","Failed to send one-way message",{action:e,error:i}),!1}}pack(e){return new Blob([qi(e)])}sendWithRetry(e,n){return Bl(async(i,t)=>{try{return await e()}catch(o){if(o instanceof F||o instanceof Te||o instanceof Ee||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:t}),i(o);return}throw o instanceof It&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:t,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:t,error:o instanceof Error?o.message:String(o)}),o}},{retries:n,onRetry:(i,t)=>{this.log("warn","Send operation retry",{attempt:t,maxRetries:n,error:i instanceof Error?i.message:String(i)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,n={},i={}){return i.responseEvent||(i.responseEvent=`${e}_${N()}`),this.call("invoke",{action:e,data:n},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(){this.closed||this.close()}terminate(e,n=4e3,i=e.message){this.terminalError=e,F.is(e,"NotebookUnavailable")&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(n,i)}close(e,n){if(!this.closed){this.log("info","Closing transport connection",{code:e,reason:n}),this.connectPromise=null,this.disposables.dispose();try{this.rws.close(e,n)}catch(i){this.log("error","Error closing WebSocket",{error:i instanceof Error?i.message:String(i)})}this.eventEmitter.emit("transport.closed",{code:e,reason:n,timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}}onDidConnect(e){this.rws.addEventListener("open",e);let n={dispose:()=>{this.rws.removeEventListener("open",e)}};return this.disposables.add(`connect_${N()}`,n),n}onDidClose(e){this.rws.addEventListener("close",e);let n={dispose:()=>{this.rws.removeEventListener("close",e)}};return this.disposables.add(`close_${N()}`,n),n}};ge=new WeakSet,io=function(){return this.terminalError?Promise.reject(this.terminalError):this.isConnected?Promise.resolve():this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((e,n)=>{if(this.isConnected){e(),pe(this,ge,oo).call(this);return}let i,t=0,o=()=>{this.rws.removeEventListener("open",a),this.rws.removeEventListener("error",s),this.rws.removeEventListener("close",c),clearTimeout(i)},a=()=>{o(),this.connectPromise=null,e(),pe(this,ge,oo).call(this)},s=u=>{t+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:t,error:Fr(u)})},c=u=>{let l=Fr(u);if(u.code===1008||u.code===4e3){o(),this.connectPromise=null,n(new Ge(`WebSocket connection failed: ${l}`,u));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:l})};this.rws.addEventListener("open",a),this.rws.addEventListener("error",s),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),i=setTimeout(()=>{o(),this.connectPromise=null,n(new no(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},oo=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.log("debug","Sending periodic ping"),await this.invoke("ping"),this.log("debug","Ping successful")}catch(n){this.log("error","Ping failed",{error:n instanceof Error?n.message:String(n)})}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};function Qf(r){if(r===null||typeof r!="object")return null;let e=Object.entries(r).filter(([n,i])=>Xf.has(n)&&["string","number","boolean"].includes(typeof i));return e.length>0?Object.fromEntries(e):null}function eg(r){let e=new URL(r);return e.search="",e.hash="",e.toString()}var so={};te(so,{default:()=>ao});function ao(r){return{all:r=r||new Map,on:function(e,n){var i=r.get(e);i?i.push(n):r.set(e,[n])},off:function(e,n){var i=r.get(e);i&&(n?i.splice(i.indexOf(n)>>>0,1):r.set(e,[]))},emit:function(e,n){var i=r.get(e);i&&i.slice().map(function(t){t(n)}),(i=r.get("*"))&&i.slice().map(function(t){t(e,n)})}}}var tg=ao??so;function rg(r){let e=tg(r);return e.once=(n,i)=>{let t=o=>{e.off(n,t),i(o)};return e.on(n,t),{dispose:()=>{e.off(n,t)}}},e}var Bt=class r{constructor(){this.emitter=rg()}listen(e,n){let i=()=>{this.removeListener(e,n)};return this.emitter.on(e,n),{dispose:i}}emit(e,...n){this.emitter.emit(e,n.length>1?n:n[0])}once(e,n){return this.emitter.once(e,n)}static make(){return new r}static refresh(){return new r}removeListener(e,n){this.emitter.off(e,n)}static createInstance(){return new r}inspect(){return this.emitter.all}};var Wt=class{constructor(e,n){this.okra=e;this.client=n;this.targets=new co(e.data.id,n)}checkpoint(e,n,i="main",t=!1){return this.okra.invoke("git.checkpoint",{author:e,message:n,branch:i,allowEmpty:t})}checkout(e,n=!0){return this.okra.invoke("git.checkout",{branch:e,create:n})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}diff(e){return this.okra.invoke("git.diff",this.normalizeRemoteInput(e))}merge(e){return this.okra.invoke("git.merge",this.normalizeRemoteInput(e))}conflicts(){return this.okra.invoke("git.conflicts",{})}abortMerge(){return this.okra.invoke("git.resolve",{action:"abort"})}continueMerge(e,n){return this.okra.invoke("git.resolve",{action:"continue",author:e,message:n})}review(){return this.okra.invoke("git.review",{})}stage(e={all:!0}){return this.okra.invoke("git.stage",e)}unstage(e={all:!0}){return this.okra.invoke("git.unstage",e)}revert(e){return this.okra.invoke("git.revert",e)}async credentials(){return(await this.client.post(`/notebook/${this.okra.data.id}/git/credentials`)).data}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}normalizeRemoteInput(e){if(e.notebookId===void 0)return e;let n=e.notebookId.trim();if(!n)throw new Error("'notebookId' cannot be empty.");if(e.url?.trim())throw new Error("Pass either 'url' or 'notebookId', not both.");if(e.target?.trim())throw new Error("Pass either 'target' or 'notebookId', not both.");let{notebookId:i,...t}=e;return{...t,url:this.gitUrlForNotebook(n)}}gitUrlForNotebook(e){let n=new URL(this.okra.data.gitUrl);return n.username="",n.password="",n.pathname=`/${encodeURIComponent(e)}.git`,n.search="",n.hash="",n.toString()}},co=class{constructor(e,n){this.notebookId=e;this.client=n}async create(e){let n=await this.client.post(`/notebook/${this.notebookId}/git/targets`,Kl({...e}));return new Gt(n.data,this.notebookId,this.client)}async list(){return(await this.client.get(`/notebook/${this.notebookId}/git/targets`)).data.map(n=>new Gt(n,this.notebookId,this.client))}async get(e){let n=await this.client.get(`/notebook/${this.notebookId}/git/targets/${encodeURIComponent(ng(e))}`);return new Gt(n.data,this.notebookId,this.client)}},Gt=class r{constructor(e,n,i){this.data=e;this.notebookId=n;this.client=i}get id(){return this.data.id}async sync(e={}){let n=await this.client.post(`/notebook/${this.notebookId}/git/targets/${encodeURIComponent(this.id)}/sync`,Kl({...e}));return new r(n.data,this.notebookId,this.client)}};function ng(r){return typeof r=="string"?r:r.id}function Kl(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}var k={};te(k,{$brand:()=>lo,$input:()=>Us,$output:()=>Ds,NEVER:()=>uo,TimePrecision:()=>js,ZodAny:()=>Su,ZodArray:()=>Eu,ZodBase64:()=>vi,ZodBase64URL:()=>bi,ZodBigInt:()=>$t,ZodBigIntFormat:()=>$i,ZodBoolean:()=>xt,ZodCIDRv4:()=>gi,ZodCIDRv6:()=>hi,ZodCUID:()=>ci,ZodCUID2:()=>ui,ZodCatch:()=>Xu,ZodCodec:()=>_r,ZodCustom:()=>wr,ZodCustomStringFormat:()=>bt,ZodDate:()=>br,ZodDefault:()=>Wu,ZodDiscriminatedUnion:()=>Du,ZodE164:()=>yi,ZodEmail:()=>oi,ZodEmoji:()=>ai,ZodEnum:()=>ht,ZodError:()=>Rv,ZodExactOptional:()=>Mu,ZodFile:()=>Lu,ZodFirstPartyTypeKind:()=>ll,ZodFunction:()=>sl,ZodGUID:()=>mr,ZodIPv4:()=>mi,ZodIPv6:()=>fi,ZodISODate:()=>Qn,ZodISODateTime:()=>Yn,ZodISODuration:()=>ti,ZodISOTime:()=>ei,ZodIntersection:()=>Uu,ZodIssueCode:()=>jv,ZodJWT:()=>xi,ZodKSUID:()=>pi,ZodLazy:()=>il,ZodLiteral:()=>Zu,ZodMAC:()=>bu,ZodMap:()=>Au,ZodNaN:()=>Qu,ZodNanoID:()=>si,ZodNever:()=>Pu,ZodNonOptional:()=>Pi,ZodNull:()=>_u,ZodNullable:()=>Gu,ZodNumber:()=>yt,ZodNumberFormat:()=>Ze,ZodObject:()=>xr,ZodOptional:()=>Ii,ZodPipe:()=>kr,ZodPrefault:()=>Vu,ZodPreprocess:()=>el,ZodPromise:()=>al,ZodReadonly:()=>tl,ZodRealError:()=>H,ZodRecord:()=>gt,ZodSet:()=>Cu,ZodString:()=>vt,ZodStringFormat:()=>T,ZodSuccess:()=>Hu,ZodSymbol:()=>$u,ZodTemplateLiteral:()=>nl,ZodTransform:()=>Fu,ZodTuple:()=>Ru,ZodType:()=>w,ZodULID:()=>li,ZodURL:()=>vr,ZodUUID:()=>se,ZodUndefined:()=>ku,ZodUnion:()=>$r,ZodUnknown:()=>Iu,ZodVoid:()=>zu,ZodXID:()=>di,ZodXor:()=>Tu,_ZodString:()=>ii,_default:()=>Ju,_function:()=>jm,any:()=>mm,array:()=>yr,base64:()=>Hp,base64url:()=>Xp,bigint:()=>cm,boolean:()=>xu,catch:()=>Yu,check:()=>Am,cidrv4:()=>Kp,cidrv6:()=>qp,clone:()=>M,codec:()=>Um,coerce:()=>dl,config:()=>R,core:()=>de,cuid:()=>Lp,cuid2:()=>Fp,custom:()=>Cm,date:()=>gm,decode:()=>du,decodeAsync:()=>mu,describe:()=>Zm,discriminatedUnion:()=>$m,e164:()=>Yp,email:()=>Tp,emoji:()=>Cp,encode:()=>lu,encodeAsync:()=>pu,endsWith:()=>ot,enum:()=>wi,exactOptional:()=>Bu,file:()=>zm,flattenError:()=>Qt,float32:()=>im,float64:()=>om,formatError:()=>er,fromJSONSchema:()=>Jm,function:()=>jm,getErrorMap:()=>Cv,globalRegistry:()=>C,gt:()=>oe,gte:()=>G,guid:()=>Dp,hash:()=>nm,hex:()=>rm,hostname:()=>tm,httpUrl:()=>Ap,includes:()=>nt,instanceof:()=>Fm,int:()=>ri,int32:()=>am,int64:()=>um,intersection:()=>Ou,invertCodec:()=>Om,ipv4:()=>Wp,ipv6:()=>Vp,iso:()=>ft,json:()=>Bm,jwt:()=>Qp,keyof:()=>hm,ksuid:()=>Gp,lazy:()=>ol,length:()=>Ae,literal:()=>Pm,locales:()=>cr,looseObject:()=>ym,looseRecord:()=>_m,lowercase:()=>tt,lt:()=>ie,lte:()=>Y,mac:()=>Jp,map:()=>wm,maxLength:()=>je,maxSize:()=>ke,meta:()=>Lm,mime:()=>at,minLength:()=>le,minSize:()=>ae,multipleOf:()=>$e,nan:()=>Dm,nanoid:()=>Zp,nativeEnum:()=>Im,negative:()=>Mn,never:()=>ki,nonnegative:()=>Gn,nonoptional:()=>qu,nonpositive:()=>Bn,normalize:()=>st,null:()=>wu,nullable:()=>gr,nullish:()=>Em,number:()=>yu,object:()=>vm,optional:()=>fr,overwrite:()=>ne,parse:()=>au,parseAsync:()=>su,partialRecord:()=>km,pipe:()=>ni,positive:()=>Fn,prefault:()=>Ku,preprocess:()=>Gm,prettifyError:()=>wo,promise:()=>Nm,property:()=>Wn,readonly:()=>rl,record:()=>ju,refine:()=>cl,regex:()=>et,regexes:()=>X,registry:()=>xn,safeDecode:()=>gu,safeDecodeAsync:()=>vu,safeEncode:()=>fu,safeEncodeAsync:()=>hu,safeParse:()=>cu,safeParseAsync:()=>uu,set:()=>Sm,setErrorMap:()=>Av,size:()=>Ne,slugify:()=>dt,startsWith:()=>it,strictObject:()=>bm,string:()=>pr,stringFormat:()=>em,stringbool:()=>Mm,success:()=>Tm,superRefine:()=>ul,symbol:()=>dm,templateLiteral:()=>Rm,toJSONSchema:()=>qn,toLowerCase:()=>ut,toUpperCase:()=>lt,transform:()=>Si,treeifyError:()=>_o,trim:()=>ct,tuple:()=>Nu,uint32:()=>sm,uint64:()=>lm,ulid:()=>Mp,undefined:()=>pm,union:()=>_i,unknown:()=>Ce,uppercase:()=>rt,url:()=>jp,util:()=>b,uuid:()=>Up,uuidv4:()=>Op,uuidv6:()=>Rp,uuidv7:()=>Np,void:()=>fm,xid:()=>Bp,xor:()=>xm});var de={};te(de,{$ZodAny:()=>Qa,$ZodArray:()=>is,$ZodAsyncError:()=>re,$ZodBase64:()=>Ba,$ZodBase64URL:()=>Ga,$ZodBigInt:()=>pn,$ZodBigIntFormat:()=>qa,$ZodBoolean:()=>ir,$ZodCIDRv4:()=>La,$ZodCIDRv6:()=>Fa,$ZodCUID:()=>za,$ZodCUID2:()=>Ea,$ZodCatch:()=>ks,$ZodCheck:()=>D,$ZodCheckBigIntFormat:()=>ia,$ZodCheckEndsWith:()=>ha,$ZodCheckGreaterThan:()=>an,$ZodCheckIncludes:()=>fa,$ZodCheckLengthEquals:()=>la,$ZodCheckLessThan:()=>on,$ZodCheckLowerCase:()=>pa,$ZodCheckMaxLength:()=>ca,$ZodCheckMaxSize:()=>oa,$ZodCheckMimeType:()=>ba,$ZodCheckMinLength:()=>ua,$ZodCheckMinSize:()=>aa,$ZodCheckMultipleOf:()=>ra,$ZodCheckNumberFormat:()=>na,$ZodCheckOverwrite:()=>ya,$ZodCheckProperty:()=>va,$ZodCheckRegex:()=>da,$ZodCheckSizeEquals:()=>sa,$ZodCheckStartsWith:()=>ga,$ZodCheckStringFormat:()=>Ye,$ZodCheckUpperCase:()=>ma,$ZodCodec:()=>ar,$ZodCustom:()=>Ts,$ZodCustomStringFormat:()=>Va,$ZodDate:()=>ns,$ZodDefault:()=>bs,$ZodDiscriminatedUnion:()=>ss,$ZodE164:()=>Wa,$ZodEmail:()=>wa,$ZodEmoji:()=>Ia,$ZodEncodeError:()=>he,$ZodEnum:()=>ps,$ZodError:()=>Yt,$ZodExactOptional:()=>hs,$ZodFile:()=>fs,$ZodFunction:()=>Ps,$ZodGUID:()=>ka,$ZodIPv4:()=>Aa,$ZodIPv6:()=>Ca,$ZodISODate:()=>Ra,$ZodISODateTime:()=>Oa,$ZodISODuration:()=>ja,$ZodISOTime:()=>Na,$ZodIntersection:()=>cs,$ZodJWT:()=>Ja,$ZodKSUID:()=>Ua,$ZodLazy:()=>Es,$ZodLiteral:()=>ms,$ZodMAC:()=>Za,$ZodMap:()=>ls,$ZodNaN:()=>_s,$ZodNanoID:()=>Pa,$ZodNever:()=>ts,$ZodNonOptional:()=>xs,$ZodNull:()=>Ya,$ZodNullable:()=>vs,$ZodNumber:()=>dn,$ZodNumberFormat:()=>Ka,$ZodObject:()=>Sd,$ZodObjectJIT:()=>os,$ZodOptional:()=>fn,$ZodPipe:()=>gn,$ZodPrefault:()=>ys,$ZodPreprocess:()=>ws,$ZodPromise:()=>zs,$ZodReadonly:()=>Ss,$ZodRealError:()=>q,$ZodRecord:()=>us,$ZodRegistry:()=>yn,$ZodSet:()=>ds,$ZodString:()=>Re,$ZodStringFormat:()=>E,$ZodSuccess:()=>$s,$ZodSymbol:()=>Ha,$ZodTemplateLiteral:()=>Is,$ZodTransform:()=>gs,$ZodTuple:()=>mn,$ZodType:()=>_,$ZodULID:()=>Ta,$ZodURL:()=>Sa,$ZodUUID:()=>_a,$ZodUndefined:()=>Xa,$ZodUnion:()=>or,$ZodUnknown:()=>es,$ZodVoid:()=>rs,$ZodXID:()=>Da,$ZodXor:()=>as,$brand:()=>lo,$constructor:()=>d,$input:()=>Us,$output:()=>Ds,Doc:()=>nr,JSONSchema:()=>Pp,JSONSchemaGenerator:()=>Hn,NEVER:()=>uo,TimePrecision:()=>js,_any:()=>nc,_array:()=>lc,_base64:()=>An,_base64url:()=>Cn,_bigint:()=>Hs,_boolean:()=>Ks,_catch:()=>Iv,_check:()=>Ip,_cidrv4:()=>Nn,_cidrv6:()=>jn,_coercedBigint:()=>Xs,_coercedBoolean:()=>qs,_coercedDate:()=>cc,_coercedNumber:()=>Ms,_coercedString:()=>Rs,_cuid:()=>zn,_cuid2:()=>En,_custom:()=>pc,_date:()=>sc,_decode:()=>qr,_decodeAsync:()=>Xr,_default:()=>_v,_discriminatedUnion:()=>dv,_e164:()=>Zn,_email:()=>$n,_emoji:()=>In,_encode:()=>Kr,_encodeAsync:()=>Hr,_endsWith:()=>ot,_enum:()=>vv,_file:()=>dc,_float32:()=>Gs,_float64:()=>Ws,_gt:()=>oe,_gte:()=>G,_guid:()=>ur,_includes:()=>nt,_int:()=>Bs,_int32:()=>Js,_int64:()=>Ys,_intersection:()=>pv,_ipv4:()=>On,_ipv6:()=>Rn,_isoDate:()=>Cs,_isoDateTime:()=>As,_isoDuration:()=>Ls,_isoTime:()=>Zs,_jwt:()=>Ln,_ksuid:()=>Un,_lazy:()=>Tv,_length:()=>Ae,_literal:()=>yv,_lowercase:()=>tt,_lt:()=>ie,_lte:()=>Y,_mac:()=>Ns,_map:()=>gv,_max:()=>Y,_maxLength:()=>je,_maxSize:()=>ke,_mime:()=>at,_min:()=>G,_minLength:()=>le,_minSize:()=>ae,_multipleOf:()=>$e,_nan:()=>uc,_nanoid:()=>Pn,_nativeEnum:()=>bv,_negative:()=>Mn,_never:()=>oc,_nonnegative:()=>Gn,_nonoptional:()=>wv,_nonpositive:()=>Bn,_normalize:()=>st,_null:()=>rc,_nullable:()=>kv,_number:()=>Fs,_optional:()=>$v,_overwrite:()=>ne,_parse:()=>Ke,_parseAsync:()=>qe,_pipe:()=>Pv,_positive:()=>Fn,_promise:()=>Dv,_property:()=>Wn,_readonly:()=>zv,_record:()=>fv,_refine:()=>mc,_regex:()=>et,_safeDecode:()=>Qr,_safeDecodeAsync:()=>tn,_safeEncode:()=>Yr,_safeEncodeAsync:()=>en,_safeParse:()=>He,_safeParseAsync:()=>Xe,_set:()=>hv,_size:()=>Ne,_slugify:()=>dt,_startsWith:()=>it,_string:()=>Os,_stringFormat:()=>pt,_stringbool:()=>vc,_success:()=>Sv,_superRefine:()=>fc,_symbol:()=>ec,_templateLiteral:()=>Ev,_toLowerCase:()=>ut,_toUpperCase:()=>lt,_transform:()=>xv,_trim:()=>ct,_tuple:()=>mv,_uint32:()=>Vs,_uint64:()=>Qs,_ulid:()=>Tn,_undefined:()=>tc,_union:()=>uv,_unknown:()=>ic,_uppercase:()=>rt,_url:()=>lr,_uuid:()=>kn,_uuidv4:()=>_n,_uuidv6:()=>wn,_uuidv7:()=>Sn,_void:()=>ac,_xid:()=>Dn,_xor:()=>lv,clone:()=>M,config:()=>R,createStandardJSONSchemaMethod:()=>mt,createToJSONSchemaMethod:()=>bc,decode:()=>Dg,decodeAsync:()=>Og,describe:()=>gc,encode:()=>Tg,encodeAsync:()=>Ug,extractDefs:()=>we,finalize:()=>Se,flattenError:()=>Qt,formatError:()=>er,globalConfig:()=>De,globalRegistry:()=>C,initializeContext:()=>_e,isValidBase64:()=>Ma,isValidBase64URL:()=>$d,isValidJWT:()=>kd,locales:()=>cr,meta:()=>hc,parse:()=>Jr,parseAsync:()=>Vr,prettifyError:()=>wo,process:()=>P,regexes:()=>X,registry:()=>xn,safeDecode:()=>Ng,safeDecodeAsync:()=>Ag,safeEncode:()=>Rg,safeEncodeAsync:()=>jg,safeParse:()=>So,safeParseAsync:()=>Io,toDotPath:()=>ed,toJSONSchema:()=>qn,treeifyError:()=>_o,util:()=>b,version:()=>xa});var ql,uo=Object.freeze({status:"aborted"});function d(r,e,n){function i(s,c){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(r))return;s._zod.traits.add(r),e(s,c);let u=a.prototype,l=Object.keys(u);for(let m=0;m<l.length;m++){let g=l[m];g in s||(s[g]=u[g].bind(s))}}let t=n?.Parent??Object;class o extends t{}Object.defineProperty(o,"name",{value:r});function a(s){var c;let u=n?.Parent?new o:this;i(u,s),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(a,"init",{value:i}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>n?.Parent&&s instanceof n.Parent?!0:s?._zod?.traits?.has(r)}),Object.defineProperty(a,"name",{value:r}),a}var lo=Symbol("zod_brand"),re=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},he=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(ql=globalThis).__zod_globalConfig??(ql.__zod_globalConfig={});var De=globalThis.__zod_globalConfig;function R(r){return r&&Object.assign(De,r),De}var b={};te(b,{BIGINT_FORMAT_RANGES:()=>$o,Class:()=>mo,NUMBER_FORMAT_RANGES:()=>xo,aborted:()=>xe,allowsEval:()=>ho,assert:()=>cg,assertEqual:()=>ig,assertIs:()=>ag,assertNever:()=>sg,assertNotEqual:()=>og,assignProp:()=>be,base64ToUint8Array:()=>Xl,base64urlToUint8Array:()=>Sg,cached:()=>Je,captureStackTrace:()=>Wr,cleanEnum:()=>wg,cleanRegex:()=>Kt,clone:()=>M,cloneDef:()=>lg,createTransparentProxy:()=>hg,defineLazy:()=>I,esc:()=>Gr,escapeRegex:()=>Q,explicitlyAborted:()=>ko,extend:()=>yg,finalizeIssue:()=>B,floatSafeRemainder:()=>fo,getElementAtPath:()=>dg,getEnumValues:()=>Vt,getLengthableOrigin:()=>Xt,getParsedType:()=>gg,getSizableOrigin:()=>Ht,hexToUint8Array:()=>Pg,isObject:()=>Ue,isPlainObject:()=>ye,issue:()=>Ve,joinValues:()=>p,jsonStringifyReplacer:()=>We,merge:()=>$g,mergeDefs:()=>ue,normalizeParams:()=>y,nullish:()=>ve,numKeys:()=>fg,objectClone:()=>ug,omit:()=>bg,optionalKeys:()=>yo,parsedType:()=>v,partial:()=>kg,pick:()=>vg,prefixIssues:()=>K,primitiveTypes:()=>bo,promiseAllObject:()=>pg,propertyKeyTypes:()=>qt,randomString:()=>mg,required:()=>_g,safeExtend:()=>xg,shallowClone:()=>vo,slugify:()=>go,stringifyPrimitive:()=>h,uint8ArrayToBase64:()=>Yl,uint8ArrayToBase64url:()=>Ig,uint8ArrayToHex:()=>zg,unwrapMessage:()=>Jt});function ig(r){return r}function og(r){return r}function ag(r){}function sg(r){throw new Error("Unexpected value in exhaustive check")}function cg(r){}function Vt(r){let e=Object.values(r).filter(i=>typeof i=="number");return Object.entries(r).filter(([i,t])=>e.indexOf(+i)===-1).map(([i,t])=>t)}function p(r,e="|"){return r.map(n=>h(n)).join(e)}function We(r,e){return typeof e=="bigint"?e.toString():e}function Je(r){return{get value(){{let n=r();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ve(r){return r==null}function Kt(r){let e=r.startsWith("^")?1:0,n=r.endsWith("$")?r.length-1:r.length;return r.slice(e,n)}function fo(r,e){let n=r/e,i=Math.round(n),t=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-i)<t?0:n-i}var Hl=Symbol("evaluating");function I(r,e,n){let i;Object.defineProperty(r,e,{get(){if(i!==Hl)return i===void 0&&(i=Hl,i=n()),i},set(t){Object.defineProperty(r,e,{value:t})},configurable:!0})}function ug(r){return Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r))}function be(r,e,n){Object.defineProperty(r,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ue(...r){let e={};for(let n of r){let i=Object.getOwnPropertyDescriptors(n);Object.assign(e,i)}return Object.defineProperties({},e)}function lg(r){return ue(r._zod.def)}function dg(r,e){return e?e.reduce((n,i)=>n?.[i],r):r}function pg(r){let e=Object.keys(r),n=e.map(i=>r[i]);return Promise.all(n).then(i=>{let t={};for(let o=0;o<e.length;o++)t[e[o]]=i[o];return t})}function mg(r=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<r;i++)n+=e[Math.floor(Math.random()*e.length)];return n}function Gr(r){return JSON.stringify(r)}function go(r){return r.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Wr="captureStackTrace"in Error?Error.captureStackTrace:(...r)=>{};function Ue(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}var ho=Je(()=>{if(De.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let r=Function;return new r(""),!0}catch{return!1}});function ye(r){if(Ue(r)===!1)return!1;let e=r.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(Ue(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function vo(r){return ye(r)?{...r}:Array.isArray(r)?[...r]:r instanceof Map?new Map(r):r instanceof Set?new Set(r):r}function fg(r){let e=0;for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&e++;return e}var gg=r=>{let e=typeof r;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(r)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(r)?"array":r===null?"null":r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?"promise":typeof Map<"u"&&r instanceof Map?"map":typeof Set<"u"&&r instanceof Set?"set":typeof Date<"u"&&r instanceof Date?"date":typeof File<"u"&&r instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},qt=new Set(["string","number","symbol"]),bo=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Q(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function M(r,e,n){let i=new r._zod.constr(e??r._zod.def);return(!e||n?.parent)&&(i._zod.parent=r),i}function y(r){let e=r;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function hg(r){let e;return new Proxy({},{get(n,i,t){return e??(e=r()),Reflect.get(e,i,t)},set(n,i,t,o){return e??(e=r()),Reflect.set(e,i,t,o)},has(n,i){return e??(e=r()),Reflect.has(e,i)},deleteProperty(n,i){return e??(e=r()),Reflect.deleteProperty(e,i)},ownKeys(n){return e??(e=r()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,i){return e??(e=r()),Reflect.getOwnPropertyDescriptor(e,i)},defineProperty(n,i,t){return e??(e=r()),Reflect.defineProperty(e,i,t)}})}function h(r){return typeof r=="bigint"?r.toString()+"n":typeof r=="string"?`"${r}"`:`${r}`}function yo(r){return Object.keys(r).filter(e=>r[e]._zod.optin==="optional"&&r[e]._zod.optout==="optional")}var xo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},$o={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vg(r,e){let n=r._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=ue(r._zod.def,{get shape(){let a={};for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(a[s]=n.shape[s])}return be(this,"shape",a),a},checks:[]});return M(r,o)}function bg(r,e){let n=r._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=ue(r._zod.def,{get shape(){let a={...r._zod.def.shape};for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete a[s]}return be(this,"shape",a),a},checks:[]});return M(r,o)}function yg(r,e){if(!ye(e))throw new Error("Invalid input to extend: expected a plain object");let n=r._zod.def.checks;if(n&&n.length>0){let o=r._zod.def.shape;for(let a in e)if(Object.getOwnPropertyDescriptor(o,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let t=ue(r._zod.def,{get shape(){let o={...r._zod.def.shape,...e};return be(this,"shape",o),o}});return M(r,t)}function xg(r,e){if(!ye(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=ue(r._zod.def,{get shape(){let i={...r._zod.def.shape,...e};return be(this,"shape",i),i}});return M(r,n)}function $g(r,e){if(r._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=ue(r._zod.def,{get shape(){let i={...r._zod.def.shape,...e._zod.def.shape};return be(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return M(r,n)}function kg(r,e,n){let t=e._zod.def.checks;if(t&&t.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let a=ue(e._zod.def,{get shape(){let s=e._zod.def.shape,c={...s};if(n)for(let u in n){if(!(u in s))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=r?new r({type:"optional",innerType:s[u]}):s[u])}else for(let u in s)c[u]=r?new r({type:"optional",innerType:s[u]}):s[u];return be(this,"shape",c),c},checks:[]});return M(e,a)}function _g(r,e,n){let i=ue(e._zod.def,{get shape(){let t=e._zod.def.shape,o={...t};if(n)for(let a in n){if(!(a in o))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(o[a]=new r({type:"nonoptional",innerType:t[a]}))}else for(let a in t)o[a]=new r({type:"nonoptional",innerType:t[a]});return be(this,"shape",o),o}});return M(e,i)}function xe(r,e=0){if(r.aborted===!0)return!0;for(let n=e;n<r.issues.length;n++)if(r.issues[n]?.continue!==!0)return!0;return!1}function ko(r,e=0){if(r.aborted===!0)return!0;for(let n=e;n<r.issues.length;n++)if(r.issues[n]?.continue===!1)return!0;return!1}function K(r,e){return e.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(r),n})}function Jt(r){return typeof r=="string"?r:r?.message}function B(r,e,n){let i=r.message?r.message:Jt(r.inst?._zod.def?.error?.(r))??Jt(e?.error?.(r))??Jt(n.customError?.(r))??Jt(n.localeError?.(r))??"Invalid input",{inst:t,continue:o,input:a,...s}=r;return s.path??(s.path=[]),s.message=i,e?.reportInput&&(s.input=a),s}function Ht(r){return r instanceof Set?"set":r instanceof Map?"map":r instanceof File?"file":"unknown"}function Xt(r){return Array.isArray(r)?"array":typeof r=="string"?"string":"unknown"}function v(r){let e=typeof r;switch(e){case"number":return Number.isNaN(r)?"nan":"number";case"object":{if(r===null)return"null";if(Array.isArray(r))return"array";let n=r;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function Ve(...r){let[e,n,i]=r;return typeof e=="string"?{message:e,code:"custom",input:n,inst:i}:{...e}}function wg(r){return Object.entries(r).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Xl(r){let e=atob(r),n=new Uint8Array(e.length);for(let i=0;i<e.length;i++)n[i]=e.charCodeAt(i);return n}function Yl(r){let e="";for(let n=0;n<r.length;n++)e+=String.fromCharCode(r[n]);return btoa(e)}function Sg(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return Xl(e+n)}function Ig(r){return Yl(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Pg(r){let e=r.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)n[i/2]=Number.parseInt(e.slice(i,i+2),16);return n}function zg(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}var mo=class{constructor(...e){}};var Ql=(r,e)=>{r.name="$ZodError",Object.defineProperty(r,"_zod",{value:r._zod,enumerable:!1}),Object.defineProperty(r,"issues",{value:e,enumerable:!1}),r.message=JSON.stringify(e,We,2),Object.defineProperty(r,"toString",{value:()=>r.message,enumerable:!1})},Yt=d("$ZodError",Ql),q=d("$ZodError",Ql,{Parent:Error});function Qt(r,e=n=>n.message){let n={},i=[];for(let t of r.issues)t.path.length>0?(n[t.path[0]]=n[t.path[0]]||[],n[t.path[0]].push(e(t))):i.push(e(t));return{formErrors:i,fieldErrors:n}}function er(r,e=n=>n.message){let n={_errors:[]},i=(t,o=[])=>{for(let a of t.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>i({issues:s},[...o,...a.path]));else if(a.code==="invalid_key")i({issues:a.issues},[...o,...a.path]);else if(a.code==="invalid_element")i({issues:a.issues},[...o,...a.path]);else{let s=[...o,...a.path];if(s.length===0)n._errors.push(e(a));else{let c=n,u=0;for(;u<s.length;){let l=s[u];u===s.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(e(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}}};return i(r),n}function _o(r,e=n=>n.message){let n={errors:[]},i=(t,o=[])=>{var a,s;for(let c of t.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(u=>i({issues:u},[...o,...c.path]));else if(c.code==="invalid_key")i({issues:c.issues},[...o,...c.path]);else if(c.code==="invalid_element")i({issues:c.issues},[...o,...c.path]);else{let u=[...o,...c.path];if(u.length===0){n.errors.push(e(c));continue}let l=n,m=0;for(;m<u.length;){let g=u[m],f=m===u.length-1;typeof g=="string"?(l.properties??(l.properties={}),(a=l.properties)[g]??(a[g]={errors:[]}),l=l.properties[g]):(l.items??(l.items=[]),(s=l.items)[g]??(s[g]={errors:[]}),l=l.items[g]),f&&l.errors.push(e(c)),m++}}};return i(r),n}function ed(r){let e=[],n=r.map(i=>typeof i=="object"?i.key:i);for(let i of n)typeof i=="number"?e.push(`[${i}]`):typeof i=="symbol"?e.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?e.push(`[${JSON.stringify(i)}]`):(e.length&&e.push("."),e.push(i));return e.join("")}function wo(r){let e=[],n=[...r.issues].sort((i,t)=>(i.path??[]).length-(t.path??[]).length);for(let i of n)e.push(`\u2716 ${i.message}`),i.path?.length&&e.push(` \u2192 at ${ed(i.path)}`);return e.join(`
|
|
3
3
|
`)}var Ke=r=>(e,n,i,t)=>{let o=i?{...i,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new re;if(a.issues.length){let s=new(t?.Err??r)(a.issues.map(c=>B(c,o,R())));throw Wr(s,t?.callee),s}return a.value},Jr=Ke(q),qe=r=>async(e,n,i,t)=>{let o=i?{...i,async:!0}:{async:!0},a=e._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(t?.Err??r)(a.issues.map(c=>B(c,o,R())));throw Wr(s,t?.callee),s}return a.value},Vr=qe(q),He=r=>(e,n,i)=>{let t=i?{...i,async:!1}:{async:!1},o=e._zod.run({value:n,issues:[]},t);if(o instanceof Promise)throw new re;return o.issues.length?{success:!1,error:new(r??Yt)(o.issues.map(a=>B(a,t,R())))}:{success:!0,data:o.value}},So=He(q),Xe=r=>async(e,n,i)=>{let t=i?{...i,async:!0}:{async:!0},o=e._zod.run({value:n,issues:[]},t);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new r(o.issues.map(a=>B(a,t,R())))}:{success:!0,data:o.value}},Io=Xe(q),Kr=r=>(e,n,i)=>{let t=i?{...i,direction:"backward"}:{direction:"backward"};return Ke(r)(e,n,t)},Tg=Kr(q),qr=r=>(e,n,i)=>Ke(r)(e,n,i),Dg=qr(q),Hr=r=>async(e,n,i)=>{let t=i?{...i,direction:"backward"}:{direction:"backward"};return qe(r)(e,n,t)},Ug=Hr(q),Xr=r=>async(e,n,i)=>qe(r)(e,n,i),Og=Xr(q),Yr=r=>(e,n,i)=>{let t=i?{...i,direction:"backward"}:{direction:"backward"};return He(r)(e,n,t)},Rg=Yr(q),Qr=r=>(e,n,i)=>He(r)(e,n,i),Ng=Qr(q),en=r=>async(e,n,i)=>{let t=i?{...i,direction:"backward"}:{direction:"backward"};return Xe(r)(e,n,t)},jg=en(q),tn=r=>async(e,n,i)=>Xe(r)(e,n,i),Ag=tn(q);var X={};te(X,{base64:()=>Mo,base64url:()=>rn,bigint:()=>qo,boolean:()=>Xo,browserEmail:()=>Wg,cidrv4:()=>Lo,cidrv6:()=>Fo,cuid:()=>Po,cuid2:()=>zo,date:()=>Wo,datetime:()=>Vo,domain:()=>Kg,duration:()=>Oo,e164:()=>Go,email:()=>No,emoji:()=>jo,extendedDuration:()=>Cg,guid:()=>Ro,hex:()=>qg,hostname:()=>Vg,html5Email:()=>Mg,httpProtocol:()=>Bo,idnEmail:()=>Gg,integer:()=>Ho,ipv4:()=>Ao,ipv6:()=>Co,ksuid:()=>Do,lowercase:()=>ea,mac:()=>Zo,md5_base64:()=>Xg,md5_base64url:()=>Yg,md5_hex:()=>Hg,nanoid:()=>Uo,null:()=>Yo,number:()=>nn,rfc5322Email:()=>Bg,sha1_base64:()=>eh,sha1_base64url:()=>th,sha1_hex:()=>Qg,sha256_base64:()=>nh,sha256_base64url:()=>ih,sha256_hex:()=>rh,sha384_base64:()=>ah,sha384_base64url:()=>sh,sha384_hex:()=>oh,sha512_base64:()=>uh,sha512_base64url:()=>lh,sha512_hex:()=>ch,string:()=>Ko,time:()=>Jo,ulid:()=>Eo,undefined:()=>Qo,unicodeEmail:()=>td,uppercase:()=>ta,uuid:()=>Oe,uuid4:()=>Zg,uuid6:()=>Lg,uuid7:()=>Fg,xid:()=>To});var Po=/^[cC][0-9a-z]{6,}$/,zo=/^[0-9a-z]+$/,Eo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,To=/^[0-9a-vA-V]{20}$/,Do=/^[A-Za-z0-9]{27}$/,Uo=/^[a-zA-Z0-9_-]{21}$/,Oo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cg=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ro=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Oe=r=>r?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${r}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Zg=Oe(4),Lg=Oe(6),Fg=Oe(7),No=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Mg=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Bg=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,td=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Gg=td,Wg=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Jg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jo(){return new RegExp(Jg,"u")}var Ao=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Co=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Zo=r=>{let e=Q(r??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},Lo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Fo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Mo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rn=/^[A-Za-z0-9_-]*$/,Vg=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Kg=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Bo=/^https?$/,Go=/^\+[1-9]\d{6,14}$/,rd="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Wo=new RegExp(`^${rd}$`);function nd(r){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof r.precision=="number"?r.precision===-1?`${e}`:r.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${r.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Jo(r){return new RegExp(`^${nd(r)}$`)}function Vo(r){let e=nd({precision:r.precision}),n=["Z"];r.local&&n.push(""),r.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${e}(?:${n.join("|")})`;return new RegExp(`^${rd}T(?:${i})$`)}var Ko=r=>{let e=r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},qo=/^-?\d+n?$/,Ho=/^-?\d+$/,nn=/^-?\d+(?:\.\d+)?$/,Xo=/^(?:true|false)$/i,Yo=/^null$/i;var Qo=/^undefined$/i;var ea=/^[^A-Z]*$/,ta=/^[^a-z]*$/,qg=/^[0-9a-fA-F]*$/;function tr(r,e){return new RegExp(`^[A-Za-z0-9+/]{${r}}${e}$`)}function rr(r){return new RegExp(`^[A-Za-z0-9_-]{${r}}$`)}var Hg=/^[0-9a-fA-F]{32}$/,Xg=tr(22,"=="),Yg=rr(22),Qg=/^[0-9a-fA-F]{40}$/,eh=tr(27,"="),th=rr(27),rh=/^[0-9a-fA-F]{64}$/,nh=tr(43,"="),ih=rr(43),oh=/^[0-9a-fA-F]{96}$/,ah=tr(64,""),sh=rr(64),ch=/^[0-9a-fA-F]{128}$/,uh=tr(86,"=="),lh=rr(86);var D=d("$ZodCheck",(r,e)=>{var n;r._zod??(r._zod={}),r._zod.def=e,(n=r._zod).onattach??(n.onattach=[])}),od={number:"number",bigint:"bigint",object:"date"},on=d("$ZodCheckLessThan",(r,e)=>{D.init(r,e);let n=od[typeof e.value];r._zod.onattach.push(i=>{let t=i._zod.bag,o=(e.inclusive?t.maximum:t.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?t.maximum=e.value:t.exclusiveMaximum=e.value)}),r._zod.check=i=>{(e.inclusive?i.value<=e.value:i.value<e.value)||i.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:i.value,inclusive:e.inclusive,inst:r,continue:!e.abort})}}),an=d("$ZodCheckGreaterThan",(r,e)=>{D.init(r,e);let n=od[typeof e.value];r._zod.onattach.push(i=>{let t=i._zod.bag,o=(e.inclusive?t.minimum:t.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?t.minimum=e.value:t.exclusiveMinimum=e.value)}),r._zod.check=i=>{(e.inclusive?i.value>=e.value:i.value>e.value)||i.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:i.value,inclusive:e.inclusive,inst:r,continue:!e.abort})}}),ra=d("$ZodCheckMultipleOf",(r,e)=>{D.init(r,e),r._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=e.value)}),r._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):fo(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:r,continue:!e.abort})}}),na=d("$ZodCheckNumberFormat",(r,e)=>{D.init(r,e),e.format=e.format||"float64";let n=e.format?.includes("int"),i=n?"int":"number",[t,o]=xo[e.format];r._zod.onattach.push(a=>{let s=a._zod.bag;s.format=e.format,s.minimum=t,s.maximum=o,n&&(s.pattern=Ho)}),r._zod.check=a=>{let s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:i,format:e.format,code:"invalid_type",continue:!1,input:s,inst:r});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:r,origin:i,inclusive:!0,continue:!e.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:r,origin:i,inclusive:!0,continue:!e.abort});return}}s<t&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:t,inclusive:!0,inst:r,continue:!e.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inclusive:!0,inst:r,continue:!e.abort})}}),ia=d("$ZodCheckBigIntFormat",(r,e)=>{D.init(r,e);let[n,i]=$o[e.format];r._zod.onattach.push(t=>{let o=t._zod.bag;o.format=e.format,o.minimum=n,o.maximum=i}),r._zod.check=t=>{let o=t.value;o<n&&t.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:r,continue:!e.abort}),o>i&&t.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inclusive:!0,inst:r,continue:!e.abort})}}),oa=d("$ZodCheckMaxSize",(r,e)=>{var n;D.init(r,e),(n=r._zod.def).when??(n.when=i=>{let t=i.value;return!ve(t)&&t.size!==void 0}),r._zod.onattach.push(i=>{let t=i._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<t&&(i._zod.bag.maximum=e.maximum)}),r._zod.check=i=>{let t=i.value;t.size<=e.maximum||i.issues.push({origin:Ht(t),code:"too_big",maximum:e.maximum,inclusive:!0,input:t,inst:r,continue:!e.abort})}}),aa=d("$ZodCheckMinSize",(r,e)=>{var n;D.init(r,e),(n=r._zod.def).when??(n.when=i=>{let t=i.value;return!ve(t)&&t.size!==void 0}),r._zod.onattach.push(i=>{let t=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>t&&(i._zod.bag.minimum=e.minimum)}),r._zod.check=i=>{let t=i.value;t.size>=e.minimum||i.issues.push({origin:Ht(t),code:"too_small",minimum:e.minimum,inclusive:!0,input:t,inst:r,continue:!e.abort})}}),sa=d("$ZodCheckSizeEquals",(r,e)=>{var n;D.init(r,e),(n=r._zod.def).when??(n.when=i=>{let t=i.value;return!ve(t)&&t.size!==void 0}),r._zod.onattach.push(i=>{let t=i._zod.bag;t.minimum=e.size,t.maximum=e.size,t.size=e.size}),r._zod.check=i=>{let t=i.value,o=t.size;if(o===e.size)return;let a=o>e.size;i.issues.push({origin:Ht(t),...a?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:i.value,inst:r,continue:!e.abort})}}),ca=d("$ZodCheckMaxLength",(r,e)=>{var n;D.init(r,e),(n=r._zod.def).when??(n.when=i=>{let t=i.value;return!ve(t)&&t.length!==void 0}),r._zod.onattach.push(i=>{let t=i._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<t&&(i._zod.bag.maximum=e.maximum)}),r._zod.check=i=>{let t=i.value;if(t.length<=e.maximum)return;let a=Xt(t);i.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:t,inst:r,continue:!e.abort})}}),ua=d("$ZodCheckMinLength",(r,e)=>{var n;D.init(r,e),(n=r._zod.def).when??(n.when=i=>{let t=i.value;return!ve(t)&&t.length!==void 0}),r._zod.onattach.push(i=>{let t=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>t&&(i._zod.bag.minimum=e.minimum)}),r._zod.check=i=>{let t=i.value;if(t.length>=e.minimum)return;let a=Xt(t);i.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:t,inst:r,continue:!e.abort})}}),la=d("$ZodCheckLengthEquals",(r,e)=>{var n;D.init(r,e),(n=r._zod.def).when??(n.when=i=>{let t=i.value;return!ve(t)&&t.length!==void 0}),r._zod.onattach.push(i=>{let t=i._zod.bag;t.minimum=e.length,t.maximum=e.length,t.length=e.length}),r._zod.check=i=>{let t=i.value,o=t.length;if(o===e.length)return;let a=Xt(t),s=o>e.length;i.issues.push({origin:a,...s?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:i.value,inst:r,continue:!e.abort})}}),Ye=d("$ZodCheckStringFormat",(r,e)=>{var n,i;D.init(r,e),r._zod.onattach.push(t=>{let o=t._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(n=r._zod).check??(n.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:e.format,input:t.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:r,continue:!e.abort})}):(i=r._zod).check??(i.check=()=>{})}),da=d("$ZodCheckRegex",(r,e)=>{Ye.init(r,e),r._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:r,continue:!e.abort})}}),pa=d("$ZodCheckLowerCase",(r,e)=>{e.pattern??(e.pattern=ea),Ye.init(r,e)}),ma=d("$ZodCheckUpperCase",(r,e)=>{e.pattern??(e.pattern=ta),Ye.init(r,e)}),fa=d("$ZodCheckIncludes",(r,e)=>{D.init(r,e);let n=Q(e.includes),i=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=i,r._zod.onattach.push(t=>{let o=t._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),r._zod.check=t=>{t.value.includes(e.includes,e.position)||t.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:t.value,inst:r,continue:!e.abort})}}),ga=d("$ZodCheckStartsWith",(r,e)=>{D.init(r,e);let n=new RegExp(`^${Q(e.prefix)}.*`);e.pattern??(e.pattern=n),r._zod.onattach.push(i=>{let t=i._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),r._zod.check=i=>{i.value.startsWith(e.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:i.value,inst:r,continue:!e.abort})}}),ha=d("$ZodCheckEndsWith",(r,e)=>{D.init(r,e);let n=new RegExp(`.*${Q(e.suffix)}$`);e.pattern??(e.pattern=n),r._zod.onattach.push(i=>{let t=i._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),r._zod.check=i=>{i.value.endsWith(e.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:i.value,inst:r,continue:!e.abort})}});function id(r,e,n){r.issues.length&&e.issues.push(...K(n,r.issues))}var va=d("$ZodCheckProperty",(r,e)=>{D.init(r,e),r._zod.check=n=>{let i=e.schema._zod.run({value:n.value[e.property],issues:[]},{});if(i instanceof Promise)return i.then(t=>id(t,n,e.property));id(i,n,e.property)}}),ba=d("$ZodCheckMimeType",(r,e)=>{D.init(r,e);let n=new Set(e.mime);r._zod.onattach.push(i=>{i._zod.bag.mime=e.mime}),r._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:e.mime,input:i.value.type,inst:r,continue:!e.abort})}}),ya=d("$ZodCheckOverwrite",(r,e)=>{D.init(r,e),r._zod.check=n=>{n.value=e.tx(n.value)}});var nr=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let i=e.split(`
|
|
4
4
|
`).filter(a=>a),t=Math.min(...i.map(a=>a.length-a.trimStart().length)),o=i.map(a=>a.slice(t)).map(a=>" ".repeat(this.indent*2)+a);for(let a of o)this.content.push(a)}compile(){let e=Function,n=this?.args,t=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...n,t.join(`
|
|
@@ -67,7 +67,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
67
67
|
|
|
68
68
|
`);n=o.pop()??"";for(let a of o){let s=Ym(a);s&&t.enqueue(s)}},flush(i){if(n+=e.decode(),n.trim()!==""){let t=Ym(n);t&&i.enqueue(t)}}}))}function Ym(r){let e="message",n="";for(let i of r.split(`
|
|
69
69
|
`))i.startsWith("event: ")?e=i.slice(7).trim():i.startsWith("data: ")?n+=i.slice(6):i.startsWith("data:")&&(n+=i.slice(5));if(n==="")return null;try{return{event:e,data:JSON.parse(n)}}catch{return{event:e,data:n}}}function fl(r,e){let n=new TextDecoder,i="";return r.pipeThrough(new TransformStream({transform(t,o){i+=n.decode(t,{stream:!0});let a=i.split(`
|
|
70
|
-
`);i=a.pop()??"";for(let s of a){let c=s.trim();c!==""&&o.enqueue(e.parse(JSON.parse(c)))}},flush(t){i+=n.decode();let o=i.trim();o!==""&&t.enqueue(e.parse(JSON.parse(o)))}}))}var Ei=class{constructor(e){this.client=e}async list(e={}){let n=e.page===void 0?"":`?${new URLSearchParams({page:String(e.page)}).toString()}`;return this.client.get(`/servers${n}`)}async create(e){let n=await this.client.post("/servers",e);return new Ti(n.data,this.client)}async get(e){let n=await this.client.get(`/servers/${e}`);return new Ti(n.data,this.client)}},Ti=class{constructor(e,n){this.data=e;this.client=n}refresh(){return this.client.servers.get(this.data.id)}async delete(){await this.client.delete(`/servers/${this.data.id}`)}async waitReady(e){let n=e?.timeout??3e5,i=e?.interval??3e3,t=Date.now()+n;for(;Date.now()<t;){let o=await this.refresh();if(o.data.status==="connected")return o;if(o.data.status==="failed")throw new Error(`Server provisioning failed: ${o.data.id}`);await new Promise(a=>setTimeout(a,i))}throw new Error(`Server did not become ready within ${n}ms`)}};function _t(r,e){return new Request(r,{...e,redirect:"manual"})}var Qm={"runtime.ready":{method:"GET",path:"/runtime"},"config.get":{method:"GET",path:"/runtime/config"},"config.update":{method:"PATCH",path:"/runtime/config"},"config.set-ports":{method:"PUT",path:"/runtime/config/ports"},"container.restart":{method:"POST",path:"/runtime/container/restart"},"container.stop":{method:"POST",path:"/runtime/container/stop"},"container.set-php":{method:"PUT",path:"/runtime/container/php"},"container.opened-ports":{method:"GET",path:"/runtime/container/ports"},"container.stats":{method:"GET",path:"/runtime/container/stats"},"terminal.list":{method:"GET",path:"/runtime/terminals"},"shell.exec":{method:"POST",path:"/runtime/executions"},"fs.readFile":{method:"GET",path:"/runtime/files/content"},"fs.writeFile":{method:"PUT",path:"/runtime/files/content"},"fs.createDirectory":{method:"PUT",path:"/runtime/directories"},"fs.readDirectory":{method:"POST",path:"/runtime/directories/read"},"fs.stat":{method:"POST",path:"/runtime/files/stat"},"fs.rename":{method:"POST",path:"/runtime/files/rename"},"fs.copy":{method:"POST",path:"/runtime/files/copy"},"fs.delete":{method:"DELETE",path:"/runtime/files"},"fs.tail":{method:"POST",path:"/runtime/files/tail"},"fs.find":{method:"POST",path:"/runtime/files/find"},"fs.textSearch":{method:"POST",path:"/runtime/files/search"},"fs.tree":{method:"POST",path:"/runtime/files/tree"},"service.list":{method:"GET",path:"/runtime/services"},"service.run":{method:"POST",path:"/runtime/services/run"},"service.stop":{method:"POST",path:"/runtime/services/stop"},"service.logs":{method:"POST",path:"/runtime/services/logs"},"composer.invoke":{method:"POST",path:"/runtime/composer/executions"},"composer.packages":{method:"GET",path:"/runtime/composer/packages"},"git.checkpoint":{method:"POST",path:"/runtime/git/checkpoints"},"git.checkout":{method:"POST",path:"/runtime/git/checkouts"},"git.log":{method:"POST",path:"/runtime/git/log"},"git.sync":{method:"POST",path:"/runtime/git/sync"},"git.diff":{method:"POST",path:"/runtime/git/diff"},"git.merge":{method:"POST",path:"/runtime/git/merge"},"git.conflicts":{method:"GET",path:"/runtime/git/conflicts"},"git.resolve":{method:"POST",path:"/runtime/git/conflicts/resolve"},"git.restore":{method:"POST",path:"/runtime/git/restore"},"git.status":{method:"GET",path:"/runtime/git/status"},"git.review":{method:"GET",path:"/runtime/git/review"},"git.stage":{method:"POST",path:"/runtime/git/stage"},"git.unstage":{method:"POST",path:"/runtime/git/unstage"},"git.revert":{method:"POST",path:"/runtime/git/revert"}},Oi=class{constructor(e,n,i){this.fetch=n;this.refresh=i;this.refreshPromise=null;this.notebookId=e.id,this.configure(e.runtimeUrl)}configure(e){let n=new URL(e),i=n.searchParams.get("ticket")??"";if(i==="")throw new J("The notebook connection does not contain a runtime ticket.");this.ticket=i,n.protocol==="wss:"?n.protocol="https:":n.protocol==="ws:"&&(n.protocol="http:"),n.pathname=`/api/v1/notebooks/${encodeURIComponent(this.notebookId)}`,n.searchParams.delete("ticket"),n.hash="",this.actionUrl=n}ready(){return this.invokeRaw("runtime.ready",{},{})}supports(e){return e in Qm}invoke(e,n={},i={}){return this.invokeRaw(e,n??{},i)}send(){throw new J("Fire-and-forget actions require the realtime transport.")}async invokeRaw(e,n,i){let t=gb(i);try{for(let o=0;o<2;o+=1){let a=await pb(this.fetch,this.request(e,n,t.signal));if(a.status===401&&o===0&&this.refresh!==void 0){await this.refreshAuthorization();continue}let s=await mb(a);if(!a.ok||s.error!==void 0)throw me("runtime",s.error,a);return s.data}throw new F(`Runtime action ${e} could not be authorized.`,{source:"runtime",status:401,code:"AuthenticationRequired"})}finally{t.dispose()}}request(e,n,i){let t=Qm[e];if(t===void 0)throw new J(`Runtime action ${e} requires the realtime transport.`);let o=new URL(this.actionUrl);o.pathname+=t.path;let a={Accept:"application/json, application/octet-stream",Authorization:`Bearer ${this.ticket}`},s=fb(e,n,o,a);return _t(o,{method:t.method,headers:a,body:t.method==="GET"?void 0:s,signal:i})}async refreshAuthorization(){this.refreshPromise===null&&(this.refreshPromise=this.refresh().then(e=>this.configure(e)));try{await this.refreshPromise}finally{this.refreshPromise=null}}};async function pb(r,e){try{return await r(e)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?n:new O("Unable to reach the PHPSandbox runtime.","ConnectionFailed",n)}}async function mb(r){if(r.ok&&r.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))return{data:new Uint8Array(await r.arrayBuffer())};let e=await r.text();if(e===""){if(r.ok)throw new O("PHPSandbox runtime returned an empty response.","InvalidResponse",r);return{}}try{return JSON.parse(e)}catch(n){throw new O("PHPSandbox runtime returned an invalid JSON response.","InvalidResponse",n)}}function fb(r,e,n,i){let t=Di(e);if(r==="fs.readFile"){Ui(n,"path",t.path);let o=Di(t.lineRange);(o.lineStart!==void 0||o.lineEnd!==void 0)&&(Ui(n,"lineStart",o.lineStart),Ui(n,"lineEnd",o.lineEnd));return}if(r==="fs.writeFile"){Ui(n,"path",t.path);let o=Di(t.options);hl(n,"overwrite",o.overwrite),hl(n,"create",o.create),hl(n,"unlock",o.unlock);let a=Di(o.atomic);if(typeof a.postfix=="string"&&a.postfix!==""&&n.searchParams.set("atomicPostfix",a.postfix),!ArrayBuffer.isView(t.contents))throw new TypeError("Runtime file contents must be binary data.");return i["Content-Type"]="application/octet-stream",Uint8Array.from(new Uint8Array(t.contents.buffer,t.contents.byteOffset,t.contents.byteLength)).buffer}return i["Content-Type"]="application/json",JSON.stringify(e)}function Di(r){return r!==null&&typeof r=="object"?r:{}}function Ui(r,e,n){if(typeof n!="string"&&typeof n!="number"||String(n)==="")throw new TypeError(`Runtime file ${e} is required.`);r.searchParams.set(e,String(n))}function hl(r,e,n){r.searchParams.set(e,n===!0?"true":"false")}function gb(r){if(r.timeout===void 0&&r.abortSignal===void 0)return{signal:new AbortController().signal,dispose:()=>{}};let e=new AbortController,n=()=>e.abort(r.abortSignal?.reason);r.abortSignal?.addEventListener("abort",n,{once:!0}),r.abortSignal?.aborted&&n();let i=r.timeout===void 0?void 0:setTimeout(()=>e.abort(),r.timeout);return{signal:e.signal,dispose:()=>{r.abortSignal?.removeEventListener("abort",n),i!==void 0&&clearTimeout(i)}}}var Ri=class{constructor(e,n){this.client=e;this.notebookId=n}async configure(e){return(await this.client.put(this.path("/configuration"),e)).data}async configuration(){return(await this.client.get(this.path("/configuration"))).data}async submit(e){return(await this.client.post(this.path(),e)).data}async list(e={}){let n=new URLSearchParams;for(let[i,t]of Object.entries(e))t!==void 0&&n.set(i,String(t));return this.client.get(`${this.path()}${n.size===0?"":`?${n.toString()}`}`)}async get(e){return(await this.client.get(this.path(`/${encodeURIComponent(e)}`))).data}async update(e,n){return(await this.client.patch(this.path(`/${encodeURIComponent(e)}`),n)).data}path(e=""){return`/notebook/${this.notebookId}/feedback${e}`}};var Ni=class{constructor(e){this.client=e}async link(e){let n=await this.client.post("/integrations",e);return new Le(n.data,this.client)}async list(){return(await this.client.get("/integrations")).data.map(n=>new Le(n,this.client))}async get(e){let n=await this.client.get(`/integrations/${encodeURIComponent(ji(e))}`);return new Le(n.data,this.client)}},Le=class r{constructor(e,n){this.data=e;this.client=n}get id(){return this.data.id}get provider(){return this.data.provider}get label(){return this.data.label}async update(e){let n=await this.client.patch(`/integrations/${encodeURIComponent(this.id)}`,e);return new r(n.data,this.client)}async unlink(){await this.client.delete(`/integrations/${encodeURIComponent(this.id)}`)}};function ji(r){return typeof r=="string"?r:r.id}var Ai=class{constructor(e,n){this.notebookId=e;this.client=n}async attach(e){let n=await this.client.post(this.path(),{...e,integration:ji(e.integration)});return new Ir(n.data,this.notebookId,this.client)}async list(){return(await this.client.get(this.path())).data.map(n=>new Ir(n,this.notebookId,this.client))}async get(e){let n=await this.client.get(this.bindingPath(e));return new Ir(n.data,this.notebookId,this.client)}path(){return`/notebook/${this.notebookId}/integrations`}bindingPath(e){return`${this.path()}/${encodeURIComponent(hb(e))}`}},Ir=class r{constructor(e,n,i){this.data=e;this.notebookId=n;this.client=i}get id(){return this.data.id}get integration(){return new Le(this.data.integration,this.client)}get effects(){return this.data.effects}async update(e){let n=await this.client.patch(this.path(),{...e,integration:e.integration===void 0?void 0:ji(e.integration)});return new r(n.data,this.notebookId,this.client)}async detach(){await this.client.delete(this.path())}path(){return`/notebook/${this.notebookId}/integrations/${encodeURIComponent(this.id)}`}};function hb(r){return typeof r=="string"?r:r.id}function vb(r){return Array.isArray(r)?r:Object.entries(r).map(([e,n])=>({name:e,...typeof n=="string"?{value:n}:n}))}var yl=class{constructor(e){this.client=e}async create(e,n={}){let i=await this.client.post("/notebook",{template:e,...n});return new Pr(i.data,this.client)}async get(e){let n=await this.client.get(`/notebook/${e}`);return new Pr(n.data,this.client)}open(e){return new Pr(e,this.client)}};function bb(r){let e=new URL(r),n=e.pathname.replace(/\/+$/,"");return e.pathname=n===""||n==="/"?"/v1/":`${n}/`,e.search="",e.hash="",e.toString()}var Ci=class{constructor(e,n="https://api.phpsandbox.io/v1",i={},t="realtime"){this.fetch=globalThis.fetch;this.publications=new zi(this),this.notebook=new yl(this),this.servers=new Ei(this),this.integrations=new Ni(this),this.options={...i},this.runtimeTransportValue=t,this.baseUrl=bb(n),i.fetch&&(this.fetch=i.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get runtimeTransport(){return this.runtimeTransportValue}get(e){return this.makeRequest("GET",e)}post(e,n){return this.makeRequest("POST",e,{body:n===void 0?void 0:JSON.stringify(n)})}delete(e){return this.makeRequest("DELETE",e)}put(e,n){return this.makeRequest("PUT",e,{body:n===void 0?void 0:JSON.stringify(n)})}patch(e,n){return this.makeRequest("PATCH",e,{body:n===void 0?void 0:JSON.stringify(n)})}async stream(e){let n=await this.fetchResponse(_t(new URL(e.replace(/^\//,""),this.baseUrl),{method:"GET",headers:this.headers}));if(!n.ok)throw me("core",bl(await vl(n)),n);if(!n.body)throw new O("PHPSandbox API response body is not readable.","InvalidResponse",n);return n.body}async sse(e){let n=await this.fetchResponse(_t(e,{method:"GET",headers:{...this.headers,Accept:"text/event-stream"}}));if(!n.ok)throw me("core",bl(await vl(n)),n);if(!n.body)throw new O("PHPSandbox API SSE response body is not readable.","InvalidResponse",n);return n.body}async makeRequest(e,n,i){let t=await this.fetchResponse(_t(new URL(n.replace(/^\//,""),this.baseUrl),{method:e,...i,headers:this.headers}));if(!t.ok)throw me("core",bl(await vl(t)),t);if(t.status===204)return{data:void 0};let o=await t.text();if(o==="")throw new O("PHPSandbox API returned an empty response.","InvalidResponse",t);try{let a=JSON.parse(o);if(a===null||typeof a!="object"||Array.isArray(a)||!Object.prototype.hasOwnProperty.call(a,"data"))throw new O("PHPSandbox API returned an invalid success response.","InvalidResponse",t);return a}catch(a){throw O.is(a)?a:new O("PHPSandbox API returned an invalid JSON response.","InvalidResponse",a)}}async fetchResponse(e){try{return await this.fetch(e)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?n:new O("Unable to reach the PHPSandbox API.","ConnectionFailed",n)}}};async function vl(r){let e=await r.text();if(e!=="")try{return JSON.parse(e)}catch(n){throw new O("PHPSandbox API returned an invalid JSON response.","InvalidResponse",n)}}function bl(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r.error:void 0}var ef=class r{constructor(e){this.client=e;this.notebook=e.notebook,this.publications=e.publications,this.servers=e.servers,this.integrations=e.integrations}get runtimeTransport(){return this.client.runtimeTransport}static realtime(e,n="https://api.phpsandbox.io/v1",i={}){return new r(new Ci(e,n,i))}static rest(e,n="https://api.phpsandbox.io/v1",i={}){return new r(new Ci(e,n,i,"rest"))}},ee,zr,xl,wl=class wl{constructor(e,n){this.data=e;this.client=n;St(this,zr);this.initialized=!1;St(this,ee,null);this.disposables=[];let i=n.options.runtimeUrlProvider;if(this.emitter=Bt.createInstance(),n.runtimeTransport==="rest")this.socket=null,this.restInvoker=new Oi(e,n.options.fetch??globalThis.fetch,i===void 0?void 0:()=>i(e.id));else{this.restInvoker=null;let t=!0,o=i===void 0?e.runtimeUrl:async()=>t?(t=!1,e.runtimeUrl):i(e.id);this.socket=new Br(o,this.emitter,{debug:n.options.debug,webSocket:n.options.webSocket}),this.watchConnection(),Er(this,ee,pe(this,zr,xl).call(this))}this.files=new Tr(this,this.socket===null?null:t=>this.onDidConnect(t)),this.terminals=new Pt(this),this.auth=new zt(this),this.lsp=new Et(this),this.composer=new Dt(this,n),this.runtime=new Nt(this),this.repl=new jt(this),this.shell=new Tt(this),this.git=new Wt(this,n),this.services=new At(this),this.config=new Ct(this),this.secrets=new $l(n,this.data.id),this.integrations=new Ai(this.data.id,n),this.preview=new kl(n,this.data.id),this.mail=new _l(n,this.data.id),this.feedback=new Ri(n,this.data.id)}get runtimeTransport(){return this.client.runtimeTransport}async ready(){if(this.restInvoker!==null)return this.restInitialization();let e=this.realtimeSocket(),n=e.getTerminalError();if(n)throw n;return(async()=>(e.isConnected||await e.connect(),Ie(this,ee)))()}async fork(e={}){let n=await this.client.post(`/notebook/${this.data.id}/fork`,e);return new wl(n.data,this.client)}async publication(){try{let e=await this.client.get(`/notebook/${this.data.id}/publication`);return new kt(e.data,this.client,this.data.id)}catch(e){if(F.is(e)&&e.status===404)return null;throw e}}async publish(e){let n=await this.client.post(`/notebook/${this.data.id}/publication`,e),i=new Sr(new kt(n.data,this.client,this.data.id),this.client);return i.start(),i}run(e,n=[],i){return Array.isArray(n)?this.shell.run(e,n,i):this.shell.run(e,n)}exec(e,n=[],i){return Array.isArray(n)?this.run(e,n,i).wait():this.run(e,n).wait()}async destroy(){await this.client.delete(`/notebook/${this.data.id}`),this.socket?.terminate(new F("Notebook has been deleted.",{source:"runtime",status:503,code:"NotebookUnavailable",details:{id:this.data.id}}))}restart(){return this.invoke("container.restart")}stop(){return this.invoke("container.stop")}invoke(e,n={},i={}){return this.restInvoker!==null?(this.restInvoker.supports(String(e))&&this.restInitialization(),this.restInvoker.invoke(e,n||{},i)):this.realtimeSocket().invoke(e,n||{},i)}send(e,n={}){return this.restInvoker!==null?this.restInvoker.send():this.realtimeSocket().send(e,n||{})}listen(e,n){let i=this.emitter.listen(e,n);return this.disposables.push(i),i}dispose(){this.disposables.forEach(e=>e.dispose()),this.socket!==null&&!this.socket.isClosed&&this.socket.disconnect()}connected(){return this.waitForSocketConnection({rejectOnClose:!0})}waitForSocketConnection(e){let n=this.realtimeSocket(),i=n.getTerminalError();return i?Promise.reject(i):n.isConnected?Promise.resolve(this):new Promise((t,o)=>{let a=[],s=!1,c=()=>{for(let l of a)l.dispose();a.length=0},u=l=>{s||(s=!0,c(),l())};try{a.push(n.onDidConnect(()=>u(()=>t(this)))),e.rejectOnClose&&a.push(n.onDidClose(()=>u(()=>o(new Error("Connection closed"))))),a.push(n.onDidBootError(l=>u(()=>o(l))))}catch(l){u(()=>o(l))}})}watchConnection(){let e=this.realtimeSocket();e.onDidConnect(()=>{e.emit("okra.connected")}),e.onDidClose(()=>{e.emit("okra.disconnected"),this.initialized=!1}),e.onDidBootError(n=>{e.emit("okra.boot_error",n),e.emit("okra.disconnected"),this.initialized=!1})}onDidConnect(e){let n=this.realtimeSocket();n.removeListener("okra.connected",e);let i=n.listen("okra.connected",e);return this.disposables.push(i),i}onDidDisconnect(e){let n=this.realtimeSocket().listen("okra.disconnected",e);return this.disposables.push(n),n}onDidBootError(e){let n=this.realtimeSocket().listen("okra.boot_error",e);return this.disposables.push(n),n}restInitialization(){if(this.restInvoker===null)throw new J("This operation requires the REST transport.");return Ie(this,ee)===null&&(Er(this,ee,this.restInvoker.ready().then(e=>(this.initialized=e,this.emitter.emit("notebook.initialized",e),e))),Ie(this,ee).catch(()=>{})),Ie(this,ee)}onDidInitialize(e){return this.listen("notebook.initialized",e)}async reconnect(){let e=this.realtimeSocket(),n=this.waitForSocketConnection({rejectOnClose:!1});return e.reconnect(),this.initialized=!1,await n,pe(this,zr,xl).call(this),this.ready().then(()=>this)}realtimeSocket(){if(this.socket===null)throw new J("This operation requires the realtime transport.");return this.socket}};ee=new WeakMap,zr=new WeakSet,xl=function(){return Er(this,ee,new Promise((e,n)=>{let i=this.onDidInitialize(o=>{if(t.dispose(),i.dispose(),this.initialized=o,o.type==="error"){n(new F(o.message,{source:"runtime",status:503,code:"NotebookInitializationFailed",details:o.data}));return}e(o)}),t=this.onDidBootError(o=>{i.dispose(),t.dispose(),n(o)})})),Ie(this,ee).catch(()=>{}),Ie(this,ee)};var Pr=wl,$l=class{constructor(e,n){this.client=e;this.notebookId=n}async list(e){let n=new URLSearchParams;e?.environment&&n.set("environment",e.environment);let i=n.toString();return(await this.client.get(`/notebook/${this.notebookId}/secrets${i?`?${i}`:""}`)).data}async set(e,n){let i=typeof n=="string"?{name:e,value:n}:{name:e,...n};return(await this.client.put(`/notebook/${this.notebookId}/secrets`,i)).data}async setMany(e){return(await this.client.put(`/notebook/${this.notebookId}/secrets`,{secrets:vb(e)})).data}async delete(e,n){let i=new URLSearchParams;n?.environment&&i.set("environment",n.environment);let t=i.toString();await this.client.delete(`/notebook/${this.notebookId}/secrets/${encodeURIComponent(e)}${t?`?${t}`:""}`)}},kl=class{constructor(e,n){this.client=e;this.notebookId=n}async get(e){let n=e===void 0?"":`?${new URLSearchParams({url:e}).toString()}`;return(await this.client.get(`/notebook/${this.notebookId}/preview${n}`)).data}async setPassword(e){return(await this.client.put(`/notebook/${this.notebookId}/preview`,e)).data}async disable(){await this.client.delete(`/notebook/${this.notebookId}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${this.notebookId}/preview/session`,e)).data}async createHandoff(e){return(await this.client.post(`/notebook/${this.notebookId}/preview/handoff`,e)).data}},_l=class{constructor(e,n){this.client=e;this.notebookId=n}async status(){return(await this.client.get(`/notebook/${this.notebookId}/mail`)).data}async enable(){return(await this.client.put(`/notebook/${this.notebookId}/mail`)).data}async disable(){await this.client.delete(`/notebook/${this.notebookId}/mail`)}async list(e={}){return this.client.get(`/notebook/${this.notebookId}/mails${yb(e)}`)}async get(e){return(await this.client.get(`/notebook/${this.notebookId}/mails/${encodeURIComponent(e)}`)).data}async delete(e){await this.client.delete(`/notebook/${this.notebookId}/mails/${encodeURIComponent(e)}`)}};function yb(r){let e=new URLSearchParams;for(let[i,t]of Object.entries(r))(typeof t=="string"||typeof t=="number"||typeof t=="boolean")&&e.set(i,String(t));let n=e.toString();return n===""?"":`?${n}`}export{Dl as FileChangeFilter,Ul as FileChangeType,Tl as FileType,Ur as LspConnection,Pr as NotebookInstance,ef as PHPSandbox,J as PHPSandboxError,F as RemoteError,O as TransportError,Rl as notebookBuiltinServices,ff as notebookKnownServices};
|
|
70
|
+
`);i=a.pop()??"";for(let s of a){let c=s.trim();c!==""&&o.enqueue(e.parse(JSON.parse(c)))}},flush(t){i+=n.decode();let o=i.trim();o!==""&&t.enqueue(e.parse(JSON.parse(o)))}}))}var Ei=class{constructor(e){this.client=e}async list(e={}){let n=e.page===void 0?"":`?${new URLSearchParams({page:String(e.page)}).toString()}`;return this.client.get(`/servers${n}`)}async create(e){let n=await this.client.post("/servers",e);return new Ti(n.data,this.client)}async get(e){let n=await this.client.get(`/servers/${e}`);return new Ti(n.data,this.client)}},Ti=class{constructor(e,n){this.data=e;this.client=n}refresh(){return this.client.servers.get(this.data.id)}async delete(){await this.client.delete(`/servers/${this.data.id}`)}async waitReady(e){let n=e?.timeout??3e5,i=e?.interval??3e3,t=Date.now()+n;for(;Date.now()<t;){let o=await this.refresh();if(o.data.status==="connected")return o;if(o.data.status==="failed")throw new Error(`Server provisioning failed: ${o.data.id}`);await new Promise(a=>setTimeout(a,i))}throw new Error(`Server did not become ready within ${n}ms`)}};function _t(r,e){return new Request(r,{...e,redirect:"manual"})}var Qm={"runtime.ready":{method:"GET",path:"/runtime"},"config.get":{method:"GET",path:"/runtime/config"},"config.update":{method:"PATCH",path:"/runtime/config"},"config.set-ports":{method:"PUT",path:"/runtime/config/ports"},"container.restart":{method:"POST",path:"/runtime/container/restart"},"container.stop":{method:"POST",path:"/runtime/container/stop"},"container.set-php":{method:"PUT",path:"/runtime/container/php"},"container.opened-ports":{method:"GET",path:"/runtime/container/ports"},"container.resolve-port":{method:"POST",path:"/runtime/container/ports/resolve"},"container.stats":{method:"GET",path:"/runtime/container/stats"},"terminal.list":{method:"GET",path:"/runtime/terminals"},"shell.exec":{method:"POST",path:"/runtime/executions"},"fs.readFile":{method:"GET",path:"/runtime/files/content"},"fs.writeFile":{method:"PUT",path:"/runtime/files/content"},"fs.createDirectory":{method:"PUT",path:"/runtime/directories"},"fs.readDirectory":{method:"POST",path:"/runtime/directories/read"},"fs.stat":{method:"POST",path:"/runtime/files/stat"},"fs.rename":{method:"POST",path:"/runtime/files/rename"},"fs.copy":{method:"POST",path:"/runtime/files/copy"},"fs.delete":{method:"DELETE",path:"/runtime/files"},"fs.tail":{method:"POST",path:"/runtime/files/tail"},"fs.find":{method:"POST",path:"/runtime/files/find"},"fs.textSearch":{method:"POST",path:"/runtime/files/search"},"fs.tree":{method:"POST",path:"/runtime/files/tree"},"service.list":{method:"GET",path:"/runtime/services"},"service.run":{method:"POST",path:"/runtime/services/run"},"service.stop":{method:"POST",path:"/runtime/services/stop"},"service.logs":{method:"POST",path:"/runtime/services/logs"},"composer.invoke":{method:"POST",path:"/runtime/composer/executions"},"composer.packages":{method:"GET",path:"/runtime/composer/packages"},"git.checkpoint":{method:"POST",path:"/runtime/git/checkpoints"},"git.checkout":{method:"POST",path:"/runtime/git/checkouts"},"git.log":{method:"POST",path:"/runtime/git/log"},"git.sync":{method:"POST",path:"/runtime/git/sync"},"git.diff":{method:"POST",path:"/runtime/git/diff"},"git.merge":{method:"POST",path:"/runtime/git/merge"},"git.conflicts":{method:"GET",path:"/runtime/git/conflicts"},"git.resolve":{method:"POST",path:"/runtime/git/conflicts/resolve"},"git.restore":{method:"POST",path:"/runtime/git/restore"},"git.status":{method:"GET",path:"/runtime/git/status"},"git.review":{method:"GET",path:"/runtime/git/review"},"git.stage":{method:"POST",path:"/runtime/git/stage"},"git.unstage":{method:"POST",path:"/runtime/git/unstage"},"git.revert":{method:"POST",path:"/runtime/git/revert"}},Oi=class{constructor(e,n,i){this.fetch=n;this.refresh=i;this.refreshPromise=null;this.notebookId=e.id,this.configure(e.runtimeUrl)}configure(e){let n=new URL(e),i=n.searchParams.get("ticket")??"";if(i==="")throw new J("The notebook connection does not contain a runtime ticket.");this.ticket=i,n.protocol==="wss:"?n.protocol="https:":n.protocol==="ws:"&&(n.protocol="http:"),n.pathname=`/api/v1/notebooks/${encodeURIComponent(this.notebookId)}`,n.searchParams.delete("ticket"),n.hash="",this.actionUrl=n}ready(){return this.invokeRaw("runtime.ready",{},{})}supports(e){return e in Qm}invoke(e,n={},i={}){return this.invokeRaw(e,n??{},i)}send(){throw new J("Fire-and-forget actions require the realtime transport.")}async invokeRaw(e,n,i){let t=gb(i);try{for(let o=0;o<2;o+=1){let a=await pb(this.fetch,this.request(e,n,t.signal));if(a.status===401&&o===0&&this.refresh!==void 0){await this.refreshAuthorization();continue}let s=await mb(a);if(!a.ok||s.error!==void 0)throw me("runtime",s.error,a);return s.data}throw new F(`Runtime action ${e} could not be authorized.`,{source:"runtime",status:401,code:"AuthenticationRequired"})}finally{t.dispose()}}request(e,n,i){let t=Qm[e];if(t===void 0)throw new J(`Runtime action ${e} requires the realtime transport.`);let o=new URL(this.actionUrl);o.pathname+=t.path;let a={Accept:"application/json, application/octet-stream",Authorization:`Bearer ${this.ticket}`},s=fb(e,n,o,a);return _t(o,{method:t.method,headers:a,body:t.method==="GET"?void 0:s,signal:i})}async refreshAuthorization(){this.refreshPromise===null&&(this.refreshPromise=this.refresh().then(e=>this.configure(e)));try{await this.refreshPromise}finally{this.refreshPromise=null}}};async function pb(r,e){try{return await r(e)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?n:new O("Unable to reach the PHPSandbox runtime.","ConnectionFailed",n)}}async function mb(r){if(r.ok&&r.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))return{data:new Uint8Array(await r.arrayBuffer())};let e=await r.text();if(e===""){if(r.ok)throw new O("PHPSandbox runtime returned an empty response.","InvalidResponse",r);return{}}try{return JSON.parse(e)}catch(n){throw new O("PHPSandbox runtime returned an invalid JSON response.","InvalidResponse",n)}}function fb(r,e,n,i){let t=Di(e);if(r==="fs.readFile"){Ui(n,"path",t.path);let o=Di(t.lineRange);(o.lineStart!==void 0||o.lineEnd!==void 0)&&(Ui(n,"lineStart",o.lineStart),Ui(n,"lineEnd",o.lineEnd));return}if(r==="fs.writeFile"){Ui(n,"path",t.path);let o=Di(t.options);hl(n,"overwrite",o.overwrite),hl(n,"create",o.create),hl(n,"unlock",o.unlock);let a=Di(o.atomic);if(typeof a.postfix=="string"&&a.postfix!==""&&n.searchParams.set("atomicPostfix",a.postfix),!ArrayBuffer.isView(t.contents))throw new TypeError("Runtime file contents must be binary data.");return i["Content-Type"]="application/octet-stream",Uint8Array.from(new Uint8Array(t.contents.buffer,t.contents.byteOffset,t.contents.byteLength)).buffer}return i["Content-Type"]="application/json",JSON.stringify(e)}function Di(r){return r!==null&&typeof r=="object"?r:{}}function Ui(r,e,n){if(typeof n!="string"&&typeof n!="number"||String(n)==="")throw new TypeError(`Runtime file ${e} is required.`);r.searchParams.set(e,String(n))}function hl(r,e,n){r.searchParams.set(e,n===!0?"true":"false")}function gb(r){if(r.timeout===void 0&&r.abortSignal===void 0)return{signal:new AbortController().signal,dispose:()=>{}};let e=new AbortController,n=()=>e.abort(r.abortSignal?.reason);r.abortSignal?.addEventListener("abort",n,{once:!0}),r.abortSignal?.aborted&&n();let i=r.timeout===void 0?void 0:setTimeout(()=>e.abort(),r.timeout);return{signal:e.signal,dispose:()=>{r.abortSignal?.removeEventListener("abort",n),i!==void 0&&clearTimeout(i)}}}var Ri=class{constructor(e,n){this.client=e;this.notebookId=n}async configure(e){return(await this.client.put(this.path("/configuration"),e)).data}async configuration(){return(await this.client.get(this.path("/configuration"))).data}async submit(e){return(await this.client.post(this.path(),e)).data}async list(e={}){let n=new URLSearchParams;for(let[i,t]of Object.entries(e))t!==void 0&&n.set(i,String(t));return this.client.get(`${this.path()}${n.size===0?"":`?${n.toString()}`}`)}async get(e){return(await this.client.get(this.path(`/${encodeURIComponent(e)}`))).data}async update(e,n){return(await this.client.patch(this.path(`/${encodeURIComponent(e)}`),n)).data}path(e=""){return`/notebook/${this.notebookId}/feedback${e}`}};var Ni=class{constructor(e){this.client=e}async link(e){let n=await this.client.post("/integrations",e);return new Le(n.data,this.client)}async list(){return(await this.client.get("/integrations")).data.map(n=>new Le(n,this.client))}async get(e){let n=await this.client.get(`/integrations/${encodeURIComponent(ji(e))}`);return new Le(n.data,this.client)}},Le=class r{constructor(e,n){this.data=e;this.client=n}get id(){return this.data.id}get provider(){return this.data.provider}get label(){return this.data.label}async update(e){let n=await this.client.patch(`/integrations/${encodeURIComponent(this.id)}`,e);return new r(n.data,this.client)}async unlink(){await this.client.delete(`/integrations/${encodeURIComponent(this.id)}`)}};function ji(r){return typeof r=="string"?r:r.id}var Ai=class{constructor(e,n){this.notebookId=e;this.client=n}async attach(e){let n=await this.client.post(this.path(),{...e,integration:ji(e.integration)});return new Ir(n.data,this.notebookId,this.client)}async list(){return(await this.client.get(this.path())).data.map(n=>new Ir(n,this.notebookId,this.client))}async get(e){let n=await this.client.get(this.bindingPath(e));return new Ir(n.data,this.notebookId,this.client)}path(){return`/notebook/${this.notebookId}/integrations`}bindingPath(e){return`${this.path()}/${encodeURIComponent(hb(e))}`}},Ir=class r{constructor(e,n,i){this.data=e;this.notebookId=n;this.client=i}get id(){return this.data.id}get integration(){return new Le(this.data.integration,this.client)}get effects(){return this.data.effects}async update(e){let n=await this.client.patch(this.path(),{...e,integration:e.integration===void 0?void 0:ji(e.integration)});return new r(n.data,this.notebookId,this.client)}async detach(){await this.client.delete(this.path())}path(){return`/notebook/${this.notebookId}/integrations/${encodeURIComponent(this.id)}`}};function hb(r){return typeof r=="string"?r:r.id}function vb(r){return Array.isArray(r)?r:Object.entries(r).map(([e,n])=>({name:e,...typeof n=="string"?{value:n}:n}))}var yl=class{constructor(e){this.client=e}async create(e,n={}){let i=await this.client.post("/notebook",{template:e,...n});return new Pr(i.data,this.client)}async get(e){let n=await this.client.get(`/notebook/${e}`);return new Pr(n.data,this.client)}open(e){return new Pr(e,this.client)}};function bb(r){let e=new URL(r),n=e.pathname.replace(/\/+$/,"");return e.pathname=n===""||n==="/"?"/v1/":`${n}/`,e.search="",e.hash="",e.toString()}var Ci=class{constructor(e,n="https://api.phpsandbox.io/v1",i={},t="realtime"){this.fetch=globalThis.fetch;this.publications=new zi(this),this.notebook=new yl(this),this.servers=new Ei(this),this.integrations=new Ni(this),this.options={...i},this.runtimeTransportValue=t,this.baseUrl=bb(n),i.fetch&&(this.fetch=i.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get runtimeTransport(){return this.runtimeTransportValue}get(e){return this.makeRequest("GET",e)}post(e,n){return this.makeRequest("POST",e,{body:n===void 0?void 0:JSON.stringify(n)})}delete(e){return this.makeRequest("DELETE",e)}put(e,n){return this.makeRequest("PUT",e,{body:n===void 0?void 0:JSON.stringify(n)})}patch(e,n){return this.makeRequest("PATCH",e,{body:n===void 0?void 0:JSON.stringify(n)})}async stream(e){let n=await this.fetchResponse(_t(new URL(e.replace(/^\//,""),this.baseUrl),{method:"GET",headers:this.headers}));if(!n.ok)throw me("core",bl(await vl(n)),n);if(!n.body)throw new O("PHPSandbox API response body is not readable.","InvalidResponse",n);return n.body}async sse(e){let n=await this.fetchResponse(_t(e,{method:"GET",headers:{...this.headers,Accept:"text/event-stream"}}));if(!n.ok)throw me("core",bl(await vl(n)),n);if(!n.body)throw new O("PHPSandbox API SSE response body is not readable.","InvalidResponse",n);return n.body}async makeRequest(e,n,i){let t=await this.fetchResponse(_t(new URL(n.replace(/^\//,""),this.baseUrl),{method:e,...i,headers:this.headers}));if(!t.ok)throw me("core",bl(await vl(t)),t);if(t.status===204)return{data:void 0};let o=await t.text();if(o==="")throw new O("PHPSandbox API returned an empty response.","InvalidResponse",t);try{let a=JSON.parse(o);if(a===null||typeof a!="object"||Array.isArray(a)||!Object.prototype.hasOwnProperty.call(a,"data"))throw new O("PHPSandbox API returned an invalid success response.","InvalidResponse",t);return a}catch(a){throw O.is(a)?a:new O("PHPSandbox API returned an invalid JSON response.","InvalidResponse",a)}}async fetchResponse(e){try{return await this.fetch(e)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?n:new O("Unable to reach the PHPSandbox API.","ConnectionFailed",n)}}};async function vl(r){let e=await r.text();if(e!=="")try{return JSON.parse(e)}catch(n){throw new O("PHPSandbox API returned an invalid JSON response.","InvalidResponse",n)}}function bl(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r.error:void 0}var ef=class r{constructor(e){this.client=e;this.notebook=e.notebook,this.publications=e.publications,this.servers=e.servers,this.integrations=e.integrations}get runtimeTransport(){return this.client.runtimeTransport}static realtime(e,n="https://api.phpsandbox.io/v1",i={}){return new r(new Ci(e,n,i))}static rest(e,n="https://api.phpsandbox.io/v1",i={}){return new r(new Ci(e,n,i,"rest"))}},ee,zr,xl,wl=class wl{constructor(e,n){this.data=e;this.client=n;St(this,zr);this.initialized=!1;St(this,ee,null);this.disposables=[];let i=n.options.runtimeUrlProvider;if(this.emitter=Bt.createInstance(),n.runtimeTransport==="rest")this.socket=null,this.restInvoker=new Oi(e,n.options.fetch??globalThis.fetch,i===void 0?void 0:()=>i(e.id));else{this.restInvoker=null;let t=!0,o=i===void 0?e.runtimeUrl:async()=>t?(t=!1,e.runtimeUrl):i(e.id);this.socket=new Br(o,this.emitter,{debug:n.options.debug,webSocket:n.options.webSocket}),this.watchConnection(),Er(this,ee,pe(this,zr,xl).call(this))}this.files=new Tr(this,this.socket===null?null:t=>this.onDidConnect(t)),this.terminals=new Pt(this),this.auth=new zt(this),this.lsp=new Et(this),this.composer=new Dt(this,n),this.runtime=new Nt(this),this.repl=new jt(this),this.shell=new Tt(this),this.git=new Wt(this,n),this.services=new At(this),this.config=new Ct(this),this.secrets=new $l(n,this.data.id),this.integrations=new Ai(this.data.id,n),this.preview=new kl(n,this.data.id),this.mail=new _l(n,this.data.id),this.feedback=new Ri(n,this.data.id)}get runtimeTransport(){return this.client.runtimeTransport}async ready(){if(this.restInvoker!==null)return this.restInitialization();let e=this.realtimeSocket(),n=e.getTerminalError();if(n)throw n;return(async()=>(e.isConnected||await e.connect(),Ie(this,ee)))()}async fork(e={}){let n=await this.client.post(`/notebook/${this.data.id}/fork`,e);return new wl(n.data,this.client)}async publication(){try{let e=await this.client.get(`/notebook/${this.data.id}/publication`);return new kt(e.data,this.client,this.data.id)}catch(e){if(F.is(e)&&e.status===404)return null;throw e}}async publish(e){let n=await this.client.post(`/notebook/${this.data.id}/publication`,e),i=new Sr(new kt(n.data,this.client,this.data.id),this.client);return i.start(),i}run(e,n=[],i){return Array.isArray(n)?this.shell.run(e,n,i):this.shell.run(e,n)}exec(e,n=[],i){return Array.isArray(n)?this.run(e,n,i).wait():this.run(e,n).wait()}async destroy(){await this.client.delete(`/notebook/${this.data.id}`),this.socket?.terminate(new F("Notebook has been deleted.",{source:"runtime",status:503,code:"NotebookUnavailable",details:{id:this.data.id}}))}restart(){return this.invoke("container.restart")}stop(){return this.invoke("container.stop")}invoke(e,n={},i={}){return this.restInvoker!==null?(this.restInvoker.supports(String(e))&&this.restInitialization(),this.restInvoker.invoke(e,n||{},i)):this.realtimeSocket().invoke(e,n||{},i)}send(e,n={}){return this.restInvoker!==null?this.restInvoker.send():this.realtimeSocket().send(e,n||{})}listen(e,n){let i=this.emitter.listen(e,n);return this.disposables.push(i),i}dispose(){this.disposables.forEach(e=>e.dispose()),this.socket!==null&&!this.socket.isClosed&&this.socket.disconnect()}connected(){return this.waitForSocketConnection({rejectOnClose:!0})}waitForSocketConnection(e){let n=this.realtimeSocket(),i=n.getTerminalError();return i?Promise.reject(i):n.isConnected?Promise.resolve(this):new Promise((t,o)=>{let a=[],s=!1,c=()=>{for(let l of a)l.dispose();a.length=0},u=l=>{s||(s=!0,c(),l())};try{a.push(n.onDidConnect(()=>u(()=>t(this)))),e.rejectOnClose&&a.push(n.onDidClose(()=>u(()=>o(new Error("Connection closed"))))),a.push(n.onDidBootError(l=>u(()=>o(l))))}catch(l){u(()=>o(l))}})}watchConnection(){let e=this.realtimeSocket();e.onDidConnect(()=>{e.emit("okra.connected")}),e.onDidClose(()=>{e.emit("okra.disconnected"),this.initialized=!1}),e.onDidBootError(n=>{e.emit("okra.boot_error",n),e.emit("okra.disconnected"),this.initialized=!1})}onDidConnect(e){let n=this.realtimeSocket();n.removeListener("okra.connected",e);let i=n.listen("okra.connected",e);return this.disposables.push(i),i}onDidDisconnect(e){let n=this.realtimeSocket().listen("okra.disconnected",e);return this.disposables.push(n),n}onDidBootError(e){let n=this.realtimeSocket().listen("okra.boot_error",e);return this.disposables.push(n),n}restInitialization(){if(this.restInvoker===null)throw new J("This operation requires the REST transport.");return Ie(this,ee)===null&&(Er(this,ee,this.restInvoker.ready().then(e=>(this.initialized=e,this.emitter.emit("notebook.initialized",e),e))),Ie(this,ee).catch(()=>{})),Ie(this,ee)}onDidInitialize(e){return this.listen("notebook.initialized",e)}async reconnect(){let e=this.realtimeSocket(),n=this.waitForSocketConnection({rejectOnClose:!1});return e.reconnect(),this.initialized=!1,await n,pe(this,zr,xl).call(this),this.ready().then(()=>this)}realtimeSocket(){if(this.socket===null)throw new J("This operation requires the realtime transport.");return this.socket}};ee=new WeakMap,zr=new WeakSet,xl=function(){return Er(this,ee,new Promise((e,n)=>{let i=this.onDidInitialize(o=>{if(t.dispose(),i.dispose(),this.initialized=o,o.type==="error"){n(new F(o.message,{source:"runtime",status:503,code:"NotebookInitializationFailed",details:o.data}));return}e(o)}),t=this.onDidBootError(o=>{i.dispose(),t.dispose(),n(o)})})),Ie(this,ee).catch(()=>{}),Ie(this,ee)};var Pr=wl,$l=class{constructor(e,n){this.client=e;this.notebookId=n}async list(e){let n=new URLSearchParams;e?.environment&&n.set("environment",e.environment);let i=n.toString();return(await this.client.get(`/notebook/${this.notebookId}/secrets${i?`?${i}`:""}`)).data}async set(e,n){let i=typeof n=="string"?{name:e,value:n}:{name:e,...n};return(await this.client.put(`/notebook/${this.notebookId}/secrets`,i)).data}async setMany(e){return(await this.client.put(`/notebook/${this.notebookId}/secrets`,{secrets:vb(e)})).data}async delete(e,n){let i=new URLSearchParams;n?.environment&&i.set("environment",n.environment);let t=i.toString();await this.client.delete(`/notebook/${this.notebookId}/secrets/${encodeURIComponent(e)}${t?`?${t}`:""}`)}},kl=class{constructor(e,n){this.client=e;this.notebookId=n}async get(e){let n=e===void 0?"":`?${new URLSearchParams({url:e}).toString()}`;return(await this.client.get(`/notebook/${this.notebookId}/preview${n}`)).data}async setPassword(e){return(await this.client.put(`/notebook/${this.notebookId}/preview`,e)).data}async disable(){await this.client.delete(`/notebook/${this.notebookId}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${this.notebookId}/preview/session`,e)).data}async createHandoff(e){return(await this.client.post(`/notebook/${this.notebookId}/preview/handoff`,e)).data}},_l=class{constructor(e,n){this.client=e;this.notebookId=n}async status(){return(await this.client.get(`/notebook/${this.notebookId}/mail`)).data}async enable(){return(await this.client.put(`/notebook/${this.notebookId}/mail`)).data}async disable(){await this.client.delete(`/notebook/${this.notebookId}/mail`)}async list(e={}){return this.client.get(`/notebook/${this.notebookId}/mails${yb(e)}`)}async get(e){return(await this.client.get(`/notebook/${this.notebookId}/mails/${encodeURIComponent(e)}`)).data}async delete(e){await this.client.delete(`/notebook/${this.notebookId}/mails/${encodeURIComponent(e)}`)}};function yb(r){let e=new URLSearchParams;for(let[i,t]of Object.entries(r))(typeof t=="string"||typeof t=="number"||typeof t=="boolean")&&e.set(i,String(t));let n=e.toString();return n===""?"":`?${n}`}export{Dl as FileChangeFilter,Ul as FileChangeType,Tl as FileType,Ur as LspConnection,Pr as NotebookInstance,ef as PHPSandbox,J as PHPSandboxError,F as RemoteError,O as TransportError,Rl as notebookBuiltinServices,ff as notebookKnownServices};
|
|
71
71
|
/*! Bundled license information:
|
|
72
72
|
|
|
73
73
|
reconnecting-websocket/dist/reconnecting-websocket-mjs.js:
|