planx 19.139.0 → 19.140.3
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/layout.main.mjs +1 -1
- package/main.js +4 -4
- package/package.json +6 -6
- package/session.main.mjs +4 -4
- package/transport.main.mjs +4 -4
package/main.js
CHANGED
|
@@ -549,9 +549,9 @@ this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names`):V
|
|
|
549
549
|
`)}var wTi,OEr,REr,LEr=g(()=>{QI();gxe();wTi="",OEr="",REr=Object.freeze({})});var jEr=g(()=>{LEr()});var DS,$Er=g(()=>{DS={up(t,e){t.curRow=Math.max(0,t.curRow-e)},down(t,e){t.curRow+=e,t.ensureRow(t.curRow)},forward(t,e){t.curCol+=e},back(t,e){t.curCol=Math.max(0,t.curCol-e)},toColumn(t,e){t.curCol=Math.max(0,e)},position(t,e,r){t.curRow=Math.max(0,e),t.curCol=Math.max(0,r),t.ensureRow(t.curRow)},prevLine(t,e){t.curRow=Math.max(0,t.curRow-e),t.curCol=0},nextLine(t,e){t.curRow+=e,t.ensureRow(t.curRow),t.curCol=0},verticalAbsolute(t,e){t.curRow=Math.max(0,e),t.ensureRow(t.curRow)}}});var qEr=g(()=>{$Er()});var Em,UEr=g(()=>{Em={getViewportTop(t){return Math.max(0,t.chars.length-t._viewportRows)},absToVpRel(t,e){return e-Em.getViewportTop(t)},vpRelToAbs(t,e){return Em.getViewportTop(t)+e},curVpRel(t){return Em.absToVpRel(t,t.curRow)},isCursorAtScrollTop(t){return Em.curVpRel(t)===t._scrollTop},isCursorAtScrollBottom(t){return t._scrollBottom<9999&&Em.curVpRel(t)===t._scrollBottom},vpToAbsSticky(t,e){let r=Em.vpRelToAbs(t,e-1),n=t._stickyCupAbsRow.get(e);return n!==void 0&&n>=Em.getViewportTop(t)&&n<t.chars.length?n:(t._stickyCupAbsRow.set(e,r),r)}}});var QEr=g(()=>{UEr()});function fk(){return{rowsAnsi:null,chars:[],stys:[],cursor:null,cursorVisible:null,viewportTop:null}}var VEr=g(()=>{});var HEr=g(()=>{VEr()});var GEr,CTi,ITi,Fse,zEr=g(()=>{wbr();kbr();Lbr();Qbr();zbr();Ybr();iEr();uEr();dEr();AEr();NEr();jEr();qEr();QEr();HEr();GEr=Object.freeze({}),CTi=1e4,ITi=CTi-1,Fse=class{constructor(){this.chars=[[]],this.stys=[[]],this.curRow=0,this.curCol=0,this._st=GEr,this._rowAnsiCache=[],this._pendingEsc="",this._altMode=!1,this._savedMain=null,this._scrollTop=0,this._scrollBottom=ITi,this._cursorVisible=!0,this._tabStops=new Set,this._inSyncUpdate=!1,this._applicationCursorKeyMode=!1,this._bracketedPasteMode=!1,this._savedCursorPos=null,this._stickyCupAbsRow=new Map,this._cursorStyle=0,this._viewportRows=40,this._viewportCols=80,this._parseStyles=GEr,this._encoders=new Set,this._feedListeners=new Set}isInSyncUpdate(){return this._inSyncUpdate}isApplicationCursorKeyMode(){return this._applicationCursorKeyMode}isBracketedPasteMode(){return this._bracketedPasteMode}getCursorStyle(){return this._cursorStyle}get viewportRows(){return this._viewportRows}get cursorRow(){return this.curRow}get cursorCol(){return this.curCol}get viewportTopRow(){return this.getViewportTop()}getViewportTop(){return Em.getViewportTop(this)}setViewportSize(e,r){Kbr(this,e,r)}setStyles(e){this._st=Object.freeze(e)}absToVpRel(e){return Em.absToVpRel(this,e)}vpRelToAbs(e){return Em.vpRelToAbs(this,e)}get curVpRel(){return Em.curVpRel(this)}get isCursorAtScrollTop(){return Em.isCursorAtScrollTop(this)}get isCursorAtScrollBottom(){return Em.isCursorAtScrollBottom(this)}vpToAbsSticky(e){return Em.vpToAbsSticky(this,e)}markRowDirty(e){this._rowAnsiCache[e]=void 0}markAllDirty(){this._rowAnsiCache.length=0}ensureRow(e){for(;this.chars.length<=e;)this.chars.push([]),this.stys.push([])}saveCursorPos(){bEr(this)}restoreCursorPos(){EEr(this)}writeChar(e){Zbr(this,e)}writeRun(e,r,n){Xbr(this,e,r,n)}writeText(e){eEr(this,e)}newline(){tEr(this)}carriageReturn(){this.curCol=0}clearLine(e){rEr(this,e)}eraseInDisplay(e){Mbr(this,e)}toSegments(){return qbr(this)}feed(e){Pbr(this,e);for(let r of this._feedListeners)try{r()}catch{}}onFeed(e){return this._feedListeners.add(e),()=>{this._feedListeners.delete(e)}}cursorUp(e){DS.up(this,e)}cursorDown(e){DS.down(this,e)}cursorForward(e){DS.forward(this,e)}cursorBack(e){DS.back(this,e)}cursorToColumn(e){DS.toColumn(this,e)}cursorPosition(e,r){DS.position(this,e,r)}cursorPrevLine(e){DS.prevLine(this,e)}cursorNextLine(e){DS.nextLine(this,e)}verticalPositionAbsolute(e){DS.verticalAbsolute(this,e)}scrollRegionUp(){oEr(this)}scrollRegionDown(){sEr(this)}feedText(e,r,n){lEr(this,e,r,n)}reverseIndex(){DEr(this)}index(){SEr(this)}nextLine(){this.newline()}reset(){wEr(this)}insertLines(e){fEr(this,e)}deleteLines(e){pEr(this,e)}insertChars(e){hEr(this,e)}deleteChars(e){mEr(this,e)}eraseChars(e){gEr(this,e)}tabStop(){yEr(this)}nextTabStop(e){return CEr(this,e)}enterAltScreen(){Vbr(this)}exitAltScreen(){Hbr(this)}trimScrollbackIfOver(){IEr(this)}serializeRow(e){return PEr(this,e)}rowsAsAnsi(){return vxe(this)}getScreenAnsi(){return BEr(this)}getViewportSnapshot(){return kEr(this)}getScrollbackAnsi(e){return MEr(this,e)}getViewportScrollback(e){return FEr(this,e)}_registerEncoder(e){this._encoders.add(e)}_unregisterEncoder(e){this._encoders.delete(e)}_emitPassthroughCsi(e){for(let r of this._encoders)r._onPassthroughCsi(e)}_emitPendingResetScreen(){for(let e of this._encoders)e._onPendingResetScreen()}_emitPendingSyncWrap(){for(let e of this._encoders)e._onPendingSyncWrap()}_emitSnapshotInvalidated(){for(let e of this._encoders)e._onSnapshotInvalidated()}_captureSnapshot(){return TEr(this)}_computeDelta(e,r){return Dbr(this,e,r)}}});var Axe=g(()=>{zEr()});var _xe,KEr=g(()=>{Axe();_xe=class{constructor(e){this.grid=e,this.prev=fk(),this.pendingPassthrough=[],this.pendingResetScreen=!1,this.pendingSyncWrap=!1,this.forceFullRefreshOnBsuExit=!1,e._registerEncoder(this)}dispose(){this.grid._unregisterEncoder(this)}encodeDelta(){if(this.grid.isInSyncUpdate())return"";this.forceFullRefreshOnBsuExit&&(this.prev=fk(),this.forceFullRefreshOnBsuExit=!1);let e=this.grid._computeDelta(this.prev,{passthroughCsi:this.pendingPassthrough,resetScreen:this.pendingResetScreen,syncWrap:this.pendingSyncWrap});return this.prev=e.next,this.pendingPassthrough=[],this.pendingResetScreen=!1,this.pendingSyncWrap=!1,e.ansi}isInBatchedSyncUpdate(){return this.grid.isInSyncUpdate()}snapshot(){return this.isInBatchedSyncUpdate()?null:{prev:this.prev,pendingPassthrough:this.pendingPassthrough,pendingResetScreen:this.pendingResetScreen,pendingSyncWrap:this.pendingSyncWrap}}restore(e){if(e===null){this.forceFullRefreshOnBsuExit=!0;return}this.prev=e.prev,this.pendingPassthrough=e.pendingPassthrough,this.pendingResetScreen=e.pendingResetScreen,this.pendingSyncWrap=e.pendingSyncWrap}markBaseline(){this.prev=this.grid._captureSnapshot(),this.pendingPassthrough=[],this.pendingResetScreen=!1,this.pendingSyncWrap=!1}resetSnapshot(){this.prev=fk(),this.pendingPassthrough=[],this.pendingResetScreen=!1,this.pendingSyncWrap=!1}_onPassthroughCsi(e){this.pendingPassthrough.push(e)}_onPendingResetScreen(){this.pendingResetScreen=!0,this.prev=fk()}_onPendingSyncWrap(){this.pendingSyncWrap=!0}_onSnapshotInvalidated(){this.prev=fk()}}});var WEr=g(()=>{KEr()});var YEr=g(()=>{QI();Axe()});var JEr=g(()=>{YEr()});var ZEr=g(()=>{});var XEr=g(()=>{ZEr()});var aut=g(()=>{Axe();WEr();JEr();QI();XEr();gxe()});var bxe=g(()=>{dH();ES();dbr();aut()});function tDr(t,e){let r=t.cursorRow,n=t.cursorCol,i=t.viewportRows,o=t.getScrollbackAnsi(e);if(o.length===0)return eDr;let s=o.split(`
|
|
550
550
|
`),a=Math.min(s.length,r+1),u=s.slice(0,a),l=u.slice(-i).map(w=>w.replace(/\s+$/,"")),c=0;for(;l.length>1&&l[0]==="";)l.shift(),c++;let f=l,h=u.length-f.length,m=r-h,A=Math.max(1,Math.min(m+1,f.length+1)),b=m>=0&&m<f.length?`\x1B[${A};${n+1}H\x1B[K`:`\x1B[${A};${n+1}H`,S=f.map((w,C)=>`\x1B[${C+1};1H${w}\x1B[K`).join("");return eDr+S+b}var eDr,rDr=g(()=>{eDr="\x1B[0m\x1B[H\x1B[2J\x1B[3J"});var TTi,Exe,uut=g(()=>{bxe();rDr();TTi=5e3,Exe=class{constructor(e,r){this.queryService=e,this.messages$=r}handleData(e,r){let n=this.queryService.sessionMap()[e];if(!n){console.warn(`[PtyDataHandler] output dropped: session missing in sessionMap sessionId=${e} dataLen=${r.length}`);return}this.updateOutputBuffer(n,r),this.messages$.next({type:"session:server:pty-manager:session-data",sessionId:e,data:r})}handleExit(e,r,n){this.processExit(e,r,n)}destroy(){}processExit(e,r,n){let i=this.queryService.sessionMap()[e];i&&(i.status="terminated",this.queryService.removeSession(e),this.messages$.next({type:"session:server:pty-manager:session-exit",sessionId:e,exitCode:r,signal:n}))}updateOutputBuffer(e,r){this.ensureGrid(e).feed(this.augmentClearWithScrollback(r))}augmentClearWithScrollback(e){return e.replace(/(?<!\x1b\[3J)\x1b\[2J(?!\x1b\[3J)/g,"\x1B[3J\x1B[2J")}ensureGrid(e){let r=e.grid;if(r)return r;let n=new Fse;return e.grid=n,Object.defineProperty(e,"outputBuffer",{get(){return tDr(n,TTi)},set(i){},enumerable:!0,configurable:!0}),n}}});import{existsSync as xTi,realpathSync as NTi}from"fs";import lut from"path";function nDr(){let t=process.argv[1];if(t)try{let e=lut.dirname(NTi(t)),r=lut.join(e,"tmux-shim");return xTi(lut.join(r,"tmux"))?r:void 0}catch{return}}var cut=g(()=>{});function iDr(){return N(this,void 0,void 0,function*(){return(yield import("node-pty")).spawn})}var oDr=g(()=>{Se()});function sDr(t){var e;let r=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.parentEnv),(e=t.optionsEnv)!==null&&e!==void 0?e:{}),{PATH:[t.shim,t.systemPath].filter(Boolean).join(":"),TERM:"xterm-256color",COLORTERM:"truecolor",FORCE_COLOR:"1",PLANX_SESSION_NAME:t.name,PLANX_SESSION_ID:t.id}),t.parentId?{PLANX_PARENT_SESSION_ID:t.parentId}:{}),{PLANX_SERVER_ID:t.serverId,PLANX_SERVER_NAME:t.serverName}),t.shim?{PLANX_TMUX_SHIM_DIR:t.shim}:{}),t.transportPortFile?{PLANX_TRANSPORT_PORT_FILE:t.transportPortFile}:{});return delete r.TMUX,delete r.TMUX_PANE,t.transportPortFile||delete r.PLANX_TRANSPORT_PORT_FILE,r}var aDr=g(()=>{});var uDr=g(()=>{aDr()});import OTi from"os";var lDr,RTi,PTi,BTi,Dxe,dut=g(()=>{Se();lDr=Be(Zt());xg();uut();cut();oDr();uDr();RTi=500,PTi=500,BTi=25,Dxe=class{constructor(e,r,n=kI,i=Eat){this.config=e,this.queryService=r,this.escalateKillFn=n,this.resolvePgidFn=i,this.ptyMap=new Map,this.exitedSessions=new Set,this.messages$=new lDr.ReplaySubject(50),this._shimResolved=!1,this.dataHandler=new Exe(this.queryService,this.messages$)}ensureGrid(e){return this.dataHandler.ensureGrid(e)}get shimDir(){return this._shimResolved||(this._shimDir=nDr(),this._shimResolved=!0),this._shimDir}createSession(e){return N(this,void 0,void 0,function*(){var r;if(this.queryService.sessionMap()[e.id])throw new Error(`Session already exists: ${e.id}`);if(e.parentId&&!this.queryService.getSession(e.parentId))throw new Error(`Parent session not found: ${e.parentId}`);let n=(r=this.config.shell)!==null&&r!==void 0?r:OTi.platform()==="win32"?"powershell.exe":"/bin/zsh",i=e.command?["-c",e.command]:["-i","-l"],o={id:e.id,name:e.name,parentId:e.parentId,cwd:e.cwd,env:e.env,createdAt:new Date,lastAccessedAt:new Date,updatedAt:new Date,status:"active",command:e.command||n};this.queryService.updateSession(o);let s=this.queryService.resolveEnv(o),a=this.queryService.resolveCwd(o);try{console.error(`DIAG_SPAWNPTY_BEFORE id=${e.id} shell=${n} ts=${Date.now()}`)}catch{}let u=yield this.spawnPty(e.id,e.name,n,i,{cwd:a,env:s});try{console.error(`DIAG_SPAWNPTY_AFTER pid=${JSON.stringify(u.pid)} pidType=${typeof u.pid} ptyKeys=${Object.keys(u).join(",").slice(0,200)} ts=${Date.now()}`)}catch{}o.pid=u.pid;try{console.error(`DIAG_SPAWNPTY_ASSIGNED session.pid=${JSON.stringify(o.pid)} session.status=${JSON.stringify(o.status)} sessionKeys=${Object.keys(o).join(",")} ts=${Date.now()}`)}catch{}return this.queryService.updateSession(o),this.ptyMap.set(e.id,u),this.messages$.next({type:"session:server:pty-manager:session-created",sessionId:e.id,parentSessionId:e.parentId}),o})}spawnPty(e,r,n,i,o){return N(this,void 0,void 0,function*(){var s,a,u,l;let c=(s=this.queryService.getSession(e))===null||s===void 0?void 0:s.parentId,f=this.shimDir,h=yield iDr(),m=sDr({parentEnv:(a=this.config.parentEnv)!==null&&a!==void 0?a:{},optionsEnv:o?.env,shim:f,systemPath:(u=this.config.systemPath)!==null&&u!==void 0?u:"",id:e,name:r,parentId:c,serverId:this.config.serverId,serverName:this.config.serverName,transportPortFile:this.config.transportPortFile}),A=h(n,i,{name:"xterm-256color",cols:80,rows:30,cwd:(l=o?.cwd)!==null&&l!==void 0?l:process.cwd(),env:m});A.onData(b=>this.dataHandler.handleData(e,b)),A.onExit(({exitCode:b,signal:S})=>{this.exitedSessions.add(e),this.dataHandler.handleExit(e,b??-1,S??0)});let E=this.queryService.getSession(e);return E&&(E.promptBootstrapped=!0),setTimeout(()=>{try{A.write(`
|
|
551
551
|
`)}catch{}},100),A})}destroySession(e){return N(this,void 0,void 0,function*(){for(let n of this.queryService.getChildSessions(e))yield this.destroySession(n.id);let r=this.ptyMap.get(e);if(r?.pid&&!this.exitedSessions.has(e)){let n=this.resolvePgidFn(r.pid)===r.pid;yield this.escalateKillFn(r.pid,{killFn:(i,o)=>process.kill(n?-i:i,o),termTimeoutMs:RTi,killTimeoutMs:PTi,pollMs:BTi})}this.queryService.removeSession(e),this.ptyMap.delete(e),this.exitedSessions.delete(e),this.messages$.next({type:"session:server:pty-manager:session-exit",sessionId:e})})}destroyAllSessions(){return N(this,void 0,void 0,function*(){let e=Object.keys(this.queryService.sessionMap()),r=0,n=[];for(let i of e)try{yield this.destroySession(i),r++}catch(o){n.push(`${i}: ${o.message}`)}return{deletedCount:r,errors:n}})}}});var cDr,Sxe,fut=g(()=>{cDr="\0@machina/silent\0",Sxe=class{constructor(e){this.queryService=e}attach(e,r){var n,i;let o=this.queryService.getSession(e);if(!o)throw new Error(`session(${e}) not found.`);o.lastAccessedAt=new Date,o.status="active";let s=r.get(e);return!o.promptBootstrapped&&((i=(n=o.outputBuffer)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)<50&&s&&(o.promptBootstrapped=!0,setTimeout(()=>s.write(`
|
|
552
|
-
`),100)),o}input(e,r,n){let i=this.queryService.getSession(e);if(!i)throw new Error("Session not found");let o=n.get(e);if(r&&!o&&console.warn(`[PtyIoService] input dropped: pty missing in ptyMap sessionId=${e} knownPtyIds=${[...n.keys()].join(",")}`),r&&o){if(r.startsWith(cDr)){let s=r.slice(cDr.length);o.write(`\x1B[8m${s}\x1B[0m\x1B[2K\r`)}else o.write(r);i.lastAccessedAt=new Date}}resize(e,r,n,i){let o=this.queryService.getSession(e);if(!o)throw new Error("Session not found");let s=i.get(e);if(!r||!n||!s||s.cols===r&&s.rows===n)return;s.resize(r,n);let a=o.grid;a&&a.setViewportSize(n,r)}renameSession(e,r){let n=this.queryService.sessionMap()[e];if(!n){let i=Object.keys(this.queryService.sessionMap());throw new Error(`Session not found: ${e}. Available: ${i.join(", ")||"none"}`)}return this.queryService.updateSession(Object.assign(Object.assign({},n),{name:r,updatedAt:new Date})),this.queryService.getSession(e)}}});var yH,put,wxe,hut=g(()=>{Se();yH=Be(Zt());xg();put=class{isProcessRunning(e){return bm(e)}isPtyValid(e){return!!(e.pid&&e.pid!==void 0)}},wxe=class{constructor(e,r,n=()=>[]){this.getSession=e,this.destroySession=r,this.listSessions=n,this.destroy$=new yH.ReplaySubject(1),this.validator=new put}start(){this.subscription=(0,yH.interval)(3e4).pipe((0,yH.takeUntil)(this.destroy$)).subscribe(()=>this.performHealthCheck())}stop(){var e;this.destroy$.next(),(e=this.subscription)===null||e===void 0||e.unsubscribe()}performHealthCheck(){return N(this,void 0,void 0,function*(){for(let e of this.listSessions())yield this.checkSessionHealth(e)})}checkSessionHealth(e){return N(this,void 0,void 0,function*(){return this.validator.isPtyValid(e)?this.validator.isProcessRunning(e.pid)?!0:(yield this.destroySession(e.id),!1):(yield this.onUnhealthySession(e.id),!1)})}onUnhealthySession(e){return N(this,void 0,void 0,function*(){let r=this.getSession(e);r&&(r.status="terminated",yield this.destroySession(e))})}}});var vH,Cxe=g(()=>{Se();bat();dut();fut();hut();vH=class{constructor(e){this.queryService=new FTe,this.factoryService=new Dxe(e,this.queryService),this.ioService=new Sxe(this.queryService),this.healthCheckService=new wxe(r=>this.queryService.getSession(r),r=>this.factoryService.destroySession(r),()=>this.queryService.listSessions()),this.sessions$=this.queryService.sessions$,this.messages$=this.factoryService.messages$}createSession(e){return this.factoryService.createSession(e)}destroySession(e){return this.factoryService.destroySession(e)}destroyAllSessions(){return this.factoryService.destroyAllSessions()}listSessions(){return this.queryService.listSessions()}getSession(e){return this.queryService.getSession(e)}getChildSessions(e){return this.queryService.getChildSessions(e)}getPty(e){return this.factoryService.ptyMap.get(e)}getScrollback(e,r){let n=this.queryService.getSession(e);if(!n)return"";let i=n.grid;return i?i.getScrollbackAnsi(r):""}ensureGrid(e){let r=this.queryService.getSession(e);return r?this.factoryService.ensureGrid(r):null}attach(e){return this.ioService.attach(e,this.factoryService.ptyMap)}input(e,r){this.ioService.input(e,r,this.factoryService.ptyMap)}resize(e,r,n){this.ioService.resize(e,r,n,this.factoryService.ptyMap)}renameSession(e,r){let n=this.ioService.renameSession(e,r);return this.messages$.next({type:"session:server:pty-manager:session-renamed",sessionId:e,name:r}),n}start(){this.healthCheckService.start()}stop(){return N(this,void 0,void 0,function*(){this.healthCheckService.stop(),yield this.factoryService.destroyAllSessions()})}}});var dDr={};vn(dDr,{readSessionEnvironment:()=>vb});import kTi from"os";function vb(){var t,e,r,n,i;return{serverId:(t=process.env.PLANX_SERVER_ID)!==null&&t!==void 0?t:"local",serverName:(e=process.env.PLANX_SERVER_NAME)!==null&&e!==void 0?e:"local",shell:(r=process.env.SHELL)!==null&&r!==void 0?r:kTi.platform()==="win32"?"powershell.exe":"/bin/zsh",systemPath:(n=process.env.PATH)!==null&&n!==void 0?n:"",parentEnv:process.env,transportPortFile:(i=process.env.PLANX_TRANSPORT_PORT_FILE)!==null&&i!==void 0?i:null,sessionPort:(()=>{var o;let s=parseInt((o=process.env.PLANX_SESSION_PORT)!==null&&o!==void 0?o:"",10);return isNaN(s)?null:s})(),wtPort:(()=>{var o;let s=parseInt((o=process.env.PLANX_SESSION_WT_PORT)!==null&&o!==void 0?o:"",10);return isNaN(s)||s<=0?null:s})(),port:(()=>{var o;let s=parseInt((o=process.env.PORT)!==null&&o!==void 0?o:"",10);return isNaN(s)||s<=0?null:s})()}}var pk=g(()=>{});var Lse,mut,Jd,Ixe=g(()=>{Se();Re();Lse=Be(Zt());Cxe();pk();Re();mut=new At("SESSION_SERVER_CONFIG",{providedIn:"root",factory:()=>()=>{var t;let e=vb();return{serverId:e.serverId,serverName:e.serverName,shell:e.shell,systemPath:e.systemPath,parentEnv:e.parentEnv,transportPortFile:(t=e.transportPortFile)!==null&&t!==void 0?t:void 0}}}),Jd=class{constructor(){this.getConfig=Z(mut),this.messageSubscriptions=[],this.message$=new Lse.Subject}get manager(){return this._manager||(this._manager=new vH(this.getConfig()),this.messageSubscriptions.push(this._manager.messages$.pipe((0,Lse.filter)(e=>e.type==="session:server:pty-manager:session-data")).subscribe(e=>{this.message$.next({type:"[session.server.pty] data",sessionId:e.sessionId,data:e.data})})),this.messageSubscriptions.push(this._manager.messages$.pipe((0,Lse.filter)(e=>e.type==="session:server:pty-manager:session-exit")).subscribe(e=>{this.message$.next({type:"[session.server.pty] exit",sessionId:e.sessionId,exitCode:e.exitCode,signal:e.signal})}))),this._manager}start(){return N(this,void 0,void 0,function*(){this.manager.start()})}stop(){return N(this,void 0,void 0,function*(){this._manager&&(yield this._manager.stop());for(let e of this.messageSubscriptions)e.unsubscribe();this.messageSubscriptions=[]})}};Jd.\u0275fac=function(e){return new(e||Jd)};Jd.\u0275prov=Ce({token:Jd,factory:Jd.\u0275fac,providedIn:"root"})});function jse(t,e){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),{allowPeersPublicKeys:e.allowPeersPublicKeys}),e.identity?{identity:e.identity}:{}),e.name!==void 0?{name:e.name}:{}),e.roles?{roles:e.roles}:{}),e.allowPeersMode!==void 0?{allowPeersMode:e.allowPeersMode}:{})}function VI(t,e){return N(this,arguments,void 0,function*(r,n,i=[],o){let s=r.getKeyPair(),a=r.getPeerId(),u=yield n.toUuid(s.publicKey),l={};l[u]=s.publicKey;let c={};for(let f of i){if(!f)continue;let h=yield n.toUuid(f);l[h]=f;let m=o?.[f];m&&(c[h]=m)}return Object.assign({peerId:a,publicKey:s.publicKey,signalingId:u,privateKey:s.privateKey,peers:l},o?{peersMeta:c}:{})})}var fDr=g(()=>{Se()});var pDr=g(()=>{fDr()});var hDr=g(()=>{});var gut=g(()=>{hDr()});function hk(t){return N(this,void 0,void 0,function*(){let e=new TextEncoder().encode(t),r=yield crypto.subtle.digest("SHA-256",e),n=new Uint8Array(r).slice(0,16);n[0]=32,n[1]=1,n[2]=0,n[3]=42,n[6]=n[6]&15|128,n[8]=n[8]&63|128;let i=Array.from(n).map(o=>o.toString(16).padStart(2,"0")).join("");return[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20,32)].join("-")})}function yut(t){let e=t.replace(/-/g,"");if(e.length!==32)throw new Error(`peerIdToBytes: invalid peerId format "${t}" (expected 32 hex chars)`);let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}var mDr=g(()=>{Se();gut()});var gDr,yDr=g(()=>{gDr={maxAgeMs:3e4,now:()=>Date.now()}});var $se=g(()=>{mDr();yDr();gut()});var vDr=g(()=>{});var ADr=g(()=>{vDr()});var _Dr=g(()=>{pDr();$se();ADr()});var bDr=g(()=>{_Dr()});function EDr(t){return new ReadableStream({start(e){e.enqueue(t),e.close()}})}function DDr(t){return N(this,void 0,void 0,function*(){return new Uint8Array(yield new Response(t).arrayBuffer())})}function SDr(t){return N(this,void 0,void 0,function*(){let e=new CompressionStream("deflate-raw");return DDr(EDr(t).pipeThrough(e))})}function wDr(t){return N(this,void 0,void 0,function*(){let e=new DecompressionStream("deflate-raw");return DDr(EDr(t).pipeThrough(e))})}var CDr=g(()=>{Se()});var IDr=g(()=>{CDr()});var Op,TDr=g(()=>{Se();$se();Re();Op=class{getPeerId(e){return N(this,void 0,void 0,function*(){return hk(e.publicKey)})}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};Op.\u0275fac=function(e){return new(e||Op)};Op.\u0275prov=Ce({token:Op,factory:Op.\u0275fac})});var qse=g(()=>{TDr()});var dN,xDr=g(()=>{Se();qse();Re();dN=class extends Op{constructor(){super(...arguments),this.counter=0}generateKeyPair(){return N(this,void 0,void 0,function*(){return this.counter++,{publicKey:`mockPublicKey_${this.counter}_${Date.now()}`,privateKey:`mockPrivateKey_${this.counter}_${Date.now()}`,algorithm:"P-256",createdAt:new Date}})}};dN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(dN)))(r||dN)}})();dN.\u0275prov=Ce({token:dN,factory:dN.\u0275fac})});var NDr=g(()=>{xDr()});var Txe=g(()=>{qse();NDr()});var Zd,ODr=g(()=>{Se();Re();Zd=class{encrypt(e,r){return N(this,void 0,void 0,function*(){return this.encryptBytes(new TextEncoder().encode(e),r)})}decrypt(e,r,n){return N(this,void 0,void 0,function*(){return new TextDecoder().decode(yield this.decryptBytes(e,r,n))})}base64ToBuffer(e){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};Zd.\u0275fac=function(e){return new(e||Zd)};Zd.\u0275prov=Ce({token:Zd,factory:Zd.\u0275fac})});var AH=g(()=>{ODr()});var fN,RDr=g(()=>{Se();AH();Re();fN=class extends Zd{deriveSharedKey(e,r){return N(this,void 0,void 0,function*(){let n=this.base64ToBuffer(e),i=yield crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),o=this.base64ToBuffer(r),s=yield crypto.subtle.importKey("spki",o,{name:"ECDH",namedCurve:"P-256"},!1,[]),a=yield crypto.subtle.deriveBits({name:"ECDH",public:s},i,256),u=yield crypto.subtle.digest("SHA-256",a);return crypto.subtle.importKey("raw",u,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])})}encryptBytes(e,r){return N(this,void 0,void 0,function*(){let n=crypto.getRandomValues(new Uint8Array(12)),i=yield crypto.subtle.encrypt({name:"AES-GCM",iv:n},r,e);return{encrypted:this.bufferToBase64(i),iv:this.bufferToBase64(n.buffer)}})}decryptBytes(e,r,n){return N(this,void 0,void 0,function*(){let i=yield crypto.subtle.decrypt({name:"AES-GCM",iv:this.base64ToBuffer(r)},n,this.base64ToBuffer(e));return new Uint8Array(i)})}};fN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(fN)))(r||fN)}})();fN.\u0275prov=Ce({token:fN,factory:fN.\u0275fac})});var vut=g(()=>{RDr()});var pN,PDr=g(()=>{Se();AH();Re();pN=class extends Zd{deriveSharedKey(e,r){return N(this,void 0,void 0,function*(){return{}})}encryptBytes(e,r){return N(this,void 0,void 0,function*(){let n="";for(let i of e)n+=String.fromCharCode(i);return{encrypted:btoa(n),iv:btoa("mock-iv-12byte")}})}decryptBytes(e,r,n){return N(this,void 0,void 0,function*(){let i=atob(e);return Uint8Array.from(i,o=>o.charCodeAt(0))})}};pN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(pN)))(r||pN)}})();pN.\u0275prov=Ce({token:pN,factory:pN.\u0275fac})});var BDr=g(()=>{PDr()});var Aut=g(()=>{AH();vut();BDr()});function _H(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t))throw new Error(`Invalid UUID 8-4-4-4-12: ${t}`);let e=t.replace(/-/g,"");return[0,4,8,12,16,20,24,28].map(r=>e.slice(r,r+4)).join(":")}function kDr(t){if(!/^[0-9a-f]{1,4}(:[0-9a-f]{1,4}){7}$/.test(t))throw new Error(`Invalid IPv6 literal (8 group form required): ${t}`);let r=t.split(":").map(n=>n.padStart(4,"0")).join("");return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")}var wd,MDr=g(()=>{Se();Re();wd=class{sha256(e){return N(this,void 0,void 0,function*(){let r=new TextEncoder().encode(e),n=yield crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")})}toUuid(e){return N(this,void 0,void 0,function*(){let r=new TextEncoder().encode(e),n=yield crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n).slice(0,16);i[0]=32,i[1]=1,i[2]=0,i[3]=42,i[6]=i[6]&15|128,i[8]=i[8]&63|128;let o=Array.from(i).map(s=>s.toString(16).padStart(2,"0")).join("");return[o.slice(0,8),o.slice(8,12),o.slice(12,16),o.slice(16,20),o.slice(20,32)].join("-")})}};wd.\u0275fac=function(e){return new(e||wd)};wd.\u0275prov=Ce({token:wd,factory:wd.\u0275fac,providedIn:"root"})});var bH=g(()=>{MDr()});var Ab,FDr=g(()=>{bH();Re();Ab=class extends wd{};Ab.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(Ab)))(r||Ab)}})();Ab.\u0275prov=Ce({token:Ab,factory:Ab.\u0275fac})});var Use=g(()=>{FDr()});var LDr=g(()=>{bH();Use()});var Xc,jDr=g(()=>{Se();$se();Re();Xc=class{canonicalStringify(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(i=>this.canonicalStringify(i)).join(",")+"]":"{"+Object.keys(e).sort().filter(i=>e[i]!==void 0).map(i=>JSON.stringify(i)+":"+this.canonicalStringify(e[i])).join(",")+"}"}sign(e,r){return N(this,void 0,void 0,function*(){let n=this.canonicalStringify(e),i=yield this.createSignature(n,r);return{payload:e,signature:i}})}verify(e,r){return N(this,void 0,void 0,function*(){try{let n=this.canonicalStringify(e.payload);return(yield this.verifySignature(n,e.signature,r))?{valid:!0,verifiedBy:r}:{valid:!1,error:"Signature verification failed"}}catch(n){return{valid:!1,error:`Verification error: ${n}`}}})}validateTimestamp(e,r=gDr){let i=(r.now?r.now():Date.now())-e;return i>=0&&i<=r.maxAgeMs}base64ToBuffer(e){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};Xc.\u0275fac=function(e){return new(e||Xc)};Xc.\u0275prov=Ce({token:Xc,factory:Xc.\u0275fac})});var EH=g(()=>{jDr()});var _ut,hN,$Dr=g(()=>{Se();EH();Re();_ut="|||",hN=class extends Xc{createSignature(e,r){return N(this,void 0,void 0,function*(){return btoa(`mock_sig${_ut}${e}${_ut}${r.substring(0,10)}`)})}verifySignature(e,r,n){return N(this,void 0,void 0,function*(){try{let o=atob(r).split(_ut);return o.length===3&&o[0]==="mock_sig"&&o[1]===e}catch{return!1}})}};hN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(hN)))(r||hN)}})();hN.\u0275prov=Ce({token:hN,factory:hN.\u0275fac})});var qDr=g(()=>{$Dr()});var but=g(()=>{EH();qDr()});var Rp,UDr=g(()=>{Re();Rp=class{};Rp.\u0275fac=function(e){return new(e||Rp)};Rp.\u0275prov=Ce({token:Rp,factory:Rp.\u0275fac})});var Qse=g(()=>{UDr()});var mN,QDr=g(()=>{Se();Qse();Re();mN=class extends Rp{constructor(){super(...arguments),this.storage=null,this.backups=[]}save(e){return N(this,void 0,void 0,function*(){this.storage=Object.assign({},e)})}load(){return N(this,void 0,void 0,function*(){return this.storage?Object.assign({},this.storage):null})}exists(){return N(this,void 0,void 0,function*(){return this.storage!==null})}delete(){return N(this,void 0,void 0,function*(){this.storage=null})}saveBackup(e,r){return N(this,void 0,void 0,function*(){this.backups.push({keyPair:Object.assign({},e),rotatedAt:r})})}loadBackups(){return N(this,void 0,void 0,function*(){return this.backups.map(e=>({keyPair:Object.assign({},e.keyPair),rotatedAt:e.rotatedAt}))})}cleanupBackups(e){return N(this,void 0,void 0,function*(){let r=Date.now()-e;this.backups=this.backups.filter(n=>n.rotatedAt>r)})}};mN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(mN)))(r||mN)}})();mN.\u0275prov=Ce({token:mN,factory:mN.\u0275fac})});var VDr=g(()=>{QDr()});var xxe=g(()=>{Qse();VDr()});var No,HDr=g(()=>{Se();Re();$se();xxe();Txe();Re();No=class{constructor(){this.keyGenerator=Z(Op),this.storage=Z(Rp),this.keyPair=null,this.peerId=null,this._initialized=ia(!1)}initialize(){return N(this,void 0,void 0,function*(){if(this._initialized())return;let e=yield this.storage.load();e?this.keyPair=e:(this.keyPair=yield this.keyGenerator.generateKeyPair(),yield this.storage.save(this.keyPair)),this.peerId=yield hk(this.keyPair.publicKey),this._initialized.set(!0)})}getKeyPair(){if(!this.keyPair)throw new Error("KeyManager not initialized");return this.keyPair}getPeerId(){if(!this.peerId)throw new Error("KeyManager not initialized");return this.peerId}isInitialized(){return this._initialized()}waitForInitialization(){return N(this,arguments,void 0,function*(e=1e4){if(this._initialized())return;let r=Date.now(),n=50;return new Promise((i,o)=>{let s=()=>{if(this._initialized()){i();return}if(Date.now()-r>e){o(new Error("KeyManager initialization timeout"));return}setTimeout(s,n)};s()})})}reset(){return N(this,void 0,void 0,function*(){yield this.storage.delete(),this.keyPair=null,this.peerId=null,this._initialized.set(!1),yield this.initialize()})}rotateKeyPair(){return N(this,void 0,void 0,function*(){if(!this.keyPair)throw new Error("KeyManager not initialized");yield this.storage.saveBackup(this.keyPair,Date.now());let e=yield this.keyGenerator.generateKeyPair();return yield this.storage.save(e),this.keyPair=e,this.peerId=yield hk(e.publicKey),e})}getBackupKeyPairs(){return N(this,void 0,void 0,function*(){return this.storage.loadBackups()})}cleanupOldBackups(){return N(this,arguments,void 0,function*(e=10080*60*1e3){yield this.storage.cleanupBackups(e)})}};No.\u0275fac=function(e){return new(e||No)};No.\u0275prov=Ce({token:No,factory:No.\u0275fac,providedIn:"root"})});var GDr=g(()=>{HDr()});var zDr=g(()=>{xxe();Txe();Aut();bH();Use();but()});var KDr=g(()=>{zDr()});var Eut=g(()=>{IDr();Txe();Aut();LDr();but();GDr();KDr()});var WDr=g(()=>{xxe()});function SS(t){return[{provide:DH,useFactory:t,multi:!0}]}var DH,YDr=g(()=>{Re();DH=new At("SIGNALING_CHANNELS")});function wS(t){return typeof t=="object"&&t!==null&&"encrypted"in t&&"iv"in t&&typeof t.encrypted=="string"&&typeof t.iv=="string"}var JDr=g(()=>{});var ZDr=g(()=>{});var HI,XDr=g(()=>{Re();HI=new At("SIGNALING_MESSAGE_SENDER")});function eSr(t){return"lost"in t&&t.lost===!0}var tSr=g(()=>{});var rSr=g(()=>{YDr();JDr();ZDr();XDr();tSr()});var _b,nSr=g(()=>{Se();Re();kr();bH();Re();_b=class{constructor(){this.logger=ct("SignalingIdService"),this.hashAdapter=Z(wd)}generateId(e){return N(this,void 0,void 0,function*(){return yield this.hashAdapter.toUuid(e)})}findPublicKeyByHash(e,r){return N(this,void 0,void 0,function*(){for(let n of r)if((yield this.generateId(n))===e)return n;return null})}isHashedId(e){return/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(e)}};_b.\u0275fac=function(e){return new(e||_b)};_b.\u0275prov=Ce({token:_b,factory:_b.\u0275fac,providedIn:"root"})});var iSr=g(()=>{nSr()});var Nxe,mk,oSr=g(()=>{Nxe={prod:{hasuraUrl:"https://graphql-prod.machina.at/v1/graphql",apiNextUrl:"https://api.machina.at",signalingUrl:"https://signaling.machina.at",firebaseDatabaseUrl:"https://x-x-machina-default-rtdb.asia-southeast1.firebasedatabase.app",webServerUrl:"https://server.machina.at",invoiceAppUrl:"https://presenter.machina.at/stable"},stg:{hasuraUrl:"https://graphql-stg.machina.at/v1/graphql",apiNextUrl:"https://api.stg.machina.at",signalingUrl:"https://signaling-stg.machina.at",firebaseDatabaseUrl:"https://x-x-machina-stg.asia-southeast1.firebasedatabase.app",webServerUrl:"https://server.machina.at",invoiceAppUrl:"https://x-x-machina-invoice.web.app"}},mk={PLANX_GRAPHQL_URL:Nxe.prod.hasuraUrl,PLANX_CLOUD_API_URL:Nxe.prod.apiNextUrl,PLANX_SIGNALING_URL:Nxe.prod.signalingUrl,PLANX_FIREBASE_DATABASE_URL:Nxe.prod.firebaseDatabaseUrl,PLANX_SIGNALING_BACKEND:"",PLANX_NOSTR_RELAYS:"wss://nos.lol,wss://relay.snort.social"}});var Oxe=g(()=>{oSr()});var GI,sSr=g(()=>{Re();GI=new At("TRPC_CLIENT")});var gk,aSr=g(()=>{gk=class t{static in(e,r){return new t(e,r)}constructor(e,r){var n;this.controller=new AbortController,this.timer=null,this.now=(n=r?.now)!==null&&n!==void 0?n:(()=>Date.now()),this.at=this.now()+Math.max(0,e);let i=()=>this.abort();e<=0?i():this.timer=setTimeout(i,e),r?.parent&&(r.parent.aborted?i():r.parent.addEventListener("abort",i,{once:!0}))}get signal(){return this.controller.signal}remaining(){return Math.max(0,this.at-this.now())}expired(){return this.remaining()===0}child(e){return new t(Math.min(e,this.remaining()),{now:this.now,parent:this.signal})}split(e){let r=Math.min(1,Math.max(0,e));return this.child(Math.floor(this.remaining()*r))}abort(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.controller.signal.aborted||this.controller.abort()}dispose(){this.abort()}}});var uSr=g(()=>{sSr();aSr()});var MTi,FTi,LTi,jTi,$Ti,Wn,lSr=g(()=>{MTi={name:"port-forward",prefix:"pf:",profile:"reliable-ordered",defaultCap:1e3,defaultBackpressureProfile:"http",buildLabel:t=>`pf:${t}`,parseLabel:t=>t.startsWith("pf:")?t.slice(3):null},FTi={name:"heartbeat",prefix:"__heartbeat__",profile:"heartbeat",defaultCap:1,defaultBackpressureProfile:"control",buildLabel:()=>"__heartbeat__",parseLabel:t=>t==="__heartbeat__"?"":null},LTi={name:"l7-http",prefix:"l7:http:",profile:"reliable-ordered",defaultCap:1e3,defaultBackpressureProfile:"http",buildLabel:t=>`l7:http:${t}`,parseLabel:t=>t.startsWith("l7:http:")?t.slice(8):null},jTi={name:"l7-datagram",prefix:"l7:dg:",profile:"unreliable",defaultCap:8,defaultBackpressureProfile:"terminal",buildLabel:t=>`l7:dg:${t}`,parseLabel:t=>t.startsWith("l7:dg:")?t.slice(6):null},$Ti={name:"l7-qpack",prefix:"l7:qpack:",profile:"reliable-ordered",defaultCap:8,defaultBackpressureProfile:"control",buildLabel:t=>`l7:qpack:${t}`,parseLabel:t=>t.startsWith("l7:qpack:")?t.slice(9):null},Wn={portForward:MTi,heartbeat:FTi,l7Http:LTi,l7Dg:jTi,l7Qpack:$Ti}});var cSr=g(()=>{lSr()});function Sut(t){return function(e,r,n){let i=Reflect.getMetadata(Dut,e.constructor)||[];return i.push({messageType:t,methodName:r}),Reflect.defineMetadata(Dut,i,e.constructor),n}}function dSr(t){return Reflect.getMetadata(Dut,t.constructor)||[]}var Dut,fSr=g(()=>{dte();Dut=Symbol("messageHandlers")});var wut=g(()=>{fSr()});var Rxe,SH,pSr=g(()=>{Se();kr();wut();Rxe=class extends Error{constructor(e){super(`No handler found for message type: ${e}`),this.messageType=e,this.code="HANDLER_NOT_FOUND",this.name="HandlerNotFoundError"}},SH=class{constructor(){this.logger=ct(this.constructor.name)}handle(e,r){return N(this,void 0,void 0,function*(){let i=dSr(e).find(o=>o.messageType===r.type);if(i){let o=e[i.methodName];typeof o=="function"&&(yield o.call(e,r))}else throw this.logger.warn("No handler found for message type:",r.type),new Rxe(r.type)})}}});var hSr=g(()=>{wut();pSr()});function Cut(t){return t.replace(/^http(s?):\/\//,"ws$1://")}var mSr=g(()=>{});function Pxe(t,e){let r=_H(t),n=e.replace(/^\//,"");return`https://[${r}]:10/${n}`}var gSr=g(()=>{Eut()});var Iut=g(()=>{mSr();gSr()});var Mn=g(()=>{bDr();Eut();WDr();rSr();iSr();Oxe();uSr();cSr();hSr();Iut()});var Bxe,ySr=g(()=>{Mn();Mn();Bxe=class extends SH{}});var vSr=g(()=>{ySr()});import*as gN from"node:fs";import*as ASr from"node:path";var bb,Tut=g(()=>{kr();Re();bb=class t{constructor(){this.logger=ct("SessionOutputRecorderService"),this.fd=null,this.buffer=[],this.flushTimer=null,this.enabled=!1}start(e){this.enabled=!0;let r=t.DIR;gN.mkdirSync(r,{recursive:!0});let n=`${e.slice(0,16)}_${Date.now()}.jsonl`,i=ASr.join(r,n);this.fd=gN.openSync(i,"a"),this.flushTimer=setInterval(()=>this.flush(),t.FLUSH_INTERVAL_MS),this.logger.info("Recording started",{filepath:i})}record(e){if(!this.enabled)return;let r=JSON.stringify(Object.assign({ts:performance.now(),iso:new Date().toISOString()},e));this.buffer.push(r)}flush(){if(this.buffer.length===0||this.fd===null)return;let e=this.buffer.join(`
|
|
552
|
+
`),100)),o}input(e,r,n){let i=this.queryService.getSession(e);if(!i)throw new Error("Session not found");let o=n.get(e);if(r&&!o&&console.warn(`[PtyIoService] input dropped: pty missing in ptyMap sessionId=${e} knownPtyIds=${[...n.keys()].join(",")}`),r&&o){if(r.startsWith(cDr)){let s=r.slice(cDr.length);o.write(`\x1B[8m${s}\x1B[0m\x1B[2K\r`)}else o.write(r);i.lastAccessedAt=new Date}}resize(e,r,n,i){let o=this.queryService.getSession(e);if(!o)throw new Error("Session not found");let s=i.get(e);if(!r||!n||!s||s.cols===r&&s.rows===n)return;s.resize(r,n);let a=o.grid;a&&a.setViewportSize(n,r)}renameSession(e,r){let n=this.queryService.sessionMap()[e];if(!n){let i=Object.keys(this.queryService.sessionMap());throw new Error(`Session not found: ${e}. Available: ${i.join(", ")||"none"}`)}return this.queryService.updateSession(Object.assign(Object.assign({},n),{name:r,updatedAt:new Date})),this.queryService.getSession(e)}}});var yH,put,wxe,hut=g(()=>{Se();yH=Be(Zt());xg();put=class{isProcessRunning(e){return bm(e)}isPtyValid(e){return!!(e.pid&&e.pid!==void 0)}},wxe=class{constructor(e,r,n=()=>[]){this.getSession=e,this.destroySession=r,this.listSessions=n,this.destroy$=new yH.ReplaySubject(1),this.validator=new put}start(){this.subscription=(0,yH.interval)(3e4).pipe((0,yH.takeUntil)(this.destroy$)).subscribe(()=>this.performHealthCheck())}stop(){var e;this.destroy$.next(),(e=this.subscription)===null||e===void 0||e.unsubscribe()}performHealthCheck(){return N(this,void 0,void 0,function*(){for(let e of this.listSessions())yield this.checkSessionHealth(e)})}checkSessionHealth(e){return N(this,void 0,void 0,function*(){return this.validator.isPtyValid(e)?this.validator.isProcessRunning(e.pid)?!0:(yield this.destroySession(e.id),!1):(yield this.onUnhealthySession(e.id),!1)})}onUnhealthySession(e){return N(this,void 0,void 0,function*(){let r=this.getSession(e);r&&(r.status="terminated",yield this.destroySession(e))})}}});var vH,Cxe=g(()=>{Se();bat();dut();fut();hut();vH=class{constructor(e){this.queryService=new FTe,this.factoryService=new Dxe(e,this.queryService),this.ioService=new Sxe(this.queryService),this.healthCheckService=new wxe(r=>this.queryService.getSession(r),r=>this.factoryService.destroySession(r),()=>this.queryService.listSessions()),this.sessions$=this.queryService.sessions$,this.messages$=this.factoryService.messages$}createSession(e){return this.factoryService.createSession(e)}destroySession(e){return this.factoryService.destroySession(e)}destroyAllSessions(){return this.factoryService.destroyAllSessions()}listSessions(){return this.queryService.listSessions()}getSession(e){return this.queryService.getSession(e)}getChildSessions(e){return this.queryService.getChildSessions(e)}getPty(e){return this.factoryService.ptyMap.get(e)}getScrollback(e,r){let n=this.queryService.getSession(e);if(!n)return"";let i=n.grid;return i?i.getScrollbackAnsi(r):""}ensureGrid(e){let r=this.queryService.getSession(e);return r?this.factoryService.ensureGrid(r):null}attach(e){return this.ioService.attach(e,this.factoryService.ptyMap)}input(e,r){this.ioService.input(e,r,this.factoryService.ptyMap)}resize(e,r,n){this.ioService.resize(e,r,n,this.factoryService.ptyMap)}renameSession(e,r){let n=this.ioService.renameSession(e,r);return this.messages$.next({type:"session:server:pty-manager:session-renamed",sessionId:e,name:r}),n}start(){this.healthCheckService.start()}stop(){return N(this,void 0,void 0,function*(){this.healthCheckService.stop(),yield this.factoryService.destroyAllSessions()})}}});var dDr={};vn(dDr,{readSessionEnvironment:()=>vb});import kTi from"os";function vb(){var t,e,r,n,i;return{serverId:(t=process.env.PLANX_SERVER_ID)!==null&&t!==void 0?t:"local",serverName:(e=process.env.PLANX_SERVER_NAME)!==null&&e!==void 0?e:"local",shell:(r=process.env.SHELL)!==null&&r!==void 0?r:kTi.platform()==="win32"?"powershell.exe":"/bin/zsh",systemPath:(n=process.env.PATH)!==null&&n!==void 0?n:"",parentEnv:process.env,transportPortFile:(i=process.env.PLANX_TRANSPORT_PORT_FILE)!==null&&i!==void 0?i:null,sessionPort:(()=>{var o;let s=parseInt((o=process.env.PLANX_SESSION_PORT)!==null&&o!==void 0?o:"",10);return isNaN(s)?null:s})(),wtPort:(()=>{var o;let s=parseInt((o=process.env.PLANX_SESSION_WT_PORT)!==null&&o!==void 0?o:"",10);return isNaN(s)||s<=0?null:s})(),port:(()=>{var o;let s=parseInt((o=process.env.PORT)!==null&&o!==void 0?o:"",10);return isNaN(s)||s<=0?null:s})()}}var pk=g(()=>{});var Lse,mut,Jd,Ixe=g(()=>{Se();Re();Lse=Be(Zt());Cxe();pk();Re();mut=new At("SESSION_SERVER_CONFIG",{providedIn:"root",factory:()=>()=>{var t;let e=vb();return{serverId:e.serverId,serverName:e.serverName,shell:e.shell,systemPath:e.systemPath,parentEnv:e.parentEnv,transportPortFile:(t=e.transportPortFile)!==null&&t!==void 0?t:void 0}}}),Jd=class{constructor(){this.getConfig=Z(mut),this.messageSubscriptions=[],this.message$=new Lse.Subject}get manager(){return this._manager||(this._manager=new vH(this.getConfig()),this.messageSubscriptions.push(this._manager.messages$.pipe((0,Lse.filter)(e=>e.type==="session:server:pty-manager:session-data")).subscribe(e=>{this.message$.next({type:"[session.server.pty] data",sessionId:e.sessionId,data:e.data})})),this.messageSubscriptions.push(this._manager.messages$.pipe((0,Lse.filter)(e=>e.type==="session:server:pty-manager:session-exit")).subscribe(e=>{this.message$.next({type:"[session.server.pty] exit",sessionId:e.sessionId,exitCode:e.exitCode,signal:e.signal})}))),this._manager}start(){return N(this,void 0,void 0,function*(){this.manager.start()})}stop(){return N(this,void 0,void 0,function*(){this._manager&&(yield this._manager.stop());for(let e of this.messageSubscriptions)e.unsubscribe();this.messageSubscriptions=[]})}};Jd.\u0275fac=function(e){return new(e||Jd)};Jd.\u0275prov=Ce({token:Jd,factory:Jd.\u0275fac,providedIn:"root"})});function jse(t,e){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),{allowPeersPublicKeys:e.allowPeersPublicKeys}),e.identity?{identity:e.identity}:{}),e.name!==void 0?{name:e.name}:{}),e.roles?{roles:e.roles}:{}),e.allowPeersMode!==void 0?{allowPeersMode:e.allowPeersMode}:{})}function VI(t,e){return N(this,arguments,void 0,function*(r,n,i=[],o){let s=r.getKeyPair(),a=r.getPeerId(),u=yield n.toUuid(s.publicKey),l={};l[u]=s.publicKey;let c={};for(let f of i){if(!f)continue;let h=yield n.toUuid(f);l[h]=f;let m=o?.[f];m&&(c[h]=m)}return Object.assign({peerId:a,publicKey:s.publicKey,signalingId:u,privateKey:s.privateKey,peers:l},o?{peersMeta:c}:{})})}var fDr=g(()=>{Se()});var pDr=g(()=>{fDr()});var hDr=g(()=>{});var gut=g(()=>{hDr()});function hk(t){return N(this,void 0,void 0,function*(){let e=new TextEncoder().encode(t),r=yield crypto.subtle.digest("SHA-256",e),n=new Uint8Array(r).slice(0,16);n[0]=32,n[1]=1,n[2]=0,n[3]=42,n[6]=n[6]&15|128,n[8]=n[8]&63|128;let i=Array.from(n).map(o=>o.toString(16).padStart(2,"0")).join("");return[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20,32)].join("-")})}function yut(t){let e=t.replace(/-/g,"");if(e.length!==32)throw new Error(`peerIdToBytes: invalid peerId format "${t}" (expected 32 hex chars)`);let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}var mDr=g(()=>{Se();gut()});var gDr,yDr=g(()=>{gDr={maxAgeMs:3e4,now:()=>Date.now()}});var $se=g(()=>{mDr();yDr();gut()});var vDr=g(()=>{});var ADr=g(()=>{vDr()});var _Dr=g(()=>{pDr();$se();ADr()});var bDr=g(()=>{_Dr()});function EDr(t){return new ReadableStream({start(e){e.enqueue(t),e.close()}})}function DDr(t){return N(this,void 0,void 0,function*(){return new Uint8Array(yield new Response(t).arrayBuffer())})}function SDr(t){return N(this,void 0,void 0,function*(){let e=new CompressionStream("deflate-raw");return DDr(EDr(t).pipeThrough(e))})}function wDr(t){return N(this,void 0,void 0,function*(){let e=new DecompressionStream("deflate-raw");return DDr(EDr(t).pipeThrough(e))})}var CDr=g(()=>{Se()});var IDr=g(()=>{CDr()});var Op,TDr=g(()=>{Se();$se();Re();Op=class{getPeerId(e){return N(this,void 0,void 0,function*(){return hk(e.publicKey)})}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};Op.\u0275fac=function(e){return new(e||Op)};Op.\u0275prov=Ce({token:Op,factory:Op.\u0275fac})});var qse=g(()=>{TDr()});var dN,xDr=g(()=>{Se();qse();Re();dN=class extends Op{constructor(){super(...arguments),this.counter=0}generateKeyPair(){return N(this,void 0,void 0,function*(){return this.counter++,{publicKey:`mockPublicKey_${this.counter}_${Date.now()}`,privateKey:`mockPrivateKey_${this.counter}_${Date.now()}`,algorithm:"P-256",createdAt:new Date}})}};dN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(dN)))(r||dN)}})();dN.\u0275prov=Ce({token:dN,factory:dN.\u0275fac})});var NDr=g(()=>{xDr()});var Txe=g(()=>{qse();NDr()});var Zd,ODr=g(()=>{Se();Re();Zd=class{encrypt(e,r){return N(this,void 0,void 0,function*(){return this.encryptBytes(new TextEncoder().encode(e),r)})}decrypt(e,r,n){return N(this,void 0,void 0,function*(){return new TextDecoder().decode(yield this.decryptBytes(e,r,n))})}base64ToBuffer(e){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};Zd.\u0275fac=function(e){return new(e||Zd)};Zd.\u0275prov=Ce({token:Zd,factory:Zd.\u0275fac})});var AH=g(()=>{ODr()});var fN,RDr=g(()=>{Se();AH();Re();fN=class extends Zd{deriveSharedKey(e,r){return N(this,void 0,void 0,function*(){let n=this.base64ToBuffer(e),i=yield crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),o=this.base64ToBuffer(r),s=yield crypto.subtle.importKey("spki",o,{name:"ECDH",namedCurve:"P-256"},!1,[]),a=yield crypto.subtle.deriveBits({name:"ECDH",public:s},i,256),u=yield crypto.subtle.digest("SHA-256",a);return crypto.subtle.importKey("raw",u,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])})}encryptBytes(e,r){return N(this,void 0,void 0,function*(){let n=crypto.getRandomValues(new Uint8Array(12)),i=yield crypto.subtle.encrypt({name:"AES-GCM",iv:n},r,e);return{encrypted:this.bufferToBase64(i),iv:this.bufferToBase64(n.buffer)}})}decryptBytes(e,r,n){return N(this,void 0,void 0,function*(){let i=yield crypto.subtle.decrypt({name:"AES-GCM",iv:this.base64ToBuffer(r)},n,this.base64ToBuffer(e));return new Uint8Array(i)})}};fN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(fN)))(r||fN)}})();fN.\u0275prov=Ce({token:fN,factory:fN.\u0275fac})});var vut=g(()=>{RDr()});var pN,PDr=g(()=>{Se();AH();Re();pN=class extends Zd{deriveSharedKey(e,r){return N(this,void 0,void 0,function*(){return{}})}encryptBytes(e,r){return N(this,void 0,void 0,function*(){let n="";for(let i of e)n+=String.fromCharCode(i);return{encrypted:btoa(n),iv:btoa("mock-iv-12byte")}})}decryptBytes(e,r,n){return N(this,void 0,void 0,function*(){let i=atob(e);return Uint8Array.from(i,o=>o.charCodeAt(0))})}};pN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(pN)))(r||pN)}})();pN.\u0275prov=Ce({token:pN,factory:pN.\u0275fac})});var BDr=g(()=>{PDr()});var Aut=g(()=>{AH();vut();BDr()});function _H(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t))throw new Error(`Invalid UUID 8-4-4-4-12: ${t}`);let e=t.replace(/-/g,"");return[0,4,8,12,16,20,24,28].map(r=>e.slice(r,r+4)).join(":")}function kDr(t){if(!/^[0-9a-f]{1,4}(:[0-9a-f]{1,4}){7}$/.test(t))throw new Error(`Invalid IPv6 literal (8 group form required): ${t}`);let r=t.split(":").map(n=>n.padStart(4,"0")).join("");return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")}var wd,MDr=g(()=>{Se();Re();wd=class{sha256(e){return N(this,void 0,void 0,function*(){let r=new TextEncoder().encode(e),n=yield crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")})}toUuid(e){return N(this,void 0,void 0,function*(){let r=new TextEncoder().encode(e),n=yield crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n).slice(0,16);i[0]=32,i[1]=1,i[2]=0,i[3]=42,i[6]=i[6]&15|128,i[8]=i[8]&63|128;let o=Array.from(i).map(s=>s.toString(16).padStart(2,"0")).join("");return[o.slice(0,8),o.slice(8,12),o.slice(12,16),o.slice(16,20),o.slice(20,32)].join("-")})}};wd.\u0275fac=function(e){return new(e||wd)};wd.\u0275prov=Ce({token:wd,factory:wd.\u0275fac,providedIn:"root"})});var bH=g(()=>{MDr()});var Ab,FDr=g(()=>{bH();Re();Ab=class extends wd{};Ab.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(Ab)))(r||Ab)}})();Ab.\u0275prov=Ce({token:Ab,factory:Ab.\u0275fac})});var Use=g(()=>{FDr()});var LDr=g(()=>{bH();Use()});var Xc,jDr=g(()=>{Se();$se();Re();Xc=class{canonicalStringify(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(i=>this.canonicalStringify(i)).join(",")+"]":"{"+Object.keys(e).sort().filter(i=>e[i]!==void 0).map(i=>JSON.stringify(i)+":"+this.canonicalStringify(e[i])).join(",")+"}"}sign(e,r){return N(this,void 0,void 0,function*(){let n=this.canonicalStringify(e),i=yield this.createSignature(n,r);return{payload:e,signature:i}})}verify(e,r){return N(this,void 0,void 0,function*(){try{let n=this.canonicalStringify(e.payload);return(yield this.verifySignature(n,e.signature,r))?{valid:!0,verifiedBy:r}:{valid:!1,error:"Signature verification failed"}}catch(n){return{valid:!1,error:`Verification error: ${n}`}}})}validateTimestamp(e,r=gDr){let i=(r.now?r.now():Date.now())-e;return i>=0&&i<=r.maxAgeMs}base64ToBuffer(e){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};Xc.\u0275fac=function(e){return new(e||Xc)};Xc.\u0275prov=Ce({token:Xc,factory:Xc.\u0275fac})});var EH=g(()=>{jDr()});var _ut,hN,$Dr=g(()=>{Se();EH();Re();_ut="|||",hN=class extends Xc{createSignature(e,r){return N(this,void 0,void 0,function*(){return btoa(`mock_sig${_ut}${e}${_ut}${r.substring(0,10)}`)})}verifySignature(e,r,n){return N(this,void 0,void 0,function*(){try{let o=atob(r).split(_ut);return o.length===3&&o[0]==="mock_sig"&&o[1]===e}catch{return!1}})}};hN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(hN)))(r||hN)}})();hN.\u0275prov=Ce({token:hN,factory:hN.\u0275fac})});var qDr=g(()=>{$Dr()});var but=g(()=>{EH();qDr()});var Rp,UDr=g(()=>{Re();Rp=class{};Rp.\u0275fac=function(e){return new(e||Rp)};Rp.\u0275prov=Ce({token:Rp,factory:Rp.\u0275fac})});var Qse=g(()=>{UDr()});var mN,QDr=g(()=>{Se();Qse();Re();mN=class extends Rp{constructor(){super(...arguments),this.storage=null,this.backups=[]}save(e){return N(this,void 0,void 0,function*(){this.storage=Object.assign({},e)})}load(){return N(this,void 0,void 0,function*(){return this.storage?Object.assign({},this.storage):null})}exists(){return N(this,void 0,void 0,function*(){return this.storage!==null})}delete(){return N(this,void 0,void 0,function*(){this.storage=null})}saveBackup(e,r){return N(this,void 0,void 0,function*(){this.backups.push({keyPair:Object.assign({},e),rotatedAt:r})})}loadBackups(){return N(this,void 0,void 0,function*(){return this.backups.map(e=>({keyPair:Object.assign({},e.keyPair),rotatedAt:e.rotatedAt}))})}cleanupBackups(e){return N(this,void 0,void 0,function*(){let r=Date.now()-e;this.backups=this.backups.filter(n=>n.rotatedAt>r)})}};mN.\u0275fac=(()=>{let t;return function(r){return(t||(t=fi(mN)))(r||mN)}})();mN.\u0275prov=Ce({token:mN,factory:mN.\u0275fac})});var VDr=g(()=>{QDr()});var xxe=g(()=>{Qse();VDr()});var No,HDr=g(()=>{Se();Re();$se();xxe();Txe();Re();No=class{constructor(){this.keyGenerator=Z(Op),this.storage=Z(Rp),this.keyPair=null,this.peerId=null,this._initialized=ia(!1)}initialize(){return N(this,void 0,void 0,function*(){if(this._initialized())return;let e=yield this.storage.load();e?this.keyPair=e:(this.keyPair=yield this.keyGenerator.generateKeyPair(),yield this.storage.save(this.keyPair)),this.peerId=yield hk(this.keyPair.publicKey),this._initialized.set(!0)})}getKeyPair(){if(!this.keyPair)throw new Error("KeyManager not initialized");return this.keyPair}getPeerId(){if(!this.peerId)throw new Error("KeyManager not initialized");return this.peerId}isInitialized(){return this._initialized()}waitForInitialization(){return N(this,arguments,void 0,function*(e=1e4){if(this._initialized())return;let r=Date.now(),n=50;return new Promise((i,o)=>{let s=()=>{if(this._initialized()){i();return}if(Date.now()-r>e){o(new Error("KeyManager initialization timeout"));return}setTimeout(s,n)};s()})})}reset(){return N(this,void 0,void 0,function*(){yield this.storage.delete(),this.keyPair=null,this.peerId=null,this._initialized.set(!1),yield this.initialize()})}rotateKeyPair(){return N(this,void 0,void 0,function*(){if(!this.keyPair)throw new Error("KeyManager not initialized");yield this.storage.saveBackup(this.keyPair,Date.now());let e=yield this.keyGenerator.generateKeyPair();return yield this.storage.save(e),this.keyPair=e,this.peerId=yield hk(e.publicKey),e})}getBackupKeyPairs(){return N(this,void 0,void 0,function*(){return this.storage.loadBackups()})}cleanupOldBackups(){return N(this,arguments,void 0,function*(e=10080*60*1e3){yield this.storage.cleanupBackups(e)})}};No.\u0275fac=function(e){return new(e||No)};No.\u0275prov=Ce({token:No,factory:No.\u0275fac,providedIn:"root"})});var GDr=g(()=>{HDr()});var zDr=g(()=>{xxe();Txe();Aut();bH();Use();but()});var KDr=g(()=>{zDr()});var Eut=g(()=>{IDr();Txe();Aut();LDr();but();GDr();KDr()});var WDr=g(()=>{xxe()});function SS(t){return[{provide:DH,useFactory:t,multi:!0}]}var DH,YDr=g(()=>{Re();DH=new At("SIGNALING_CHANNELS")});function wS(t){return typeof t=="object"&&t!==null&&"encrypted"in t&&"iv"in t&&typeof t.encrypted=="string"&&typeof t.iv=="string"}var JDr=g(()=>{});var ZDr=g(()=>{});var HI,XDr=g(()=>{Re();HI=new At("SIGNALING_MESSAGE_SENDER")});function eSr(t){return"lost"in t&&t.lost===!0}var tSr=g(()=>{});var rSr=g(()=>{YDr();JDr();ZDr();XDr();tSr()});var _b,nSr=g(()=>{Se();Re();kr();bH();Re();_b=class{constructor(){this.logger=ct("SignalingIdService"),this.hashAdapter=Z(wd)}generateId(e){return N(this,void 0,void 0,function*(){return yield this.hashAdapter.toUuid(e)})}findPublicKeyByHash(e,r){return N(this,void 0,void 0,function*(){for(let n of r)if((yield this.generateId(n))===e)return n;return null})}isHashedId(e){return/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(e)}};_b.\u0275fac=function(e){return new(e||_b)};_b.\u0275prov=Ce({token:_b,factory:_b.\u0275fac,providedIn:"root"})});var iSr=g(()=>{nSr()});var Nxe,mk,oSr=g(()=>{Nxe={prod:{hasuraUrl:"https://graphql-prod.machina.at/v1/graphql",apiNextUrl:"https://api.machina.at",signalingUrl:"https://signaling.machina.at",firebaseDatabaseUrl:"https://x-x-machina-default-rtdb.asia-southeast1.firebasedatabase.app",webServerUrl:"https://server.machina.at",invoiceAppUrl:"https://presenter.machina.at/stable"},stg:{hasuraUrl:"https://graphql-stg.machina.at/v1/graphql",apiNextUrl:"https://api.stg.machina.at",signalingUrl:"https://signaling-stg.machina.at",firebaseDatabaseUrl:"https://x-x-machina-stg.asia-southeast1.firebasedatabase.app",webServerUrl:"https://server.machina.at",invoiceAppUrl:"https://presenter.machina.at/stable"}},mk={PLANX_GRAPHQL_URL:Nxe.prod.hasuraUrl,PLANX_CLOUD_API_URL:Nxe.prod.apiNextUrl,PLANX_SIGNALING_URL:Nxe.prod.signalingUrl,PLANX_FIREBASE_DATABASE_URL:Nxe.prod.firebaseDatabaseUrl,PLANX_SIGNALING_BACKEND:"",PLANX_NOSTR_RELAYS:"wss://nos.lol,wss://relay.snort.social"}});var Oxe=g(()=>{oSr()});var GI,sSr=g(()=>{Re();GI=new At("TRPC_CLIENT")});var gk,aSr=g(()=>{gk=class t{static in(e,r){return new t(e,r)}constructor(e,r){var n;this.controller=new AbortController,this.timer=null,this.now=(n=r?.now)!==null&&n!==void 0?n:(()=>Date.now()),this.at=this.now()+Math.max(0,e);let i=()=>this.abort();e<=0?i():this.timer=setTimeout(i,e),r?.parent&&(r.parent.aborted?i():r.parent.addEventListener("abort",i,{once:!0}))}get signal(){return this.controller.signal}remaining(){return Math.max(0,this.at-this.now())}expired(){return this.remaining()===0}child(e){return new t(Math.min(e,this.remaining()),{now:this.now,parent:this.signal})}split(e){let r=Math.min(1,Math.max(0,e));return this.child(Math.floor(this.remaining()*r))}abort(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.controller.signal.aborted||this.controller.abort()}dispose(){this.abort()}}});var uSr=g(()=>{sSr();aSr()});var MTi,FTi,LTi,jTi,$Ti,Wn,lSr=g(()=>{MTi={name:"port-forward",prefix:"pf:",profile:"reliable-ordered",defaultCap:1e3,defaultBackpressureProfile:"http",buildLabel:t=>`pf:${t}`,parseLabel:t=>t.startsWith("pf:")?t.slice(3):null},FTi={name:"heartbeat",prefix:"__heartbeat__",profile:"heartbeat",defaultCap:1,defaultBackpressureProfile:"control",buildLabel:()=>"__heartbeat__",parseLabel:t=>t==="__heartbeat__"?"":null},LTi={name:"l7-http",prefix:"l7:http:",profile:"reliable-ordered",defaultCap:1e3,defaultBackpressureProfile:"http",buildLabel:t=>`l7:http:${t}`,parseLabel:t=>t.startsWith("l7:http:")?t.slice(8):null},jTi={name:"l7-datagram",prefix:"l7:dg:",profile:"unreliable",defaultCap:8,defaultBackpressureProfile:"terminal",buildLabel:t=>`l7:dg:${t}`,parseLabel:t=>t.startsWith("l7:dg:")?t.slice(6):null},$Ti={name:"l7-qpack",prefix:"l7:qpack:",profile:"reliable-ordered",defaultCap:8,defaultBackpressureProfile:"control",buildLabel:t=>`l7:qpack:${t}`,parseLabel:t=>t.startsWith("l7:qpack:")?t.slice(9):null},Wn={portForward:MTi,heartbeat:FTi,l7Http:LTi,l7Dg:jTi,l7Qpack:$Ti}});var cSr=g(()=>{lSr()});function Sut(t){return function(e,r,n){let i=Reflect.getMetadata(Dut,e.constructor)||[];return i.push({messageType:t,methodName:r}),Reflect.defineMetadata(Dut,i,e.constructor),n}}function dSr(t){return Reflect.getMetadata(Dut,t.constructor)||[]}var Dut,fSr=g(()=>{dte();Dut=Symbol("messageHandlers")});var wut=g(()=>{fSr()});var Rxe,SH,pSr=g(()=>{Se();kr();wut();Rxe=class extends Error{constructor(e){super(`No handler found for message type: ${e}`),this.messageType=e,this.code="HANDLER_NOT_FOUND",this.name="HandlerNotFoundError"}},SH=class{constructor(){this.logger=ct(this.constructor.name)}handle(e,r){return N(this,void 0,void 0,function*(){let i=dSr(e).find(o=>o.messageType===r.type);if(i){let o=e[i.methodName];typeof o=="function"&&(yield o.call(e,r))}else throw this.logger.warn("No handler found for message type:",r.type),new Rxe(r.type)})}}});var hSr=g(()=>{wut();pSr()});function Cut(t){return t.replace(/^http(s?):\/\//,"ws$1://")}var mSr=g(()=>{});function Pxe(t,e){let r=_H(t),n=e.replace(/^\//,"");return`https://[${r}]:10/${n}`}var gSr=g(()=>{Eut()});var Iut=g(()=>{mSr();gSr()});var Mn=g(()=>{bDr();Eut();WDr();rSr();iSr();Oxe();uSr();cSr();hSr();Iut()});var Bxe,ySr=g(()=>{Mn();Mn();Bxe=class extends SH{}});var vSr=g(()=>{ySr()});import*as gN from"node:fs";import*as ASr from"node:path";var bb,Tut=g(()=>{kr();Re();bb=class t{constructor(){this.logger=ct("SessionOutputRecorderService"),this.fd=null,this.buffer=[],this.flushTimer=null,this.enabled=!1}start(e){this.enabled=!0;let r=t.DIR;gN.mkdirSync(r,{recursive:!0});let n=`${e.slice(0,16)}_${Date.now()}.jsonl`,i=ASr.join(r,n);this.fd=gN.openSync(i,"a"),this.flushTimer=setInterval(()=>this.flush(),t.FLUSH_INTERVAL_MS),this.logger.info("Recording started",{filepath:i})}record(e){if(!this.enabled)return;let r=JSON.stringify(Object.assign({ts:performance.now(),iso:new Date().toISOString()},e));this.buffer.push(r)}flush(){if(this.buffer.length===0||this.fd===null)return;let e=this.buffer.join(`
|
|
553
553
|
`)+`
|
|
554
|
-
`;this.buffer=[];let r=Buffer.from(e);gN.write(this.fd,r,0,r.length,null,n=>{n&&this.logger.error("Write error",{error:n})})}stop(){this.enabled=!1,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush(),this.fd!==null&&(gN.closeSync(this.fd),this.fd=null),this.logger.info("Recording stopped")}};bb.FLUSH_INTERVAL_MS=500;bb.DIR="/tmp/planx/logs/sessions";bb.\u0275fac=function(e){return new(e||bb)};bb.\u0275prov=Ce({token:bb,factory:bb.\u0275fac,providedIn:"root"})});function qTi(){return N(this,void 0,void 0,function*(){return yield import("@fails-components/webtransport")})}var Vse,_Sr=g(()=>{Se();Vse=class t{constructor(e){var r;this.opts=e,this.server=null,this.sessionLoopActive=!1,this.assignedPort=null,this.pathPrefix=(r=e.pathPrefix)!==null&&r!==void 0?r:"/sessions",this.pathPattern=`${this.pathPrefix}/*`}start(){return N(this,void 0,void 0,function*(){var e;if(this.server)return;let r=yield qTi(),n=this.opts.port;if(n===0){let{createSocket:o}=yield import("dgram");n=yield new Promise((s,a)=>{let u=o("udp4");u.bind(0,"127.0.0.1",()=>{let l=u.address(),c=typeof l=="object"&&l!==null?l.port:0;u.close(()=>s(c))}),u.on("error",a)}),this.assignedPort=n}let i=new r.Http3Server({port:n,host:t.BIND_HOST,secret:"session-wt-output",cert:this.opts.cert,privKey:this.opts.privKey});(e=i.setRequestCallback)===null||e===void 0||e.call(i,o=>Promise.resolve(t.buildRequestResult(this.pathPrefix,o.header))),i.startServer(),yield i.ready,this.server=i,this.sessionLoopActive=!0,this.runSessionLoop()})}static buildRequestResult(e,r){var n;let i=(n=r[":path"])!==null&&n!==void 0?n:"";return t.parseSessionPath(e,i)!==null?{path:e,status:200}:{path:i,status:404}}stop(){return N(this,void 0,void 0,function*(){this.sessionLoopActive=!1,this.server&&(yield this.server.stopServer(),this.server=null)})}getBindHost(){return t.BIND_HOST}isRunning(){return this.server!==null}getListenPort(){var e,r,n;if(!this.server)return null;if(this.opts.port>0)return this.opts.port;if(this.assignedPort!==null)return this.assignedPort;let i=(r=(e=this.server).address)===null||r===void 0?void 0:r.call(e);return(n=i?.port)!==null&&n!==void 0?n:null}static parseSessionPath(e,r){let n=r.split("?")[0],i=[["output","/output"],["input","/input"]];for(let[o,s]of i){if(!n.startsWith(`${e}/`)||!n.endsWith(s))continue;let a=n.slice(e.length+1,n.length-s.length);if(a.length>0&&!a.includes("/"))return{sessionId:a,direction:o}}return null}static extractSessionId(e,r){let n=t.parseSessionPath(e,r);return n?.direction==="output"?n.sessionId:null}runSessionLoop(){return N(this,void 0,void 0,function*(){if(!this.server)return;let e=this.server.sessionStream(this.pathPrefix).getReader();yield this.consumeSessions(e)})}consumeSessions(e){return N(this,void 0,void 0,function*(){for(var r,n,i,o;this.sessionLoopActive;){let s,a;try{({value:s,done:a}=yield e.read())}catch(u){(n=(r=this.opts).log)===null||n===void 0||n.call(r,"error","session stream read error",t.serializeErr(u));return}if(a)return;if(s)try{this.handleSession(s)}catch(u){(o=(i=this.opts).log)===null||o===void 0||o.call(i,"error","session handler error (isolated)",t.serializeErr(u)),t.safeCloseSession(s)}}})}static serializeErr(e){var r;if(e instanceof Error)return(r=e.stack)!==null&&r!==void 0?r:`${e.name}: ${e.message}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}static safeCloseSession(e){return N(this,void 0,void 0,function*(){var r;try{yield(r=e.close)===null||r===void 0?void 0:r.call(e,{closeCode:404,reason:"session not found"})}catch{}})}handleSession(e){var r,n,i,o,s,a,u,l,c,f,h,m,A,E,b,S;let w=(i=(n=(r=e.header)===null||r===void 0?void 0:r[":path"])!==null&&n!==void 0?n:e.path)!==null&&i!==void 0?i:"";console.error("[wt-output-endpoint] handleSession entered",{":path":(s=(o=e.header)===null||o===void 0?void 0:o[":path"])!==null&&s!==void 0?s:"<no-header>","session.path":(a=e.path)!==null&&a!==void 0?a:"<no-shim>",resolvedPath:w,hasOnOutputSession:!!this.opts.onOutputSession,hasOnInputSession:!!this.opts.onInputSession});let C=t.parseSessionPath(this.pathPrefix,w);if(C===null){(l=(u=this.opts).log)===null||l===void 0||l.call(u,"warn","incoming session with invalid path",{path:w}),console.error("[wt-output-endpoint] SILENT FAIL: parseSessionPath returned null",{pathPrefix:this.pathPrefix,path:w});return}let{sessionId:x,direction:B}=C;if(B==="input"){(f=(c=this.opts).log)===null||f===void 0||f.call(c,"info","incoming input session",{sessionId:x,path:w}),console.error("[wt-output-endpoint] dispatching onInputSession",{sessionId:x,path:w}),(m=(h=this.opts).onInputSession)===null||m===void 0||m.call(h,x,e);return}(E=(A=this.opts).log)===null||E===void 0||E.call(A,"info","incoming output session",{sessionId:x,path:w}),console.error("[wt-output-endpoint] dispatching onOutputSession",{sessionId:x,path:w}),(S=(b=this.opts).onOutputSession)===null||S===void 0||S.call(b,x,e)}};Vse.BIND_HOST="127.0.0.1"});var bSr=g(()=>{_Sr()});import{createServer as UTi}from"http";import{Http2ServerRequest as QTi}from"http2";import{Http2ServerRequest as xut}from"http2";import{Readable as ESr}from"stream";import txi from"crypto";async function ZTi(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function CSr(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(s,i),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function i(a){a&&e.destroy(a)}function o(){t.read().then(s,i)}function s({done:a,value:u}){try{if(a)e.end();else if(!e.write(u))e.once("drain",o);else return t.read().then(s,i)}catch(l){i(l)}}}function XTi(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:CSr(t.getReader(),e)}var yk,VTi,HTi,Hse,GTi,SSr,zTi,IH,KTi,kxe,Mxe,WTi,CH,YTi,Fxe,JTi,DSr,wH,vk,Out,Gse,ISr,exi,rxi,Rut,nxi,TSr,Nut,xSr,NSr,ixi,oxi,sxi,axi,CS,TH=g(()=>{yk=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},VTi=t=>t instanceof yk?t:new yk(t.message,{cause:t}),HTi=global.Request,Hse=class extends HTi{constructor(t,e){typeof t=="object"&&IH in t&&(t=t[IH]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},GTi=t=>{let e=[],r=t.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:i,[n+1]:o}=r;i.charCodeAt(0)!==58&&e.push([i,o])}return new Headers(e)},SSr=Symbol("wrapBodyStream"),zTi=(t,e,r,n,i)=>{let o={method:t,headers:r,signal:i.signal};if(t==="TRACE"){o.method="GET";let s=new Hse(e,o);return Object.defineProperty(s,"method",{get(){return"TRACE"}}),s}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)o.body=new ReadableStream({start(s){s.enqueue(n.rawBody),s.close()}});else if(n[SSr]){let s;o.body=new ReadableStream({async pull(a){try{s||=ESr.toWeb(n).getReader();let{done:u,value:l}=await s.read();u?a.close():a.enqueue(l)}catch(u){a.error(u)}}})}else o.body=ESr.toWeb(n);return new Hse(e,o)},IH=Symbol("getRequestCache"),KTi=Symbol("requestCache"),kxe=Symbol("incomingKey"),Mxe=Symbol("urlKey"),WTi=Symbol("headersKey"),CH=Symbol("abortControllerKey"),YTi=Symbol("getAbortController"),Fxe={get method(){return this[kxe].method||"GET"},get url(){return this[Mxe]},get headers(){return this[WTi]||=GTi(this[kxe])},[YTi](){return this[IH](),this[CH]},[IH](){return this[CH]||=new AbortController,this[KTi]||=zTi(this.method,this[Mxe],this.headers,this[kxe],this[CH])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(Fxe,t,{get(){return this[IH]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Fxe,t,{value:function(){return this[IH]()[t]()}})});Object.setPrototypeOf(Fxe,Hse.prototype);JTi=(t,e)=>{let r=Object.create(Fxe);r[kxe]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof xut)throw new yk("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[Mxe]=a.href}catch(a){throw new yk("Invalid absolute URL",{cause:a})}return r}let i=(t instanceof xut?t.authority:t.headers.host)||e;if(!i)throw new yk("Missing host header");let o;if(t instanceof xut){if(o=t.scheme,!(o==="http"||o==="https"))throw new yk("Unsupported scheme")}else o=t.socket&&t.socket.encrypted?"https":"http";let s=new URL(`${o}://${i}${n}`);if(s.hostname.length!==i.length&&s.hostname!==i.replace(/:\d+$/,""))throw new yk("Invalid host header");return r[Mxe]=s.href,r},DSr=Symbol("responseCache"),wH=Symbol("getResponseCache"),vk=Symbol("cache"),Out=global.Response,Gse=class wSr{#t;#e;[wH](){return delete this[vk],this[DSr]||=new Out(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof wSr){let i=r[DSr];if(i){this.#e=i,this[wH]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(n||=r?.headers||{"content-type":"text/plain; charset=UTF-8"},this[vk]=[r?.status||200,e,n])}get headers(){let e=this[vk];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[wH]().headers}get status(){return this[vk]?.[0]??this[wH]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Gse.prototype,t,{get(){return this[wH]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Gse.prototype,t,{value:function(){return this[wH]()[t]()}})});Object.setPrototypeOf(Gse,Out);Object.setPrototypeOf(Gse.prototype,Out.prototype);ISr=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[n,i]of t)n==="set-cookie"?r.push(i):e[n]=i;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},exi="x-hono-already-sent",rxi=global.fetch;typeof global.crypto>"u"&&(global.crypto=txi);global.fetch=(t,e)=>(e={compress:!1,...e},rxi(t,e));Rut=Symbol("outgoingEnded"),nxi=()=>new Response(null,{status:400}),TSr=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Nut=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},xSr=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},NSr=async(t,e)=>{let[r,n,i]=t[vk];i instanceof Headers&&(i=ISr(i)),typeof n=="string"?i["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?i["Content-Length"]=n.byteLength:n instanceof Blob&&(i["Content-Length"]=n.size),e.writeHead(r,i),typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(xSr(e),await XTi(n,e)?.catch(o=>Nut(o,e))),e[Rut]?.()},ixi=t=>typeof t.then=="function",oxi=async(t,e,r={})=>{if(ixi(t))if(r.errorHandler)try{t=await t}catch(i){let o=await r.errorHandler(i);if(!o)return;t=o}else t=await t.catch(TSr);if(vk in t)return NSr(t,e);let n=ISr(t.headers);if(t.body){let i=t.body.getReader(),o=[],s=!1,a;if(n["transfer-encoding"]!=="chunked"){let u=2;for(let l=0;l<u;l++){a||=i.read();let c=await ZTi(a).catch(f=>{console.error(f),s=!0});if(!c){if(l===1){await new Promise(f=>setTimeout(f)),u=3;continue}break}if(a=void 0,c.value&&o.push(c.value),c.done){s=!0;break}}s&&!("content-length"in n)&&(n["content-length"]=o.reduce((l,c)=>l+c.length,0))}e.writeHead(t.status,n),o.forEach(u=>{e.write(u)}),s?e.end():(o.length===0&&xSr(e),await CSr(i,e,a))}else n[exi]||(e.writeHead(t.status,n),e.end());e[Rut]?.()},sxi=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Hse&&(Object.defineProperty(global,"Request",{value:Hse}),Object.defineProperty(global,"Response",{value:Gse})),async(n,i)=>{let o,s;try{s=JTi(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[SSr]=!0,n.on("end",()=>{a=!0}),n instanceof QTi&&(i[Rut]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),i.destroy()})})})),i.on("close",()=>{s[CH]&&(n.errored?s[CH].abort(n.errored.toString()):i.writableFinished||s[CH].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),o=t(s,{incoming:n,outgoing:i}),vk in o)return NSr(o,i)}catch(a){if(o)return Nut(a,i);if(e.errorHandler){if(o=await e.errorHandler(s?a:VTi(a)),!o)return}else s?o=TSr(a):o=nxi()}try{return await oxi(o,i,e)}catch(a){return Nut(a,i)}}},axi=t=>{let e=t.fetch,r=sxi(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||UTi)(t.serverOptions||{},r)},CS=(t,e)=>{let r=axi(t);return r.listen(t?.port??3e3,t.hostname,()=>{let n=r.address();e&&e(n)}),r}});var Put,OSr=g(()=>{Put=(t,e,r)=>(n,i)=>{let o=-1;return s(0);async function s(a){if(a<=o)throw new Error("next() called multiple times");o=a;let u,l=!1,c;if(t[a]?(c=t[a][0][0],n.req.routeIndex=a):c=a===t.length&&i||void 0,c)try{u=await c(n,()=>s(a+1))}catch(f){if(f instanceof Error&&e)n.error=f,u=await e(f,n),l=!0;else throw f}else n.finalized===!1&&r&&(u=await r(n));return u&&(n.finalized===!1||l)&&(n.res=u),n}}});var RSr=g(()=>{});var PSr,BSr=g(()=>{PSr=Symbol()});async function uxi(t,e){let r=await t.formData();return r?lxi(r,e):{}}function lxi(t,e){let r=Object.create(null);return t.forEach((n,i)=>{e.all||i.endsWith("[]")?cxi(r,i,n):r[i]=n}),e.dot&&Object.entries(r).forEach(([n,i])=>{n.includes(".")&&(dxi(r,n,i),delete r[n])}),r}var kSr,cxi,dxi,MSr=g(()=>{But();kSr=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,o=(t instanceof Lxe?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?uxi(t,{all:r,dot:n}):{}};cxi=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},dxi=(t,e,r)=>{let n=t,i=e.split(".");i.forEach((o,s)=>{s===i.length-1?n[o]=r:((!n[o]||typeof n[o]!="object"||Array.isArray(n[o])||n[o]instanceof File)&&(n[o]=Object.create(null)),n=n[o])})}});var Mut,FSr,fxi,pxi,jxe,LSr,$xe,hxi,Fut,jSr,Ak,qxe,kut,$Sr,qSr,USr,Lut,xH=g(()=>{Mut=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},FSr=t=>{let{groups:e,path:r}=fxi(t),n=Mut(r);return pxi(n,e)},fxi=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let i=`@${n}`;return e.push([i,r]),i}),{groups:e,path:t}},pxi=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let i=t.length-1;i>=0;i--)if(t[i].includes(n)){t[i]=t[i].replace(n,e[r][1]);break}}return t},jxe={},LSr=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return jxe[n]||(r[2]?jxe[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:jxe[n]=[t,r[1],!0]),jxe[n]}return null},$xe=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},hxi=t=>$xe(t,decodeURI),Fut=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let i=e.charCodeAt(n);if(i===37){let o=e.indexOf("?",n),s=e.slice(r,o===-1?void 0:o);return hxi(s.includes("%25")?s.replace(/%25/g,"%2525"):s)}else if(i===63)break}return e.slice(r,n)},jSr=t=>{let e=Fut(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Ak=(t,e,...r)=>(r.length&&(e=Ak(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),qxe=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(i=>{if(i!==""&&!/\:/.test(i))n+="/"+i;else if(/\:/.test(i))if(/\?/.test(i)){r.length===0&&n===""?r.push("/"):r.push(n);let o=i.replace("?","");n+="/"+o,r.push(n)}else n+="/"+i}),r.filter((i,o,s)=>s.indexOf(i)===o)},kut=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?$xe(t,Lut):t):t,$Sr=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let s=t.indexOf(`?${e}`,8);for(s===-1&&(s=t.indexOf(`&${e}`,8));s!==-1;){let a=t.charCodeAt(s+e.length+1);if(a===61){let u=s+e.length+2,l=t.indexOf("&",u);return kut(t.slice(u,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";s=t.indexOf(`&${e}`,s+1)}if(n=/[%+]/.test(t),!n)return}let i={};n??=/[%+]/.test(t);let o=t.indexOf("?",8);for(;o!==-1;){let s=t.indexOf("&",o+1),a=t.indexOf("=",o);a>s&&s!==-1&&(a=-1);let u=t.slice(o+1,a===-1?s===-1?void 0:s:a);if(n&&(u=kut(u)),o=s,u==="")continue;let l;a===-1?l="":(l=t.slice(a+1,s===-1?void 0:s),n&&(l=kut(l))),r?(i[u]&&Array.isArray(i[u])||(i[u]=[]),i[u].push(l)):i[u]??=l}return e?i[e]:i},qSr=$Sr,USr=(t,e)=>$Sr(t,e,!0),Lut=decodeURIComponent});var QSr,Lxe,But=g(()=>{RSr();BSr();MSr();xH();QSr=t=>$xe(t,Lut),Lxe=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#o()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#i(e);return r&&/\%/.test(r)?QSr(r):r}#o(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#i(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?QSr(n):n)}return t}#i(t){return this.#e[1]?this.#e[1][t]:t}query(t){return qSr(this.url,t)}queries(t){return USr(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return this.bodyCache.parsedBody??=await kSr(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let i=Object.keys(e)[0];return i?e[i].then(o=>(i==="json"&&(o=JSON.stringify(o)),new Response(o)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[PSr](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}}});var Uxe,mxi,zse,jut=g(()=>{Uxe={Stringify:1,BeforeStream:2,Stream:3},mxi=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r},zse=async(t,e,r,n,i)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let o=t.callbacks;if(!o?.length)return Promise.resolve(t);i?i[0]+=t:i=[t];let s=Promise.all(o.map(a=>a({phase:e,buffer:i,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(u=>zse(u,e,!1,n,i))).then(()=>i[0]));return r?mxi(await s,o):s}});var VSr,$ut,HSr,qut=g(()=>{But();jut();VSr="text/plain; charset=UTF-8",$ut=(t,e)=>({"Content-Type":t,...e}),HSr=class{#t;#e;env={};#r;finalized=!1;error;#o;#i;#n;#c;#u;#l;#a;#d;#f;constructor(t,e){this.#t=t,e&&(this.#i=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#f=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Lxe(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=new Response(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=new Response(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let i of n)t.headers.append("set-cookie",i)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#u??=e=>this.html(e),this.#u(...t));setLayout=t=>this.#c=t;getLayout=()=>this.#c;setRenderer=t=>{this.#u=t};header=(t,e,r)=>{this.finalized&&(this.#n=new Response(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#o=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#s(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[s,a]of o)s.toLowerCase()==="set-cookie"?n.append(s,a):n.set(s,a)}if(r)for(let[o,s]of Object.entries(r))if(typeof s=="string")n.set(o,s);else{n.delete(o);for(let a of s)n.append(o,a)}let i=typeof e=="number"?e:e?.status??this.#o;return new Response(t,{status:i,headers:n})}newResponse=(...t)=>this.#s(...t);body=(t,e,r)=>this.#s(t,e,r);text=(t,e,r)=>!this.#a&&!this.#o&&!e&&!r&&!this.finalized?new Response(t):this.#s(t,e,$ut(VSr,r));json=(t,e,r)=>this.#s(JSON.stringify(t),e,$ut("application/json",r));html=(t,e,r)=>{let n=i=>this.#s(i,e,$ut("text/html; charset=UTF-8",r));return typeof t=="object"?zse(t,Uxe.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))}});var Sl,GSr,zSr,Qxe,Vxe,_k=g(()=>{Sl="ALL",GSr="all",zSr=["get","post","put","delete","options","patch"],Qxe="Can not add a route since the matcher is already built.",Vxe=class extends Error{}});var KSr,WSr=g(()=>{KSr="__COMPOSED_HANDLER"});var gxi,YSr,Uut,JSr=g(()=>{OSr();qut();_k();WSr();xH();gxi=t=>t.text("404 Not Found",404),YSr=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Uut=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...zSr,GSr].forEach(i=>{this[i]=(o,...s)=>(typeof o=="string"?this.#t=o:this.#o(i,this.#t,o),s.forEach(a=>{this.#o(i,this.#t,a)}),this)}),this.on=(i,o,...s)=>{for(let a of[o].flat()){this.#t=a;for(let u of[i].flat())s.map(l=>{this.#o(u.toUpperCase(),this.#t,l)})}return this},this.use=(i,...o)=>(typeof i=="string"?this.#t=i:(this.#t="*",o.unshift(i)),o.forEach(s=>{this.#o(Sl,this.#t,s)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??Fut:jSr}#e(){let t=new Uut({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=gxi;errorHandler=YSr;route(t,e){let r=this.basePath(t);return e.routes.map(n=>{let i;e.errorHandler===YSr?i=n.handler:(i=async(o,s)=>(await Put([],e.errorHandler)(o,()=>n.handler(o,s))).res,i[KSr]=n.handler),r.#o(n.method,n.path,i)}),this}basePath(t){let e=this.#e();return e._basePath=Ak(this._basePath,t),e}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,e,r){let n,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===!1?n=a=>a:n=r.replaceRequest));let o=i?a=>{let u=i(a);return Array.isArray(u)?u:[u]}:a=>{let u;try{u=a.executionCtx}catch{}return[a.env,u]};n||=(()=>{let a=Ak(this._basePath,t),u=a==="/"?0:a.length;return l=>{let c=new URL(l.url);return c.pathname=c.pathname.slice(u)||"/",new Request(c,l)}})();let s=async(a,u)=>{let l=await e(n(a.req.raw),...o(a));if(l)return l;await u()};return this.#o(Sl,Ak(t,"*"),s),this}#o(t,e,r){t=t.toUpperCase(),e=Ak(this._basePath,e);let n={basePath:this._basePath,path:e,method:t,handler:r};this.router.add(t,e,[r,n]),this.routes.push(n)}#i(t,e){if(t instanceof Error)return this.errorHandler(t,e);throw t}#n(t,e,r,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(t,e,r,"GET")))();let i=this.getPath(t,{env:r}),o=this.router.match(n,i),s=new HSr(t,{path:i,matchResult:o,env:r,executionCtx:e,notFoundHandler:this.#r});if(o[0].length===1){let u;try{u=o[0][0][0][0](s,async()=>{s.res=await this.#r(s)})}catch(l){return this.#i(l,s)}return u instanceof Promise?u.then(l=>l||(s.finalized?s.res:this.#r(s))).catch(l=>this.#i(l,s)):u??this.#r(s)}let a=Put(o[0],this.errorHandler,this.#r);return(async()=>{try{let u=await a(s);if(!u.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#i(u,s)}})()}fetch=(t,...e)=>this.#n(t,e[1],e[0],t.method);request=(t,e,r,n)=>t instanceof Request?this.fetch(e?new Request(t,e):t,r,n):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Ak("/",t)}`,e),r,n));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}}});function Qut(t,e){let r=this.buildAllMatchers(),n=(i,o)=>{let s=r[i]||r[Sl],a=s[2][o];if(a)return a;let u=o.match(s[0]);if(!u)return[[],Hxe];let l=u.indexOf("",1);return[s[1][l],u]};return this.match=n,n(t,e)}var Hxe,Vut=g(()=>{_k();Hxe=[]});function vxi(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===Kse||t===Wse?1:e===Kse||e===Wse?-1:t===Gxe?1:e===Gxe?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Gxe,Kse,Wse,bk,yxi,zxe,Hut=g(()=>{Gxe="[^/]+",Kse=".*",Wse="(?:|/.*)",bk=Symbol(),yxi=new Set(".\\+*[^]$()");zxe=class{#t;#e;#r=Object.create(null);insert(t,e,r,n,i){if(t.length===0){if(this.#t!==void 0)throw bk;if(i)return;this.#t=e;return}let[o,...s]=t,a=o==="*"?s.length===0?["","",Kse]:["","",Gxe]:o==="/*"?["","",Wse]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(a){let l=a[1],c=a[2]||Gxe;if(l&&a[2]&&(c===".*"||(c=c.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(c))))throw bk;if(u=this.#r[c],!u){if(Object.keys(this.#r).some(f=>f!==Kse&&f!==Wse))throw bk;if(i)return;u=this.#r[c]=new zxe,l!==""&&(u.#e=n.varIndex++)}!i&&l!==""&&r.push([l,u.#e])}else if(u=this.#r[o],!u){if(Object.keys(this.#r).some(l=>l.length>1&&l!==Kse&&l!==Wse))throw bk;if(i)return;u=this.#r[o]=new zxe}u.insert(s,e,r,n,i)}buildRegExpStr(){let e=Object.keys(this.#r).sort(vxi).map(r=>{let n=this.#r[r];return(typeof n.#e=="number"?`(${r})@${n.#e}`:yxi.has(r)?`\\${r}`:r)+n.buildRegExpStr()});return typeof this.#t=="number"&&e.unshift(`#${this.#t}`),e.length===0?"":e.length===1?e[0]:"(?:"+e.join("|")+")"}}});var ZSr,XSr=g(()=>{Hut();ZSr=class{#t={varIndex:0};#e=new zxe;insert(t,e,r){let n=[],i=[];for(let s=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,u=>{let l=`@\\${s}`;return i[s]=[l,u],s++,a=!0,l}),!a)break}let o=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=i.length-1;s>=0;s--){let[a]=i[s];for(let u=o.length-1;u>=0;u--)if(o[u].indexOf(a)!==-1){o[u]=o[u].replace(a,i[s][1]);break}}return this.#e.insert(o,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,o,s)=>o!==void 0?(r[++e]=Number(o),"$()"):(s!==void 0&&(n[Number(s)]=++e),"")),[new RegExp(`^${t}`),r,n]}}});function twr(t){return ewr[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function _xi(){ewr=Object.create(null)}function bxi(t){let e=new ZSr,r=[];if(t.length===0)return Axi;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,c],[f,h])=>l?1:f?-1:c.length-h.length),i=Object.create(null);for(let l=0,c=-1,f=n.length;l<f;l++){let[h,m,A]=n[l];h?i[m]=[A.map(([b])=>[b,Object.create(null)]),Hxe]:c++;let E;try{E=e.insert(m,c,h)}catch(b){throw b===bk?new Vxe(m):b}h||(r[c]=A.map(([b,S])=>{let w=Object.create(null);for(S-=1;S>=0;S--){let[C,x]=E[S];w[C]=x}return[b,w]}))}let[o,s,a]=e.buildRegExp();for(let l=0,c=r.length;l<c;l++)for(let f=0,h=r[l].length;f<h;f++){let m=r[l][f]?.[1];if(!m)continue;let A=Object.keys(m);for(let E=0,b=A.length;E<b;E++)m[A[E]]=a[m[A[E]]]}let u=[];for(let l in s)u[l]=r[s[l]];return[o,u,i]}function NH(t,e){if(t){for(let r of Object.keys(t).sort((n,i)=>i.length-n.length))if(twr(r).test(e))return[...t[r]]}}var Axi,ewr,Kxe,Gut=g(()=>{_k();xH();Vut();Hut();XSr();Axi=[/^$/,[],Object.create(null)],ewr=Object.create(null);Kxe=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[Sl]:Object.create(null)},this.#e={[Sl]:Object.create(null)}}add(t,e,r){let n=this.#t,i=this.#e;if(!n||!i)throw new Error(Qxe);n[t]||[n,i].forEach(a=>{a[t]=Object.create(null),Object.keys(a[Sl]).forEach(u=>{a[t][u]=[...a[Sl][u]]})}),e==="/*"&&(e="*");let o=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=twr(e);t===Sl?Object.keys(n).forEach(u=>{n[u][e]||=NH(n[u],e)||NH(n[Sl],e)||[]}):n[t][e]||=NH(n[t],e)||NH(n[Sl],e)||[],Object.keys(n).forEach(u=>{(t===Sl||t===u)&&Object.keys(n[u]).forEach(l=>{a.test(l)&&n[u][l].push([r,o])})}),Object.keys(i).forEach(u=>{(t===Sl||t===u)&&Object.keys(i[u]).forEach(l=>a.test(l)&&i[u][l].push([r,o]))});return}let s=qxe(e)||[e];for(let a=0,u=s.length;a<u;a++){let l=s[a];Object.keys(i).forEach(c=>{(t===Sl||t===c)&&(i[c][l]||=[...NH(n[c],l)||NH(n[Sl],l)||[]],i[c][l].push([r,o-u+a+1]))})}}match=Qut;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,_xi(),t}#r(t){let e=[],r=t===Sl;return[this.#t,this.#e].forEach(n=>{let i=n[t]?Object.keys(n[t]).map(o=>[o,n[t][o]]):[];i.length!==0?(r||=!0,e.push(...i)):t!==Sl&&e.push(...Object.keys(n[Sl]).map(o=>[o,n[Sl][o]]))}),r?bxi(e):null}}});var rwr=g(()=>{_k();Vut();Gut()});var nwr=g(()=>{Gut();rwr()});var zut,iwr=g(()=>{_k();zut=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(Qxe);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,i=r.length,o=0,s;for(;o<i;o++){let a=r[o];try{for(let u=0,l=n.length;u<l;u++)a.add(...n[u]);s=a.match(t,e)}catch(u){if(u instanceof Vxe)continue;throw u}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===i)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}}});var owr=g(()=>{iwr()});var Yse,Kut,swr=g(()=>{_k();xH();Yse=Object.create(null),Kut=class{#t;#e;#r;#o=0;#i=Yse;constructor(t,e,r){if(this.#e=r||Object.create(null),this.#t=[],t&&e){let n=Object.create(null);n[t]={handler:e,possibleKeys:[],score:0},this.#t=[n]}this.#r=[]}insert(t,e,r){this.#o=++this.#o;let n=this,i=FSr(e),o=[];for(let s=0,a=i.length;s<a;s++){let u=i[s],l=i[s+1],c=LSr(u,l),f=Array.isArray(c)?c[0]:u;if(f in n.#e){n=n.#e[f],c&&o.push(c[1]);continue}n.#e[f]=new Kut,c&&(n.#r.push(c),o.push(c[1])),n=n.#e[f]}return n.#t.push({[t]:{handler:r,possibleKeys:o.filter((s,a,u)=>u.indexOf(s)===a),score:this.#o}}),n}#n(t,e,r,n){let i=[];for(let o=0,s=t.#t.length;o<s;o++){let a=t.#t[o],u=a[e]||a[Sl],l={};if(u!==void 0&&(u.params=Object.create(null),i.push(u),r!==Yse||n&&n!==Yse))for(let c=0,f=u.possibleKeys.length;c<f;c++){let h=u.possibleKeys[c],m=l[u.score];u.params[h]=n?.[h]&&!m?n[h]:r[h]??n?.[h],l[u.score]=!0}}return i}search(t,e){let r=[];this.#i=Yse;let i=[this],o=Mut(e),s=[];for(let a=0,u=o.length;a<u;a++){let l=o[a],c=a===u-1,f=[];for(let h=0,m=i.length;h<m;h++){let A=i[h],E=A.#e[l];E&&(E.#i=A.#i,c?(E.#e["*"]&&r.push(...this.#n(E.#e["*"],t,A.#i)),r.push(...this.#n(E,t,A.#i))):f.push(E));for(let b=0,S=A.#r.length;b<S;b++){let w=A.#r[b],C=A.#i===Yse?{}:{...A.#i};if(w==="*"){let V=A.#e["*"];V&&(r.push(...this.#n(V,t,A.#i)),V.#i=C,f.push(V));continue}let[x,B,L]=w;if(!l&&!(L instanceof RegExp))continue;let $=A.#e[x],Q=o.slice(a).join("/");if(L instanceof RegExp){let V=L.exec(Q);if(V){if(C[B]=V[0],r.push(...this.#n($,t,A.#i,C)),Object.keys($.#e).length){$.#i=C;let le=V[0].match(/\//)?.length??0;(s[le]||=[]).push($)}continue}}(L===!0||L.test(l))&&(C[B]=l,c?(r.push(...this.#n($,t,C,A.#i)),$.#e["*"]&&r.push(...this.#n($.#e["*"],t,C,A.#i))):($.#i=C,f.push($)))}}i=f.concat(s.shift()??[])}return r.length>1&&r.sort((a,u)=>a.score-u.score),[r.map(({handler:a,params:u})=>[a,u])]}}});var Wut,awr=g(()=>{xH();swr();Wut=class{name="TrieRouter";#t;constructor(){this.#t=new Kut}add(t,e,r){let n=qxe(e);if(n){for(let i=0,o=n.length;i<o;i++)this.#t.insert(t,n[i],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}}});var uwr=g(()=>{awr()});var Vu,lwr=g(()=>{JSr();nwr();owr();uwr();Vu=class extends Uut{constructor(t={}){super(t),this.router=t.router??new zut({routers:[new Kxe,new Wut]})}}});var ey=g(()=>{lwr()});var IS,OH=g(()=>{IS=t=>{let r={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},n=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(r.origin),i=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(r.allowMethods);return async function(s,a){function u(c,f){s.res.headers.set(c,f)}let l=await n(s.req.header("origin")||"",s);if(l&&u("Access-Control-Allow-Origin",l),r.credentials&&u("Access-Control-Allow-Credentials","true"),r.exposeHeaders?.length&&u("Access-Control-Expose-Headers",r.exposeHeaders.join(",")),s.req.method==="OPTIONS"){r.origin!=="*"&&u("Vary","Origin"),r.maxAge!=null&&u("Access-Control-Max-Age",r.maxAge.toString());let c=await i(s.req.header("origin")||"",s);c.length&&u("Access-Control-Allow-Methods",c.join(","));let f=r.allowHeaders;if(!f?.length){let h=s.req.header("Access-Control-Request-Headers");h&&(f=h.split(/\s*,\s*/))}return f?.length&&(u("Access-Control-Allow-Headers",f.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await a(),r.origin!=="*"&&s.header("Vary","Origin",{append:!0})}}});var cwr={};vn(cwr,{__resetForTesting:()=>Sxi,applySessionFps:()=>Xut,getManager:()=>Gl,getPendingFpsForSession:()=>elt,getPendingStreamConfig:()=>rlt,getServerConfig:()=>Dxi,getWtConfigSnapshot:()=>Yut,initContext:()=>tlt,setSessionFpsApplier:()=>Zut,setWtConfigProvider:()=>Exi});function Exi(t){Yxe=t}function Yut(){return N(this,void 0,void 0,function*(){return Yxe?yield Yxe():null})}function Zut(t){Jse=t}function Xut(t,e){Jse?.(t,e)}function elt(t){let e;for(let[r,n]of Jut)r.endsWith(`\0${t}`)&&(e=n.fps);return e}function tlt(t,e){return yN||(Wxe=t,yN=e??new vH(t),e||yN.start(),yN)}function Gl(){if(!yN)throw new Error("PtyManagerService not initialized. Call initContext() first.");return yN}function Dxi(){if(!Wxe)throw new Error("SessionServerConfig not initialized. Call initContext() first.");return Wxe}function rlt(){return Jut}function Sxi(){yN=null,Wxe=null,Yxe=null,Jut.clear(),Jse=null}var yN,Wxe,Yxe,Jut,Jse,zI=g(()=>{Se();Cxe();yN=null,Wxe=null,Yxe=null;Jut=new Map,Jse=null});function dwr(t){let e=t;"keepAliveTimeout"in e&&(e.keepAliveTimeout=3e4),"requestTimeout"in e&&(e.requestTimeout=0),"headersTimeout"in e&&(e.headersTimeout=0),"timeout"in e&&(e.timeout=0)}var fwr=g(()=>{});function vN(t){var e;return{id:t.id,name:t.name,pid:(e=t.pid)!==null&&e!==void 0?e:null,command:t.command,parentId:t.parentId,createdAt:t.createdAt.toISOString(),lastAccessedAt:t.lastAccessedAt.toISOString(),status:t.status}}var Zse=g(()=>{});var ss,nlt,In,TS,Xse=g(()=>{(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ss||(ss={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(nlt||(nlt={}));In=ss.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),TS=t=>{switch(typeof t){case"undefined":return In.undefined;case"string":return In.string;case"number":return Number.isNaN(t)?In.nan:In.number;case"boolean":return In.boolean;case"function":return In.function;case"bigint":return In.bigint;case"symbol":return In.symbol;case"object":return Array.isArray(t)?In.array:t===null?In.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?In.promise:typeof Map<"u"&&t instanceof Map?In.map:typeof Set<"u"&&t instanceof Set?In.set:typeof Date<"u"&&t instanceof Date?In.date:In.object;default:return In.unknown}}});var Mr,wxi,Ng,Jxe=g(()=>{Xse();Mr=ss.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wxi=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ng=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,u=0;for(;u<s.path.length;){let l=s.path[u];u===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],u++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ss.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ng.create=t=>new Ng(t)});var Cxi,KI,ilt=g(()=>{Jxe();Xse();Cxi=(t,e)=>{let r;switch(t.code){case Mr.invalid_type:t.received===In.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Mr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ss.jsonStringifyReplacer)}`;break;case Mr.unrecognized_keys:r=`Unrecognized key(s) in object: ${ss.joinValues(t.keys,", ")}`;break;case Mr.invalid_union:r="Invalid input";break;case Mr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ss.joinValues(t.options)}`;break;case Mr.invalid_enum_value:r=`Invalid enum value. Expected ${ss.joinValues(t.options)}, received '${t.received}'`;break;case Mr.invalid_arguments:r="Invalid function arguments";break;case Mr.invalid_return_type:r="Invalid function return type";break;case Mr.invalid_date:r="Invalid date";break;case Mr.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ss.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Mr.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Mr.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Mr.custom:r="Invalid input";break;case Mr.invalid_intersection_types:r="Intersection results could not be merged";break;case Mr.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Mr.not_finite:r="Number must be finite";break;default:r=e.defaultError,ss.assertNever(t)}return{message:r}},KI=Cxi});function Ixi(t){pwr=t}function RH(){return pwr}var pwr,Zxe=g(()=>{ilt();pwr=KI});function pn(t,e){let r=RH(),n=eae({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===KI?void 0:KI].filter(i=>!!i)});t.common.issues.push(n)}var eae,Txi,Pp,Ci,Ek,wh,Xxe,e3e,AN,PH,olt=g(()=>{Zxe();ilt();eae=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)a=l(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},Txi=[];Pp=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return Ci;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return Ci;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},Ci=Object.freeze({status:"aborted"}),Ek=t=>({status:"dirty",value:t}),wh=t=>({status:"valid",value:t}),Xxe=t=>t.status==="aborted",e3e=t=>t.status==="dirty",AN=t=>t.status==="valid",PH=t=>typeof Promise<"u"&&t instanceof Promise});var hwr=g(()=>{});var Yn,mwr=g(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Yn||(Yn={}))});function bo(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:u}=t;return s.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:i}}function Awr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Hxi(t){return new RegExp(`^${Awr(t)}$`)}function _wr(t){let e=`${vwr}T${Awr(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Gxi(t,e){return!!((e==="v4"||!e)&&Lxi.test(t)||(e==="v6"||!e)&&$xi.test(t))}function zxi(t,e){if(!Bxi.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Kxi(t,e){return!!((e==="v4"||!e)&&jxi.test(t)||(e==="v6"||!e)&&qxi.test(t))}function Wxi(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}function BH(t){if(t instanceof Og){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Vv.create(BH(n))}return new Og({...t._def,shape:()=>e})}else return t instanceof JI?new JI({...t._def,type:BH(t.element)}):t instanceof Vv?Vv.create(BH(t.unwrap())):t instanceof NS?NS.create(BH(t.unwrap())):t instanceof xS?xS.create(t.items.map(e=>BH(e))):t}function alt(t,e){let r=TS(t),n=TS(e);if(t===e)return{valid:!0,data:t};if(r===In.object&&n===In.object){let i=ss.objectKeys(e),o=ss.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let u=alt(t[a],e[a]);if(!u.valid)return{valid:!1};s[a]=u.data}return{valid:!0,data:s}}else if(r===In.array&&n===In.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],u=alt(s,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===In.date&&n===In.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function bwr(t,e){return new Pk({values:t,typeName:Lr.ZodEnum,...bo(e)})}function ywr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Ewr(t,e={},r){return t?bN.create().superRefine((n,i)=>{let o=t(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=ywr(e,n),u=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:u})}});if(!o){let s=ywr(e,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):bN.create()}var Hv,gwr,Eo,xxi,Nxi,Oxi,Rxi,Pxi,Bxi,kxi,Mxi,Fxi,slt,Lxi,jxi,$xi,qxi,Uxi,Qxi,vwr,Vxi,_N,Dk,Sk,wk,Ck,kH,Ik,Tk,bN,YI,Eb,MH,JI,Og,xk,WI,t3e,Nk,xS,r3e,FH,LH,n3e,Ok,Rk,Pk,Bk,EN,Gv,Vv,NS,kk,Mk,jH,Yxi,tae,rae,Fk,Jxi,Lr,Zxi,Dwr,Swr,Xxi,e3i,wwr,t3i,r3i,n3i,i3i,o3i,s3i,a3i,u3i,l3i,c3i,d3i,f3i,p3i,h3i,m3i,g3i,y3i,v3i,A3i,_3i,b3i,E3i,D3i,S3i,w3i,C3i,I3i,T3i,x3i,N3i,O3i,R3i,P3i,B3i,Cwr=g(()=>{Jxe();Zxe();mwr();olt();Xse();Hv=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},gwr=(t,e)=>{if(AN(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ng(t.common.issues);return this._error=r,this._error}}};Eo=class{get description(){return this._def.description}_getType(e){return TS(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:TS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pp,ctx:{common:e.parent.common,data:e.data,parsedType:TS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(PH(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:TS(e)},i=this._parseSync({data:e,path:n.path,parent:n});return gwr(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:TS(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return AN(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>AN(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:TS(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(PH(i)?i:Promise.resolve(i));return gwr(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:Mr.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Gv({schema:this,typeName:Lr.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Vv.create(this,this._def)}nullable(){return NS.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return JI.create(this)}promise(){return EN.create(this,this._def)}or(e){return xk.create([this,e],this._def)}and(e){return Nk.create(this,e,this._def)}transform(e){return new Gv({...bo(this._def),schema:this,typeName:Lr.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new kk({...bo(this._def),innerType:this,defaultValue:r,typeName:Lr.ZodDefault})}brand(){return new tae({typeName:Lr.ZodBranded,type:this,...bo(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Mk({...bo(this._def),innerType:this,catchValue:r,typeName:Lr.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return rae.create(this,e)}readonly(){return Fk.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xxi=/^c[^\s-]{8,}$/i,Nxi=/^[0-9a-z]+$/,Oxi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rxi=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Pxi=/^[a-z0-9_-]{21}$/i,Bxi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kxi=/^[-+]?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)?)??$/,Mxi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fxi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Lxi=/^(?:(?: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])$/,jxi=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,$xi=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,qxi=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Uxi=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qxi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vwr="((\\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])))",Vxi=new RegExp(`^${vwr}$`);_N=class t extends Eo{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==In.string){let o=this._getOrReturnCtx(e);return pn(o,{code:Mr.invalid_type,expected:In.string,received:o.parsedType}),Ci}let n=new Pp,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?pn(i,{code:Mr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&pn(i,{code:Mr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Mxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"email",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")slt||(slt=new RegExp(Fxi,"u")),slt.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"emoji",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Rxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"uuid",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Pxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"nanoid",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")xxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"cuid",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Nxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"cuid2",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Oxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"ulid",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),pn(i,{validation:"url",code:Mr.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"regex",code:Mr.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?_wr(o).test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Vxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Hxi(o).test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?kxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"duration",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Gxi(e.data,o.version)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"ip",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?zxi(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"jwt",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Kxi(e.data,o.version)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"cidr",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Uxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"base64",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Qxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"base64url",code:Mr.invalid_string,message:o.message}),n.dirty()):ss.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Mr.invalid_string,...Yn.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Yn.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Yn.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Yn.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Yn.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Yn.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Yn.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Yn.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Yn.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Yn.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Yn.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Yn.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Yn.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Yn.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Yn.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Yn.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Yn.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Yn.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...Yn.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Yn.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Yn.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Yn.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Yn.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Yn.errToObj(r)})}nonempty(e){return this.min(1,Yn.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};_N.create=t=>new _N({checks:[],typeName:Lr.ZodString,coerce:t?.coerce??!1,...bo(t)});Dk=class t extends Eo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==In.number){let o=this._getOrReturnCtx(e);return pn(o,{code:Mr.invalid_type,expected:In.number,received:o.parsedType}),Ci}let n,i=new Pp;for(let o of this._def.checks)o.kind==="int"?ss.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Wxi(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.not_finite,message:o.message}),i.dirty()):ss.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Yn.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Yn.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Yn.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Yn.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Yn.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Yn.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Yn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Yn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Yn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Yn.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Yn.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Yn.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Yn.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Yn.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ss.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Dk.create=t=>new Dk({checks:[],typeName:Lr.ZodNumber,coerce:t?.coerce||!1,...bo(t)});Sk=class t extends Eo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==In.bigint)return this._getInvalidInput(e);let n,i=new Pp;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ss.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return pn(r,{code:Mr.invalid_type,expected:In.bigint,received:r.parsedType}),Ci}gte(e,r){return this.setLimit("min",e,!0,Yn.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Yn.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Yn.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Yn.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Yn.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Yn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Yn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Yn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Yn.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Yn.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Sk.create=t=>new Sk({checks:[],typeName:Lr.ZodBigInt,coerce:t?.coerce??!1,...bo(t)});wk=class extends Eo{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==In.boolean){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.boolean,received:n.parsedType}),Ci}return wh(e.data)}};wk.create=t=>new wk({typeName:Lr.ZodBoolean,coerce:t?.coerce||!1,...bo(t)});Ck=class t extends Eo{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==In.date){let o=this._getOrReturnCtx(e);return pn(o,{code:Mr.invalid_type,expected:In.date,received:o.parsedType}),Ci}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return pn(o,{code:Mr.invalid_date}),Ci}let n=new Pp,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ss.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Yn.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Yn.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Ck.create=t=>new Ck({checks:[],coerce:t?.coerce||!1,typeName:Lr.ZodDate,...bo(t)});kH=class extends Eo{_parse(e){if(this._getType(e)!==In.symbol){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.symbol,received:n.parsedType}),Ci}return wh(e.data)}};kH.create=t=>new kH({typeName:Lr.ZodSymbol,...bo(t)});Ik=class extends Eo{_parse(e){if(this._getType(e)!==In.undefined){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.undefined,received:n.parsedType}),Ci}return wh(e.data)}};Ik.create=t=>new Ik({typeName:Lr.ZodUndefined,...bo(t)});Tk=class extends Eo{_parse(e){if(this._getType(e)!==In.null){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.null,received:n.parsedType}),Ci}return wh(e.data)}};Tk.create=t=>new Tk({typeName:Lr.ZodNull,...bo(t)});bN=class extends Eo{constructor(){super(...arguments),this._any=!0}_parse(e){return wh(e.data)}};bN.create=t=>new bN({typeName:Lr.ZodAny,...bo(t)});YI=class extends Eo{constructor(){super(...arguments),this._unknown=!0}_parse(e){return wh(e.data)}};YI.create=t=>new YI({typeName:Lr.ZodUnknown,...bo(t)});Eb=class extends Eo{_parse(e){let r=this._getOrReturnCtx(e);return pn(r,{code:Mr.invalid_type,expected:In.never,received:r.parsedType}),Ci}};Eb.create=t=>new Eb({typeName:Lr.ZodNever,...bo(t)});MH=class extends Eo{_parse(e){if(this._getType(e)!==In.undefined){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.void,received:n.parsedType}),Ci}return wh(e.data)}};MH.create=t=>new MH({typeName:Lr.ZodVoid,...bo(t)});JI=class t extends Eo{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==In.array)return pn(r,{code:Mr.invalid_type,expected:In.array,received:r.parsedType}),Ci;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(pn(r,{code:s?Mr.too_big:Mr.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(pn(r,{code:Mr.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(pn(r,{code:Mr.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new Hv(r,s,r.path,a)))).then(s=>Pp.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Hv(r,s,r.path,a)));return Pp.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:Yn.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:Yn.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:Yn.toString(r)}})}nonempty(e){return this.min(1,e)}};JI.create=(t,e)=>new JI({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Lr.ZodArray,...bo(e)});Og=class t extends Eo{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ss.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==In.object){let l=this._getOrReturnCtx(e);return pn(l,{code:Mr.invalid_type,expected:In.object,received:l.parsedType}),Ci}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Eb&&this._def.unknownKeys==="strip"))for(let l in i.data)s.includes(l)||a.push(l);let u=[];for(let l of s){let c=o[l],f=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new Hv(i,f,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof Eb){let l=this._def.unknownKeys;if(l==="passthrough")for(let c of a)u.push({key:{status:"valid",value:c},value:{status:"valid",value:i.data[c]}});else if(l==="strict")a.length>0&&(pn(i,{code:Mr.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let c of a){let f=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new Hv(i,f,i.path,c)),alwaysSet:c in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let c of u){let f=await c.key,h=await c.value;l.push({key:f,value:h,alwaysSet:c.alwaysSet})}return l}).then(l=>Pp.mergeObjectSync(n,l)):Pp.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return Yn.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Yn.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Lr.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ss.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ss.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return BH(this)}partial(e){let r={};for(let n of ss.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ss.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Vv;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return bwr(ss.objectKeys(this.shape))}};Og.create=(t,e)=>new Og({shape:()=>t,unknownKeys:"strip",catchall:Eb.create(),typeName:Lr.ZodObject,...bo(e)});Og.strictCreate=(t,e)=>new Og({shape:()=>t,unknownKeys:"strict",catchall:Eb.create(),typeName:Lr.ZodObject,...bo(e)});Og.lazycreate=(t,e)=>new Og({shape:t,unknownKeys:"strip",catchall:Eb.create(),typeName:Lr.ZodObject,...bo(e)});xk=class extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new Ng(a.ctx.common.issues));return pn(r,{code:Mr.invalid_union,unionErrors:s}),Ci}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let u of n){let l={...r,common:{...r.common,issues:[]},parent:null},c=u._parseSync({data:r.data,path:r.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!o&&(o={result:c,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(u=>new Ng(u));return pn(r,{code:Mr.invalid_union,unionErrors:a}),Ci}}get options(){return this._def.options}};xk.create=(t,e)=>new xk({options:t,typeName:Lr.ZodUnion,...bo(e)});WI=t=>t instanceof Ok?WI(t.schema):t instanceof Gv?WI(t.innerType()):t instanceof Rk?[t.value]:t instanceof Pk?t.options:t instanceof Bk?ss.objectValues(t.enum):t instanceof kk?WI(t._def.innerType):t instanceof Ik?[void 0]:t instanceof Tk?[null]:t instanceof Vv?[void 0,...WI(t.unwrap())]:t instanceof NS?[null,...WI(t.unwrap())]:t instanceof tae||t instanceof Fk?WI(t.unwrap()):t instanceof Mk?WI(t._def.innerType):[],t3e=class t extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==In.object)return pn(r,{code:Mr.invalid_type,expected:In.object,received:r.parsedType}),Ci;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(pn(r,{code:Mr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Ci)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let s=WI(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:Lr.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...bo(n)})}};Nk=class extends Eo{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(Xxe(o)||Xxe(s))return Ci;let a=alt(o.value,s.value);return a.valid?((e3e(o)||e3e(s))&&r.dirty(),{status:r.value,value:a.data}):(pn(n,{code:Mr.invalid_intersection_types}),Ci)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Nk.create=(t,e,r)=>new Nk({left:t,right:e,typeName:Lr.ZodIntersection,...bo(r)});xS=class t extends Eo{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==In.array)return pn(n,{code:Mr.invalid_type,expected:In.array,received:n.parsedType}),Ci;if(n.data.length<this._def.items.length)return pn(n,{code:Mr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ci;!this._def.rest&&n.data.length>this._def.items.length&&(pn(n,{code:Mr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Hv(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Pp.mergeArray(r,s)):Pp.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xS.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xS({items:t,typeName:Lr.ZodTuple,rest:null,...bo(e)})};r3e=class t extends Eo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==In.object)return pn(n,{code:Mr.invalid_type,expected:In.object,received:n.parsedType}),Ci;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Hv(n,a,n.path,a)),value:s._parse(new Hv(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Pp.mergeObjectAsync(r,i):Pp.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Eo?new t({keyType:e,valueType:r,typeName:Lr.ZodRecord,...bo(n)}):new t({keyType:_N.create(),valueType:e,typeName:Lr.ZodRecord,...bo(r)})}},FH=class extends Eo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==In.map)return pn(n,{code:Mr.invalid_type,expected:In.map,received:n.parsedType}),Ci;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,u],l)=>({key:i._parse(new Hv(n,a,n.path,[l,"key"])),value:o._parse(new Hv(n,u,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of s){let l=await u.key,c=await u.value;if(l.status==="aborted"||c.status==="aborted")return Ci;(l.status==="dirty"||c.status==="dirty")&&r.dirty(),a.set(l.value,c.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of s){let l=u.key,c=u.value;if(l.status==="aborted"||c.status==="aborted")return Ci;(l.status==="dirty"||c.status==="dirty")&&r.dirty(),a.set(l.value,c.value)}return{status:r.value,value:a}}}};FH.create=(t,e,r)=>new FH({valueType:e,keyType:t,typeName:Lr.ZodMap,...bo(r)});LH=class t extends Eo{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==In.set)return pn(n,{code:Mr.invalid_type,expected:In.set,received:n.parsedType}),Ci;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(pn(n,{code:Mr.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(pn(n,{code:Mr.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(u){let l=new Set;for(let c of u){if(c.status==="aborted")return Ci;c.status==="dirty"&&r.dirty(),l.add(c.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((u,l)=>o._parse(new Hv(n,u,n.path,l)));return n.common.async?Promise.all(a).then(u=>s(u)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:Yn.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:Yn.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};LH.create=(t,e)=>new LH({valueType:t,minSize:null,maxSize:null,typeName:Lr.ZodSet,...bo(e)});n3e=class t extends Eo{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==In.function)return pn(r,{code:Mr.invalid_type,expected:In.function,received:r.parsedType}),Ci;function n(a,u){return eae({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,RH(),KI].filter(l=>!!l),issueData:{code:Mr.invalid_arguments,argumentsError:u}})}function i(a,u){return eae({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,RH(),KI].filter(l=>!!l),issueData:{code:Mr.invalid_return_type,returnTypeError:u}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof EN){let a=this;return wh(async function(...u){let l=new Ng([]),c=await a._def.args.parseAsync(u,o).catch(m=>{throw l.addIssue(n(u,m)),l}),f=await Reflect.apply(s,this,c);return await a._def.returns._def.type.parseAsync(f,o).catch(m=>{throw l.addIssue(i(f,m)),l})})}else{let a=this;return wh(function(...u){let l=a._def.args.safeParse(u,o);if(!l.success)throw new Ng([n(u,l.error)]);let c=Reflect.apply(s,this,l.data),f=a._def.returns.safeParse(c,o);if(!f.success)throw new Ng([i(c,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:xS.create(e).rest(YI.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||xS.create([]).rest(YI.create()),returns:r||YI.create(),typeName:Lr.ZodFunction,...bo(n)})}},Ok=class extends Eo{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ok.create=(t,e)=>new Ok({getter:t,typeName:Lr.ZodLazy,...bo(e)});Rk=class extends Eo{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return pn(r,{received:r.data,code:Mr.invalid_literal,expected:this._def.value}),Ci}return{status:"valid",value:e.data}}get value(){return this._def.value}};Rk.create=(t,e)=>new Rk({value:t,typeName:Lr.ZodLiteral,...bo(e)});Pk=class t extends Eo{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return pn(r,{expected:ss.joinValues(n),received:r.parsedType,code:Mr.invalid_type}),Ci}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return pn(r,{received:r.data,code:Mr.invalid_enum_value,options:n}),Ci}return wh(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Pk.create=bwr;Bk=class extends Eo{_parse(e){let r=ss.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==In.string&&n.parsedType!==In.number){let i=ss.objectValues(r);return pn(n,{expected:ss.joinValues(i),received:n.parsedType,code:Mr.invalid_type}),Ci}if(this._cache||(this._cache=new Set(ss.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ss.objectValues(r);return pn(n,{received:n.data,code:Mr.invalid_enum_value,options:i}),Ci}return wh(e.data)}get enum(){return this._def.values}};Bk.create=(t,e)=>new Bk({values:t,typeName:Lr.ZodNativeEnum,...bo(e)});EN=class extends Eo{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==In.promise&&r.common.async===!1)return pn(r,{code:Mr.invalid_type,expected:In.promise,received:r.parsedType}),Ci;let n=r.parsedType===In.promise?r.data:Promise.resolve(r.data);return wh(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};EN.create=(t,e)=>new EN({type:t,typeName:Lr.ZodPromise,...bo(e)});Gv=class extends Eo{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Lr.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{pn(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return Ci;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?Ci:u.status==="dirty"?Ek(u.value):r.value==="dirty"?Ek(u.value):u});{if(r.value==="aborted")return Ci;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?Ci:a.status==="dirty"?Ek(a.value):r.value==="dirty"?Ek(a.value):a}}if(i.type==="refinement"){let s=a=>{let u=i.refinement(a,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Ci:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?Ci:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!AN(s))return Ci;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>AN(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):Ci);ss.assertNever(i)}};Gv.create=(t,e,r)=>new Gv({schema:t,typeName:Lr.ZodEffects,effect:e,...bo(r)});Gv.createWithPreprocess=(t,e,r)=>new Gv({schema:e,effect:{type:"preprocess",transform:t},typeName:Lr.ZodEffects,...bo(r)});Vv=class extends Eo{_parse(e){return this._getType(e)===In.undefined?wh(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vv.create=(t,e)=>new Vv({innerType:t,typeName:Lr.ZodOptional,...bo(e)});NS=class extends Eo{_parse(e){return this._getType(e)===In.null?wh(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};NS.create=(t,e)=>new NS({innerType:t,typeName:Lr.ZodNullable,...bo(e)});kk=class extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===In.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};kk.create=(t,e)=>new kk({innerType:t,typeName:Lr.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...bo(e)});Mk=class extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return PH(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ng(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ng(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Mk.create=(t,e)=>new Mk({innerType:t,typeName:Lr.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...bo(e)});jH=class extends Eo{_parse(e){if(this._getType(e)!==In.nan){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.nan,received:n.parsedType}),Ci}return{status:"valid",value:e.data}}};jH.create=t=>new jH({typeName:Lr.ZodNaN,...bo(t)});Yxi=Symbol("zod_brand"),tae=class extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},rae=class t extends Eo{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Ci:o.status==="dirty"?(r.dirty(),Ek(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ci:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Lr.ZodPipeline})}},Fk=class extends Eo{_parse(e){let r=this._def.innerType._parse(e),n=i=>(AN(i)&&(i.value=Object.freeze(i.value)),i);return PH(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Fk.create=(t,e)=>new Fk({innerType:t,typeName:Lr.ZodReadonly,...bo(e)});Jxi={object:Og.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Lr||(Lr={}));Zxi=(t,e={message:`Input not instance of ${t.name}`})=>Ewr(r=>r instanceof t,e),Dwr=_N.create,Swr=Dk.create,Xxi=jH.create,e3i=Sk.create,wwr=wk.create,t3i=Ck.create,r3i=kH.create,n3i=Ik.create,i3i=Tk.create,o3i=bN.create,s3i=YI.create,a3i=Eb.create,u3i=MH.create,l3i=JI.create,c3i=Og.create,d3i=Og.strictCreate,f3i=xk.create,p3i=t3e.create,h3i=Nk.create,m3i=xS.create,g3i=r3e.create,y3i=FH.create,v3i=LH.create,A3i=n3e.create,_3i=Ok.create,b3i=Rk.create,E3i=Pk.create,D3i=Bk.create,S3i=EN.create,w3i=Gv.create,C3i=Vv.create,I3i=NS.create,T3i=Gv.createWithPreprocess,x3i=rae.create,N3i=()=>Dwr().optional(),O3i=()=>Swr().optional(),R3i=()=>wwr().optional(),P3i={string:(t=>_N.create({...t,coerce:!0})),number:(t=>Dk.create({...t,coerce:!0})),boolean:(t=>wk.create({...t,coerce:!0})),bigint:(t=>Sk.create({...t,coerce:!0})),date:(t=>Ck.create({...t,coerce:!0}))},B3i=Ci});var X={};vn(X,{BRAND:()=>Yxi,DIRTY:()=>Ek,EMPTY_PATH:()=>Txi,INVALID:()=>Ci,NEVER:()=>B3i,OK:()=>wh,ParseStatus:()=>Pp,Schema:()=>Eo,ZodAny:()=>bN,ZodArray:()=>JI,ZodBigInt:()=>Sk,ZodBoolean:()=>wk,ZodBranded:()=>tae,ZodCatch:()=>Mk,ZodDate:()=>Ck,ZodDefault:()=>kk,ZodDiscriminatedUnion:()=>t3e,ZodEffects:()=>Gv,ZodEnum:()=>Pk,ZodError:()=>Ng,ZodFirstPartyTypeKind:()=>Lr,ZodFunction:()=>n3e,ZodIntersection:()=>Nk,ZodIssueCode:()=>Mr,ZodLazy:()=>Ok,ZodLiteral:()=>Rk,ZodMap:()=>FH,ZodNaN:()=>jH,ZodNativeEnum:()=>Bk,ZodNever:()=>Eb,ZodNull:()=>Tk,ZodNullable:()=>NS,ZodNumber:()=>Dk,ZodObject:()=>Og,ZodOptional:()=>Vv,ZodParsedType:()=>In,ZodPipeline:()=>rae,ZodPromise:()=>EN,ZodReadonly:()=>Fk,ZodRecord:()=>r3e,ZodSchema:()=>Eo,ZodSet:()=>LH,ZodString:()=>_N,ZodSymbol:()=>kH,ZodTransformer:()=>Gv,ZodTuple:()=>xS,ZodType:()=>Eo,ZodUndefined:()=>Ik,ZodUnion:()=>xk,ZodUnknown:()=>YI,ZodVoid:()=>MH,addIssueToContext:()=>pn,any:()=>o3i,array:()=>l3i,bigint:()=>e3i,boolean:()=>wwr,coerce:()=>P3i,custom:()=>Ewr,date:()=>t3i,datetimeRegex:()=>_wr,defaultErrorMap:()=>KI,discriminatedUnion:()=>p3i,effect:()=>w3i,enum:()=>E3i,function:()=>A3i,getErrorMap:()=>RH,getParsedType:()=>TS,instanceof:()=>Zxi,intersection:()=>h3i,isAborted:()=>Xxe,isAsync:()=>PH,isDirty:()=>e3e,isValid:()=>AN,late:()=>Jxi,lazy:()=>_3i,literal:()=>b3i,makeIssue:()=>eae,map:()=>y3i,nan:()=>Xxi,nativeEnum:()=>D3i,never:()=>a3i,null:()=>i3i,nullable:()=>I3i,number:()=>Swr,object:()=>c3i,objectUtil:()=>nlt,oboolean:()=>R3i,onumber:()=>O3i,optional:()=>C3i,ostring:()=>N3i,pipeline:()=>x3i,preprocess:()=>T3i,promise:()=>S3i,quotelessJson:()=>wxi,record:()=>g3i,set:()=>v3i,setErrorMap:()=>Ixi,strictObject:()=>d3i,string:()=>Dwr,symbol:()=>r3i,transformer:()=>w3i,tuple:()=>m3i,undefined:()=>n3i,union:()=>f3i,unknown:()=>s3i,util:()=>ss,void:()=>u3i});var ult=g(()=>{Zxe();olt();hwr();Xse();Cwr();Jxe()});var Cd=g(()=>{ult();ult()});function Twr(t){return k3i.includes(t)}function xwr(t){if(/^C-(.+)$/i.test(t)){let e=t.slice(2).toLowerCase();return e.length===1&&e>="a"&&e<="z"?String.fromCharCode(e.charCodeAt(0)-96):e==="space"||e==="@"?"\0":e==="["?"\x1B":e==="\\"?"":e==="]"?"":e==="^"?"":e==="_"?"":t}return/^M-(.+)$/i.test(t)?"\x1B"+t.slice(2):/^[A-Z]/.test(t)&&t.length>1&&Iwr[t]?Iwr[t]:t}var k3i,Iwr,Nwr=g(()=>{k3i=["\u82F1\u6570","\u304B\u306A","Eisu","Kana"];Iwr={Enter:"\r",Escape:"\x1B",Tab:" ",Space:" ",BSpace:"\x7F",Backspace:"\x7F",DC:"\x1B[3~",Delete:"\x1B[3~",Up:"\x1B[A",Down:"\x1B[B",Right:"\x1B[C",Left:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",PageUp:"\x1B[5~",PageDown:"\x1B[6~",Insert:"\x1B[2~",F1:"\x1BOP",F2:"\x1BOQ",F3:"\x1BOR",F4:"\x1BOS",F5:"\x1B[15~",F6:"\x1B[17~",F7:"\x1B[18~",F8:"\x1B[19~",F9:"\x1B[20~",F10:"\x1B[21~",F11:"\x1B[23~",F12:"\x1B[24~"}});import{randomUUID as M3i}from"crypto";function llt(t){return N(this,void 0,void 0,function*(){try{return yield t.req.json()}catch{return null}})}function Owr(){let t=new Vu;return t.post("/sessions",e=>N(this,void 0,void 0,function*(){var r,n;let i=F3i.safeParse(yield llt(e));if(!i.success)return e.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let o=i.data,s=(r=o.id)!==null&&r!==void 0?r:M3i(),a=yield Gl().createSession({id:s,name:(n=o.name)!==null&&n!==void 0?n:s.slice(0,8),command:o.command,parentId:o.parentId,cwd:o.cwd,env:o.env});return e.json(vN(a),201)})),t.patch("/sessions/:id",e=>N(this,void 0,void 0,function*(){let r=e.req.param("id"),n=L3i.safeParse(yield llt(e));if(!n.success)return e.json({error:{code:"INVALID_BODY",message:n.error.message}},400);let i=Gl().getSession(r);if(!i)return e.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);let{name:o,status:s,cols:a,rows:u}=n.data;a!==void 0&&u!==void 0&&Gl().resize(r,a,u),s==="detached"&&(i.status="detached"),o!==void 0&&Gl().renameSession(r,o);let l=Gl().getSession(r);return e.json(vN(l??i))})),t.delete("/sessions/:id",e=>N(this,void 0,void 0,function*(){let r=e.req.param("id");return yield Gl().destroySession(r),e.json({success:!0,id:r})})),t.post("/sessions/:id/input",e=>N(this,void 0,void 0,function*(){let r=e.req.param("id"),n=yield llt(e),i=j3i.safeParse(n),o=i.success?null:$3i.safeParse(n);if(!i.success&&!o?.success)return e.json({error:{code:"INVALID_BODY",message:"body \u306F {data} \u307E\u305F\u306F {keys, literal?}"}},400);if(!Gl().getSession(r))return e.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);if(i.success)return Gl().input(r,i.data.data),e.json({success:!0,id:r});let{keys:s,literal:a}=o.success?o.data:{keys:[],literal:!1},u=s.filter(l=>!Twr(l)).map(l=>a?l:xwr(l)).join("");return u.length>0&&Gl().input(r,u),e.json({success:!0,id:r})})),t}var F3i,L3i,j3i,$3i,Rwr=g(()=>{Se();ey();Cd();zI();Zse();Nwr();F3i=X.object({id:X.string().optional(),name:X.string().optional(),command:X.string().optional(),parentId:X.string().optional(),cwd:X.string().optional(),env:X.record(X.string()).optional()}),L3i=X.object({name:X.string().optional(),status:X.literal("detached").optional(),cols:X.number().optional(),rows:X.number().optional()}).refine(t=>t.name!==void 0||t.status!==void 0||t.cols!==void 0&&t.rows!==void 0,{message:"name / status / {cols,rows} \u306E\u3044\u305A\u308C\u304B\u304C\u5FC5\u8981"}),j3i=X.object({data:X.string()}),$3i=X.object({keys:X.array(X.string()),literal:X.boolean().optional()})});function Pwr(){let t=new Vu;return t.put("/sessions/:id/stream-config",e=>N(this,void 0,void 0,function*(){let r=e.req.param("id"),n=null;try{n=yield e.req.json()}catch{}let i=q3i.safeParse(n);if(!i.success)return e.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let{peerId:o,fps:s}=i.data,a=`${o}\0${r}`;return rlt().set(a,{fps:s}),Xut(r,s),e.json({success:!0,id:r})})),t.get("/system/wt-config",e=>N(this,void 0,void 0,function*(){return e.json(yield Yut())})),t}var q3i,Bwr=g(()=>{Se();ey();Cd();zI();q3i=X.object({peerId:X.string(),fps:X.number()})});function i3e(t){var e,r;let n=(e=t.intervalMs)!==null&&e!==void 0?e:25e3,i=(r=t.now)!==null&&r!==void 0?r:(()=>Date.now()),o=new TextEncoder,s=!1,a=setInterval(()=>{if(!s)try{t.enqueue(o.encode(`: heartbeat ${i()}
|
|
554
|
+
`;this.buffer=[];let r=Buffer.from(e);gN.write(this.fd,r,0,r.length,null,n=>{n&&this.logger.error("Write error",{error:n})})}stop(){this.enabled=!1,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush(),this.fd!==null&&(gN.closeSync(this.fd),this.fd=null),this.logger.info("Recording stopped")}};bb.FLUSH_INTERVAL_MS=500;bb.DIR="/tmp/planx/logs/sessions";bb.\u0275fac=function(e){return new(e||bb)};bb.\u0275prov=Ce({token:bb,factory:bb.\u0275fac,providedIn:"root"})});function qTi(){return N(this,void 0,void 0,function*(){return yield import("@fails-components/webtransport")})}var Vse,_Sr=g(()=>{Se();Vse=class t{constructor(e){var r;this.opts=e,this.server=null,this.sessionLoopActive=!1,this.assignedPort=null,this.pathPrefix=(r=e.pathPrefix)!==null&&r!==void 0?r:"/sessions",this.pathPattern=`${this.pathPrefix}/*`}start(){return N(this,void 0,void 0,function*(){var e;if(this.server)return;let r=yield qTi(),n=this.opts.port;if(n===0){let{createSocket:o}=yield import("dgram");n=yield new Promise((s,a)=>{let u=o("udp4");u.bind(0,"127.0.0.1",()=>{let l=u.address(),c=typeof l=="object"&&l!==null?l.port:0;u.close(()=>s(c))}),u.on("error",a)}),this.assignedPort=n}let i=new r.Http3Server({port:n,host:t.BIND_HOST,secret:"session-wt-output",cert:this.opts.cert,privKey:this.opts.privKey});(e=i.setRequestCallback)===null||e===void 0||e.call(i,o=>Promise.resolve(t.buildRequestResult(this.pathPrefix,o.header))),i.startServer(),yield i.ready,this.server=i,this.sessionLoopActive=!0,this.runSessionLoop()})}static buildRequestResult(e,r){var n;let i=(n=r[":path"])!==null&&n!==void 0?n:"";return t.parseSessionPath(e,i)!==null?{path:e,status:200}:{path:i,status:404}}stop(){return N(this,void 0,void 0,function*(){this.sessionLoopActive=!1,this.server&&(yield this.server.stopServer(),this.server=null)})}getBindHost(){return t.BIND_HOST}isRunning(){return this.server!==null}getListenPort(){var e,r,n;if(!this.server)return null;if(this.opts.port>0)return this.opts.port;if(this.assignedPort!==null)return this.assignedPort;let i=(r=(e=this.server).address)===null||r===void 0?void 0:r.call(e);return(n=i?.port)!==null&&n!==void 0?n:null}static parseSessionPath(e,r){let n=r.split("?")[0],i=[["output","/output"],["input","/input"]];for(let[o,s]of i){if(!n.startsWith(`${e}/`)||!n.endsWith(s))continue;let a=n.slice(e.length+1,n.length-s.length);if(a.length>0&&!a.includes("/"))return{sessionId:a,direction:o}}return null}static extractSessionId(e,r){let n=t.parseSessionPath(e,r);return n?.direction==="output"?n.sessionId:null}runSessionLoop(){return N(this,void 0,void 0,function*(){if(!this.server)return;let e=this.server.sessionStream(this.pathPrefix).getReader();yield this.consumeSessions(e)})}consumeSessions(e){return N(this,void 0,void 0,function*(){for(var r,n,i,o;this.sessionLoopActive;){let s,a;try{({value:s,done:a}=yield e.read())}catch(u){(n=(r=this.opts).log)===null||n===void 0||n.call(r,"error","session stream read error",t.serializeErr(u));return}if(a)return;if(s)try{this.handleSession(s)}catch(u){(o=(i=this.opts).log)===null||o===void 0||o.call(i,"error","session handler error (isolated)",t.serializeErr(u)),t.safeCloseSession(s)}}})}static serializeErr(e){var r;if(e instanceof Error)return(r=e.stack)!==null&&r!==void 0?r:`${e.name}: ${e.message}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}static safeCloseSession(e){return N(this,void 0,void 0,function*(){var r;try{yield(r=e.close)===null||r===void 0?void 0:r.call(e,{closeCode:404,reason:"session not found"})}catch{}})}handleSession(e){var r,n,i,o,s,a,u,l,c,f,h,m,A,E,b,S;let w=(i=(n=(r=e.header)===null||r===void 0?void 0:r[":path"])!==null&&n!==void 0?n:e.path)!==null&&i!==void 0?i:"";console.error("[wt-output-endpoint] handleSession entered",{":path":(s=(o=e.header)===null||o===void 0?void 0:o[":path"])!==null&&s!==void 0?s:"<no-header>","session.path":(a=e.path)!==null&&a!==void 0?a:"<no-shim>",resolvedPath:w,hasOnOutputSession:!!this.opts.onOutputSession,hasOnInputSession:!!this.opts.onInputSession});let C=t.parseSessionPath(this.pathPrefix,w);if(C===null){(l=(u=this.opts).log)===null||l===void 0||l.call(u,"warn","incoming session with invalid path",{path:w}),console.error("[wt-output-endpoint] SILENT FAIL: parseSessionPath returned null",{pathPrefix:this.pathPrefix,path:w});return}let{sessionId:x,direction:B}=C;if(B==="input"){(f=(c=this.opts).log)===null||f===void 0||f.call(c,"info","incoming input session",{sessionId:x,path:w}),console.error("[wt-output-endpoint] dispatching onInputSession",{sessionId:x,path:w}),(m=(h=this.opts).onInputSession)===null||m===void 0||m.call(h,x,e);return}(E=(A=this.opts).log)===null||E===void 0||E.call(A,"info","incoming output session",{sessionId:x,path:w}),console.error("[wt-output-endpoint] dispatching onOutputSession",{sessionId:x,path:w}),(S=(b=this.opts).onOutputSession)===null||S===void 0||S.call(b,x,e)}};Vse.BIND_HOST="127.0.0.1"});var bSr=g(()=>{_Sr()});import{createServer as UTi}from"http";import{Http2ServerRequest as QTi}from"http2";import{Http2ServerRequest as xut}from"http2";import{Readable as ESr}from"stream";import txi from"crypto";async function ZTi(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function CSr(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(s,i),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function i(a){a&&e.destroy(a)}function o(){t.read().then(s,i)}function s({done:a,value:u}){try{if(a)e.end();else if(!e.write(u))e.once("drain",o);else return t.read().then(s,i)}catch(l){i(l)}}}function XTi(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:CSr(t.getReader(),e)}var yk,VTi,HTi,Hse,GTi,SSr,zTi,IH,KTi,kxe,Mxe,WTi,CH,YTi,Fxe,JTi,DSr,wH,vk,Out,Gse,ISr,exi,rxi,Rut,nxi,TSr,Nut,xSr,NSr,ixi,oxi,sxi,axi,CS,TH=g(()=>{yk=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},VTi=t=>t instanceof yk?t:new yk(t.message,{cause:t}),HTi=global.Request,Hse=class extends HTi{constructor(t,e){typeof t=="object"&&IH in t&&(t=t[IH]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},GTi=t=>{let e=[],r=t.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:i,[n+1]:o}=r;i.charCodeAt(0)!==58&&e.push([i,o])}return new Headers(e)},SSr=Symbol("wrapBodyStream"),zTi=(t,e,r,n,i)=>{let o={method:t,headers:r,signal:i.signal};if(t==="TRACE"){o.method="GET";let s=new Hse(e,o);return Object.defineProperty(s,"method",{get(){return"TRACE"}}),s}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)o.body=new ReadableStream({start(s){s.enqueue(n.rawBody),s.close()}});else if(n[SSr]){let s;o.body=new ReadableStream({async pull(a){try{s||=ESr.toWeb(n).getReader();let{done:u,value:l}=await s.read();u?a.close():a.enqueue(l)}catch(u){a.error(u)}}})}else o.body=ESr.toWeb(n);return new Hse(e,o)},IH=Symbol("getRequestCache"),KTi=Symbol("requestCache"),kxe=Symbol("incomingKey"),Mxe=Symbol("urlKey"),WTi=Symbol("headersKey"),CH=Symbol("abortControllerKey"),YTi=Symbol("getAbortController"),Fxe={get method(){return this[kxe].method||"GET"},get url(){return this[Mxe]},get headers(){return this[WTi]||=GTi(this[kxe])},[YTi](){return this[IH](),this[CH]},[IH](){return this[CH]||=new AbortController,this[KTi]||=zTi(this.method,this[Mxe],this.headers,this[kxe],this[CH])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(Fxe,t,{get(){return this[IH]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Fxe,t,{value:function(){return this[IH]()[t]()}})});Object.setPrototypeOf(Fxe,Hse.prototype);JTi=(t,e)=>{let r=Object.create(Fxe);r[kxe]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof xut)throw new yk("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[Mxe]=a.href}catch(a){throw new yk("Invalid absolute URL",{cause:a})}return r}let i=(t instanceof xut?t.authority:t.headers.host)||e;if(!i)throw new yk("Missing host header");let o;if(t instanceof xut){if(o=t.scheme,!(o==="http"||o==="https"))throw new yk("Unsupported scheme")}else o=t.socket&&t.socket.encrypted?"https":"http";let s=new URL(`${o}://${i}${n}`);if(s.hostname.length!==i.length&&s.hostname!==i.replace(/:\d+$/,""))throw new yk("Invalid host header");return r[Mxe]=s.href,r},DSr=Symbol("responseCache"),wH=Symbol("getResponseCache"),vk=Symbol("cache"),Out=global.Response,Gse=class wSr{#t;#e;[wH](){return delete this[vk],this[DSr]||=new Out(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof wSr){let i=r[DSr];if(i){this.#e=i,this[wH]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(n||=r?.headers||{"content-type":"text/plain; charset=UTF-8"},this[vk]=[r?.status||200,e,n])}get headers(){let e=this[vk];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[wH]().headers}get status(){return this[vk]?.[0]??this[wH]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(Gse.prototype,t,{get(){return this[wH]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Gse.prototype,t,{value:function(){return this[wH]()[t]()}})});Object.setPrototypeOf(Gse,Out);Object.setPrototypeOf(Gse.prototype,Out.prototype);ISr=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[n,i]of t)n==="set-cookie"?r.push(i):e[n]=i;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},exi="x-hono-already-sent",rxi=global.fetch;typeof global.crypto>"u"&&(global.crypto=txi);global.fetch=(t,e)=>(e={compress:!1,...e},rxi(t,e));Rut=Symbol("outgoingEnded"),nxi=()=>new Response(null,{status:400}),TSr=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Nut=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},xSr=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},NSr=async(t,e)=>{let[r,n,i]=t[vk];i instanceof Headers&&(i=ISr(i)),typeof n=="string"?i["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?i["Content-Length"]=n.byteLength:n instanceof Blob&&(i["Content-Length"]=n.size),e.writeHead(r,i),typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(xSr(e),await XTi(n,e)?.catch(o=>Nut(o,e))),e[Rut]?.()},ixi=t=>typeof t.then=="function",oxi=async(t,e,r={})=>{if(ixi(t))if(r.errorHandler)try{t=await t}catch(i){let o=await r.errorHandler(i);if(!o)return;t=o}else t=await t.catch(TSr);if(vk in t)return NSr(t,e);let n=ISr(t.headers);if(t.body){let i=t.body.getReader(),o=[],s=!1,a;if(n["transfer-encoding"]!=="chunked"){let u=2;for(let l=0;l<u;l++){a||=i.read();let c=await ZTi(a).catch(f=>{console.error(f),s=!0});if(!c){if(l===1){await new Promise(f=>setTimeout(f)),u=3;continue}break}if(a=void 0,c.value&&o.push(c.value),c.done){s=!0;break}}s&&!("content-length"in n)&&(n["content-length"]=o.reduce((l,c)=>l+c.length,0))}e.writeHead(t.status,n),o.forEach(u=>{e.write(u)}),s?e.end():(o.length===0&&xSr(e),await CSr(i,e,a))}else n[exi]||(e.writeHead(t.status,n),e.end());e[Rut]?.()},sxi=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Hse&&(Object.defineProperty(global,"Request",{value:Hse}),Object.defineProperty(global,"Response",{value:Gse})),async(n,i)=>{let o,s;try{s=JTi(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[SSr]=!0,n.on("end",()=>{a=!0}),n instanceof QTi&&(i[Rut]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),i.destroy()})})})),i.on("close",()=>{s[CH]&&(n.errored?s[CH].abort(n.errored.toString()):i.writableFinished||s[CH].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),o=t(s,{incoming:n,outgoing:i}),vk in o)return NSr(o,i)}catch(a){if(o)return Nut(a,i);if(e.errorHandler){if(o=await e.errorHandler(s?a:VTi(a)),!o)return}else s?o=TSr(a):o=nxi()}try{return await oxi(o,i,e)}catch(a){return Nut(a,i)}}},axi=t=>{let e=t.fetch,r=sxi(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||UTi)(t.serverOptions||{},r)},CS=(t,e)=>{let r=axi(t);return r.listen(t?.port??3e3,t.hostname,()=>{let n=r.address();e&&e(n)}),r}});var Put,OSr=g(()=>{Put=(t,e,r)=>(n,i)=>{let o=-1;return s(0);async function s(a){if(a<=o)throw new Error("next() called multiple times");o=a;let u,l=!1,c;if(t[a]?(c=t[a][0][0],n.req.routeIndex=a):c=a===t.length&&i||void 0,c)try{u=await c(n,()=>s(a+1))}catch(f){if(f instanceof Error&&e)n.error=f,u=await e(f,n),l=!0;else throw f}else n.finalized===!1&&r&&(u=await r(n));return u&&(n.finalized===!1||l)&&(n.res=u),n}}});var RSr=g(()=>{});var PSr,BSr=g(()=>{PSr=Symbol()});async function uxi(t,e){let r=await t.formData();return r?lxi(r,e):{}}function lxi(t,e){let r=Object.create(null);return t.forEach((n,i)=>{e.all||i.endsWith("[]")?cxi(r,i,n):r[i]=n}),e.dot&&Object.entries(r).forEach(([n,i])=>{n.includes(".")&&(dxi(r,n,i),delete r[n])}),r}var kSr,cxi,dxi,MSr=g(()=>{But();kSr=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,o=(t instanceof Lxe?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?uxi(t,{all:r,dot:n}):{}};cxi=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},dxi=(t,e,r)=>{let n=t,i=e.split(".");i.forEach((o,s)=>{s===i.length-1?n[o]=r:((!n[o]||typeof n[o]!="object"||Array.isArray(n[o])||n[o]instanceof File)&&(n[o]=Object.create(null)),n=n[o])})}});var Mut,FSr,fxi,pxi,jxe,LSr,$xe,hxi,Fut,jSr,Ak,qxe,kut,$Sr,qSr,USr,Lut,xH=g(()=>{Mut=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},FSr=t=>{let{groups:e,path:r}=fxi(t),n=Mut(r);return pxi(n,e)},fxi=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let i=`@${n}`;return e.push([i,r]),i}),{groups:e,path:t}},pxi=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let i=t.length-1;i>=0;i--)if(t[i].includes(n)){t[i]=t[i].replace(n,e[r][1]);break}}return t},jxe={},LSr=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return jxe[n]||(r[2]?jxe[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:jxe[n]=[t,r[1],!0]),jxe[n]}return null},$xe=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},hxi=t=>$xe(t,decodeURI),Fut=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let i=e.charCodeAt(n);if(i===37){let o=e.indexOf("?",n),s=e.slice(r,o===-1?void 0:o);return hxi(s.includes("%25")?s.replace(/%25/g,"%2525"):s)}else if(i===63)break}return e.slice(r,n)},jSr=t=>{let e=Fut(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Ak=(t,e,...r)=>(r.length&&(e=Ak(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),qxe=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(i=>{if(i!==""&&!/\:/.test(i))n+="/"+i;else if(/\:/.test(i))if(/\?/.test(i)){r.length===0&&n===""?r.push("/"):r.push(n);let o=i.replace("?","");n+="/"+o,r.push(n)}else n+="/"+i}),r.filter((i,o,s)=>s.indexOf(i)===o)},kut=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?$xe(t,Lut):t):t,$Sr=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let s=t.indexOf(`?${e}`,8);for(s===-1&&(s=t.indexOf(`&${e}`,8));s!==-1;){let a=t.charCodeAt(s+e.length+1);if(a===61){let u=s+e.length+2,l=t.indexOf("&",u);return kut(t.slice(u,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";s=t.indexOf(`&${e}`,s+1)}if(n=/[%+]/.test(t),!n)return}let i={};n??=/[%+]/.test(t);let o=t.indexOf("?",8);for(;o!==-1;){let s=t.indexOf("&",o+1),a=t.indexOf("=",o);a>s&&s!==-1&&(a=-1);let u=t.slice(o+1,a===-1?s===-1?void 0:s:a);if(n&&(u=kut(u)),o=s,u==="")continue;let l;a===-1?l="":(l=t.slice(a+1,s===-1?void 0:s),n&&(l=kut(l))),r?(i[u]&&Array.isArray(i[u])||(i[u]=[]),i[u].push(l)):i[u]??=l}return e?i[e]:i},qSr=$Sr,USr=(t,e)=>$Sr(t,e,!0),Lut=decodeURIComponent});var QSr,Lxe,But=g(()=>{RSr();BSr();MSr();xH();QSr=t=>$xe(t,Lut),Lxe=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#o()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#i(e);return r&&/\%/.test(r)?QSr(r):r}#o(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#i(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?QSr(n):n)}return t}#i(t){return this.#e[1]?this.#e[1][t]:t}query(t){return qSr(this.url,t)}queries(t){return USr(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return this.bodyCache.parsedBody??=await kSr(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let i=Object.keys(e)[0];return i?e[i].then(o=>(i==="json"&&(o=JSON.stringify(o)),new Response(o)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[PSr](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}}});var Uxe,mxi,zse,jut=g(()=>{Uxe={Stringify:1,BeforeStream:2,Stream:3},mxi=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r},zse=async(t,e,r,n,i)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let o=t.callbacks;if(!o?.length)return Promise.resolve(t);i?i[0]+=t:i=[t];let s=Promise.all(o.map(a=>a({phase:e,buffer:i,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(u=>zse(u,e,!1,n,i))).then(()=>i[0]));return r?mxi(await s,o):s}});var VSr,$ut,HSr,qut=g(()=>{But();jut();VSr="text/plain; charset=UTF-8",$ut=(t,e)=>({"Content-Type":t,...e}),HSr=class{#t;#e;env={};#r;finalized=!1;error;#o;#i;#n;#c;#u;#l;#a;#d;#f;constructor(t,e){this.#t=t,e&&(this.#i=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#f=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Lxe(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=new Response(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=new Response(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let i of n)t.headers.append("set-cookie",i)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#u??=e=>this.html(e),this.#u(...t));setLayout=t=>this.#c=t;getLayout=()=>this.#c;setRenderer=t=>{this.#u=t};header=(t,e,r)=>{this.finalized&&(this.#n=new Response(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#o=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#s(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[s,a]of o)s.toLowerCase()==="set-cookie"?n.append(s,a):n.set(s,a)}if(r)for(let[o,s]of Object.entries(r))if(typeof s=="string")n.set(o,s);else{n.delete(o);for(let a of s)n.append(o,a)}let i=typeof e=="number"?e:e?.status??this.#o;return new Response(t,{status:i,headers:n})}newResponse=(...t)=>this.#s(...t);body=(t,e,r)=>this.#s(t,e,r);text=(t,e,r)=>!this.#a&&!this.#o&&!e&&!r&&!this.finalized?new Response(t):this.#s(t,e,$ut(VSr,r));json=(t,e,r)=>this.#s(JSON.stringify(t),e,$ut("application/json",r));html=(t,e,r)=>{let n=i=>this.#s(i,e,$ut("text/html; charset=UTF-8",r));return typeof t=="object"?zse(t,Uxe.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))}});var Sl,GSr,zSr,Qxe,Vxe,_k=g(()=>{Sl="ALL",GSr="all",zSr=["get","post","put","delete","options","patch"],Qxe="Can not add a route since the matcher is already built.",Vxe=class extends Error{}});var KSr,WSr=g(()=>{KSr="__COMPOSED_HANDLER"});var gxi,YSr,Uut,JSr=g(()=>{OSr();qut();_k();WSr();xH();gxi=t=>t.text("404 Not Found",404),YSr=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Uut=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...zSr,GSr].forEach(i=>{this[i]=(o,...s)=>(typeof o=="string"?this.#t=o:this.#o(i,this.#t,o),s.forEach(a=>{this.#o(i,this.#t,a)}),this)}),this.on=(i,o,...s)=>{for(let a of[o].flat()){this.#t=a;for(let u of[i].flat())s.map(l=>{this.#o(u.toUpperCase(),this.#t,l)})}return this},this.use=(i,...o)=>(typeof i=="string"?this.#t=i:(this.#t="*",o.unshift(i)),o.forEach(s=>{this.#o(Sl,this.#t,s)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??Fut:jSr}#e(){let t=new Uut({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=gxi;errorHandler=YSr;route(t,e){let r=this.basePath(t);return e.routes.map(n=>{let i;e.errorHandler===YSr?i=n.handler:(i=async(o,s)=>(await Put([],e.errorHandler)(o,()=>n.handler(o,s))).res,i[KSr]=n.handler),r.#o(n.method,n.path,i)}),this}basePath(t){let e=this.#e();return e._basePath=Ak(this._basePath,t),e}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,e,r){let n,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===!1?n=a=>a:n=r.replaceRequest));let o=i?a=>{let u=i(a);return Array.isArray(u)?u:[u]}:a=>{let u;try{u=a.executionCtx}catch{}return[a.env,u]};n||=(()=>{let a=Ak(this._basePath,t),u=a==="/"?0:a.length;return l=>{let c=new URL(l.url);return c.pathname=c.pathname.slice(u)||"/",new Request(c,l)}})();let s=async(a,u)=>{let l=await e(n(a.req.raw),...o(a));if(l)return l;await u()};return this.#o(Sl,Ak(t,"*"),s),this}#o(t,e,r){t=t.toUpperCase(),e=Ak(this._basePath,e);let n={basePath:this._basePath,path:e,method:t,handler:r};this.router.add(t,e,[r,n]),this.routes.push(n)}#i(t,e){if(t instanceof Error)return this.errorHandler(t,e);throw t}#n(t,e,r,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(t,e,r,"GET")))();let i=this.getPath(t,{env:r}),o=this.router.match(n,i),s=new HSr(t,{path:i,matchResult:o,env:r,executionCtx:e,notFoundHandler:this.#r});if(o[0].length===1){let u;try{u=o[0][0][0][0](s,async()=>{s.res=await this.#r(s)})}catch(l){return this.#i(l,s)}return u instanceof Promise?u.then(l=>l||(s.finalized?s.res:this.#r(s))).catch(l=>this.#i(l,s)):u??this.#r(s)}let a=Put(o[0],this.errorHandler,this.#r);return(async()=>{try{let u=await a(s);if(!u.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#i(u,s)}})()}fetch=(t,...e)=>this.#n(t,e[1],e[0],t.method);request=(t,e,r,n)=>t instanceof Request?this.fetch(e?new Request(t,e):t,r,n):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Ak("/",t)}`,e),r,n));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}}});function Qut(t,e){let r=this.buildAllMatchers(),n=(i,o)=>{let s=r[i]||r[Sl],a=s[2][o];if(a)return a;let u=o.match(s[0]);if(!u)return[[],Hxe];let l=u.indexOf("",1);return[s[1][l],u]};return this.match=n,n(t,e)}var Hxe,Vut=g(()=>{_k();Hxe=[]});function vxi(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===Kse||t===Wse?1:e===Kse||e===Wse?-1:t===Gxe?1:e===Gxe?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Gxe,Kse,Wse,bk,yxi,zxe,Hut=g(()=>{Gxe="[^/]+",Kse=".*",Wse="(?:|/.*)",bk=Symbol(),yxi=new Set(".\\+*[^]$()");zxe=class{#t;#e;#r=Object.create(null);insert(t,e,r,n,i){if(t.length===0){if(this.#t!==void 0)throw bk;if(i)return;this.#t=e;return}let[o,...s]=t,a=o==="*"?s.length===0?["","",Kse]:["","",Gxe]:o==="/*"?["","",Wse]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(a){let l=a[1],c=a[2]||Gxe;if(l&&a[2]&&(c===".*"||(c=c.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(c))))throw bk;if(u=this.#r[c],!u){if(Object.keys(this.#r).some(f=>f!==Kse&&f!==Wse))throw bk;if(i)return;u=this.#r[c]=new zxe,l!==""&&(u.#e=n.varIndex++)}!i&&l!==""&&r.push([l,u.#e])}else if(u=this.#r[o],!u){if(Object.keys(this.#r).some(l=>l.length>1&&l!==Kse&&l!==Wse))throw bk;if(i)return;u=this.#r[o]=new zxe}u.insert(s,e,r,n,i)}buildRegExpStr(){let e=Object.keys(this.#r).sort(vxi).map(r=>{let n=this.#r[r];return(typeof n.#e=="number"?`(${r})@${n.#e}`:yxi.has(r)?`\\${r}`:r)+n.buildRegExpStr()});return typeof this.#t=="number"&&e.unshift(`#${this.#t}`),e.length===0?"":e.length===1?e[0]:"(?:"+e.join("|")+")"}}});var ZSr,XSr=g(()=>{Hut();ZSr=class{#t={varIndex:0};#e=new zxe;insert(t,e,r){let n=[],i=[];for(let s=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,u=>{let l=`@\\${s}`;return i[s]=[l,u],s++,a=!0,l}),!a)break}let o=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=i.length-1;s>=0;s--){let[a]=i[s];for(let u=o.length-1;u>=0;u--)if(o[u].indexOf(a)!==-1){o[u]=o[u].replace(a,i[s][1]);break}}return this.#e.insert(o,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,o,s)=>o!==void 0?(r[++e]=Number(o),"$()"):(s!==void 0&&(n[Number(s)]=++e),"")),[new RegExp(`^${t}`),r,n]}}});function twr(t){return ewr[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function _xi(){ewr=Object.create(null)}function bxi(t){let e=new ZSr,r=[];if(t.length===0)return Axi;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,c],[f,h])=>l?1:f?-1:c.length-h.length),i=Object.create(null);for(let l=0,c=-1,f=n.length;l<f;l++){let[h,m,A]=n[l];h?i[m]=[A.map(([b])=>[b,Object.create(null)]),Hxe]:c++;let E;try{E=e.insert(m,c,h)}catch(b){throw b===bk?new Vxe(m):b}h||(r[c]=A.map(([b,S])=>{let w=Object.create(null);for(S-=1;S>=0;S--){let[C,x]=E[S];w[C]=x}return[b,w]}))}let[o,s,a]=e.buildRegExp();for(let l=0,c=r.length;l<c;l++)for(let f=0,h=r[l].length;f<h;f++){let m=r[l][f]?.[1];if(!m)continue;let A=Object.keys(m);for(let E=0,b=A.length;E<b;E++)m[A[E]]=a[m[A[E]]]}let u=[];for(let l in s)u[l]=r[s[l]];return[o,u,i]}function NH(t,e){if(t){for(let r of Object.keys(t).sort((n,i)=>i.length-n.length))if(twr(r).test(e))return[...t[r]]}}var Axi,ewr,Kxe,Gut=g(()=>{_k();xH();Vut();Hut();XSr();Axi=[/^$/,[],Object.create(null)],ewr=Object.create(null);Kxe=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[Sl]:Object.create(null)},this.#e={[Sl]:Object.create(null)}}add(t,e,r){let n=this.#t,i=this.#e;if(!n||!i)throw new Error(Qxe);n[t]||[n,i].forEach(a=>{a[t]=Object.create(null),Object.keys(a[Sl]).forEach(u=>{a[t][u]=[...a[Sl][u]]})}),e==="/*"&&(e="*");let o=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=twr(e);t===Sl?Object.keys(n).forEach(u=>{n[u][e]||=NH(n[u],e)||NH(n[Sl],e)||[]}):n[t][e]||=NH(n[t],e)||NH(n[Sl],e)||[],Object.keys(n).forEach(u=>{(t===Sl||t===u)&&Object.keys(n[u]).forEach(l=>{a.test(l)&&n[u][l].push([r,o])})}),Object.keys(i).forEach(u=>{(t===Sl||t===u)&&Object.keys(i[u]).forEach(l=>a.test(l)&&i[u][l].push([r,o]))});return}let s=qxe(e)||[e];for(let a=0,u=s.length;a<u;a++){let l=s[a];Object.keys(i).forEach(c=>{(t===Sl||t===c)&&(i[c][l]||=[...NH(n[c],l)||NH(n[Sl],l)||[]],i[c][l].push([r,o-u+a+1]))})}}match=Qut;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,_xi(),t}#r(t){let e=[],r=t===Sl;return[this.#t,this.#e].forEach(n=>{let i=n[t]?Object.keys(n[t]).map(o=>[o,n[t][o]]):[];i.length!==0?(r||=!0,e.push(...i)):t!==Sl&&e.push(...Object.keys(n[Sl]).map(o=>[o,n[Sl][o]]))}),r?bxi(e):null}}});var rwr=g(()=>{_k();Vut();Gut()});var nwr=g(()=>{Gut();rwr()});var zut,iwr=g(()=>{_k();zut=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(Qxe);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,i=r.length,o=0,s;for(;o<i;o++){let a=r[o];try{for(let u=0,l=n.length;u<l;u++)a.add(...n[u]);s=a.match(t,e)}catch(u){if(u instanceof Vxe)continue;throw u}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===i)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}}});var owr=g(()=>{iwr()});var Yse,Kut,swr=g(()=>{_k();xH();Yse=Object.create(null),Kut=class{#t;#e;#r;#o=0;#i=Yse;constructor(t,e,r){if(this.#e=r||Object.create(null),this.#t=[],t&&e){let n=Object.create(null);n[t]={handler:e,possibleKeys:[],score:0},this.#t=[n]}this.#r=[]}insert(t,e,r){this.#o=++this.#o;let n=this,i=FSr(e),o=[];for(let s=0,a=i.length;s<a;s++){let u=i[s],l=i[s+1],c=LSr(u,l),f=Array.isArray(c)?c[0]:u;if(f in n.#e){n=n.#e[f],c&&o.push(c[1]);continue}n.#e[f]=new Kut,c&&(n.#r.push(c),o.push(c[1])),n=n.#e[f]}return n.#t.push({[t]:{handler:r,possibleKeys:o.filter((s,a,u)=>u.indexOf(s)===a),score:this.#o}}),n}#n(t,e,r,n){let i=[];for(let o=0,s=t.#t.length;o<s;o++){let a=t.#t[o],u=a[e]||a[Sl],l={};if(u!==void 0&&(u.params=Object.create(null),i.push(u),r!==Yse||n&&n!==Yse))for(let c=0,f=u.possibleKeys.length;c<f;c++){let h=u.possibleKeys[c],m=l[u.score];u.params[h]=n?.[h]&&!m?n[h]:r[h]??n?.[h],l[u.score]=!0}}return i}search(t,e){let r=[];this.#i=Yse;let i=[this],o=Mut(e),s=[];for(let a=0,u=o.length;a<u;a++){let l=o[a],c=a===u-1,f=[];for(let h=0,m=i.length;h<m;h++){let A=i[h],E=A.#e[l];E&&(E.#i=A.#i,c?(E.#e["*"]&&r.push(...this.#n(E.#e["*"],t,A.#i)),r.push(...this.#n(E,t,A.#i))):f.push(E));for(let b=0,S=A.#r.length;b<S;b++){let w=A.#r[b],C=A.#i===Yse?{}:{...A.#i};if(w==="*"){let V=A.#e["*"];V&&(r.push(...this.#n(V,t,A.#i)),V.#i=C,f.push(V));continue}let[x,B,L]=w;if(!l&&!(L instanceof RegExp))continue;let $=A.#e[x],Q=o.slice(a).join("/");if(L instanceof RegExp){let V=L.exec(Q);if(V){if(C[B]=V[0],r.push(...this.#n($,t,A.#i,C)),Object.keys($.#e).length){$.#i=C;let le=V[0].match(/\//)?.length??0;(s[le]||=[]).push($)}continue}}(L===!0||L.test(l))&&(C[B]=l,c?(r.push(...this.#n($,t,C,A.#i)),$.#e["*"]&&r.push(...this.#n($.#e["*"],t,C,A.#i))):($.#i=C,f.push($)))}}i=f.concat(s.shift()??[])}return r.length>1&&r.sort((a,u)=>a.score-u.score),[r.map(({handler:a,params:u})=>[a,u])]}}});var Wut,awr=g(()=>{xH();swr();Wut=class{name="TrieRouter";#t;constructor(){this.#t=new Kut}add(t,e,r){let n=qxe(e);if(n){for(let i=0,o=n.length;i<o;i++)this.#t.insert(t,n[i],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}}});var uwr=g(()=>{awr()});var Vu,lwr=g(()=>{JSr();nwr();owr();uwr();Vu=class extends Uut{constructor(t={}){super(t),this.router=t.router??new zut({routers:[new Kxe,new Wut]})}}});var ey=g(()=>{lwr()});var IS,OH=g(()=>{IS=t=>{let r={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},n=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(r.origin),i=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(r.allowMethods);return async function(s,a){function u(c,f){s.res.headers.set(c,f)}let l=await n(s.req.header("origin")||"",s);if(l&&u("Access-Control-Allow-Origin",l),r.credentials&&u("Access-Control-Allow-Credentials","true"),r.exposeHeaders?.length&&u("Access-Control-Expose-Headers",r.exposeHeaders.join(",")),s.req.method==="OPTIONS"){r.origin!=="*"&&u("Vary","Origin"),r.maxAge!=null&&u("Access-Control-Max-Age",r.maxAge.toString());let c=await i(s.req.header("origin")||"",s);c.length&&u("Access-Control-Allow-Methods",c.join(","));let f=r.allowHeaders;if(!f?.length){let h=s.req.header("Access-Control-Request-Headers");h&&(f=h.split(/\s*,\s*/))}return f?.length&&(u("Access-Control-Allow-Headers",f.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await a(),r.origin!=="*"&&s.header("Vary","Origin",{append:!0})}}});var cwr={};vn(cwr,{__resetForTesting:()=>Sxi,applySessionFps:()=>Xut,getManager:()=>Gl,getPendingFpsForSession:()=>elt,getPendingStreamConfig:()=>rlt,getServerConfig:()=>Dxi,getWtConfigSnapshot:()=>Yut,initContext:()=>tlt,setSessionFpsApplier:()=>Zut,setWtConfigProvider:()=>Exi});function Exi(t){Yxe=t}function Yut(){return N(this,void 0,void 0,function*(){return Yxe?yield Yxe():null})}function Zut(t){Jse=t}function Xut(t,e){Jse?.(t,e)}function elt(t){let e;for(let[r,n]of Jut)r.endsWith(`\0${t}`)&&(e=n.fps);return e}function tlt(t,e){return yN||(Wxe=t,yN=e??new vH(t),e||yN.start(),yN)}function Gl(){if(!yN)throw new Error("PtyManagerService not initialized. Call initContext() first.");return yN}function Dxi(){if(!Wxe)throw new Error("SessionServerConfig not initialized. Call initContext() first.");return Wxe}function rlt(){return Jut}function Sxi(){yN=null,Wxe=null,Yxe=null,Jut.clear(),Jse=null}var yN,Wxe,Yxe,Jut,Jse,zI=g(()=>{Se();Cxe();yN=null,Wxe=null,Yxe=null;Jut=new Map,Jse=null});function dwr(t){let e=t;"keepAliveTimeout"in e&&(e.keepAliveTimeout=3e4),"requestTimeout"in e&&(e.requestTimeout=0),"headersTimeout"in e&&(e.headersTimeout=0),"timeout"in e&&(e.timeout=0)}var fwr=g(()=>{});function vN(t){var e;return{id:t.id,name:t.name,pid:(e=t.pid)!==null&&e!==void 0?e:null,command:t.command,parentId:t.parentId,createdAt:t.createdAt.toISOString(),lastAccessedAt:t.lastAccessedAt.toISOString(),status:t.status}}var Zse=g(()=>{});var ss,nlt,In,TS,Xse=g(()=>{(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ss||(ss={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(nlt||(nlt={}));In=ss.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),TS=t=>{switch(typeof t){case"undefined":return In.undefined;case"string":return In.string;case"number":return Number.isNaN(t)?In.nan:In.number;case"boolean":return In.boolean;case"function":return In.function;case"bigint":return In.bigint;case"symbol":return In.symbol;case"object":return Array.isArray(t)?In.array:t===null?In.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?In.promise:typeof Map<"u"&&t instanceof Map?In.map:typeof Set<"u"&&t instanceof Set?In.set:typeof Date<"u"&&t instanceof Date?In.date:In.object;default:return In.unknown}}});var Mr,wxi,Ng,Jxe=g(()=>{Xse();Mr=ss.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wxi=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ng=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,u=0;for(;u<s.path.length;){let l=s.path[u];u===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],u++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ss.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ng.create=t=>new Ng(t)});var Cxi,KI,ilt=g(()=>{Jxe();Xse();Cxi=(t,e)=>{let r;switch(t.code){case Mr.invalid_type:t.received===In.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Mr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ss.jsonStringifyReplacer)}`;break;case Mr.unrecognized_keys:r=`Unrecognized key(s) in object: ${ss.joinValues(t.keys,", ")}`;break;case Mr.invalid_union:r="Invalid input";break;case Mr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ss.joinValues(t.options)}`;break;case Mr.invalid_enum_value:r=`Invalid enum value. Expected ${ss.joinValues(t.options)}, received '${t.received}'`;break;case Mr.invalid_arguments:r="Invalid function arguments";break;case Mr.invalid_return_type:r="Invalid function return type";break;case Mr.invalid_date:r="Invalid date";break;case Mr.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ss.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Mr.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Mr.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Mr.custom:r="Invalid input";break;case Mr.invalid_intersection_types:r="Intersection results could not be merged";break;case Mr.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Mr.not_finite:r="Number must be finite";break;default:r=e.defaultError,ss.assertNever(t)}return{message:r}},KI=Cxi});function Ixi(t){pwr=t}function RH(){return pwr}var pwr,Zxe=g(()=>{ilt();pwr=KI});function pn(t,e){let r=RH(),n=eae({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===KI?void 0:KI].filter(i=>!!i)});t.common.issues.push(n)}var eae,Txi,Pp,Ci,Ek,wh,Xxe,e3e,AN,PH,olt=g(()=>{Zxe();ilt();eae=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)a=l(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},Txi=[];Pp=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return Ci;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return Ci;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},Ci=Object.freeze({status:"aborted"}),Ek=t=>({status:"dirty",value:t}),wh=t=>({status:"valid",value:t}),Xxe=t=>t.status==="aborted",e3e=t=>t.status==="dirty",AN=t=>t.status==="valid",PH=t=>typeof Promise<"u"&&t instanceof Promise});var hwr=g(()=>{});var Yn,mwr=g(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Yn||(Yn={}))});function bo(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:u}=t;return s.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:i}}function Awr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Hxi(t){return new RegExp(`^${Awr(t)}$`)}function _wr(t){let e=`${vwr}T${Awr(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Gxi(t,e){return!!((e==="v4"||!e)&&Lxi.test(t)||(e==="v6"||!e)&&$xi.test(t))}function zxi(t,e){if(!Bxi.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Kxi(t,e){return!!((e==="v4"||!e)&&jxi.test(t)||(e==="v6"||!e)&&qxi.test(t))}function Wxi(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}function BH(t){if(t instanceof Og){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Vv.create(BH(n))}return new Og({...t._def,shape:()=>e})}else return t instanceof JI?new JI({...t._def,type:BH(t.element)}):t instanceof Vv?Vv.create(BH(t.unwrap())):t instanceof NS?NS.create(BH(t.unwrap())):t instanceof xS?xS.create(t.items.map(e=>BH(e))):t}function alt(t,e){let r=TS(t),n=TS(e);if(t===e)return{valid:!0,data:t};if(r===In.object&&n===In.object){let i=ss.objectKeys(e),o=ss.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let u=alt(t[a],e[a]);if(!u.valid)return{valid:!1};s[a]=u.data}return{valid:!0,data:s}}else if(r===In.array&&n===In.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],u=alt(s,a);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===In.date&&n===In.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function bwr(t,e){return new Pk({values:t,typeName:Lr.ZodEnum,...bo(e)})}function ywr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Ewr(t,e={},r){return t?bN.create().superRefine((n,i)=>{let o=t(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=ywr(e,n),u=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:u})}});if(!o){let s=ywr(e,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):bN.create()}var Hv,gwr,Eo,xxi,Nxi,Oxi,Rxi,Pxi,Bxi,kxi,Mxi,Fxi,slt,Lxi,jxi,$xi,qxi,Uxi,Qxi,vwr,Vxi,_N,Dk,Sk,wk,Ck,kH,Ik,Tk,bN,YI,Eb,MH,JI,Og,xk,WI,t3e,Nk,xS,r3e,FH,LH,n3e,Ok,Rk,Pk,Bk,EN,Gv,Vv,NS,kk,Mk,jH,Yxi,tae,rae,Fk,Jxi,Lr,Zxi,Dwr,Swr,Xxi,e3i,wwr,t3i,r3i,n3i,i3i,o3i,s3i,a3i,u3i,l3i,c3i,d3i,f3i,p3i,h3i,m3i,g3i,y3i,v3i,A3i,_3i,b3i,E3i,D3i,S3i,w3i,C3i,I3i,T3i,x3i,N3i,O3i,R3i,P3i,B3i,Cwr=g(()=>{Jxe();Zxe();mwr();olt();Xse();Hv=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},gwr=(t,e)=>{if(AN(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ng(t.common.issues);return this._error=r,this._error}}};Eo=class{get description(){return this._def.description}_getType(e){return TS(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:TS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pp,ctx:{common:e.parent.common,data:e.data,parsedType:TS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(PH(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:TS(e)},i=this._parseSync({data:e,path:n.path,parent:n});return gwr(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:TS(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return AN(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>AN(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:TS(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(PH(i)?i:Promise.resolve(i));return gwr(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:Mr.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Gv({schema:this,typeName:Lr.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Vv.create(this,this._def)}nullable(){return NS.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return JI.create(this)}promise(){return EN.create(this,this._def)}or(e){return xk.create([this,e],this._def)}and(e){return Nk.create(this,e,this._def)}transform(e){return new Gv({...bo(this._def),schema:this,typeName:Lr.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new kk({...bo(this._def),innerType:this,defaultValue:r,typeName:Lr.ZodDefault})}brand(){return new tae({typeName:Lr.ZodBranded,type:this,...bo(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Mk({...bo(this._def),innerType:this,catchValue:r,typeName:Lr.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return rae.create(this,e)}readonly(){return Fk.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xxi=/^c[^\s-]{8,}$/i,Nxi=/^[0-9a-z]+$/,Oxi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rxi=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Pxi=/^[a-z0-9_-]{21}$/i,Bxi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kxi=/^[-+]?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)?)??$/,Mxi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fxi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Lxi=/^(?:(?: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])$/,jxi=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,$xi=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,qxi=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Uxi=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qxi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vwr="((\\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])))",Vxi=new RegExp(`^${vwr}$`);_N=class t extends Eo{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==In.string){let o=this._getOrReturnCtx(e);return pn(o,{code:Mr.invalid_type,expected:In.string,received:o.parsedType}),Ci}let n=new Pp,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?pn(i,{code:Mr.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&pn(i,{code:Mr.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Mxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"email",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")slt||(slt=new RegExp(Fxi,"u")),slt.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"emoji",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Rxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"uuid",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Pxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"nanoid",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")xxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"cuid",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Nxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"cuid2",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Oxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"ulid",code:Mr.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),pn(i,{validation:"url",code:Mr.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"regex",code:Mr.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?_wr(o).test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Vxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Hxi(o).test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?kxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"duration",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Gxi(e.data,o.version)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"ip",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?zxi(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"jwt",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Kxi(e.data,o.version)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"cidr",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Uxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"base64",code:Mr.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Qxi.test(e.data)||(i=this._getOrReturnCtx(e,i),pn(i,{validation:"base64url",code:Mr.invalid_string,message:o.message}),n.dirty()):ss.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Mr.invalid_string,...Yn.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Yn.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Yn.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Yn.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Yn.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Yn.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Yn.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Yn.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Yn.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Yn.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Yn.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Yn.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Yn.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Yn.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Yn.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Yn.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Yn.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Yn.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...Yn.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Yn.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Yn.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Yn.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Yn.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Yn.errToObj(r)})}nonempty(e){return this.min(1,Yn.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};_N.create=t=>new _N({checks:[],typeName:Lr.ZodString,coerce:t?.coerce??!1,...bo(t)});Dk=class t extends Eo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==In.number){let o=this._getOrReturnCtx(e);return pn(o,{code:Mr.invalid_type,expected:In.number,received:o.parsedType}),Ci}let n,i=new Pp;for(let o of this._def.checks)o.kind==="int"?ss.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Wxi(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.not_finite,message:o.message}),i.dirty()):ss.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Yn.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Yn.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Yn.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Yn.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Yn.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Yn.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Yn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Yn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Yn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Yn.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Yn.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Yn.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Yn.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Yn.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ss.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Dk.create=t=>new Dk({checks:[],typeName:Lr.ZodNumber,coerce:t?.coerce||!1,...bo(t)});Sk=class t extends Eo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==In.bigint)return this._getInvalidInput(e);let n,i=new Pp;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),pn(n,{code:Mr.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ss.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return pn(r,{code:Mr.invalid_type,expected:In.bigint,received:r.parsedType}),Ci}gte(e,r){return this.setLimit("min",e,!0,Yn.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Yn.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Yn.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Yn.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Yn.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Yn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Yn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Yn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Yn.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Yn.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Sk.create=t=>new Sk({checks:[],typeName:Lr.ZodBigInt,coerce:t?.coerce??!1,...bo(t)});wk=class extends Eo{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==In.boolean){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.boolean,received:n.parsedType}),Ci}return wh(e.data)}};wk.create=t=>new wk({typeName:Lr.ZodBoolean,coerce:t?.coerce||!1,...bo(t)});Ck=class t extends Eo{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==In.date){let o=this._getOrReturnCtx(e);return pn(o,{code:Mr.invalid_type,expected:In.date,received:o.parsedType}),Ci}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return pn(o,{code:Mr.invalid_date}),Ci}let n=new Pp,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),pn(i,{code:Mr.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ss.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Yn.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Yn.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Ck.create=t=>new Ck({checks:[],coerce:t?.coerce||!1,typeName:Lr.ZodDate,...bo(t)});kH=class extends Eo{_parse(e){if(this._getType(e)!==In.symbol){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.symbol,received:n.parsedType}),Ci}return wh(e.data)}};kH.create=t=>new kH({typeName:Lr.ZodSymbol,...bo(t)});Ik=class extends Eo{_parse(e){if(this._getType(e)!==In.undefined){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.undefined,received:n.parsedType}),Ci}return wh(e.data)}};Ik.create=t=>new Ik({typeName:Lr.ZodUndefined,...bo(t)});Tk=class extends Eo{_parse(e){if(this._getType(e)!==In.null){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.null,received:n.parsedType}),Ci}return wh(e.data)}};Tk.create=t=>new Tk({typeName:Lr.ZodNull,...bo(t)});bN=class extends Eo{constructor(){super(...arguments),this._any=!0}_parse(e){return wh(e.data)}};bN.create=t=>new bN({typeName:Lr.ZodAny,...bo(t)});YI=class extends Eo{constructor(){super(...arguments),this._unknown=!0}_parse(e){return wh(e.data)}};YI.create=t=>new YI({typeName:Lr.ZodUnknown,...bo(t)});Eb=class extends Eo{_parse(e){let r=this._getOrReturnCtx(e);return pn(r,{code:Mr.invalid_type,expected:In.never,received:r.parsedType}),Ci}};Eb.create=t=>new Eb({typeName:Lr.ZodNever,...bo(t)});MH=class extends Eo{_parse(e){if(this._getType(e)!==In.undefined){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.void,received:n.parsedType}),Ci}return wh(e.data)}};MH.create=t=>new MH({typeName:Lr.ZodVoid,...bo(t)});JI=class t extends Eo{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==In.array)return pn(r,{code:Mr.invalid_type,expected:In.array,received:r.parsedType}),Ci;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(pn(r,{code:s?Mr.too_big:Mr.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(pn(r,{code:Mr.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(pn(r,{code:Mr.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new Hv(r,s,r.path,a)))).then(s=>Pp.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Hv(r,s,r.path,a)));return Pp.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:Yn.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:Yn.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:Yn.toString(r)}})}nonempty(e){return this.min(1,e)}};JI.create=(t,e)=>new JI({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Lr.ZodArray,...bo(e)});Og=class t extends Eo{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ss.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==In.object){let l=this._getOrReturnCtx(e);return pn(l,{code:Mr.invalid_type,expected:In.object,received:l.parsedType}),Ci}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Eb&&this._def.unknownKeys==="strip"))for(let l in i.data)s.includes(l)||a.push(l);let u=[];for(let l of s){let c=o[l],f=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new Hv(i,f,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof Eb){let l=this._def.unknownKeys;if(l==="passthrough")for(let c of a)u.push({key:{status:"valid",value:c},value:{status:"valid",value:i.data[c]}});else if(l==="strict")a.length>0&&(pn(i,{code:Mr.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let c of a){let f=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new Hv(i,f,i.path,c)),alwaysSet:c in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let c of u){let f=await c.key,h=await c.value;l.push({key:f,value:h,alwaysSet:c.alwaysSet})}return l}).then(l=>Pp.mergeObjectSync(n,l)):Pp.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return Yn.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Yn.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Lr.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ss.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ss.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return BH(this)}partial(e){let r={};for(let n of ss.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ss.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Vv;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return bwr(ss.objectKeys(this.shape))}};Og.create=(t,e)=>new Og({shape:()=>t,unknownKeys:"strip",catchall:Eb.create(),typeName:Lr.ZodObject,...bo(e)});Og.strictCreate=(t,e)=>new Og({shape:()=>t,unknownKeys:"strict",catchall:Eb.create(),typeName:Lr.ZodObject,...bo(e)});Og.lazycreate=(t,e)=>new Og({shape:t,unknownKeys:"strip",catchall:Eb.create(),typeName:Lr.ZodObject,...bo(e)});xk=class extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new Ng(a.ctx.common.issues));return pn(r,{code:Mr.invalid_union,unionErrors:s}),Ci}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let u of n){let l={...r,common:{...r.common,issues:[]},parent:null},c=u._parseSync({data:r.data,path:r.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!o&&(o={result:c,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(u=>new Ng(u));return pn(r,{code:Mr.invalid_union,unionErrors:a}),Ci}}get options(){return this._def.options}};xk.create=(t,e)=>new xk({options:t,typeName:Lr.ZodUnion,...bo(e)});WI=t=>t instanceof Ok?WI(t.schema):t instanceof Gv?WI(t.innerType()):t instanceof Rk?[t.value]:t instanceof Pk?t.options:t instanceof Bk?ss.objectValues(t.enum):t instanceof kk?WI(t._def.innerType):t instanceof Ik?[void 0]:t instanceof Tk?[null]:t instanceof Vv?[void 0,...WI(t.unwrap())]:t instanceof NS?[null,...WI(t.unwrap())]:t instanceof tae||t instanceof Fk?WI(t.unwrap()):t instanceof Mk?WI(t._def.innerType):[],t3e=class t extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==In.object)return pn(r,{code:Mr.invalid_type,expected:In.object,received:r.parsedType}),Ci;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(pn(r,{code:Mr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Ci)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let s=WI(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:Lr.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...bo(n)})}};Nk=class extends Eo{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(Xxe(o)||Xxe(s))return Ci;let a=alt(o.value,s.value);return a.valid?((e3e(o)||e3e(s))&&r.dirty(),{status:r.value,value:a.data}):(pn(n,{code:Mr.invalid_intersection_types}),Ci)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Nk.create=(t,e,r)=>new Nk({left:t,right:e,typeName:Lr.ZodIntersection,...bo(r)});xS=class t extends Eo{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==In.array)return pn(n,{code:Mr.invalid_type,expected:In.array,received:n.parsedType}),Ci;if(n.data.length<this._def.items.length)return pn(n,{code:Mr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ci;!this._def.rest&&n.data.length>this._def.items.length&&(pn(n,{code:Mr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Hv(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Pp.mergeArray(r,s)):Pp.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xS.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xS({items:t,typeName:Lr.ZodTuple,rest:null,...bo(e)})};r3e=class t extends Eo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==In.object)return pn(n,{code:Mr.invalid_type,expected:In.object,received:n.parsedType}),Ci;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Hv(n,a,n.path,a)),value:s._parse(new Hv(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Pp.mergeObjectAsync(r,i):Pp.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Eo?new t({keyType:e,valueType:r,typeName:Lr.ZodRecord,...bo(n)}):new t({keyType:_N.create(),valueType:e,typeName:Lr.ZodRecord,...bo(r)})}},FH=class extends Eo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==In.map)return pn(n,{code:Mr.invalid_type,expected:In.map,received:n.parsedType}),Ci;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,u],l)=>({key:i._parse(new Hv(n,a,n.path,[l,"key"])),value:o._parse(new Hv(n,u,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of s){let l=await u.key,c=await u.value;if(l.status==="aborted"||c.status==="aborted")return Ci;(l.status==="dirty"||c.status==="dirty")&&r.dirty(),a.set(l.value,c.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of s){let l=u.key,c=u.value;if(l.status==="aborted"||c.status==="aborted")return Ci;(l.status==="dirty"||c.status==="dirty")&&r.dirty(),a.set(l.value,c.value)}return{status:r.value,value:a}}}};FH.create=(t,e,r)=>new FH({valueType:e,keyType:t,typeName:Lr.ZodMap,...bo(r)});LH=class t extends Eo{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==In.set)return pn(n,{code:Mr.invalid_type,expected:In.set,received:n.parsedType}),Ci;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(pn(n,{code:Mr.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(pn(n,{code:Mr.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(u){let l=new Set;for(let c of u){if(c.status==="aborted")return Ci;c.status==="dirty"&&r.dirty(),l.add(c.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((u,l)=>o._parse(new Hv(n,u,n.path,l)));return n.common.async?Promise.all(a).then(u=>s(u)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:Yn.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:Yn.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};LH.create=(t,e)=>new LH({valueType:t,minSize:null,maxSize:null,typeName:Lr.ZodSet,...bo(e)});n3e=class t extends Eo{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==In.function)return pn(r,{code:Mr.invalid_type,expected:In.function,received:r.parsedType}),Ci;function n(a,u){return eae({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,RH(),KI].filter(l=>!!l),issueData:{code:Mr.invalid_arguments,argumentsError:u}})}function i(a,u){return eae({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,RH(),KI].filter(l=>!!l),issueData:{code:Mr.invalid_return_type,returnTypeError:u}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof EN){let a=this;return wh(async function(...u){let l=new Ng([]),c=await a._def.args.parseAsync(u,o).catch(m=>{throw l.addIssue(n(u,m)),l}),f=await Reflect.apply(s,this,c);return await a._def.returns._def.type.parseAsync(f,o).catch(m=>{throw l.addIssue(i(f,m)),l})})}else{let a=this;return wh(function(...u){let l=a._def.args.safeParse(u,o);if(!l.success)throw new Ng([n(u,l.error)]);let c=Reflect.apply(s,this,l.data),f=a._def.returns.safeParse(c,o);if(!f.success)throw new Ng([i(c,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:xS.create(e).rest(YI.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||xS.create([]).rest(YI.create()),returns:r||YI.create(),typeName:Lr.ZodFunction,...bo(n)})}},Ok=class extends Eo{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ok.create=(t,e)=>new Ok({getter:t,typeName:Lr.ZodLazy,...bo(e)});Rk=class extends Eo{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return pn(r,{received:r.data,code:Mr.invalid_literal,expected:this._def.value}),Ci}return{status:"valid",value:e.data}}get value(){return this._def.value}};Rk.create=(t,e)=>new Rk({value:t,typeName:Lr.ZodLiteral,...bo(e)});Pk=class t extends Eo{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return pn(r,{expected:ss.joinValues(n),received:r.parsedType,code:Mr.invalid_type}),Ci}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return pn(r,{received:r.data,code:Mr.invalid_enum_value,options:n}),Ci}return wh(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Pk.create=bwr;Bk=class extends Eo{_parse(e){let r=ss.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==In.string&&n.parsedType!==In.number){let i=ss.objectValues(r);return pn(n,{expected:ss.joinValues(i),received:n.parsedType,code:Mr.invalid_type}),Ci}if(this._cache||(this._cache=new Set(ss.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ss.objectValues(r);return pn(n,{received:n.data,code:Mr.invalid_enum_value,options:i}),Ci}return wh(e.data)}get enum(){return this._def.values}};Bk.create=(t,e)=>new Bk({values:t,typeName:Lr.ZodNativeEnum,...bo(e)});EN=class extends Eo{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==In.promise&&r.common.async===!1)return pn(r,{code:Mr.invalid_type,expected:In.promise,received:r.parsedType}),Ci;let n=r.parsedType===In.promise?r.data:Promise.resolve(r.data);return wh(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};EN.create=(t,e)=>new EN({type:t,typeName:Lr.ZodPromise,...bo(e)});Gv=class extends Eo{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Lr.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{pn(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return Ci;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?Ci:u.status==="dirty"?Ek(u.value):r.value==="dirty"?Ek(u.value):u});{if(r.value==="aborted")return Ci;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?Ci:a.status==="dirty"?Ek(a.value):r.value==="dirty"?Ek(a.value):a}}if(i.type==="refinement"){let s=a=>{let u=i.refinement(a,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Ci:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?Ci:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!AN(s))return Ci;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>AN(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):Ci);ss.assertNever(i)}};Gv.create=(t,e,r)=>new Gv({schema:t,typeName:Lr.ZodEffects,effect:e,...bo(r)});Gv.createWithPreprocess=(t,e,r)=>new Gv({schema:e,effect:{type:"preprocess",transform:t},typeName:Lr.ZodEffects,...bo(r)});Vv=class extends Eo{_parse(e){return this._getType(e)===In.undefined?wh(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vv.create=(t,e)=>new Vv({innerType:t,typeName:Lr.ZodOptional,...bo(e)});NS=class extends Eo{_parse(e){return this._getType(e)===In.null?wh(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};NS.create=(t,e)=>new NS({innerType:t,typeName:Lr.ZodNullable,...bo(e)});kk=class extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===In.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};kk.create=(t,e)=>new kk({innerType:t,typeName:Lr.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...bo(e)});Mk=class extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return PH(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ng(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ng(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Mk.create=(t,e)=>new Mk({innerType:t,typeName:Lr.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...bo(e)});jH=class extends Eo{_parse(e){if(this._getType(e)!==In.nan){let n=this._getOrReturnCtx(e);return pn(n,{code:Mr.invalid_type,expected:In.nan,received:n.parsedType}),Ci}return{status:"valid",value:e.data}}};jH.create=t=>new jH({typeName:Lr.ZodNaN,...bo(t)});Yxi=Symbol("zod_brand"),tae=class extends Eo{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},rae=class t extends Eo{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Ci:o.status==="dirty"?(r.dirty(),Ek(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ci:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Lr.ZodPipeline})}},Fk=class extends Eo{_parse(e){let r=this._def.innerType._parse(e),n=i=>(AN(i)&&(i.value=Object.freeze(i.value)),i);return PH(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Fk.create=(t,e)=>new Fk({innerType:t,typeName:Lr.ZodReadonly,...bo(e)});Jxi={object:Og.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Lr||(Lr={}));Zxi=(t,e={message:`Input not instance of ${t.name}`})=>Ewr(r=>r instanceof t,e),Dwr=_N.create,Swr=Dk.create,Xxi=jH.create,e3i=Sk.create,wwr=wk.create,t3i=Ck.create,r3i=kH.create,n3i=Ik.create,i3i=Tk.create,o3i=bN.create,s3i=YI.create,a3i=Eb.create,u3i=MH.create,l3i=JI.create,c3i=Og.create,d3i=Og.strictCreate,f3i=xk.create,p3i=t3e.create,h3i=Nk.create,m3i=xS.create,g3i=r3e.create,y3i=FH.create,v3i=LH.create,A3i=n3e.create,_3i=Ok.create,b3i=Rk.create,E3i=Pk.create,D3i=Bk.create,S3i=EN.create,w3i=Gv.create,C3i=Vv.create,I3i=NS.create,T3i=Gv.createWithPreprocess,x3i=rae.create,N3i=()=>Dwr().optional(),O3i=()=>Swr().optional(),R3i=()=>wwr().optional(),P3i={string:(t=>_N.create({...t,coerce:!0})),number:(t=>Dk.create({...t,coerce:!0})),boolean:(t=>wk.create({...t,coerce:!0})),bigint:(t=>Sk.create({...t,coerce:!0})),date:(t=>Ck.create({...t,coerce:!0}))},B3i=Ci});var X={};vn(X,{BRAND:()=>Yxi,DIRTY:()=>Ek,EMPTY_PATH:()=>Txi,INVALID:()=>Ci,NEVER:()=>B3i,OK:()=>wh,ParseStatus:()=>Pp,Schema:()=>Eo,ZodAny:()=>bN,ZodArray:()=>JI,ZodBigInt:()=>Sk,ZodBoolean:()=>wk,ZodBranded:()=>tae,ZodCatch:()=>Mk,ZodDate:()=>Ck,ZodDefault:()=>kk,ZodDiscriminatedUnion:()=>t3e,ZodEffects:()=>Gv,ZodEnum:()=>Pk,ZodError:()=>Ng,ZodFirstPartyTypeKind:()=>Lr,ZodFunction:()=>n3e,ZodIntersection:()=>Nk,ZodIssueCode:()=>Mr,ZodLazy:()=>Ok,ZodLiteral:()=>Rk,ZodMap:()=>FH,ZodNaN:()=>jH,ZodNativeEnum:()=>Bk,ZodNever:()=>Eb,ZodNull:()=>Tk,ZodNullable:()=>NS,ZodNumber:()=>Dk,ZodObject:()=>Og,ZodOptional:()=>Vv,ZodParsedType:()=>In,ZodPipeline:()=>rae,ZodPromise:()=>EN,ZodReadonly:()=>Fk,ZodRecord:()=>r3e,ZodSchema:()=>Eo,ZodSet:()=>LH,ZodString:()=>_N,ZodSymbol:()=>kH,ZodTransformer:()=>Gv,ZodTuple:()=>xS,ZodType:()=>Eo,ZodUndefined:()=>Ik,ZodUnion:()=>xk,ZodUnknown:()=>YI,ZodVoid:()=>MH,addIssueToContext:()=>pn,any:()=>o3i,array:()=>l3i,bigint:()=>e3i,boolean:()=>wwr,coerce:()=>P3i,custom:()=>Ewr,date:()=>t3i,datetimeRegex:()=>_wr,defaultErrorMap:()=>KI,discriminatedUnion:()=>p3i,effect:()=>w3i,enum:()=>E3i,function:()=>A3i,getErrorMap:()=>RH,getParsedType:()=>TS,instanceof:()=>Zxi,intersection:()=>h3i,isAborted:()=>Xxe,isAsync:()=>PH,isDirty:()=>e3e,isValid:()=>AN,late:()=>Jxi,lazy:()=>_3i,literal:()=>b3i,makeIssue:()=>eae,map:()=>y3i,nan:()=>Xxi,nativeEnum:()=>D3i,never:()=>a3i,null:()=>i3i,nullable:()=>I3i,number:()=>Swr,object:()=>c3i,objectUtil:()=>nlt,oboolean:()=>R3i,onumber:()=>O3i,optional:()=>C3i,ostring:()=>N3i,pipeline:()=>x3i,preprocess:()=>T3i,promise:()=>S3i,quotelessJson:()=>wxi,record:()=>g3i,set:()=>v3i,setErrorMap:()=>Ixi,strictObject:()=>d3i,string:()=>Dwr,symbol:()=>r3i,transformer:()=>w3i,tuple:()=>m3i,undefined:()=>n3i,union:()=>f3i,unknown:()=>s3i,util:()=>ss,void:()=>u3i});var ult=g(()=>{Zxe();olt();hwr();Xse();Cwr();Jxe()});var Cd=g(()=>{ult();ult()});function Twr(t){return k3i.includes(t)}function xwr(t){if(/^C-(.+)$/i.test(t)){let e=t.slice(2).toLowerCase();return e.length===1&&e>="a"&&e<="z"?String.fromCharCode(e.charCodeAt(0)-96):e==="space"||e==="@"?"\0":e==="["?"\x1B":e==="\\"?"":e==="]"?"":e==="^"?"":e==="_"?"":t}return/^M-(.+)$/i.test(t)?"\x1B"+t.slice(2):/^[A-Z]/.test(t)&&t.length>1&&Iwr[t]?Iwr[t]:t}var k3i,Iwr,Nwr=g(()=>{k3i=["\u82F1\u6570","\u304B\u306A","Eisu","Kana"];Iwr={Enter:"\r",Escape:"\x1B",Tab:" ",Space:" ",BSpace:"\x7F",Backspace:"\x7F",DC:"\x1B[3~",Delete:"\x1B[3~",Up:"\x1B[A",Down:"\x1B[B",Right:"\x1B[C",Left:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",PageUp:"\x1B[5~",PageDown:"\x1B[6~",Insert:"\x1B[2~",F1:"\x1BOP",F2:"\x1BOQ",F3:"\x1BOR",F4:"\x1BOS",F5:"\x1B[15~",F6:"\x1B[17~",F7:"\x1B[18~",F8:"\x1B[19~",F9:"\x1B[20~",F10:"\x1B[21~",F11:"\x1B[23~",F12:"\x1B[24~"}});import{randomUUID as M3i}from"crypto";function llt(t){return N(this,void 0,void 0,function*(){try{return yield t.req.json()}catch{return null}})}function Owr(){let t=new Vu;return t.post("/sessions",e=>N(this,void 0,void 0,function*(){var r,n;let i=F3i.safeParse(yield llt(e));if(!i.success)return e.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let o=i.data,s=(r=o.id)!==null&&r!==void 0?r:M3i(),a=yield Gl().createSession({id:s,name:(n=o.name)!==null&&n!==void 0?n:s.slice(0,8),command:o.command,parentId:o.parentId,cwd:o.cwd,env:o.env});return e.json(vN(a),201)})),t.patch("/sessions/:id",e=>N(this,void 0,void 0,function*(){let r=e.req.param("id"),n=L3i.safeParse(yield llt(e));if(!n.success)return e.json({error:{code:"INVALID_BODY",message:n.error.message}},400);let i=Gl().getSession(r);if(!i)return e.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);let{name:o,status:s,cols:a,rows:u}=n.data;a!==void 0&&u!==void 0&&Gl().resize(r,a,u),s==="detached"&&(i.status="detached"),o!==void 0&&Gl().renameSession(r,o);let l=Gl().getSession(r);return e.json(vN(l??i))})),t.delete("/sessions/:id",e=>N(this,void 0,void 0,function*(){let r=e.req.param("id");return yield Gl().destroySession(r),e.json({success:!0,id:r})})),t.post("/sessions/:id/input",e=>N(this,void 0,void 0,function*(){let r=e.req.param("id"),n=yield llt(e),i=j3i.safeParse(n),o=i.success?null:$3i.safeParse(n);if(!i.success&&!o?.success)return e.json({error:{code:"INVALID_BODY",message:"body \u306F {data} \u307E\u305F\u306F {keys, literal?}"}},400);if(!Gl().getSession(r))return e.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);if(i.success)return Gl().input(r,i.data.data),e.json({success:!0,id:r});let{keys:s,literal:a}=o.success?o.data:{keys:[],literal:!1},u=s.filter(l=>!Twr(l)).map(l=>a?l:xwr(l)).join("");return u.length>0&&Gl().input(r,u),e.json({success:!0,id:r})})),t}var F3i,L3i,j3i,$3i,Rwr=g(()=>{Se();ey();Cd();zI();Zse();Nwr();F3i=X.object({id:X.string().optional(),name:X.string().optional(),command:X.string().optional(),parentId:X.string().optional(),cwd:X.string().optional(),env:X.record(X.string(),X.string()).optional()}),L3i=X.object({name:X.string().optional(),status:X.literal("detached").optional(),cols:X.number().optional(),rows:X.number().optional()}).refine(t=>t.name!==void 0||t.status!==void 0||t.cols!==void 0&&t.rows!==void 0,{message:"name / status / {cols,rows} \u306E\u3044\u305A\u308C\u304B\u304C\u5FC5\u8981"}),j3i=X.object({data:X.string()}),$3i=X.object({keys:X.array(X.string()),literal:X.boolean().optional()})});function Pwr(){let t=new Vu;return t.put("/sessions/:id/stream-config",e=>N(this,void 0,void 0,function*(){let r=e.req.param("id"),n=null;try{n=yield e.req.json()}catch{}let i=q3i.safeParse(n);if(!i.success)return e.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let{peerId:o,fps:s}=i.data,a=`${o}\0${r}`;return rlt().set(a,{fps:s}),Xut(r,s),e.json({success:!0,id:r})})),t.get("/system/wt-config",e=>N(this,void 0,void 0,function*(){return e.json(yield Yut())})),t}var q3i,Bwr=g(()=>{Se();ey();Cd();zI();q3i=X.object({peerId:X.string(),fps:X.number()})});function i3e(t){var e,r;let n=(e=t.intervalMs)!==null&&e!==void 0?e:25e3,i=(r=t.now)!==null&&r!==void 0?r:(()=>Date.now()),o=new TextEncoder,s=!1,a=setInterval(()=>{if(!s)try{t.enqueue(o.encode(`: heartbeat ${i()}
|
|
555
555
|
|
|
556
556
|
`))}catch{u()}},n),u=()=>{s||(s=!0,clearInterval(a))};return t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u,{once:!0})),u}var clt=g(()=>{});function kwr(t){let e=new TextEncoder,r;try{r=t.req.raw.signal}catch{r=void 0}let n=!1,i=null,o=null,s=()=>{n=!0;try{i?.unsubscribe()}catch{}try{o?.()}catch{}},a=new ReadableStream({start(u){u.enqueue(e.encode(`: sse-init
|
|
557
557
|
|
|
@@ -1220,7 +1220,7 @@ Error: ${f}
|
|
|
1220
1220
|
To fix: Run "planx server restart" in your terminal.`)}return Oy(`Server Status: CONNECTED
|
|
1221
1221
|
Transport Port File: ${c.transportPortFile}
|
|
1222
1222
|
Transport Port Exists: ${c.transportPortExists}`)})),t.tool("list_sessions",{serverId:X.string().optional().describe("Server ID or name to filter sessions"),parentId:X.string().optional().describe("Parent session ID to filter child sessions")},c=>N(this,void 0,void 0,function*(){try{let f=Ny(),h=Asn(c.serverId,f),m=rSt(c.parentId,f),A=s.listSessions(h,{timeout:8e3});A.catch(()=>{});let E=yield Promise.race([A,new Promise((b,S)=>setTimeout(()=>S(new Error("list_sessions timed out after 9s (server unreachable)")),9e3))]);return E=bsn(E,f),m&&!c0(f)&&(E=E.filter(b=>b.parentId===m)),Oy(`Found ${E.length} sessions
|
|
1223
|
-
${JSON.stringify(E,null,2)}`)}catch(f){return Zx(f)}})),t.tool("create_session",{serverId:X.string().optional().describe("Target server ID or name to create session on"),name:X.string().describe("Session name"),command:X.string().optional().describe("Command to run (default: ~/.planx/config.json `defaultCommand` or /bin/bash)"),parentId:X.string().optional().describe("Parent session ID for hierarchical sessions"),cwd:X.string().optional().describe("Working directory for the session"),env:X.record(X.string()).optional().describe("Environment variables for the session")},c=>N(this,void 0,void 0,function*(){let f=Date.now();console.error(`[MCP create_session] START serverId=${c.serverId} name=${c.name} parentId=${c.parentId||"none"}`);try{let h=Ny(),m=r.getServers?yield r.getServers():[],A=yield W7(c.serverId,h,m);if(!A)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");let E=rSt(c.parentId,h),b=yield n.createSession({id:my(),serverId:A,name:c.name,command:c.command||l||"/bin/bash",parentId:E,cwd:c.cwd,env:c.env});return console.error(`[MCP create_session] SUCCESS elapsed=${Date.now()-f}ms`),Oy(`Session created successfully
|
|
1223
|
+
${JSON.stringify(E,null,2)}`)}catch(f){return Zx(f)}})),t.tool("create_session",{serverId:X.string().optional().describe("Target server ID or name to create session on"),name:X.string().describe("Session name"),command:X.string().optional().describe("Command to run (default: ~/.planx/config.json `defaultCommand` or /bin/bash)"),parentId:X.string().optional().describe("Parent session ID for hierarchical sessions"),cwd:X.string().optional().describe("Working directory for the session"),env:X.record(X.string(),X.string()).optional().describe("Environment variables for the session")},c=>N(this,void 0,void 0,function*(){let f=Date.now();console.error(`[MCP create_session] START serverId=${c.serverId} name=${c.name} parentId=${c.parentId||"none"}`);try{let h=Ny(),m=r.getServers?yield r.getServers():[],A=yield W7(c.serverId,h,m);if(!A)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");let E=rSt(c.parentId,h),b=yield n.createSession({id:my(),serverId:A,name:c.name,command:c.command||l||"/bin/bash",parentId:E,cwd:c.cwd,env:c.env});return console.error(`[MCP create_session] SUCCESS elapsed=${Date.now()-f}ms`),Oy(`Session created successfully
|
|
1224
1224
|
${JSON.stringify(b,null,2)}`)}catch(h){return console.error(`[MCP create_session] ERROR elapsed=${Date.now()-f}ms error=${h?.message}`),Zx(h)}})),t.tool("rename_session",{serverId:X.string().optional().describe("Server ID or name where the session exists"),sessionId:X.string().describe("Session ID to rename"),newName:X.string().describe("New name for the session")},c=>N(this,void 0,void 0,function*(){try{let f=Ny(),h=r.getServers?yield r.getServers():[],m=yield W7(c.serverId,f,h);if(!m)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");return yield $Y(m,c.sessionId,f,s),yield o.renameSession({serverId:m,sessionId:c.sessionId,newName:c.newName}),Oy(`Session renamed to "${c.newName}" successfully`)}catch(f){return Zx(f)}})),t.tool("delete_session",{serverId:X.string().optional().describe("Server ID or name where the session exists"),sessionId:X.string().describe("Session ID to delete")},c=>N(this,void 0,void 0,function*(){try{let f=Ny(),h=r.getServers?yield r.getServers():[],m=yield W7(c.serverId,f,h);if(!m)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");return yield $Y(m,c.sessionId,f,s),yield i.deleteSession({serverId:m,sessionId:c.sessionId}),Oy(`Session ${c.sessionId} deleted successfully`)}catch(f){return Zx(f)}})),t.tool("send_keys",{serverId:X.string().optional().describe("Server ID or name where the session exists"),sessionId:X.string().describe("Session ID to send keys to"),keys:X.array(X.string()).describe("Keys to send (e.g., ['ls -la', 'Enter'], ['C-c'] for Ctrl+C)"),literal:X.boolean().optional().describe("If true, send keys literally without interpretation")},c=>N(this,void 0,void 0,function*(){try{let f=Ny(),h=r.getServers?yield r.getServers():[],m=yield W7(c.serverId,f,h);if(!m)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");return yield $Y(m,c.sessionId,f,s),yield u.sendKeysToSession(m,c.sessionId,c.keys,{literal:c.literal}),Oy(`Keys sent successfully to session ${c.sessionId}`)}catch(f){return Zx(f)}})),t.tool("get_session_output",{serverId:X.string().optional().describe("Server ID or name where the session exists"),sessionId:X.string().describe("Session ID to get output from"),lines:X.number().optional().describe("Number of lines to retrieve (default: all)")},c=>N(this,void 0,void 0,function*(){try{let f=Ny(),h=r.getServers?yield r.getServers():[],m=yield W7(c.serverId,f,h);if(!m)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");yield $Y(m,c.sessionId,f,s);let A=yield a.getOutput({serverId:m,sessionId:c.sessionId,lines:c.lines});return Oy(A.output||"(no output)")}catch(f){return Zx(f)}})),t.tool("resize_session",{serverId:X.string().optional().describe("Server ID or name where the session exists"),sessionId:X.string().describe("Session ID to resize"),cols:X.number().describe("Number of columns"),rows:X.number().describe("Number of rows")},c=>N(this,void 0,void 0,function*(){try{let f=Ny(),h=r.getServers?yield r.getServers():[],m=yield W7(c.serverId,f,h);if(!m)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");yield $Y(m,c.sessionId,f,s);let A=yield r.resolveServerPeerId(m);return yield r.resize(A,c.sessionId,{cols:c.cols,rows:c.rows}),Oy(`Session ${c.sessionId} resized to ${c.cols}x${c.rows}`)}catch(f){return Zx(f)}}))}var Ssn=g(()=>{Se();Cd();a1();w5e()});var wsn=g(()=>{});import{readFile as Poo}from"fs/promises";import{homedir as Boo}from"os";import{join as koo}from"path";function Isn(){return N(this,void 0,void 0,function*(){var t,e,r;try{let n=yield Poo(Csn,"utf-8"),i=JSON.parse(n);if(!(!((t=i.env)===null||t===void 0)&&t.ANTHROPIC_AUTH_TOKEN))throw new Error("ANTHROPIC_AUTH_TOKEN is required in settings.zai.json");if(!(!((e=i.env)===null||e===void 0)&&e.ANTHROPIC_BASE_URL))throw new Error("ANTHROPIC_BASE_URL is required in settings.zai.json");if(!(!((r=i.env)===null||r===void 0)&&r.ANTHROPIC_DEFAULT_SONNET_MODEL))throw new Error("ANTHROPIC_DEFAULT_SONNET_MODEL is required in settings.zai.json");return i}catch(n){throw n.code==="ENOENT"?new Error(`z.ai settings file not found at ${Csn}. Please create it with the following format:
|
|
1225
1225
|
`+JSON.stringify({env:{ANTHROPIC_AUTH_TOKEN:"your-zai-api-key",ANTHROPIC_BASE_URL:"https://api.z.ai/api/anthropic",ANTHROPIC_DEFAULT_SONNET_MODEL:"glm-4.7"}},null,2)):n}})}var Csn,Tsn=g(()=>{Se();Csn=koo(Boo(),".claude","settings.zai.json")});function qY(t){return new Promise(e=>setTimeout(e,t))}function Nsn(){return`subagent-${Date.now()}`}function Osn(t){return[[`export ANTHROPIC_AUTH_TOKEN='${t.env.ANTHROPIC_AUTH_TOKEN}'`,"Enter"],[`export ANTHROPIC_BASE_URL='${t.env.ANTHROPIC_BASE_URL}'`,"Enter"],[`export ANTHROPIC_DEFAULT_SONNET_MODEL='${t.env.ANTHROPIC_DEFAULT_SONNET_MODEL}'`,"Enter"]]}function Rsn(t){switch(t){case"machina":return["machina agent --json","Enter"];case"claude":return["claude --dangerously-skip-permissions","Enter"]}}function nSt(t,e){switch(e){case"machina":return t.includes('"status"')&&(t.includes('"running"')||t.includes('"completed"'));case"claude":return t.includes(">")||t.includes("\u276F")}}function Psn(t,e){switch(e){case"machina":return t.includes('"status": "success"')||t.includes('"status": "error"')||t.includes('"status":"success"')||t.includes('"status":"error"');case"claude":let n=t.trim().split(`
|
|
1226
1226
|
`).slice(-5).join(`
|
|
@@ -1228,7 +1228,7 @@ ${JSON.stringify(b,null,2)}`)}catch(h){return console.error(`[MCP create_session
|
|
|
1228
1228
|
${E.output}`);return UY.info("[Subagent] Agent started successfully"),f})}var UY,ksn=g(()=>{Se();a1();kr();C5e();UY=ct("Subagent")});function Fsn(t,e){return N(this,void 0,void 0,function*(){let{serverId:r,sessionId:n,sessionName:i,agentType:o,startTime:s,timeoutMs:a}=t,u=o==="machina"?50:20;for(;Date.now()-s<a;){yield qY(5e3);let c=yield e.getOutput({serverId:r,sessionId:n,lines:u});if(Psn(c.output||"",o)){Msn.info("[Subagent] Task completed");let f=yield e.getOutput({serverId:r,sessionId:n,lines:100});return{sessionId:n,sessionName:i,status:"completed",output:f.output||"",duration:Math.round((Date.now()-s)/1e3),agentType:o}}}Msn.warn("[Subagent] Task timed out");let l=yield e.getOutput({serverId:r,sessionId:n,lines:100});return{sessionId:n,sessionName:i,status:"timeout",output:l.output||"",duration:Math.round((Date.now()-s)/1e3),agentType:o,error:`Task timed out after ${Math.round(a/1e3)} seconds`}})}var Msn,Lsn=g(()=>{Se();kr();C5e();Msn=ct("Subagent")});function jsn(t,e,r,n){return N(this,void 0,void 0,function*(){let{task:i,agentType:o,timeout:s,sessionName:a}=t,{serverId:u,parentId:l}=e,{sessionCreateService:c,sessionLogService:f,sendKeyUsecase:h}=n,m=Date.now(),A=a||Nsn(),E;try{return E=yield Bsn({serverId:u,parentId:l,sessionName:A,agentType:o,settings:r},{sessionCreateService:c,sessionLogService:f,sendKeyUsecase:h}),console.error("[Subagent] Sending task"),yield h.sendKeysToSession(u,E,[i,"Enter"]),console.error("[Subagent] Waiting for task completion"),yield Fsn({serverId:u,sessionId:E,sessionName:A,agentType:o,startTime:m,timeoutMs:s*1e3},f)}catch(b){return console.error(`[Subagent] Error: ${b.message}`),{sessionId:E||"",sessionName:A,status:"error",output:"",duration:Math.round((Date.now()-m)/1e3),agentType:o,error:b.message}}})}var $sn=g(()=>{Se();C5e();ksn();Lsn()});var qsn=g(()=>{wsn();Tsn();$sn()});function Foo(t){return{content:[{type:"text",text:t}]}}function iSt(t){let e=t?.message||String(t);return console.error(`[Subagent Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function Loo(t){let e=["## Subagent Result","",`**Status**: ${t.status}`,`**Agent Type**: ${t.agentType}`,`**Duration**: ${t.duration}s`,`**Session ID**: ${t.sessionId}`,`**Session Name**: ${t.sessionName}`,""];return t.error&&e.push(`**Error**: ${t.error}`,""),e.push("### Output","```",t.output,"```"),e.join(`
|
|
1229
1229
|
`)}function Usn(t,e){t.tool("run_subagent",{task:X.string().describe("Task to execute"),agentType:X.enum(["machina","claude"]).default("machina").describe("Agent type (machina: lightweight, claude: full-featured)"),timeout:X.number().optional().default(300).describe("Timeout in seconds (default: 300)"),sessionName:X.string().optional().describe("Session name (default: subagent-{timestamp})")},r=>N(this,void 0,void 0,function*(){var n;let i=Date.now();console.error(`[MCP run_subagent] START task="${r.task.substring(0,50)}..." agentType=${r.agentType}`);try{let o=Ny();if(!c0(o))return iSt(new Error("run_subagent requires restricted mode. Please set PLANX_SERVER_ID and PLANX_SESSION_ID environment variables."));if(!o.serverId||!o.sessionId)return iSt(new Error("PLANX_SERVER_ID and PLANX_SESSION_ID are required."));let s=yield Isn(),a={task:r.task,agentType:r.agentType,timeout:(n=r.timeout)!==null&&n!==void 0?n:300,sessionName:r.sessionName},u={serverId:o.serverId,parentId:o.sessionId},l=yield jsn(a,u,s,e);return console.error(`[MCP run_subagent] DONE status=${l.status} elapsed=${Date.now()-i}ms`),Foo(Loo(l))}catch(o){return console.error(`[MCP run_subagent] ERROR elapsed=${Date.now()-i}ms error=${o?.message}`),iSt(o)}}))}var Qsn=g(()=>{Se();Cd();w5e();qsn()});import{existsSync as joo,readFileSync as $oo,writeFileSync as Vsn}from"fs";import{homedir as qoo}from"os";import{join as Uoo}from"path";function Hsn(t,e,r){let n=Uoo(qoo(),".claude","teams",t,"config.json");if(!joo(n))throw new Error(`Team config not found: ${n}. TeamCreate must be called before create_subagent.`);let i=JSON.parse($oo(n,"utf-8")),o=`${e}@${t}`,s=i.members.find(a=>a.agentId===o);return s?(s.isActive=!0,s.cwd=r,Vsn(n,JSON.stringify(i,null,2)+`
|
|
1230
1230
|
`),{agentId:o,created:!1}):(i.members.push({agentId:o,name:e,agentType:"worker",model:"claude-opus-4-6",joinedAt:Date.now(),tmuxPaneId:"",cwd:r,subscriptions:[],isActive:!0}),Vsn(n,JSON.stringify(i,null,2)+`
|
|
1231
|
-
`),{agentId:o,created:!0})}var Gsn=g(()=>{});function Qoo(t,e){return[["CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1","claude","--dangerously-skip-permissions",`--agent-name ${t}`,`--agent-id ${t}@${e}`,`--team-name ${e}`,"--session-id $(uuidgen)"].join(" "),"Enter"]}function oSt(t,e,r){return N(this,void 0,void 0,function*(){let{teamName:n,workerName:i,cwd:o}=t,{serverId:s,parentId:a,parentName:u}=e,{sessionCreateService:l,sendKeyUsecase:c}=r,f=o||process.cwd();Dhe.info(`[create_subagent] Adding worker ${i} to team ${n}`);let{agentId:h,created:m}=Hsn(n,i,f);Dhe.info(`[create_subagent] Worker ${m?"created":"updated"}: ${h}`);let A=`${n}-${i}`;Dhe.info(`[create_subagent] Creating session: ${A}`);let E=yield l.createSession({id:my(),serverId:s,name:A,command:"/bin/zsh",parentId:a,cwd:f,env:{PLANX_IS_SUBAGENT:"1",PLANX_AGENT_NAME:i,PLANX_AGENT_ROLES:"worker",PLANX_AGENT_TEAM_NAME:n,PLANX_AGENT_PARENT_NAME:u,PLANX_SERVER_ID:s}});Dhe.info(`[create_subagent] Session created: ${E.id}`),Dhe.info("[create_subagent] Sending claude startup command");let b=Qoo(i,n);return yield c.sendKeysToSession(s,E.id,b),{sessionId:E.id,sessionName:A,agentId:h,teamName:n,workerName:i}})}var Dhe,zsn=g(()=>{Se();a1();kr();Gsn();Dhe=ct("create_subagent")});var Ksn=g(()=>{zsn()});function Voo(t){return{content:[{type:"text",text:t}]}}function sSt(t){let e=t?.message||String(t);return console.error(`[create_subagent Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function Wsn(t,e){t.tool("create_subagent",{teamName:X.string().describe("Team name (from TeamCreate)"),workerName:X.string().describe("Worker name (e.g. worker-1)"),cwd:X.string().optional().describe("Working directory for the worker session")},r=>N(this,void 0,void 0,function*(){console.error(`[MCP create_subagent] START team=${r.teamName} worker=${r.workerName}`);try{let n=Ny();if(!c0(n))return sSt(new Error("create_subagent requires restricted mode. Set PLANX_SERVER_ID and PLANX_SESSION_ID."));if(!n.serverId||!n.sessionId)return sSt(new Error("PLANX_SERVER_ID and PLANX_SESSION_ID are required."));let i={serverId:n.serverId,parentId:n.sessionId,parentName:process.env.PLANX_AGENT_NAME||"team-lead"},o=yield oSt({teamName:r.teamName,workerName:r.workerName,cwd:r.cwd},i,e);return console.error(`[MCP create_subagent] DONE session=${o.sessionId}`),Voo(JSON.stringify(o,null,2))}catch(n){return console.error(`[MCP create_subagent] ERROR: ${n?.message}`),sSt(n)}}))}var Ysn=g(()=>{Se();Cd();w5e();Ksn()});function Jsn(t,e,r,n){var i;if(r===e)return!0;let o=n.find(s=>{var a;return((a=s.env)===null||a===void 0?void 0:a.PLANX_AGENT_NAME)===r});return((i=o?.env)===null||i===void 0?void 0:i.PLANX_AGENT_PARENT_NAME)===t}var Zsn=g(()=>{});import*as Xx from"fs";import*as aSt from"path";import*as uSt from"os";function Hoo(t,e){return aSt.join(uSt.homedir(),".claude","teams",t,"inboxes",`${e}.json`)}function Goo(t){let e=aSt.join(uSt.homedir(),".claude","teams",t,"inboxes");Xx.existsSync(e)||Xx.mkdirSync(e,{recursive:!0})}function zoo(t){if(!Xx.existsSync(t))return[];let e=Xx.readFileSync(t,"utf-8");return JSON.parse(e)}function Xsn(t,e,r){Goo(t);let n=Hoo(t,e),i=zoo(n);i.push(r),Xx.writeFileSync(n,JSON.stringify(i,null,2),"utf-8")}var ean=g(()=>{});function lSt(t,e,r){return N(this,void 0,void 0,function*(){let{recipient:n,content:i,summary:o}=t,{agentName:s,teamName:a,parentName:u,serverId:l}=e,{sessionListService:c}=r,f=yield c.listSessions(l,{timeout:3e4});if(!Jsn(s,u,n,f))throw new Error(`Access denied: '${s}' cannot send messages to '${n}'. Only parent ('${u}') or child agents are allowed.`);let h=new Date().toISOString(),m=Object.assign(Object.assign({from:s,text:i},o?{summary:o}:{}),{timestamp:h,read:!1});return Xsn(a,n,m),{success:!0,recipient:n,timestamp:h}})}var tan=g(()=>{Se();Zsn();ean()});var ran=g(()=>{tan()});function Koo(t){return{content:[{type:"text",text:t}]}}function nan(t){let e=t?.message||String(t);return console.error(`[send_message Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function Woo(){return process.env.PLANX_SERVER_ID}function ian(t,e){t.tool("agent_send_message",{recipient:X.string().describe("Recipient name (e.g. team-lead, worker-1)"),content:X.string().describe("Message content"),summary:X.string().optional().describe("Brief summary of the message"),sender_name:X.string().describe("Sender agent name"),team_name:X.string().describe("Team name")},r=>N(this,void 0,void 0,function*(){var n;console.error(`[MCP agent_send_message] START from=${r.sender_name} to=${r.recipient}`);try{let i=Woo();if(!i)return nan(new Error("PLANX_SERVER_ID not set in server process."));let s=(yield e.sessionListService.listSessions(i,{timeout:3e4})).find(c=>{var f;return((f=c.env)===null||f===void 0?void 0:f.PLANX_AGENT_NAME)===r.sender_name}),a=((n=s?.env)===null||n===void 0?void 0:n.PLANX_AGENT_PARENT_NAME)||"",u={agentName:r.sender_name,teamName:r.team_name,parentName:a,serverId:i},l=yield lSt({recipient:r.recipient,content:r.content,summary:r.summary},u,e);return console.error(`[MCP agent_send_message] DONE to=${l.recipient}`),Koo(JSON.stringify(l,null,2))}catch(i){return console.error(`[MCP agent_send_message] ERROR: ${i?.message}`),nan(i)}}))}var oan=g(()=>{Se();Cd();ran()});function She(t){return{content:[{type:"text",text:t}]}}function QY(t){return{content:[{type:"text",text:`Error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function whe(t,e){let r=t.agent_name||e.defaultAgentName;if(!r)throw new Error("agent_name is required. Either pass it as parameter or set PLANX_AGENT_NAME env var.");return r}function san(t){return Om({links:[jp({url:`${t.stateServerUrl}/trpc`})]})}var aan=g(()=>{nw()});function Y7(t,e="root"){let r=[];if(!t||typeof t!="object")return r.push(`${e}: schema must be an object`),r;let n=t,i=n.type;if(i==="object")if(!n.properties||typeof n.properties!="object")r.push(`${e}: type 'object' requires 'properties' to be defined`);else for(let[o,s]of Object.entries(n.properties))r.push(...Y7(s,`${e}.${o}`));else i==="array"&&(!n.items||typeof n.items!="object"?r.push(`${e}: type 'array' requires 'items' to be defined`):r.push(...Y7(n.items,`${e}[items]`)));return r}var cSt=g(()=>{});function uan(t,e){console.error("[State Tools] Starting registration"),console.error("[State Tools] State server URL:",e.stateServerUrl),console.error("[State Tools] Default agent name:",e.defaultAgentName||"(not set)");let r=san(e),n=X.lazy(()=>X.object({type:X.enum(["string","number","boolean","array","object"]),default:X.any().optional(),items:n.optional(),properties:X.record(n).optional()}));t.tool("init_state",{agent_name:X.string().optional().describe("Unique state identifier (defaults to PLANX_AGENT_NAME env var)"),schema:X.object({type:X.literal("object"),properties:X.record(n)}).describe("JSON Schema for state structure")},i=>N(this,void 0,void 0,function*(){try{let o=whe(i,e),{schema:s}=i,a=Y7(s);if(a.length>0)return QY(`Schema validation failed:
|
|
1231
|
+
`),{agentId:o,created:!0})}var Gsn=g(()=>{});function Qoo(t,e){return[["CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1","claude","--dangerously-skip-permissions",`--agent-name ${t}`,`--agent-id ${t}@${e}`,`--team-name ${e}`,"--session-id $(uuidgen)"].join(" "),"Enter"]}function oSt(t,e,r){return N(this,void 0,void 0,function*(){let{teamName:n,workerName:i,cwd:o}=t,{serverId:s,parentId:a,parentName:u}=e,{sessionCreateService:l,sendKeyUsecase:c}=r,f=o||process.cwd();Dhe.info(`[create_subagent] Adding worker ${i} to team ${n}`);let{agentId:h,created:m}=Hsn(n,i,f);Dhe.info(`[create_subagent] Worker ${m?"created":"updated"}: ${h}`);let A=`${n}-${i}`;Dhe.info(`[create_subagent] Creating session: ${A}`);let E=yield l.createSession({id:my(),serverId:s,name:A,command:"/bin/zsh",parentId:a,cwd:f,env:{PLANX_IS_SUBAGENT:"1",PLANX_AGENT_NAME:i,PLANX_AGENT_ROLES:"worker",PLANX_AGENT_TEAM_NAME:n,PLANX_AGENT_PARENT_NAME:u,PLANX_SERVER_ID:s}});Dhe.info(`[create_subagent] Session created: ${E.id}`),Dhe.info("[create_subagent] Sending claude startup command");let b=Qoo(i,n);return yield c.sendKeysToSession(s,E.id,b),{sessionId:E.id,sessionName:A,agentId:h,teamName:n,workerName:i}})}var Dhe,zsn=g(()=>{Se();a1();kr();Gsn();Dhe=ct("create_subagent")});var Ksn=g(()=>{zsn()});function Voo(t){return{content:[{type:"text",text:t}]}}function sSt(t){let e=t?.message||String(t);return console.error(`[create_subagent Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function Wsn(t,e){t.tool("create_subagent",{teamName:X.string().describe("Team name (from TeamCreate)"),workerName:X.string().describe("Worker name (e.g. worker-1)"),cwd:X.string().optional().describe("Working directory for the worker session")},r=>N(this,void 0,void 0,function*(){console.error(`[MCP create_subagent] START team=${r.teamName} worker=${r.workerName}`);try{let n=Ny();if(!c0(n))return sSt(new Error("create_subagent requires restricted mode. Set PLANX_SERVER_ID and PLANX_SESSION_ID."));if(!n.serverId||!n.sessionId)return sSt(new Error("PLANX_SERVER_ID and PLANX_SESSION_ID are required."));let i={serverId:n.serverId,parentId:n.sessionId,parentName:process.env.PLANX_AGENT_NAME||"team-lead"},o=yield oSt({teamName:r.teamName,workerName:r.workerName,cwd:r.cwd},i,e);return console.error(`[MCP create_subagent] DONE session=${o.sessionId}`),Voo(JSON.stringify(o,null,2))}catch(n){return console.error(`[MCP create_subagent] ERROR: ${n?.message}`),sSt(n)}}))}var Ysn=g(()=>{Se();Cd();w5e();Ksn()});function Jsn(t,e,r,n){var i;if(r===e)return!0;let o=n.find(s=>{var a;return((a=s.env)===null||a===void 0?void 0:a.PLANX_AGENT_NAME)===r});return((i=o?.env)===null||i===void 0?void 0:i.PLANX_AGENT_PARENT_NAME)===t}var Zsn=g(()=>{});import*as Xx from"fs";import*as aSt from"path";import*as uSt from"os";function Hoo(t,e){return aSt.join(uSt.homedir(),".claude","teams",t,"inboxes",`${e}.json`)}function Goo(t){let e=aSt.join(uSt.homedir(),".claude","teams",t,"inboxes");Xx.existsSync(e)||Xx.mkdirSync(e,{recursive:!0})}function zoo(t){if(!Xx.existsSync(t))return[];let e=Xx.readFileSync(t,"utf-8");return JSON.parse(e)}function Xsn(t,e,r){Goo(t);let n=Hoo(t,e),i=zoo(n);i.push(r),Xx.writeFileSync(n,JSON.stringify(i,null,2),"utf-8")}var ean=g(()=>{});function lSt(t,e,r){return N(this,void 0,void 0,function*(){let{recipient:n,content:i,summary:o}=t,{agentName:s,teamName:a,parentName:u,serverId:l}=e,{sessionListService:c}=r,f=yield c.listSessions(l,{timeout:3e4});if(!Jsn(s,u,n,f))throw new Error(`Access denied: '${s}' cannot send messages to '${n}'. Only parent ('${u}') or child agents are allowed.`);let h=new Date().toISOString(),m=Object.assign(Object.assign({from:s,text:i},o?{summary:o}:{}),{timestamp:h,read:!1});return Xsn(a,n,m),{success:!0,recipient:n,timestamp:h}})}var tan=g(()=>{Se();Zsn();ean()});var ran=g(()=>{tan()});function Koo(t){return{content:[{type:"text",text:t}]}}function nan(t){let e=t?.message||String(t);return console.error(`[send_message Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function Woo(){return process.env.PLANX_SERVER_ID}function ian(t,e){t.tool("agent_send_message",{recipient:X.string().describe("Recipient name (e.g. team-lead, worker-1)"),content:X.string().describe("Message content"),summary:X.string().optional().describe("Brief summary of the message"),sender_name:X.string().describe("Sender agent name"),team_name:X.string().describe("Team name")},r=>N(this,void 0,void 0,function*(){var n;console.error(`[MCP agent_send_message] START from=${r.sender_name} to=${r.recipient}`);try{let i=Woo();if(!i)return nan(new Error("PLANX_SERVER_ID not set in server process."));let s=(yield e.sessionListService.listSessions(i,{timeout:3e4})).find(c=>{var f;return((f=c.env)===null||f===void 0?void 0:f.PLANX_AGENT_NAME)===r.sender_name}),a=((n=s?.env)===null||n===void 0?void 0:n.PLANX_AGENT_PARENT_NAME)||"",u={agentName:r.sender_name,teamName:r.team_name,parentName:a,serverId:i},l=yield lSt({recipient:r.recipient,content:r.content,summary:r.summary},u,e);return console.error(`[MCP agent_send_message] DONE to=${l.recipient}`),Koo(JSON.stringify(l,null,2))}catch(i){return console.error(`[MCP agent_send_message] ERROR: ${i?.message}`),nan(i)}}))}var oan=g(()=>{Se();Cd();ran()});function She(t){return{content:[{type:"text",text:t}]}}function QY(t){return{content:[{type:"text",text:`Error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function whe(t,e){let r=t.agent_name||e.defaultAgentName;if(!r)throw new Error("agent_name is required. Either pass it as parameter or set PLANX_AGENT_NAME env var.");return r}function san(t){return Om({links:[jp({url:`${t.stateServerUrl}/trpc`})]})}var aan=g(()=>{nw()});function Y7(t,e="root"){let r=[];if(!t||typeof t!="object")return r.push(`${e}: schema must be an object`),r;let n=t,i=n.type;if(i==="object")if(!n.properties||typeof n.properties!="object")r.push(`${e}: type 'object' requires 'properties' to be defined`);else for(let[o,s]of Object.entries(n.properties))r.push(...Y7(s,`${e}.${o}`));else i==="array"&&(!n.items||typeof n.items!="object"?r.push(`${e}: type 'array' requires 'items' to be defined`):r.push(...Y7(n.items,`${e}[items]`)));return r}var cSt=g(()=>{});function uan(t,e){console.error("[State Tools] Starting registration"),console.error("[State Tools] State server URL:",e.stateServerUrl),console.error("[State Tools] Default agent name:",e.defaultAgentName||"(not set)");let r=san(e),n=X.lazy(()=>X.object({type:X.enum(["string","number","boolean","array","object"]),default:X.any().optional(),items:n.optional(),properties:X.record(X.string(),n).optional()}));t.tool("init_state",{agent_name:X.string().optional().describe("Unique state identifier (defaults to PLANX_AGENT_NAME env var)"),schema:X.object({type:X.literal("object"),properties:X.record(X.string(),n)}).describe("JSON Schema for state structure")},i=>N(this,void 0,void 0,function*(){try{let o=whe(i,e),{schema:s}=i,a=Y7(s);if(a.length>0)return QY(`Schema validation failed:
|
|
1232
1232
|
${a.join(`
|
|
1233
1233
|
`)}`);let u=yield r.state.initState.mutate({stateId:o,schema:s});return She(`State initialized: ${o}
|
|
1234
1234
|
${JSON.stringify(u,null,2)}`)}catch(o){return QY(o)}})),t.tool("get_state",{agent_name:X.string().optional().describe("State identifier (defaults to PLANX_AGENT_NAME env var)")},i=>N(this,void 0,void 0,function*(){try{let o=whe(i,e),s=yield r.state.getState.query({stateId:o});return She(JSON.stringify(s,null,2))}catch(o){return QY(o)}})),t.tool("update_state",{agent_name:X.string().optional().describe("State identifier (defaults to PLANX_AGENT_NAME env var)"),operation:X.enum(["set","push","remove","updateAt"]).describe("CRDT operation type"),path:X.string().describe('Dot-separated path (e.g., "tasks" or "config.theme")'),value:X.any().describe("Value for the operation")},i=>N(this,void 0,void 0,function*(){try{let o=whe(i,e),{operation:s,path:a,value:u}=i,l=yield r.state.updateState.mutate({stateId:o,operation:s,path:a,value:u});return She(`State updated (${s} at ${a})
|