openpond 0.2.31 → 0.2.32

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.
@@ -0,0 +1,42 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{A as g,C as Ce,Sa as ee,Xa as _e,Ya as He,p as xe,q as Ae}from"./chunk-YD2IWF3T.js";import{a as Z,b as Te,h as Pe}from"./chunk-7FX5ABXG.js";import{i as Ee,o as Oe,q as ke}from"./chunk-JVIHGSOV.js";import{Aa as E,Ae as Re,Ba as Ie,Ea as N,Fa as H,Ga as X,Sa as L,U as j,we as O,ze as D}from"./chunk-MVAJMRCW.js";import{Aa as le,Ca as ce,Da as pe,Ea as de,Fa as me,Ha as ge,W as _,b as ae,c as ue,gb as he,hb as fe,jb as Q,mb as ve,pb as we,qb as F,ub as be,wb as Se,xb as ye}from"./chunk-IFP6W4OW.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as oe,d as U,f as ie,h as k}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{promises as re}from"node:fs";import pt from"node:os";import dt from"node:path";import{createServer as mt}from"node:http";import{randomBytes as gt}from"node:crypto";var st=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),ot=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(st).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:be,importOnly:o.boolean().optional()})]);function Me(n){let e=null;async function t(s,i){let u=k(n).config,l=null,d=null,p=null;try{l=await ue(u),p=await F(n,{projectRoot:s,accountId:i}),s||(e=p)}catch(b){d=U(b,u)}let h=p??(s?null:e);return{path:u,text:l,rawRevision:ae(l),issue:d,effective:h,usingLastValid:!p&&!!h,applies:"next_turn",recoverableRevisions:await ce(n),clientState:d?null:await Se(n)}}a(t,"status");async function r(s){let i=ot.parse(s);return i.action==="validate"?{valid:!0,document:le(i.text,k(n).config)}:(i.action==="patch"&&await ge(n,i.expectedRevision,i.operations),i.action==="replace"&&await pe(n,i.expectedRevision,i.text),i.action==="restore"&&await de(n,i.revision,i.expectedRevision),i.action==="trust"&&await we(n,i.root,i.accountId,i.trusted),i.action==="client-state"?ye(n,i.owner,i.patch,i.importOnly):t())}return a(r,"mutate"),{status:t,mutate:r,schema:me}}a(Me,"createConfigurationPayloads");import{Buffer as Ue}from"node:buffer";var V={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},it=25*1024*1024,q=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{a(this,"HttpBodyError")}};function qe(n,e,t={}){for(let[s,i]of Object.entries(V))e.setHeader(s,i);let r=Fe(n.headers.origin);return r?(e.setHeader("Vary",ct(e.getHeader("Vary"))),at(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}a(qe,"applyCorsHeaders");function at(n,e={}){if(n==="null")return!0;let t=Ne(n);return t?lt(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Ne(s):null).filter(s=>!!s)).has(t):!1}a(at,"isAllowedCorsOrigin");function y(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...V}),n.end(JSON.stringify(t))}a(y,"sendJson");function zt(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...V}),n.end(t)}a(zt,"sendText");function Yt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...V}),n.end(t)}a(Yt,"sendBinary");async function te(n,e={}){let t=e.maxBytes??it,r=Fe(n.headers["content-type"]),s=[],i=0;for await(let l of n){let d=Ue.from(l);if(i+=d.byteLength,i>t)throw new q(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(d)}let u=Ue.concat(s).toString("utf8").trim();if(!u)return{};if(!ut(r))throw new q(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(u)}catch{throw new q(400,"invalid_json","Request body is not valid JSON.")}}a(te,"readJson");function Be(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}a(Be,"hasAuth");function Fe(n){return Array.isArray(n)?n[0]??null:n??null}a(Fe,"headerValue");function ut(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}a(ut,"isJsonContentType");function Ne(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}a(Ne,"normalizeOrigin");function lt(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}a(lt,"isLoopbackOrigin");function ct(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}a(ct,"appendVaryOrigin");function je(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
3
+ <style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
4
+ <h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
5
+ <p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
6
+ <details id="editor"><summary>Edit configuration</summary><textarea id="text" aria-label="Configuration TOML" spellcheck="false"></textarea><button id="save">Validate and save</button><button id="reload">Reload file</button><select id="revisions" aria-label="Restore a verified configuration revision"><option value="">Restore a verified revision\u2026</option></select></details>
7
+ <details><summary>Migration sources and diagnostics</summary><pre id="migration"></pre><label>Previous app home <input id="appHome"></label><label>Previous account config <input id="configSource"></label><label>Configuration conflict choices (JSON from the preview) <textarea id="resolutions" aria-label="Migration conflict choices" spellcheck="false" placeholder='[{"path":["chat","steer_active_responses"],"choice":"existing"}]'></textarea></label><button id="preview">Preview migration</button><button id="migrate">Use these sources</button><button id="restart">Restart failed preparation</button><button id="diagnostics">Export diagnostics</button></details>
8
+ <button id="retry">Retry startup</button><p id="message" role="status"></p>
9
+ <script nonce="${n}">
10
+ let token='',state=null,editing=false,revision=null;
11
+ const el=id=>document.getElementById(id);
12
+ async function request(route,body){const r=await fetch(route,{method:body?'POST':'GET',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:body?JSON.stringify(body):undefined});const v=await r.json();if(!r.ok)throw Error(v.error||'Recovery request failed');return v;}
13
+ function message(error){el('message').textContent=error instanceof Error?error.message:String(error);}
14
+ async function load(){state=await request('/v1/recovery');el('issue').textContent=state.issue.message;el('action').textContent=state.issue.action;el('file').textContent=state.issue.path;el('migration').textContent=JSON.stringify(state.migration,null,2);if(!editing){el('text').value=state.config.text||'schema_version = 1\\n';revision=state.config.rawRevision;}el('revisions').replaceChildren(new Option('Restore a verified revision\u2026',''),...state.config.recoverableRevisions.map(r=>new Option(r.createdAt,r.revision)));el('editor').hidden=!state.configEditable;}
15
+ el('text').oninput=()=>{editing=true};
16
+ el('reload').onclick=()=>{editing=false;load().catch(message)};
17
+ el('save').onclick=async()=>{try{await request('/v1/configuration',{action:'replace',text:el('text').value,expectedRevision:revision});editing=false;await load();message('Configuration saved. Retry startup when ready.')}catch(e){message(e)}};
18
+ el('revisions').onchange=async e=>{if(!e.target.value)return;try{await request('/v1/configuration',{action:'restore',revision:e.target.value,expectedRevision:state.config.rawRevision});editing=false;await load();message('Verified revision restored.')}catch(e){message(e)}};
19
+ for(const [id,action] of [['preview','preview'],['migrate','migrate'],['restart','restart']])el(id).onclick=async()=>{try{const result=await request('/v1/recovery',{action,sourceAppHome:el('appHome').value||undefined,sourceConfig:el('configSource').value||undefined,resolutions:el('resolutions').value?JSON.parse(el('resolutions').value):undefined});el('migration').textContent=JSON.stringify(result,null,2);message(action==='preview'?'Review the source paths above.':'Migration operation completed; retry startup.')}catch(e){message(e)}};
20
+ el('diagnostics').onclick=()=>{if(!state)return;const blob=new Blob([JSON.stringify({issue:state.issue,migration:state.migration,config:{path:state.config.path,rawRevision:state.config.rawRevision,issue:state.config.issue}},null,2)],{type:'application/json'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='openpond-recovery-diagnostics.json';a.click();URL.revokeObjectURL(a.href)};
21
+ el('retry').onclick=async()=>{try{await request('/v1/recovery',{action:'retry'});message('Starting OpenPond\u2026');const timer=setInterval(async()=>{try{const h=await(await fetch('/health')).json();if(!h.recovery){clearInterval(timer);const next=new URLSearchParams(location.hash.slice(1)).get('returnTo');if(next){const u=new URL(next);if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)){location.replace(u.toString());return}}location.reload();}}catch{}},500)}catch(e){message(e)}};
22
+ (async()=>{const params=new URLSearchParams(location.hash.slice(1));token=params.get('openpondToken')||'';if(!token&&window.openpond?.getConnection)token=(await window.openpond.getConnection()).token;if(!token){message('Open the authenticated recovery URL from the launcher.');return}await load()})().catch(message);
23
+ </script></html>`}a(je,"startupRecoveryPage");var ht=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:he.optional()});function Le(n){return n instanceof oe&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}a(Le,"isRecoverableStartupError");async function De(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await re.mkdtemp(dt.join(pt.tmpdir(),"openpond-recovery-")):n;return xe(s,async()=>{let{token:i,tokenFile:u}=await _e(s),l=Me(n),d=t.issue,p,h=new Promise(f=>{p=f}),b=mt((f,v)=>{(async()=>{let w=new URL(f.url??"/","http://127.0.0.1");if(!qe(f,v).allowed){y(v,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){y(v,204,{});return}if(f.method==="GET"&&w.pathname==="/health"){y(v,200,{ok:!0,server:"openpond-app-server",version:Te,recovery:!0});return}if(f.method==="GET"&&w.pathname==="/"){let c=gt(18).toString("base64");v.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${c}'; style-src 'nonce-${c}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),v.end(je(c));return}if(!Be(f,w,i)){y(v,401,{error:"Unauthorized"});return}let A=!r;if(f.method==="GET"&&w.pathname==="/v1/recovery"){y(v,200,{issue:d,configEditable:A,config:r?{path:k(n).config,text:null,rawRevision:"unavailable",issue:d,recoverableRevisions:[]}:await l.status(),migration:await fe(n).catch(c=>({issue:U(c,n)}))});return}if(f.method==="POST"&&w.pathname==="/v1/configuration"&&A){y(v,200,await l.mutate(await te(f)));return}if(f.method==="POST"&&w.pathname==="/v1/recovery"){let c=ht.parse(await te(f));if(r&&c.action!=="retry"&&c.action!=="preview")throw t;if(c.action==="restart"){y(v,200,await ve(n));return}if(c.action==="preview"||c.action==="migrate"){y(v,200,await Q(n,{sourceAppHome:c.sourceAppHome,sourceConfig:c.sourceConfig,resolutions:c.resolutions,dryRun:c.action==="preview"}));return}await Q(n),await F(n),y(v,200,{ready:!0}),p();return}y(v,503,{error:`${d.message} ${d.action}`,issue:d,recovery:!0})})().catch(w=>{d=U(w,n),y(v,422,{error:`${d.message} ${d.action}`,issue:d})})});await new Promise((f,v)=>{b.once("error",v),b.listen(e,"127.0.0.1",()=>{b.off("error",v),f()})});let T=b.address().port,x=`http://127.0.0.1:${T}`;return await Ae(s,x,"startup-recovery"),{url:x,port:T,token:i,tokenFile:u,storePath:k(n).database,repaired:h,close:a(async()=>{b.closeIdleConnections(),await new Promise((f,v)=>b.close(w=>w?v(w):f())),r&&await re.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await re.rm(s,{recursive:!0,force:!0}),i})}a(De,"startRecoveryServer");import{createHash as Ut}from"node:crypto";import{createHash as ft,randomUUID as ne}from"node:crypto";var Ve=o.object({approval:X,revision:o.number().int().positive()}).strict(),$e=o.object({record:L}).strict(),vt=o.object({startedAt:o.string().min(1),requestOrdinal:o.number().int().nonnegative(),id:o.string().min(1)}).strict(),wt=o.object({records:o.array(L).max(200),nextBefore:vt.nullable()}).strict(),We=1e4,$=class{constructor(e){this.client=e}client;static{a(this,"HostedApprovalStorage")}async readApproval(e){let t=await this.client.request({contractVersion:g,requestId:ne(),operation:"approval/get",params:{approvalId:e}});return t===null?null:Ve.parse(t)}async getApproval(e){return(await this.readApproval(e))?.approval??null}async putApproval(e){let t=X.parse(e.approval);if(!e.requestId.trim())throw new Error("Approval mutation requires a stable request ID.");return Ve.parse(await this.client.request({contractVersion:g,requestId:e.requestId,operation:"approval/upsert",params:{approval:t,expectedRevision:e.expectedRevision}}))}},W=class{constructor(e){this.client=e}client;static{a(this,"HostedModelUsageStorage")}async upsertModelUsageRecord(e){let t=L.parse(e),r=ft("sha256").update(JSON.stringify(t)).digest("hex"),s=await this.client.request({contractVersion:g,requestId:`usage:${r}`,operation:"usage/upsert",params:{record:t}}),i=$e.parse(s).record;if(i.requestId!==t.requestId)throw new Error("Host usage upsert changed request identity.");return i}async getModelUsageRecordByRequestId(e){let t=await this.client.request({contractVersion:g,requestId:ne(),operation:"usage/getByRequestId",params:{requestId:e}});return t===null?null:$e.parse(t).record}async listModelUsageRecords(e={}){let t=e.limit===void 0||e.limit>=We,r=e.limit===void 0?We:Math.max(1,Math.min(1e4,Math.trunc(e.limit))),s={...e.sessionId?{sessionId:e.sessionId}:{},...e.turnId?{turnId:e.turnId}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.startedAtFrom?{startedAtFrom:e.startedAtFrom}:{},...e.startedAtTo?{startedAtTo:e.startedAtTo}:{},...e.visibility&&e.visibility!=="all"?{visibility:e.visibility}:{},...e.status&&e.status!=="all"?{status:e.status}:{}},i=[],u=null;for(;i.length<r+(t?1:0);){let l=wt.parse(await this.client.request({contractVersion:g,requestId:ne(),operation:"usage/page",params:{query:s,before:u,limit:Math.min(200,r+(t?1:0)-i.length)}}));if(i.push(...l.records),i.length>r)throw new Error(`Hosted usage query exceeds ${r} rows; narrow its filters or use a streamed aggregation.`);if(l.nextBefore===null)break;if(l.records.length===0||JSON.stringify(l.nextBefore)===JSON.stringify(u))throw new Error("Host usage cursor did not advance.");u=l.nextBefore}return i}async listModelUsageRecordsComplete(e={}){return this.listModelUsageRecords(e)}};import{createHash as bt,randomUUID as Ge}from"node:crypto";var St=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),yt=o.object({entries:o.array(E).max(200),nextBefore:St.nullable()}).strict(),It=o.object({run:E,replayed:o.boolean()}).strict(),G=class{constructor(e){this.client=e}client;static{a(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:g,requestId:Ge(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:E.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let u=yt.parse(await this.client.request({contractVersion:g,requestId:Ge(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&u.entries.some(l=>l.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...u.entries),!u.nextBefore)break;if(u.entries.length===0||i&&(u.nextBefore.updatedAt>i.updatedAt||u.nextBefore.updatedAt===i.updatedAt&&u.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=u.nextBefore}return s}async upsertCreateImproveRun(e){let t=E.parse(e),r=`create-improve:${bt("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:g,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return E.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=Ie.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=E.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return It.parse(await this.client.request({contractVersion:g,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as Tt}from"node:crypto";async function B(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!Rt(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}a(B,"hostedBoundedPage");function Rt(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}a(Rt,"isOversizeResponse");var Pt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:j})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),J=class{constructor(e){this.client=e}client;static{a(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],u=Math.max(0,t.afterSequence??0),l=0,d=t.names?new Set(t.names):null;for(;i.length<=s;){let p=await this.runtimeEventPageRows({sessionId:e,afterSequence:u,beforeSequence:null,limit:Math.min(200,s+1-i.length)});for(let h of p.entries){if(h.sequence<=u)throw new Error("Host event cursor did not advance.");if(u=h.sequence,l+=1,l>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!d||d.has(h.event.name))&&i.push(h.event)}if(p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=j.parse(e),r=await this.client.request({contractVersion:g,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:j}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],u=0,l=0;for(;i.length<t;){let d=Math.min(200,t-i.length),p=await B(d,async h=>Pt.parse(await this.client.request({contractVersion:g,requestId:`event-page:${Tt()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:h}})));if(i.length===0&&(u=p.totalMatchingEvents,l=p.remainingMatchingEvents),i=s===null?[...i,...p.entries]:[...p.entries,...i],p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break;if(s===null){let h=p.entries.at(-1).sequence;if(h<=r)throw new Error("Host event cursor did not advance.");r=h}else{let h=p.entries[0].sequence;if(h>=s)throw new Error("Host event cursor did not advance.");s=h}}return{entries:i,totalMatchingEvents:u,remainingMatchingEvents:l}}};import{randomUUID as S}from"node:crypto";var Je=o.object({revision:o.number().int().min(1),session:N}).strict(),ze=o.object({revision:o.number().int().min(1),turn:H}).strict(),xt=o.object({sessions:o.array(N).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),At=o.object({turns:o.array(H).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),z=class{constructor(e){this.client=e}client;static{a(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:g,requestId:S(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:g,requestId:S(),operation:"session/get",params:{sessionId:e}});return t===null?null:Je.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await B(Math.min(10,1001-e.length),async s=>xt.parse(await this.client.request({contractVersion:g,requestId:S(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:S()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=N.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:S()})).session}async put(e){let t=N.parse(e.session);return Je.parse(await this.client.request({contractVersion:g,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:g,requestId:S(),operation:"turn/get",params:{turnId:e}});return t===null?null:ze.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let u=await B(Math.min(200,r-s.length),async l=>At.parse(await this.client.request({contractVersion:g,requestId:S(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:l}})));if(s.push(...u.turns),u.nextBeforeSortIndex===null)break;if(i!==null&&u.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=u.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:g,requestId:S(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:g,requestId:S(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:g,requestId:S(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:g,requestId:S(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:H.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:S()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=H.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:S()})).turn}async putTurn(e){let t=H.parse(e.turn);return ze.parse(await this.client.request({contractVersion:g,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as Ct,randomUUID as Et}from"node:crypto";var P=o.object({ok:o.literal(!0)}).strict(),Y=o.array(O),Ot=o.array(o.string()),kt=o.object({turnId:o.string(),run:_}).strict(),_t=o.object({inputs:o.array(O).max(10),hasMore:o.boolean()}).strict(),Ht=o.object({items:o.array(D).max(10),hasMore:o.boolean()}).strict(),Mt=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function K(n,e){return`inbox:${n}:${Ct("sha256").update(JSON.stringify(e)).digest("hex")}`}a(K,"retryKey");var M=class{constructor(e){this.client=e}client;static{a(this,"HostedTaskInboxStorage")}async call(e,t,r=Et()){let s=await this.client.request({contractVersion:g,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),_t);for(let u of i.inputs){if(u.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=u.sequence,r.push(u),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},Re),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},P)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},Ot)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},O)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},Y)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},P)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},O.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let u=Math.min(10,r-s.length),l=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:u}},Y);if(!l.length)break;for(let d of l){if(d.sequence<=i)throw new Error("Host task input cursor did not advance.");i=d.sequence,s.push(d)}if(l.length<u)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},O,K("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},P,K("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},P)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},P)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},Y,K("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},P)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},Y)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},P)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},O.nullable(),K("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},Mt);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},D)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},D)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},Ht);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},P)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(kt).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},P)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:_.parse(e)},_)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},_.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let u=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(_).max(10));for(let l of u){if(l.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=l.id,r.push(l),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(u.length<10)break}return r.sort((u,l)=>(l.updatedAt??l.createdAt).localeCompare(u.updatedAt??u.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var se=class extends M{static{a(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new z(e),this.events=new J(e),this.approvals=new $(e),this.usage=new W(e),this.createImprove=new G(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Ut("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function Ye(n){return new se(n)}a(Ye,"createHostedRuntimeCoreStorage");function Ke(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return a(async function*(u){if(u.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Ee({...u,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}a(Ke,"createHostedModelStreamFromEnvironment");import{existsSync as Nt}from"node:fs";import R from"node:path";import{fileURLToPath as qt}from"node:url";var Qe=R.dirname(qt(import.meta.url));function I(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}a(I,"requireValue");function Xe(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}a(Xe,"parsePort");function tt(n){let e="serve",t=Z,r=17874,s=null,i=!1,u=!1,l=null,d,p=null,h=null,b=null,T=null,x,f="sqlite_bundle",v=0,w=n[0];if(w&&!w.startsWith("-")){if(w==="serve"||w==="server")e="serve";else if(w==="app-server")e="app-server";else if(w==="web")e="web";else{if(w==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:u,storeDir:l,runtimeStorage:f,help:!0};throw new Error(`Unknown command: ${w}`)}v=1}for(let c=v;c<n.length;c+=1){let m=n[c];if(m==="--help"||m==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:u,storeDir:l,runtimeStorage:f,help:!0};if(m==="--listen"){let C=Pe(I(n,c,m));t=C.host,r=Xe(String(C.port),m),c+=1}else if(m==="--hostname"||m==="--host")t=I(n,c,m),c+=1;else if(m==="--port")r=Xe(I(n,c,m),m),c+=1;else if(m==="--web-root")s=R.resolve(I(n,c,m)),c+=1;else if(m==="--source-browser-state")d=R.resolve(I(n,c,m)),c+=1;else{if(m==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(m==="--home")l=R.resolve(I(n,c,m)),c+=1;else if(m==="--runtime-storage"){if(I(n,c,m)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");f="hosted_postgres",c+=1}else if(m==="--profile-source-root")p=R.resolve(I(n,c,m)),c+=1;else if(m==="--profile-repository-id")h=I(n,c,m),c+=1;else if(m==="--profile-id")b=I(n,c,m),c+=1;else if(m==="--profile-revision")T=I(n,c,m),c+=1;else if(m==="--hosted-profile-release"){if(x)throw new Error("Duplicate hosted Profile release descriptor.");let C=I(n,c,m);if(C.length>16e3||!/^[A-Za-z0-9_-]+$/.test(C))throw new Error("Invalid hosted Profile release descriptor.");try{x=He.parse(JSON.parse(Buffer.from(C,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}c+=1}else if(m==="--open-browser")i=!0;else if(m==="--print-access-url")u=!0;else throw new Error(`Unknown option: ${m}`)}}if(i&&u)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||u))throw new Error("Browser options are only available in web mode.");let A=[p,h,b,T].filter(Boolean).length;if(A&&(A!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(f==="hosted_postgres"&&(e!=="app-server"||l||A))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(x&&f!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:u,storeDir:l,runtimeStorage:f,sourceBrowserState:d,...A?{profileSource:{repoPath:p,repositoryId:h,profileId:b,sourceRevision:T}}:{},...x?{admittedProfileRelease:x}:{},help:!1}}a(tt,"parseCliArgs");function Bt(){return[process.env.OPENPOND_WEB_ROOT,R.resolve(process.cwd(),"apps/web/dist"),R.resolve(Qe,"../../web/dist"),R.resolve(process.cwd(),"web"),R.resolve(Qe,"../web")].filter(n=>!!n)}a(Bt,"defaultWebRootCandidates");function Ft(n){let e=n?[n]:Bt();for(let t of e){let r=R.resolve(t);if(Nt(R.join(r,"index.html")))return r}return null}a(Ft,"resolveWebRoot");function jt(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}a(jt,"formatHostForUrl");function Lt(n){return`http://${jt(n.status.host)}:${n.status.port}`}a(Lt,"browserBaseUrl");function Dt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}a(Dt,"tokenizedWebUrl");async function Ze(n,e=ke){let t=Dt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}a(Ze,"resolveWebLaunchMessages");function rt(){console.log(`Usage:
24
+ openpond-app-server serve [--hostname HOST] [--port PORT]
25
+ openpond-app-server app-server [--home DIR]
26
+ openpond-app-server web [--hostname HOST] [--port PORT] [--web-root DIR]
27
+
28
+ Options:
29
+ --listen HOST:PORT Set host and port together
30
+ --hostname HOST Bind host (default ${Z})
31
+ --port PORT Bind port, or 0 for any free port (default ${17874})
32
+ --web-root DIR Directory containing the built web UI for web mode
33
+ --home DIR Local app-server state directory
34
+ --runtime-storage hosted-postgres Host-admitted Postgres app-server mode
35
+ --hosted-profile-release BASE64URL Host-admitted immutable Profile release descriptor
36
+ --profile-source-root DIR Authorized Profile repository source for app-server
37
+ --profile-repository-id ID Source repository identity supplied by the host
38
+ --profile-id ID Profile within that source
39
+ --profile-revision REV Accepted immutable source revision
40
+ --open-browser Open the authenticated web URL in the system browser
41
+ --print-access-url Print the authenticated URL instead of opening it
42
+ `)}a(rt,"printHelp");async function yn(n){let e=tt(process.argv.slice(2));if(e.help){rt();return}let t=e.mode==="web"?Ft(e.webRoot):null;if(e.mode==="web"&&!t)throw new Error("Could not find a built OpenPond web UI. Run `pnpm build:web` or pass --web-root.");if(e.mode==="app-server"){await nt(n.createOpenPondAppServer,e.storeDir,e.profileSource,e.runtimeStorage);return}e.storeDir&&(process.env.OPENPOND_HOME=e.storeDir);let r,s=e.port;for(;;)try{r=await n.createOpenPondServer({host:e.host,port:s,webRoot:t,sourceBrowserState:e.sourceBrowserState,...e.storeDir?{storeDir:e.storeDir}:{},httpEnabled:!0});break}catch(d){if(!Le(d))throw d;let p=await De(ie({home:e.storeDir??void 0}),s,d);s=p.port,console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:"recovery",url:p.url,tokenFile:p.tokenFile,storePath:p.storePath})}`),console.error(`${d.issue.code}: ${d.issue.message} ${d.issue.action}`);let h=await Ze({baseUrl:p.url,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:p.token});for(let T of h.stdout)console.log(T);for(let T of h.stderr)console.error(T);let b=a(()=>{p.close().finally(()=>process.exit(0))},"close");process.once("SIGINT",b),process.once("SIGTERM",b);try{await p.repaired}finally{process.off("SIGINT",b),process.off("SIGTERM",b),await p.close()}}let i=e.mode==="web"?Lt(r):null;if(console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:e.mode,url:r.url,webUrl:null,webRoot:t,tokenFile:r.tokenFile,storePath:r.storePath,runtime:Oe()})}`),i){let d=await Ze({baseUrl:i,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:r.token});for(let p of d.stderr)console.error(p);for(let p of d.stdout)console.log(p)}else console.log(`OpenPond API server: ${r.url}`);let u=!1,l=a(async()=>{u||(u=!0,await r.close(),process.exit(0))},"shutdown");process.on("SIGINT",()=>{l()}),process.on("SIGTERM",()=>{l()}),await new Promise(()=>{})}a(yn,"runOpenPondServerCli");async function In(n){let e=process.argv.slice(2),t=tt(!e[0]||e[0].startsWith("-")?["app-server",...e]:e);if(t.help){rt();return}if(t.mode!=="app-server")throw new Error("The app-server entrypoint only accepts the app-server command.");await nt(n,t.storeDir,t.profileSource,t.runtimeStorage,t.admittedProfileRelease)}a(In,"runOpenPondAppServerCli");async function nt(n,e,t,r="sqlite_bundle",s){let i=new Ce;if(r==="hosted_postgres"){if(e||t)throw new Error("Hosted Postgres app-server cannot use local storage sources.");await ee({appServer:a(()=>n({hostStorageClient:i,runtimeStorage:{kind:"hosted_postgres",client:i,core:Ye(i),inbox:new M(i),...s?{admittedProfileRelease:s}:{}},streamOpenPondHostedChatTurn:Ke()}),"appServer"),readable:process.stdin,writable:process.stdout,hostStorageClient:i});return}e&&(process.env.OPENPOND_HOME=e);let u=await n({...e?{storeDir:e}:{},...t?{profileSource:t}:{},hostStorageClient:i});await ee({appServer:u,readable:process.stdin,writable:process.stdout,hostStorageClient:i})}a(nt,"runAgentServer");export{Me as a,q as b,qe as c,y as d,zt as e,Yt as f,te as g,Be as h,Ze as i,yn as j,In as k};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{i as a,j as b,k as c}from"./chunk-YW6HS6TZ.js";import"./chunk-YD2IWF3T.js";import"./chunk-7FX5ABXG.js";import"./chunk-JVIHGSOV.js";import"./chunk-MVAJMRCW.js";import"./chunk-L54LZUGH.js";import"./chunk-L3KS6MOV.js";import"./chunk-55UCBRIX.js";import"./chunk-6MI4KKWF.js";import"./chunk-QTEYV4TW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-6FA3GG5B.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as resolveWebLaunchMessages,c as runOpenPondAppServerCli,b as runOpenPondServerCli};
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
3
- import{a as qA,b as zA,c as WA,d as j,e as VA,f as co,g as z,h as Su,j as JA}from"./chunk-4476RDBS.js";import{$ as eu,$a as tT,$b as qT,$c as TA,A as I_,Aa as mc,Ab as kT,Ac as cA,B as R_,Ba as Ox,Bb as bT,Bc as dA,C as P_,Ca as Dx,Cb as ST,Cc as ah,D as A_,Da as vs,Db as IT,Dc as lA,E as C_,Ea as ks,Eb as _T,Ec as sh,F as E_,Fa as Bx,Fb as xT,Fc as uA,G as M_,Ga as $x,Gb as gu,Gc as pA,H as j_,Ha as Lx,Hb as TT,Hc as mA,I as H_,Ia as Nx,Ib as AT,Ic as fA,J as Xl,Ja as Ux,Jb as CT,Jc as gA,K as O_,Ka as Fx,Kb as ET,Kc as hA,L as Ql,La as qx,Lb as MT,Lc as wA,M as D_,Ma as oo,Mb as nh,Mc as yA,N as B_,Na as zx,Nb as jT,Nc as vA,O as $_,Oa as Wx,Ob as HT,Oc as kA,P as gs,Pa as eh,Pb as OT,Pc as ih,Q as Zl,Qa as Vx,Qb as DT,Qc as bA,R as lc,Ra as Jx,Rb as BT,Rc as ch,S as Kg,Sa as Gx,Sb as $T,Sc as SA,T as Xo,Ta as bs,Tb as LT,Tc as IA,U as L_,Ua as Kx,Ub as Dn,Uc as RA,V as N_,Va as Yx,Vb as NT,Vc as PA,W as U_,Wa as Xx,Wb as hu,Wc as _A,X as F_,Xa as Qx,Xb as UT,Xc as io,Y as q_,Ya as ae,Yb as FT,Yc as xr,Z as z_,Za as Zx,Zb as Nt,Zc as dh,_ as W_,_a as eT,_b as Qo,_c as xA,a as uS,aa as tu,ab as uu,ac as _r,ad as ku,b as pS,ba as hs,bb as nT,bc as zT,bd as Is,c as mS,ca as J_,cb as rT,cc as WT,cd as AA,d as fS,da as ou,db as oT,dc as VT,dd as bu,e as gS,ea as ox,eb as aT,ec as JT,ed as CA,f as pl,fa as ax,fb as sT,fc as GT,fd as EA,g as SS,ga as sx,gb as pu,gc as KT,gd as MA,h as IS,ha as au,hb as iT,hc as YT,hd as jA,i as RS,ia as ix,ib as ao,ic as XT,id as HA,j as PS,ja as cx,jb as Ae,jc as QT,jd as OA,k as _S,ka as su,kb as cT,kc as ZT,kd as DA,l as vg,la as dx,lb as pe,lc as eA,ld as BA,m as AS,ma as lx,mb as dT,mc as tA,md as $A,n as CS,na as ux,nb as lT,nc as wu,nd as LA,o as ES,oa as iu,ob as uT,oc as nA,od as NA,p as MS,pa as px,pb as pT,pc as Zo,pd as UA,q as jS,qa as mx,qb as mT,qc as yu,r as HS,ra as fx,rb as fT,rc as rA,rd as FA,s as qo,sa as gx,sb as gT,sc as so,t as OS,ta as hx,tb as hT,tc as vu,u as DS,ua as pc,ub as wT,uc as oA,v as gl,va as Cx,vb as yT,vc as aA,w as BS,wa as Ex,wb as vT,wc as rh,x as $S,xa as Mx,xb as Ss,xc as oh,y as z2,ya as jx,yb as On,yc as sA,z as S_,za as Hx,zb as He,zc as iA}from"./chunk-PZ6KPMEZ.js";import{A as Ix,C as du,F as lu,G as cr,H as Rx,I as Yg,J as Px,K as Xg,N as _x,O as Qg,P as xx,Q as Tx,R as Ax,S as Zg,T as ys,b as cu,d as wx,e as yx,h as vx,m as ws,n as kx,p as bx,q as Sx,s as uc}from"./chunk-GCU66EAF.js";import{A as mu,B as fu,C as PT,a as ct,b as __,c as x_,f as T_,w as V_,y as th,z as RT}from"./chunk-L2UT3YIF.js";import{a as k_,b as Yl,d as ie,e as it,f as fs,g as ne,i as b_}from"./chunk-CE27WEHK.js";import{a as on,b as G_,c as K_,d as nu,e as ru,g as Y_,h as X_,j as Q_,k as Z_,l as ex,m as tx,n as nx,o as rx}from"./chunk-JVIHGSOV.js";import{$ as gR,$a as to,$b as gP,$c as ls,$d as Gl,A as oR,Aa as jg,Ab as Dg,B as Tl,Bb as Bl,Bc as DP,C as aR,Ca as qe,Cc as sc,D as Cg,Da as Ml,Db as Bg,Dc as qg,E as sR,Ea as PR,Eb as oc,F as iR,Fa as Hg,G as tt,Gb as rP,Gc as Nl,Gd as Ko,H as cR,Ha as _R,Hd as n_,I as yt,Ic as zg,Id as Pr,J as rc,Jb as oP,Jc as BP,Jd as r_,K as dR,Kb as aP,Kc as $P,Kd as o_,L as lR,Lb as sP,Ld as a_,Md as no,N as uR,Na as xR,Nb as cs,Nc as Ul,Nd as ps,Ob as iP,Oc as LP,Od as Wl,P as pR,Pa as jl,Pc as Wg,Pd as s_,Q as mR,Qa as TR,Qb as ac,Qc as sr,Qd as i_,R as Hn,Rb as $l,Rc as NP,Rd as c_,Sa as AR,Sb as cP,Sc as UP,Sd as cc,Ta as CR,Tb as $g,Tc as Vg,Td as ms,Ua as ER,Ub as dP,Uc as ic,Ud as Vl,Va as MR,Vb as lP,Vc as FP,Vd as d_,Wa as jR,Wb as Lg,Wc as Fl,Wd as Jl,X as fR,Xa as HR,Xb as uP,Xc as qP,Xd as ro,Ya as OR,Yb as pP,Yc as zP,Yd as l_,Z as Al,Za as DR,Zb as mP,Zc as ds,Zd as u_,_a as BR,_b as fP,_c as WP,_d as p_,ac as hP,ad as VP,ae as m_,bb as $R,bc as wP,bd as JP,be as dc,c as WI,ca as Eg,cb as LR,cc as Ng,cd as Jg,ce as f_,da as hR,db as NR,dc as yP,dd as ql,de as g_,ea as Lt,eb as UR,ec as vP,ed as GP,fa as Vo,fc as kP,fd as Be,ga as Jo,gb as FR,gc as bP,gd as zl,ha as Mg,hb as Hl,hc as Ug,hd as KP,ia as wR,ib as qR,ic as SP,id as YP,ja as yR,jb as zR,jc as IP,jd as XP,ka as vR,kb as WR,kc as RP,kd as Gg,l as VI,la as kR,lb as VR,lc as PP,ld as QP,m as JI,ma as bR,mb as JR,mc as _P,md as ZP,me as Kl,n as GI,na as SR,nb as GR,nc as xP,nd as e_,ne as h_,oa as Cl,ob as KR,oc as TP,oe as w_,pb as YR,pc as AP,pd as us,pe as ir,q as KI,qa as El,qb as XR,qc as CP,qd as t_,qe as y_,r as YI,rb as QR,rc as EP,re as Yo,s as XI,sb as ZR,sc as Fg,se as v_,t as QI,tb as eP,tc as Go,u as ZI,ub as tP,uc as MP,v as Ag,vb as Og,vc as jP,w as eR,wb as Ol,wc as HP,x as tR,xa as IR,xb as nP,y as nR,yb as ar,yc as Ll,z as rR,za as RR,zb as Dl,zc as OP}from"./chunk-MVAJMRCW.js";import{a as YS,c as jI,h as HI}from"./chunk-L54LZUGH.js";import{b as hS,c as wS}from"./chunk-L3KS6MOV.js";import"./chunk-XEOEKFG6.js";import{A as tc,B as _g,C as xl,D as $I,E as LI,I as NI,J as UI,N as is,O as nc,P as FI,Q as qI,R as zI,T as xg,V as Tg,i as OI,t as DI,u as BI,v as wn,w as _l,z as Wo}from"./chunk-55UCBRIX.js";import"./chunk-6MI4KKWF.js";import{A as kg,Aa as sI,Ac as Il,B as NS,Bc as Rl,C as US,Ca as rs,Cb as gI,Cc as Pl,D as FS,Dc as xI,E as wl,Eb as hI,Ec as Pg,F as qS,Fa as iI,Fb as wI,Fc as TI,G as zS,H as WS,Ha as cI,Hc as AI,I as VS,Ic as CI,Jc as EI,Kc as eo,Lc as MI,Mc as or,Nb as yI,Pa as jn,Q as JS,Qa as dI,Qb as vI,R as GS,Ra as vl,Sa as rn,V as KS,Va as lI,Vb as kI,_a as uI,_b as as,a as yS,ab as Sg,b as vS,bb as je,c as hn,cb as zo,db as Qe,f as kS,fa as XS,fc as Rg,g as ul,gc as bI,h as bS,hb as pI,jc as SI,kb as ec,kc as bl,lb as mI,m as ml,ma as QS,mb as kl,mc as Sl,na as ZS,nc as II,o as xS,oa as eI,ob as fI,pa as tI,pb as Ig,pc as RI,qa as nI,qb as os,ra as yl,sa as bg,ta as rI,u as fl,ua as oI,v as TS,va as aI,w as LS,x as hl,xc as ss,yc as PI,zc as _I}from"./chunk-QTEYV4TW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{D as ns,E as Qi,F as ll,d as dl,m as dS,n as Zr,o as Ve,p as lS}from"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import{$a as cl,$b as iS,Da as q2,Ea as eS,Fa as wg,Ga as yg,Ia as tS,Lb as Je,Mb as Vt,Pa as nS,S as sl,Sb as sS,Ta as rS,Ua as oS,a as nn,bc as cS,hb as aS,qa as Xb,ra as il,ta as Qb,wa as Zb}from"./chunk-5BFWDFPX.js";import{a as Zi}from"./chunk-6FA3GG5B.js";import{A as Ct,B as Lo,C as xb,D as Xi,E as Rr,F as tl,G as Tb,Ga as Qr,H as nl,I as Ab,Ia as No,J as es,L as Cb,M as Eb,N as Mb,Na as Nb,O as jb,Oa as Ub,P as Hb,Pa as qb,Qa as zb,Ta as Wb,Va as gg,W as fg,Wa as hg,Xa as Vb,ca as Ob,f as Xd,ga as Xr,ia as Db,ib as ol,jb as Jb,k as Qa,ka as Bb,l as Za,la as $b,m as pg,ma as Lb,n as Qd,nb as Gb,o as st,ob as Kb,p as mg,q as Zd,qb as Fo,rb as Yb,sb as al,t as We,u as Se,v as O,w as Pb,y as _b,z as el}from"./chunk-IFP6W4OW.js";import{a as $o,b as _}from"./chunk-ES2ISFJC.js";import{a as Sb,c as Bo,f as Ib,h as Yd,i as Rb,p as ts,q as Fb,r as Uo,s as rl}from"./chunk-H7IWJN7L.js";import{a,b as Pe,c as Te,e as Mn}from"./chunk-FTQLQJQV.js";var Br=Te((Zpe,aj)=>{"use strict";var rj=["nodebuffer","arraybuffer","fragments"],oj=typeof Blob<"u";oj&&rj.push("blob");aj.exports={BINARY_TYPES:rj,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:oj,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:a(()=>{},"NOOP")}});var $c=Te((tme,fp)=>{"use strict";var{EMPTY_BUFFER:NG}=Br(),Mw=Buffer[Symbol.species];function UG(e,t){if(e.length===0)return NG;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),r=0;for(let o=0;o<e.length;o++){let s=e[o];n.set(s,r),r+=s.length}return r<t?new Mw(n.buffer,n.byteOffset,r):n}a(UG,"concat");function sj(e,t,n,r,o){for(let s=0;s<o;s++)n[r+s]=e[s]^t[s&3]}a(sj,"_mask");function ij(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}a(ij,"_unmask");function FG(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}a(FG,"toArrayBuffer");function jw(e){if(jw.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new Mw(e):ArrayBuffer.isView(e)?t=new Mw(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),jw.readOnly=!1),t}a(jw,"toBuffer");fp.exports={concat:UG,mask:sj,toArrayBuffer:FG,toBuffer:jw,unmask:ij};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=Pe("bufferutil");fp.exports.mask=function(t,n,r,o,s){s<48?sj(t,n,r,o,s):e.mask(t,n,r,o,s)},fp.exports.unmask=function(t,n){t.length<32?ij(t,n):e.unmask(t,n)}}catch{}});var lj=Te((rme,dj)=>{"use strict";var cj=Symbol("kDone"),Hw=Symbol("kRun"),Ow=class{static{a(this,"Limiter")}constructor(t){this[cj]=()=>{this.pending--,this[Hw]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[Hw]()}[Hw](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[cj])}}};dj.exports=Ow});var ei=Te((ame,fj)=>{"use strict";var Lc=Pe("zlib"),uj=$c(),qG=lj(),{kStatusCode:pj}=Br(),zG=Buffer[Symbol.species],WG=Buffer.from([0,0,255,255]),hp=Symbol("permessage-deflate"),$r=Symbol("total-length"),Qs=Symbol("callback"),So=Symbol("buffers"),Zs=Symbol("error"),gp,Dw=class{static{a(this,"PerMessageDeflate")}constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!gp){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;gp=new qG(n)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Qs];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let n=this._options,r=t.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(t){let n=t[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(t){return t.forEach(n=>{Object.keys(n).forEach(r=>{let o=n[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=s}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=o})}),t}decompress(t,n,r){gp.add(o=>{this._decompress(t,n,(s,i)=>{o(),r(s,i)})})}compress(t,n,r){gp.add(o=>{this._compress(t,n,(s,i)=>{o(),r(s,i)})})}_decompress(t,n,r){let o=this._isServer?"client":"server";if(!this._inflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Lc.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Lc.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[hp]=this,this._inflate[$r]=0,this._inflate[So]=[],this._inflate.on("error",JG),this._inflate.on("data",mj)}this._inflate[Qs]=r,this._inflate.write(t),n&&this._inflate.write(WG),this._inflate.flush(()=>{let s=this._inflate[Zs];if(s){this._inflate.close(),this._inflate=null,r(s);return}let i=uj.concat(this._inflate[So],this._inflate[$r]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[$r]=0,this._inflate[So]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,i)})}_compress(t,n,r){let o=this._isServer?"server":"client";if(!this._deflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Lc.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Lc.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[$r]=0,this._deflate[So]=[],this._deflate.on("data",VG)}this._deflate[Qs]=r,this._deflate.write(t),this._deflate.flush(Lc.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=uj.concat(this._deflate[So],this._deflate[$r]);n&&(s=new zG(s.buffer,s.byteOffset,s.length-4)),this._deflate[Qs]=null,this._deflate[$r]=0,this._deflate[So]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};fj.exports=Dw;function VG(e){this[So].push(e),this[$r]+=e.length}a(VG,"deflateOnData");function mj(e){if(this[$r]+=e.length,this[hp]._maxPayload<1||this[$r]<=this[hp]._maxPayload){this[So].push(e);return}this[Zs]=new RangeError("Max payload size exceeded"),this[Zs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zs][pj]=1009,this.removeListener("data",mj),this.reset()}a(mj,"inflateOnData");function JG(e){if(this[hp]._inflate=null,this[Zs]){this[Qs](this[Zs]);return}e[pj]=1007,this[Qs](e)}a(JG,"inflateOnError")});var ti=Te((ime,wp)=>{"use strict";var{isUtf8:gj}=Pe("buffer"),{hasBlob:GG}=Br(),KG=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function YG(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}a(YG,"isValidStatusCode");function Bw(e){let t=e.length,n=0;for(;n<t;)if((e[n]&128)===0)n++;else if((e[n]&224)===192){if(n+1===t||(e[n+1]&192)!==128||(e[n]&254)===192)return!1;n+=2}else if((e[n]&240)===224){if(n+2>=t||(e[n+1]&192)!==128||(e[n+2]&192)!==128||e[n]===224&&(e[n+1]&224)===128||e[n]===237&&(e[n+1]&224)===160)return!1;n+=3}else if((e[n]&248)===240){if(n+3>=t||(e[n+1]&192)!==128||(e[n+2]&192)!==128||(e[n+3]&192)!==128||e[n]===240&&(e[n+1]&240)===128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}a(Bw,"_isValidUTF8");function XG(e){return GG&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}a(XG,"isBlob");wp.exports={isBlob:XG,isValidStatusCode:YG,isValidUTF8:Bw,tokenChars:KG};if(gj)wp.exports.isValidUTF8=function(e){return e.length<24?Bw(e):gj(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=Pe("utf-8-validate");wp.exports.isValidUTF8=function(t){return t.length<32?Bw(t):e(t)}}catch{}});var Fw=Te((dme,Sj)=>{"use strict";var{Writable:QG}=Pe("stream"),hj=ei(),{BINARY_TYPES:ZG,EMPTY_BUFFER:wj,kStatusCode:e6,kWebSocket:t6}=Br(),{concat:$w,toArrayBuffer:n6,unmask:r6}=$c(),{isValidStatusCode:o6,isValidUTF8:yj}=ti(),yp=Buffer[Symbol.species],Rn=0,vj=1,kj=2,bj=3,Lw=4,Nw=5,vp=6,Uw=class extends QG{static{a(this,"Receiver")}constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||ZG[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[t6]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Rn}_write(t,n,r){if(this._opcode===8&&this._state==Rn)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(r)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new yp(r.buffer,r.byteOffset+t,r.length-t),new yp(r.buffer,r.byteOffset,t)}let n=Buffer.allocUnsafe(t);do{let r=this._buffers[0],o=n.length-t;t>=r.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(r.buffer,r.byteOffset,t),o),this._buffers[0]=new yp(r.buffer,r.byteOffset+t,r.length-t)),t-=r.length}while(t>0);return n}startLoop(t){this._loop=!0;do switch(this._state){case Rn:this.getInfo(t);break;case vj:this.getPayloadLength16(t);break;case kj:this.getPayloadLength64(t);break;case bj:this.getMask();break;case Lw:this.getData(t);break;case Nw:case vp:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(o);return}let r=(n[0]&64)===64;if(r&&!this._extensions[hj.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=vj:this._payloadLength===127?this._state=kj:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(o);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(n);return}this._masked?this._state=bj:this._state=Lw}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Lw}getData(t){let n=wj;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&r6(n,this._mask)}if(this._opcode>7){this.controlMessage(n,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(r);return}if(this._compressed){this._state=Nw,this.decompress(n,t);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(t)}decompress(t,n){this._extensions[hj.extensionName].decompress(t,this._fin,(o,s)=>{if(o)return n(o);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(i);return}this._fragments.push(s)}this.dataMessage(n),this._state===Rn&&this.startLoop(n)})}dataMessage(t){if(!this._fin){this._state=Rn;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=$w(r,n):this._binaryType==="arraybuffer"?o=n6($w(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Rn):(this._state=vp,setImmediate(()=>{this.emit("message",o,!0),this._state=Rn,this.startLoop(t)}))}else{let o=$w(r,n);if(!this._skipUTF8Validation&&!yj(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._state===Nw||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Rn):(this._state=vp,setImmediate(()=>{this.emit("message",o,!1),this._state=Rn,this.startLoop(t)}))}}controlMessage(t,n){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,wj),this.end();else{let r=t.readUInt16BE(0);if(!o6(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let o=new yp(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!yj(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=Rn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=Rn):(this._state=vp,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=Rn,this.startLoop(n)}))}createError(t,n,r,o,s){this._loop=!1,this._errored=!0;let i=new t(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(i,this.createError),i.code=s,i[e6]=o,i}};Sj.exports=Uw});var Ww=Te((pme,Pj)=>{"use strict";var{Duplex:ume}=Pe("stream"),{randomFillSync:a6}=Pe("crypto"),{types:{isUint8Array:s6}}=Pe("util"),Ij=ei(),{EMPTY_BUFFER:i6,kWebSocket:c6,NOOP:d6}=Br(),{isBlob:ni,isValidStatusCode:l6}=ti(),{mask:Rj,toBuffer:ca}=$c(),Pn=Symbol("kByteLength"),u6=Buffer.alloc(4),kp=8*1024,da,ri=kp,Nn=0,p6=1,m6=2,qw=class e{static{a(this,"Sender")}constructor(t,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Nn,this.onerror=d6,this[c6]=void 0}static frame(t,n){let r,o=!1,s=2,i=!1;n.mask&&(r=n.maskBuffer||u6,n.generateMask?n.generateMask(r):(ri===kp&&(da===void 0&&(da=Buffer.alloc(kp)),a6(da,0,kp),ri=0),r[0]=da[ri++],r[1]=da[ri++],r[2]=da[ri++],r[3]=da[ri++]),i=(r[0]|r[1]|r[2]|r[3])===0,s=6);let c;typeof t=="string"?(!n.mask||i)&&n[Pn]!==void 0?c=n[Pn]:(t=Buffer.from(t),c=t.length):(c=t.length,o=n.mask&&n.readOnly&&!i);let d=c;c>=65536?(s+=8,d=127):c>125&&(s+=2,d=126);let l=Buffer.allocUnsafe(o?c+s:s);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(c,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),n.mask?(l[1]|=128,l[s-4]=r[0],l[s-3]=r[1],l[s-2]=r[2],l[s-1]=r[3],i?[l,t]:o?(Rj(t,r,l,s,c),[l]):(Rj(t,r,t,0,c),[l,t])):[l,t]}close(t,n,r,o){let s;if(t===void 0)s=i6;else{if(typeof t!="number"||!l6(t))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0);else{let c=Buffer.byteLength(n);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+c),s.writeUInt16BE(t,0),typeof n=="string")s.write(n,2);else if(s6(n))s.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Pn]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Nn?this.enqueue([this.dispatch,s,!1,i,o]):this.sendFrame(e.frame(s,i),o)}ping(t,n,r){let o,s;if(typeof t=="string"?(o=Buffer.byteLength(t),s=!1):ni(t)?(o=t.size,s=!1):(t=ca(t),o=t.length,s=ca.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Pn]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ni(t)?this._state!==Nn?this.enqueue([this.getBlobData,t,!1,i,r]):this.getBlobData(t,!1,i,r):this._state!==Nn?this.enqueue([this.dispatch,t,!1,i,r]):this.sendFrame(e.frame(t,i),r)}pong(t,n,r){let o,s;if(typeof t=="string"?(o=Buffer.byteLength(t),s=!1):ni(t)?(o=t.size,s=!1):(t=ca(t),o=t.length,s=ca.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Pn]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ni(t)?this._state!==Nn?this.enqueue([this.getBlobData,t,!1,i,r]):this.getBlobData(t,!1,i,r):this._state!==Nn?this.enqueue([this.dispatch,t,!1,i,r]):this.sendFrame(e.frame(t,i),r)}send(t,n,r){let o=this._extensions[Ij.extensionName],s=n.binary?2:1,i=n.compress,c,d;typeof t=="string"?(c=Buffer.byteLength(t),d=!1):ni(t)?(c=t.size,d=!1):(t=ca(t),c=t.length,d=ca.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=o._threshold),this._compress=i):(i=!1,s=0),n.fin&&(this._firstFragment=!0);let l={[Pn]:c,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:d,rsv1:i};ni(t)?this._state!==Nn?this.enqueue([this.getBlobData,t,this._compress,l,r]):this.getBlobData(t,this._compress,l,r):this._state!==Nn?this.enqueue([this.dispatch,t,this._compress,l,r]):this.dispatch(t,this._compress,l,r)}getBlobData(t,n,r,o){this._bufferedBytes+=r[Pn],this._state=m6,t.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(zw,this,c,o);return}this._bufferedBytes-=r[Pn];let i=ca(s);n?this.dispatch(i,n,r,o):(this._state=Nn,this.sendFrame(e.frame(i,r),o),this.dequeue())}).catch(s=>{process.nextTick(f6,this,s,o)})}dispatch(t,n,r,o){if(!n){this.sendFrame(e.frame(t,r),o);return}let s=this._extensions[Ij.extensionName];this._bufferedBytes+=r[Pn],this._state=p6,s.compress(t,r.fin,(i,c)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");zw(this,d,o);return}this._bufferedBytes-=r[Pn],this._state=Nn,r.readOnly=!1,this.sendFrame(e.frame(c,r),o),this.dequeue()})}dequeue(){for(;this._state===Nn&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][Pn],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][Pn],this._queue.push(t)}sendFrame(t,n){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],n),this._socket.uncork()):this._socket.write(t[0],n)}};Pj.exports=qw;function zw(e,t,n){typeof n=="function"&&n(t);for(let r=0;r<e._queue.length;r++){let o=e._queue[r],s=o[o.length-1];typeof s=="function"&&s(t)}}a(zw,"callCallbacks");function f6(e,t,n){zw(e,t,n),e.onerror(t)}a(f6,"onError")});var Hj=Te((fme,jj)=>{"use strict";var{kForOnEventAttribute:Nc,kListener:Vw}=Br(),_j=Symbol("kCode"),xj=Symbol("kData"),Tj=Symbol("kError"),Aj=Symbol("kMessage"),Cj=Symbol("kReason"),oi=Symbol("kTarget"),Ej=Symbol("kType"),Mj=Symbol("kWasClean"),Lr=class{static{a(this,"Event")}constructor(t){this[oi]=null,this[Ej]=t}get target(){return this[oi]}get type(){return this[Ej]}};Object.defineProperty(Lr.prototype,"target",{enumerable:!0});Object.defineProperty(Lr.prototype,"type",{enumerable:!0});var la=class extends Lr{static{a(this,"CloseEvent")}constructor(t,n={}){super(t),this[_j]=n.code===void 0?0:n.code,this[Cj]=n.reason===void 0?"":n.reason,this[Mj]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[_j]}get reason(){return this[Cj]}get wasClean(){return this[Mj]}};Object.defineProperty(la.prototype,"code",{enumerable:!0});Object.defineProperty(la.prototype,"reason",{enumerable:!0});Object.defineProperty(la.prototype,"wasClean",{enumerable:!0});var ai=class extends Lr{static{a(this,"ErrorEvent")}constructor(t,n={}){super(t),this[Tj]=n.error===void 0?null:n.error,this[Aj]=n.message===void 0?"":n.message}get error(){return this[Tj]}get message(){return this[Aj]}};Object.defineProperty(ai.prototype,"error",{enumerable:!0});Object.defineProperty(ai.prototype,"message",{enumerable:!0});var Uc=class extends Lr{static{a(this,"MessageEvent")}constructor(t,n={}){super(t),this[xj]=n.data===void 0?null:n.data}get data(){return this[xj]}};Object.defineProperty(Uc.prototype,"data",{enumerable:!0});var g6={addEventListener(e,t,n={}){for(let o of this.listeners(e))if(!n[Nc]&&o[Vw]===t&&!o[Nc])return;let r;if(e==="message")r=a(function(s,i){let c=new Uc("message",{data:i?s:s.toString()});c[oi]=this,bp(t,this,c)},"onMessage");else if(e==="close")r=a(function(s,i){let c=new la("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[oi]=this,bp(t,this,c)},"onClose");else if(e==="error")r=a(function(s){let i=new ai("error",{error:s,message:s.message});i[oi]=this,bp(t,this,i)},"onError");else if(e==="open")r=a(function(){let s=new Lr("open");s[oi]=this,bp(t,this,s)},"onOpen");else return;r[Nc]=!!n[Nc],r[Vw]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(let n of this.listeners(e))if(n[Vw]===t&&!n[Nc]){this.removeListener(e,n);break}}};jj.exports={CloseEvent:la,ErrorEvent:ai,Event:Lr,EventTarget:g6,MessageEvent:Uc};function bp(e,t,n){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}a(bp,"callListener")});var Sp=Te((hme,Oj)=>{"use strict";var{tokenChars:Fc}=ti();function mr(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}a(mr,"push");function h6(e){let t=Object.create(null),n=Object.create(null),r=!1,o=!1,s=!1,i,c,d=-1,l=-1,u=-1,p=0;for(;p<e.length;p++)if(l=e.charCodeAt(p),i===void 0)if(u===-1&&Fc[l]===1)d===-1&&(d=p);else if(p!==0&&(l===32||l===9))u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=e.slice(d,u);l===44?(mr(t,f,n),n=Object.create(null)):i=f,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===void 0)if(u===-1&&Fc[l]===1)d===-1&&(d=p);else if(l===32||l===9)u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),mr(n,e.slice(d,u),!0),l===44&&(mr(t,i,n),n=Object.create(null),i=void 0),d=u=-1}else if(l===61&&d!==-1&&u===-1)c=e.slice(d,p),d=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(Fc[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:r||(r=!0),o=!1}else if(s)if(Fc[l]===1)d===-1&&(d=p);else if(l===34&&d!==-1)s=!1,u=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&e.charCodeAt(p-1)===61)s=!0;else if(u===-1&&Fc[l]===1)d===-1&&(d=p);else if(d!==-1&&(l===32||l===9))u===-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=e.slice(d,u);r&&(f=f.replace(/\\/g,""),r=!1),mr(n,c,f),l===44&&(mr(t,i,n),n=Object.create(null),i=void 0),c=void 0,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let m=e.slice(d,u);return i===void 0?mr(t,m,n):(c===void 0?mr(n,m,!0):r?mr(n,c,m.replace(/\\/g,"")):mr(n,c,m),mr(t,i,n)),t}a(h6,"parse");function w6(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(r=>[t].concat(Object.keys(r).map(o=>{let s=r[o];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}a(w6,"format");Oj.exports={format:w6,parse:h6}});var _p=Te((kme,Jj)=>{"use strict";var y6=Pe("events"),v6=Pe("https"),k6=Pe("http"),$j=Pe("net"),b6=Pe("tls"),{randomBytes:S6,createHash:I6}=Pe("crypto"),{Duplex:yme,Readable:vme}=Pe("stream"),{URL:Jw}=Pe("url"),Io=ei(),R6=Fw(),P6=Ww(),{isBlob:_6}=ti(),{BINARY_TYPES:Dj,CLOSE_TIMEOUT:x6,EMPTY_BUFFER:Ip,GUID:T6,kForOnEventAttribute:Gw,kListener:A6,kStatusCode:C6,kWebSocket:pt,NOOP:Lj}=Br(),{EventTarget:{addEventListener:E6,removeEventListener:M6}}=Hj(),{format:j6,parse:H6}=Sp(),{toBuffer:O6}=$c(),Nj=Symbol("kAborted"),Kw=[8,13],Nr=["CONNECTING","OPEN","CLOSING","CLOSED"],D6=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ze=class e extends y6{static{a(this,"WebSocket")}constructor(t,n,r){super(),this._binaryType=Dj[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ip,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Uj(this,t,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Dj.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let o=new R6({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new P6(t,this._extensions,r.generateMask);this._receiver=o,this._sender=s,this._socket=t,o[pt]=this,s[pt]=this,t[pt]=this,o.on("conclude",L6),o.on("drain",N6),o.on("error",U6),o.on("message",F6),o.on("ping",q6),o.on("pong",z6),s.onerror=W6,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",zj),t.on("data",Pp),t.on("end",Wj),t.on("error",Vj),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Io.extensionName]&&this._extensions[Io.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){dn(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),qj(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(r=t,t=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Yw(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||Ip,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(r=t,t=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Yw(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||Ip,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Yw(this,t,r);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Io.extensionName]||(o.compress=!1),this._sender.send(t||Ip,o,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){dn(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(ze,"CONNECTING",{enumerable:!0,value:Nr.indexOf("CONNECTING")});Object.defineProperty(ze.prototype,"CONNECTING",{enumerable:!0,value:Nr.indexOf("CONNECTING")});Object.defineProperty(ze,"OPEN",{enumerable:!0,value:Nr.indexOf("OPEN")});Object.defineProperty(ze.prototype,"OPEN",{enumerable:!0,value:Nr.indexOf("OPEN")});Object.defineProperty(ze,"CLOSING",{enumerable:!0,value:Nr.indexOf("CLOSING")});Object.defineProperty(ze.prototype,"CLOSING",{enumerable:!0,value:Nr.indexOf("CLOSING")});Object.defineProperty(ze,"CLOSED",{enumerable:!0,value:Nr.indexOf("CLOSED")});Object.defineProperty(ze.prototype,"CLOSED",{enumerable:!0,value:Nr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(ze.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(ze.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[Gw])return t[A6];return null},set(t){for(let n of this.listeners(e))if(n[Gw]){this.removeListener(e,n);break}typeof t=="function"&&this.addEventListener(e,t,{[Gw]:!0})}})});ze.prototype.addEventListener=E6;ze.prototype.removeEventListener=M6;Jj.exports=ze;function Uj(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:x6,protocolVersion:Kw[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!Kw.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Kw.join(", ")})`);let s;if(t instanceof Jw)s=t;else try{s=new Jw(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",c=s.protocol==="ws+unix:",d;if(s.protocol!=="ws:"&&!i&&!c?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!s.pathname?d="The URL's pathname is empty":s.hash&&(d="The URL contains a fragment identifier"),d){let h=new SyntaxError(d);if(e._redirects===0)throw h;Rp(e,h);return}let l=i?443:80,u=S6(16).toString("base64"),p=i?v6.request:k6.request,m=new Set,f;if(o.createConnection=o.createConnection||(i?$6:B6),o.defaultPort=o.defaultPort||l,o.port=s.port||l,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(f=new Io({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=j6({[Io.extensionName]:f.offer()})),n.length){for(let h of n){if(typeof h!="string"||!D6.test(h)||m.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(h)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),c){let h=o.path.split(":");o.socketPath=h[0],o.path=h[1]}let y;if(o.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=i,e._originalHostOrSocketPath=c?o.socketPath:s.host;let h=r&&r.headers;if(r={...r,headers:{}},h)for(let[v,g]of Object.entries(h))r.headers[v.toLowerCase()]=g}else if(e.listenerCount("redirect")===0){let h=c?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!h||e._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,h||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),y=e._req=p(o),e._redirects&&e.emit("redirect",e.url,y)}else y=e._req=p(o);o.timeout&&y.on("timeout",()=>{dn(e,y,"Opening handshake has timed out")}),y.on("error",h=>{y===null||y[Nj]||(y=e._req=null,Rp(e,h))}),y.on("response",h=>{let v=h.headers.location,g=h.statusCode;if(v&&o.followRedirects&&g>=300&&g<400){if(++e._redirects>o.maxRedirects){dn(e,y,"Maximum redirects exceeded");return}y.abort();let I;try{I=new Jw(v,t)}catch{let k=new SyntaxError(`Invalid URL: ${v}`);Rp(e,k);return}Uj(e,I,n,r)}else e.emit("unexpected-response",y,h)||dn(e,y,`Unexpected server response: ${h.statusCode}`)}),y.on("upgrade",(h,v,g)=>{if(e.emit("upgrade",h),e.readyState!==ze.CONNECTING)return;y=e._req=null;let I=h.headers.upgrade;if(I===void 0||I.toLowerCase()!=="websocket"){dn(e,v,"Invalid Upgrade header");return}let R=I6("sha1").update(u+T6).digest("base64");if(h.headers["sec-websocket-accept"]!==R){dn(e,v,"Invalid Sec-WebSocket-Accept header");return}let k=h.headers["sec-websocket-protocol"],w;if(k!==void 0?m.size?m.has(k)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":m.size&&(w="Server sent no subprotocol"),w){dn(e,v,w);return}k&&(e._protocol=k);let T=h.headers["sec-websocket-extensions"];if(T!==void 0){if(!f){dn(e,v,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let C;try{C=H6(T)}catch{dn(e,v,"Invalid Sec-WebSocket-Extensions header");return}let b=Object.keys(C);if(b.length!==1||b[0]!==Io.extensionName){dn(e,v,"Server indicated an extension that was not requested");return}try{f.accept(C[Io.extensionName])}catch{dn(e,v,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[Io.extensionName]=f}e.setSocket(v,g,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(y,e):y.end()}a(Uj,"initAsClient");function Rp(e,t){e._readyState=ze.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}a(Rp,"emitErrorAndClose");function B6(e){return e.path=e.socketPath,$j.connect(e)}a(B6,"netConnect");function $6(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=$j.isIP(e.host)?"":e.host),b6.connect(e)}a($6,"tlsConnect");function dn(e,t,n){e._readyState=ze.CLOSING;let r=new Error(n);Error.captureStackTrace(r,dn),t.setHeader?(t[Nj]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Rp,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}a(dn,"abortHandshake");function Yw(e,t,n){if(t){let r=_6(t)?t.size:O6(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${e.readyState} (${Nr[e.readyState]})`);process.nextTick(n,r)}}a(Yw,"sendAfterClose");function L6(e,t){let n=this[pt];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[pt]!==void 0&&(n._socket.removeListener("data",Pp),process.nextTick(Fj,n._socket),e===1005?n.close():n.close(e,t))}a(L6,"receiverOnConclude");function N6(){let e=this[pt];e.isPaused||e._socket.resume()}a(N6,"receiverOnDrain");function U6(e){let t=this[pt];t._socket[pt]!==void 0&&(t._socket.removeListener("data",Pp),process.nextTick(Fj,t._socket),t.close(e[C6])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}a(U6,"receiverOnError");function Bj(){this[pt].emitClose()}a(Bj,"receiverOnFinish");function F6(e,t){this[pt].emit("message",e,t)}a(F6,"receiverOnMessage");function q6(e){let t=this[pt];t._autoPong&&t.pong(e,!this._isServer,Lj),t.emit("ping",e)}a(q6,"receiverOnPing");function z6(e){this[pt].emit("pong",e)}a(z6,"receiverOnPong");function Fj(e){e.resume()}a(Fj,"resume");function W6(e){let t=this[pt];t.readyState!==ze.CLOSED&&(t.readyState===ze.OPEN&&(t._readyState=ze.CLOSING,qj(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}a(W6,"senderOnError");function qj(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}a(qj,"setCloseTimer");function zj(){let e=this[pt];if(this.removeListener("close",zj),this.removeListener("data",Pp),this.removeListener("end",Wj),e._readyState=ze.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[pt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Bj),e._receiver.on("finish",Bj))}a(zj,"socketOnClose");function Pp(e){this[pt]._receiver.write(e)||this.pause()}a(Pp,"socketOnData");function Wj(){let e=this[pt];e._readyState=ze.CLOSING,e._receiver.end(),this.end()}a(Wj,"socketOnEnd");function Vj(){let e=this[pt];this.removeListener("error",Vj),this.on("error",Lj),e&&(e._readyState=ze.CLOSING,this.destroy())}a(Vj,"socketOnError")});var Xj=Te((Ime,Yj)=>{"use strict";var Sme=_p(),{Duplex:V6}=Pe("stream");function Gj(e){e.emit("close")}a(Gj,"emitClose");function J6(){!this.destroyed&&this._writableState.finished&&this.destroy()}a(J6,"duplexOnEnd");function Kj(e){this.removeListener("error",Kj),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}a(Kj,"duplexOnError");function G6(e,t){let n=!0,r=new V6({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",a(function(s,i){let c=!i&&r._readableState.objectMode?s.toString():s;r.push(c)||e.pause()},"message")),e.once("error",a(function(s){r.destroyed||(n=!1,r.destroy(s))},"error")),e.once("close",a(function(){r.destroyed||r.push(null)},"close")),r._destroy=function(o,s){if(e.readyState===e.CLOSED){s(o),process.nextTick(Gj,r);return}let i=!1;e.once("error",a(function(d){i=!0,s(d)},"error")),e.once("close",a(function(){i||s(o),process.nextTick(Gj,r)},"close")),n&&e.terminate()},r._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",a(function(){r._final(o)},"open"));return}e._socket!==null&&(e._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(e._socket.once("finish",a(function(){o()},"finish")),e.close()))},r._read=function(){e.isPaused&&e.resume()},r._write=function(o,s,i){if(e.readyState===e.CONNECTING){e.once("open",a(function(){r._write(o,s,i)},"open"));return}e.send(o,i)},r.on("end",J6),r.on("error",Kj),r}a(G6,"createWebSocketStream");Yj.exports=G6});var Xw=Te((Pme,Qj)=>{"use strict";var{tokenChars:K6}=ti();function Y6(e){let t=new Set,n=-1,r=-1,o=0;for(o;o<e.length;o++){let i=e.charCodeAt(o);if(r===-1&&K6[i]===1)n===-1&&(n=o);else if(o!==0&&(i===32||i===9))r===-1&&n!==-1&&(r=o);else if(i===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let c=e.slice(n,r);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(n,o);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}a(Y6,"parse");Qj.exports={parse:Y6}});var aH=Te((Tme,oH)=>{"use strict";var X6=Pe("events"),xp=Pe("http"),{Duplex:xme}=Pe("stream"),{createHash:Q6}=Pe("crypto"),Zj=Sp(),ua=ei(),Z6=Xw(),e5=_p(),{CLOSE_TIMEOUT:t5,GUID:n5,kWebSocket:r5}=Br(),o5=/^[+/0-9A-Za-z]{22}==$/,eH=0,tH=1,rH=2,Qw=class extends X6{static{a(this,"WebSocketServer")}constructor(t,n){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:t5,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:e5,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=xp.createServer((r,o)=>{let s=xp.STATUS_CODES[426];o.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),o.end(s)}),this._server.listen(t.port,t.host,t.backlog,n)):t.server&&(this._server=t.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=a5(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:a((o,s,i)=>{this.handleUpgrade(o,s,i,r)},"upgrade")})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=eH}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===rH){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(qc,this);return}if(t&&this.once("close",t),this._state!==tH)if(this._state=tH,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(qc,this):process.nextTick(qc,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{qc(this)})}}shouldHandle(t){if(this.options.path){let n=t.url.indexOf("?");if((n!==-1?t.url.slice(0,n):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,n,r,o){n.on("error",nH);let s=t.headers["sec-websocket-key"],i=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){pa(this,t,n,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){pa(this,t,n,400,"Invalid Upgrade header");return}if(s===void 0||!o5.test(s)){pa(this,t,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){pa(this,t,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){zc(n,400);return}let d=t.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=Z6.parse(d)}catch{pa(this,t,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=t.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let m=new ua({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=Zj.parse(u);f[ua.extensionName]&&(m.accept(f[ua.extensionName]),p[ua.extensionName]=m)}catch{pa(this,t,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,y,h,v)=>{if(!f)return zc(n,y||401,h,v);this.completeUpgrade(p,s,l,t,n,r,o)});return}if(!this.options.verifyClient(m))return zc(n,401)}this.completeUpgrade(p,s,l,t,n,r,o)}completeUpgrade(t,n,r,o,s,i,c){if(!s.readable||!s.writable)return s.destroy();if(s[r5])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>eH)return zc(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Q6("sha1").update(n+n5).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(t[ua.extensionName]){let p=t[ua.extensionName].params,m=Zj.format({[ua.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),u._extensions=t}this.emit("headers",l,o),s.write(l.concat(`\r
3
+ import{a as qA,b as zA,c as WA,d as j,e as VA,f as co,g as z,h as Su,j as JA}from"./chunk-YW6HS6TZ.js";import{$ as qx,$a as MT,$b as wA,A as su,Aa as cT,Ab as ZT,Ac as DA,B as dx,Ba as pe,Bb as eA,Bc as BA,C as lx,Ca as dT,Cb as tA,Cc as $A,D as ux,Da as lT,Db as wu,Dc as LA,E as iu,Ea as uT,Eb as nA,Ec as NA,F as px,Fa as pT,Fb as Zo,Fc as UA,G as mx,Ga as mT,Gb as yu,H as fx,Ha as fT,Hb as rA,Hc as FA,I as gx,Ia as gT,Ib as so,J as hx,Ja as hT,Jb as vu,K as pc,Ka as wT,Kb as oA,L as Cx,La as yT,Lb as aA,M as Ex,Ma as vT,Mb as rh,N as Mx,Na as Ss,Nb as oh,O as jx,Oa as On,Ob as sA,P as Hx,Pa as He,Pb as iA,Q as mc,Qa as kT,Qb as cA,R as Ox,Ra as bT,Rb as dA,S as Dx,Sa as ST,Sb as ah,T as vs,Ta as IT,Tb as lA,U as ks,Ua as _T,Ub as sh,V as Bx,Va as xT,Vb as uA,W as $x,Wa as gu,Wb as pA,X as Lx,Xa as TT,Xb as mA,Y as Nx,Ya as AT,Yb as fA,Z as Ux,Za as CT,Zb as gA,_ as Fx,_a as ET,_b as hA,a as vg,aa as oo,ab as nh,ac as yA,b as AS,ba as zx,bb as jT,bc as vA,c as CS,ca as Wx,cb as HT,cc as kA,d as ES,da as eh,db as OT,dc as ih,e as MS,ea as Vx,eb as DT,ec as bA,f as jS,fa as Jx,fb as BT,fc as ch,g as HS,ga as Gx,gb as $T,gc as SA,h as qo,ha as bs,hb as LT,hc as IA,i as OS,ia as Kx,ib as Dn,ic as RA,j as DS,ja as Yx,jb as NT,jc as PA,k as gl,ka as Xx,kb as hu,kc as _A,l as BS,la as Qx,lb as UT,lc as io,m as $S,ma as ae,mb as FT,mc as xr,n as z2,na as Zx,nb as Nt,nc as dh,o as S_,oa as eT,ob as Qo,oc as xA,p as I_,pa as tT,pb as qT,pc as TA,q as R_,qa as uu,qb as _r,qc as ku,r as P_,ra as nT,rb as zT,rc as Is,s as J_,sa as rT,sb as WT,sc as AA,t as ou,ta as oT,tb as VT,tc as bu,u as ox,ua as aT,ub as JT,uc as CA,v as ax,va as sT,vb as GT,vc as EA,w as sx,wa as pu,wb as KT,wc as MA,x as au,xa as iT,xb as YT,xc as jA,y as ix,ya as ao,yb as XT,yc as HA,z as cx,za as Ae,zb as QT,zc as OA}from"./chunk-PZXZYP6Z.js";import{A as Ix,C as du,F as lu,G as cr,H as Rx,I as Yg,J as Px,K as Xg,N as _x,O as Qg,P as xx,Q as Tx,R as Ax,S as Zg,T as ys,b as cu,d as wx,e as yx,h as vx,m as ws,n as kx,p as bx,q as Sx,s as uc}from"./chunk-2OQ6LFSG.js";import{Aa as F_,Ca as q_,Fa as z_,Ka as W_,La as eu,Ma as tu,Na as hs,P as A_,Q as C_,R as E_,Ra as V_,S as M_,T as j_,Ta as th,U as H_,Ua as RT,V as Xl,Va as mu,W as O_,Wa as fu,Xa as PT,a as uS,b as pS,c as mS,e as fS,f as gS,g as pl,h as SS,i as IS,j as RS,ja as Ql,k as PS,l as _S,ma as D_,o as ct,p as __,pa as B_,q as x_,qa as $_,ra as gs,sa as Zl,t as T_,ta as lc,va as Kg,wa as Xo,xa as L_,ya as N_,za as U_}from"./chunk-YD2IWF3T.js";import{a as k_,b as Yl,d as ie,e as it,f as fs,g as ne,i as b_}from"./chunk-7FX5ABXG.js";import{a as on,b as G_,c as K_,d as nu,e as ru,g as Y_,h as X_,j as Q_,k as Z_,l as ex,m as tx,n as nx,o as rx}from"./chunk-JVIHGSOV.js";import{$ as gR,$a as to,$b as gP,$c as ls,$d as Gl,A as oR,Aa as jg,Ab as Dg,B as Tl,Bb as Bl,Bc as DP,C as aR,Ca as qe,Cc as sc,D as Cg,Da as Ml,Db as Bg,Dc as qg,E as sR,Ea as PR,Eb as oc,F as iR,Fa as Hg,G as tt,Gb as rP,Gc as Nl,Gd as Ko,H as cR,Ha as _R,Hd as n_,I as yt,Ic as zg,Id as Pr,J as rc,Jb as oP,Jc as BP,Jd as r_,K as dR,Kb as aP,Kc as $P,Kd as o_,L as lR,Lb as sP,Ld as a_,Md as no,N as uR,Na as xR,Nb as cs,Nc as Ul,Nd as ps,Ob as iP,Oc as LP,Od as Wl,P as pR,Pa as jl,Pc as Wg,Pd as s_,Q as mR,Qa as TR,Qb as ac,Qc as sr,Qd as i_,R as Hn,Rb as $l,Rc as NP,Rd as c_,Sa as AR,Sb as cP,Sc as UP,Sd as cc,Ta as CR,Tb as $g,Tc as Vg,Td as ms,Ua as ER,Ub as dP,Uc as ic,Ud as Vl,Va as MR,Vb as lP,Vc as FP,Vd as d_,Wa as jR,Wb as Lg,Wc as Fl,Wd as Jl,X as fR,Xa as HR,Xb as uP,Xc as qP,Xd as ro,Ya as OR,Yb as pP,Yc as zP,Yd as l_,Z as Al,Za as DR,Zb as mP,Zc as ds,Zd as u_,_a as BR,_b as fP,_c as WP,_d as p_,ac as hP,ad as VP,ae as m_,bb as $R,bc as wP,bd as JP,be as dc,c as WI,ca as Eg,cb as LR,cc as Ng,cd as Jg,ce as f_,da as hR,db as NR,dc as yP,dd as ql,de as g_,ea as Lt,eb as UR,ec as vP,ed as GP,fa as Vo,fc as kP,fd as Be,ga as Jo,gb as FR,gc as bP,gd as zl,ha as Mg,hb as Hl,hc as Ug,hd as KP,ia as wR,ib as qR,ic as SP,id as YP,ja as yR,jb as zR,jc as IP,jd as XP,ka as vR,kb as WR,kc as RP,kd as Gg,l as VI,la as kR,lb as VR,lc as PP,ld as QP,m as JI,ma as bR,mb as JR,mc as _P,md as ZP,me as Kl,n as GI,na as SR,nb as GR,nc as xP,nd as e_,ne as h_,oa as Cl,ob as KR,oc as TP,oe as w_,pb as YR,pc as AP,pd as us,pe as ir,q as KI,qa as El,qb as XR,qc as CP,qd as t_,qe as y_,r as YI,rb as QR,rc as EP,re as Yo,s as XI,sb as ZR,sc as Fg,se as v_,t as QI,tb as eP,tc as Go,u as ZI,ub as tP,uc as MP,v as Ag,vb as Og,vc as jP,w as eR,wb as Ol,wc as HP,x as tR,xa as IR,xb as nP,y as nR,yb as ar,yc as Ll,z as rR,za as RR,zb as Dl,zc as OP}from"./chunk-MVAJMRCW.js";import{a as YS,c as jI,h as HI}from"./chunk-L54LZUGH.js";import{b as hS,c as wS}from"./chunk-L3KS6MOV.js";import"./chunk-XEOEKFG6.js";import{A as tc,B as _g,C as xl,D as $I,E as LI,I as NI,J as UI,N as is,O as nc,P as FI,Q as qI,R as zI,T as xg,V as Tg,i as OI,t as DI,u as BI,v as wn,w as _l,z as Wo}from"./chunk-55UCBRIX.js";import"./chunk-6MI4KKWF.js";import{A as kg,Aa as sI,Ac as Il,B as NS,Bc as Rl,C as US,Ca as rs,Cb as gI,Cc as Pl,D as FS,Dc as xI,E as wl,Eb as hI,Ec as Pg,F as qS,Fa as iI,Fb as wI,Fc as TI,G as zS,H as WS,Ha as cI,Hc as AI,I as VS,Ic as CI,Jc as EI,Kc as eo,Lc as MI,Mc as or,Nb as yI,Pa as jn,Q as JS,Qa as dI,Qb as vI,R as GS,Ra as vl,Sa as rn,V as KS,Va as lI,Vb as kI,_a as uI,_b as as,a as yS,ab as Sg,b as vS,bb as je,c as hn,cb as zo,db as Qe,f as kS,fa as XS,fc as Rg,g as ul,gc as bI,h as bS,hb as pI,jc as SI,kb as ec,kc as bl,lb as mI,m as ml,ma as QS,mb as kl,mc as Sl,na as ZS,nc as II,o as xS,oa as eI,ob as fI,pa as tI,pb as Ig,pc as RI,qa as nI,qb as os,ra as yl,sa as bg,ta as rI,u as fl,ua as oI,v as TS,va as aI,w as LS,x as hl,xc as ss,yc as PI,zc as _I}from"./chunk-QTEYV4TW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{D as ns,E as Qi,F as ll,d as dl,m as dS,n as Zr,o as Ve,p as lS}from"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import{$a as cl,$b as iS,Da as q2,Ea as eS,Fa as wg,Ga as yg,Ia as tS,Lb as Je,Mb as Vt,Pa as nS,S as sl,Sb as sS,Ta as rS,Ua as oS,a as nn,bc as cS,hb as aS,qa as Xb,ra as il,ta as Qb,wa as Zb}from"./chunk-5BFWDFPX.js";import{a as Zi}from"./chunk-6FA3GG5B.js";import{A as Ct,B as Lo,C as xb,D as Xi,E as Rr,F as tl,G as Tb,Ga as Qr,H as nl,I as Ab,Ia as No,J as es,L as Cb,M as Eb,N as Mb,Na as Nb,O as jb,Oa as Ub,P as Hb,Pa as qb,Qa as zb,Ta as Wb,Va as gg,W as fg,Wa as hg,Xa as Vb,ca as Ob,f as Xd,ga as Xr,ia as Db,ib as ol,jb as Jb,k as Qa,ka as Bb,l as Za,la as $b,m as pg,ma as Lb,n as Qd,nb as Gb,o as st,ob as Kb,p as mg,q as Zd,qb as Fo,rb as Yb,sb as al,t as We,u as Se,v as O,w as Pb,y as _b,z as el}from"./chunk-IFP6W4OW.js";import{a as $o,b as _}from"./chunk-ES2ISFJC.js";import{a as Sb,c as Bo,f as Ib,h as Yd,i as Rb,p as ts,q as Fb,r as Uo,s as rl}from"./chunk-H7IWJN7L.js";import{a,b as Pe,c as Te,e as Mn}from"./chunk-FTQLQJQV.js";var Br=Te((Zpe,aj)=>{"use strict";var rj=["nodebuffer","arraybuffer","fragments"],oj=typeof Blob<"u";oj&&rj.push("blob");aj.exports={BINARY_TYPES:rj,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:oj,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:a(()=>{},"NOOP")}});var $c=Te((tme,fp)=>{"use strict";var{EMPTY_BUFFER:NG}=Br(),Mw=Buffer[Symbol.species];function UG(e,t){if(e.length===0)return NG;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),r=0;for(let o=0;o<e.length;o++){let s=e[o];n.set(s,r),r+=s.length}return r<t?new Mw(n.buffer,n.byteOffset,r):n}a(UG,"concat");function sj(e,t,n,r,o){for(let s=0;s<o;s++)n[r+s]=e[s]^t[s&3]}a(sj,"_mask");function ij(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}a(ij,"_unmask");function FG(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}a(FG,"toArrayBuffer");function jw(e){if(jw.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new Mw(e):ArrayBuffer.isView(e)?t=new Mw(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),jw.readOnly=!1),t}a(jw,"toBuffer");fp.exports={concat:UG,mask:sj,toArrayBuffer:FG,toBuffer:jw,unmask:ij};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=Pe("bufferutil");fp.exports.mask=function(t,n,r,o,s){s<48?sj(t,n,r,o,s):e.mask(t,n,r,o,s)},fp.exports.unmask=function(t,n){t.length<32?ij(t,n):e.unmask(t,n)}}catch{}});var lj=Te((rme,dj)=>{"use strict";var cj=Symbol("kDone"),Hw=Symbol("kRun"),Ow=class{static{a(this,"Limiter")}constructor(t){this[cj]=()=>{this.pending--,this[Hw]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[Hw]()}[Hw](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[cj])}}};dj.exports=Ow});var ei=Te((ame,fj)=>{"use strict";var Lc=Pe("zlib"),uj=$c(),qG=lj(),{kStatusCode:pj}=Br(),zG=Buffer[Symbol.species],WG=Buffer.from([0,0,255,255]),hp=Symbol("permessage-deflate"),$r=Symbol("total-length"),Qs=Symbol("callback"),So=Symbol("buffers"),Zs=Symbol("error"),gp,Dw=class{static{a(this,"PerMessageDeflate")}constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!gp){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;gp=new qG(n)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Qs];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let n=this._options,r=t.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(t){let n=t[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(t){return t.forEach(n=>{Object.keys(n).forEach(r=>{let o=n[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=s}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=o})}),t}decompress(t,n,r){gp.add(o=>{this._decompress(t,n,(s,i)=>{o(),r(s,i)})})}compress(t,n,r){gp.add(o=>{this._compress(t,n,(s,i)=>{o(),r(s,i)})})}_decompress(t,n,r){let o=this._isServer?"client":"server";if(!this._inflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Lc.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Lc.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[hp]=this,this._inflate[$r]=0,this._inflate[So]=[],this._inflate.on("error",JG),this._inflate.on("data",mj)}this._inflate[Qs]=r,this._inflate.write(t),n&&this._inflate.write(WG),this._inflate.flush(()=>{let s=this._inflate[Zs];if(s){this._inflate.close(),this._inflate=null,r(s);return}let i=uj.concat(this._inflate[So],this._inflate[$r]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[$r]=0,this._inflate[So]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,i)})}_compress(t,n,r){let o=this._isServer?"server":"client";if(!this._deflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Lc.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Lc.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[$r]=0,this._deflate[So]=[],this._deflate.on("data",VG)}this._deflate[Qs]=r,this._deflate.write(t),this._deflate.flush(Lc.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=uj.concat(this._deflate[So],this._deflate[$r]);n&&(s=new zG(s.buffer,s.byteOffset,s.length-4)),this._deflate[Qs]=null,this._deflate[$r]=0,this._deflate[So]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};fj.exports=Dw;function VG(e){this[So].push(e),this[$r]+=e.length}a(VG,"deflateOnData");function mj(e){if(this[$r]+=e.length,this[hp]._maxPayload<1||this[$r]<=this[hp]._maxPayload){this[So].push(e);return}this[Zs]=new RangeError("Max payload size exceeded"),this[Zs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zs][pj]=1009,this.removeListener("data",mj),this.reset()}a(mj,"inflateOnData");function JG(e){if(this[hp]._inflate=null,this[Zs]){this[Qs](this[Zs]);return}e[pj]=1007,this[Qs](e)}a(JG,"inflateOnError")});var ti=Te((ime,wp)=>{"use strict";var{isUtf8:gj}=Pe("buffer"),{hasBlob:GG}=Br(),KG=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function YG(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}a(YG,"isValidStatusCode");function Bw(e){let t=e.length,n=0;for(;n<t;)if((e[n]&128)===0)n++;else if((e[n]&224)===192){if(n+1===t||(e[n+1]&192)!==128||(e[n]&254)===192)return!1;n+=2}else if((e[n]&240)===224){if(n+2>=t||(e[n+1]&192)!==128||(e[n+2]&192)!==128||e[n]===224&&(e[n+1]&224)===128||e[n]===237&&(e[n+1]&224)===160)return!1;n+=3}else if((e[n]&248)===240){if(n+3>=t||(e[n+1]&192)!==128||(e[n+2]&192)!==128||(e[n+3]&192)!==128||e[n]===240&&(e[n+1]&240)===128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}a(Bw,"_isValidUTF8");function XG(e){return GG&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}a(XG,"isBlob");wp.exports={isBlob:XG,isValidStatusCode:YG,isValidUTF8:Bw,tokenChars:KG};if(gj)wp.exports.isValidUTF8=function(e){return e.length<24?Bw(e):gj(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=Pe("utf-8-validate");wp.exports.isValidUTF8=function(t){return t.length<32?Bw(t):e(t)}}catch{}});var Fw=Te((dme,Sj)=>{"use strict";var{Writable:QG}=Pe("stream"),hj=ei(),{BINARY_TYPES:ZG,EMPTY_BUFFER:wj,kStatusCode:e6,kWebSocket:t6}=Br(),{concat:$w,toArrayBuffer:n6,unmask:r6}=$c(),{isValidStatusCode:o6,isValidUTF8:yj}=ti(),yp=Buffer[Symbol.species],Rn=0,vj=1,kj=2,bj=3,Lw=4,Nw=5,vp=6,Uw=class extends QG{static{a(this,"Receiver")}constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||ZG[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[t6]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Rn}_write(t,n,r){if(this._opcode===8&&this._state==Rn)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(r)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new yp(r.buffer,r.byteOffset+t,r.length-t),new yp(r.buffer,r.byteOffset,t)}let n=Buffer.allocUnsafe(t);do{let r=this._buffers[0],o=n.length-t;t>=r.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(r.buffer,r.byteOffset,t),o),this._buffers[0]=new yp(r.buffer,r.byteOffset+t,r.length-t)),t-=r.length}while(t>0);return n}startLoop(t){this._loop=!0;do switch(this._state){case Rn:this.getInfo(t);break;case vj:this.getPayloadLength16(t);break;case kj:this.getPayloadLength64(t);break;case bj:this.getMask();break;case Lw:this.getData(t);break;case Nw:case vp:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(o);return}let r=(n[0]&64)===64;if(r&&!this._extensions[hj.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=vj:this._payloadLength===127?this._state=kj:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(o);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(n);return}this._masked?this._state=bj:this._state=Lw}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Lw}getData(t){let n=wj;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&r6(n,this._mask)}if(this._opcode>7){this.controlMessage(n,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(r);return}if(this._compressed){this._state=Nw,this.decompress(n,t);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(t)}decompress(t,n){this._extensions[hj.extensionName].decompress(t,this._fin,(o,s)=>{if(o)return n(o);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(i);return}this._fragments.push(s)}this.dataMessage(n),this._state===Rn&&this.startLoop(n)})}dataMessage(t){if(!this._fin){this._state=Rn;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=$w(r,n):this._binaryType==="arraybuffer"?o=n6($w(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Rn):(this._state=vp,setImmediate(()=>{this.emit("message",o,!0),this._state=Rn,this.startLoop(t)}))}else{let o=$w(r,n);if(!this._skipUTF8Validation&&!yj(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._state===Nw||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Rn):(this._state=vp,setImmediate(()=>{this.emit("message",o,!1),this._state=Rn,this.startLoop(t)}))}}controlMessage(t,n){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,wj),this.end();else{let r=t.readUInt16BE(0);if(!o6(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let o=new yp(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!yj(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=Rn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=Rn):(this._state=vp,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=Rn,this.startLoop(n)}))}createError(t,n,r,o,s){this._loop=!1,this._errored=!0;let i=new t(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(i,this.createError),i.code=s,i[e6]=o,i}};Sj.exports=Uw});var Ww=Te((pme,Pj)=>{"use strict";var{Duplex:ume}=Pe("stream"),{randomFillSync:a6}=Pe("crypto"),{types:{isUint8Array:s6}}=Pe("util"),Ij=ei(),{EMPTY_BUFFER:i6,kWebSocket:c6,NOOP:d6}=Br(),{isBlob:ni,isValidStatusCode:l6}=ti(),{mask:Rj,toBuffer:ca}=$c(),Pn=Symbol("kByteLength"),u6=Buffer.alloc(4),kp=8*1024,da,ri=kp,Nn=0,p6=1,m6=2,qw=class e{static{a(this,"Sender")}constructor(t,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Nn,this.onerror=d6,this[c6]=void 0}static frame(t,n){let r,o=!1,s=2,i=!1;n.mask&&(r=n.maskBuffer||u6,n.generateMask?n.generateMask(r):(ri===kp&&(da===void 0&&(da=Buffer.alloc(kp)),a6(da,0,kp),ri=0),r[0]=da[ri++],r[1]=da[ri++],r[2]=da[ri++],r[3]=da[ri++]),i=(r[0]|r[1]|r[2]|r[3])===0,s=6);let c;typeof t=="string"?(!n.mask||i)&&n[Pn]!==void 0?c=n[Pn]:(t=Buffer.from(t),c=t.length):(c=t.length,o=n.mask&&n.readOnly&&!i);let d=c;c>=65536?(s+=8,d=127):c>125&&(s+=2,d=126);let l=Buffer.allocUnsafe(o?c+s:s);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(c,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),n.mask?(l[1]|=128,l[s-4]=r[0],l[s-3]=r[1],l[s-2]=r[2],l[s-1]=r[3],i?[l,t]:o?(Rj(t,r,l,s,c),[l]):(Rj(t,r,t,0,c),[l,t])):[l,t]}close(t,n,r,o){let s;if(t===void 0)s=i6;else{if(typeof t!="number"||!l6(t))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0);else{let c=Buffer.byteLength(n);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(s=Buffer.allocUnsafe(2+c),s.writeUInt16BE(t,0),typeof n=="string")s.write(n,2);else if(s6(n))s.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Pn]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Nn?this.enqueue([this.dispatch,s,!1,i,o]):this.sendFrame(e.frame(s,i),o)}ping(t,n,r){let o,s;if(typeof t=="string"?(o=Buffer.byteLength(t),s=!1):ni(t)?(o=t.size,s=!1):(t=ca(t),o=t.length,s=ca.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Pn]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ni(t)?this._state!==Nn?this.enqueue([this.getBlobData,t,!1,i,r]):this.getBlobData(t,!1,i,r):this._state!==Nn?this.enqueue([this.dispatch,t,!1,i,r]):this.sendFrame(e.frame(t,i),r)}pong(t,n,r){let o,s;if(typeof t=="string"?(o=Buffer.byteLength(t),s=!1):ni(t)?(o=t.size,s=!1):(t=ca(t),o=t.length,s=ca.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Pn]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ni(t)?this._state!==Nn?this.enqueue([this.getBlobData,t,!1,i,r]):this.getBlobData(t,!1,i,r):this._state!==Nn?this.enqueue([this.dispatch,t,!1,i,r]):this.sendFrame(e.frame(t,i),r)}send(t,n,r){let o=this._extensions[Ij.extensionName],s=n.binary?2:1,i=n.compress,c,d;typeof t=="string"?(c=Buffer.byteLength(t),d=!1):ni(t)?(c=t.size,d=!1):(t=ca(t),c=t.length,d=ca.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=o._threshold),this._compress=i):(i=!1,s=0),n.fin&&(this._firstFragment=!0);let l={[Pn]:c,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:d,rsv1:i};ni(t)?this._state!==Nn?this.enqueue([this.getBlobData,t,this._compress,l,r]):this.getBlobData(t,this._compress,l,r):this._state!==Nn?this.enqueue([this.dispatch,t,this._compress,l,r]):this.dispatch(t,this._compress,l,r)}getBlobData(t,n,r,o){this._bufferedBytes+=r[Pn],this._state=m6,t.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(zw,this,c,o);return}this._bufferedBytes-=r[Pn];let i=ca(s);n?this.dispatch(i,n,r,o):(this._state=Nn,this.sendFrame(e.frame(i,r),o),this.dequeue())}).catch(s=>{process.nextTick(f6,this,s,o)})}dispatch(t,n,r,o){if(!n){this.sendFrame(e.frame(t,r),o);return}let s=this._extensions[Ij.extensionName];this._bufferedBytes+=r[Pn],this._state=p6,s.compress(t,r.fin,(i,c)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");zw(this,d,o);return}this._bufferedBytes-=r[Pn],this._state=Nn,r.readOnly=!1,this.sendFrame(e.frame(c,r),o),this.dequeue()})}dequeue(){for(;this._state===Nn&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][Pn],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][Pn],this._queue.push(t)}sendFrame(t,n){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],n),this._socket.uncork()):this._socket.write(t[0],n)}};Pj.exports=qw;function zw(e,t,n){typeof n=="function"&&n(t);for(let r=0;r<e._queue.length;r++){let o=e._queue[r],s=o[o.length-1];typeof s=="function"&&s(t)}}a(zw,"callCallbacks");function f6(e,t,n){zw(e,t,n),e.onerror(t)}a(f6,"onError")});var Hj=Te((fme,jj)=>{"use strict";var{kForOnEventAttribute:Nc,kListener:Vw}=Br(),_j=Symbol("kCode"),xj=Symbol("kData"),Tj=Symbol("kError"),Aj=Symbol("kMessage"),Cj=Symbol("kReason"),oi=Symbol("kTarget"),Ej=Symbol("kType"),Mj=Symbol("kWasClean"),Lr=class{static{a(this,"Event")}constructor(t){this[oi]=null,this[Ej]=t}get target(){return this[oi]}get type(){return this[Ej]}};Object.defineProperty(Lr.prototype,"target",{enumerable:!0});Object.defineProperty(Lr.prototype,"type",{enumerable:!0});var la=class extends Lr{static{a(this,"CloseEvent")}constructor(t,n={}){super(t),this[_j]=n.code===void 0?0:n.code,this[Cj]=n.reason===void 0?"":n.reason,this[Mj]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[_j]}get reason(){return this[Cj]}get wasClean(){return this[Mj]}};Object.defineProperty(la.prototype,"code",{enumerable:!0});Object.defineProperty(la.prototype,"reason",{enumerable:!0});Object.defineProperty(la.prototype,"wasClean",{enumerable:!0});var ai=class extends Lr{static{a(this,"ErrorEvent")}constructor(t,n={}){super(t),this[Tj]=n.error===void 0?null:n.error,this[Aj]=n.message===void 0?"":n.message}get error(){return this[Tj]}get message(){return this[Aj]}};Object.defineProperty(ai.prototype,"error",{enumerable:!0});Object.defineProperty(ai.prototype,"message",{enumerable:!0});var Uc=class extends Lr{static{a(this,"MessageEvent")}constructor(t,n={}){super(t),this[xj]=n.data===void 0?null:n.data}get data(){return this[xj]}};Object.defineProperty(Uc.prototype,"data",{enumerable:!0});var g6={addEventListener(e,t,n={}){for(let o of this.listeners(e))if(!n[Nc]&&o[Vw]===t&&!o[Nc])return;let r;if(e==="message")r=a(function(s,i){let c=new Uc("message",{data:i?s:s.toString()});c[oi]=this,bp(t,this,c)},"onMessage");else if(e==="close")r=a(function(s,i){let c=new la("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[oi]=this,bp(t,this,c)},"onClose");else if(e==="error")r=a(function(s){let i=new ai("error",{error:s,message:s.message});i[oi]=this,bp(t,this,i)},"onError");else if(e==="open")r=a(function(){let s=new Lr("open");s[oi]=this,bp(t,this,s)},"onOpen");else return;r[Nc]=!!n[Nc],r[Vw]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(let n of this.listeners(e))if(n[Vw]===t&&!n[Nc]){this.removeListener(e,n);break}}};jj.exports={CloseEvent:la,ErrorEvent:ai,Event:Lr,EventTarget:g6,MessageEvent:Uc};function bp(e,t,n){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}a(bp,"callListener")});var Sp=Te((hme,Oj)=>{"use strict";var{tokenChars:Fc}=ti();function mr(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}a(mr,"push");function h6(e){let t=Object.create(null),n=Object.create(null),r=!1,o=!1,s=!1,i,c,d=-1,l=-1,u=-1,p=0;for(;p<e.length;p++)if(l=e.charCodeAt(p),i===void 0)if(u===-1&&Fc[l]===1)d===-1&&(d=p);else if(p!==0&&(l===32||l===9))u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=e.slice(d,u);l===44?(mr(t,f,n),n=Object.create(null)):i=f,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===void 0)if(u===-1&&Fc[l]===1)d===-1&&(d=p);else if(l===32||l===9)u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),mr(n,e.slice(d,u),!0),l===44&&(mr(t,i,n),n=Object.create(null),i=void 0),d=u=-1}else if(l===61&&d!==-1&&u===-1)c=e.slice(d,p),d=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(Fc[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:r||(r=!0),o=!1}else if(s)if(Fc[l]===1)d===-1&&(d=p);else if(l===34&&d!==-1)s=!1,u=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&e.charCodeAt(p-1)===61)s=!0;else if(u===-1&&Fc[l]===1)d===-1&&(d=p);else if(d!==-1&&(l===32||l===9))u===-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=e.slice(d,u);r&&(f=f.replace(/\\/g,""),r=!1),mr(n,c,f),l===44&&(mr(t,i,n),n=Object.create(null),i=void 0),c=void 0,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let m=e.slice(d,u);return i===void 0?mr(t,m,n):(c===void 0?mr(n,m,!0):r?mr(n,c,m.replace(/\\/g,"")):mr(n,c,m),mr(t,i,n)),t}a(h6,"parse");function w6(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(r=>[t].concat(Object.keys(r).map(o=>{let s=r[o];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}a(w6,"format");Oj.exports={format:w6,parse:h6}});var _p=Te((kme,Jj)=>{"use strict";var y6=Pe("events"),v6=Pe("https"),k6=Pe("http"),$j=Pe("net"),b6=Pe("tls"),{randomBytes:S6,createHash:I6}=Pe("crypto"),{Duplex:yme,Readable:vme}=Pe("stream"),{URL:Jw}=Pe("url"),Io=ei(),R6=Fw(),P6=Ww(),{isBlob:_6}=ti(),{BINARY_TYPES:Dj,CLOSE_TIMEOUT:x6,EMPTY_BUFFER:Ip,GUID:T6,kForOnEventAttribute:Gw,kListener:A6,kStatusCode:C6,kWebSocket:pt,NOOP:Lj}=Br(),{EventTarget:{addEventListener:E6,removeEventListener:M6}}=Hj(),{format:j6,parse:H6}=Sp(),{toBuffer:O6}=$c(),Nj=Symbol("kAborted"),Kw=[8,13],Nr=["CONNECTING","OPEN","CLOSING","CLOSED"],D6=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ze=class e extends y6{static{a(this,"WebSocket")}constructor(t,n,r){super(),this._binaryType=Dj[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ip,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Uj(this,t,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Dj.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let o=new R6({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new P6(t,this._extensions,r.generateMask);this._receiver=o,this._sender=s,this._socket=t,o[pt]=this,s[pt]=this,t[pt]=this,o.on("conclude",L6),o.on("drain",N6),o.on("error",U6),o.on("message",F6),o.on("ping",q6),o.on("pong",z6),s.onerror=W6,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",zj),t.on("data",Pp),t.on("end",Wj),t.on("error",Vj),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Io.extensionName]&&this._extensions[Io.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){dn(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),qj(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(r=t,t=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Yw(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||Ip,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(r=t,t=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Yw(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||Ip,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Yw(this,t,r);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Io.extensionName]||(o.compress=!1),this._sender.send(t||Ip,o,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){dn(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(ze,"CONNECTING",{enumerable:!0,value:Nr.indexOf("CONNECTING")});Object.defineProperty(ze.prototype,"CONNECTING",{enumerable:!0,value:Nr.indexOf("CONNECTING")});Object.defineProperty(ze,"OPEN",{enumerable:!0,value:Nr.indexOf("OPEN")});Object.defineProperty(ze.prototype,"OPEN",{enumerable:!0,value:Nr.indexOf("OPEN")});Object.defineProperty(ze,"CLOSING",{enumerable:!0,value:Nr.indexOf("CLOSING")});Object.defineProperty(ze.prototype,"CLOSING",{enumerable:!0,value:Nr.indexOf("CLOSING")});Object.defineProperty(ze,"CLOSED",{enumerable:!0,value:Nr.indexOf("CLOSED")});Object.defineProperty(ze.prototype,"CLOSED",{enumerable:!0,value:Nr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(ze.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(ze.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[Gw])return t[A6];return null},set(t){for(let n of this.listeners(e))if(n[Gw]){this.removeListener(e,n);break}typeof t=="function"&&this.addEventListener(e,t,{[Gw]:!0})}})});ze.prototype.addEventListener=E6;ze.prototype.removeEventListener=M6;Jj.exports=ze;function Uj(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:x6,protocolVersion:Kw[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!Kw.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Kw.join(", ")})`);let s;if(t instanceof Jw)s=t;else try{s=new Jw(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",c=s.protocol==="ws+unix:",d;if(s.protocol!=="ws:"&&!i&&!c?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!s.pathname?d="The URL's pathname is empty":s.hash&&(d="The URL contains a fragment identifier"),d){let h=new SyntaxError(d);if(e._redirects===0)throw h;Rp(e,h);return}let l=i?443:80,u=S6(16).toString("base64"),p=i?v6.request:k6.request,m=new Set,f;if(o.createConnection=o.createConnection||(i?$6:B6),o.defaultPort=o.defaultPort||l,o.port=s.port||l,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(f=new Io({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=j6({[Io.extensionName]:f.offer()})),n.length){for(let h of n){if(typeof h!="string"||!D6.test(h)||m.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(h)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),c){let h=o.path.split(":");o.socketPath=h[0],o.path=h[1]}let y;if(o.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=i,e._originalHostOrSocketPath=c?o.socketPath:s.host;let h=r&&r.headers;if(r={...r,headers:{}},h)for(let[v,g]of Object.entries(h))r.headers[v.toLowerCase()]=g}else if(e.listenerCount("redirect")===0){let h=c?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!h||e._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,h||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),y=e._req=p(o),e._redirects&&e.emit("redirect",e.url,y)}else y=e._req=p(o);o.timeout&&y.on("timeout",()=>{dn(e,y,"Opening handshake has timed out")}),y.on("error",h=>{y===null||y[Nj]||(y=e._req=null,Rp(e,h))}),y.on("response",h=>{let v=h.headers.location,g=h.statusCode;if(v&&o.followRedirects&&g>=300&&g<400){if(++e._redirects>o.maxRedirects){dn(e,y,"Maximum redirects exceeded");return}y.abort();let I;try{I=new Jw(v,t)}catch{let k=new SyntaxError(`Invalid URL: ${v}`);Rp(e,k);return}Uj(e,I,n,r)}else e.emit("unexpected-response",y,h)||dn(e,y,`Unexpected server response: ${h.statusCode}`)}),y.on("upgrade",(h,v,g)=>{if(e.emit("upgrade",h),e.readyState!==ze.CONNECTING)return;y=e._req=null;let I=h.headers.upgrade;if(I===void 0||I.toLowerCase()!=="websocket"){dn(e,v,"Invalid Upgrade header");return}let R=I6("sha1").update(u+T6).digest("base64");if(h.headers["sec-websocket-accept"]!==R){dn(e,v,"Invalid Sec-WebSocket-Accept header");return}let k=h.headers["sec-websocket-protocol"],w;if(k!==void 0?m.size?m.has(k)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":m.size&&(w="Server sent no subprotocol"),w){dn(e,v,w);return}k&&(e._protocol=k);let T=h.headers["sec-websocket-extensions"];if(T!==void 0){if(!f){dn(e,v,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let C;try{C=H6(T)}catch{dn(e,v,"Invalid Sec-WebSocket-Extensions header");return}let b=Object.keys(C);if(b.length!==1||b[0]!==Io.extensionName){dn(e,v,"Server indicated an extension that was not requested");return}try{f.accept(C[Io.extensionName])}catch{dn(e,v,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[Io.extensionName]=f}e.setSocket(v,g,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(y,e):y.end()}a(Uj,"initAsClient");function Rp(e,t){e._readyState=ze.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}a(Rp,"emitErrorAndClose");function B6(e){return e.path=e.socketPath,$j.connect(e)}a(B6,"netConnect");function $6(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=$j.isIP(e.host)?"":e.host),b6.connect(e)}a($6,"tlsConnect");function dn(e,t,n){e._readyState=ze.CLOSING;let r=new Error(n);Error.captureStackTrace(r,dn),t.setHeader?(t[Nj]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Rp,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}a(dn,"abortHandshake");function Yw(e,t,n){if(t){let r=_6(t)?t.size:O6(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${e.readyState} (${Nr[e.readyState]})`);process.nextTick(n,r)}}a(Yw,"sendAfterClose");function L6(e,t){let n=this[pt];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[pt]!==void 0&&(n._socket.removeListener("data",Pp),process.nextTick(Fj,n._socket),e===1005?n.close():n.close(e,t))}a(L6,"receiverOnConclude");function N6(){let e=this[pt];e.isPaused||e._socket.resume()}a(N6,"receiverOnDrain");function U6(e){let t=this[pt];t._socket[pt]!==void 0&&(t._socket.removeListener("data",Pp),process.nextTick(Fj,t._socket),t.close(e[C6])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}a(U6,"receiverOnError");function Bj(){this[pt].emitClose()}a(Bj,"receiverOnFinish");function F6(e,t){this[pt].emit("message",e,t)}a(F6,"receiverOnMessage");function q6(e){let t=this[pt];t._autoPong&&t.pong(e,!this._isServer,Lj),t.emit("ping",e)}a(q6,"receiverOnPing");function z6(e){this[pt].emit("pong",e)}a(z6,"receiverOnPong");function Fj(e){e.resume()}a(Fj,"resume");function W6(e){let t=this[pt];t.readyState!==ze.CLOSED&&(t.readyState===ze.OPEN&&(t._readyState=ze.CLOSING,qj(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}a(W6,"senderOnError");function qj(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}a(qj,"setCloseTimer");function zj(){let e=this[pt];if(this.removeListener("close",zj),this.removeListener("data",Pp),this.removeListener("end",Wj),e._readyState=ze.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[pt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Bj),e._receiver.on("finish",Bj))}a(zj,"socketOnClose");function Pp(e){this[pt]._receiver.write(e)||this.pause()}a(Pp,"socketOnData");function Wj(){let e=this[pt];e._readyState=ze.CLOSING,e._receiver.end(),this.end()}a(Wj,"socketOnEnd");function Vj(){let e=this[pt];this.removeListener("error",Vj),this.on("error",Lj),e&&(e._readyState=ze.CLOSING,this.destroy())}a(Vj,"socketOnError")});var Xj=Te((Ime,Yj)=>{"use strict";var Sme=_p(),{Duplex:V6}=Pe("stream");function Gj(e){e.emit("close")}a(Gj,"emitClose");function J6(){!this.destroyed&&this._writableState.finished&&this.destroy()}a(J6,"duplexOnEnd");function Kj(e){this.removeListener("error",Kj),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}a(Kj,"duplexOnError");function G6(e,t){let n=!0,r=new V6({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",a(function(s,i){let c=!i&&r._readableState.objectMode?s.toString():s;r.push(c)||e.pause()},"message")),e.once("error",a(function(s){r.destroyed||(n=!1,r.destroy(s))},"error")),e.once("close",a(function(){r.destroyed||r.push(null)},"close")),r._destroy=function(o,s){if(e.readyState===e.CLOSED){s(o),process.nextTick(Gj,r);return}let i=!1;e.once("error",a(function(d){i=!0,s(d)},"error")),e.once("close",a(function(){i||s(o),process.nextTick(Gj,r)},"close")),n&&e.terminate()},r._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",a(function(){r._final(o)},"open"));return}e._socket!==null&&(e._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(e._socket.once("finish",a(function(){o()},"finish")),e.close()))},r._read=function(){e.isPaused&&e.resume()},r._write=function(o,s,i){if(e.readyState===e.CONNECTING){e.once("open",a(function(){r._write(o,s,i)},"open"));return}e.send(o,i)},r.on("end",J6),r.on("error",Kj),r}a(G6,"createWebSocketStream");Yj.exports=G6});var Xw=Te((Pme,Qj)=>{"use strict";var{tokenChars:K6}=ti();function Y6(e){let t=new Set,n=-1,r=-1,o=0;for(o;o<e.length;o++){let i=e.charCodeAt(o);if(r===-1&&K6[i]===1)n===-1&&(n=o);else if(o!==0&&(i===32||i===9))r===-1&&n!==-1&&(r=o);else if(i===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let c=e.slice(n,r);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(n,o);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}a(Y6,"parse");Qj.exports={parse:Y6}});var aH=Te((Tme,oH)=>{"use strict";var X6=Pe("events"),xp=Pe("http"),{Duplex:xme}=Pe("stream"),{createHash:Q6}=Pe("crypto"),Zj=Sp(),ua=ei(),Z6=Xw(),e5=_p(),{CLOSE_TIMEOUT:t5,GUID:n5,kWebSocket:r5}=Br(),o5=/^[+/0-9A-Za-z]{22}==$/,eH=0,tH=1,rH=2,Qw=class extends X6{static{a(this,"WebSocketServer")}constructor(t,n){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:t5,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:e5,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=xp.createServer((r,o)=>{let s=xp.STATUS_CODES[426];o.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),o.end(s)}),this._server.listen(t.port,t.host,t.backlog,n)):t.server&&(this._server=t.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=a5(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:a((o,s,i)=>{this.handleUpgrade(o,s,i,r)},"upgrade")})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=eH}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===rH){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(qc,this);return}if(t&&this.once("close",t),this._state!==tH)if(this._state=tH,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(qc,this):process.nextTick(qc,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{qc(this)})}}shouldHandle(t){if(this.options.path){let n=t.url.indexOf("?");if((n!==-1?t.url.slice(0,n):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,n,r,o){n.on("error",nH);let s=t.headers["sec-websocket-key"],i=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){pa(this,t,n,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){pa(this,t,n,400,"Invalid Upgrade header");return}if(s===void 0||!o5.test(s)){pa(this,t,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){pa(this,t,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){zc(n,400);return}let d=t.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=Z6.parse(d)}catch{pa(this,t,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=t.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let m=new ua({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=Zj.parse(u);f[ua.extensionName]&&(m.accept(f[ua.extensionName]),p[ua.extensionName]=m)}catch{pa(this,t,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,y,h,v)=>{if(!f)return zc(n,y||401,h,v);this.completeUpgrade(p,s,l,t,n,r,o)});return}if(!this.options.verifyClient(m))return zc(n,401)}this.completeUpgrade(p,s,l,t,n,r,o)}completeUpgrade(t,n,r,o,s,i,c){if(!s.readable||!s.writable)return s.destroy();if(s[r5])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>eH)return zc(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Q6("sha1").update(n+n5).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(t[ua.extensionName]){let p=t[ua.extensionName].params,m=Zj.format({[ua.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),u._extensions=t}this.emit("headers",l,o),s.write(l.concat(`\r
4
4
  `).join(`\r
5
5
  `)),s.removeListener("error",nH),u.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(qc,this)})),c(u,o)}};oH.exports=Qw;function a5(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return a(function(){for(let r of Object.keys(t))e.removeListener(r,t[r])},"removeListeners")}a(a5,"addListeners");function qc(e){e._state=rH,e.emit("close")}a(qc,"emitClose");function nH(){this.destroy()}a(nH,"socketOnError");function zc(e,t,n,r){n=n||xp.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${xp.STATUS_CODES[t]}\r
6
6
  `+Object.keys(r).map(o=>`${o}: ${r[o]}`).join(`\r
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-GCU66EAF.js";import"./chunk-CE27WEHK.js";import"./chunk-FTQLQJQV.js";export{a as MACOS_GIT_MISSING_DEVELOPER_TOOLS_ERROR,C as appWorkspacePaths,B as assertSafeBranchName,d as checkWorkspaceGitAvailability,J as checkoutBranch,K as checkoutBranchAtPath,M as clearWorkspaceDiffCacheForTests,D as cloneWorkspace,H as createAndCheckoutBranch,I as createAndCheckoutBranchAtPath,A as expectedRemoteUrl,t as isGeneratedWorkspacePath,i as isGitRepo,c as isMacOSGitDeveloperToolsMissing,u as isVisibleGitWorkspaceFile,r as isWorkspaceDirectory,E as lastFetchAt,z as listPlainWorkspaceFiles,P as loadGitCommitDiffAtPath,N as loadWorkspaceDiff,O as loadWorkspaceDiffAtPath,Q as loadWorkspaceFile,T as loadWorkspaceFileAtPath,R as loadWorkspaceImageFile,S as loadWorkspaceImageFileAtPath,F as loadWorkspaceState,G as loadWorkspaceStateAtPath,n as localVideoContentType,L as mapWorkspaceDiffEntriesWithConcurrency,s as normalizeWorkspaceFilePath,w as parseBranchStatusLine,x as parseNumstat,v as parseStatusLine,h as pathExists,p as readLocalImageFile,q as readLocalVideoFile,l as readWorkspaceDocumentPreview,k as readWorkspaceFile,o as readWorkspaceImageFile,g as redactRemoteUrl,b as runWorkspaceCommand,f as sourceFromRemote,e as startMacOSCommandLineToolsInstall,j as truncatePatch,y as uniqueSortedPaths,m as workspaceImageContentType};
2
+ import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-2OQ6LFSG.js";import"./chunk-7FX5ABXG.js";import"./chunk-FTQLQJQV.js";export{a as MACOS_GIT_MISSING_DEVELOPER_TOOLS_ERROR,C as appWorkspacePaths,B as assertSafeBranchName,d as checkWorkspaceGitAvailability,J as checkoutBranch,K as checkoutBranchAtPath,M as clearWorkspaceDiffCacheForTests,D as cloneWorkspace,H as createAndCheckoutBranch,I as createAndCheckoutBranchAtPath,A as expectedRemoteUrl,t as isGeneratedWorkspacePath,i as isGitRepo,c as isMacOSGitDeveloperToolsMissing,u as isVisibleGitWorkspaceFile,r as isWorkspaceDirectory,E as lastFetchAt,z as listPlainWorkspaceFiles,P as loadGitCommitDiffAtPath,N as loadWorkspaceDiff,O as loadWorkspaceDiffAtPath,Q as loadWorkspaceFile,T as loadWorkspaceFileAtPath,R as loadWorkspaceImageFile,S as loadWorkspaceImageFileAtPath,F as loadWorkspaceState,G as loadWorkspaceStateAtPath,n as localVideoContentType,L as mapWorkspaceDiffEntriesWithConcurrency,s as normalizeWorkspaceFilePath,w as parseBranchStatusLine,x as parseNumstat,v as parseStatusLine,h as pathExists,p as readLocalImageFile,q as readLocalVideoFile,l as readWorkspaceDocumentPreview,k as readWorkspaceFile,o as readWorkspaceImageFile,g as redactRemoteUrl,b as runWorkspaceCommand,f as sourceFromRemote,e as startMacOSCommandLineToolsInstall,j as truncatePatch,y as uniqueSortedPaths,m as workspaceImageContentType};
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
3
- import{a as m,b as l}from"./chunks/chunk-BSHAIAXY.js";import"./chunks/chunk-XWPC3AN4.js";import"./chunks/chunk-GLUWATL5.js";import{b as u}from"./chunks/chunk-UU7RXSJS.js";import{a as c,j as d}from"./chunks/chunk-JFR34MIK.js";import{f as s}from"./chunks/chunk-3M53YXEI.js";import{a as i}from"./chunks/chunk-FTQLQJQV.js";function f(e){return!e.command&&s(e.options.version)?"version":s(e.options.checkUpdate)?"check-update":!e.command&&s(e.options.help)?"help":!e.command&&s(e.options.tui)?"tui":e.command?"command":"ui"}i(f,"resolveCliTopLevelAction");async function v(e=process.argv.slice(2)){if(await C(e))return;let{command:r,options:o,rest:t}=u(e);typeof o.home=="string"&&(process.env.OPENPOND_HOME=(await import("./chunks/dist-XCT2G25K.js")).resolveOpenPondHome({home:o.home}));let n=f({command:r,options:o});if(n==="version"){console.log(c());return}if(n==="check-update"){await(await import("./chunks/core-commands-F2HIN7V4.js")).runCheckUpdate();return}if(n==="help"){(await import("./chunks/help-5MKQV36D.js")).printHelp();return}let a=m(o),p=l(o);if(a&&(process.env.OPENPOND_ACCOUNT=a),p&&(process.env.OPENPOND_BASE_URL=p),n==="tui"){await(await import("./chunks/app-layer-ZZHTHTJU.js")).runOpenPondTerminalCommand(o,t);return}if(n==="ui"){await(await import("./chunks/app-layer-ZZHTHTJU.js")).runOpenPondServerCommand("web",o,t);return}await d({command:r,options:o,rest:t})||((await import("./chunks/help-5MKQV36D.js")).printHelp(),process.exit(1))}i(v,"runOpenPondCli");async function C(e){if(e[0]==="__app-server"){process.argv=[process.execPath,"openpond-app-server",...e.slice(1)];let[{createOpenPondAppServer:r},{runOpenPondAppServerCli:o}]=await Promise.all([import("./chunks/app-server-runtime-256UCS6N.js"),import("./chunks/cli-DSFTE4KT.js")]);return await o(r),!0}if(e[0]==="__server"){process.argv=[process.execPath,"openpond-server",...e.slice(1)];let[{createOpenPondServer:r},{runOpenPondServerCli:o}]=await Promise.all([import("./chunks/src-RM2LIZGT.js"),import("./chunks/cli-DSFTE4KT.js")]),{createOpenPondAppServer:t}=await import("./chunks/app-server-runtime-256UCS6N.js");return await o({createOpenPondServer:r,createOpenPondAppServer:t}),!0}return e[0]==="__terminal"?(await(await import("./chunks/src-RINMQ7IQ.js")).runOpenPondTerminalCli(e.slice(1)),!0):!1}i(C,"runEmbeddedCompanion");v().catch(e=>{let r=e instanceof Error?e.message:String(e),o=e.issue;if(process.argv.includes("--json")&&!(e instanceof Error&&e.name==="OpenPondChildProcessExitError"))console.log(JSON.stringify({error:o??{code:"CLI_ERROR",message:r}}));else if(o&&typeof o=="object"){let n=o;console.error(`${n.code}: ${n.message}
3
+ import{a as m,b as l}from"./chunks/chunk-BSHAIAXY.js";import"./chunks/chunk-XWPC3AN4.js";import"./chunks/chunk-GLUWATL5.js";import{b as u}from"./chunks/chunk-UU7RXSJS.js";import{a as c,j as d}from"./chunks/chunk-JFR34MIK.js";import{f as s}from"./chunks/chunk-3M53YXEI.js";import{a as i}from"./chunks/chunk-FTQLQJQV.js";function f(e){return!e.command&&s(e.options.version)?"version":s(e.options.checkUpdate)?"check-update":!e.command&&s(e.options.help)?"help":!e.command&&s(e.options.tui)?"tui":e.command?"command":"ui"}i(f,"resolveCliTopLevelAction");async function v(e=process.argv.slice(2)){if(await C(e))return;let{command:r,options:o,rest:t}=u(e);typeof o.home=="string"&&(process.env.OPENPOND_HOME=(await import("./chunks/dist-XCT2G25K.js")).resolveOpenPondHome({home:o.home}));let n=f({command:r,options:o});if(n==="version"){console.log(c());return}if(n==="check-update"){await(await import("./chunks/core-commands-F2HIN7V4.js")).runCheckUpdate();return}if(n==="help"){(await import("./chunks/help-5MKQV36D.js")).printHelp();return}let a=m(o),p=l(o);if(a&&(process.env.OPENPOND_ACCOUNT=a),p&&(process.env.OPENPOND_BASE_URL=p),n==="tui"){await(await import("./chunks/app-layer-ZZHTHTJU.js")).runOpenPondTerminalCommand(o,t);return}if(n==="ui"){await(await import("./chunks/app-layer-ZZHTHTJU.js")).runOpenPondServerCommand("web",o,t);return}await d({command:r,options:o,rest:t})||((await import("./chunks/help-5MKQV36D.js")).printHelp(),process.exit(1))}i(v,"runOpenPondCli");async function C(e){if(e[0]==="__app-server"){process.argv=[process.execPath,"openpond-app-server",...e.slice(1)];let[{createOpenPondAppServer:r},{runOpenPondAppServerCli:o}]=await Promise.all([import("./chunks/app-server-runtime-C7YELTKS.js"),import("./chunks/cli-HGDLR5TC.js")]);return await o(r),!0}if(e[0]==="__server"){process.argv=[process.execPath,"openpond-server",...e.slice(1)];let[{createOpenPondServer:r},{runOpenPondServerCli:o}]=await Promise.all([import("./chunks/src-Q4W4NIPB.js"),import("./chunks/cli-HGDLR5TC.js")]),{createOpenPondAppServer:t}=await import("./chunks/app-server-runtime-C7YELTKS.js");return await o({createOpenPondServer:r,createOpenPondAppServer:t}),!0}return e[0]==="__terminal"?(await(await import("./chunks/src-RINMQ7IQ.js")).runOpenPondTerminalCli(e.slice(1)),!0):!1}i(C,"runEmbeddedCompanion");v().catch(e=>{let r=e instanceof Error?e.message:String(e),o=e.issue;if(process.argv.includes("--json")&&!(e instanceof Error&&e.name==="OpenPondChildProcessExitError"))console.log(JSON.stringify({error:o??{code:"CLI_ERROR",message:r}}));else if(o&&typeof o=="object"){let n=o;console.error(`${n.code}: ${n.message}
4
4
  ${n.path}
5
5
  ${n.action}`)}else console.error(r);let t=typeof e.exitCode=="number"?e.exitCode:1;process.exit(t)});export{v as runOpenPondCli};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openpond",
3
- "version": "0.2.31",
3
+ "version": "0.2.32",
4
4
  "openpondReleaseVersioned": true,
5
5
  "license": "MIT",
6
6
  "description": "OpenPond CLI and local harness",
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{qd as c,rd as d}from"./chunk-PZ6KPMEZ.js";import"./chunk-GCU66EAF.js";import{j as a,x as b}from"./chunk-L2UT3YIF.js";import"./chunk-CE27WEHK.js";import"./chunk-JVIHGSOV.js";import"./chunk-MVAJMRCW.js";import"./chunk-L54LZUGH.js";import"./chunk-L3KS6MOV.js";import"./chunk-XEOEKFG6.js";import"./chunk-55UCBRIX.js";import"./chunk-6MI4KKWF.js";import"./chunk-QTEYV4TW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-6FA3GG5B.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as AGENT_PROTOCOL_VERSION,c as APP_SERVER_COMPOSITION,d as createOpenPondAppServer,b as runAppServerJsonl};