oioxo-mcp 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/cli.js +279 -100
- package/package.json +56 -53
package/bundle/cli.js
CHANGED
|
@@ -1,31 +1,50 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var tre=Object.create;var y_=Object.defineProperty;var rre=Object.getOwnPropertyDescriptor;var nre=Object.getOwnPropertyNames;var sre=Object.getPrototypeOf,ire=Object.prototype.hasOwnProperty;var on=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var mr=(t,e)=>()=>(t&&(e=t(t=0)),e);var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$a=(t,e)=>{for(var r in e)y_(t,r,{get:e[r],enumerable:!0})},CB=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of nre(e))!ire.call(t,s)&&s!==r&&y_(t,s,{get:()=>e[s],enumerable:!(n=rre(e,s))||n.enumerable});return t};var vt=(t,e,r)=>(r=t!=null?tre(sre(t)):{},CB(e||!t||!t.__esModule?y_(r,"default",{value:t,enumerable:!0}):r,t)),H=t=>CB(y_({},"__esModule",{value:!0}),t);import{promises as yl}from"node:fs";import*as Am from"node:path";import*as kB from"node:os";import{randomBytes as ore}from"node:crypto";import{execFile as are}from"node:child_process";import{promisify as cre}from"node:util";async function Ma(){let t=process.env.OIOXO_TOKEN?.trim();if(t)return{token:t,expiresAt:Number.MAX_SAFE_INTEGER,device:process.env.OIOXO_DEVICE_ID||"env"};try{let e=JSON.parse(await yl.readFile(x_,"utf8"));return e?.token?e:null}catch{return null}}async function lre(t){if(process.platform!=="win32")return;let e=process.env.USERNAME||process.env.USER;if(e)try{await ure("icacls",[t,"/inheritance:r","/grant:r",`${e}:F`],{windowsHide:!0})}catch{}}async function TB(t){await yl.mkdir(Sm,{recursive:!0}),await yl.writeFile(x_,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),await lre(x_)}async function IB(){try{await yl.unlink(x_)}catch{}}async function Cm(){let t=await Ma();if(t?.device)return t.device;try{let r=await yl.readFile(Am.join(Sm,"device"),"utf8");if(r.trim())return r.trim()}catch{}let e=ore(16).toString("base64url");return await yl.mkdir(Sm,{recursive:!0}),await yl.writeFile(Am.join(Sm,"device"),e,"utf8"),e}function dre(){return`cli-${process.platform==="win32"?"windows":process.platform==="darwin"?"mac":"linux"}`}function fre(){if(process.env.OIOXO_DESKTOP_CLIENT_KEY)return process.env.OIOXO_DESKTOP_CLIENT_KEY;try{return""}catch{}return""}async function KC(){let t=await Ma(),e=await Cm(),r={"content-type":"application/json","x-oioxo-client":dre(),"x-oioxo-device":e},n=fre();return n&&(r["x-oioxo-desktop-key"]=n),t?.token&&t.expiresAt>Date.now()&&(r.authorization=`Bearer ${t.token}`),r}async function ms(t,e){try{let r=await fetch(`${gn}/api/usage/save`,{method:"POST",headers:await KC(),body:JSON.stringify(t==="report"?{action:t,savedTokens:e}:{action:t})});return r.ok?await r.json():null}catch{return null}}async function Uc(){let t=await Ma();return!!t&&t.expiresAt>Date.now()}async function PB(){if(!await Uc())return{ok:!1,message:`OIOXO: sign in to use the coding agent. ${Em}
|
|
3
|
+
Free accounts include a monthly allowance; OIOXO Pro is unlimited \u2192 ${xl}`};let t=await ms("check");return t?t.optimize?{ok:!0,state:t}:t.tier==="anon"?{ok:!1,message:`Your OIOXO session expired. ${Em}`}:{ok:!1,message:`You've used your monthly OIOXO allowance. OIOXO Pro is unlimited \u2192 ${xl}`}:{ok:!1,message:"OIOXO could not verify your plan (oioxo.com unreachable). The coding agent is paused until the connection returns."}}var ure,gn,Sm,x_,xl,Em,$o=mr(()=>{"use strict";ure=cre(are),gn=process.env.OIOXO_CONTROL_PLANE?.replace(/\/$/,"")||"https://oioxo.com",Sm=process.env.OIOXO_HOME||Am.join(kB.homedir(),".oioxo"),x_=Am.join(Sm,"credentials.json");xl="https://oioxo.com/?upgrade=pro",Em="Run `oioxo-mcp login` in a terminal to connect your OIOXO account."});import LB from"node:os";function bl(){return Qf}async function DB(){let t=UB();try{let e=await fetch(`${gn}/api/models?platform=${t}`,{headers:{"x-oioxo-client":t}});if(!e.ok)return Qf;let r=await e.json();r.selection&&(Qf=r.selection)}catch{}return Qf}function UB(){let t=process.platform;return`cli-${t==="darwin"?"mac":t==="win32"?"windows":"linux"}`}async function Gre(){try{let{getLlama:t}=await import("node-llama-cpp");return!!(await t()).gpu}catch{return!1}}async function qB(t=()=>{}){let e=UB(),r,n;try{let m=await fetch(`${gn}/api/models?platform=${e}`,{headers:{"x-oioxo-client":e}});if(!m.ok)return null;let y=await m.json();r=y.models??[],n=y.selection??{},Qf=n}catch{return null}let s=r.filter(m=>m.kind==="generic"||m.kind==="desktop").sort((m,y)=>m.approxMB-y.approxMB);if(!s.length)return null;let i=LB.totalmem()/1024**3,o=await Gre(),a=n.budgetFracOfTotalRam??.45,c=n.nativeDesktopCapMB??12e3,u=Math.min(i*1024*a,c);if(n.defaultAssetId){let m=s.find(y=>y.assetId===n.defaultAssetId);if(m&&m.approxMB<=u)return{...jB(m),reason:`admin-pinned ${m.name} fits (${zB(i)} RAM, gpu=${o})`}}let l=[...s].reverse().find(m=>m.approxMB<=u),d=s.find(m=>m.assetId===n.floorAssetId),f=l??d??s[0],p=l?`largest fitting tier (${zB(i)} RAM \xD7 ${a} \u2192 ${Math.round(u)}MB, gpu=${o})`:`device below floor \u2014 using ${f.name}`;return{...jB(f),reason:p}}function jB(t){return{assetId:t.assetId,name:t.name,manifestUrl:t.manifestUrl,approxMB:t.approxMB}}function zB(t){return`${t.toFixed(1)}GB`}function ek(){let t=LB.totalmem()/1073741824,e=[{gb:2,uri:"hf:Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF/qwen2.5-coder-0.5b-instruct-q4_k_m.gguf",label:"Qwen2.5-Coder-0.5B"},{gb:4,uri:"hf:Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf",label:"Qwen2.5-Coder-1.5B"},{gb:10,uri:"hf:Qwen/Qwen2.5-Coder-7B-Instruct-GGUF/qwen2.5-coder-7b-instruct-q4_k_m.gguf",label:"Qwen2.5-Coder-7B"}],r=t*(Qf?.budgetFracOfTotalRam??.45),n=e[0];for(let s of e)(s.gb*.45<=r||s.gb<=t*.9)&&(n=s);return t>=16?n=e[2]:t>=6?n=e[1]:n=e[0],{uri:process.env.OIOXO_LOCAL_MODEL||n.uri,label:n.label}}var Qf,S_=mr(()=>{"use strict";$o();Qf=null});function KB(){return eh}async function ZB(){if(VB&&eh)return eh;VB=!0;try{let t=await fetch(`${gn}/api/app-config`);if(!t.ok)return eh;let e=await t.json();e.coder&&(eh=e.coder)}catch{}return eh}var eh,VB,GB=mr(()=>{"use strict";$o();eh=null,VB=!1});function ane(t){let e=t.length%4?"=".repeat(4-t.length%4):"",r=atob(t.replace(/-/g,"+").replace(/_/g,"/")+e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}function WB(t){let e=t.indexOf(".");if(e<1)return null;try{return JSON.parse(one.decode(ane(t.slice(0,e))))}catch{return null}}var gCe,one,rk=mr(()=>{"use strict";gCe=new TextEncoder,one=new TextDecoder});function XB(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}async function cne(t,e){return crypto.subtle.importKey("raw",nk(t),{name:"AES-GCM"},!1,e)}async function JB(t,e){let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:nk(XB(t.iv))},await cne(e,["decrypt"]),nk(XB(t.ct)));return new Uint8Array(r)}var xCe,nk,YB=mr(()=>{"use strict";xCe=new TextEncoder,nk=t=>t});function une(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e)}function lne(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}async function dne(){let t=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),e=new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey));return{publicKeyB64:une(e),privateKey:t.privateKey}}async function fne(t){return crypto.subtle.importKey("raw",e$(lne(t)),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function hne(t,e,r){let n=new Uint8Array(await crypto.subtle.deriveBits({name:"ECDH",public:await fne(e)},t,256)),s=await crypto.subtle.importKey("raw",e$(n),"HKDF",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:QB.encode("oioxo:unlock"),info:QB.encode(r)},s,256);return new Uint8Array(i)}async function pne(t,e,r,n){let s=`${r}|${n}|${e.assetId}|${t.publicKeyB64}|${e.serverPubB64}`,i=await hne(t.privateKey,e.serverPubB64,s);return JB(e.wrapped,i)}async function t$(t,e){let r=e.fetchImpl??globalThis.fetch,n=await dne(),s=new AbortController,i=setTimeout(()=>s.abort(),e.timeoutMs??15e3),o;try{o=await r(t,{method:"POST",headers:{"content-type":"application/json",...e.extraHeaders??{}},cache:"no-store",body:JSON.stringify({entitlement:e.entitlement,device:e.device,assetId:e.assetId,clientPubB64:n.publicKeyB64}),signal:s.signal})}catch(c){throw c.name==="AbortError"?new Error("unlock timed out"):c}finally{clearTimeout(i)}if(o.status===403){let c=await o.json().catch(()=>({}));throw new Error("unlock denied: "+(c.reason??"forbidden"))}if(!o.ok)throw new Error("unlock unavailable ("+o.status+")");let a=await o.json();return pne(n,a,e.sub,e.device)}var QB,e$,r$=mr(()=>{"use strict";YB();rk();QB=new TextEncoder,e$=t=>t});import{homedir as mne}from"node:os";import n$ from"node:path";import{promises as Im,createReadStream as gne,createWriteStream as yne}from"node:fs";import{createHash as s$,createDecipheriv as xne}from"node:crypto";function bne(t,e){return/^https?:\/\//i.test(e)?e:t.slice(0,t.lastIndexOf("/")+1)+e.replace(/^\.?\//,"")}async function i$(t,e){let r=bl(),n=e??r?.fetchRetryTries??4,s=r?.fetchRetryBackoffMs??600,i;for(let o=0;o<n;o++){try{let a=await fetch(t);if(a.ok)return a;if(i=new Error(`HTTP ${a.status}`),a.status>=400&&a.status<500&&a.status!==429)break}catch(a){i=a}o<n-1&&await new Promise(a=>setTimeout(a,s*(o+1)))}throw new Error(`fetch failed after ${n} tries: ${i instanceof Error?i.message:String(i)}`)}async function _ne(t){let e=await Cm(),r=await KC(),n=await fetch(`${gn}/api/entitlement`,{method:"POST",headers:r,body:JSON.stringify({device:e})});if(!n.ok)throw new Error(`entitlement failed (${n.status}) \u2014 sign in with \`oioxo login\`.`);let{entitlement:s}=await n.json(),i=s?WB(s):null;if(!s||!i)throw new Error("could not establish a session");if(!i.sub||i.sub==="anon")throw new Error("this model is Pro-only \u2014 your account did not unlock it (free entitlement).");return t$(`${gn}/api/code-key`,{entitlement:s,sub:i.sub,device:e,assetId:t,extraHeaders:r,timeoutMs:bl()?.unlockTimeoutMs})}async function o$(t,e,r=()=>{}){let n=n$.join(mne(),".oioxo","models");await Im.mkdir(n,{recursive:!0});let s=await(await i$(e)).json();if(!s?.chunks?.length||!s.sha256)throw new Error("OIOXO manifest is malformed");let i=n$.join(n,`${t}-${s.release}.gguf`);try{if((await Im.stat(i)).size===s.totalBytes){let p=s$("sha256"),m=gne(i);for await(let y of m)p.update(y);if(p.digest("hex")===s.sha256)return r(`\xB7 OIOXO model cached: ${s.fileName}`),i}}catch{}r(`\xB7 unlocking ${t} (device-bound handshake)\u2026`);let o=Buffer.from(await _ne(t)),a=i+".part",c=yne(a),u=s$("sha256"),l=0,d=[...s.chunks].sort((f,p)=>f.index-p.index);try{for(let f of d){let p=Buffer.from(await(await i$(bne(e,f.url))).arrayBuffer()),m=Buffer.from(f.iv,"base64"),y=p.subarray(p.length-16),_=p.subarray(0,p.length-16),S=xne("aes-256-gcm",o,m);S.setAuthTag(y);let C=Buffer.concat([S.update(_),S.final()]);u.update(C),c.write(C)||await new Promise(E=>c.once("drain",()=>E())),l+=C.byteLength,r(`\xB7 decrypting OIOXO model\u2026 ${Math.round(l/s.totalBytes*100)}%`)}}finally{await new Promise((f,p)=>c.end(m=>m?p(m):f()))}if(l!==s.totalBytes)throw await Im.rm(a,{force:!0}),new Error("OIOXO assembled size mismatch");if(u.digest("hex")!==s.sha256)throw await Im.rm(a,{force:!0}),new Error("OIOXO integrity check failed");return await Im.rename(a,i),r(`\xB7 OIOXO model ready: ${s.fileName} (decrypted, private \u2014 never leaves this machine)`),i}var a$=mr(()=>{"use strict";$o();rk();r$();S_()});var u$={};$a(u$,{DeviceCoderLocal:()=>sk});import{homedir as vne}from"node:os";import c$ from"node:path";import{mkdir as wne}from"node:fs/promises";function Ane(){return KB()?.cliSystemPrompt||Sne}function Ene(t){let e=[`TASK:
|
|
3
4
|
${t.task}`,`
|
|
4
5
|
CONTEXT (OIOXO capsule):
|
|
5
6
|
${t.grounding}`];return t.error&&e.push(`
|
|
6
7
|
The previous attempt FAILED \u2014 fix with a minimal change:
|
|
7
8
|
${t.error}`),e.push(`
|
|
8
9
|
Return the changed files now.`),e.join(`
|
|
9
|
-
`)}
|
|
10
|
+
`)}function Cne(t){let e=`${t.task}
|
|
11
|
+
${t.grounding}`,r=new Set;for(let n of e.matchAll(/\b([\w./-]+\.[a-zA-Z][a-zA-Z0-9]{0,5})\b/g))r.add(n[1]);return[...r]}var Sne,sk,l$=mr(()=>{"use strict";A_();S_();GB();a$();Sne=`You are OIOXO, a precise on-device coding agent. Given a TASK and a CONTEXT capsule
|
|
10
12
|
(the minimal relevant slice of the repo), make the SMALLEST change that satisfies the task.
|
|
11
|
-
|
|
13
|
+
|
|
14
|
+
OUTPUT FORMAT \u2014 follow EXACTLY, no exceptions:
|
|
15
|
+
For each changed file, emit a FILE line then a fenced block with the ENTIRE new file content:
|
|
12
16
|
FILE: <relative/path>
|
|
13
17
|
\`\`\`
|
|
14
|
-
<the
|
|
18
|
+
<the complete file content>
|
|
15
19
|
\`\`\`
|
|
16
|
-
|
|
17
|
-
|
|
20
|
+
|
|
21
|
+
HARD RULES:
|
|
22
|
+
- Output ONLY FILE blocks. No prose, no explanation, no notes before/after.
|
|
23
|
+
- NEVER output a diff/patch (no \`diff\`, no \`@@\`, no +/- lines). Emit WHOLE files.
|
|
24
|
+
- NEVER output JSON. Use the FILE: + fenced-block format only.
|
|
25
|
+
- Preserve required keywords the task implies (e.g. \`export\` for an exported function).
|
|
26
|
+
- Emit the full file even for a one-line change.`;sk=class{onNote;label="OIOXO on-device (private, local model)";session=null;modelLabel="";constructor(e=()=>{}){this.onNote=e}async ensureSession(){if(this.session)return this.session;let e;try{e=await import("node-llama-cpp")}catch{throw new Error(`On-device mode needs node-llama-cpp. Install it once: npm i -g node-llama-cpp
|
|
27
|
+
(or run without --local to use a BYOK key). It ships prebuilt binaries \u2014 no compiler needed.`)}let{getLlama:r,LlamaChatSession:n,resolveModelFile:s}=e,i=c$.join(vne(),".oioxo","models");await wne(i,{recursive:!0}),await ZB().catch(()=>null);let o;if(process.env.OIOXO_LOCAL_MODEL){let _=process.env.OIOXO_LOCAL_MODEL;this.onNote(`\xB7 preparing the on-device model (override: ${_.split("/").pop()})\u2026`),o=await s(_,i),await DB().catch(()=>null)}else{let _=await qB(this.onNote).catch(()=>null);if(_){this.onNote(`\xB7 OIOXO selected ${_.name} for this device \u2014 ${_.reason}`);try{o=await o$(_.assetId,_.manifestUrl,this.onNote)}catch(S){let C=ek();this.onNote(`\xB7 couldn't load the OIOXO model (${S instanceof Error?S.message:"unlock failed"}) \u2014 using ${C.label}`),o=await s(C.uri,i)}}else{let S=ek();this.onNote(`\xB7 catalog unreachable \u2014 using a device-sized open coder (${S.label})\u2026`),o=await s(S.uri,i)}}let c=await(await r()).loadModel({modelPath:o}),u=bl(),l=Math.min(u?.coderContextSize??8192,c.trainContextSize),d=u?.coderMaxTokensNative??4096,f=u?.coderTemperature??.2,p=await c.createContext({contextSize:l}),m=new n({contextSequence:p.getSequence(),systemPrompt:Ane()});this.modelLabel=c$.basename(o),this.onNote(`\xB7 on-device model ready: ${this.modelLabel} (private, no tokens leave your machine)`);let y={prompt:_=>m.prompt(_,{temperature:f,maxTokens:d})};return this.session=y,y}async generate(e){let n=await(await this.ensureSession()).prompt(Ene(e));if(process.env.OIOXO_DEBUG_REPLY)try{process.stderr.write(`
|
|
28
|
+
--- OIOXO RAW REPLY ---
|
|
29
|
+
`+n+`
|
|
30
|
+
--- END RAW REPLY ---
|
|
31
|
+
`)}catch{}return ik(n,Cne(e))}}});function kne(t){let e=[`TASK:
|
|
18
32
|
${t.task}`,`
|
|
19
33
|
CONTEXT (OIOXO capsule):
|
|
20
34
|
${t.grounding}`];return t.error&&e.push(`
|
|
21
35
|
The previous attempt FAILED with this error \u2014 fix it with a minimal change:
|
|
22
36
|
${t.error}`),e.push(`
|
|
23
37
|
Return the changed files now, each as a FILE: block.`),e.join(`
|
|
24
|
-
`)}function
|
|
38
|
+
`)}function Fc(t){let e=t.trim().replace(/^['"`]|['"`]$/g,"").replace(/\\/g,"/").replace(/^\.\/+/,"");return!e||e==="."||e.startsWith("/")||/^[a-zA-Z]:\//.test(e)||e.split("/").some(r=>r==="..")?null:e}function ik(t,e=[]){let r=[],n=/FILE:\s*([^\n`]+?)\s*\n```[a-zA-Z0-9+\-.]*\n([\s\S]*?)```/g,s;for(;s=n.exec(t);){let y=Fc(s[1]);y&&r.push({path:y,content:s[2].replace(/\n$/,"")})}if(r.length)return r;let i=t.split(`
|
|
39
|
+
`),o=[],a=!1,c=[],u="",l="";for(let y=0;y<i.length;y++){let _=i[y],S=_.match(/^\s*```([a-zA-Z0-9+\-.]*)\s*$/);if(S&&!a){a=!0,c=[],u=S[1],l="";for(let C=y-1;C>=0;C--)if(i[C].trim()){l=i[C].trim();break}}else S&&a?(o.push({lang:u,pre:l,body:c.join(`
|
|
40
|
+
`)}),a=!1):a&&c.push(_)}let d=y=>/^[\w./-]+\.[a-zA-Z0-9]+$/.test(y.trim());for(let y=0;y<o.length;y++){let _=o[y];if(d(_.body)&&o[y+1]&&!d(o[y+1].body)){let S=Fc(_.body);if(S){r.push({path:S,content:o[y+1].body}),y++;continue}}if(d(_.pre)&&!d(_.body)){let S=Fc(_.pre);S&&r.push({path:S,content:_.body})}}if(r.length)return r;let f=y=>{let _,S=y.trim();try{_=JSON.parse(S)}catch{try{let E=!1,B=!1,G="";for(let se of S){if(B){G+=se,B=!1;continue}if(se==="\\"){G+=se,B=!0;continue}if(se==='"'){E=!E,G+=se;continue}if(E&&se===`
|
|
41
|
+
`){G+="\\n";continue}if(E&&se===" "){G+="\\t";continue}E&&se==="\r"||(G+=se)}_=JSON.parse(G)}catch{return!1}}if(!_||typeof _!="object"||Array.isArray(_))return!1;let C=!1;for(let[E,B]of Object.entries(_)){if(typeof B!="string"||!d(E))continue;let G=Fc(E);G&&(r.push({path:G,content:B.replace(/\n$/,"")}),C=!0)}return C};for(let y of o)if((y.lang==="json"||!y.lang)&&f(y.body))return r;if(f(t))return r;let p=o.find(y=>y.lang==="diff"||/^(diff --git|---\s|\+\+\+\s|@@ )/m.test(y.body))?.body??(/^(diff --git|\+\+\+\s|@@ )/m.test(t)?t:null);if(p){let y=p.split(/^(?=diff --git |\+\+\+ )/m);for(let _ of y){let S=_.match(/\+\+\+ [ab]?\/?([^\s\n]+)/);if(!S)continue;let C=Fc(S[1]==="dev/null"?"":S[1]);if(!C)continue;let E=_.split(`
|
|
42
|
+
`).filter(B=>B.startsWith("+")&&!B.startsWith("+++")).map(B=>B.slice(1)).join(`
|
|
43
|
+
`);E.trim()&&r.push({path:C,content:E})}if(r.length)return r}let m=o.filter(y=>!d(y.body)&&y.body.trim());if(m.length===1&&e.length===1){let y=Fc(e[0]);y&&r.push({path:y,content:m[0].body})}return r}function Pm(t={}){if(t.local||process.env.OIOXO_LOCAL==="1")return{coder:new ok(t.onNote)};let e=t.config??{},r=process.env.OIOXO_PROVIDER||e.provider,n=process.env.OIOXO_MODEL||e.model,s=process.env.OIOXO_API_KEY||e.apiKey,i=process.env.OIOXO_BASE_URL||e.baseUrl;return r&&n?{coder:new th({provider:r,model:n,key:s,baseUrl:i})}:process.env.OPENAI_API_KEY?{coder:new th({provider:"openai",model:process.env.OIOXO_MODEL||"gpt-4.1",key:process.env.OPENAI_API_KEY})}:process.env.ANTHROPIC_API_KEY?{coder:new th({provider:"anthropic",model:process.env.OIOXO_MODEL||"claude-sonnet-4-6",key:process.env.ANTHROPIC_API_KEY})}:process.env.GROQ_API_KEY?{coder:new th({provider:"groq",model:process.env.OIOXO_MODEL||"llama-3.3-70b-versatile",key:process.env.GROQ_API_KEY})}:{error:`No coder configured. Either:
|
|
25
44
|
\u2022 set a key: OPENAI_API_KEY / ANTHROPIC_API_KEY / GROQ_API_KEY (optionally OIOXO_MODEL)
|
|
26
45
|
\u2022 or any OpenAI-compatible base: OIOXO_PROVIDER=custom OIOXO_BASE_URL=\u2026 OIOXO_MODEL=\u2026 OIOXO_API_KEY=\u2026
|
|
27
46
|
\u2022 or local Ollama: OIOXO_PROVIDER=ollama OIOXO_MODEL=qwen2.5-coder (no key)
|
|
28
|
-
On-device OIOXO (\`--local\`) is coming next.`}}var
|
|
47
|
+
On-device OIOXO (\`--local\`) is coming next.`}}var d$,f$,th,ok,A_=mr(()=>{"use strict";d$=`You are OIOXO, a precise coding agent. You are given a TASK and a CONTEXT capsule
|
|
29
48
|
(the minimal relevant slice of the user's repository \u2014 full excerpts for the key files,
|
|
30
49
|
signatures only for their neighbors). Make the SMALLEST change that satisfies the task.
|
|
31
50
|
|
|
@@ -38,15 +57,144 @@ FILE: <relative/path>
|
|
|
38
57
|
Rules:
|
|
39
58
|
- Emit the COMPLETE file content, never a diff or "// unchanged" placeholder.
|
|
40
59
|
- Touch as few files as possible. Do not invent files you weren't shown unless the task needs a new one.
|
|
41
|
-
- No prose outside the FILE blocks.`;ap={openai:"https://api.openai.com/v1",groq:"https://api.groq.com/openai/v1",mistral:"https://api.mistral.ai/v1",together:"https://api.together.xyz/v1",ollama:"http://localhost:11434/v1",anthropic:"https://api.anthropic.com",custom:""},Fr=class{cfg;label;constructor(e){this.cfg=e,this.label=`your ${e.provider} key (${e.model})`}async generate(e){let r=Zv(e),n=this.cfg.provider==="anthropic"?await this.callAnthropic(r):await this.callOpenAICompatible(r);return Ji(n)}async callOpenAICompatible(e){let r=(this.cfg.baseUrl||ap[this.cfg.provider]).replace(/\/$/,"");if(!r)throw new Error("a baseUrl is required for the custom provider");let n={"content-type":"application/json"};this.cfg.key&&(n.authorization=`Bearer ${this.cfg.key}`);let o=await fetch(`${r}/chat/completions`,{method:"POST",headers:n,body:JSON.stringify({model:this.cfg.model,temperature:.2,messages:[{role:"system",content:ip},{role:"user",content:e}]})});if(!o.ok)throw new Error(`${this.cfg.provider} ${o.status}: ${(await o.text()).slice(0,300)}`);return(await o.json()).choices?.[0]?.message?.content??""}async callAnthropic(e){let r=(this.cfg.baseUrl||ap.anthropic).replace(/\/$/,""),n=await fetch(`${r}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-api-key":this.cfg.key??"","anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.cfg.model,max_tokens:8192,temperature:.2,system:ip,messages:[{role:"user",content:e}]})});if(!n.ok)throw new Error(`anthropic ${n.status}: ${(await n.text()).slice(0,300)}`);return((await n.json()).content??[]).map(s=>s.text??"").join("")}},Wi=class{onNote;label="OIOXO on-device (private)";impl=null;constructor(e=()=>{}){this.onNote=e}async generate(e){if(!this.impl){let{DeviceCoderLocal:r}=await Promise.resolve().then(()=>(sp(),op));this.impl=new r(this.onNote)}return this.impl.generate(e)}}});var fo=S(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.regexpCode=Y.getEsmExportName=Y.getProperty=Y.safeStringify=Y.stringify=Y.strConcat=Y.addCodeArg=Y.str=Y._=Y.nil=Y._Code=Y.Name=Y.IDENTIFIER=Y._CodeOrName=void 0;var lo=class{};Y._CodeOrName=lo;Y.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ir=class extends lo{constructor(e){if(super(),!Y.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Y.Name=Ir;var tt=class extends lo{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Ir&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Y._Code=tt;Y.nil=new tt("");function yh(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Lu(r,e[n]),r.push(t[++n]);return new tt(r)}Y._=yh;var Du=new tt("+");function _h(t,...e){let r=[po(t[0])],n=0;for(;n<e.length;)r.push(Du),Lu(r,e[n]),r.push(Du,po(t[++n]));return q0(r),new tt(r)}Y.str=_h;function Lu(t,e){e instanceof tt?t.push(...e._items):e instanceof Ir?t.push(e):t.push(V0(e))}Y.addCodeArg=Lu;function q0(t){let e=1;for(;e<t.length-1;){if(t[e]===Du){let r=U0(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function U0(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ir||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ir))return`"${t}${e.slice(1)}`}function F0(t,e){return e.emptyStr()?t:t.emptyStr()?e:_h`${t}${e}`}Y.strConcat=F0;function V0(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:po(Array.isArray(t)?t.join(","):t)}function H0(t){return new tt(po(t))}Y.stringify=H0;function po(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Y.safeStringify=po;function K0(t){return typeof t=="string"&&Y.IDENTIFIER.test(t)?new tt(`.${t}`):yh`[${t}]`}Y.getProperty=K0;function B0(t){if(typeof t=="string"&&Y.IDENTIFIER.test(t))return new tt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Y.getEsmExportName=B0;function X0(t){return new tt(t.toString())}Y.regexpCode=X0});var Fu=S(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.ValueScope=Ue.ValueScopeName=Ue.Scope=Ue.varKinds=Ue.UsedValueState=void 0;var qe=fo(),qu=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Gs;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Gs||(Ue.UsedValueState=Gs={}));Ue.varKinds={const:new qe.Name("const"),let:new qe.Name("let"),var:new qe.Name("var")};var Ws=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof qe.Name?e:this.name(e)}name(e){return new qe.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ue.Scope=Ws;var Ys=class extends qe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,qe._)`.${new qe.Name(r)}[${n}]`}};Ue.ValueScopeName=Ys;var J0=(0,qe._)`\n`,Uu=class extends Ws{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?J0:qe.nil}}get(){return this._scope}name(e){return new Ys(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,qe._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=qe.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Gs.Started);let l=r(u);if(l){let d=this.opts.es5?Ue.varKinds.var:Ue.varKinds.const;s=(0,qe._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,qe._)`${s}${l}${this.opts._n}`;else throw new qu(u);c.set(u,Gs.Completed)})}return s}};Ue.ValueScope=Uu});var U=S(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.or=F.and=F.not=F.CodeGen=F.operators=F.varKinds=F.ValueScopeName=F.ValueScope=F.Scope=F.Name=F.regexpCode=F.stringify=F.getProperty=F.nil=F.strConcat=F.str=F._=void 0;var J=fo(),ut=Fu(),Bt=fo();Object.defineProperty(F,"_",{enumerable:!0,get:function(){return Bt._}});Object.defineProperty(F,"str",{enumerable:!0,get:function(){return Bt.str}});Object.defineProperty(F,"strConcat",{enumerable:!0,get:function(){return Bt.strConcat}});Object.defineProperty(F,"nil",{enumerable:!0,get:function(){return Bt.nil}});Object.defineProperty(F,"getProperty",{enumerable:!0,get:function(){return Bt.getProperty}});Object.defineProperty(F,"stringify",{enumerable:!0,get:function(){return Bt.stringify}});Object.defineProperty(F,"regexpCode",{enumerable:!0,get:function(){return Bt.regexpCode}});Object.defineProperty(F,"Name",{enumerable:!0,get:function(){return Bt.Name}});var ri=Fu();Object.defineProperty(F,"Scope",{enumerable:!0,get:function(){return ri.Scope}});Object.defineProperty(F,"ValueScope",{enumerable:!0,get:function(){return ri.ValueScope}});Object.defineProperty(F,"ValueScopeName",{enumerable:!0,get:function(){return ri.ValueScopeName}});Object.defineProperty(F,"varKinds",{enumerable:!0,get:function(){return ri.varKinds}});F.operators={GT:new J._Code(">"),GTE:new J._Code(">="),LT:new J._Code("<"),LTE:new J._Code("<="),EQ:new J._Code("==="),NEQ:new J._Code("!=="),NOT:new J._Code("!"),OR:new J._Code("||"),AND:new J._Code("&&"),ADD:new J._Code("+")};var Et=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Vu=class extends Et{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ut.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=un(this.rhs,e,r)),this}get names(){return this.rhs instanceof J._CodeOrName?this.rhs.names:{}}},Qs=class extends Et{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof J.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=un(this.rhs,e,r),this}get names(){let e=this.lhs instanceof J.Name?{}:{...this.lhs.names};return ti(e,this.rhs)}},Hu=class extends Qs{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ku=class extends Et{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Bu=class extends Et{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Xu=class extends Et{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ju=class extends Et{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=un(this.code,e,r),this}get names(){return this.code instanceof J._CodeOrName?this.code.names:{}}},mo=class extends Et{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(G0(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Nr(e,r.names),{})}},It=class extends mo{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Gu=class extends mo{},cn=class extends It{};cn.kind="else";var Rr=class t extends It{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new cn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(vh(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=un(this.condition,e,r),this}get names(){let e=super.names;return ti(e,this.condition),this.else&&Nr(e,this.else.names),e}};Rr.kind="if";var jr=class extends It{};jr.kind="for";var Wu=class extends jr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=un(this.iteration,e,r),this}get names(){return Nr(super.names,this.iteration.names)}},Yu=class extends jr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?ut.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ti(super.names,this.from);return ti(e,this.to)}},ei=class extends jr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=un(this.iterable,e,r),this}get names(){return Nr(super.names,this.iterable.names)}},ho=class extends It{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ho.kind="func";var go=class extends mo{render(e){return"return "+super.render(e)}};go.kind="return";var Qu=class extends It{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Nr(e,this.catch.names),this.finally&&Nr(e,this.finally.names),e}},yo=class extends It{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};yo.kind="catch";var _o=class extends It{render(e){return"finally"+super.render(e)}};_o.kind="finally";var el=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
42
|
-
`:""},this._extScope=e,this._scope=new ut.Scope({parent:e}),this._nodes=[new Gu]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Vu(e,s,n)),s}const(e,r,n){return this._def(ut.varKinds.const,e,r,n)}let(e,r,n){return this._def(ut.varKinds.let,e,r,n)}var(e,r,n){return this._def(ut.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Qs(e,r,n))}add(e,r){return this._leafNode(new Hu(e,F.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==J.nil&&this._leafNode(new Ju(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,J.addCodeArg)(r,o));return r.push("}"),new J._Code(r)}if(e,r,n){if(this._blockNode(new Rr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Rr(e))}else(){return this._elseNode(new cn)}endIf(){return this._endBlockNode(Rr,cn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Wu(e),r)}forRange(e,r,n,o,s=this.opts.es5?ut.varKinds.var:ut.varKinds.let){let i=this._scope.toName(e);return this._for(new Yu(s,i,r,n),()=>o(i))}forOf(e,r,n,o=ut.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof J.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,J._)`${i}.length`,a=>{this.var(s,(0,J._)`${i}[${a}]`),n(s)})}return this._for(new ei("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?ut.varKinds.var:ut.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,J._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new ei("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(jr)}label(e){return this._leafNode(new Ku(e))}break(e){return this._leafNode(new Bu(e))}return(e){let r=new go;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(go)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Qu;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new yo(s),r(s)}return n&&(this._currNode=o.finally=new _o,this.code(n)),this._endBlockNode(yo,_o)}throw(e){return this._leafNode(new Xu(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=J.nil,n,o){return this._blockNode(new ho(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ho)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Rr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};F.CodeGen=el;function Nr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ti(t,e){return e instanceof J._CodeOrName?Nr(t,e.names):t}function un(t,e,r){if(t instanceof J.Name)return n(t);if(!o(t))return t;return new J._Code(t._items.reduce((s,i)=>(i instanceof J.Name&&(i=n(i)),i instanceof J._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof J._Code&&s._items.some(i=>i instanceof J.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function G0(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function vh(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,J._)`!${tl(t)}`}F.not=vh;var W0=xh(F.operators.AND);function Y0(...t){return t.reduce(W0)}F.and=Y0;var Q0=xh(F.operators.OR);function ek(...t){return t.reduce(Q0)}F.or=ek;function xh(t){return(e,r)=>e===J.nil?r:r===J.nil?e:(0,J._)`${tl(e)} ${t} ${tl(r)}`}function tl(t){return t instanceof J.Name?t:(0,J._)`(${t})`}});var G=S(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.checkStrictMode=V.getErrorPath=V.Type=V.useFunc=V.setEvaluated=V.evaluatedPropsToName=V.mergeEvaluated=V.eachItem=V.unescapeJsonPointer=V.escapeJsonPointer=V.escapeFragment=V.unescapeFragment=V.schemaRefOrVal=V.schemaHasRulesButRef=V.schemaHasRules=V.checkUnknownRules=V.alwaysValidSchema=V.toHash=void 0;var re=U(),tk=fo();function rk(t){let e={};for(let r of t)e[r]=!0;return e}V.toHash=rk;function nk(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:($h(t,e),!kh(e,t.self.RULES.all))}V.alwaysValidSchema=nk;function $h(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Th(t,`unknown keyword: "${s}"`)}V.checkUnknownRules=$h;function kh(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}V.schemaHasRules=kh;function ok(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}V.schemaHasRulesButRef=ok;function sk({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,re._)`${r}`}return(0,re._)`${t}${e}${(0,re.getProperty)(n)}`}V.schemaRefOrVal=sk;function ik(t){return Sh(decodeURIComponent(t))}V.unescapeFragment=ik;function ak(t){return encodeURIComponent(nl(t))}V.escapeFragment=ak;function nl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}V.escapeJsonPointer=nl;function Sh(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}V.unescapeJsonPointer=Sh;function ck(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}V.eachItem=ck;function wh({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof re.Name?(s instanceof re.Name?t(o,s,i):e(o,s,i),i):s instanceof re.Name?(e(o,i,s),s):r(s,i);return a===re.Name&&!(c instanceof re.Name)?n(o,c):c}}V.mergeEvaluated={props:wh({mergeNames:(t,e,r)=>t.if((0,re._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,re._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,re._)`${r} || {}`).code((0,re._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,re._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,re._)`${r} || {}`),ol(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:zh}),items:wh({mergeNames:(t,e,r)=>t.if((0,re._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,re._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,re._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,re._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function zh(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,re._)`{}`);return e!==void 0&&ol(t,r,e),r}V.evaluatedPropsToName=zh;function ol(t,e,r){Object.keys(r).forEach(n=>t.assign((0,re._)`${e}${(0,re.getProperty)(n)}`,!0))}V.setEvaluated=ol;var bh={};function uk(t,e){return t.scopeValue("func",{ref:e,code:bh[e.code]||(bh[e.code]=new tk._Code(e.code))})}V.useFunc=uk;var rl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(rl||(V.Type=rl={}));function lk(t,e,r){if(t instanceof re.Name){let n=e===rl.Num;return r?n?(0,re._)`"[" + ${t} + "]"`:(0,re._)`"['" + ${t} + "']"`:n?(0,re._)`"/" + ${t}`:(0,re._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,re.getProperty)(t).toString():"/"+nl(t)}V.getErrorPath=lk;function Th(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}V.checkStrictMode=Th});var Rt=S(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});var Pe=U(),dk={data:new Pe.Name("data"),valCxt:new Pe.Name("valCxt"),instancePath:new Pe.Name("instancePath"),parentData:new Pe.Name("parentData"),parentDataProperty:new Pe.Name("parentDataProperty"),rootData:new Pe.Name("rootData"),dynamicAnchors:new Pe.Name("dynamicAnchors"),vErrors:new Pe.Name("vErrors"),errors:new Pe.Name("errors"),this:new Pe.Name("this"),self:new Pe.Name("self"),scope:new Pe.Name("scope"),json:new Pe.Name("json"),jsonPos:new Pe.Name("jsonPos"),jsonLen:new Pe.Name("jsonLen"),jsonPart:new Pe.Name("jsonPart")};sl.default=dk});var vo=S(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.extendErrors=Oe.resetErrorsCount=Oe.reportExtraError=Oe.reportError=Oe.keyword$DataError=Oe.keywordError=void 0;var W=U(),ni=G(),Ne=Rt();Oe.keywordError={message:({keyword:t})=>(0,W.str)`must pass "${t}" keyword validation`};Oe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,W.str)`"${t}" keyword must be ${e} ($data)`:(0,W.str)`"${t}" keyword is invalid ($data)`};function pk(t,e=Oe.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Eh(t,e,r);n??(i||a)?Ph(s,c):Oh(o,(0,W._)`[${c}]`)}Oe.reportError=pk;function fk(t,e=Oe.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Eh(t,e,r);Ph(o,a),s||i||Oh(n,Ne.default.vErrors)}Oe.reportExtraError=fk;function mk(t,e){t.assign(Ne.default.errors,e),t.if((0,W._)`${Ne.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,W._)`${Ne.default.vErrors}.length`,e),()=>t.assign(Ne.default.vErrors,null)))}Oe.resetErrorsCount=mk;function hk({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Ne.default.errors,a=>{t.const(i,(0,W._)`${Ne.default.vErrors}[${a}]`),t.if((0,W._)`${i}.instancePath === undefined`,()=>t.assign((0,W._)`${i}.instancePath`,(0,W.strConcat)(Ne.default.instancePath,s.errorPath))),t.assign((0,W._)`${i}.schemaPath`,(0,W.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,W._)`${i}.schema`,r),t.assign((0,W._)`${i}.data`,n))})}Oe.extendErrors=hk;function Ph(t,e){let r=t.const("err",e);t.if((0,W._)`${Ne.default.vErrors} === null`,()=>t.assign(Ne.default.vErrors,(0,W._)`[${r}]`),(0,W._)`${Ne.default.vErrors}.push(${r})`),t.code((0,W._)`${Ne.default.errors}++`)}function Oh(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,W._)`new ${t.ValidationError}(${e})`):(r.assign((0,W._)`${n}.errors`,e),r.return(!1))}var Cr={keyword:new W.Name("keyword"),schemaPath:new W.Name("schemaPath"),params:new W.Name("params"),propertyName:new W.Name("propertyName"),message:new W.Name("message"),schema:new W.Name("schema"),parentSchema:new W.Name("parentSchema")};function Eh(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,W._)`{}`:gk(t,e,r)}function gk(t,e,r={}){let{gen:n,it:o}=t,s=[yk(o,r),_k(t,r)];return vk(t,e,s),n.object(...s)}function yk({errorPath:t},{instancePath:e}){let r=e?(0,W.str)`${t}${(0,ni.getErrorPath)(e,ni.Type.Str)}`:t;return[Ne.default.instancePath,(0,W.strConcat)(Ne.default.instancePath,r)]}function _k({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,W.str)`${e}/${t}`;return r&&(o=(0,W.str)`${o}${(0,ni.getErrorPath)(r,ni.Type.Str)}`),[Cr.schemaPath,o]}function vk(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Cr.keyword,o],[Cr.params,typeof e=="function"?e(t):e||(0,W._)`{}`]),c.messages&&n.push([Cr.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Cr.schema,i],[Cr.parentSchema,(0,W._)`${l}${d}`],[Ne.default.data,s]),u&&n.push([Cr.propertyName,u])}});var Rh=S(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.boolOrEmptySchema=ln.topBoolOrEmptySchema=void 0;var xk=vo(),wk=U(),bk=Rt(),$k={message:"boolean schema is false"};function kk(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ih(t,!1):typeof r=="object"&&r.$async===!0?e.return(bk.default.data):(e.assign((0,wk._)`${n}.errors`,null),e.return(!0))}ln.topBoolOrEmptySchema=kk;function Sk(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ih(t)):r.var(e,!0)}ln.boolOrEmptySchema=Sk;function Ih(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,xk.reportError)(o,$k,void 0,e)}});var il=S(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.getRules=dn.isJSONType=void 0;var zk=["string","number","integer","boolean","null","object","array"],Tk=new Set(zk);function Pk(t){return typeof t=="string"&&Tk.has(t)}dn.isJSONType=Pk;function Ok(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}dn.getRules=Ok});var al=S(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.shouldUseRule=Xt.shouldUseGroup=Xt.schemaHasRulesForType=void 0;function Ek({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&jh(t,n)}Xt.schemaHasRulesForType=Ek;function jh(t,e){return e.rules.some(r=>Nh(t,r))}Xt.shouldUseGroup=jh;function Nh(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Xt.shouldUseRule=Nh});var xo=S(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.reportTypeError=Ee.checkDataTypes=Ee.checkDataType=Ee.coerceAndCheckDataType=Ee.getJSONTypes=Ee.getSchemaTypes=Ee.DataType=void 0;var Ik=il(),Rk=al(),jk=vo(),L=U(),Ch=G(),pn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(pn||(Ee.DataType=pn={}));function Nk(t){let e=Zh(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ee.getSchemaTypes=Nk;function Zh(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Ik.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ee.getJSONTypes=Zh;function Ck(t,e){let{gen:r,data:n,opts:o}=t,s=Zk(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Rk.schemaHasRulesForType)(t,e[0]));if(i){let a=ul(e,n,o.strictNumbers,pn.Wrong);r.if(a,()=>{s.length?Ak(t,e,s):ll(t)})}return i}Ee.coerceAndCheckDataType=Ck;var Ah=new Set(["string","number","integer","boolean","null"]);function Zk(t,e){return e?t.filter(r=>Ah.has(r)||e==="array"&&r==="array"):[]}function Ak(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,L._)`typeof ${o}`),a=n.let("coerced",(0,L._)`undefined`);s.coerceTypes==="array"&&n.if((0,L._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,L._)`${o}[0]`).assign(i,(0,L._)`typeof ${o}`).if(ul(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,L._)`${a} !== undefined`);for(let u of r)(Ah.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),ll(t),n.endIf(),n.if((0,L._)`${a} !== undefined`,()=>{n.assign(o,a),Mk(t,a)});function c(u){switch(u){case"string":n.elseIf((0,L._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,L._)`"" + ${o}`).elseIf((0,L._)`${o} === null`).assign(a,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${i} == "boolean" || ${o} === null
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,L._)`[${o}]`)}}}function Mk({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,L._)`${e} !== undefined`,()=>t.assign((0,L._)`${e}[${r}]`,n))}function cl(t,e,r,n=pn.Correct){let o=n===pn.Correct?L.operators.EQ:L.operators.NEQ,s;switch(t){case"null":return(0,L._)`${e} ${o} null`;case"array":s=(0,L._)`Array.isArray(${e})`;break;case"object":s=(0,L._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,L._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,L._)`typeof ${e} ${o} ${t}`}return n===pn.Correct?s:(0,L.not)(s);function i(a=L.nil){return(0,L.and)((0,L._)`typeof ${e} == "number"`,a,r?(0,L._)`isFinite(${e})`:L.nil)}}Ee.checkDataType=cl;function ul(t,e,r,n){if(t.length===1)return cl(t[0],e,r,n);let o,s=(0,Ch.toHash)(t);if(s.array&&s.object){let i=(0,L._)`typeof ${e} != "object"`;o=s.null?i:(0,L._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=L.nil;s.number&&delete s.integer;for(let i in s)o=(0,L.and)(o,cl(i,e,r,n));return o}Ee.checkDataTypes=ul;var Dk={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,L._)`{type: ${t}}`:(0,L._)`{type: ${e}}`};function ll(t){let e=Lk(t);(0,jk.reportError)(e,Dk)}Ee.reportTypeError=ll;function Lk(t){let{gen:e,data:r,schema:n}=t,o=(0,Ch.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Dh=S(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.assignDefaults=void 0;var fn=U(),qk=G();function Uk(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Mh(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Mh(t,s,o.default))}oi.assignDefaults=Uk;function Mh(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,fn._)`${s}${(0,fn.getProperty)(e)}`;if(o){(0,qk.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,fn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,fn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,fn._)`${a} = ${(0,fn.stringify)(r)}`)}});var rt=S(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.validateUnion=te.validateArray=te.usePattern=te.callValidateCode=te.schemaProperties=te.allSchemaProperties=te.noPropertyInData=te.propertyInData=te.isOwnProperty=te.hasPropFunc=te.reportMissingProp=te.checkMissingProp=te.checkReportMissingProp=void 0;var ae=U(),dl=G(),Jt=Rt(),Fk=G();function Vk(t,e){let{gen:r,data:n,it:o}=t;r.if(fl(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ae._)`${e}`},!0),t.error()})}te.checkReportMissingProp=Vk;function Hk({gen:t,data:e,it:{opts:r}},n,o){return(0,ae.or)(...n.map(s=>(0,ae.and)(fl(t,e,s,r.ownProperties),(0,ae._)`${o} = ${s}`)))}te.checkMissingProp=Hk;function Kk(t,e){t.setParams({missingProperty:e},!0),t.error()}te.reportMissingProp=Kk;function Lh(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ae._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=Lh;function pl(t,e,r){return(0,ae._)`${Lh(t)}.call(${e}, ${r})`}te.isOwnProperty=pl;function Bk(t,e,r,n){let o=(0,ae._)`${e}${(0,ae.getProperty)(r)} !== undefined`;return n?(0,ae._)`${o} && ${pl(t,e,r)}`:o}te.propertyInData=Bk;function fl(t,e,r,n){let o=(0,ae._)`${e}${(0,ae.getProperty)(r)} === undefined`;return n?(0,ae.or)(o,(0,ae.not)(pl(t,e,r))):o}te.noPropertyInData=fl;function qh(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}te.allSchemaProperties=qh;function Xk(t,e){return qh(e).filter(r=>!(0,dl.alwaysValidSchema)(t,e[r]))}te.schemaProperties=Xk;function Jk({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ae._)`${t}, ${e}, ${n}${o}`:e,d=[[Jt.default.instancePath,(0,ae.strConcat)(Jt.default.instancePath,s)],[Jt.default.parentData,i.parentData],[Jt.default.parentDataProperty,i.parentDataProperty],[Jt.default.rootData,Jt.default.rootData]];i.opts.dynamicRef&&d.push([Jt.default.dynamicAnchors,Jt.default.dynamicAnchors]);let f=(0,ae._)`${l}, ${r.object(...d)}`;return c!==ae.nil?(0,ae._)`${a}.call(${c}, ${f})`:(0,ae._)`${a}(${f})`}te.callValidateCode=Jk;var Gk=(0,ae._)`new RegExp`;function Wk({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ae._)`${o.code==="new RegExp"?Gk:(0,Fk.useFunc)(t,o)}(${r}, ${n})`})}te.usePattern=Wk;function Yk(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ae._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:dl.Type.Num},s),e.if((0,ae.not)(s),a)})}}te.validateArray=Yk;function Qk(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,dl.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ae._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ae.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}te.validateUnion=Qk});var Vh=S(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.validateKeywordUsage=_t.validSchemaType=_t.funcKeywordCode=_t.macroKeywordCode=void 0;var Ce=U(),Zr=Rt(),eS=rt(),tS=vo();function rS(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Fh(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ce.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}_t.macroKeywordCode=rS;function nS(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;sS(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Fh(n,o,u),d=n.let("valid");t.block$data(d,f),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function f(){if(e.errors===!1)h(),e.modifying&&Uh(t),g(()=>t.error());else{let w=e.async?m():p();e.modifying&&Uh(t),g(()=>oS(t,w))}}function m(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,Ce._)`await `),v=>n.assign(d,!1).if((0,Ce._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Ce._)`${v}.errors`),()=>n.throw(v))),w}function p(){let w=(0,Ce._)`${l}.errors`;return n.assign(w,null),h(Ce.nil),w}function h(w=e.async?(0,Ce._)`await `:Ce.nil){let v=c.opts.passContext?Zr.default.this:Zr.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ce._)`${w}${(0,eS.callValidateCode)(t,l,v,x)}`,e.modifying)}function g(w){var v;n.if((0,Ce.not)((v=e.valid)!==null&&v!==void 0?v:d),w)}}_t.funcKeywordCode=nS;function Uh(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ce._)`${n.parentData}[${n.parentDataProperty}]`))}function oS(t,e){let{gen:r}=t;r.if((0,Ce._)`Array.isArray(${e})`,()=>{r.assign(Zr.default.vErrors,(0,Ce._)`${Zr.default.vErrors} === null ? ${e} : ${Zr.default.vErrors}.concat(${e})`).assign(Zr.default.errors,(0,Ce._)`${Zr.default.vErrors}.length`),(0,tS.extendErrors)(t)},()=>t.error())}function sS({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Fh(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ce.stringify)(r)})}function iS(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}_t.validSchemaType=iS;function aS({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}_t.validateKeywordUsage=aS});var Kh=S(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.extendSubschemaMode=Gt.extendSubschemaData=Gt.getSubschema=void 0;var vt=U(),Hh=G();function cS(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,vt._)`${t.schemaPath}${(0,vt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,vt._)`${t.schemaPath}${(0,vt.getProperty)(e)}${(0,vt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Hh.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Gt.getSubschema=cS;function uS(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,vt._)`${e.data}${(0,vt.getProperty)(r)}`,!0);c(f),t.errorPath=(0,vt.str)`${u}${(0,Hh.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,vt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof vt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Gt.extendSubschemaData=uS;function lS(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Gt.extendSubschemaMode=lS});var ml=S((gC,Bh)=>{"use strict";Bh.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Jh=S((yC,Xh)=>{"use strict";var Wt=Xh.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};si(e,n,o,t,"",t)};Wt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Wt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Wt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Wt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function si(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Wt.arrayKeywords)for(var f=0;f<d.length;f++)si(t,e,r,d[f],o+"/"+l+"/"+f,s,o,l,n,f)}else if(l in Wt.propsKeywords){if(d&&typeof d=="object")for(var m in d)si(t,e,r,d[m],o+"/"+l+"/"+dS(m),s,o,l,n,m)}else(l in Wt.keywords||t.allKeys&&!(l in Wt.skipKeywords))&&si(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function dS(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var wo=S(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.getSchemaRefs=Fe.resolveUrl=Fe.normalizeId=Fe._getFullPath=Fe.getFullPath=Fe.inlineRef=void 0;var pS=G(),fS=ml(),mS=Jh(),hS=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function gS(t,e=!0){return typeof t=="boolean"?!0:e===!0?!hl(t):e?Gh(t)<=e:!1}Fe.inlineRef=gS;var yS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hl(t){for(let e in t){if(yS.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(hl)||typeof r=="object"&&hl(r))return!0}return!1}function Gh(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!hS.has(r)&&(typeof t[r]=="object"&&(0,pS.eachItem)(t[r],n=>e+=Gh(n)),e===1/0))return 1/0}return e}function Wh(t,e="",r){r!==!1&&(e=mn(e));let n=t.parse(e);return Yh(t,n)}Fe.getFullPath=Wh;function Yh(t,e){return t.serialize(e).split("#")[0]+"#"}Fe._getFullPath=Yh;var _S=/#\/?$/;function mn(t){return t?t.replace(_S,""):""}Fe.normalizeId=mn;function vS(t,e,r){return r=mn(r),t.resolve(e,r)}Fe.resolveUrl=vS;var xS=/^[a-z_][-a-z0-9._]*$/i;function wS(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=mn(t[r]||e),s={"":o},i=Wh(n,o,!1),a={},c=new Set;return mS(t,{allKeys:!0},(d,f,m,p)=>{if(p===void 0)return;let h=i+f,g=s[p];typeof d[r]=="string"&&(g=w.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[f]=g;function w(x){let T=this.opts.uriResolver.resolve;if(x=mn(g?T(g,x):x),c.has(x))throw l(x);c.add(x);let N=this.refs[x];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(d,N.schema,x):x!==mn(h)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=h),x}function v(x){if(typeof x=="string"){if(!xS.test(x))throw new Error(`invalid anchor "${x}"`);w.call(this,`#${x}`)}}}),a;function u(d,f,m){if(f!==void 0&&!fS(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Fe.getSchemaRefs=wS});var ko=S(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.getData=Yt.KeywordCxt=Yt.validateFunctionCode=void 0;var ng=Rh(),Qh=xo(),yl=al(),ii=xo(),bS=Dh(),$o=Vh(),gl=Kh(),R=U(),M=Rt(),$S=wo(),jt=G(),bo=vo();function kS(t){if(ig(t)&&(ag(t),sg(t))){TS(t);return}og(t,()=>(0,ng.topBoolOrEmptySchema)(t))}Yt.validateFunctionCode=kS;function og({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,R._)`${M.default.data}, ${M.default.valCxt}`,n.$async,()=>{t.code((0,R._)`"use strict"; ${eg(r,o)}`),zS(t,o),t.code(s)}):t.func(e,(0,R._)`${M.default.data}, ${SS(o)}`,n.$async,()=>t.code(eg(r,o)).code(s))}function SS(t){return(0,R._)`{${M.default.instancePath}="", ${M.default.parentData}, ${M.default.parentDataProperty}, ${M.default.rootData}=${M.default.data}${t.dynamicRef?(0,R._)`, ${M.default.dynamicAnchors}={}`:R.nil}}={}`}function zS(t,e){t.if(M.default.valCxt,()=>{t.var(M.default.instancePath,(0,R._)`${M.default.valCxt}.${M.default.instancePath}`),t.var(M.default.parentData,(0,R._)`${M.default.valCxt}.${M.default.parentData}`),t.var(M.default.parentDataProperty,(0,R._)`${M.default.valCxt}.${M.default.parentDataProperty}`),t.var(M.default.rootData,(0,R._)`${M.default.valCxt}.${M.default.rootData}`),e.dynamicRef&&t.var(M.default.dynamicAnchors,(0,R._)`${M.default.valCxt}.${M.default.dynamicAnchors}`)},()=>{t.var(M.default.instancePath,(0,R._)`""`),t.var(M.default.parentData,(0,R._)`undefined`),t.var(M.default.parentDataProperty,(0,R._)`undefined`),t.var(M.default.rootData,M.default.data),e.dynamicRef&&t.var(M.default.dynamicAnchors,(0,R._)`{}`)})}function TS(t){let{schema:e,opts:r,gen:n}=t;og(t,()=>{r.$comment&&e.$comment&&ug(t),RS(t),n.let(M.default.vErrors,null),n.let(M.default.errors,0),r.unevaluated&&PS(t),cg(t),CS(t)})}function PS(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,R._)`${r}.evaluated`),e.if((0,R._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,R._)`${t.evaluated}.props`,(0,R._)`undefined`)),e.if((0,R._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,R._)`${t.evaluated}.items`,(0,R._)`undefined`))}function eg(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,R._)`/*# sourceURL=${r} */`:R.nil}function OS(t,e){if(ig(t)&&(ag(t),sg(t))){ES(t,e);return}(0,ng.boolOrEmptySchema)(t,e)}function sg({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function ig(t){return typeof t.schema!="boolean"}function ES(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&ug(t),jS(t),NS(t);let s=n.const("_errs",M.default.errors);cg(t,s),n.var(e,(0,R._)`${s} === ${M.default.errors}`)}function ag(t){(0,jt.checkUnknownRules)(t),IS(t)}function cg(t,e){if(t.opts.jtd)return tg(t,[],!1,e);let r=(0,Qh.getSchemaTypes)(t.schema),n=(0,Qh.coerceAndCheckDataType)(t,r);tg(t,r,!n,e)}function IS(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,jt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function RS(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,jt.checkStrictMode)(t,"default is ignored in the schema root")}function jS(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,$S.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function NS(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function ug({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,R._)`${M.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,R.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,R._)`${M.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function CS(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,R._)`${M.default.errors} === 0`,()=>e.return(M.default.data),()=>e.throw((0,R._)`new ${o}(${M.default.vErrors})`)):(e.assign((0,R._)`${n}.errors`,M.default.vErrors),s.unevaluated&&ZS(t),e.return((0,R._)`${M.default.errors} === 0`))}function ZS({gen:t,evaluated:e,props:r,items:n}){r instanceof R.Name&&t.assign((0,R._)`${e}.props`,r),n instanceof R.Name&&t.assign((0,R._)`${e}.items`,n)}function tg(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,jt.schemaHasRulesButRef)(s,l))){o.block(()=>dg(t,"$ref",l.all.$ref.definition));return}c.jtd||AS(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,yl.shouldUseGroup)(s,f)&&(f.type?(o.if((0,ii.checkDataType)(f.type,i,c.strictNumbers)),rg(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,ii.reportTypeError)(t)),o.endIf()):rg(t,f),a||o.if((0,R._)`${M.default.errors} === ${n||0}`))}}function rg(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,bS.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,yl.shouldUseRule)(n,s)&&dg(t,s.keyword,s.definition,e.type)})}function AS(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(MS(t,e),t.opts.allowUnionTypes||DS(t,e),LS(t,t.dataTypes))}function MS(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{lg(t.dataTypes,r)||_l(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),US(t,e)}}function DS(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&_l(t,"use allowUnionTypes to allow union type keyword")}function LS(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,yl.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>qS(e,i))&&_l(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function qS(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function lg(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function US(t,e){let r=[];for(let n of t.dataTypes)lg(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function _l(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,jt.checkStrictMode)(t,e,t.opts.strictTypes)}var ai=class{constructor(e,r,n){if((0,$o.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,jt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",pg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,$o.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",M.default.errors))}result(e,r,n){this.failResult((0,R.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,R.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,R._)`${r} !== undefined && (${(0,R.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?bo.reportExtraError:bo.reportError)(this,this.def.error,r)}$dataError(){(0,bo.reportError)(this,this.def.$dataError||bo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,bo.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=R.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=R.nil,r=R.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,R.or)((0,R._)`${o} === undefined`,r)),e!==R.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==R.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,R.or)(i(),a());function i(){if(n.length){if(!(r instanceof R.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,R._)`${(0,ii.checkDataTypes)(c,r,s.opts.strictNumbers,ii.DataType.Wrong)}`}return R.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,R._)`!${c}(${r})`}return R.nil}}subschema(e,r){let n=(0,gl.getSubschema)(this.it,e);(0,gl.extendSubschemaData)(n,this.it,e),(0,gl.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return OS(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=jt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,R.Name)),!0}};Yt.KeywordCxt=ai;function dg(t,e,r,n){let o=new ai(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,$o.funcKeywordCode)(o,r):"macro"in r?(0,$o.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,$o.funcKeywordCode)(o,r)}var FS=/^\/(?:[^~]|~0|~1)*$/,VS=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return M.default.rootData;if(t[0]==="/"){if(!FS.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=M.default.rootData}else{let u=VS.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,R._)`${s}${(0,R.getProperty)((0,jt.unescapeJsonPointer)(u))}`,i=(0,R._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Yt.getData=pg});var ci=S(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var vl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xl.default=vl});var So=S($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var wl=wo(),bl=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,wl.resolveUrl)(e,r,n),this.missingSchema=(0,wl.normalizeId)((0,wl.getFullPath)(e,this.missingRef))}};$l.default=bl});var li=S(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.resolveSchema=nt.getCompilingSchema=nt.resolveRef=nt.compileSchema=nt.SchemaEnv=void 0;var lt=U(),HS=ci(),Ar=Rt(),dt=wo(),fg=G(),KS=ko(),hn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,dt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};nt.SchemaEnv=hn;function Sl(t){let e=mg.call(this,t);if(e)return e;let r=(0,dt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new lt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:HS.default,code:(0,lt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Ar.default.data,parentData:Ar.default.parentData,parentDataProperty:Ar.default.parentDataProperty,dataNames:[Ar.default.data],dataPathArr:[lt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,lt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:lt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,lt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,KS.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Ar.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Ar.default.self}`,`${Ar.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;m.evaluated={props:p instanceof lt.Name?void 0:p,items:h instanceof lt.Name?void 0:h,dynamicProps:p instanceof lt.Name,dynamicItems:h instanceof lt.Name},m.source&&(m.source.evaluated=(0,lt.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}nt.compileSchema=Sl;function BS(t,e,r){var n;r=(0,dt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=GS.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new hn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=XS.call(this,s)}nt.resolveRef=BS;function XS(t){return(0,dt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Sl.call(this,t)}function mg(t){for(let e of this._compilations)if(JS(e,t))return e}nt.getCompilingSchema=mg;function JS(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function GS(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ui.call(this,t,e)}function ui(t,e){let r=this.opts.uriResolver.parse(e),n=(0,dt._getFullPath)(this.opts.uriResolver,r),o=(0,dt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return kl.call(this,r,t);let s=(0,dt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ui.call(this,t,i);return typeof a?.schema!="object"?void 0:kl.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Sl.call(this,i),s===(0,dt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,dt.resolveUrl)(this.opts.uriResolver,o,u)),new hn({schema:a,schemaId:c,root:t,baseId:o})}return kl.call(this,r,i)}}nt.resolveSchema=ui;var WS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function kl(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,fg.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!WS.has(a)&&u&&(e=(0,dt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,fg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,dt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ui.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new hn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var hg=S(($C,YS)=>{YS.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Pl=S((kC,wg)=>{"use strict";var QS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),yg=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),zl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),_g=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ez=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Tl(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var tz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function gg(t){return t.length=0,!0}function rz(t,e,r){if(t.length){let n=Tl(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function nz(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=rz;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=gg}else{o.push(u);continue}}return o.length&&(a===gg?r.zone=o.join(""):i?n.push(o.join("")):n.push(Tl(o))),r.address=n.join(""),r}function vg(t){if(oz(t,":")<2)return{host:t,isIPV6:!1};let e=nz(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function oz(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function sz(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var iz={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},az=/[@/?#:]/g,cz=/[@/?#]/g;function xg(t,e){let r=e?cz:az;return r.lastIndex=0,t.replace(r,n=>iz[n])}function uz(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(zl(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&_g(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function lz(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(zl(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&_g(s)?e+=s:e+="%"+o,r+=2;continue}}ez(t[r])?e+=t[r]:e+=escape(t[r])}return e}function dz(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(zl(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function pz(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!yg(r)){let n=vg(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=xg(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}wg.exports={nonSimpleDomain:tz,recomposeAuthority:pz,reescapeHostDelimiters:xg,normalizePercentEncoding:uz,normalizePathEncoding:lz,escapePreservingEscapes:dz,removeDotSegments:sz,isIPv4:yg,isUUID:QS,normalizeIPv6:vg,stringArrayToHexStripped:Tl}});var zg=S((SC,Sg)=>{"use strict";var{isUUID:fz}=Pl(),mz=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,hz=["http","https","ws","wss","urn","urn:uuid"];function gz(t){return hz.indexOf(t)!==-1}function Ol(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function bg(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function $g(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function yz(t){return t.secure=Ol(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function _z(t){if((t.port===(Ol(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function vz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(mz);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=El(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function xz(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=El(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function wz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!fz(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function bz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var kg={scheme:"http",domainHost:!0,parse:bg,serialize:$g},$z={scheme:"https",domainHost:kg.domainHost,parse:bg,serialize:$g},di={scheme:"ws",domainHost:!0,parse:yz,serialize:_z},kz={scheme:"wss",domainHost:di.domainHost,parse:di.parse,serialize:di.serialize},Sz={scheme:"urn",parse:vz,serialize:xz,skipNormalize:!0},zz={scheme:"urn:uuid",parse:wz,serialize:bz,skipNormalize:!0},pi={http:kg,https:$z,ws:di,wss:kz,urn:Sz,"urn:uuid":zz};Object.setPrototypeOf(pi,null);function El(t){return t&&(pi[t]||pi[t.toLowerCase()])||void 0}Sg.exports={wsIsSecure:Ol,SCHEMES:pi,isValidSchemeName:gz,getSchemeHandler:El}});var Rg=S((zC,fi)=>{"use strict";var{normalizeIPv6:Tz,removeDotSegments:zo,recomposeAuthority:Pz,normalizePercentEncoding:Oz,normalizePathEncoding:Ez,escapePreservingEscapes:Iz,reescapeHostDelimiters:Rz,isIPv4:jz,nonSimpleDomain:Nz}=Pl(),{SCHEMES:Cz,getSchemeHandler:Pg}=zg();function Zz(t,e){return typeof t=="string"?t=qz(t,e):typeof t=="object"&&(t=gn(Mr(t,e),e)),t}function Az(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Og(gn(t,n),gn(e,n),n,!0);return n.skipEscape=!0,Mr(o,n)}function Og(t,e,r,n){let o={};return n||(t=gn(Mr(t,r),r),e=gn(Mr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=zo(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=zo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=zo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=zo(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function Mz(t,e,r){let n=Tg(t,r),o=Tg(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Mr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=Pg(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Oz(r.path):(r.path=Iz(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=Pz(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=zo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var Dz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Lz(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Eg(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(Dz);if(i){n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]);let a=Lz(n,i);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(jz(n.host)===!1){let l=Tz(n.host);n.host=l.host.toLowerCase(),s=l.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let c=Pg(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&s===!1&&Nz(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!c||c&&!c.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Rz(unescape(n.host),s))),n.path&&(n.path=Ez(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function gn(t,e){return Eg(t,e).parsed}function qz(t,e){return Ig(t,e).normalized}function Ig(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Eg(t,e);return{normalized:n?t:Mr(r,e),malformedAuthorityOrPort:n}}function Tg(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Ig(t,e);return n?void 0:r}if(typeof t=="object")return Mr(t,e)}var Il={SCHEMES:Cz,normalize:Zz,resolve:Az,resolveComponent:Og,equal:Mz,serialize:Mr,parse:gn};fi.exports=Il;fi.exports.default=Il;fi.exports.fastUri=Il});var Ng=S(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var jg=Rg();jg.code='require("ajv/dist/runtime/uri").default';Rl.default=jg});var Ug=S(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.CodeGen=Se.Name=Se.nil=Se.stringify=Se.str=Se._=Se.KeywordCxt=void 0;var Uz=ko();Object.defineProperty(Se,"KeywordCxt",{enumerable:!0,get:function(){return Uz.KeywordCxt}});var yn=U();Object.defineProperty(Se,"_",{enumerable:!0,get:function(){return yn._}});Object.defineProperty(Se,"str",{enumerable:!0,get:function(){return yn.str}});Object.defineProperty(Se,"stringify",{enumerable:!0,get:function(){return yn.stringify}});Object.defineProperty(Se,"nil",{enumerable:!0,get:function(){return yn.nil}});Object.defineProperty(Se,"Name",{enumerable:!0,get:function(){return yn.Name}});Object.defineProperty(Se,"CodeGen",{enumerable:!0,get:function(){return yn.CodeGen}});var Fz=ci(),Dg=So(),Vz=il(),To=li(),Hz=U(),Po=wo(),mi=xo(),Nl=G(),Cg=hg(),Kz=Ng(),Lg=(t,e)=>new RegExp(t,e);Lg.code="new RegExp";var Bz=["removeAdditional","useDefaults","coerceTypes"],Xz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Jz={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Gz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Zg=200;function Wz(t){var e,r,n,o,s,i,a,c,u,l,d,f,m,p,h,g,w,v,x,T,N,he,He,ye,Ke;let Tn=t.strict,Ai=(e=t.code)===null||e===void 0?void 0:e.optimize,qd=Ai===!0||Ai===void 0?1:Ai||0,Ud=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Lg,S_=(o=t.uriResolver)!==null&&o!==void 0?o:Kz.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Tn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Tn)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Tn)!==null&&l!==void 0?l:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:Tn)!==null&&f!==void 0?f:"log",strictRequired:(p=(m=t.strictRequired)!==null&&m!==void 0?m:Tn)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:qd,regExp:Ud}:{optimize:qd,regExp:Ud},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Zg,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Zg,meta:(w=t.meta)!==null&&w!==void 0?w:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(T=t.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(N=t.addUsedSchema)!==null&&N!==void 0?N:!0,validateSchema:(he=t.validateSchema)!==null&&he!==void 0?he:!0,validateFormats:(He=t.validateFormats)!==null&&He!==void 0?He:!0,unicodeRegExp:(ye=t.unicodeRegExp)!==null&&ye!==void 0?ye:!0,int32range:(Ke=t.int32range)!==null&&Ke!==void 0?Ke:!0,uriResolver:S_}}var Oo=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Wz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Hz.ValueScope({scope:{},prefixes:Xz,es5:r,lines:n}),this.logger=nT(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Vz.getRules)(),Ag.call(this,Jz,e,"NOT SUPPORTED"),Ag.call(this,Gz,e,"DEPRECATED","warn"),this._metaOpts=tT.call(this),e.formats&&Qz.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&eT.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Yz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Cg;n==="id"&&(o={...Cg},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let f=this._addSchema(l,d);return f.validate||i.call(this,f)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof Dg.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Po.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Mg.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new To.SchemaEnv({schema:{},schemaId:n});if(r=To.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Mg.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Po.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(sT.call(this,n,r),!r)return(0,Nl.eachItem)(n,s=>jl.call(this,s)),this;aT.call(this,r);let o={...r,type:(0,mi.getJSONTypes)(r.type),schemaType:(0,mi.getJSONTypes)(r.schemaType)};return(0,Nl.eachItem)(n,o.type.length===0?s=>jl.call(this,s,o):s=>o.type.forEach(i=>jl.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=qg(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Po.normalizeId)(i||n);let u=Po.getSchemaRefs.call(this,e,n);return c=new To.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):To.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{To.compileSchema.call(this,e)}finally{this.opts=r}}};Oo.ValidationError=Fz.default;Oo.MissingRefError=Dg.default;Se.default=Oo;function Ag(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Mg(t){return t=(0,Po.normalizeId)(t),this.schemas[t]||this.refs[t]}function Yz(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Qz(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function eT(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function tT(){let t={...this.opts};for(let e of Bz)delete t[e];return t}var rT={log(){},warn(){},error(){}};function nT(t){if(t===!1)return rT;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var oT=/^[a-z_$][a-z0-9_$:-]*$/i;function sT(t,e){let{RULES:r}=this;if((0,Nl.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!oT.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function jl(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,mi.getJSONTypes)(e.type),schemaType:(0,mi.getJSONTypes)(e.schemaType)}};e.before?iT.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function iT(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function aT(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=qg(e)),t.validateSchema=this.compile(e,!0))}var cT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function qg(t){return{anyOf:[t,cT]}}});var Fg=S(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});var uT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Cl.default=uT});var Bg=S(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.callRef=Dr.getValidate=void 0;var lT=So(),Vg=rt(),Ve=U(),_n=Rt(),Hg=li(),hi=G(),dT={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=Hg.resolveRef.call(c,u,o,r);if(l===void 0)throw new lT.default(n.opts.uriResolver,o,r);if(l instanceof Hg.SchemaEnv)return f(l);return m(l);function d(){if(s===u)return gi(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return gi(t,(0,Ve._)`${p}.validate`,u,u.$async)}function f(p){let h=Kg(t,p);gi(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Ve.stringify)(p)}:{ref:p}),g=e.name("valid"),w=t.subschema({schema:p,dataTypes:[],schemaPath:Ve.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(w),t.ok(g)}}};function Kg(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ve._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Dr.getValidate=Kg;function gi(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?_n.default.this:Ve.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,Ve._)`await ${(0,Vg.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,Ve._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,Vg.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,Ve._)`${p}.errors`;o.assign(_n.default.vErrors,(0,Ve._)`${_n.default.vErrors} === null ? ${h} : ${_n.default.vErrors}.concat(${h})`),o.assign(_n.default.errors,(0,Ve._)`${_n.default.vErrors}.length`)}function m(p){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=hi.mergeEvaluated.props(o,g.props,s.props));else{let w=o.var("props",(0,Ve._)`${p}.evaluated.props`);s.props=hi.mergeEvaluated.props(o,w,s.props,Ve.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=hi.mergeEvaluated.items(o,g.items,s.items));else{let w=o.var("items",(0,Ve._)`${p}.evaluated.items`);s.items=hi.mergeEvaluated.items(o,w,s.items,Ve.Name)}}}Dr.callRef=gi;Dr.default=dT});var Xg=S(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var pT=Fg(),fT=Bg(),mT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",pT.default,fT.default];Zl.default=mT});var Jg=S(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var yi=U(),Qt=yi.operators,_i={maximum:{okStr:"<=",ok:Qt.LTE,fail:Qt.GT},minimum:{okStr:">=",ok:Qt.GTE,fail:Qt.LT},exclusiveMaximum:{okStr:"<",ok:Qt.LT,fail:Qt.GTE},exclusiveMinimum:{okStr:">",ok:Qt.GT,fail:Qt.LTE}},hT={message:({keyword:t,schemaCode:e})=>(0,yi.str)`must be ${_i[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,yi._)`{comparison: ${_i[t].okStr}, limit: ${e}}`},gT={keyword:Object.keys(_i),type:"number",schemaType:"number",$data:!0,error:hT,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,yi._)`${r} ${_i[e].fail} ${n} || isNaN(${r})`)}};Al.default=gT});var Gg=S(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var Eo=U(),yT={message:({schemaCode:t})=>(0,Eo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Eo._)`{multipleOf: ${t}}`},_T={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:yT,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Eo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Eo._)`${i} !== parseInt(${i})`;t.fail$data((0,Eo._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Ml.default=_T});var Yg=S(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});function Wg(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Dl.default=Wg;Wg.code='require("ajv/dist/runtime/ucs2length").default'});var Qg=S(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var Lr=U(),vT=G(),xT=Yg(),wT={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Lr.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Lr._)`{limit: ${t}}`},bT={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:wT,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Lr.operators.GT:Lr.operators.LT,i=o.opts.unicode===!1?(0,Lr._)`${r}.length`:(0,Lr._)`${(0,vT.useFunc)(t.gen,xT.default)}(${r})`;t.fail$data((0,Lr._)`${i} ${s} ${n}`)}};Ll.default=bT});var ey=S(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var $T=rt(),kT=G(),vn=U(),ST={message:({schemaCode:t})=>(0,vn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,vn._)`{pattern: ${t}}`},zT={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ST,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,vn._)`new RegExp`:(0,kT.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,vn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,vn._)`!${l}`)}else{let c=(0,$T.usePattern)(t,o);t.fail$data((0,vn._)`!${c}.test(${r})`)}}};ql.default=zT});var ty=S(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var Io=U(),TT={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Io.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Io._)`{limit: ${t}}`},PT={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:TT,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Io.operators.GT:Io.operators.LT;t.fail$data((0,Io._)`Object.keys(${r}).length ${o} ${n}`)}};Ul.default=PT});var ry=S(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var Ro=rt(),jo=U(),OT=G(),ET={message:({params:{missingProperty:t}})=>(0,jo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,jo._)`{missingProperty: ${t}}`},IT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ET,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(m?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,w=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,OT.checkStrictMode)(i,w,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(jo.nil,d);else for(let m of r)(0,Ro.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>f(m,p)),t.ok(p)}else e.if((0,Ro.checkMissingProp)(t,r,m)),(0,Ro.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,Ro.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(p,(0,Ro.propertyInData)(e,o,m,a.ownProperties)),e.if((0,jo.not)(p),()=>{t.error(),e.break()})},jo.nil)}}};Fl.default=IT});var ny=S(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var No=U(),RT={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,No.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,No._)`{limit: ${t}}`},jT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:RT,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?No.operators.GT:No.operators.LT;t.fail$data((0,No._)`${r}.length ${o} ${n}`)}};Vl.default=jT});var vi=S(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var oy=ml();oy.code='require("ajv/dist/runtime/equal").default';Hl.default=oy});var sy=S(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var Kl=xo(),ze=U(),NT=G(),CT=vi(),ZT={message:({params:{i:t,j:e}})=>(0,ze.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ze._)`{i: ${t}, j: ${e}}`},AT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ZT,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Kl.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,ze._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,ze._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,ze._)`${p} > 1`,()=>(d()?f:m)(p,h))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,h){let g=e.name("item"),w=(0,Kl.checkDataTypes)(u,g,a.opts.strictNumbers,Kl.DataType.Wrong),v=e.const("indices",(0,ze._)`{}`);e.for((0,ze._)`;${p}--;`,()=>{e.let(g,(0,ze._)`${r}[${p}]`),e.if(w,(0,ze._)`continue`),u.length>1&&e.if((0,ze._)`typeof ${g} == "string"`,(0,ze._)`${g} += "_"`),e.if((0,ze._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,ze._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,ze._)`${v}[${g}] = ${p}`)})}function m(p,h){let g=(0,NT.useFunc)(e,CT.default),w=e.name("outer");e.label(w).for((0,ze._)`;${p}--;`,()=>e.for((0,ze._)`${h} = ${p}; ${h}--;`,()=>e.if((0,ze._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(w)})))}}};Bl.default=AT});var iy=S(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var Xl=U(),MT=G(),DT=vi(),LT={message:"must be equal to constant",params:({schemaCode:t})=>(0,Xl._)`{allowedValue: ${t}}`},qT={keyword:"const",$data:!0,error:LT,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Xl._)`!${(0,MT.useFunc)(e,DT.default)}(${r}, ${o})`):t.fail((0,Xl._)`${s} !== ${r}`)}};Jl.default=qT});var ay=S(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var Co=U(),UT=G(),FT=vi(),VT={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Co._)`{allowedValues: ${t}}`},HT={keyword:"enum",schemaType:"array",$data:!0,error:VT,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,UT.useFunc)(e,FT.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);l=(0,Co.or)(...o.map((p,h)=>f(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,Co._)`${u()}(${r}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,Co._)`${u()}(${r}, ${m}[${p}])`:(0,Co._)`${r} === ${h}`}}};Gl.default=HT});var cy=S(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var KT=Jg(),BT=Gg(),XT=Qg(),JT=ey(),GT=ty(),WT=ry(),YT=ny(),QT=sy(),eP=iy(),tP=ay(),rP=[KT.default,BT.default,XT.default,JT.default,GT.default,WT.default,YT.default,QT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},eP.default,tP.default];Wl.default=rP});var Ql=S(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.validateAdditionalItems=void 0;var qr=U(),Yl=G(),nP={message:({params:{len:t}})=>(0,qr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,qr._)`{limit: ${t}}`},oP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:nP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Yl.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}uy(t,n)}};function uy(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,qr._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,qr._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Yl.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,qr._)`${a} <= ${e.length}`);r.if((0,qr.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Yl.Type.Num},u),i.allErrors||r.if((0,qr.not)(u),()=>r.break())})}}Zo.validateAdditionalItems=uy;Zo.default=oP});var ed=S(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.validateTuple=void 0;var ly=U(),xi=G(),sP=rt(),iP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return dy(t,"additionalItems",e);r.items=!0,!(0,xi.alwaysValidSchema)(r,e)&&t.ok((0,sP.validateArray)(t))}};function dy(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=xi.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,ly._)`${s}.length`);r.forEach((d,f)=>{(0,xi.alwaysValidSchema)(a,d)||(n.if((0,ly._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:m}=a,p=r.length,h=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,xi.checkStrictMode)(a,g,f.strictTuples)}}}Ao.validateTuple=dy;Ao.default=iP});var py=S(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var aP=ed(),cP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,aP.validateTuple)(t,"items")};td.default=cP});var my=S(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var fy=U(),uP=G(),lP=rt(),dP=Ql(),pP={message:({params:{len:t}})=>(0,fy.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,fy._)`{limit: ${t}}`},fP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:pP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,uP.alwaysValidSchema)(n,e)&&(o?(0,dP.validateAdditionalItems)(t,o):t.ok((0,lP.validateArray)(t)))}};rd.default=fP});var hy=S(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var ot=U(),wi=G(),mP={message:({params:{min:t,max:e}})=>e===void 0?(0,ot.str)`must contain at least ${t} valid item(s)`:(0,ot.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ot._)`{minContains: ${t}}`:(0,ot._)`{minContains: ${t}, maxContains: ${e}}`},hP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:mP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,ot._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,wi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,wi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,wi.alwaysValidSchema)(s,r)){let h=(0,ot._)`${l} >= ${i}`;a!==void 0&&(h=(0,ot._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ot._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let h=e.name("_valid"),g=e.let("count",0);m(h,()=>e.if(h,()=>p(g)))}function m(h,g){e.forRange("i",0,l,w=>{t.subschema({keyword:"contains",dataProp:w,dataPropType:wi.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,ot._)`${h}++`),a===void 0?e.if((0,ot._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ot._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ot._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};nd.default=hP});var _y=S(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.validateSchemaDeps=xt.validatePropertyDeps=xt.error=void 0;var od=U(),gP=G(),Mo=rt();xt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,od.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,od._)`{property: ${t},
|
|
60
|
+
- No prose outside the FILE blocks.`;f$={openai:"https://api.openai.com/v1",groq:"https://api.groq.com/openai/v1",mistral:"https://api.mistral.ai/v1",together:"https://api.together.xyz/v1",ollama:"http://localhost:11434/v1",anthropic:"https://api.anthropic.com",custom:""},th=class{cfg;label;constructor(e){this.cfg=e,this.label=`your ${e.provider} key (${e.model})`}async generate(e){let r=kne(e),n=this.cfg.provider==="anthropic"?await this.callAnthropic(r):await this.callOpenAICompatible(r);return ik(n)}async callOpenAICompatible(e){let r=(this.cfg.baseUrl||f$[this.cfg.provider]).replace(/\/$/,"");if(!r)throw new Error("a baseUrl is required for the custom provider");let n={"content-type":"application/json"};this.cfg.key&&(n.authorization=`Bearer ${this.cfg.key}`);let s=await fetch(`${r}/chat/completions`,{method:"POST",headers:n,body:JSON.stringify({model:this.cfg.model,temperature:.2,messages:[{role:"system",content:d$},{role:"user",content:e}]})});if(!s.ok)throw new Error(`${this.cfg.provider} ${s.status}: ${(await s.text()).slice(0,300)}`);return(await s.json()).choices?.[0]?.message?.content??""}async callAnthropic(e){let r=(this.cfg.baseUrl||f$.anthropic).replace(/\/$/,""),n=await fetch(`${r}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-api-key":this.cfg.key??"","anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.cfg.model,max_tokens:8192,temperature:.2,system:d$,messages:[{role:"user",content:e}]})});if(!n.ok)throw new Error(`anthropic ${n.status}: ${(await n.text()).slice(0,300)}`);return((await n.json()).content??[]).map(i=>i.text??"").join("")}},ok=class{onNote;label="OIOXO on-device (private)";impl=null;constructor(e=()=>{}){this.onNote=e}async generate(e){if(!this.impl){let{DeviceCoderLocal:r}=await Promise.resolve().then(()=>(l$(),u$));this.impl=new r(this.onNote)}return this.impl.generate(e)}}});function k_(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Bm(t){let e=t.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((t.length+3)%4),r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n}function b$(t){return new TextDecoder().decode(Bm(t))}var T_=mr(()=>{"use strict"});var v$={};$a(v$,{deviceIdForJwk:()=>rh,makeVerifier:()=>lk});async function rh(t){let e=await crypto.subtle.importKey("jwk",t,_$,!0,["verify"]),r=await crypto.subtle.exportKey("raw",e);return k_(await crypto.subtle.digest("SHA-256",r))}function lk(t){return async(e,r,n)=>{try{let s=await t(n);if(!s||await rh(s)!==n)return!1;let i=await crypto.subtle.importKey("jwk",s,_$,!0,["verify"]);return await crypto.subtle.verify(Mne,i,new Uint8Array(Bm(r)),jne.encode(e))}catch{return!1}}}var _$,Mne,jne,I_=mr(()=>{"use strict";T_();_$={name:"ECDSA",namedCurve:"P-256"},Mne={name:"ECDSA",hash:"SHA-256"},jne=new TextEncoder});var Vc=v(C$=>{function Fne(){var t,e=!1,r=this;r._DeArray=function(n,s,i){return[n.slice(s,s+i)]},r._EnArray=function(n,s,i,o){for(var a=0;a<i;n[s+a]=o[a]?o[a]:0,a++);},r._DeChar=function(n,s){return String.fromCharCode(n[s])},r._EnChar=function(n,s,i){n[s]=i.charCodeAt(0)},r._DeInt=function(n,s){var i=e?t.len-1:0,o=e?-1:1,a=i+o*t.len,c,u,l;for(c=0,u=i,l=1;u!=a;c+=n[s+u]*l,u+=o,l*=256);return t.bSigned&&c&Math.pow(2,t.len*8-1)&&(c-=Math.pow(2,t.len*8)),c},r._EnInt=function(n,s,i){var o=e?t.len-1:0,a=e?-1:1,c=o+a*t.len,u;for(i=i<t.min?t.min:i>t.max?t.max:i,u=o;u!=c;n[s+u]=i&255,u+=a,i>>=8);},r._DeString=function(n,s,i){for(var o=new Array(i),a=0;a<i;o[a]=String.fromCharCode(n[s+a]),a++);return o.join("")},r._EnString=function(n,s,i,o){for(var a,c=0;c<i;n[s+c]=(a=o.charCodeAt(c))?a:0,c++);},r._De754=function(n,s){var i,o,a,c,u,l,d,f,p,m;for(d=t.mLen,f=t.len*8-t.mLen-1,m=(1<<f)-1,p=m>>1,c=e?0:t.len-1,u=e?1:-1,i=n[s+c],c+=u,l=-7,o=i&(1<<-l)-1,i>>=-l,l+=f;l>0;o=o*256+n[s+c],c+=u,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=d;l>0;a=a*256+n[s+c],c+=u,l-=8);switch(o){case 0:o=1-p;break;case m:return a?NaN:(i?-1:1)*(1/0);default:a=a+Math.pow(2,d),o=o-p;break}return(i?-1:1)*a*Math.pow(2,o-d)},r._En754=function(n,s,i){var o,a,c,u,l,d,f,p,m,y;for(f=t.mLen,p=t.len*8-t.mLen-1,y=(1<<p)-1,m=y>>1,o=i<0?1:0,i=Math.abs(i),isNaN(i)||i==1/0?(c=isNaN(i)?1:0,a=y):(a=Math.floor(Math.log(i)/Math.LN2),i*(d=Math.pow(2,-a))<1&&(a--,d*=2),a+m>=1?i+=t.rt/d:i+=t.rt*Math.pow(2,1-m),i*d>=2&&(a++,d/=2),a+m>=y?(c=0,a=y):a+m>=1?(c=(i*d-1)*Math.pow(2,f),a=a+m):(c=i*Math.pow(2,m-1)*Math.pow(2,f),a=0)),u=e?t.len-1:0,l=e?-1:1;f>=8;n[s+u]=c&255,u+=l,c/=256,f-=8);for(a=a<<f|c,p+=f;p>0;n[s+u]=a&255,u+=l,a/=256,p-=8);n[s+u-l]|=o*128},r._DeInt64=function(n,s){var i=e?0:7,o=e?1:-1,a=i+o*8,c=[0,0,!t.bSigned],u,l,d;for(u=i,d=1,l=0;u!=a;c[d]=(c[d]<<8>>>0)+n[s+u],u+=o,l++,d=l<4?1:0);return c},r._EnInt64=function(n,s,i){var o=e?0:7,a=e?1:-1,c=o+a*8,u,l,d,f;for(u=o,d=1,l=0,f=24;u!=c;n[s+u]=i[d]>>f&255,u+=a,l++,d=l<4?1:0,f=24-8*(l%4));},r._sPattern="(\\d + )?([AxcbBhHsfdiIlLqQ])",r._lenLut={A:1,x:1,c:1,b:1,B:1,h:2,H:2,s:1,f:4,d:8,i:4,I:4,l:4,L:4,q:8,Q:8},r._elLut={A:{en:r._EnArray,de:r._DeArray},s:{en:r._EnString,de:r._DeString},c:{en:r._EnChar,de:r._DeChar},b:{en:r._EnInt,de:r._DeInt,len:1,bSigned:!0,min:-Math.pow(2,7),max:Math.pow(2,7)-1},B:{en:r._EnInt,de:r._DeInt,len:1,bSigned:!1,min:0,max:Math.pow(2,8)-1},h:{en:r._EnInt,de:r._DeInt,len:2,bSigned:!0,min:-Math.pow(2,15),max:Math.pow(2,15)-1},H:{en:r._EnInt,de:r._DeInt,len:2,bSigned:!1,min:0,max:Math.pow(2,16)-1},i:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},I:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},l:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},L:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},f:{en:r._En754,de:r._De754,len:4,mLen:23,rt:Math.pow(2,-24)-Math.pow(2,-77)},d:{en:r._En754,de:r._De754,len:8,mLen:52,rt:0},q:{en:r._EnInt64,de:r._DeInt64,bSigned:!0},Q:{en:r._EnInt64,de:r._DeInt64,bSigned:!1}},r._UnpackSeries=function(n,s,i,o){for(var a=t.de,c=[],u=0;u<n;c.push(a(i,o+u*s)),u++);return c},r._PackSeries=function(n,s,i,o,a,c){for(var u=t.en,l=0;l<n;u(i,o+l*s,a[c+l]),l++);},r.Unpack=function(n,s,i){e=n.charAt(0)!="<",i=i||0;for(var o=new RegExp(this._sPattern,"g"),a,c,u,l=[];a=o.exec(n);){if(c=a[1]==null||a[1]==""?1:parseInt(a[1]),u=this._lenLut[a[2]],i+c*u>s.length)return;switch(a[2]){case"A":case"s":l.push(this._elLut[a[2]].de(s,i,c));break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":t=this._elLut[a[2]],l.push(this._UnpackSeries(c,u,s,i));break}i+=c*u}return Array.prototype.concat.apply([],l)},r.PackTo=function(n,s,i,o){e=n.charAt(0)!="<";for(var a=new RegExp(this._sPattern,"g"),c,u,l,d,f=0;c=a.exec(n);){if(u=c[1]==null||c[1]==""?1:parseInt(c[1]),l=this._lenLut[c[2]],i+u*l>s.length)return!1;switch(c[2]){case"A":case"s":if(f+1>o.length)return!1;this._elLut[c[2]].en(s,i,u,o[f]),f+=1;break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":if(t=this._elLut[c[2]],f+u>o.length)return!1;this._PackSeries(u,l,s,i,o,f),f+=u;break;case"x":for(d=0;d<u;d++)s[i+d]=0;break}i+=u*l}return s},r.Pack=function(n,s){return this.PackTo(n,new Array(this.CalcLength(n)),0,s)},r.CalcLength=function(n){for(var s=new RegExp(this._sPattern,"g"),i=0,o;o=s.exec(n);)i+=(o[1]==null||o[1]==""?1:parseInt(o[1]))*this._lenLut[o[2]];return i}}C$.jspack=new Fne});var T$=v((uke,k$)=>{var nh=1e3,sh=nh*60,ih=sh*60,wl=ih*24,Vne=wl*7,Kne=wl*365.25;k$.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return Zne(t);if(r==="number"&&isFinite(t))return e.long?Wne(t):Gne(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function Zne(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*Kne;case"weeks":case"week":case"w":return r*Vne;case"days":case"day":case"d":return r*wl;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ih;case"minutes":case"minute":case"mins":case"min":case"m":return r*sh;case"seconds":case"second":case"secs":case"sec":case"s":return r*nh;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function Gne(t){var e=Math.abs(t);return e>=wl?Math.round(t/wl)+"d":e>=ih?Math.round(t/ih)+"h":e>=sh?Math.round(t/sh)+"m":e>=nh?Math.round(t/nh)+"s":t+"ms"}function Wne(t){var e=Math.abs(t);return e>=wl?R_(t,e,wl,"day"):e>=ih?R_(t,e,ih,"hour"):e>=sh?R_(t,e,sh,"minute"):e>=nh?R_(t,e,nh,"second"):t+" ms"}function R_(t,e,r,n){var s=e>=r*1.5;return Math.round(t/r)+" "+n+(s?"s":"")}});var pk=v((lke,I$)=>{function Xne(t){r.debug=r,r.default=r,r.coerce=c,r.disable=o,r.enable=s,r.enabled=a,r.humanize=T$(),r.destroy=u,Object.keys(t).forEach(l=>{r[l]=t[l]}),r.names=[],r.skips=[],r.formatters={};function e(l){let d=0;for(let f=0;f<l.length;f++)d=(d<<5)-d+l.charCodeAt(f),d|=0;return r.colors[Math.abs(d)%r.colors.length]}r.selectColor=e;function r(l){let d,f=null,p,m;function y(..._){if(!y.enabled)return;let S=y,C=Number(new Date),E=C-(d||C);S.diff=E,S.prev=d,S.curr=C,d=C,_[0]=r.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let B=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(se,_e)=>{if(se==="%%")return"%";B++;let he=r.formatters[_e];if(typeof he=="function"){let J=_[B];se=he.call(S,J),_.splice(B,1),B--}return se}),r.formatArgs.call(S,_),(S.log||r.log).apply(S,_)}return y.namespace=l,y.useColors=r.useColors(),y.color=r.selectColor(l),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(p!==r.namespaces&&(p=r.namespaces,m=r.enabled(l)),m),set:_=>{f=_}}),typeof r.init=="function"&&r.init(y),y}function n(l,d){let f=r(this.namespace+(typeof d>"u"?":":d)+l);return f.log=this.log,f}function s(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];let d=(typeof l=="string"?l:"").trim().replace(" ",",").split(",").filter(Boolean);for(let f of d)f[0]==="-"?r.skips.push(f.slice(1)):r.names.push(f)}function i(l,d){let f=0,p=0,m=-1,y=0;for(;f<l.length;)if(p<d.length&&(d[p]===l[f]||d[p]==="*"))d[p]==="*"?(m=p,y=f,p++):(f++,p++);else if(m!==-1)p=m+1,y++,f=y;else return!1;for(;p<d.length&&d[p]==="*";)p++;return p===d.length}function o(){let l=[...r.names,...r.skips.map(d=>"-"+d)].join(",");return r.enable(""),l}function a(l){for(let d of r.skips)if(i(l,d))return!1;for(let d of r.names)if(i(l,d))return!0;return!1}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}I$.exports=Xne});var P$=v((ti,O_)=>{ti.formatArgs=Yne;ti.save=Qne;ti.load=ese;ti.useColors=Jne;ti.storage=tse();ti.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();ti.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Jne(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Yne(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+O_.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(r++,s==="%c"&&(n=r))}),t.splice(n,0,e)}ti.log=console.debug||console.log||(()=>{});function Qne(t){try{t?ti.storage.setItem("debug",t):ti.storage.removeItem("debug")}catch{}}function ese(){let t;try{t=ti.storage.getItem("debug")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function tse(){try{return localStorage}catch{}}O_.exports=pk()(ti);var{formatters:rse}=O_.exports;rse.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var O$=v((dke,R$)=>{"use strict";R$.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var $$=v((fke,B$)=>{"use strict";var nse=on("os"),N$=on("tty"),_i=O$(),{env:Rn}=process,Kc;_i("no-color")||_i("no-colors")||_i("color=false")||_i("color=never")?Kc=0:(_i("color")||_i("colors")||_i("color=true")||_i("color=always"))&&(Kc=1);"FORCE_COLOR"in Rn&&(Rn.FORCE_COLOR==="true"?Kc=1:Rn.FORCE_COLOR==="false"?Kc=0:Kc=Rn.FORCE_COLOR.length===0?1:Math.min(parseInt(Rn.FORCE_COLOR,10),3));function mk(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function gk(t,e){if(Kc===0)return 0;if(_i("color=16m")||_i("color=full")||_i("color=truecolor"))return 3;if(_i("color=256"))return 2;if(t&&!e&&Kc===void 0)return 0;let r=Kc||0;if(Rn.TERM==="dumb")return r;if(process.platform==="win32"){let n=nse.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in Rn)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in Rn)||Rn.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in Rn)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Rn.TEAMCITY_VERSION)?1:0;if(Rn.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Rn){let n=parseInt((Rn.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Rn.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Rn.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Rn.TERM)||"COLORTERM"in Rn?1:r}function sse(t){let e=gk(t,t&&t.isTTY);return mk(e)}B$.exports={supportsColor:sse,stdout:mk(gk(!0,N$.isatty(1))),stderr:mk(gk(!0,N$.isatty(2)))}});var j$=v((On,B_)=>{var ise=on("tty"),N_=on("util");On.init=fse;On.log=use;On.formatArgs=ase;On.save=lse;On.load=dse;On.useColors=ose;On.destroy=N_.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");On.colors=[6,2,3,4,5,1];try{let t=$$();t&&(t.stderr||t).level>=2&&(On.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}On.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});function ose(){return"colors"in On.inspectOpts?!!On.inspectOpts.colors:ise.isatty(process.stderr.fd)}function ase(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;t[0]=i+t[0].split(`
|
|
61
|
+
`).join(`
|
|
62
|
+
`+i),t.push(s+"m+"+B_.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=cse()+e+" "+t[0]}function cse(){return On.inspectOpts.hideDate?"":new Date().toISOString()+" "}function use(...t){return process.stderr.write(N_.formatWithOptions(On.inspectOpts,...t)+`
|
|
63
|
+
`)}function lse(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function dse(){return process.env.DEBUG}function fse(t){t.inspectOpts={};let e=Object.keys(On.inspectOpts);for(let r=0;r<e.length;r++)t.inspectOpts[e[r]]=On.inspectOpts[e[r]]}B_.exports=pk()(On);var{formatters:M$}=B_.exports;M$.o=function(t){return this.inspectOpts.colors=this.useColors,N_.inspect(t,this.inspectOpts).split(`
|
|
64
|
+
`).map(e=>e.trim()).join(" ")};M$.O=function(t){return this.inspectOpts.colors=this.useColors,N_.inspect(t,this.inspectOpts)}});var z$=v((hke,yk)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?yk.exports=P$():yk.exports=j$()});var $_=v(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var hse=on("net");function pse(t){switch(hse.isIP(t)){case 4:return Buffer.from(t.split(".").map(s=>parseInt(s,10)));case 6:let e=t.split(":"),r=Buffer.alloc(16),n=0;e[e.length-1]===""&&(e[e.length-1]="0");for(let s=0;s<e.length;s++){if(e[s]===""){s+1<e.length&&e[s+1]!==""&&(n=16-(e.length-s-1)*2);continue}r.writeUInt16BE(parseInt(e[s],16),n),n+=2}return r;default:return null}}oh.bytesFromIP=pse;function mse(t){switch(t.length){case 4:return[t[0],t[1],t[2],t[3]].join(".");case 16:let e=[],r=-1,n=0,s=-1,i=0;for(let o=0;o<t.length;o+=2){let a=t[o]<<8|t[o+1];a===0?(n++,r===-1&&(r=e.length),n>i&&(i=n,s=r)):(r=-1,n=0),e.push(a.toString(16))}if(i>0){let o="",a=e.slice(s+i);e.length=s,e.length===0&&(o+=":"),a.length===0&&(o+=":"),e.push(o,...a)}return e.join(":");default:return""}}oh.bytesToIP=mse;var Zc=Object.create(null),L$=/^[0-9.]+$/;function gse(t){return L$.test(t)&&Zc[t]!==""?t:Zc[t]==null?"":Zc[t]}oh.getOID=gse;function yse(t){return!L$.test(t)&&Zc[t]!==""||Zc[t]==null?t:Zc[t]}oh.getOIDName=yse;function ie(t,e){Zc[t]=e,Zc[e]=t}ie("1.2.840.113549.1.1.1","rsaEncryption");ie("1.2.840.113549.1.1.4","md5WithRsaEncryption");ie("1.2.840.113549.1.1.5","sha1WithRsaEncryption");ie("1.2.840.113549.1.1.8","mgf1");ie("1.2.840.113549.1.1.10","RSASSA-PSS");ie("1.2.840.113549.1.1.11","sha256WithRsaEncryption");ie("1.2.840.113549.1.1.12","sha384WithRsaEncryption");ie("1.2.840.113549.1.1.13","sha512WithRsaEncryption");ie("1.2.840.10045.2.1","ecEncryption");ie("1.2.840.10045.4.1","ecdsaWithSha1");ie("1.2.840.10045.4.3.2","ecdsaWithSha256");ie("1.2.840.10045.4.3.3","ecdsaWithSha384");ie("1.2.840.10045.4.3.4","ecdsaWithSha512");ie("1.2.840.10040.4.3","dsaWithSha1");ie("2.16.840.1.101.3.4.3.2","dsaWithSha256");ie("1.3.14.3.2.7","desCBC");ie("1.3.14.3.2.26","sha1");ie("2.16.840.1.101.3.4.2.1","sha256");ie("2.16.840.1.101.3.4.2.2","sha384");ie("2.16.840.1.101.3.4.2.3","sha512");ie("1.2.840.113549.2.5","md5");ie("1.3.101.110","X25519");ie("1.3.101.111","X448");ie("1.3.101.112","Ed25519");ie("1.3.101.113","Ed448");ie("1.2.840.113549.1.7.1","data");ie("1.2.840.113549.1.7.2","signedData");ie("1.2.840.113549.1.7.3","envelopedData");ie("1.2.840.113549.1.7.4","signedAndEnvelopedData");ie("1.2.840.113549.1.7.5","digestedData");ie("1.2.840.113549.1.7.6","encryptedData");ie("1.2.840.113549.1.9.1","emailAddress");ie("1.2.840.113549.1.9.2","unstructuredName");ie("1.2.840.113549.1.9.3","contentType");ie("1.2.840.113549.1.9.4","messageDigest");ie("1.2.840.113549.1.9.5","signingTime");ie("1.2.840.113549.1.9.6","counterSignature");ie("1.2.840.113549.1.9.7","challengePassword");ie("1.2.840.113549.1.9.8","unstructuredAddress");ie("1.2.840.113549.1.9.14","extensionRequest");ie("1.2.840.113549.1.9.20","friendlyName");ie("1.2.840.113549.1.9.21","localKeyId");ie("1.2.840.113549.1.9.22.1","x509Certificate");ie("1.2.840.113549.1.12.10.1.1","keyBag");ie("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");ie("1.2.840.113549.1.12.10.1.3","certBag");ie("1.2.840.113549.1.12.10.1.4","crlBag");ie("1.2.840.113549.1.12.10.1.5","secretBag");ie("1.2.840.113549.1.12.10.1.6","safeContentsBag");ie("1.2.840.113549.1.5.13","pkcs5PBES2");ie("1.2.840.113549.1.5.12","pkcs5PBKDF2");ie("1.2.840.113549.2.7","hmacWithSha1");ie("1.2.840.113549.2.9","hmacWithSha256");ie("1.2.840.113549.2.10","hmacWithSha384");ie("1.2.840.113549.2.11","hmacWithSha512");ie("1.2.840.113549.3.7","3desCBC");ie("2.16.840.1.101.3.4.1.2","aesCBC128");ie("2.16.840.1.101.3.4.1.42","aesCBC256");ie("2.5.4.3","commonName");ie("2.5.4.5","serialName");ie("2.5.4.6","countryName");ie("2.5.4.7","localityName");ie("2.5.4.8","stateOrProvinceName");ie("2.5.4.10","organizationName");ie("2.5.4.11","organizationalUnitName");ie("2.5.4.15","businessCategory");ie("2.16.840.1.113730.1.1","nsCertType");ie("2.5.29.2","keyAttributes");ie("2.5.29.4","keyUsageRestriction");ie("2.5.29.6","subtreesConstraint");ie("2.5.29.9","subjectDirectoryAttributes");ie("2.5.29.14","subjectKeyIdentifier");ie("2.5.29.15","keyUsage");ie("2.5.29.16","privateKeyUsagePeriod");ie("2.5.29.17","subjectAltName");ie("2.5.29.18","issuerAltName");ie("2.5.29.19","basicConstraints");ie("2.5.29.20","cRLNumber");ie("2.5.29.21","cRLReason");ie("2.5.29.22","expirationDate");ie("2.5.29.23","instructionCode");ie("2.5.29.24","invalidityDate");ie("2.5.29.27","deltaCRLIndicator");ie("2.5.29.28","issuingDistributionPoint");ie("2.5.29.29","certificateIssuer");ie("2.5.29.30","nameConstraints");ie("2.5.29.31","cRLDistributionPoints");ie("2.5.29.32","certificatePolicies");ie("2.5.29.33","policyMappings");ie("2.5.29.35","authorityKeyIdentifier");ie("2.5.29.36","policyConstraints");ie("2.5.29.37","extKeyUsage");ie("2.5.29.46","freshestCRL");ie("2.5.29.54","inhibitAnyPolicy");ie("1.3.6.1.4.1.311.60.2.1.2","jurisdictionST");ie("1.3.6.1.4.1.311.60.2.1.3","jurisdictionC");ie("1.3.6.1.4.1.11129.2.4.2","timestampList");ie("1.3.6.1.5.5.7.1.1","authorityInfoAccess");ie("1.3.6.1.5.5.7.3.1","serverAuth");ie("1.3.6.1.5.5.7.3.2","clientAuth");ie("1.3.6.1.5.5.7.3.3","codeSigning");ie("1.3.6.1.5.5.7.3.4","emailProtection");ie("1.3.6.1.5.5.7.3.8","timeStamping");ie("1.3.6.1.5.5.7.48.1","authorityInfoAccessOcsp");ie("1.3.6.1.5.5.7.48.2","authorityInfoAccessIssuers")});var j_=v((mke,M_)=>{(function(t){"use strict";var e=function(g){var b,x=new Float64Array(16);if(g)for(b=0;b<g.length;b++)x[b]=g[b];return x},r=function(){throw new Error("no PRNG")},n=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var i=e(),o=e([1]),a=e([56129,1]),c=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),u=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),l=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),d=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function p(g,b,x,h){g[b]=x>>24&255,g[b+1]=x>>16&255,g[b+2]=x>>8&255,g[b+3]=x&255,g[b+4]=h>>24&255,g[b+5]=h>>16&255,g[b+6]=h>>8&255,g[b+7]=h&255}function m(g,b,x,h,w){var R,N=0;for(R=0;R<w;R++)N|=g[b+R]^x[h+R];return(1&N-1>>>8)-1}function y(g,b,x,h){return m(g,b,x,h,16)}function _(g,b,x,h){return m(g,b,x,h,32)}function S(g,b,x,h){for(var w=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,R=x[0]&255|(x[1]&255)<<8|(x[2]&255)<<16|(x[3]&255)<<24,N=x[4]&255|(x[5]&255)<<8|(x[6]&255)<<16|(x[7]&255)<<24,Y=x[8]&255|(x[9]&255)<<8|(x[10]&255)<<16|(x[11]&255)<<24,me=x[12]&255|(x[13]&255)<<8|(x[14]&255)<<16|(x[15]&255)<<24,Ke=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,Te=b[0]&255|(b[1]&255)<<8|(b[2]&255)<<16|(b[3]&255)<<24,sr=b[4]&255|(b[5]&255)<<8|(b[6]&255)<<16|(b[7]&255)<<24,$e=b[8]&255|(b[9]&255)<<8|(b[10]&255)<<16|(b[11]&255)<<24,ft=b[12]&255|(b[13]&255)<<8|(b[14]&255)<<16|(b[15]&255)<<24,pt=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,Et=x[16]&255|(x[17]&255)<<8|(x[18]&255)<<16|(x[19]&255)<<24,At=x[20]&255|(x[21]&255)<<8|(x[22]&255)<<16|(x[23]&255)<<24,mt=x[24]&255|(x[25]&255)<<8|(x[26]&255)<<16|(x[27]&255)<<24,bt=x[28]&255|(x[29]&255)<<8|(x[30]&255)<<16|(x[31]&255)<<24,gt=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,Ue=w,Ye=R,Pe=N,qe=Y,Ve=me,Ee=Ke,L=Te,D=sr,oe=$e,X=ft,Q=pt,ue=Et,nt=At,Ct=mt,It=bt,kt=gt,A,$t=0;$t<20;$t+=2)A=Ue+nt|0,Ve^=A<<7|A>>>25,A=Ve+Ue|0,oe^=A<<9|A>>>23,A=oe+Ve|0,nt^=A<<13|A>>>19,A=nt+oe|0,Ue^=A<<18|A>>>14,A=Ee+Ye|0,X^=A<<7|A>>>25,A=X+Ee|0,Ct^=A<<9|A>>>23,A=Ct+X|0,Ye^=A<<13|A>>>19,A=Ye+Ct|0,Ee^=A<<18|A>>>14,A=Q+L|0,It^=A<<7|A>>>25,A=It+Q|0,Pe^=A<<9|A>>>23,A=Pe+It|0,L^=A<<13|A>>>19,A=L+Pe|0,Q^=A<<18|A>>>14,A=kt+ue|0,qe^=A<<7|A>>>25,A=qe+kt|0,D^=A<<9|A>>>23,A=D+qe|0,ue^=A<<13|A>>>19,A=ue+D|0,kt^=A<<18|A>>>14,A=Ue+qe|0,Ye^=A<<7|A>>>25,A=Ye+Ue|0,Pe^=A<<9|A>>>23,A=Pe+Ye|0,qe^=A<<13|A>>>19,A=qe+Pe|0,Ue^=A<<18|A>>>14,A=Ee+Ve|0,L^=A<<7|A>>>25,A=L+Ee|0,D^=A<<9|A>>>23,A=D+L|0,Ve^=A<<13|A>>>19,A=Ve+D|0,Ee^=A<<18|A>>>14,A=Q+X|0,ue^=A<<7|A>>>25,A=ue+Q|0,oe^=A<<9|A>>>23,A=oe+ue|0,X^=A<<13|A>>>19,A=X+oe|0,Q^=A<<18|A>>>14,A=kt+It|0,nt^=A<<7|A>>>25,A=nt+kt|0,Ct^=A<<9|A>>>23,A=Ct+nt|0,It^=A<<13|A>>>19,A=It+Ct|0,kt^=A<<18|A>>>14;Ue=Ue+w|0,Ye=Ye+R|0,Pe=Pe+N|0,qe=qe+Y|0,Ve=Ve+me|0,Ee=Ee+Ke|0,L=L+Te|0,D=D+sr|0,oe=oe+$e|0,X=X+ft|0,Q=Q+pt|0,ue=ue+Et|0,nt=nt+At|0,Ct=Ct+mt|0,It=It+bt|0,kt=kt+gt|0,g[0]=Ue>>>0&255,g[1]=Ue>>>8&255,g[2]=Ue>>>16&255,g[3]=Ue>>>24&255,g[4]=Ye>>>0&255,g[5]=Ye>>>8&255,g[6]=Ye>>>16&255,g[7]=Ye>>>24&255,g[8]=Pe>>>0&255,g[9]=Pe>>>8&255,g[10]=Pe>>>16&255,g[11]=Pe>>>24&255,g[12]=qe>>>0&255,g[13]=qe>>>8&255,g[14]=qe>>>16&255,g[15]=qe>>>24&255,g[16]=Ve>>>0&255,g[17]=Ve>>>8&255,g[18]=Ve>>>16&255,g[19]=Ve>>>24&255,g[20]=Ee>>>0&255,g[21]=Ee>>>8&255,g[22]=Ee>>>16&255,g[23]=Ee>>>24&255,g[24]=L>>>0&255,g[25]=L>>>8&255,g[26]=L>>>16&255,g[27]=L>>>24&255,g[28]=D>>>0&255,g[29]=D>>>8&255,g[30]=D>>>16&255,g[31]=D>>>24&255,g[32]=oe>>>0&255,g[33]=oe>>>8&255,g[34]=oe>>>16&255,g[35]=oe>>>24&255,g[36]=X>>>0&255,g[37]=X>>>8&255,g[38]=X>>>16&255,g[39]=X>>>24&255,g[40]=Q>>>0&255,g[41]=Q>>>8&255,g[42]=Q>>>16&255,g[43]=Q>>>24&255,g[44]=ue>>>0&255,g[45]=ue>>>8&255,g[46]=ue>>>16&255,g[47]=ue>>>24&255,g[48]=nt>>>0&255,g[49]=nt>>>8&255,g[50]=nt>>>16&255,g[51]=nt>>>24&255,g[52]=Ct>>>0&255,g[53]=Ct>>>8&255,g[54]=Ct>>>16&255,g[55]=Ct>>>24&255,g[56]=It>>>0&255,g[57]=It>>>8&255,g[58]=It>>>16&255,g[59]=It>>>24&255,g[60]=kt>>>0&255,g[61]=kt>>>8&255,g[62]=kt>>>16&255,g[63]=kt>>>24&255}function C(g,b,x,h){for(var w=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,R=x[0]&255|(x[1]&255)<<8|(x[2]&255)<<16|(x[3]&255)<<24,N=x[4]&255|(x[5]&255)<<8|(x[6]&255)<<16|(x[7]&255)<<24,Y=x[8]&255|(x[9]&255)<<8|(x[10]&255)<<16|(x[11]&255)<<24,me=x[12]&255|(x[13]&255)<<8|(x[14]&255)<<16|(x[15]&255)<<24,Ke=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,Te=b[0]&255|(b[1]&255)<<8|(b[2]&255)<<16|(b[3]&255)<<24,sr=b[4]&255|(b[5]&255)<<8|(b[6]&255)<<16|(b[7]&255)<<24,$e=b[8]&255|(b[9]&255)<<8|(b[10]&255)<<16|(b[11]&255)<<24,ft=b[12]&255|(b[13]&255)<<8|(b[14]&255)<<16|(b[15]&255)<<24,pt=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,Et=x[16]&255|(x[17]&255)<<8|(x[18]&255)<<16|(x[19]&255)<<24,At=x[20]&255|(x[21]&255)<<8|(x[22]&255)<<16|(x[23]&255)<<24,mt=x[24]&255|(x[25]&255)<<8|(x[26]&255)<<16|(x[27]&255)<<24,bt=x[28]&255|(x[29]&255)<<8|(x[30]&255)<<16|(x[31]&255)<<24,gt=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,Ue=w,Ye=R,Pe=N,qe=Y,Ve=me,Ee=Ke,L=Te,D=sr,oe=$e,X=ft,Q=pt,ue=Et,nt=At,Ct=mt,It=bt,kt=gt,A,$t=0;$t<20;$t+=2)A=Ue+nt|0,Ve^=A<<7|A>>>25,A=Ve+Ue|0,oe^=A<<9|A>>>23,A=oe+Ve|0,nt^=A<<13|A>>>19,A=nt+oe|0,Ue^=A<<18|A>>>14,A=Ee+Ye|0,X^=A<<7|A>>>25,A=X+Ee|0,Ct^=A<<9|A>>>23,A=Ct+X|0,Ye^=A<<13|A>>>19,A=Ye+Ct|0,Ee^=A<<18|A>>>14,A=Q+L|0,It^=A<<7|A>>>25,A=It+Q|0,Pe^=A<<9|A>>>23,A=Pe+It|0,L^=A<<13|A>>>19,A=L+Pe|0,Q^=A<<18|A>>>14,A=kt+ue|0,qe^=A<<7|A>>>25,A=qe+kt|0,D^=A<<9|A>>>23,A=D+qe|0,ue^=A<<13|A>>>19,A=ue+D|0,kt^=A<<18|A>>>14,A=Ue+qe|0,Ye^=A<<7|A>>>25,A=Ye+Ue|0,Pe^=A<<9|A>>>23,A=Pe+Ye|0,qe^=A<<13|A>>>19,A=qe+Pe|0,Ue^=A<<18|A>>>14,A=Ee+Ve|0,L^=A<<7|A>>>25,A=L+Ee|0,D^=A<<9|A>>>23,A=D+L|0,Ve^=A<<13|A>>>19,A=Ve+D|0,Ee^=A<<18|A>>>14,A=Q+X|0,ue^=A<<7|A>>>25,A=ue+Q|0,oe^=A<<9|A>>>23,A=oe+ue|0,X^=A<<13|A>>>19,A=X+oe|0,Q^=A<<18|A>>>14,A=kt+It|0,nt^=A<<7|A>>>25,A=nt+kt|0,Ct^=A<<9|A>>>23,A=Ct+nt|0,It^=A<<13|A>>>19,A=It+Ct|0,kt^=A<<18|A>>>14;g[0]=Ue>>>0&255,g[1]=Ue>>>8&255,g[2]=Ue>>>16&255,g[3]=Ue>>>24&255,g[4]=Ee>>>0&255,g[5]=Ee>>>8&255,g[6]=Ee>>>16&255,g[7]=Ee>>>24&255,g[8]=Q>>>0&255,g[9]=Q>>>8&255,g[10]=Q>>>16&255,g[11]=Q>>>24&255,g[12]=kt>>>0&255,g[13]=kt>>>8&255,g[14]=kt>>>16&255,g[15]=kt>>>24&255,g[16]=L>>>0&255,g[17]=L>>>8&255,g[18]=L>>>16&255,g[19]=L>>>24&255,g[20]=D>>>0&255,g[21]=D>>>8&255,g[22]=D>>>16&255,g[23]=D>>>24&255,g[24]=oe>>>0&255,g[25]=oe>>>8&255,g[26]=oe>>>16&255,g[27]=oe>>>24&255,g[28]=X>>>0&255,g[29]=X>>>8&255,g[30]=X>>>16&255,g[31]=X>>>24&255}function E(g,b,x,h){S(g,b,x,h)}function B(g,b,x,h){C(g,b,x,h)}var G=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function se(g,b,x,h,w,R,N){var Y=new Uint8Array(16),me=new Uint8Array(64),Ke,Te;for(Te=0;Te<16;Te++)Y[Te]=0;for(Te=0;Te<8;Te++)Y[Te]=R[Te];for(;w>=64;){for(E(me,Y,N,G),Te=0;Te<64;Te++)g[b+Te]=x[h+Te]^me[Te];for(Ke=1,Te=8;Te<16;Te++)Ke=Ke+(Y[Te]&255)|0,Y[Te]=Ke&255,Ke>>>=8;w-=64,b+=64,h+=64}if(w>0)for(E(me,Y,N,G),Te=0;Te<w;Te++)g[b+Te]=x[h+Te]^me[Te];return 0}function _e(g,b,x,h,w){var R=new Uint8Array(16),N=new Uint8Array(64),Y,me;for(me=0;me<16;me++)R[me]=0;for(me=0;me<8;me++)R[me]=h[me];for(;x>=64;){for(E(N,R,w,G),me=0;me<64;me++)g[b+me]=N[me];for(Y=1,me=8;me<16;me++)Y=Y+(R[me]&255)|0,R[me]=Y&255,Y>>>=8;x-=64,b+=64}if(x>0)for(E(N,R,w,G),me=0;me<x;me++)g[b+me]=N[me];return 0}function he(g,b,x,h,w){var R=new Uint8Array(32);B(R,h,w,G);for(var N=new Uint8Array(8),Y=0;Y<8;Y++)N[Y]=h[Y+16];return _e(g,b,x,N,R)}function J(g,b,x,h,w,R,N){var Y=new Uint8Array(32);B(Y,R,N,G);for(var me=new Uint8Array(8),Ke=0;Ke<8;Ke++)me[Ke]=R[Ke+16];return se(g,b,x,h,w,me,Y)}var ct=function(g){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var b,x,h,w,R,N,Y,me;b=g[0]&255|(g[1]&255)<<8,this.r[0]=b&8191,x=g[2]&255|(g[3]&255)<<8,this.r[1]=(b>>>13|x<<3)&8191,h=g[4]&255|(g[5]&255)<<8,this.r[2]=(x>>>10|h<<6)&7939,w=g[6]&255|(g[7]&255)<<8,this.r[3]=(h>>>7|w<<9)&8191,R=g[8]&255|(g[9]&255)<<8,this.r[4]=(w>>>4|R<<12)&255,this.r[5]=R>>>1&8190,N=g[10]&255|(g[11]&255)<<8,this.r[6]=(R>>>14|N<<2)&8191,Y=g[12]&255|(g[13]&255)<<8,this.r[7]=(N>>>11|Y<<5)&8065,me=g[14]&255|(g[15]&255)<<8,this.r[8]=(Y>>>8|me<<8)&8191,this.r[9]=me>>>5&127,this.pad[0]=g[16]&255|(g[17]&255)<<8,this.pad[1]=g[18]&255|(g[19]&255)<<8,this.pad[2]=g[20]&255|(g[21]&255)<<8,this.pad[3]=g[22]&255|(g[23]&255)<<8,this.pad[4]=g[24]&255|(g[25]&255)<<8,this.pad[5]=g[26]&255|(g[27]&255)<<8,this.pad[6]=g[28]&255|(g[29]&255)<<8,this.pad[7]=g[30]&255|(g[31]&255)<<8};ct.prototype.blocks=function(g,b,x){for(var h=this.fin?0:2048,w,R,N,Y,me,Ke,Te,sr,$e,ft,pt,Et,At,mt,bt,gt,Ue,Ye,Pe,qe=this.h[0],Ve=this.h[1],Ee=this.h[2],L=this.h[3],D=this.h[4],oe=this.h[5],X=this.h[6],Q=this.h[7],ue=this.h[8],nt=this.h[9],Ct=this.r[0],It=this.r[1],kt=this.r[2],A=this.r[3],$t=this.r[4],ir=this.r[5],or=this.r[6],Ot=this.r[7],Xt=this.r[8],Jt=this.r[9];x>=16;)w=g[b+0]&255|(g[b+1]&255)<<8,qe+=w&8191,R=g[b+2]&255|(g[b+3]&255)<<8,Ve+=(w>>>13|R<<3)&8191,N=g[b+4]&255|(g[b+5]&255)<<8,Ee+=(R>>>10|N<<6)&8191,Y=g[b+6]&255|(g[b+7]&255)<<8,L+=(N>>>7|Y<<9)&8191,me=g[b+8]&255|(g[b+9]&255)<<8,D+=(Y>>>4|me<<12)&8191,oe+=me>>>1&8191,Ke=g[b+10]&255|(g[b+11]&255)<<8,X+=(me>>>14|Ke<<2)&8191,Te=g[b+12]&255|(g[b+13]&255)<<8,Q+=(Ke>>>11|Te<<5)&8191,sr=g[b+14]&255|(g[b+15]&255)<<8,ue+=(Te>>>8|sr<<8)&8191,nt+=sr>>>5|h,$e=0,ft=$e,ft+=qe*Ct,ft+=Ve*(5*Jt),ft+=Ee*(5*Xt),ft+=L*(5*Ot),ft+=D*(5*or),$e=ft>>>13,ft&=8191,ft+=oe*(5*ir),ft+=X*(5*$t),ft+=Q*(5*A),ft+=ue*(5*kt),ft+=nt*(5*It),$e+=ft>>>13,ft&=8191,pt=$e,pt+=qe*It,pt+=Ve*Ct,pt+=Ee*(5*Jt),pt+=L*(5*Xt),pt+=D*(5*Ot),$e=pt>>>13,pt&=8191,pt+=oe*(5*or),pt+=X*(5*ir),pt+=Q*(5*$t),pt+=ue*(5*A),pt+=nt*(5*kt),$e+=pt>>>13,pt&=8191,Et=$e,Et+=qe*kt,Et+=Ve*It,Et+=Ee*Ct,Et+=L*(5*Jt),Et+=D*(5*Xt),$e=Et>>>13,Et&=8191,Et+=oe*(5*Ot),Et+=X*(5*or),Et+=Q*(5*ir),Et+=ue*(5*$t),Et+=nt*(5*A),$e+=Et>>>13,Et&=8191,At=$e,At+=qe*A,At+=Ve*kt,At+=Ee*It,At+=L*Ct,At+=D*(5*Jt),$e=At>>>13,At&=8191,At+=oe*(5*Xt),At+=X*(5*Ot),At+=Q*(5*or),At+=ue*(5*ir),At+=nt*(5*$t),$e+=At>>>13,At&=8191,mt=$e,mt+=qe*$t,mt+=Ve*A,mt+=Ee*kt,mt+=L*It,mt+=D*Ct,$e=mt>>>13,mt&=8191,mt+=oe*(5*Jt),mt+=X*(5*Xt),mt+=Q*(5*Ot),mt+=ue*(5*or),mt+=nt*(5*ir),$e+=mt>>>13,mt&=8191,bt=$e,bt+=qe*ir,bt+=Ve*$t,bt+=Ee*A,bt+=L*kt,bt+=D*It,$e=bt>>>13,bt&=8191,bt+=oe*Ct,bt+=X*(5*Jt),bt+=Q*(5*Xt),bt+=ue*(5*Ot),bt+=nt*(5*or),$e+=bt>>>13,bt&=8191,gt=$e,gt+=qe*or,gt+=Ve*ir,gt+=Ee*$t,gt+=L*A,gt+=D*kt,$e=gt>>>13,gt&=8191,gt+=oe*It,gt+=X*Ct,gt+=Q*(5*Jt),gt+=ue*(5*Xt),gt+=nt*(5*Ot),$e+=gt>>>13,gt&=8191,Ue=$e,Ue+=qe*Ot,Ue+=Ve*or,Ue+=Ee*ir,Ue+=L*$t,Ue+=D*A,$e=Ue>>>13,Ue&=8191,Ue+=oe*kt,Ue+=X*It,Ue+=Q*Ct,Ue+=ue*(5*Jt),Ue+=nt*(5*Xt),$e+=Ue>>>13,Ue&=8191,Ye=$e,Ye+=qe*Xt,Ye+=Ve*Ot,Ye+=Ee*or,Ye+=L*ir,Ye+=D*$t,$e=Ye>>>13,Ye&=8191,Ye+=oe*A,Ye+=X*kt,Ye+=Q*It,Ye+=ue*Ct,Ye+=nt*(5*Jt),$e+=Ye>>>13,Ye&=8191,Pe=$e,Pe+=qe*Jt,Pe+=Ve*Xt,Pe+=Ee*Ot,Pe+=L*or,Pe+=D*ir,$e=Pe>>>13,Pe&=8191,Pe+=oe*$t,Pe+=X*A,Pe+=Q*kt,Pe+=ue*It,Pe+=nt*Ct,$e+=Pe>>>13,Pe&=8191,$e=($e<<2)+$e|0,$e=$e+ft|0,ft=$e&8191,$e=$e>>>13,pt+=$e,qe=ft,Ve=pt,Ee=Et,L=At,D=mt,oe=bt,X=gt,Q=Ue,ue=Ye,nt=Pe,b+=16,x-=16;this.h[0]=qe,this.h[1]=Ve,this.h[2]=Ee,this.h[3]=L,this.h[4]=D,this.h[5]=oe,this.h[6]=X,this.h[7]=Q,this.h[8]=ue,this.h[9]=nt},ct.prototype.finish=function(g,b){var x=new Uint16Array(10),h,w,R,N;if(this.leftover){for(N=this.leftover,this.buffer[N++]=1;N<16;N++)this.buffer[N]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(h=this.h[1]>>>13,this.h[1]&=8191,N=2;N<10;N++)this.h[N]+=h,h=this.h[N]>>>13,this.h[N]&=8191;for(this.h[0]+=h*5,h=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=h,h=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=h,x[0]=this.h[0]+5,h=x[0]>>>13,x[0]&=8191,N=1;N<10;N++)x[N]=this.h[N]+h,h=x[N]>>>13,x[N]&=8191;for(x[9]-=8192,w=(h^1)-1,N=0;N<10;N++)x[N]&=w;for(w=~w,N=0;N<10;N++)this.h[N]=this.h[N]&w|x[N];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,R=this.h[0]+this.pad[0],this.h[0]=R&65535,N=1;N<8;N++)R=(this.h[N]+this.pad[N]|0)+(R>>>16)|0,this.h[N]=R&65535;g[b+0]=this.h[0]>>>0&255,g[b+1]=this.h[0]>>>8&255,g[b+2]=this.h[1]>>>0&255,g[b+3]=this.h[1]>>>8&255,g[b+4]=this.h[2]>>>0&255,g[b+5]=this.h[2]>>>8&255,g[b+6]=this.h[3]>>>0&255,g[b+7]=this.h[3]>>>8&255,g[b+8]=this.h[4]>>>0&255,g[b+9]=this.h[4]>>>8&255,g[b+10]=this.h[5]>>>0&255,g[b+11]=this.h[5]>>>8&255,g[b+12]=this.h[6]>>>0&255,g[b+13]=this.h[6]>>>8&255,g[b+14]=this.h[7]>>>0&255,g[b+15]=this.h[7]>>>8&255},ct.prototype.update=function(g,b,x){var h,w;if(this.leftover){for(w=16-this.leftover,w>x&&(w=x),h=0;h<w;h++)this.buffer[this.leftover+h]=g[b+h];if(x-=w,b+=w,this.leftover+=w,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(x>=16&&(w=x-x%16,this.blocks(g,b,w),b+=w,x-=w),x){for(h=0;h<x;h++)this.buffer[this.leftover+h]=g[b+h];this.leftover+=x}};function ut(g,b,x,h,w,R){var N=new ct(R);return N.update(x,h,w),N.finish(g,b),0}function ze(g,b,x,h,w,R){var N=new Uint8Array(16);return ut(N,0,x,h,w,R),y(g,b,N,0)}function z(g,b,x,h,w){var R;if(x<32)return-1;for(J(g,0,b,0,x,h,w),ut(g,16,g,32,x-32,g),R=0;R<16;R++)g[R]=0;return 0}function $(g,b,x,h,w){var R,N=new Uint8Array(32);if(x<32||(he(N,0,32,h,w),ze(b,16,b,32,x-32,N)!==0))return-1;for(J(g,0,b,0,x,h,w),R=0;R<32;R++)g[R]=0;return 0}function U(g,b){var x;for(x=0;x<16;x++)g[x]=b[x]|0}function be(g){var b,x,h=1;for(b=0;b<16;b++)x=g[b]+h+65535,h=Math.floor(x/65536),g[b]=x-h*65536;g[0]+=h-1+37*(h-1)}function ke(g,b,x){for(var h,w=~(x-1),R=0;R<16;R++)h=w&(g[R]^b[R]),g[R]^=h,b[R]^=h}function Le(g,b){var x,h,w,R=e(),N=e();for(x=0;x<16;x++)N[x]=b[x];for(be(N),be(N),be(N),h=0;h<2;h++){for(R[0]=N[0]-65517,x=1;x<15;x++)R[x]=N[x]-65535-(R[x-1]>>16&1),R[x-1]&=65535;R[15]=N[15]-32767-(R[14]>>16&1),w=R[15]>>16&1,R[14]&=65535,ke(N,R,1-w)}for(x=0;x<16;x++)g[2*x]=N[x]&255,g[2*x+1]=N[x]>>8}function k(g,b){var x=new Uint8Array(32),h=new Uint8Array(32);return Le(x,g),Le(h,b),_(x,0,h,0)}function P(g){var b=new Uint8Array(32);return Le(b,g),b[0]&1}function Z(g,b){var x;for(x=0;x<16;x++)g[x]=b[2*x]+(b[2*x+1]<<8);g[15]&=32767}function I(g,b,x){for(var h=0;h<16;h++)g[h]=b[h]+x[h]}function M(g,b,x){for(var h=0;h<16;h++)g[h]=b[h]-x[h]}function fe(g,b,x){var h,w,R=0,N=0,Y=0,me=0,Ke=0,Te=0,sr=0,$e=0,ft=0,pt=0,Et=0,At=0,mt=0,bt=0,gt=0,Ue=0,Ye=0,Pe=0,qe=0,Ve=0,Ee=0,L=0,D=0,oe=0,X=0,Q=0,ue=0,nt=0,Ct=0,It=0,kt=0,A=x[0],$t=x[1],ir=x[2],or=x[3],Ot=x[4],Xt=x[5],Jt=x[6],fn=x[7],pr=x[8],rn=x[9],nn=x[10],sn=x[11],vn=x[12],Qn=x[13],es=x[14],ts=x[15];h=b[0],R+=h*A,N+=h*$t,Y+=h*ir,me+=h*or,Ke+=h*Ot,Te+=h*Xt,sr+=h*Jt,$e+=h*fn,ft+=h*pr,pt+=h*rn,Et+=h*nn,At+=h*sn,mt+=h*vn,bt+=h*Qn,gt+=h*es,Ue+=h*ts,h=b[1],N+=h*A,Y+=h*$t,me+=h*ir,Ke+=h*or,Te+=h*Ot,sr+=h*Xt,$e+=h*Jt,ft+=h*fn,pt+=h*pr,Et+=h*rn,At+=h*nn,mt+=h*sn,bt+=h*vn,gt+=h*Qn,Ue+=h*es,Ye+=h*ts,h=b[2],Y+=h*A,me+=h*$t,Ke+=h*ir,Te+=h*or,sr+=h*Ot,$e+=h*Xt,ft+=h*Jt,pt+=h*fn,Et+=h*pr,At+=h*rn,mt+=h*nn,bt+=h*sn,gt+=h*vn,Ue+=h*Qn,Ye+=h*es,Pe+=h*ts,h=b[3],me+=h*A,Ke+=h*$t,Te+=h*ir,sr+=h*or,$e+=h*Ot,ft+=h*Xt,pt+=h*Jt,Et+=h*fn,At+=h*pr,mt+=h*rn,bt+=h*nn,gt+=h*sn,Ue+=h*vn,Ye+=h*Qn,Pe+=h*es,qe+=h*ts,h=b[4],Ke+=h*A,Te+=h*$t,sr+=h*ir,$e+=h*or,ft+=h*Ot,pt+=h*Xt,Et+=h*Jt,At+=h*fn,mt+=h*pr,bt+=h*rn,gt+=h*nn,Ue+=h*sn,Ye+=h*vn,Pe+=h*Qn,qe+=h*es,Ve+=h*ts,h=b[5],Te+=h*A,sr+=h*$t,$e+=h*ir,ft+=h*or,pt+=h*Ot,Et+=h*Xt,At+=h*Jt,mt+=h*fn,bt+=h*pr,gt+=h*rn,Ue+=h*nn,Ye+=h*sn,Pe+=h*vn,qe+=h*Qn,Ve+=h*es,Ee+=h*ts,h=b[6],sr+=h*A,$e+=h*$t,ft+=h*ir,pt+=h*or,Et+=h*Ot,At+=h*Xt,mt+=h*Jt,bt+=h*fn,gt+=h*pr,Ue+=h*rn,Ye+=h*nn,Pe+=h*sn,qe+=h*vn,Ve+=h*Qn,Ee+=h*es,L+=h*ts,h=b[7],$e+=h*A,ft+=h*$t,pt+=h*ir,Et+=h*or,At+=h*Ot,mt+=h*Xt,bt+=h*Jt,gt+=h*fn,Ue+=h*pr,Ye+=h*rn,Pe+=h*nn,qe+=h*sn,Ve+=h*vn,Ee+=h*Qn,L+=h*es,D+=h*ts,h=b[8],ft+=h*A,pt+=h*$t,Et+=h*ir,At+=h*or,mt+=h*Ot,bt+=h*Xt,gt+=h*Jt,Ue+=h*fn,Ye+=h*pr,Pe+=h*rn,qe+=h*nn,Ve+=h*sn,Ee+=h*vn,L+=h*Qn,D+=h*es,oe+=h*ts,h=b[9],pt+=h*A,Et+=h*$t,At+=h*ir,mt+=h*or,bt+=h*Ot,gt+=h*Xt,Ue+=h*Jt,Ye+=h*fn,Pe+=h*pr,qe+=h*rn,Ve+=h*nn,Ee+=h*sn,L+=h*vn,D+=h*Qn,oe+=h*es,X+=h*ts,h=b[10],Et+=h*A,At+=h*$t,mt+=h*ir,bt+=h*or,gt+=h*Ot,Ue+=h*Xt,Ye+=h*Jt,Pe+=h*fn,qe+=h*pr,Ve+=h*rn,Ee+=h*nn,L+=h*sn,D+=h*vn,oe+=h*Qn,X+=h*es,Q+=h*ts,h=b[11],At+=h*A,mt+=h*$t,bt+=h*ir,gt+=h*or,Ue+=h*Ot,Ye+=h*Xt,Pe+=h*Jt,qe+=h*fn,Ve+=h*pr,Ee+=h*rn,L+=h*nn,D+=h*sn,oe+=h*vn,X+=h*Qn,Q+=h*es,ue+=h*ts,h=b[12],mt+=h*A,bt+=h*$t,gt+=h*ir,Ue+=h*or,Ye+=h*Ot,Pe+=h*Xt,qe+=h*Jt,Ve+=h*fn,Ee+=h*pr,L+=h*rn,D+=h*nn,oe+=h*sn,X+=h*vn,Q+=h*Qn,ue+=h*es,nt+=h*ts,h=b[13],bt+=h*A,gt+=h*$t,Ue+=h*ir,Ye+=h*or,Pe+=h*Ot,qe+=h*Xt,Ve+=h*Jt,Ee+=h*fn,L+=h*pr,D+=h*rn,oe+=h*nn,X+=h*sn,Q+=h*vn,ue+=h*Qn,nt+=h*es,Ct+=h*ts,h=b[14],gt+=h*A,Ue+=h*$t,Ye+=h*ir,Pe+=h*or,qe+=h*Ot,Ve+=h*Xt,Ee+=h*Jt,L+=h*fn,D+=h*pr,oe+=h*rn,X+=h*nn,Q+=h*sn,ue+=h*vn,nt+=h*Qn,Ct+=h*es,It+=h*ts,h=b[15],Ue+=h*A,Ye+=h*$t,Pe+=h*ir,qe+=h*or,Ve+=h*Ot,Ee+=h*Xt,L+=h*Jt,D+=h*fn,oe+=h*pr,X+=h*rn,Q+=h*nn,ue+=h*sn,nt+=h*vn,Ct+=h*Qn,It+=h*es,kt+=h*ts,R+=38*Ye,N+=38*Pe,Y+=38*qe,me+=38*Ve,Ke+=38*Ee,Te+=38*L,sr+=38*D,$e+=38*oe,ft+=38*X,pt+=38*Q,Et+=38*ue,At+=38*nt,mt+=38*Ct,bt+=38*It,gt+=38*kt,w=1,h=R+w+65535,w=Math.floor(h/65536),R=h-w*65536,h=N+w+65535,w=Math.floor(h/65536),N=h-w*65536,h=Y+w+65535,w=Math.floor(h/65536),Y=h-w*65536,h=me+w+65535,w=Math.floor(h/65536),me=h-w*65536,h=Ke+w+65535,w=Math.floor(h/65536),Ke=h-w*65536,h=Te+w+65535,w=Math.floor(h/65536),Te=h-w*65536,h=sr+w+65535,w=Math.floor(h/65536),sr=h-w*65536,h=$e+w+65535,w=Math.floor(h/65536),$e=h-w*65536,h=ft+w+65535,w=Math.floor(h/65536),ft=h-w*65536,h=pt+w+65535,w=Math.floor(h/65536),pt=h-w*65536,h=Et+w+65535,w=Math.floor(h/65536),Et=h-w*65536,h=At+w+65535,w=Math.floor(h/65536),At=h-w*65536,h=mt+w+65535,w=Math.floor(h/65536),mt=h-w*65536,h=bt+w+65535,w=Math.floor(h/65536),bt=h-w*65536,h=gt+w+65535,w=Math.floor(h/65536),gt=h-w*65536,h=Ue+w+65535,w=Math.floor(h/65536),Ue=h-w*65536,R+=w-1+37*(w-1),w=1,h=R+w+65535,w=Math.floor(h/65536),R=h-w*65536,h=N+w+65535,w=Math.floor(h/65536),N=h-w*65536,h=Y+w+65535,w=Math.floor(h/65536),Y=h-w*65536,h=me+w+65535,w=Math.floor(h/65536),me=h-w*65536,h=Ke+w+65535,w=Math.floor(h/65536),Ke=h-w*65536,h=Te+w+65535,w=Math.floor(h/65536),Te=h-w*65536,h=sr+w+65535,w=Math.floor(h/65536),sr=h-w*65536,h=$e+w+65535,w=Math.floor(h/65536),$e=h-w*65536,h=ft+w+65535,w=Math.floor(h/65536),ft=h-w*65536,h=pt+w+65535,w=Math.floor(h/65536),pt=h-w*65536,h=Et+w+65535,w=Math.floor(h/65536),Et=h-w*65536,h=At+w+65535,w=Math.floor(h/65536),At=h-w*65536,h=mt+w+65535,w=Math.floor(h/65536),mt=h-w*65536,h=bt+w+65535,w=Math.floor(h/65536),bt=h-w*65536,h=gt+w+65535,w=Math.floor(h/65536),gt=h-w*65536,h=Ue+w+65535,w=Math.floor(h/65536),Ue=h-w*65536,R+=w-1+37*(w-1),g[0]=R,g[1]=N,g[2]=Y,g[3]=me,g[4]=Ke,g[5]=Te,g[6]=sr,g[7]=$e,g[8]=ft,g[9]=pt,g[10]=Et,g[11]=At,g[12]=mt,g[13]=bt,g[14]=gt,g[15]=Ue}function ye(g,b){fe(g,b,b)}function xt(g,b){var x=e(),h;for(h=0;h<16;h++)x[h]=b[h];for(h=253;h>=0;h--)ye(x,x),h!==2&&h!==4&&fe(x,x,b);for(h=0;h<16;h++)g[h]=x[h]}function Rt(g,b){var x=e(),h;for(h=0;h<16;h++)x[h]=b[h];for(h=250;h>=0;h--)ye(x,x),h!==1&&fe(x,x,b);for(h=0;h<16;h++)g[h]=x[h]}function cr(g,b,x){var h=new Uint8Array(32),w=new Float64Array(80),R,N,Y=e(),me=e(),Ke=e(),Te=e(),sr=e(),$e=e();for(N=0;N<31;N++)h[N]=b[N];for(h[31]=b[31]&127|64,h[0]&=248,Z(w,x),N=0;N<16;N++)me[N]=w[N],Te[N]=Y[N]=Ke[N]=0;for(Y[0]=Te[0]=1,N=254;N>=0;--N)R=h[N>>>3]>>>(N&7)&1,ke(Y,me,R),ke(Ke,Te,R),I(sr,Y,Ke),M(Y,Y,Ke),I(Ke,me,Te),M(me,me,Te),ye(Te,sr),ye($e,Y),fe(Y,Ke,Y),fe(Ke,me,sr),I(sr,Y,Ke),M(Y,Y,Ke),ye(me,Y),M(Ke,Te,$e),fe(Y,Ke,a),I(Y,Y,Te),fe(Ke,Ke,Y),fe(Y,Te,$e),fe(Te,me,w),ye(me,sr),ke(Y,me,R),ke(Ke,Te,R);for(N=0;N<16;N++)w[N+16]=Y[N],w[N+32]=Ke[N],w[N+48]=me[N],w[N+64]=Te[N];var ft=w.subarray(32),pt=w.subarray(16);return xt(ft,ft),fe(pt,pt,ft),Le(g,pt),0}function zt(g,b){return cr(g,b,s)}function lr(g,b){return r(b,32),zt(g,b)}function xi(g,b,x){var h=new Uint8Array(32);return cr(h,x,b),B(g,n,h,G)}var bi=z,hl=$;function HC(g,b,x,h,w,R){var N=new Uint8Array(32);return xi(N,w,R),bi(g,b,x,h,N)}function gm(g,b,x,h,w,R){var N=new Uint8Array(32);return xi(N,w,R),hl(g,b,x,h,N)}var ym=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function xm(g,b,x,h){for(var w=new Int32Array(16),R=new Int32Array(16),N,Y,me,Ke,Te,sr,$e,ft,pt,Et,At,mt,bt,gt,Ue,Ye,Pe,qe,Ve,Ee,L,D,oe,X,Q,ue,nt=g[0],Ct=g[1],It=g[2],kt=g[3],A=g[4],$t=g[5],ir=g[6],or=g[7],Ot=b[0],Xt=b[1],Jt=b[2],fn=b[3],pr=b[4],rn=b[5],nn=b[6],sn=b[7],vn=0;h>=128;){for(Ve=0;Ve<16;Ve++)Ee=8*Ve+vn,w[Ve]=x[Ee+0]<<24|x[Ee+1]<<16|x[Ee+2]<<8|x[Ee+3],R[Ve]=x[Ee+4]<<24|x[Ee+5]<<16|x[Ee+6]<<8|x[Ee+7];for(Ve=0;Ve<80;Ve++)if(N=nt,Y=Ct,me=It,Ke=kt,Te=A,sr=$t,$e=ir,ft=or,pt=Ot,Et=Xt,At=Jt,mt=fn,bt=pr,gt=rn,Ue=nn,Ye=sn,L=or,D=sn,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=(A>>>14|pr<<18)^(A>>>18|pr<<14)^(pr>>>9|A<<23),D=(pr>>>14|A<<18)^(pr>>>18|A<<14)^(A>>>9|pr<<23),oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,L=A&$t^~A&ir,D=pr&rn^~pr&nn,oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,L=ym[Ve*2],D=ym[Ve*2+1],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,L=w[Ve%16],D=R[Ve%16],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,Pe=Q&65535|ue<<16,qe=oe&65535|X<<16,L=Pe,D=qe,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=(nt>>>28|Ot<<4)^(Ot>>>2|nt<<30)^(Ot>>>7|nt<<25),D=(Ot>>>28|nt<<4)^(nt>>>2|Ot<<30)^(nt>>>7|Ot<<25),oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,L=nt&Ct^nt&It^Ct&It,D=Ot&Xt^Ot&Jt^Xt&Jt,oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,ft=Q&65535|ue<<16,Ye=oe&65535|X<<16,L=Ke,D=mt,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=Pe,D=qe,oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,Ke=Q&65535|ue<<16,mt=oe&65535|X<<16,Ct=N,It=Y,kt=me,A=Ke,$t=Te,ir=sr,or=$e,nt=ft,Xt=pt,Jt=Et,fn=At,pr=mt,rn=bt,nn=gt,sn=Ue,Ot=Ye,Ve%16===15)for(Ee=0;Ee<16;Ee++)L=w[Ee],D=R[Ee],oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=w[(Ee+9)%16],D=R[(Ee+9)%16],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,Pe=w[(Ee+1)%16],qe=R[(Ee+1)%16],L=(Pe>>>1|qe<<31)^(Pe>>>8|qe<<24)^Pe>>>7,D=(qe>>>1|Pe<<31)^(qe>>>8|Pe<<24)^(qe>>>7|Pe<<25),oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,Pe=w[(Ee+14)%16],qe=R[(Ee+14)%16],L=(Pe>>>19|qe<<13)^(qe>>>29|Pe<<3)^Pe>>>6,D=(qe>>>19|Pe<<13)^(Pe>>>29|qe<<3)^(qe>>>6|Pe<<26),oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,w[Ee]=Q&65535|ue<<16,R[Ee]=oe&65535|X<<16;L=nt,D=Ot,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=g[0],D=b[0],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,g[0]=nt=Q&65535|ue<<16,b[0]=Ot=oe&65535|X<<16,L=Ct,D=Xt,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=g[1],D=b[1],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,g[1]=Ct=Q&65535|ue<<16,b[1]=Xt=oe&65535|X<<16,L=It,D=Jt,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=g[2],D=b[2],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,g[2]=It=Q&65535|ue<<16,b[2]=Jt=oe&65535|X<<16,L=kt,D=fn,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=g[3],D=b[3],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,g[3]=kt=Q&65535|ue<<16,b[3]=fn=oe&65535|X<<16,L=A,D=pr,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=g[4],D=b[4],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,g[4]=A=Q&65535|ue<<16,b[4]=pr=oe&65535|X<<16,L=$t,D=rn,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=g[5],D=b[5],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,g[5]=$t=Q&65535|ue<<16,b[5]=rn=oe&65535|X<<16,L=ir,D=nn,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=g[6],D=b[6],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,g[6]=ir=Q&65535|ue<<16,b[6]=nn=oe&65535|X<<16,L=or,D=sn,oe=D&65535,X=D>>>16,Q=L&65535,ue=L>>>16,L=g[7],D=b[7],oe+=D&65535,X+=D>>>16,Q+=L&65535,ue+=L>>>16,X+=oe>>>16,Q+=X>>>16,ue+=Q>>>16,g[7]=or=Q&65535|ue<<16,b[7]=sn=oe&65535|X<<16,vn+=128,h-=128}return h}function Bo(g,b,x){var h=new Int32Array(8),w=new Int32Array(8),R=new Uint8Array(256),N,Y=x;for(h[0]=1779033703,h[1]=3144134277,h[2]=1013904242,h[3]=2773480762,h[4]=1359893119,h[5]=2600822924,h[6]=528734635,h[7]=1541459225,w[0]=4089235720,w[1]=2227873595,w[2]=4271175723,w[3]=1595750129,w[4]=2917565137,w[5]=725511199,w[6]=4215389547,w[7]=327033209,xm(h,w,b,x),x%=128,N=0;N<x;N++)R[N]=b[Y-x+N];for(R[x]=128,x=256-128*(x<112?1:0),R[x-9]=0,p(R,x-8,Y/536870912|0,Y<<3),xm(h,w,R,x),N=0;N<8;N++)p(g,8*N,h[N],w[N]);return 0}function pl(g,b){var x=e(),h=e(),w=e(),R=e(),N=e(),Y=e(),me=e(),Ke=e(),Te=e();M(x,g[1],g[0]),M(Te,b[1],b[0]),fe(x,x,Te),I(h,g[0],g[1]),I(Te,b[0],b[1]),fe(h,h,Te),fe(w,g[3],b[3]),fe(w,w,u),fe(R,g[2],b[2]),I(R,R,R),M(N,h,x),M(Y,R,w),I(me,R,w),I(Ke,h,x),fe(g[0],N,Y),fe(g[1],Ke,me),fe(g[2],me,Y),fe(g[3],N,Ke)}function bm(g,b,x){var h;for(h=0;h<4;h++)ke(g[h],b[h],x)}function ml(g,b){var x=e(),h=e(),w=e();xt(w,b[2]),fe(x,b[0],w),fe(h,b[1],w),Le(g,h),g[31]^=P(x)<<7}function _m(g,b,x){var h,w;for(U(g[0],i),U(g[1],o),U(g[2],o),U(g[3],i),w=255;w>=0;--w)h=x[w/8|0]>>(w&7)&1,bm(g,b,h),pl(b,g),pl(g,g),bm(g,b,h)}function Wf(g,b){var x=[e(),e(),e(),e()];U(x[0],l),U(x[1],d),U(x[2],o),fe(x[3],l,d),_m(g,x,b)}function vm(g,b,x){var h=new Uint8Array(64),w=[e(),e(),e(),e()],R;for(x||r(b,32),Bo(h,b,32),h[0]&=248,h[31]&=127,h[31]|=64,Wf(w,h),ml(g,w),R=0;R<32;R++)b[R+32]=g[R];return 0}var Xf=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Ba(g,b){var x,h,w,R;for(h=63;h>=32;--h){for(x=0,w=h-32,R=h-12;w<R;++w)b[w]+=x-16*b[h]*Xf[w-(h-32)],x=Math.floor((b[w]+128)/256),b[w]-=x*256;b[w]+=x,b[h]=0}for(x=0,w=0;w<32;w++)b[w]+=x-(b[31]>>4)*Xf[w],x=b[w]>>8,b[w]&=255;for(w=0;w<32;w++)b[w]-=x*Xf[w];for(h=0;h<32;h++)b[h+1]+=b[h]>>8,g[h]=b[h]&255}function wm(g){var b=new Float64Array(64),x;for(x=0;x<64;x++)b[x]=g[x];for(x=0;x<64;x++)g[x]=0;Ba(g,b)}function m_(g,b,x,h){var w=new Uint8Array(64),R=new Uint8Array(64),N=new Uint8Array(64),Y,me,Ke=new Float64Array(64),Te=[e(),e(),e(),e()];Bo(w,h,32),w[0]&=248,w[31]&=127,w[31]|=64;var sr=x+64;for(Y=0;Y<x;Y++)g[64+Y]=b[Y];for(Y=0;Y<32;Y++)g[32+Y]=w[32+Y];for(Bo(N,g.subarray(32),x+32),wm(N),Wf(Te,N),ml(g,Te),Y=32;Y<64;Y++)g[Y]=h[Y];for(Bo(R,g,x+64),wm(R),Y=0;Y<64;Y++)Ke[Y]=0;for(Y=0;Y<32;Y++)Ke[Y]=N[Y];for(Y=0;Y<32;Y++)for(me=0;me<32;me++)Ke[Y+me]+=R[Y]*w[me];return Ba(g.subarray(32),Ke),sr}function FC(g,b){var x=e(),h=e(),w=e(),R=e(),N=e(),Y=e(),me=e();return U(g[2],o),Z(g[1],b),ye(w,g[1]),fe(R,w,c),M(w,w,g[2]),I(R,g[2],R),ye(N,R),ye(Y,N),fe(me,Y,N),fe(x,me,w),fe(x,x,R),Rt(x,x),fe(x,x,w),fe(x,x,R),fe(x,x,R),fe(g[0],x,R),ye(h,g[0]),fe(h,h,R),k(h,w)&&fe(g[0],g[0],f),ye(h,g[0]),fe(h,h,R),k(h,w)?-1:(P(g[0])===b[31]>>7&&M(g[0],i,g[0]),fe(g[3],g[0],g[1]),0)}function gl(g,b,x,h){var w,R=new Uint8Array(32),N=new Uint8Array(64),Y=[e(),e(),e(),e()],me=[e(),e(),e(),e()];if(x<64||FC(me,h))return-1;for(w=0;w<x;w++)g[w]=b[w];for(w=0;w<32;w++)g[w+32]=h[w];if(Bo(N,g,x),wm(N),_m(Y,me,N),Wf(me,b.subarray(32)),pl(Y,me),ml(R,Y),x-=64,_(b,0,R,0)){for(w=0;w<x;w++)g[w]=0;return-1}for(w=0;w<x;w++)g[w]=b[w+64];return x}var O=32,j=24,W=32,pe=16,Ge=32,Ir=32,$r=32,St=32,we=32,Re=j,De=W,Fe=pe,ht=64,nr=32,br=64,ps=32,Jf=64;t.lowlevel={crypto_core_hsalsa20:B,crypto_stream_xor:J,crypto_stream:he,crypto_stream_salsa20_xor:se,crypto_stream_salsa20:_e,crypto_onetimeauth:ut,crypto_onetimeauth_verify:ze,crypto_verify_16:y,crypto_verify_32:_,crypto_secretbox:z,crypto_secretbox_open:$,crypto_scalarmult:cr,crypto_scalarmult_base:zt,crypto_box_beforenm:xi,crypto_box_afternm:bi,crypto_box:HC,crypto_box_open:gm,crypto_box_keypair:lr,crypto_hash:Bo,crypto_sign:m_,crypto_sign_keypair:vm,crypto_sign_open:gl,crypto_secretbox_KEYBYTES:O,crypto_secretbox_NONCEBYTES:j,crypto_secretbox_ZEROBYTES:W,crypto_secretbox_BOXZEROBYTES:pe,crypto_scalarmult_BYTES:Ge,crypto_scalarmult_SCALARBYTES:Ir,crypto_box_PUBLICKEYBYTES:$r,crypto_box_SECRETKEYBYTES:St,crypto_box_BEFORENMBYTES:we,crypto_box_NONCEBYTES:Re,crypto_box_ZEROBYTES:De,crypto_box_BOXZEROBYTES:Fe,crypto_sign_BYTES:ht,crypto_sign_PUBLICKEYBYTES:nr,crypto_sign_SECRETKEYBYTES:br,crypto_sign_SEEDBYTES:ps,crypto_hash_BYTES:Jf,gf:e,D:c,L:Xf,pack25519:Le,unpack25519:Z,M:fe,A:I,S:ye,Z:M,pow2523:Rt,add:pl,set25519:U,modL:Ba,scalarmult:_m,scalarbase:Wf};function g_(g,b){if(g.length!==O)throw new Error("bad key size");if(b.length!==j)throw new Error("bad nonce size")}function VC(g,b){if(g.length!==$r)throw new Error("bad public key size");if(b.length!==St)throw new Error("bad secret key size")}function ei(){for(var g=0;g<arguments.length;g++)if(!(arguments[g]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function EB(g){for(var b=0;b<g.length;b++)g[b]=0}t.randomBytes=function(g){var b=new Uint8Array(g);return r(b,g),b},t.secretbox=function(g,b,x){ei(g,b,x),g_(x,b);for(var h=new Uint8Array(W+g.length),w=new Uint8Array(h.length),R=0;R<g.length;R++)h[R+W]=g[R];return z(w,h,h.length,b,x),w.subarray(pe)},t.secretbox.open=function(g,b,x){ei(g,b,x),g_(x,b);for(var h=new Uint8Array(pe+g.length),w=new Uint8Array(h.length),R=0;R<g.length;R++)h[R+pe]=g[R];return h.length<32||$(w,h,h.length,b,x)!==0?null:w.subarray(W)},t.secretbox.keyLength=O,t.secretbox.nonceLength=j,t.secretbox.overheadLength=pe,t.scalarMult=function(g,b){if(ei(g,b),g.length!==Ir)throw new Error("bad n size");if(b.length!==Ge)throw new Error("bad p size");var x=new Uint8Array(Ge);return cr(x,g,b),x},t.scalarMult.base=function(g){if(ei(g),g.length!==Ir)throw new Error("bad n size");var b=new Uint8Array(Ge);return zt(b,g),b},t.scalarMult.scalarLength=Ir,t.scalarMult.groupElementLength=Ge,t.box=function(g,b,x,h){var w=t.box.before(x,h);return t.secretbox(g,b,w)},t.box.before=function(g,b){ei(g,b),VC(g,b);var x=new Uint8Array(we);return xi(x,g,b),x},t.box.after=t.secretbox,t.box.open=function(g,b,x,h){var w=t.box.before(x,h);return t.secretbox.open(g,b,w)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var g=new Uint8Array($r),b=new Uint8Array(St);return lr(g,b),{publicKey:g,secretKey:b}},t.box.keyPair.fromSecretKey=function(g){if(ei(g),g.length!==St)throw new Error("bad secret key size");var b=new Uint8Array($r);return zt(b,g),{publicKey:b,secretKey:new Uint8Array(g)}},t.box.publicKeyLength=$r,t.box.secretKeyLength=St,t.box.sharedKeyLength=we,t.box.nonceLength=Re,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(g,b){if(ei(g,b),b.length!==br)throw new Error("bad secret key size");var x=new Uint8Array(ht+g.length);return m_(x,g,g.length,b),x},t.sign.open=function(g,b){if(ei(g,b),b.length!==nr)throw new Error("bad public key size");var x=new Uint8Array(g.length),h=gl(x,g,g.length,b);if(h<0)return null;for(var w=new Uint8Array(h),R=0;R<w.length;R++)w[R]=x[R];return w},t.sign.detached=function(g,b){for(var x=t.sign(g,b),h=new Uint8Array(ht),w=0;w<h.length;w++)h[w]=x[w];return h},t.sign.detached.verify=function(g,b,x){if(ei(g,b,x),b.length!==ht)throw new Error("bad signature size");if(x.length!==nr)throw new Error("bad public key size");var h=new Uint8Array(ht+g.length),w=new Uint8Array(ht+g.length),R;for(R=0;R<ht;R++)h[R]=b[R];for(R=0;R<g.length;R++)h[R+ht]=g[R];return gl(w,h,h.length,x)>=0},t.sign.keyPair=function(){var g=new Uint8Array(nr),b=new Uint8Array(br);return vm(g,b),{publicKey:g,secretKey:b}},t.sign.keyPair.fromSecretKey=function(g){if(ei(g),g.length!==br)throw new Error("bad secret key size");for(var b=new Uint8Array(nr),x=0;x<b.length;x++)b[x]=g[32+x];return{publicKey:b,secretKey:new Uint8Array(g)}},t.sign.keyPair.fromSeed=function(g){if(ei(g),g.length!==ps)throw new Error("bad seed size");for(var b=new Uint8Array(nr),x=new Uint8Array(br),h=0;h<32;h++)x[h]=g[h];return vm(b,x,!0),{publicKey:b,secretKey:x}},t.sign.publicKeyLength=nr,t.sign.secretKeyLength=br,t.sign.seedLength=ps,t.sign.signatureLength=ht,t.hash=function(g){ei(g);var b=new Uint8Array(Jf);return Bo(b,g,g.length),b},t.hash.hashLength=Jf,t.verify=function(g,b){return ei(g,b),g.length===0||b.length===0||g.length!==b.length?!1:m(g,0,b,0,g.length)===0},t.setPRNG=function(g){r=g},(function(){var g=typeof self<"u"?self.crypto||self.msCrypto:null;if(g&&g.getRandomValues){var b=65536;t.setPRNG(function(x,h){var w,R=new Uint8Array(h);for(w=0;w<h;w+=b)g.getRandomValues(R.subarray(w,w+Math.min(h-w,b)));for(w=0;w<h;w++)x[w]=R[w];EB(R)})}else typeof on<"u"&&(g=on("crypto"),g&&g.randomBytes&&t.setPRNG(function(x,h){var w,R=g.randomBytes(h);for(w=0;w<h;w++)x[w]=R[w];EB(R)}))})()})(typeof M_<"u"&&M_.exports?M_.exports:self.nacl=self.nacl||{})});var _k=v(bk=>{"use strict";Object.defineProperty(bk,"__esModule",{value:!0});var xk=class{constructor(e,r=0,n=0){this.start=r,this.end=n>r?n:r,this.buf=e}get length(){return this.buf.length}reset(e=0,r=0){return this.start=e,r>=this.start?this.end=r:this.end<this.start&&(this.end=this.start),this}walk(e){return this.start=this.end,this.end+=e,this}mustHas(e,r="Too few bytes to parse."){let n=this.end+e;if(n>this.buf.length){let s=new Error(r);throw s.available=this.buf.length,s.requested=n,s}return this.walk(0),this}mustWalk(e,r){return this.mustHas(e,r),this.walk(e),this}};bk.BufferVisitor=xk});var q$=v(Ak=>{"use strict";Object.defineProperty(Ak,"__esModule",{value:!0});var D$=on("util"),U$=64,wk="-----BEGIN ",Sk="-----END ",$m="-----",vk="Proc-Type",z_=class{static parse(e){let r=[],n=e.toString("utf8").split(`
|
|
65
|
+
`).map(s=>s.trim()).filter(s=>s!==""&&!s.startsWith("#"));for(;n.length>0;)r.push(xse(n));if(r.length===0)throw new Error("PEM: no block");return r}constructor(e,r){this.type=e,this.body=r,this.headers=Object.create(null)}get procType(){return this.getHeader(vk)}getHeader(e){let r=this.headers[e];return r??""}setHeader(e,r){if(e.includes(":"))throw new Error("pem: cannot encode a header key that contains a colon");if(e===""||r==="")throw new Error("pem: invalid header key or value");this.headers[e]=r}toString(){let e=wk+this.type+$m+`
|
|
66
|
+
`,r=Object.keys(this.headers);if(r.length>0){let i=this.procType;i!==""&&(e+=`${vk}: ${i}
|
|
67
|
+
`),r.sort();for(let o of r)o!==vk&&(e+=`${o}: ${this.headers[o]}
|
|
68
|
+
`);e+=`
|
|
69
|
+
`}let n=this.body.toString("base64"),s=0;for(;s<n.length;)e+=n.slice(s,s+U$)+`
|
|
70
|
+
`,s+=U$;return e+=Sk+this.type+$m+`
|
|
71
|
+
`,e}toBuffer(){return Buffer.from(this.toString(),"utf8")}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[D$.inspect.custom](e,r){return`<${this.constructor.name} ${D$.inspect(this.toJSON(),r)}>`}};Ak.PEM=z_;function xse(t){let e=t.shift();if(e==null||!e.startsWith(wk)||!e.endsWith($m))throw new Error("pem: invalid BEGIN line");let r=e.slice(wk.length,e.length-$m.length);if(r==="")throw new Error("pem: invalid type");let n=[];for(e=t.shift();e!=null&&e.includes(": ");){let o=e.split(": ");if(o.length!==2||o[0]===""||o[1]==="")throw new Error("pem: invalid Header line");n.push(o),e=t.shift()}let s="";for(;e!=null&&!e.startsWith(Sk);)s+=e,e=t.shift();if(e==null||e!==`${Sk}${r}${$m}`)throw new Error("pem: invalid END line");let i=new z_(r,Buffer.from(s,"base64"));if(s===""||i.body.toString("base64")!==s)throw new Error("pem: invalid base64 body");for(let o of n)i.setHeader(o[0],o[1]);return i}});var K$=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var H$=on("util"),L_=_k(),an;(function(t){t[t.UNIVERSAL=0]="UNIVERSAL",t[t.APPLICATION=64]="APPLICATION",t[t.CONTEXT_SPECIFIC=128]="CONTEXT_SPECIFIC",t[t.PRIVATE=192]="PRIVATE"})(an=Gc.Class||(Gc.Class={}));var Lt;(function(t){t[t.NONE=0]="NONE",t[t.BOOLEAN=1]="BOOLEAN",t[t.INTEGER=2]="INTEGER",t[t.BITSTRING=3]="BITSTRING",t[t.OCTETSTRING=4]="OCTETSTRING",t[t.NULL=5]="NULL",t[t.OID=6]="OID",t[t.ENUMERATED=10]="ENUMERATED",t[t.UTF8=12]="UTF8",t[t.SEQUENCE=16]="SEQUENCE",t[t.SET=17]="SET",t[t.NUMERICSTRING=18]="NUMERICSTRING",t[t.PRINTABLESTRING=19]="PRINTABLESTRING",t[t.T61STRING=20]="T61STRING",t[t.IA5STRING=22]="IA5STRING",t[t.UTCTIME=23]="UTCTIME",t[t.GENERALIZEDTIME=24]="GENERALIZEDTIME",t[t.GENERALSTRING=27]="GENERALSTRING"})(Lt=Gc.Tag||(Gc.Tag={}));var Mm=class{constructor(e,r){this.buf=e,this.bitLen=r}at(e){if(e<0||e>=this.bitLen||!Number.isInteger(e))return 0;let r=Math.floor(e/8),n=7-e%8;return this.buf[r]>>n&1}rightAlign(){let e=8-this.bitLen%8;if(e===8||this.buf.length===0)return this.buf;let r=Buffer.alloc(this.buf.length);r[0]=this.buf[0]>>e;for(let n=1;n<this.buf.length;n++)r[n]=this.buf[n-1]<<8-e,r[n]|=this.buf[n]>>e;return r}};Gc.BitString=Mm;var Ek=class t{static Bool(e){let r=new t(an.UNIVERSAL,Lt.BOOLEAN,Buffer.from([e?255:0]));return r._value=e,r}static parseBool(e){if(!(e instanceof Buffer)||e.length!==1)throw new Error("ASN1 syntax error: invalid boolean");switch(e[0]){case 0:return!1;case 255:return!0;default:throw new Error("ASN1 syntax error: invalid boolean")}}static Integer(e){if(e instanceof Buffer){let s=new t(an.UNIVERSAL,Lt.INTEGER,e);return s._value=e.toString("hex"),s}if(!Number.isSafeInteger(e))throw new Error("ASN1 syntax error: invalid integer");let r;if(e>=-128&&e<128)r=Buffer.alloc(1),r.writeInt8(e,0);else if(e>=-32768&&e<32768)r=Buffer.alloc(2),r.writeIntBE(e,0,2);else if(e>=-8388608&&e<8388608)r=Buffer.alloc(3),r.writeIntBE(e,0,3);else if(e>=-2147483648&&e<2147483648)r=Buffer.alloc(4),r.writeIntBE(e,0,4);else if(e>=-549755813888&&e<549755813888)r=Buffer.alloc(5),r.writeIntBE(e,0,5);else if(e>=-0x800000000000&&e<0x800000000000)r=Buffer.alloc(6),r.writeIntBE(e,0,6);else throw new Error("ASN1 syntax error: invalid Integer");let n=new t(an.UNIVERSAL,Lt.INTEGER,r);return n._value=e,n}static parseInteger(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Integer");return e.length>6?e.toString("hex"):e.readIntBE(0,e.length)}static parseIntegerNum(e){let r=t.parseInteger(e);if(typeof r!="number")throw new Error("ASN1 syntax error: invalid Integer number");return r}static parseIntegerStr(e){let r=t.parseInteger(e);return typeof r=="number"?r.toString(16):r}static BitString(e){e instanceof Buffer&&(e=new Mm(e,e.length*8));let r=e.buf.length*8-e.bitLen,n=Buffer.alloc(e.buf.length+1);return n.writeInt8(r,0),e.buf.copy(n,1),new t(an.UNIVERSAL,Lt.BITSTRING,n)}static parseBitString(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid BitString");let r=e[0];if(r>7||e.length===1&&r>0||(e[e.length-1]&(1<<e[0])-1)!==0)throw new Error("ASN1 syntax error: invalid padding bits in BIT STRING");return new Mm(e.slice(1),(e.length-1)*8-r)}static Null(){let e=new t(an.UNIVERSAL,Lt.NULL,Buffer.alloc(0));return e._value=null,e}static parseNull(e){if(!(e instanceof Buffer)||e.length!==0)throw new Error("ASN1 syntax error: invalid null");return null}static OID(e){let r=e.split(".");if(r.length===0)throw new Error("ASN1 syntax error: invalid Object Identifier");let n=[];n.push(40*wn(r[0])+wn(r[1]));let s=[];for(let o=2;o<r.length;++o){let a=wn(r[o]);for(s.length=0,s.push(a&127);a>127;)a=a>>>7,s.unshift(a&127|128);n.push(...s)}let i=new t(an.UNIVERSAL,Lt.OID,Buffer.from(n));return i._value=e,i}static parseOID(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid OID");let r=Math.floor(e[0]/40)+"."+e[0]%40,n=0;for(let s=1;s<e.length;s++)e[s]>=128?(n+=e[s]&127,n=n<<7):(r+="."+(n+e[s]),n=0);return r}static UTF8(e){let r=new t(an.UNIVERSAL,Lt.UTF8,Buffer.from(e,"utf8"));return r._value=e,r}static parseUTF8(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static NumericString(e){if(!F$(e))throw new Error("ASN1 syntax error: invalid NumericString");let r=new t(an.UNIVERSAL,Lt.NUMERICSTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseNumericString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let r=e.toString("utf8");if(!F$(r))throw new Error("ASN1 syntax error: invalid NumericString");return r}static PrintableString(e){let r=new t(an.UNIVERSAL,Lt.PRINTABLESTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parsePrintableString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static IA5String(e){if(!V$(e))throw new Error("ASN1 syntax error: invalid IA5String");let r=new t(an.UNIVERSAL,Lt.IA5STRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseIA5String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let r=e.toString("utf8");if(!V$(r))throw new Error("ASN1 syntax error: invalid IA5String");return r}static T61String(e){let r=new t(an.UNIVERSAL,Lt.T61STRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseT61String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static GeneralString(e){let r=new t(an.UNIVERSAL,Lt.GENERALSTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseGeneralString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static UTCTime(e){let r="",n=[];n.push((""+e.getUTCFullYear()).substr(2)),n.push(""+(e.getUTCMonth()+1)),n.push(""+e.getUTCDate()),n.push(""+e.getUTCHours()),n.push(""+e.getUTCMinutes()),n.push(""+e.getUTCSeconds());for(let i of n)i.length<2&&(r+="0"),r+=i;r+="Z";let s=new t(an.UNIVERSAL,Lt.UTCTIME,Buffer.from(r,"utf8"));return s._value=e,s}static parseUTCTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid UTC Time");let r=e.toString("utf8"),n=new Date,s=wn(r.substr(0,2));s=s>=50?1900+s:2e3+s;let i=wn(r.substr(2,2))-1,o=wn(r.substr(4,2)),a=wn(r.substr(6,2)),c=wn(r.substr(8,2)),u=0,l=0,d="";if(r.length>11&&(l=10,d=r.charAt(l),d!=="+"&&d!=="-"&&(u=wn(r.substr(10,2)),l+=2)),n.setUTCFullYear(s,i,o),n.setUTCHours(a,c,u,0),l>0&&(d=r.charAt(l),d==="+"||d==="-")){let f=wn(r.substr(l+1,2)),p=wn(r.substr(l+4,2)),m=f*60+p;m*=6e4,d==="+"?n.setTime(+n-m):n.setTime(+n+m)}return n}static GeneralizedTime(e){let r="",n=[];n.push(""+e.getUTCFullYear()),n.push(""+(e.getUTCMonth()+1)),n.push(""+e.getUTCDate()),n.push(""+e.getUTCHours()),n.push(""+e.getUTCMinutes()),n.push(""+e.getUTCSeconds());for(let i of n)i.length<2&&(r+="0"),r+=i;r+="Z";let s=new t(an.UNIVERSAL,Lt.GENERALIZEDTIME,Buffer.from(r,"utf8"));return s._value=e,s}static parseGeneralizedTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");let r=e.toString("utf8"),n=new Date,s=wn(r.substr(0,4)),i=wn(r.substr(4,2))-1,o=wn(r.substr(6,2)),a=wn(r.substr(8,2)),c=wn(r.substr(10,2)),u=wn(r.substr(12,2)),l=0,d=0,f=!1;r.charAt(r.length-1)==="Z"&&(f=!0);let p=r.length-5,m=r.charAt(p);if(m==="+"||m==="-"){let y=wn(r.substr(p+1,2)),_=wn(r.substr(p+4,2));d=y*60+_,d*=6e4,m==="+"&&(d*=-1),f=!0}return r.charAt(14)==="."&&(l=parseFloat(r.substr(14))*1e3),f?(n.setUTCFullYear(s,i,o),n.setUTCHours(a,c,u,l),n.setTime(+n+d)):(n.setFullYear(s,i,o),n.setHours(a,c,u,l)),n}static parseTime(e,r){switch(e){case Lt.UTCTIME:return t.parseUTCTime(r);case Lt.GENERALIZEDTIME:return t.parseGeneralizedTime(r);default:throw new Error("Invalid ASN1 time tag")}}static Set(e){let r=new t(an.UNIVERSAL,Lt.SET,Buffer.concat(e.map(n=>n.toDER())));return r._value=e,r}static Seq(e){let r=new t(an.UNIVERSAL,Lt.SEQUENCE,Buffer.concat(e.map(n=>n.toDER())));return r._value=e,r}static Spec(e,r,n=!0){let s=Array.isArray(r)?Buffer.concat(r.map(o=>o.toDER())):r.toDER();Array.isArray(r)&&(n=!0);let i=new t(an.CONTEXT_SPECIFIC,e,s,n);return i._value=r,i}static fromDER(e,r=!1){return t._fromDER(new L_.BufferVisitor(e),r)}static parseDER(e,r,n){let s=t._fromDER(new L_.BufferVisitor(e),!1);if(s.class!==r&&s.tag!==n)throw new Error(`invalid ASN.1 DER for class ${r} and tag ${n}`);return s}static parseDERWithTemplate(e,r){let n=t._fromDER(new L_.BufferVisitor(e),!0),s={},i=n.validate(r,s);if(i!=null)throw i.data=n,i;return s}static _parseCompound(e,r){let n=[],s=e.length,i=new L_.BufferVisitor(e),o=0;for(;o<s;){let a=i.end;n.push(t._fromDER(i,r)),o+=i.end-a}return n}static _fromDER(e,r){if(!(e.buf instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");e.mustWalk(1,"Too few bytes to read ASN.1 tag.");let n=e.start,s=e.buf[n],i=s&192,o=s&31,a=bse(e);if(e.mustHas(a),a!==0&&o===Lt.NULL)throw new Error("invalid value length or NULL tag.");e.mustWalk(a);let c=(s&32)===32,u=new t(i,o,e.buf.slice(e.start,e.end),c);return c&&r&&(u._value=t._parseCompound(u.bytes,r)),u._der=e.buf.slice(n,e.end),u}constructor(e,r,n,s=!1){this.class=e,this.tag=r,this.bytes=n,this.isCompound=s||r===Lt.SEQUENCE||r===Lt.SET,this._value=void 0,this._der=null}get value(){return this._value===void 0&&(this._value=this.valueOf()),this._value}get DER(){return this._der==null&&(this._der=this.toDER()),this._der}mustCompound(e="asn1 object value is not compound"){if(!this.isCompound||!Array.isArray(this.value)){let r=new Error(e);throw r.data=this.toJSON(),r}return this.value}equals(e){return!(!(e instanceof t)||this.class!==e.class||this.tag!==e.tag||this.isCompound!==e.isCompound||!this.bytes.equals(e.bytes))}toDER(){let e=this.class|this.tag;this.isCompound&&(e|=32);let r=_se(this.bytes.length),n=Buffer.allocUnsafe(2+r+this.bytes.length);return n.writeInt8(e,0),r===0?(n.writeUInt8(this.bytes.length,1),this.bytes.copy(n,2)):(n.writeUInt8(r|128,1),n.writeUIntBE(this.bytes.length,2,r),this.bytes.copy(n,2+r)),n}valueOf(){if(this.isCompound)return t._parseCompound(this.bytes,!1);if(this.class!==an.UNIVERSAL)return this.bytes;switch(this.tag){case Lt.BOOLEAN:return t.parseBool(this.bytes);case Lt.INTEGER:return t.parseInteger(this.bytes);case Lt.BITSTRING:return t.parseBitString(this.bytes);case Lt.NULL:return t.parseNull(this.bytes);case Lt.OID:return t.parseOID(this.bytes);case Lt.UTF8:return t.parseUTF8(this.bytes);case Lt.NUMERICSTRING:return t.parseNumericString(this.bytes);case Lt.PRINTABLESTRING:return t.parsePrintableString(this.bytes);case Lt.T61STRING:return t.parseT61String(this.bytes);case Lt.IA5STRING:return t.parseIA5String(this.bytes);case Lt.GENERALSTRING:return t.parseGeneralString(this.bytes);case Lt.UTCTIME:return t.parseUTCTime(this.bytes);case Lt.GENERALIZEDTIME:return t.parseGeneralizedTime(this.bytes);default:return this.bytes}}validate(e,r={}){if(this.class!==e.class)return new Error(`ASN.1 object validate failure for ${e.name} : error class ${an[this.class]}`);if(!(Array.isArray(e.tag)?e.tag:[e.tag]).includes(this.tag))return new Error(`ASN.1 object validate failure for ${e.name}: error tag ${Lt[this.tag]}`);if(e.capture!=null&&(r[e.capture]=this),Array.isArray(e.value)){let s=this.mustCompound(`${e.name} need compound ASN1 value`);for(let i=0,o=0;i<e.value.length;i++)if(s[o]!=null){let a=s[o].validate(e.value[i],r);if(a==null)o++;else if(e.value[i].optional!==!0)return a}else if(e.value[i].optional!==!0)return new Error(`ASN.1 object validate failure for ${e.value[i].name}: not exists`)}else if(e.value!=null){let s=this.tag===Lt.BITSTRING?this.bytes.slice(1):this.bytes;return t.fromDER(s).validate(e.value,r)}return null}toJSON(){let e=this.value;return Array.isArray(e)&&(e=e.map(r=>r.toJSON())),{class:an[this.class],tag:this.class===an.UNIVERSAL?Lt[this.tag]:this.tag,value:e}}[H$.inspect.custom](e,r){return r.depth<=2&&(r.depth=10),`<${this.constructor.name} ${H$.inspect(this.toJSON(),r)}>`}};Gc.ASN1=Ek;function bse(t){t.mustWalk(1,"Too few bytes to read ASN.1 value length.");let e=t.buf[t.start];if((e&128)===0)return e;let r=e&127;return t.mustWalk(r,"Too few bytes to read ASN.1 value length."),t.buf.readUIntBE(t.start,r)}function _se(t){if(t<=127)return 0;if(t<=255)return 1;if(t<=65535)return 2;if(t<=16777215)return 3;if(t<=4294967295)return 4;if(t<=0xffffffffff)return 5;if(t<=0xffffffffffff)return 6;throw new Error("invalid value length")}function F$(t){for(let e of t){let r=e.charCodeAt(0);if(r!==32&&(r<48||r>57))return!1}return!0}function V$(t){for(let e of t)if(e.charCodeAt(0)>=128)return!1;return!0}function wn(t,e=10){let r=parseInt(t,e);if(Number.isNaN(r))throw new Error(`Invalid numeric string "${t}" in radix ${e}.`);return r}});var Ck=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var vse=_k();Wc.BufferVisitor=vse.BufferVisitor;var wse=q$();Wc.PEM=wse.PEM;var D_=K$();Wc.ASN1=D_.ASN1;Wc.Class=D_.Class;Wc.Tag=D_.Tag;Wc.BitString=D_.BitString});var Pk=v(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var Jc=on("util"),jm=on("crypto"),Ik=j_(),ge=Ck(),rs=$_();Mo.publicKeyValidator={name:"PublicKeyInfo",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,capture:"publicKeyInfo",value:[{name:"PublicKeyInfo.AlgorithmIdentifier",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"PublicKeyAlgorithmIdentifier.algorithm",class:ge.Class.UNIVERSAL,tag:ge.Tag.OID,capture:"publicKeyOID"}]},{name:"PublicKeyInfo.PublicKey",class:ge.Class.UNIVERSAL,tag:ge.Tag.BITSTRING,capture:"publicKey"}]};Mo.privateKeyValidator={name:"PrivateKeyInfo",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,capture:"privateKeyInfo",value:[{name:"PrivateKeyInfo.Version",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.AlgorithmIdentifier",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"PrivateKeyAlgorithmIdentifier.algorithm",class:ge.Class.UNIVERSAL,tag:ge.Tag.OID,capture:"privateKeyOID"}]},{name:"PrivateKeyInfo.PrivateKey",class:ge.Class.UNIVERSAL,tag:ge.Tag.OCTETSTRING,capture:"privateKey"}]};var Sse={name:"RSAPublicKey",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"RSAPublicKey.modulus",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"publicKeyExponent"}]},Ase={name:"RSAPrivateKey",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"RSAPrivateKey.version",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"privateKeyCoefficient"}]},Ese=[rs.getOID("X25519"),rs.getOID("X448"),rs.getOID("Ed25519"),rs.getOID("Ed448")],ah=class t{constructor(e){let r={},n=e.validate(Mo.publicKeyValidator,r);if(n!=null)throw new Error("Cannot read X.509 public key: "+n.message);this.oid=ge.ASN1.parseOID(r.publicKeyOID.bytes),this.algo=rs.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=ge.ASN1.parseBitString(r.publicKey.bytes).buf,this._finalKey=this._keyRaw,this._finalPEM=""}static fromPEM(e){let r=ge.PEM.parse(e)[0];if(r.procType.includes("ENCRYPTED"))throw new Error("Could not convert public key from PEM, PEM is encrypted.");let n=ge.ASN1.fromDER(r.body,!0);switch(r.type){case"PUBLIC KEY":return new t(n);case"RSA PUBLIC KEY":let s=ge.ASN1.Seq([ge.ASN1.Seq([ge.ASN1.OID(rs.getOID("rsaEncryption")),ge.ASN1.Null()]),ge.ASN1.BitString(n.DER)]);return new t(s);default:throw new Error("Could not convert public key from PEM, recommend PKCS#8 PEM")}}static addVerifier(e,r){if(e=rs.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(t._verifiers[e]!=null)throw new Error(`Verifier ${e} exists`);t._verifiers[e]=r}get keyRaw(){return this._finalKey}verify(e,r,n){let s=t._verifiers[this.oid];if(s!=null){let o=jm.createHash(n).update(e).digest();return s.call(this,o,r)}let i=jm.createVerify(n);return i.update(e),i.verify(this.toPEM(),r)}getFingerprint(e,r="PublicKey"){let n;switch(r){case"PublicKeyInfo":n=this._pkcs8.DER;break;case"PublicKey":n=this._keyRaw;break;default:throw new Error(`Unknown fingerprint type "${r}".`)}let s=jm.createHash(e);return s.update(n),s.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new ge.PEM("PUBLIC KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{oid:this.oid,algo:this.algo,publicKey:this._keyRaw}}[Jc.inspect.custom](e,r){return`<${this.constructor.name} ${Jc.inspect(this.toJSON(),r)}>`}};ah._verifiers=Object.create(null);Mo.PublicKey=ah;var ch=class t{constructor(e){let r=Object.create(null),n=e.validate(Mo.privateKeyValidator,r);if(n!=null)throw new Error("Cannot read X.509 private key: "+n.message);if(this.version=ge.ASN1.parseIntegerNum(r.privateKeyVersion.bytes)+1,this.oid=ge.ASN1.parseOID(r.privateKeyOID.bytes),this.algo=rs.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=r.privateKey.bytes,this._publicKeyRaw=null,this._finalKey=this._keyRaw,this._finalPEM="",Ese.includes(this.oid)){if(this._finalKey=this._keyRaw=ge.ASN1.parseDER(this._keyRaw,ge.Class.UNIVERSAL,ge.Tag.OCTETSTRING).bytes,this.oid==="1.3.101.112"){let s=Ik.sign.keyPair.fromSeed(this._keyRaw);this._publicKeyRaw=Buffer.from(s.publicKey),this._finalKey=Buffer.from(s.secretKey)}else if(this.version===2)for(let s of e.mustCompound())s.class===ge.Class.CONTEXT_SPECIFIC&&s.tag===1&&(this._publicKeyRaw=ge.ASN1.parseBitString(s.bytes).buf,this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw]))}}static fromPEM(e){let r=ge.PEM.parse(e)[0];if(r.procType.includes("ENCRYPTED"))throw new Error("Could not convert private key from PEM, PEM is encrypted.");let n=ge.ASN1.fromDER(r.body,!0);switch(r.type){case"PRIVATE KEY":return new t(n);case"RSA PRIVATE KEY":return n=ge.ASN1.Seq([n.value[0],ge.ASN1.Seq([ge.ASN1.OID(rs.getOID("rsaEncryption")),ge.ASN1.Null()]),new ge.ASN1(ge.Class.UNIVERSAL,ge.Tag.OCTETSTRING,n.DER)]),new t(n);default:throw new Error("Could not convert private key from PEM, recommend PKCS#8 PEM")}}static addSigner(e,r){if(e=rs.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(t._signers[e]!=null)throw new Error(`Signer ${e} exists`);t._signers[e]=r}get keyRaw(){return this._finalKey}get publicKeyRaw(){return this._publicKeyRaw}sign(e,r){let n=t._signers[this.oid];if(n!=null){let i=jm.createHash(r).update(e).digest();return n.call(this,i)}let s=jm.createSign(r);return s.update(e),s.sign(this.toPEM())}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new ge.PEM("PRIVATE KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,privateKey:this._keyRaw,publicKey:this._publicKeyRaw}}[Jc.inspect.custom](e,r){return`<${this.constructor.name} ${Jc.inspect(this.toJSON(),r)}>`}};ch._signers=Object.create(null);Mo.PrivateKey=ch;var kk=class t extends ah{static fromPublicKey(e){return new t(e.toASN1())}constructor(e){if(super(e),rs.getOID(this.oid)!==rs.getOID("rsaEncryption"))throw new Error(`Invalid RSA public key, unknown OID: ${this.oid}`);let r=Object.create(null);this._pkcs1=ge.ASN1.fromDER(this._keyRaw,!0);let n=this._pkcs1.validate(Sse,r);if(n!=null)throw new Error("Cannot read RSA public key: "+n.message);this.modulus=ge.ASN1.parseIntegerStr(r.publicKeyModulus.bytes),this.exponent=ge.ASN1.parseIntegerNum(r.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new ge.PEM("RSA PUBLIC KEY",this._keyRaw).toString()),this._finalPEM}toPublicKeyPEM(){return new ge.PEM("PUBLIC KEY",this._pkcs8.DER).toString()}toJSON(){return{oid:this.oid,algo:this.algo,modulus:Xc(this.modulus),exponent:this.exponent}}[Jc.inspect.custom](e,r){return`<${this.constructor.name} ${Jc.inspect(this.toJSON(),r)}>`}};Mo.RSAPublicKey=kk;var Tk=class t extends ch{static fromPrivateKey(e){return new t(e.toASN1())}constructor(e){if(super(e),rs.getOID(this.oid)!==rs.getOID("rsaEncryption"))throw new Error(`Invalid RSA private key, unknown OID: ${this.oid}`);let r=Object.create(null);this._pkcs1=ge.ASN1.fromDER(this._keyRaw,!0);let n=this._pkcs1.validate(Ase,r);if(n!=null)throw new Error("Cannot read RSA private key: "+n.message);this.publicExponent=ge.ASN1.parseIntegerNum(r.privateKeyPublicExponent.bytes),this.privateExponent=ge.ASN1.parseIntegerStr(r.privateKeyPrivateExponent.bytes),this.modulus=ge.ASN1.parseIntegerStr(r.privateKeyModulus.bytes),this.prime1=ge.ASN1.parseIntegerStr(r.privateKeyPrime1.bytes),this.prime2=ge.ASN1.parseIntegerStr(r.privateKeyPrime2.bytes),this.exponent1=ge.ASN1.parseIntegerStr(r.privateKeyExponent1.bytes),this.exponent2=ge.ASN1.parseIntegerStr(r.privateKeyExponent2.bytes),this.coefficient=ge.ASN1.parseIntegerStr(r.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new ge.PEM("RSA PRIVATE KEY",this._keyRaw).toString()),this._finalPEM}toPrivateKeyPEM(){return new ge.PEM("PRIVATE KEY",this._pkcs8.DER).toString()}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,publicExponent:this.publicExponent,privateExponent:Xc(this.privateExponent),modulus:Xc(this.modulus),prime1:Xc(this.prime1),prime2:Xc(this.prime2),exponent1:Xc(this.exponent1),exponent2:Xc(this.exponent2),coefficient:Xc(this.coefficient)}}[Jc.inspect.custom](e,r){return`<${this.constructor.name} ${Jc.inspect(this.toJSON(),r)}>`}};Mo.RSAPrivateKey=Tk;function Xc(t){return t.length%8!==0&&t.startsWith("00")?t.slice(2):t}ah.addVerifier(rs.getOID("Ed25519"),function(t,e){return Ik.sign.detached.verify(t,e,this.keyRaw)});ch.addSigner(rs.getOID("Ed25519"),function(t){let e=this.keyRaw;if(e.length!==64)throw new Error("Invalid signing key.");return Buffer.from(Ik.sign.detached(t,e))})});var Y$=v(U_=>{"use strict";Object.defineProperty(U_,"__esModule",{value:!0});var Z$=on("util"),Cse=on("crypto"),ae=Ck(),ns=$_(),J$=Pk(),Sn=Object.create(null);Sn.CN=ns.getOID("commonName");Sn.commonName="CN";Sn.C=ns.getOID("countryName");Sn.countryName="C";Sn.L=ns.getOID("localityName");Sn.localityName="L";Sn.ST=ns.getOID("stateOrProvinceName");Sn.stateOrProvinceName="ST";Sn.O=ns.getOID("organizationName");Sn.organizationName="O";Sn.OU=ns.getOID("organizationalUnitName");Sn.organizationalUnitName="OU";Sn.E=ns.getOID("emailAddress");Sn.emailAddress="E";function kse(t){return Sn[t]==null?"":Sn[t]}var Tse={name:"Certificate",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,capture:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",class:ae.Class.CONTEXT_SPECIFIC,tag:ae.Tag.NONE,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",class:ae.Class.UNIVERSAL,tag:ae.Tag.INTEGER,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",class:ae.Class.UNIVERSAL,tag:ae.Tag.INTEGER,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.signature.algorithm",class:ae.Class.UNIVERSAL,tag:ae.Tag.OID,capture:"certinfoSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ae.Class.UNIVERSAL,tag:ae.Tag.OCTETSTRING,optional:!0,capture:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,capture:"certIssuer"},{name:"Certificate.TBSCertificate.validity",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.validity.notBefore",class:ae.Class.UNIVERSAL,tag:[ae.Tag.UTCTIME,ae.Tag.GENERALIZEDTIME],capture:"certValidityNotBefore"},{name:"Certificate.TBSCertificate.validity.notAfter",class:ae.Class.UNIVERSAL,tag:[ae.Tag.UTCTIME,ae.Tag.GENERALIZEDTIME],capture:"certValidityNotAfter"}]},{name:"Certificate.TBSCertificate.subject",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,capture:"certSubject"},J$.publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",class:ae.Class.CONTEXT_SPECIFIC,tag:ae.Tag.BOOLEAN,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",class:ae.Class.UNIVERSAL,tag:ae.Tag.BITSTRING,capture:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",class:ae.Class.CONTEXT_SPECIFIC,tag:ae.Tag.INTEGER,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",class:ae.Class.UNIVERSAL,tag:ae.Tag.BITSTRING,capture:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",class:ae.Class.CONTEXT_SPECIFIC,tag:ae.Tag.BITSTRING,capture:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,value:[{name:"Certificate.signatureAlgorithm.algorithm",class:ae.Class.UNIVERSAL,tag:ae.Tag.OID,capture:"certSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ae.Class.UNIVERSAL,tag:ae.Tag.OCTETSTRING,optional:!0,capture:"certSignatureParams"}]},{name:"Certificate.signatureValue",class:ae.Class.UNIVERSAL,tag:ae.Tag.BITSTRING,capture:"certSignature"}]},zm=class{constructor(){this.attributes=[],this.uniqueId=null}get commonName(){return this.getFieldValue("commonName")}get organizationName(){return this.getFieldValue("organizationName")}get organizationalUnitName(){return this.getFieldValue("organizationalUnitName")}get countryName(){return this.getFieldValue("countryName")}get localityName(){return this.getFieldValue("localityName")}get serialName(){return this.getFieldValue("serialName")}getHash(){let e=Cse.createHash("sha1");for(let r of this.attributes)e.update(r.oid),e.update(r.value);return e.digest()}getField(e){for(let r of this.attributes)if(e===r.oid||e===r.name||e===r.shortName)return r;return null}addField(e){W$([e]),this.attributes.push(e)}setAttrs(e){W$(e),this.attributes=e}toJSON(){let e={};for(let r of this.attributes){let n=r.shortName;typeof n=="string"&&n!==""&&(e[n]=r.value)}return e.uniqueId=this.uniqueId,e.attributes=this.attributes,e}getFieldValue(e){let r=this.getField(e);return r!=null?r.value:""}};U_.DistinguishedName=zm;var Rk=class t{static fromPEMs(e){let r=[],n=ae.PEM.parse(e);for(let s of n){if(s.type!=="CERTIFICATE"&&s.type!=="X509 CERTIFICATE"&&s.type!=="TRUSTED CERTIFICATE")throw new Error("Could not convert certificate from PEM: invalid type");if(s.procType.includes("ENCRYPTED"))throw new Error("Could not convert certificate from PEM: PEM is encrypted.");let i=ae.ASN1.fromDER(s.body);r.push(new t(i))}if(r.length===0)throw new Error("No Certificate");return r}static fromPEM(e){return t.fromPEMs(e)[0]}constructor(e){let r=Object.create(null),n=e.validate(Tse,r);if(n!=null)throw new Error("Cannot read X.509 certificate: "+n.message);if(this.raw=e.DER,this.version=r.certVersion==null?0:ae.ASN1.parseIntegerNum(r.certVersion.bytes)+1,this.serialNumber=ae.ASN1.parseIntegerStr(r.certSerialNumber.bytes),this.signatureOID=ae.ASN1.parseOID(r.certSignatureOID.bytes),this.signatureAlgorithm=ns.getOIDName(this.signatureOID),this.infoSignatureOID=ae.ASN1.parseOID(r.certinfoSignatureOID.bytes),this.signature=ae.ASN1.parseBitString(r.certSignature.bytes).buf,this.validFrom=ae.ASN1.parseTime(r.certValidityNotBefore.tag,r.certValidityNotBefore.bytes),this.validTo=ae.ASN1.parseTime(r.certValidityNotAfter.tag,r.certValidityNotAfter.bytes),this.issuer=new zm,this.issuer.setAttrs(X$(r.certIssuer)),r.certIssuerUniqueId!=null&&(this.issuer.uniqueId=ae.ASN1.parseBitString(r.certIssuerUniqueId.bytes)),this.subject=new zm,this.subject.setAttrs(X$(r.certSubject)),r.certSubjectUniqueId!=null&&(this.subject.uniqueId=ae.ASN1.parseBitString(r.certSubjectUniqueId.bytes)),this.extensions=[],this.subjectKeyIdentifier="",this.authorityKeyIdentifier="",this.ocspServer="",this.issuingCertificateURL="",this.isCA=!1,this.maxPathLen=-1,this.basicConstraintsValid=!1,this.keyUsage=0,this.dnsNames=[],this.emailAddresses=[],this.ipAddresses=[],this.uris=[],r.certExtensions!=null){this.extensions=Ise(r.certExtensions);for(let s of this.extensions)if(typeof s.subjectKeyIdentifier=="string"&&(this.subjectKeyIdentifier=s.subjectKeyIdentifier),typeof s.authorityKeyIdentifier=="string"&&(this.authorityKeyIdentifier=s.authorityKeyIdentifier),typeof s.authorityInfoAccessOcsp=="string"&&(this.ocspServer=s.authorityInfoAccessOcsp),typeof s.authorityInfoAccessIssuers=="string"&&(this.issuingCertificateURL=s.authorityInfoAccessIssuers),typeof s.basicConstraintsValid=="boolean"&&(this.isCA=s.isCA,this.maxPathLen=s.maxPathLen,this.basicConstraintsValid=s.basicConstraintsValid),typeof s.keyUsage=="number"&&(this.keyUsage=s.keyUsage),Array.isArray(s.altNames))for(let i of s.altNames)i.dnsName!=null&&this.dnsNames.push(i.dnsName),i.email!=null&&this.emailAddresses.push(i.email),i.ip!=null&&this.ipAddresses.push(i.ip),i.uri!=null&&this.uris.push(i.uri)}this.publicKey=new J$.PublicKey(r.publicKeyInfo),this.publicKeyRaw=this.publicKey.toDER(),this.tbsCertificate=r.tbsCertificate}getExtension(e,r=""){for(let n of this.extensions)if(e===n.oid||e===n.name)return r===""?n:n[r];return null}checkSignature(e){if(this.version===3&&!this.basicConstraintsValid||this.basicConstraintsValid&&!this.isCA)return new Error("The parent constraint violation error");if(this.getExtension("keyUsage","keyCertSign")!==!0)return new Error("The parent constraint violation error");if(!e.isIssuer(this))return new Error("The parent certificate did not issue the given child certificate");let r=Use(e.signatureOID);return r===""?new Error("Unknown child signature OID."):this.publicKey.verify(e.tbsCertificate.DER,e.signature,r)===!1?new Error("Child signature not matched"):null}isIssuer(e){return this.issuer.getHash().equals(e.subject.getHash())}verifySubjectKeyIdentifier(){return this.publicKey.getFingerprint("sha1","PublicKey").toString("hex")===this.subjectKeyIdentifier}toJSON(){let e={};for(let r of Object.keys(this))e[r]=qse(this[r]);return delete e.tbsCertificate,e}[Z$.inspect.custom](e,r){return r.depth<=2&&(r.depth=10),`<${this.constructor.name} ${Z$.inspect(this.toJSON(),r)}>`}};U_.Certificate=Rk;function Ise(t){let e=[];for(let r of t.mustCompound())for(let n of r.mustCompound())e.push(Pse(n));return e}function Pse(t){let e={};switch(e.oid=ae.ASN1.parseOID(t.value[0].bytes),e.critical=!1,t.value[1].tag===ae.Tag.BOOLEAN?(e.critical=ae.ASN1.parseBool(t.value[1].bytes),e.value=t.value[2].bytes):e.value=t.value[1].bytes,e.name=ns.getOIDName(e.oid),e.name){case"keyUsage":Rse(e);break;case"basicConstraints":Ose(e);break;case"extKeyUsage":Nse(e);break;case"nsCertType":Bse(e);break;case"subjectAltName":G$(e);break;case"issuerAltName":G$(e);break;case"subjectKeyIdentifier":Mse(e);break;case"authorityKeyIdentifier":zse(e);break;case"authorityInfoAccess":Dse(e);break}return e}function Rse(t){let e=ae.ASN1.parseBitString(ae.ASN1.fromDER(t.value).bytes),r=0,n=0;t.keyUsage=0;for(let s=0;s<9;s++)e.at(s)!==0&&(t.keyUsage|=1<<s);e.buf.length>0&&(r=e.buf[0],n=e.buf.length>1?e.buf[1]:0),t.digitalSignature=(r&128)===128,t.nonRepudiation=(r&64)===64,t.keyEncipherment=(r&32)===32,t.dataEncipherment=(r&16)===16,t.keyAgreement=(r&8)===8,t.keyCertSign=(r&4)===4,t.cRLSign=(r&2)===2,t.encipherOnly=(r&1)===1,t.decipherOnly=(n&128)===128}function Ose(t){let r=ae.ASN1.fromDER(t.value).mustCompound();r.length>0&&r[0].tag===ae.Tag.BOOLEAN?t.isCA=ae.ASN1.parseBool(r[0].bytes):t.isCA=!1;let n=null;r.length>0&&r[0].tag===ae.Tag.INTEGER?n=r[0].bytes:r.length>1&&(n=r[1].bytes),n!==null?t.maxPathLen=ae.ASN1.parseInteger(n):t.maxPathLen=-1,t.basicConstraintsValid=!0}function Nse(t){let r=ae.ASN1.fromDER(t.value).mustCompound();for(let n of r)t[ns.getOIDName(ae.ASN1.parseOID(n.bytes))]=!0}function Bse(t){let e=ae.ASN1.parseBitString(ae.ASN1.fromDER(t.value).bytes),r=0;e.buf.length>0&&(r=e.buf[0]),t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}function G$(t){t.altNames=[];let r=ae.ASN1.fromDER(t.value).mustCompound();for(let n of r){let s={tag:n.tag,value:n.bytes};switch(t.altNames.push(s),n.tag){case 1:s.email=n.bytes.toString();break;case 2:s.dnsName=n.bytes.toString();break;case 6:s.uri=n.bytes.toString();break;case 7:s.ip=ns.bytesToIP(n.bytes);break;case 8:s.oid=ae.ASN1.parseOID(n.bytes);break;default:}}}var $se={name:"subjectKeyIdentifier",class:ae.Class.UNIVERSAL,tag:ae.Tag.OCTETSTRING,capture:"subjectKeyIdentifier"};function Mse(t){let e=ae.ASN1.parseDERWithTemplate(t.value,$se);t.subjectKeyIdentifier=e.subjectKeyIdentifier.bytes.toString("hex")}var jse={name:"authorityKeyIdentifier",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,value:[{name:"authorityKeyIdentifier.value",class:ae.Class.CONTEXT_SPECIFIC,tag:ae.Tag.NONE,capture:"authorityKeyIdentifier"}]};function zse(t){let e=ae.ASN1.parseDERWithTemplate(t.value,jse);t.authorityKeyIdentifier=e.authorityKeyIdentifier.bytes.toString("hex")}var Lse={name:"authorityInfoAccess",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp.oid",class:ae.Class.UNIVERSAL,tag:ae.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessOcsp.value",class:ae.Class.CONTEXT_SPECIFIC,tag:ae.Tag.OID,capture:"authorityInfoAccessOcsp"}]},{name:"authorityInfoAccess.authorityInfoAccessIssuers",class:ae.Class.UNIVERSAL,tag:ae.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessIssuers.oid",class:ae.Class.UNIVERSAL,tag:ae.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessIssuers.value",class:ae.Class.CONTEXT_SPECIFIC,tag:ae.Tag.OID,capture:"authorityInfoAccessIssuers"}]}]};function Dse(t){let e=ae.ASN1.parseDERWithTemplate(t.value,Lse);e.authorityInfoAccessOcsp!=null&&(t.authorityInfoAccessOcsp=e.authorityInfoAccessOcsp.bytes.toString()),e.authorityInfoAccessIssuers!=null&&(t.authorityInfoAccessIssuers=e.authorityInfoAccessIssuers.bytes.toString())}function W$(t){for(let e of t){if((e.name==null||e.name==="")&&(e.oid!=null&&(e.name=ns.getOIDName(e.oid)),e.name===""&&e.shortName!=null&&(e.name=ns.getOIDName(Sn[e.shortName]))),e.oid==null||e.oid==="")if(e.name!=="")e.oid=ns.getOID(e.name);else throw new Error("Attribute oid not specified.");if((e.shortName==null||e.shortName==="")&&(e.shortName=Sn[e.name]==null?"":Sn[e.name]),e.value==null)throw new Error("Attribute value not specified.")}}function Use(t){switch(ns.getOIDName(t)){case"sha1WithRsaEncryption":return"sha1";case"md5WithRsaEncryption":return"md5";case"sha256WithRsaEncryption":return"sha256";case"sha384WithRsaEncryption":return"sha384";case"sha512WithRsaEncryption":return"sha512";case"RSASSA-PSS":return"sha256";case"ecdsaWithSha1":return"sha1";case"ecdsaWithSha256":return"sha256";case"ecdsaWithSha384":return"sha384";case"ecdsaWithSha512":return"sha512";case"dsaWithSha1":return"sha1";case"dsaWithSha256":return"sha256";default:return""}}function X$(t){let e=[];for(let r of t.mustCompound())for(let n of r.mustCompound()){let s=n.mustCompound(),i={};i.oid=ae.ASN1.parseOID(s[0].bytes),i.value=s[1].value,i.valueTag=s[1].tag,i.name=ns.getOIDName(i.oid),i.shortName=kse(i.name),e.push(i)}return e}function qse(t){return t!=null&&!(t instanceof Buffer)&&typeof t.toJSON=="function"?t.toJSON():t}});var Ok=v(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var q_=$_();vi.bytesFromIP=q_.bytesFromIP;vi.bytesToIP=q_.bytesToIP;vi.getOID=q_.getOID;vi.getOIDName=q_.getOIDName;var H_=Pk();vi.PublicKey=H_.PublicKey;vi.PrivateKey=H_.PrivateKey;vi.RSAPublicKey=H_.RSAPublicKey;vi.RSAPrivateKey=H_.RSAPrivateKey;var Q$=Y$();vi.Certificate=Q$.Certificate;vi.DistinguishedName=Q$.DistinguishedName});var t7=v(()=>{var e7;(function(t){(function(e){var r=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),n=s(t);typeof r.Reflect<"u"&&(n=s(r.Reflect,n)),e(n,r),typeof r.Reflect>"u"&&(r.Reflect=t);function s(c,u){return function(l,d){Object.defineProperty(c,l,{configurable:!0,writable:!0,value:d}),u&&u(l,d)}}function i(){try{return Function("return this;")()}catch{}}function o(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return i()||o()}})(function(e,r){var n=Object.prototype.hasOwnProperty,s=typeof Symbol=="function",i=s&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",o=s&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",c={__proto__:[]}instanceof Array,u=!a&&!c,l={create:a?function(){return gl(Object.create(null))}:c?function(){return gl({__proto__:null})}:function(){return gl({})},has:u?function(O,j){return n.call(O,j)}:function(O,j){return j in O},get:u?function(O,j){return n.call(O,j)?O[j]:void 0}:function(O,j){return O[j]}},d=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:wm(),p=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:m_(),m=typeof WeakMap=="function"?WeakMap:FC(),y=s?Symbol.for("@reflect-metadata:registry"):void 0,_=Wf(),S=vm(_);function C(O,j,W,pe){if(I(W)){if(!xi(O))throw new TypeError;if(!hl(j))throw new TypeError;return ze(O,j)}else{if(!xi(O))throw new TypeError;if(!ye(j))throw new TypeError;if(!ye(pe)&&!I(pe)&&!M(pe))throw new TypeError;return M(pe)&&(pe=void 0),W=lr(W),z(O,j,W,pe)}}e("decorate",C);function E(O,j){function W(pe,Ge){if(!ye(pe))throw new TypeError;if(!I(Ge)&&!HC(Ge))throw new TypeError;Le(O,j,pe,Ge)}return W}e("metadata",E);function B(O,j,W,pe){if(!ye(W))throw new TypeError;return I(pe)||(pe=lr(pe)),Le(O,j,W,pe)}e("defineMetadata",B);function G(O,j,W){if(!ye(j))throw new TypeError;return I(W)||(W=lr(W)),$(O,j,W)}e("hasMetadata",G);function se(O,j,W){if(!ye(j))throw new TypeError;return I(W)||(W=lr(W)),U(O,j,W)}e("hasOwnMetadata",se);function _e(O,j,W){if(!ye(j))throw new TypeError;return I(W)||(W=lr(W)),be(O,j,W)}e("getMetadata",_e);function he(O,j,W){if(!ye(j))throw new TypeError;return I(W)||(W=lr(W)),ke(O,j,W)}e("getOwnMetadata",he);function J(O,j){if(!ye(O))throw new TypeError;return I(j)||(j=lr(j)),k(O,j)}e("getMetadataKeys",J);function ct(O,j){if(!ye(O))throw new TypeError;return I(j)||(j=lr(j)),P(O,j)}e("getOwnMetadataKeys",ct);function ut(O,j,W){if(!ye(j))throw new TypeError;if(I(W)||(W=lr(W)),!ye(j))throw new TypeError;I(W)||(W=lr(W));var pe=Ba(j,W,!1);return I(pe)?!1:pe.OrdinaryDeleteMetadata(O,j,W)}e("deleteMetadata",ut);function ze(O,j){for(var W=O.length-1;W>=0;--W){var pe=O[W],Ge=pe(j);if(!I(Ge)&&!M(Ge)){if(!hl(Ge))throw new TypeError;j=Ge}}return j}function z(O,j,W,pe){for(var Ge=O.length-1;Ge>=0;--Ge){var Ir=O[Ge],$r=Ir(j,W,pe);if(!I($r)&&!M($r)){if(!ye($r))throw new TypeError;pe=$r}}return pe}function $(O,j,W){var pe=U(O,j,W);if(pe)return!0;var Ge=ml(j);return M(Ge)?!1:$(O,Ge,W)}function U(O,j,W){var pe=Ba(j,W,!1);return I(pe)?!1:cr(pe.OrdinaryHasOwnMetadata(O,j,W))}function be(O,j,W){var pe=U(O,j,W);if(pe)return ke(O,j,W);var Ge=ml(j);if(!M(Ge))return be(O,Ge,W)}function ke(O,j,W){var pe=Ba(j,W,!1);if(!I(pe))return pe.OrdinaryGetOwnMetadata(O,j,W)}function Le(O,j,W,pe){var Ge=Ba(W,pe,!0);Ge.OrdinaryDefineOwnMetadata(O,j,W,pe)}function k(O,j){var W=P(O,j),pe=ml(O);if(pe===null)return W;var Ge=k(pe,j);if(Ge.length<=0)return W;if(W.length<=0)return Ge;for(var Ir=new p,$r=[],St=0,we=W;St<we.length;St++){var Re=we[St],De=Ir.has(Re);De||(Ir.add(Re),$r.push(Re))}for(var Fe=0,ht=Ge;Fe<ht.length;Fe++){var Re=ht[Fe],De=Ir.has(Re);De||(Ir.add(Re),$r.push(Re))}return $r}function P(O,j){var W=Ba(O,j,!1);return W?W.OrdinaryOwnMetadataKeys(O,j):[]}function Z(O){if(O===null)return 1;switch(typeof O){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return O===null?1:6;default:return 6}}function I(O){return O===void 0}function M(O){return O===null}function fe(O){return typeof O=="symbol"}function ye(O){return typeof O=="object"?O!==null:typeof O=="function"}function xt(O,j){switch(Z(O)){case 0:return O;case 1:return O;case 2:return O;case 3:return O;case 4:return O;case 5:return O}var W=j===3?"string":j===5?"number":"default",pe=ym(O,i);if(pe!==void 0){var Ge=pe.call(O,W);if(ye(Ge))throw new TypeError;return Ge}return Rt(O,W==="default"?"number":W)}function Rt(O,j){if(j==="string"){var W=O.toString;if(bi(W)){var pe=W.call(O);if(!ye(pe))return pe}var Ge=O.valueOf;if(bi(Ge)){var pe=Ge.call(O);if(!ye(pe))return pe}}else{var Ge=O.valueOf;if(bi(Ge)){var pe=Ge.call(O);if(!ye(pe))return pe}var Ir=O.toString;if(bi(Ir)){var pe=Ir.call(O);if(!ye(pe))return pe}}throw new TypeError}function cr(O){return!!O}function zt(O){return""+O}function lr(O){var j=xt(O,3);return fe(j)?j:zt(j)}function xi(O){return Array.isArray?Array.isArray(O):O instanceof Object?O instanceof Array:Object.prototype.toString.call(O)==="[object Array]"}function bi(O){return typeof O=="function"}function hl(O){return typeof O=="function"}function HC(O){switch(Z(O)){case 3:return!0;case 4:return!0;default:return!1}}function gm(O,j){return O===j||O!==O&&j!==j}function ym(O,j){var W=O[j];if(W!=null){if(!bi(W))throw new TypeError;return W}}function xm(O){var j=ym(O,o);if(!bi(j))throw new TypeError;var W=j.call(O);if(!ye(W))throw new TypeError;return W}function Bo(O){return O.value}function pl(O){var j=O.next();return j.done?!1:j}function bm(O){var j=O.return;j&&j.call(O)}function ml(O){var j=Object.getPrototypeOf(O);if(typeof O!="function"||O===d||j!==d)return j;var W=O.prototype,pe=W&&Object.getPrototypeOf(W);if(pe==null||pe===Object.prototype)return j;var Ge=pe.constructor;return typeof Ge!="function"||Ge===O?j:Ge}function _m(){var O;!I(y)&&typeof r.Reflect<"u"&&!(y in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(O=Xf(r.Reflect));var j,W,pe,Ge=new m,Ir={registerProvider:$r,getProvider:we,setProvider:De};return Ir;function $r(Fe){if(!Object.isExtensible(Ir))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case O===Fe:break;case I(j):j=Fe;break;case j===Fe:break;case I(W):W=Fe;break;case W===Fe:break;default:pe===void 0&&(pe=new p),pe.add(Fe);break}}function St(Fe,ht){if(!I(j)){if(j.isProviderFor(Fe,ht))return j;if(!I(W)){if(W.isProviderFor(Fe,ht))return j;if(!I(pe))for(var nr=xm(pe);;){var br=pl(nr);if(!br)return;var ps=Bo(br);if(ps.isProviderFor(Fe,ht))return bm(nr),ps}}}if(!I(O)&&O.isProviderFor(Fe,ht))return O}function we(Fe,ht){var nr=Ge.get(Fe),br;return I(nr)||(br=nr.get(ht)),I(br)&&(br=St(Fe,ht),I(br)||(I(nr)&&(nr=new f,Ge.set(Fe,nr)),nr.set(ht,br))),br}function Re(Fe){if(I(Fe))throw new TypeError;return j===Fe||W===Fe||!I(pe)&&pe.has(Fe)}function De(Fe,ht,nr){if(!Re(nr))throw new Error("Metadata provider not registered.");var br=we(Fe,ht);if(br!==nr){if(!I(br))return!1;var ps=Ge.get(Fe);I(ps)&&(ps=new f,Ge.set(Fe,ps)),ps.set(ht,nr)}return!0}}function Wf(){var O;return!I(y)&&ye(r.Reflect)&&Object.isExtensible(r.Reflect)&&(O=r.Reflect[y]),I(O)&&(O=_m()),!I(y)&&ye(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:O}),O}function vm(O){var j=new m,W={isProviderFor:function(Re,De){var Fe=j.get(Re);return I(Fe)?!1:Fe.has(De)},OrdinaryDefineOwnMetadata:$r,OrdinaryHasOwnMetadata:Ge,OrdinaryGetOwnMetadata:Ir,OrdinaryOwnMetadataKeys:St,OrdinaryDeleteMetadata:we};return _.registerProvider(W),W;function pe(Re,De,Fe){var ht=j.get(Re),nr=!1;if(I(ht)){if(!Fe)return;ht=new f,j.set(Re,ht),nr=!0}var br=ht.get(De);if(I(br)){if(!Fe)return;if(br=new f,ht.set(De,br),!O.setProvider(Re,De,W))throw ht.delete(De),nr&&j.delete(Re),new Error("Wrong provider for target.")}return br}function Ge(Re,De,Fe){var ht=pe(De,Fe,!1);return I(ht)?!1:cr(ht.has(Re))}function Ir(Re,De,Fe){var ht=pe(De,Fe,!1);if(!I(ht))return ht.get(Re)}function $r(Re,De,Fe,ht){var nr=pe(Fe,ht,!0);nr.set(Re,De)}function St(Re,De){var Fe=[],ht=pe(Re,De,!1);if(I(ht))return Fe;for(var nr=ht.keys(),br=xm(nr),ps=0;;){var Jf=pl(br);if(!Jf)return Fe.length=ps,Fe;var g_=Bo(Jf);try{Fe[ps]=g_}catch(VC){try{bm(br)}finally{throw VC}}ps++}}function we(Re,De,Fe){var ht=pe(De,Fe,!1);if(I(ht)||!ht.delete(Re))return!1;if(ht.size===0){var nr=j.get(De);I(nr)||(nr.delete(Fe),nr.size===0&&j.delete(nr))}return!0}}function Xf(O){var j=O.defineMetadata,W=O.hasOwnMetadata,pe=O.getOwnMetadata,Ge=O.getOwnMetadataKeys,Ir=O.deleteMetadata,$r=new m,St={isProviderFor:function(we,Re){var De=$r.get(we);return!I(De)&&De.has(Re)?!0:Ge(we,Re).length?(I(De)&&(De=new p,$r.set(we,De)),De.add(Re),!0):!1},OrdinaryDefineOwnMetadata:j,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:pe,OrdinaryOwnMetadataKeys:Ge,OrdinaryDeleteMetadata:Ir};return St}function Ba(O,j,W){var pe=_.getProvider(O,j);if(!I(pe))return pe;if(W){if(_.setProvider(O,j,S))return S;throw new Error("Illegal state.")}}function wm(){var O={},j=[],W=(function(){function St(we,Re,De){this._index=0,this._keys=we,this._values=Re,this._selector=De}return St.prototype["@@iterator"]=function(){return this},St.prototype[o]=function(){return this},St.prototype.next=function(){var we=this._index;if(we>=0&&we<this._keys.length){var Re=this._selector(this._keys[we],this._values[we]);return we+1>=this._keys.length?(this._index=-1,this._keys=j,this._values=j):this._index++,{value:Re,done:!1}}return{value:void 0,done:!0}},St.prototype.throw=function(we){throw this._index>=0&&(this._index=-1,this._keys=j,this._values=j),we},St.prototype.return=function(we){return this._index>=0&&(this._index=-1,this._keys=j,this._values=j),{value:we,done:!0}},St})(),pe=(function(){function St(){this._keys=[],this._values=[],this._cacheKey=O,this._cacheIndex=-2}return Object.defineProperty(St.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),St.prototype.has=function(we){return this._find(we,!1)>=0},St.prototype.get=function(we){var Re=this._find(we,!1);return Re>=0?this._values[Re]:void 0},St.prototype.set=function(we,Re){var De=this._find(we,!0);return this._values[De]=Re,this},St.prototype.delete=function(we){var Re=this._find(we,!1);if(Re>=0){for(var De=this._keys.length,Fe=Re+1;Fe<De;Fe++)this._keys[Fe-1]=this._keys[Fe],this._values[Fe-1]=this._values[Fe];return this._keys.length--,this._values.length--,gm(we,this._cacheKey)&&(this._cacheKey=O,this._cacheIndex=-2),!0}return!1},St.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=O,this._cacheIndex=-2},St.prototype.keys=function(){return new W(this._keys,this._values,Ge)},St.prototype.values=function(){return new W(this._keys,this._values,Ir)},St.prototype.entries=function(){return new W(this._keys,this._values,$r)},St.prototype["@@iterator"]=function(){return this.entries()},St.prototype[o]=function(){return this.entries()},St.prototype._find=function(we,Re){if(!gm(this._cacheKey,we)){this._cacheIndex=-1;for(var De=0;De<this._keys.length;De++)if(gm(this._keys[De],we)){this._cacheIndex=De;break}}return this._cacheIndex<0&&Re&&(this._cacheIndex=this._keys.length,this._keys.push(we),this._values.push(void 0)),this._cacheIndex},St})();return pe;function Ge(St,we){return St}function Ir(St,we){return we}function $r(St,we){return[St,we]}}function m_(){var O=(function(){function j(){this._map=new f}return Object.defineProperty(j.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),j.prototype.has=function(W){return this._map.has(W)},j.prototype.add=function(W){return this._map.set(W,W),this},j.prototype.delete=function(W){return this._map.delete(W)},j.prototype.clear=function(){this._map.clear()},j.prototype.keys=function(){return this._map.keys()},j.prototype.values=function(){return this._map.keys()},j.prototype.entries=function(){return this._map.entries()},j.prototype["@@iterator"]=function(){return this.keys()},j.prototype[o]=function(){return this.keys()},j})();return O}function FC(){var O=16,j=l.create(),W=pe();return(function(){function we(){this._key=pe()}return we.prototype.has=function(Re){var De=Ge(Re,!1);return De!==void 0?l.has(De,this._key):!1},we.prototype.get=function(Re){var De=Ge(Re,!1);return De!==void 0?l.get(De,this._key):void 0},we.prototype.set=function(Re,De){var Fe=Ge(Re,!0);return Fe[this._key]=De,this},we.prototype.delete=function(Re){var De=Ge(Re,!1);return De!==void 0?delete De[this._key]:!1},we.prototype.clear=function(){this._key=pe()},we})();function pe(){var we;do we="@@WeakMap@@"+St();while(l.has(j,we));return j[we]=!0,we}function Ge(we,Re){if(!n.call(we,W)){if(!Re)return;Object.defineProperty(we,W,{value:l.create()})}return we[W]}function Ir(we,Re){for(var De=0;De<Re;++De)we[De]=Math.random()*255|0;return we}function $r(we){if(typeof Uint8Array=="function"){var Re=new Uint8Array(we);return typeof crypto<"u"?crypto.getRandomValues(Re):typeof msCrypto<"u"?msCrypto.getRandomValues(Re):Ir(Re,we),Re}return Ir(new Array(we),we)}function St(){var we=$r(O);we[6]=we[6]&79|64,we[8]=we[8]&191|128;for(var Re="",De=0;De<O;++De){var Fe=we[De];(De===4||De===6||De===8)&&(Re+="-"),Fe<16&&(Re+="0"),Re+=Fe.toString(16).toLowerCase()}return Re}}function gl(O){return O.__=void 0,delete O.__,O}})})(e7||(e7={}))});var F={};$a(F,{__addDisposableResource:()=>C7,__assign:()=>F_,__asyncDelegator:()=>x7,__asyncGenerator:()=>y7,__asyncValues:()=>b7,__await:()=>uh,__awaiter:()=>d7,__classPrivateFieldGet:()=>S7,__classPrivateFieldIn:()=>E7,__classPrivateFieldSet:()=>A7,__createBinding:()=>K_,__decorate:()=>s7,__disposeResources:()=>k7,__esDecorate:()=>o7,__exportStar:()=>h7,__extends:()=>r7,__generator:()=>f7,__importDefault:()=>w7,__importStar:()=>v7,__makeTemplateObject:()=>_7,__metadata:()=>l7,__param:()=>i7,__propKey:()=>c7,__read:()=>$k,__rest:()=>n7,__rewriteRelativeImportExtension:()=>T7,__runInitializers:()=>a7,__setFunctionName:()=>u7,__spread:()=>p7,__spreadArray:()=>g7,__spreadArrays:()=>m7,__values:()=>V_,default:()=>Vse});function r7(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Nk(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function n7(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r}function s7(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i}function i7(t,e){return function(r,n){e(r,n,t)}}function o7(t,e,r,n,s,i){function o(S){if(S!==void 0&&typeof S!="function")throw new TypeError("Function expected");return S}for(var a=n.kind,c=a==="getter"?"get":a==="setter"?"set":"value",u=!e&&t?n.static?t:t.prototype:null,l=e||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),d,f=!1,p=r.length-1;p>=0;p--){var m={};for(var y in n)m[y]=y==="access"?{}:n[y];for(var y in n.access)m.access[y]=n.access[y];m.addInitializer=function(S){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(S||null))};var _=(0,r[p])(a==="accessor"?{get:l.get,set:l.set}:l[c],m);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(d=o(_.get))&&(l.get=d),(d=o(_.set))&&(l.set=d),(d=o(_.init))&&s.unshift(d)}else(d=o(_))&&(a==="field"?s.unshift(d):l[c]=d)}u&&Object.defineProperty(u,n.name,l),f=!0}function a7(t,e,r){for(var n=arguments.length>2,s=0;s<e.length;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function c7(t){return typeof t=="symbol"?t:"".concat(t)}function u7(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function l7(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function d7(t,e,r,n){function s(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(l){try{u(n.next(l))}catch(d){o(d)}}function c(l){try{u(n.throw(l))}catch(d){o(d)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function f7(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,s,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,u[0]&&(r=0)),r;)try{if(n=1,s&&(i=u[0]&2?s.return:u[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,u[1])).done)return i;switch(s=0,i&&(u=[u[0]&2,i.value]),u[0]){case 0:case 1:i=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,s=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){r.label=u[1];break}if(u[0]===6&&r.label<i[1]){r.label=i[1],i=u;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(u);break}i[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],s=0}finally{n=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function h7(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&K_(e,t,r)}function V_(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function $k(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i}function p7(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat($k(arguments[e]));return t}function m7(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),s=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)n[s]=i[o];return n}function g7(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,i;n<s;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function uh(t){return this instanceof uh?(this.v=t,this):new uh(t)}function y7(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),s,i=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),s[Symbol.asyncIterator]=function(){return this},s;function o(p){return function(m){return Promise.resolve(m).then(p,d)}}function a(p,m){n[p]&&(s[p]=function(y){return new Promise(function(_,S){i.push([p,y,_,S])>1||c(p,y)})},m&&(s[p]=m(s[p])))}function c(p,m){try{u(n[p](m))}catch(y){f(i[0][3],y)}}function u(p){p.value instanceof uh?Promise.resolve(p.value.v).then(l,d):f(i[0][2],p)}function l(p){c("next",p)}function d(p){c("throw",p)}function f(p,m){p(m),i.shift(),i.length&&c(i[0][0],i[0][1])}}function x7(t){var e,r;return e={},n("next"),n("throw",function(s){throw s}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(s,i){e[s]=t[s]?function(o){return(r=!r)?{value:uh(t[s](o)),done:!1}:i?i(o):o}:i}}function b7(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof V_=="function"?V_(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(u){i({value:u,done:a})},o)}}function _7(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function v7(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=Bk(t),n=0;n<r.length;n++)r[n]!=="default"&&K_(e,t,r[n]);return Hse(e,t),e}function w7(t){return t&&t.__esModule?t:{default:t}}function S7(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function A7(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function E7(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function C7(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(s=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function k7(t){function e(i){t.error=t.hasError?new Fse(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;function s(){for(;r=t.stack.pop();)try{if(!r.async&&n===1)return n=0,t.stack.push(r),Promise.resolve().then(s);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(i).then(s,function(o){return e(o),s()})}else n|=1}catch(o){e(o)}if(n===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return s()}function T7(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,n,s,i,o){return n?e?".jsx":".js":s&&(!i||!o)?r:s+i+"."+o.toLowerCase()+"js"}):t}var Nk,F_,K_,Hse,Bk,Fse,Vse,V=mr(()=>{Nk=function(t,e){return Nk=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])},Nk(t,e)};F_=function(){return F_=Object.assign||function(e){for(var r,n=1,s=arguments.length;n<s;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},F_.apply(this,arguments)};K_=Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]});Hse=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e},Bk=function(t){return Bk=Object.getOwnPropertyNames||function(e){var r=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[r.length]=n);return r},Bk(t)};Fse=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};Vse={__extends:r7,__assign:F_,__rest:n7,__decorate:s7,__param:i7,__esDecorate:o7,__runInitializers:a7,__propKey:c7,__setFunctionName:u7,__metadata:l7,__awaiter:d7,__generator:f7,__createBinding:K_,__exportStar:h7,__values:V_,__read:$k,__spread:p7,__spreadArrays:m7,__spreadArray:g7,__await:uh,__asyncGenerator:y7,__asyncDelegator:x7,__asyncValues:b7,__makeTemplateObject:_7,__importStar:v7,__importDefault:w7,__classPrivateFieldGet:S7,__classPrivateFieldSet:A7,__classPrivateFieldIn:E7,__addDisposableResource:C7,__disposeResources:k7,__rewriteRelativeImportExtension:T7}});var jk=v(lh=>{"use strict";var Kse="[object ArrayBuffer]",ja=class t{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Kse}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,r){if(e.constructor===r)return e;if(this.isArrayBuffer(e))return new r(e);if(this.isArrayBufferView(e))return new r(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,r){let n=t.toUint8Array(e),s=t.toUint8Array(r);if(n.length!==s.byteLength)return!1;for(let i=0;i<n.length;i++)if(n[i]!==s[i])return!1;return!0}static concat(...e){let r;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?r=e[0]:e[e.length-1]instanceof Function?r=e.slice(0,e.length-1):r=e;let n=0;for(let o of r)n+=o.byteLength;let s=new Uint8Array(n),i=0;for(let o of r){let a=this.toUint8Array(o);s.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}},Mk="string",Zse=/^[0-9a-f\s]+$/i,Gse=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Wse=/^[a-zA-Z0-9-_]+$/,Z_=class{static fromString(e){let r=unescape(encodeURIComponent(e)),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n.buffer}static toString(e){let r=ja.toUint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return decodeURIComponent(escape(n))}},wi=class{static toString(e,r=!1){let n=ja.toArrayBuffer(e),s=new DataView(n),i="";for(let o=0;o<n.byteLength;o+=2){let a=s.getUint16(o,r);i+=String.fromCharCode(a)}return i}static fromString(e,r=!1){let n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let i=0;i<e.length;i++)s.setUint16(i*2,e.charCodeAt(i),r);return n}},G_=class t{static isHex(e){return typeof e===Mk&&Zse.test(e)}static isBase64(e){return typeof e===Mk&&Gse.test(e)}static isBase64Url(e){return typeof e===Mk&&Wse.test(e)}static ToString(e,r="utf8"){let n=ja.toUint8Array(e);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return wi.toString(n,!0);case"utf16":case"utf16be":return wi.toString(n);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromString(e,r="utf8"){if(!e)return new ArrayBuffer(0);switch(r.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return wi.fromString(e,!0);case"utf16":case"utf16be":return wi.fromString(e);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToBase64(e){let r=ja.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(r,"binary");return btoa(n)}else return Buffer.from(r).toString("base64")}static FromBase64(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isBase64(r))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(r)):new Uint8Array(Buffer.from(r,"base64")).buffer}static FromBase64Url(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isBase64Url(r))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(r.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,r=t.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.FromBinary(e);case"utf8":return Z_.fromString(e);case"utf16":case"utf16be":return wi.fromString(e);case"utf16le":case"usc2":return wi.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToUtf8String(e,r=t.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.ToBinary(e);case"utf8":return Z_.toString(e);case"utf16":case"utf16be":return wi.toString(e);case"utf16le":case"usc2":return wi.toString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromBinary(e){let r=e.length,n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){let r=ja.toUint8Array(e),n="";for(let s=0;s<r.length;s++)n+=String.fromCharCode(r[s]);return n}static ToHex(e){let r=ja.toUint8Array(e),n="",s=r.length;for(let i=0;i<s;i++){let o=r[i];o<16&&(n+="0"),n+=o.toString(16)}return n}static FromHex(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isHex(r))throw new TypeError("Argument 'hexString' is not HEX encoded");r.length%2&&(r=`0${r}`);let n=new Uint8Array(r.length/2);for(let s=0;s<r.length;s=s+2){let i=r.slice(s,s+2);n[s/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,r=!1){return wi.toString(e,r)}static FromUtf16String(e,r=!1){return wi.fromString(e,r)}static Base64Padding(e){let r=4-e.length%4;if(r<4)for(let n=0;n<r;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};G_.DEFAULT_UTF8_ENCODING="utf8";function Xse(t,...e){let r=arguments[0];for(let n=1;n<arguments.length;n++){let s=arguments[n];for(let i in s)r[i]=s[i]}return r}function Jse(...t){let e=t.map(s=>s.byteLength).reduce((s,i)=>s+i),r=new Uint8Array(e),n=0;return t.map(s=>new Uint8Array(s)).forEach(s=>{for(let i of s)r[n++]=i}),r.buffer}function Yse(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<t.byteLength;s++)if(r[s]!==n[s])return!1;return!0}lh.BufferSourceConverter=ja;lh.Convert=G_;lh.assign=Xse;lh.combine=Jse;lh.isEqual=Yse});var R7=v(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});function Qse(t){return new Date(t.getTime()+t.getTimezoneOffset()*6e4)}function eie(t,e,r){var n;return t instanceof Object&&(n=t[e])!==null&&n!==void 0?n:r}function tie(t,e=0,r=t.byteLength-e,n=!1){let s="";for(let i of new Uint8Array(t,e,r)){let o=i.toString(16).toUpperCase();o.length===1&&(s+="0"),s+=o,n&&(s+=" ")}return s.trim()}function rie(t,e,r,n){return e instanceof ArrayBuffer?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):n<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-n<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error='Wrong parameter: inputBuffer must be "ArrayBuffer"',!1)}function zk(t,e){let r=0;if(t.length===1)return t[0];for(let n=t.length-1;n>=0;n--)r+=t[t.length-1-n]*Math.pow(2,e*n);return r}function Lk(t,e,r=-1){let n=r,s=t,i=0,o=Math.pow(2,e);for(let a=1;a<8;a++){if(t<o){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let u=new Uint8Array(c);for(let l=a-1;l>=0;l--){let d=Math.pow(2,l*e);u[i-l-1]=Math.floor(s/d),s-=u[i-l-1]*d}return c}o*=Math.pow(2,e)}return new ArrayBuffer(0)}function nie(...t){let e=0,r=0;for(let i of t)e+=i.byteLength;let n=new ArrayBuffer(e),s=new Uint8Array(n);for(let i of t)s.set(new Uint8Array(i),r),r+=i.byteLength;return n}function sie(...t){let e=0,r=0;for(let i of t)e+=i.length;let n=new ArrayBuffer(e),s=new Uint8Array(n);for(let i of t)s.set(i,r),r+=i.length;return s}function iie(){let t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=t[0]===255&&t[1]&128,c=t[0]===0&&(t[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)r[a]=0;r[0]=t[0]&128;let n=zk(r,8),s=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(s);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=t[a];return i[0]&=127,zk(i,8)-n}function oie(t){let e=t<0?t*-1:t,r=128;for(let n=1;n<8;n++){if(e<=r){if(t<0){let o=r-e,a=Lk(o,8,n),c=new Uint8Array(a);return c[0]|=128,a}let s=Lk(e,8,n),i=new Uint8Array(s);if(i[0]&128){let o=s.slice(0),a=new Uint8Array(o);s=new ArrayBuffer(s.byteLength+1),i=new Uint8Array(s);for(let c=0;c<o.byteLength;c++)i[c+1]=a[c];i[0]=0}return s}r*=Math.pow(2,8)}return new ArrayBuffer(0)}function aie(t,e){if(t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<r.length;s++)if(r[s]!==n[s])return!1;return!0}function cie(t,e){let r=t.toString(10);if(e<r.length)return"";let n=e-r.length,s=new Array(n);for(let o=0;o<n;o++)s[o]="0";return s.join("").concat(r)}var I7="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",P7="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";function uie(t,e=!1,r=!1,n=!1){let s=0,i=0,o=0,a="",c=e?P7:I7;if(n){let u=0;for(let l=0;l<t.length;l++)if(t.charCodeAt(l)!==0){u=l;break}t=t.slice(u)}for(;s<t.length;){let u=t.charCodeAt(s++);s>=t.length&&(i=1);let l=t.charCodeAt(s++);s>=t.length&&(o=1);let d=t.charCodeAt(s++),f=u>>2,p=(u&3)<<4|l>>4,m=(l&15)<<2|d>>6,y=d&63;i===1?m=y=64:o===1&&(y=64),r?m===64?a+=`${c.charAt(f)}${c.charAt(p)}`:y===64?a+=`${c.charAt(f)}${c.charAt(p)}${c.charAt(m)}`:a+=`${c.charAt(f)}${c.charAt(p)}${c.charAt(m)}${c.charAt(y)}`:a+=`${c.charAt(f)}${c.charAt(p)}${c.charAt(m)}${c.charAt(y)}`}return a}function lie(t,e=!1,r=!1){let n=e?P7:I7;function s(c){for(let u=0;u<64;u++)if(n.charAt(u)===c)return u;return 64}function i(c){return c===64?0:c}let o=0,a="";for(;o<t.length;){let c=s(t.charAt(o++)),u=o>=t.length?0:s(t.charAt(o++)),l=o>=t.length?0:s(t.charAt(o++)),d=o>=t.length?0:s(t.charAt(o++)),f=i(c)<<2|i(u)>>4,p=(i(u)&15)<<4|i(l)>>2,m=(i(l)&3)<<6|i(d);a+=String.fromCharCode(f),l!==64&&(a+=String.fromCharCode(p)),d!==64&&(a+=String.fromCharCode(m))}if(r){let c=a.length,u=-1;for(let l=c-1;l>=0;l--)if(a.charCodeAt(l)!==0){u=l;break}u!==-1?a=a.slice(0,u+1):a=""}return a}function die(t){let e="",r=new Uint8Array(t);for(let n of r)e+=String.fromCharCode(n);return e}function fie(t){let e=t.length,r=new ArrayBuffer(e),n=new Uint8Array(r);for(let s=0;s<e;s++)n[s]=t.charCodeAt(s);return r}var hie=Math.log(2);function pie(t){let e=Math.log(t)/hie,r=Math.floor(e),n=Math.round(e);return r===n?r:n}function mie(t,e){for(let r of e)delete t[r]}yn.arrayBufferToString=die;yn.bufferToHexCodes=tie;yn.checkBufferParams=rie;yn.clearProps=mie;yn.fromBase64=lie;yn.getParametersValue=eie;yn.getUTCDate=Qse;yn.isEqualBuffer=aie;yn.nearestPowerOf2=pie;yn.padNumber=cie;yn.stringToArrayBuffer=fie;yn.toBase64=uie;yn.utilConcatBuf=nie;yn.utilConcatView=sie;yn.utilDecodeTC=iie;yn.utilEncodeTC=oie;yn.utilFromBase=zk;yn.utilToBase=Lk});var Yc=v(lt=>{"use strict";var gie=jk(),yie=R7();function $7(t){var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var qt=$7(gie),gr=$7(yie);function W_(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function qk(t){let e=0,r=0;for(let s=0;s<t.length;s++){let i=t[s];e+=i.byteLength}let n=new Uint8Array(e);for(let s=0;s<t.length;s++){let i=t[s];n.set(new Uint8Array(i),r),r+=i.byteLength}return n.buffer}function Da(t,e,r,n){return e instanceof Uint8Array?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):n<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-n<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var fh=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return qk(this.items)}},Lm=[new Uint8Array([1])],O7="0123456789",Dk="name",N7="valueHexView",xie="isHexOnly",bie="idBlock",_ie="tagClass",vie="tagNumber",wie="isConstructed",Sie="fromBER",Aie="toBER",Eie="local",Ts="",Lo=new ArrayBuffer(0),dv=new Uint8Array(0),Um="EndOfContent",M7="OCTET STRING",j7="BIT STRING";function Do(t){var e;return e=class extends t{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var s;super(...n);let i=n[0]||{};this.isHexOnly=(s=i.isHexOnly)!==null&&s!==void 0?s:!1,this.valueHexView=i.valueHex?qt.BufferSourceConverter.toUint8Array(i.valueHex):dv}fromBER(n,s,i,o){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Da(this,a,s,i))return-1;let c=s+i;return this.valueHexView=a.subarray(s,c),this.valueHexView.length?(this.blockLength=i,c):(this.warnings.push("Zero buffer length"),s)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Lo)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:qt.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var za=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:r=Ts,warnings:n=[],valueBeforeDecode:s=dv}={}){this.blockLength=e,this.error=r,this.warnings=n,this.valueBeforeDecodeView=qt.BufferSourceConverter.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:qt.Convert.ToHex(this.valueBeforeDecodeView)}}};za.NAME="baseBlock";var Nn=class extends za{fromBER(e,r,n,s){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Nn.NAME="valueBlock";var X_=class extends Do(za){constructor({idBlock:e={}}={}){var r,n,s,i;super(),e?(this.isHexOnly=(r=e.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=e.valueHex?qt.BufferSourceConverter.toUint8Array(e.valueHex):dv,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(s=e.tagNumber)!==null&&s!==void 0?s:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let r=0;switch(this.tagClass){case 1:r|=0;break;case 2:r|=64;break;case 3:r|=128;break;case 4:r|=192;break;default:return this.error="Unknown tag class",Lo}if(this.isConstructed&&(r|=32),this.tagNumber<31&&!this.isHexOnly){let s=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,r|=i,s[0]=r}return s.buffer}if(!this.isHexOnly){let s=gr.utilToBase(this.tagNumber,7),i=new Uint8Array(s),o=s.byteLength,a=new Uint8Array(o+1);if(a[0]=r|31,!e){for(let c=0;c<o-1;c++)a[c+1]=i[c]|128;a[o]=i[o-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=r|31,!e){let s=this.valueHexView;for(let i=0;i<s.length-1;i++)n[i+1]=s[i]|128;n[this.valueHexView.byteLength]=s[s.length-1]}return n.buffer}fromBER(e,r,n){let s=qt.BufferSourceConverter.toUint8Array(e);if(!Da(this,s,r,n))return-1;let i=s.subarray(r,r+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let l=c+1;if(l>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(i[l]&128)===0)break}this.blockLength=c+1;let u=this.valueHexView=new Uint8Array(c);for(let l=0;l<c;l++)u[l]=i[l+1]&127;this.blockLength<=9?this.tagNumber=gr.utilFromBase(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return r+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};X_.NAME="identificationBlock";var J_=class extends za{constructor({lenBlock:e={}}={}){var r,n,s;super(),this.isIndefiniteForm=(r=e.isIndefiniteForm)!==null&&r!==void 0?r:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(s=e.length)!==null&&s!==void 0?s:0}fromBER(e,r,n){let s=qt.BufferSourceConverter.toUint8Array(e);if(!Da(this,s,r,n))return-1;let i=s.subarray(r,r+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,r+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,r+this.blockLength;let o=i[0]&127;if(o>8)return this.error="Too big integer",-1;if(o+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=r+1,c=s.subarray(a,a+o);return c[o-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=gr.utilFromBase(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=o+1,r+this.blockLength}toBER(e=!1){let r,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=128),r;if(this.longFormUsed){let s=gr.utilToBase(this.length,8);if(s.byteLength>127)return this.error="Too big length",Lo;if(r=new ArrayBuffer(s.byteLength+1),e)return r;let i=new Uint8Array(s);n=new Uint8Array(r),n[0]=s.byteLength|128;for(let o=0;o<s.byteLength;o++)n[o+1]=i[o];return r}return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=this.length),r}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};J_.NAME="lengthBlock";var Ne={},An=class extends za{constructor({name:e=Ts,optional:r=!1,primitiveSchema:n,...s}={},i){super(s),this.name=e,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new X_(s),this.lenBlock=new J_(s),this.valueBlock=i?new i(s):new Nn(s)}fromBER(e,r,n,s){let i=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(e,r){let n=r||new fh;r||z7(this);let s=this.idBlock.toBER(e);if(n.write(s),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let o=this.lenBlock.toBER(e);n.write(o),n.write(i)}return r?Lo:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():qt.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,r=qt.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${r}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let r=this.toBER(),n=e.toBER();return gr.isEqualBuffer(r,n)}};An.NAME="BaseBlock";function z7(t){var e;if(t instanceof Ne.Constructed)for(let r of t.valueBlock.value)z7(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var qm=class extends An{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Ts,...r}={},n){super(r,n),e&&this.fromString(e)}fromBER(e,r,n){let s=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};qm.NAME="BaseStringBlock";var Y_=class extends Do(Nn){constructor({isHexOnly:e=!0,...r}={}){super(r),this.isHexOnly=e}};Y_.NAME="PrimitiveValueBlock";var L7,Hm=class extends An{constructor(e={}){super(e,Y_),this.idBlock.isConstructed=!1}};L7=Hm;Ne.Primitive=L7;Hm.NAME="PRIMITIVE";var D7=100,U7=1e4,q7=16*1024*1024,Cie="Maximum ASN.1 nesting depth exceeded",kie="Maximum ASN.1 node count exceeded",Tie="Maximum ASN.1 content length exceeded";function _g(t={}){var e,r,n;return{depth:0,maxDepth:(e=t.maxDepth)!==null&&e!==void 0?e:D7,nodesCount:0,maxNodes:(r=t.maxNodes)!==null&&r!==void 0?r:U7,maxContentLength:(n=t.maxContentLength)!==null&&n!==void 0?n:q7}}function Iie(t){let e=new An({},Nn);return e.error=t,{offset:-1,result:e}}function Pie(t){if(t.nodesCount+=1,t.nodesCount>t.maxNodes)return kie}function Rie(t,e){if(t>e.maxContentLength)return Tie}function Hk(t,e,r,n){let s=n.depth+1;if(s>n.maxDepth)return Iie(Cie);n.depth=s;try{return fv(t,e,r,n)}finally{n.depth-=1}}function Oie(t,e){if(t instanceof e)return t;let r=new e;return r.idBlock=t.idBlock,r.lenBlock=t.lenBlock,r.warnings=t.warnings,r.valueBeforeDecodeView=t.valueBeforeDecodeView,r}function fv(t,e=0,r=t.length,n=_g()){let s=e,i=new An({},Nn),o=new za;if(!Da(o,t,e,r))return i.error=o.error,{offset:-1,result:i};if(!t.subarray(e,e+r).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=Pie(n);if(c)return i.error=c,{offset:-1,result:i};let u=i.idBlock.fromBER(t,e,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),u===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(e=u,r-=i.idBlock.blockLength,u=i.lenBlock.fromBER(t,e,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),u===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};e=u,r-=i.lenBlock.blockLength;let l=i.lenBlock.isIndefiniteForm?r:i.lenBlock.length,d=Rie(l,n);if(d)return i.error=d,{offset:-1,result:i};if(!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let f=An;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};f=Ne.EndOfContent;break;case 1:f=Ne.Boolean;break;case 2:f=Ne.Integer;break;case 3:f=Ne.BitString;break;case 4:f=Ne.OctetString;break;case 5:f=Ne.Null;break;case 6:f=Ne.ObjectIdentifier;break;case 10:f=Ne.Enumerated;break;case 12:f=Ne.Utf8String;break;case 13:f=Ne.RelativeObjectIdentifier;break;case 14:f=Ne.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:f=Ne.Sequence;break;case 17:f=Ne.Set;break;case 18:f=Ne.NumericString;break;case 19:f=Ne.PrintableString;break;case 20:f=Ne.TeletexString;break;case 21:f=Ne.VideotexString;break;case 22:f=Ne.IA5String;break;case 23:f=Ne.UTCTime;break;case 24:f=Ne.GeneralizedTime;break;case 25:f=Ne.GraphicString;break;case 26:f=Ne.VisibleString;break;case 27:f=Ne.GeneralString;break;case 28:f=Ne.UniversalString;break;case 29:f=Ne.CharacterString;break;case 30:f=Ne.BmpString;break;case 31:f=Ne.DATE;break;case 32:f=Ne.TimeOfDay;break;case 33:f=Ne.DateTime;break;case 34:f=Ne.Duration;break;default:{let p=i.idBlock.isConstructed?new Ne.Constructed:new Ne.Primitive;p.idBlock=i.idBlock,p.lenBlock=i.lenBlock,p.warnings=i.warnings,i=p}}break;default:f=i.idBlock.isConstructed?Ne.Constructed:Ne.Primitive}return i=Oie(i,f),u=i.fromBER(t,e,l,n),i.valueBeforeDecodeView=t.subarray(s,s+i.blockLength),{offset:u,result:i}}function Nie(t,e={}){if(!t.byteLength){let r=new An({},Nn);return r.error="Input buffer has zero length",{offset:-1,result:r}}return fv(qt.BufferSourceConverter.toUint8Array(t).slice(),0,t.byteLength,_g(e))}function Bie(t,e){return t?1:e}var jo=class extends Nn{constructor({value:e=[],isIndefiniteForm:r=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=r}fromBER(e,r,n,s){let i=qt.BufferSourceConverter.toUint8Array(e),o=s??_g();if(!Da(this,i,r,n))return-1;if(this.valueBeforeDecodeView=i.subarray(r,r+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),r;let a=r;for(;Bie(this.isIndefiniteForm,n)>0;){let c=Hk(i,a,n,o);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Um)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Um?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,r){let n=r||new fh;for(let s=0;s<this.value.length;s++)this.value[s].toBER(e,n);return r?Lo:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let r of this.value)e.value.push(r.toJSON());return e}};jo.NAME="ConstructedValueBlock";var H7,La=class extends An{constructor(e={}){super(e,jo),this.idBlock.isConstructed=!0}fromBER(e,r,n,s){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
72
|
+
`).map(s=>` ${s}`).join(`
|
|
73
|
+
`));let r=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${r} :
|
|
74
|
+
${e.join(`
|
|
75
|
+
`)}`:`${r} :`}};H7=La;Ne.Constructed=H7;La.NAME="CONSTRUCTED";var Q_=class extends Nn{fromBER(e,r,n){return r}toBER(e){return Lo}};Q_.override="EndOfContentValueBlock";var F7,Fm=class extends An{constructor(e={}){super(e,Q_),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};F7=Fm;Ne.EndOfContent=F7;Fm.NAME=Um;var V7,Vm=class extends An{constructor(e={}){super(e,Nn),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,r,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,r+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):r+n}toBER(e,r){let n=new ArrayBuffer(2);if(!e){let s=new Uint8Array(n);s[0]=5,s[1]=0}return r&&r.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};V7=Vm;Ne.Null=V7;Vm.NAME="NULL";var ev=class extends Do(Nn){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...r}={}){super(r),r.valueHex?this.valueHexView=qt.BufferSourceConverter.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,r,n){let s=qt.BufferSourceConverter.toUint8Array(e);return Da(this,s,r,n)?(this.valueHexView=s.subarray(r,r+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,gr.utilDecodeTC.call(this),this.blockLength=n,r+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ev.NAME="BooleanValueBlock";var K7,Km=class extends An{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,ev),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};K7=Km;Ne.Boolean=K7;Km.NAME="BOOLEAN";var tv=class extends Do(jo){constructor({isConstructed:e=!1,...r}={}){super(r),this.isConstructed=e}fromBER(e,r,n,s){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=jo.prototype.fromBER.call(this,e,r,n,s),i===-1)return i;for(let o=0;o<this.value.length;o++){let a=this.value[o].constructor.NAME;if(a===Um){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==M7)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,i=super.fromBER(e,r,n),this.blockLength=n;return i}toBER(e,r){return this.isConstructed?jo.prototype.toBER.call(this,e,r):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};tv.NAME="OctetStringValueBlock";var Fk,Zm=class extends An{constructor({idBlock:e={},lenBlock:r={},...n}={}){var s,i;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},tv),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,r,n,s){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),r;if(!this.valueBlock.isConstructed){let o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(r,r+n);try{if(o.byteLength){let a=s??_g(),c=Hk(o,0,o.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,r,n,s)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return La.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,r=qt.Convert.ToHex(this.valueBlock.valueHexView);return`${e} : ${r}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let r of this.valueBlock.value)r instanceof Fk&&e.push(r.valueBlock.valueHexView);return qt.BufferSourceConverter.concat(e)}};Fk=Zm;Ne.OctetString=Fk;Zm.NAME=M7;var rv=class extends Do(jo){constructor({unusedBits:e=0,isConstructed:r=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,r,n,s){if(!n)return r;let i=-1;if(this.isConstructed){if(i=jo.prototype.fromBER.call(this,e,r,n,s),i===-1)return i;for(let c of this.value){let u=c.constructor.NAME;if(u===Um){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(u!==j7)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=c.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return i}let o=qt.BufferSourceConverter.toUint8Array(e);if(!Da(this,o,r,n))return-1;let a=o.subarray(r,r+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let u=s??_g(),l=Hk(c,0,c.byteLength,u);l.offset!==-1&&l.offset===n-1&&(this.value=[l.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,r+n}toBER(e,r){if(this.isConstructed)return jo.prototype.toBER.call(this,e,r);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let s=new Uint8Array(1);return s[0]=0,s.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};rv.NAME="BitStringValueBlock";var Z7,Gm=class extends An{constructor({idBlock:e={},lenBlock:r={},...n}={}){var s,i;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},rv),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,r,n,s){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,r,n,s)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return La.prototype.onAsciiEncoding.call(this);{let e=[],r=this.valueBlock.valueHexView;for(let o of r)e.push(o.toString(2).padStart(8,"0"));let n=e.join(""),s=this.constructor.NAME,i=n.substring(0,n.length-this.valueBlock.unusedBits);return`${s} : ${i}`}}};Z7=Gm;Ne.BitString=Z7;Gm.NAME=j7;var G7;function $ie(t,e){let r=new Uint8Array([0]),n=new Uint8Array(t),s=new Uint8Array(e),i=n.slice(0),o=i.length-1,a=s.slice(0),c=a.length-1,u=0,l=c<o?o:c,d=0;for(let f=l;f>=0;f--,d++)!0===d<a.length?u=i[o-d]+a[c-d]+r[0]:u=i[o-d]+r[0],r[0]=u/10,!0===d>=i.length?i=gr.utilConcatView(new Uint8Array([u%10]),i):i[o-d]=u%10;return r[0]>0&&(i=gr.utilConcatView(r,i)),i}function B7(t){if(t>=Lm.length)for(let e=Lm.length;e<=t;e++){let r=new Uint8Array([0]),n=Lm[e-1].slice(0);for(let s=n.length-1;s>=0;s--){let i=new Uint8Array([(n[s]<<1)+r[0]]);r[0]=i[0]/10,n[s]=i[0]%10}r[0]>0&&(n=gr.utilConcatView(r,n)),Lm.push(n)}return Lm[t]}function Mie(t,e){let r=0,n=new Uint8Array(t),s=new Uint8Array(e),i=n.slice(0),o=i.length-1,a=s.slice(0),c=a.length-1,u,l=0;for(let d=c;d>=0;d--,l++)u=i[o-l]-a[c-l]-r,!0===u<0?(r=1,i[o-l]=u+10):(r=0,i[o-l]=u);if(r>0)for(let d=o-c+1;d>=0;d--,l++)if(u=i[o-l]-r,u<0)r=1,i[o-l]=u+10;else{r=0,i[o-l]=u;break}return i.slice()}var Wm=class extends Do(Nn){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=gr.utilDecodeTC.call(this)))}constructor({value:e,...r}={}){super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(gr.utilEncodeTC(e))}get valueDec(){return this._valueDec}fromDER(e,r,n,s=0){let i=this.fromBER(e,r,n);if(i===-1)return i;let o=this.valueHexView;return o[0]===0&&(o[1]&128)!==0?this.valueHexView=o.subarray(1):s!==0&&o.length<s&&(s-o.length>1&&(s=o.length+1),this.valueHexView=o.subarray(s-o.length)),i}toDER(e=!1){let r=this.valueHexView;switch(!0){case(r[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(r,1),this.valueHexView=n}break;case(r[0]===0&&(r[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,r,n){let s=super.fromBER(e,r,n);return s===-1||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,r=new Uint8Array(this.valueHexView.length*8/3),n=0,s,i=this.valueHexView,o="",a=!1;for(let c=i.byteLength-1;c>=0;c--){s=i[c];for(let u=0;u<8;u++)(s&1)===1&&(n===e?(r=Mie(B7(n),r),o="-"):r=$ie(r,B7(n))),n++,s>>=1}for(let c=0;c<r.length;c++)r[c]&&(a=!0),a&&(o+=O7.charAt(r[c]));return a===!1&&(o+=O7.charAt(0)),o}};G7=Wm;Wm.NAME="IntegerValueBlock";Object.defineProperty(G7.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Dm,hh=class extends An{constructor(e={}){super(e,Wm),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return W_(),BigInt(this.valueBlock.toString())}static fromBigInt(e){W_();let r=BigInt(e),n=new fh,s=r.toString(16).replace(/^-/,""),i=new Uint8Array(qt.Convert.FromHex(s));if(r<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${qt.Convert.ToHex(a)}`)+r,l=qt.BufferSourceConverter.toUint8Array(qt.Convert.FromHex(u.toString(16)));l[0]|=128,n.write(l)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new Dm({valueHex:n.final()})}convertToDER(){let e=new Dm({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Dm({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Dm=hh;Ne.Integer=Dm;hh.NAME="INTEGER";var W7,Xm=class extends hh{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};W7=Xm;Ne.Enumerated=W7;Xm.NAME="ENUMERATED";var Jm=class extends Do(Nn){constructor({valueDec:e=-1,isFirstSid:r=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=r}fromBER(e,r,n){if(!n)return r;let s=qt.BufferSourceConverter.toUint8Array(e);if(!Da(this,s,r,n))return-1;let i=s.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=gr.utilFromBase(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}set valueBigInt(e){W_();let r=BigInt(e).toString(2);for(;r.length%7;)r="0"+r;let n=new Uint8Array(r.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(r.slice(s*7,s*7+7),2)+(s+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=s[o]|128;return i[this.blockLength-1]=s[this.blockLength-1],i.buffer}let r=gr.utilToBase(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Lo;let n=new Uint8Array(r.byteLength);if(!e){let s=new Uint8Array(r),i=r.byteLength-1;for(let o=0;o<i;o++)n[o]=s[o]|128;n[i]=s[i]}return n}toString(){let e="";if(this.isHexOnly)e=qt.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let r=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",r-=40):(e="2.",r-=80),e+=r.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Jm.NAME="sidBlock";var nv=class extends Nn{constructor({value:e=Ts,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let s=r;for(;n>0;){let i=new Jm;if(s=i.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=i.error,s;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return s}toBER(e){let r=[];for(let n=0;n<this.value.length;n++){let s=this.value[n].toBER(e);if(s.byteLength===0)return this.error=this.value[n].error,Lo;r.push(s)}return qk(r)}fromString(e){this.value=[];let r=0,n=0,s="",i=!1;do if(n=e.indexOf(".",r),n===-1?s=e.substring(r):s=e.substring(r,n),r=n+1,i){let o=this.value[0],a=0;switch(o.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(s,10);if(isNaN(c))return;o.valueDec=c+a,i=!1}else{let o=new Jm;if(s>Number.MAX_SAFE_INTEGER){W_();let a=BigInt(s);o.valueBigInt=a}else if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return;this.value.length||(o.isFirstSid=!0,i=!0),this.value.push(o)}while(n!==-1)}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),r?(s=`{${s}}`,this.value[n].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}};nv.NAME="ObjectIdentifierValueBlock";var X7,Ym=class extends An{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,nv),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};X7=Ym;Ne.ObjectIdentifier=X7;Ym.NAME="OBJECT IDENTIFIER";var Qm=class extends Do(za){constructor({valueDec:e=0,...r}={}){super(r),this.valueDec=e}fromBER(e,r,n){if(n===0)return r;let s=qt.BufferSourceConverter.toUint8Array(e);if(!Da(this,s,r,n))return-1;let i=s.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=gr.utilFromBase(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=s[o]|128;return i[this.blockLength-1]=s[this.blockLength-1],i.buffer}let r=gr.utilToBase(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Lo;let n=new Uint8Array(r.byteLength);if(!e){let s=new Uint8Array(r),i=r.byteLength-1;for(let o=0;o<i;o++)n[o]=s[o]|128;n[i]=s[i]}return n.buffer}toString(){let e="";return this.isHexOnly?e=qt.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Qm.NAME="relativeSidBlock";var sv=class extends Nn{constructor({value:e=Ts,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let s=r;for(;n>0;){let i=new Qm;if(s=i.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=i.error,s;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return s}toBER(e,r){let n=[];for(let s=0;s<this.value.length;s++){let i=this.value[s].toBER(e);if(i.byteLength===0)return this.error=this.value[s].error,Lo;n.push(i)}return qk(n)}fromString(e){this.value=[];let r=0,n=0,s="";do{n=e.indexOf(".",r),n===-1?s=e.substring(r):s=e.substring(r,n),r=n+1;let i=new Qm;if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),r&&(s=`{${s}}`),e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}};sv.NAME="RelativeObjectIdentifierValueBlock";var J7,eg=class extends An{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,sv),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};J7=eg;Ne.RelativeObjectIdentifier=J7;eg.NAME="RelativeObjectIdentifier";var Y7,tg=class extends La{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Y7=tg;Ne.Sequence=Y7;tg.NAME="SEQUENCE";var Q7,rg=class extends La{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Q7=rg;Ne.Set=Q7;rg.NAME="SET";var iv=class extends Do(Nn){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ts}toJSON(){return{...super.toJSON(),value:this.value}}};iv.NAME="StringValueBlock";var ov=class extends iv{};ov.NAME="SimpleStringValueBlock";var gs=class extends qm{constructor({...e}={}){super(e,ov)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,qt.BufferSourceConverter.toUint8Array(e))}fromString(e){let r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);this.valueBlock.value=e}};gs.NAME="SIMPLE STRING";var av=class extends gs{fromBuffer(e){this.valueBlock.valueHexView=qt.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=qt.Convert.ToUtf8String(e)}catch(r){this.warnings.push(`Error during "decodeURIComponent": ${r}, using raw string`),this.valueBlock.value=qt.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(qt.Convert.FromUtf8String(e)),this.valueBlock.value=e}};av.NAME="Utf8StringValueBlock";var eM,zo=class extends av{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};eM=zo;Ne.Utf8String=eM;zo.NAME="UTF8String";var cv=class extends gs{fromBuffer(e){this.valueBlock.value=qt.Convert.ToUtf16String(e),this.valueBlock.valueHexView=qt.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(qt.Convert.FromUtf16String(e))}};cv.NAME="BmpStringValueBlock";var tM,ng=class extends cv{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};tM=ng;Ne.BmpString=tM;ng.NAME="BMPString";var uv=class extends gs{fromBuffer(e){let r=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(r);for(let s=0;s<n.length;s+=4)n[s]=n[s+3],n[s+1]=n[s+2],n[s+2]=0,n[s+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(r))}fromString(e){let r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r*4);for(let s=0;s<r;s++){let i=gr.utilToBase(e.charCodeAt(s),8),o=new Uint8Array(i);if(o.length>4)continue;let a=4-o.length;for(let c=o.length-1;c>=0;c--)n[s*4+c+a]=o[c]}this.valueBlock.value=e}};uv.NAME="UniversalStringValueBlock";var rM,sg=class extends uv{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};rM=sg;Ne.UniversalString=rM;sg.NAME="UniversalString";var nM,ig=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};nM=ig;Ne.NumericString=nM;ig.NAME="NumericString";var sM,og=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};sM=og;Ne.PrintableString=sM;og.NAME="PrintableString";var iM,ag=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};iM=ag;Ne.TeletexString=iM;ag.NAME="TeletexString";var oM,cg=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};oM=cg;Ne.VideotexString=oM;cg.NAME="VideotexString";var aM,ug=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};aM=ug;Ne.IA5String=aM;ug.NAME="IA5String";var cM,lg=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};cM=lg;Ne.GraphicString=cM;lg.NAME="GraphicString";var uM,ph=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};uM=ph;Ne.VisibleString=uM;ph.NAME="VisibleString";var lM,dg=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};lM=dg;Ne.GeneralString=lM;dg.NAME="GeneralString";var dM,fg=class extends gs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};dM=fg;Ne.CharacterString=dM;fg.NAME="CharacterString";var fM,mh=class extends ph{constructor({value:e,valueDate:r,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,qt.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),r=new ArrayBuffer(e.length),n=new Uint8Array(r);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return r}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let s=parseInt(n[1],10);s>=50?this.year=1900+s:this.year=2e3+s,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let r=new Array(7);return r[0]=gr.padNumber(this.year<2e3?this.year-1900:this.year-2e3,2),r[1]=gr.padNumber(this.month,2),r[2]=gr.padNumber(this.day,2),r[3]=gr.padNumber(this.hour,2),r[4]=gr.padNumber(this.minute,2),r[5]=gr.padNumber(this.second,2),r[6]="Z",r.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};fM=mh;Ne.UTCTime=fM;mh.NAME="UTCTime";var hM,hg=class extends mh{constructor(e={}){var r;super(e),(r=this.millisecond)!==null&&r!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let r=!1,n="",s="",i=0,o,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),r=!0;else{let d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,f=n.indexOf("+"),p="";if(f===-1&&(f=n.indexOf("-"),d=-1),f!==-1){if(p=n.substring(f+1),n=n.substring(0,f),p.length!==2&&p.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(p.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=d*m,p.length===4){if(m=parseInt(p.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=d*m}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let d=new Number(`0${n.substring(u)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");i=d.valueOf(),s=n.substring(0,u)}else s=n;switch(!0){case s.length===8:if(o=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let d=60*i;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case s.length===12:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let d=60*i;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case s.length===14:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let d=1e3*i;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}let l=o.exec(s);if(l===null)throw new Error("Wrong input string for conversion");for(let d=1;d<l.length;d++)switch(d){case 1:this.year=parseInt(l[d],10);break;case 2:this.month=parseInt(l[d],10);break;case 3:this.day=parseInt(l[d],10);break;case 4:this.hour=parseInt(l[d],10)+a;break;case 5:this.minute=parseInt(l[d],10)+c;break;case 6:this.second=parseInt(l[d],10);break;default:throw new Error("Wrong input string for conversion")}if(r===!1){let d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let r=[];return r.push(gr.padNumber(this.year,4)),r.push(gr.padNumber(this.month,2)),r.push(gr.padNumber(this.day,2)),r.push(gr.padNumber(this.hour,2)),r.push(gr.padNumber(this.minute,2)),r.push(gr.padNumber(this.second,2)),this.millisecond!==0&&(r.push("."),r.push(gr.padNumber(this.millisecond,3))),r.push("Z"),r.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};hM=hg;Ne.GeneralizedTime=hM;hg.NAME="GeneralizedTime";var pM,pg=class extends zo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};pM=pg;Ne.DATE=pM;pg.NAME="DATE";var mM,mg=class extends zo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};mM=mg;Ne.TimeOfDay=mM;mg.NAME="TimeOfDay";var gM,gg=class extends zo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};gM=gg;Ne.DateTime=gM;gg.NAME="DateTime";var yM,yg=class extends zo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};yM=yg;Ne.Duration=yM;yg.NAME="Duration";var xM,xg=class extends zo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};xM=xg;Ne.TIME=xM;xg.NAME="TIME";var Sl=class{constructor({name:e=Ts,optional:r=!1}={}){this.name=e,this.optional=r}},lv=class extends Sl{constructor({value:e=[],...r}={}){super(r),this.value=e}},bg=class extends Sl{constructor({value:e=new Sl,local:r=!1,...n}={}){super(n),this.value=e,this.local=r}},Uk=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=qt.BufferSourceConverter.toUint8Array(e)}constructor({data:e=dv}={}){this.dataView=qt.BufferSourceConverter.toUint8Array(e)}fromBER(e,r,n){let s=r+n;return this.dataView=qt.BufferSourceConverter.toUint8Array(e).subarray(r,s),s}toBER(e){return this.dataView.slice().buffer}};function dh(t,e,r){if(r instanceof lv){for(let i of r.value)if(dh(t,e,i).verified)return{verified:!0,result:t};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Dk)&&(i.name=r.name),i}}if(r instanceof Sl)return r.hasOwnProperty(Dk)&&(t[r.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(bie in r))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(Sie in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(Aie in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let n=r.idBlock.toBER(!1);if(n.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(r.idBlock.fromBER(n,0,n.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(r.idBlock.hasOwnProperty(_ie)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(vie)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(wie)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(xie in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(r.idBlock.isHexOnly){if(!(N7 in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let i=r.idBlock.valueHexView,o=e.idBlock.valueHexView;if(i.length!==o.length)return{verified:!1,result:t};for(let a=0;a<i.length;a++)if(i[a]!==o[1])return{verified:!1,result:t}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Ts),r.name&&(t[r.name]=e)),r instanceof Ne.Constructed){let i=0,o={verified:!1,result:{error:"Unknown error"}},a=r.valueBlock.value.length;if(a>0&&r.valueBlock.value[0]instanceof bg&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&r.valueBlock.value.length!==0){let c=!0;for(let u=0;u<r.valueBlock.value.length;u++)c=c&&(r.valueBlock.value[u].optional||!1);return c?{verified:!0,result:t}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Ts),r.name&&delete t[r.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let c=0;c<a;c++)if(c-i>=e.valueBlock.value.length){if(r.valueBlock.value[c].optional===!1){let u={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Ts),r.name&&(delete t[r.name],u.name=r.name)),u}}else if(r.valueBlock.value[0]instanceof bg){if(o=dh(t,e.valueBlock.value[c],r.valueBlock.value[0].value),o.verified===!1)if(r.valueBlock.value[0].optional)i++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Ts),r.name&&delete t[r.name]),o;if(Dk in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let u={};Eie in r.valueBlock.value[0]&&r.valueBlock.value[0].local?u=e:u=t,typeof u[r.valueBlock.value[0].name]>"u"&&(u[r.valueBlock.value[0].name]=[]),u[r.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(o=dh(t,e.valueBlock.value[c-i],r.valueBlock.value[c]),o.verified===!1)if(r.valueBlock.value[c].optional)i++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Ts),r.name&&delete t[r.name]),o;if(o.verified===!1){let c={verified:!1,result:t};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Ts),r.name&&(delete t[r.name],c.name=r.name)),c}return{verified:!0,result:t}}if(r.primitiveSchema&&N7 in e.valueBlock){let i=fv(e.valueBlock.valueHexView);if(i.offset===-1){let o={verified:!1,result:i.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Ts),r.name&&(delete t[r.name],o.name=r.name)),o}return dh(t,i.result,r.primitiveSchema)}return{verified:!0,result:t}}function jie(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let r=fv(qt.BufferSourceConverter.toUint8Array(t));return r.offset===-1?{verified:!1,result:r.result}:dh(r.result,r.result,e)}lt.Any=Sl;lt.BaseBlock=An;lt.BaseStringBlock=qm;lt.BitString=Gm;lt.BmpString=ng;lt.Boolean=Km;lt.CharacterString=fg;lt.Choice=lv;lt.Constructed=La;lt.DATE=pg;lt.DEFAULT_MAX_CONTENT_LENGTH=q7;lt.DEFAULT_MAX_DEPTH=D7;lt.DEFAULT_MAX_NODES=U7;lt.DateTime=gg;lt.Duration=yg;lt.EndOfContent=Fm;lt.Enumerated=Xm;lt.GeneralString=dg;lt.GeneralizedTime=hg;lt.GraphicString=lg;lt.HexBlock=Do;lt.IA5String=ug;lt.Integer=hh;lt.Null=Vm;lt.NumericString=ig;lt.ObjectIdentifier=Ym;lt.OctetString=Zm;lt.Primitive=Hm;lt.PrintableString=og;lt.RawData=Uk;lt.RelativeObjectIdentifier=eg;lt.Repeated=bg;lt.Sequence=tg;lt.Set=rg;lt.TIME=xg;lt.TeletexString=ag;lt.TimeOfDay=mg;lt.UTCTime=mh;lt.UniversalString=sg;lt.Utf8String=zo;lt.ValueBlock=Nn;lt.VideotexString=cg;lt.ViewWriter=fh;lt.VisibleString=ph;lt.compareSchema=dh;lt.fromBER=Nie;lt.verifySchema=jie});var Sg=v(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.isArrayBuffer=Vk;Is.isSharedArrayBuffer=wM;Is.isArrayBufferLike=vg;Is.isArrayBufferView=SM;Is.isBufferSource=AM;Is.assertBufferSource=wg;Is.toUint8Array=hv;Is.toUint8ArrayCopy=EM;Is.toArrayBuffer=qie;Is.toArrayBufferLike=Hie;Is.toView=CM;Is.toViewCopy=Fie;var zie="[object ArrayBuffer]",Lie="[object SharedArrayBuffer]";function bM(t){return Object.prototype.toString.call(t)}function _M(t){return t===DataView||t.prototype instanceof DataView}function Die(t){return _M(t)?1:t.BYTES_PER_ELEMENT??1}function Uie(t){if(ArrayBuffer.isView(t))return!0;if(!t||typeof t!="object")return!1;let e=t;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&vg(e.buffer)}function vM(t){let e=hv(t),r=new Uint8Array(e.byteLength);return r.set(e),r}function Vk(t){return bM(t)===zie}function wM(t){return typeof SharedArrayBuffer<"u"&&bM(t)===Lie}function vg(t){return Vk(t)||wM(t)}function SM(t){return Uie(t)}function AM(t){return vg(t)||SM(t)}function wg(t){if(!AM(t))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function hv(t){return wg(t),vg(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function EM(t){return vM(t)}function qie(t){if(wg(t),Vk(t))return t;let e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(hv(t)),e}function Hie(t){return wg(t),vg(t)?t:t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:vM(t).buffer}function CM(t,e){if(wg(t),ArrayBuffer.isView(t)&&t.constructor===e)return t;let r=hv(t),n=Die(e);if(r.byteOffset%n!==0||r.byteLength%n!==0)throw new RangeError(`Cannot create ${e.name} over unaligned byte range`);return _M(e)?new e(r.buffer,r.byteOffset,r.byteLength):new e(r.buffer,r.byteOffset,r.byteLength/n)}function Fie(t,e){let r=EM(t);return CM(r,e)}});var TM=v(mv=>{"use strict";Object.defineProperty(mv,"__esModule",{value:!0});mv.concatToUint8Array=kM;mv.concat=Vie;var pv=Sg();function kM(t){let e=[],r=0;for(let i of t){let o=(0,pv.toUint8Array)(i);e.push(o),r+=o.byteLength}let n=new Uint8Array(r),s=0;for(let i of e)n.set(i,s),s+=i.byteLength;return n}function Vie(t,e,...r){let n,s;typeof e=="function"?(n=Array.from(t),s=e):(0,pv.isBufferSource)(t)?n=[t,e,...r].filter(pv.isBufferSource):(n=Array.from(t),e&&n.push(e),n.push(...r));let i=kM(n);return s?(0,pv.toView)(i,s):i.buffer}});var PM=v(Kk=>{"use strict";Object.defineProperty(Kk,"__esModule",{value:!0});Kk.equal=Kie;var IM=Sg();function Kie(t,e,r={}){let n=(0,IM.toUint8Array)(t),s=(0,IM.toUint8Array)(e);if(!r.constantTime&&n.byteLength!==s.byteLength)return!1;let i=Math.max(n.byteLength,s.byteLength),o=n.byteLength^s.byteLength;for(let a=0;a<i;a++)o|=(n[a]??0)^(s[a]??0);return o===0}});var NM=v(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.indexOf=OM;Ki.lastIndexOf=Jie;Ki.includes=Yie;Ki.startsWith=Qie;Ki.endsWith=eoe;Ki.slice=toe;Ki.tail=roe;Ki.copy=noe;Ki.compare=soe;var Uo=Sg();function gv(t,e,r){let n=Number.isFinite(t)?Math.trunc(t):e;return n<=0?0:n>=r?r:n}function Zie(t,e){let r=gv(e?.start,0,t),n=gv(e?.end,t,t);return n>=r?[r,n]:[r,r]}function Gie(t,e){let r=gv(e?.start,t,t),n=gv(e?.end,0,t);return r>=n?[n,r]:[r,r]}function RM(t,e,r){let n=Number.isFinite(t)?Math.trunc(t):e;return n<0?Math.max(r+n,0):n>r?r:n}function Wie(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function Xie(t){return new TextEncoder().encode(t)}function yv(t,e){return typeof t=="string"?e?.encoding==="utf8"?Xie(t):Wie(t):(0,Uo.toUint8Array)(t)}function xv(t,e,r){for(let n=0;n<e.byteLength;n++)if(t[r+n]!==e[n])return!1;return!0}function OM(t,e,r){let n=(0,Uo.toUint8Array)(t),s=yv(e,r),[i,o]=Zie(n.byteLength,r);if(s.byteLength===0)return i;let a=o-s.byteLength;if(a<i)return-1;for(let c=i;c<=a;c++)if(xv(n,s,c))return c;return-1}function Jie(t,e,r){let n=(0,Uo.toUint8Array)(t),s=yv(e,r),[i,o]=Gie(n.byteLength,r);if(s.byteLength===0)return o;let a=o-s.byteLength;if(a<i)return-1;for(let c=a;c>=i;c--)if(xv(n,s,c))return c;return-1}function Yie(t,e,r){return OM(t,e,r)!==-1}function Qie(t,e,r){let n=(0,Uo.toUint8Array)(t),s=yv(e,r);return s.byteLength>n.byteLength?!1:xv(n,s,0)}function eoe(t,e,r){let n=(0,Uo.toUint8Array)(t),s=yv(e,r);return s.byteLength>n.byteLength?!1:xv(n,s,n.byteLength-s.byteLength)}function toe(t,e,r){let n=(0,Uo.toUint8Array)(t),s=RM(e,0,n.byteLength),i=RM(r,n.byteLength,n.byteLength);return i<=s?n.subarray(s,s):n.subarray(s,i)}function roe(t,e){let r=(0,Uo.toUint8Array)(t),n=Number.isFinite(e)?Math.max(0,Math.trunc(e)):0;return n>=r.byteLength?r:r.subarray(r.byteLength-n)}function noe(t){return(0,Uo.toUint8ArrayCopy)(t)}function soe(t,e){let r=(0,Uo.toUint8Array)(t),n=(0,Uo.toUint8Array)(e),s=Math.min(r.byteLength,n.byteLength);for(let i=0;i<s;i++){if(r[i]<n[i])return-1;if(r[i]>n[i])return 1}return r.byteLength<n.byteLength?-1:r.byteLength>n.byteLength?1:0}});var ri=v(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.tail=ot.startsWith=ot.slice=ot.lastIndexOf=ot.indexOf=ot.includes=ot.endsWith=ot.copy=ot.compare=ot.equal=ot.concatToUint8Array=ot.concat=ot.toViewCopy=ot.toView=ot.toUint8ArrayCopy=ot.toUint8Array=ot.toArrayBufferLike=ot.toArrayBuffer=ot.isSharedArrayBuffer=ot.isBufferSource=ot.isArrayBufferView=ot.isArrayBufferLike=ot.isArrayBuffer=ot.assertBufferSource=void 0;var Si=Sg();Object.defineProperty(ot,"assertBufferSource",{enumerable:!0,get:function(){return Si.assertBufferSource}});Object.defineProperty(ot,"isArrayBuffer",{enumerable:!0,get:function(){return Si.isArrayBuffer}});Object.defineProperty(ot,"isArrayBufferLike",{enumerable:!0,get:function(){return Si.isArrayBufferLike}});Object.defineProperty(ot,"isArrayBufferView",{enumerable:!0,get:function(){return Si.isArrayBufferView}});Object.defineProperty(ot,"isBufferSource",{enumerable:!0,get:function(){return Si.isBufferSource}});Object.defineProperty(ot,"isSharedArrayBuffer",{enumerable:!0,get:function(){return Si.isSharedArrayBuffer}});Object.defineProperty(ot,"toArrayBuffer",{enumerable:!0,get:function(){return Si.toArrayBuffer}});Object.defineProperty(ot,"toArrayBufferLike",{enumerable:!0,get:function(){return Si.toArrayBufferLike}});Object.defineProperty(ot,"toUint8Array",{enumerable:!0,get:function(){return Si.toUint8Array}});Object.defineProperty(ot,"toUint8ArrayCopy",{enumerable:!0,get:function(){return Si.toUint8ArrayCopy}});Object.defineProperty(ot,"toView",{enumerable:!0,get:function(){return Si.toView}});Object.defineProperty(ot,"toViewCopy",{enumerable:!0,get:function(){return Si.toViewCopy}});var BM=TM();Object.defineProperty(ot,"concat",{enumerable:!0,get:function(){return BM.concat}});Object.defineProperty(ot,"concatToUint8Array",{enumerable:!0,get:function(){return BM.concatToUint8Array}});var ioe=PM();Object.defineProperty(ot,"equal",{enumerable:!0,get:function(){return ioe.equal}});var Ua=NM();Object.defineProperty(ot,"compare",{enumerable:!0,get:function(){return Ua.compare}});Object.defineProperty(ot,"copy",{enumerable:!0,get:function(){return Ua.copy}});Object.defineProperty(ot,"endsWith",{enumerable:!0,get:function(){return Ua.endsWith}});Object.defineProperty(ot,"includes",{enumerable:!0,get:function(){return Ua.includes}});Object.defineProperty(ot,"indexOf",{enumerable:!0,get:function(){return Ua.indexOf}});Object.defineProperty(ot,"lastIndexOf",{enumerable:!0,get:function(){return Ua.lastIndexOf}});Object.defineProperty(ot,"slice",{enumerable:!0,get:function(){return Ua.slice}});Object.defineProperty(ot,"startsWith",{enumerable:!0,get:function(){return Ua.startsWith}});Object.defineProperty(ot,"tail",{enumerable:!0,get:function(){return Ua.tail}})});var Al=v(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});gh.AsnPropTypes=gh.AsnTypeTypes=void 0;var $M;(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})($M||(gh.AsnTypeTypes=$M={}));var MM;(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null"})(MM||(gh.AsnPropTypes=MM={}))});var jM=v(bv=>{"use strict";Object.defineProperty(bv,"__esModule",{value:!0});bv.BitString=void 0;var ooe=(V(),H(F)),Zk=ooe.__importStar(Yc()),Gk=ri(),Wk=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,r=0){if(e)if(typeof e=="number")this.fromNumber(e);else if((0,Gk.isBufferSource)(e))this.unusedBits=r,this.value=(0,Gk.toArrayBuffer)(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof Zk.BitString))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=(0,Gk.toArrayBuffer)(e.valueBlock.valueHex),this}toASN(){return new Zk.BitString({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Zk.BitString({name:e})}toNumber(){let e="",r=new Uint8Array(this.value);for(let n of r)e+=n.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let r=e.toString(2),n=r.length+7>>3;this.unusedBits=(n<<3)-r.length;let s=new Uint8Array(n);r=r.padStart(n<<3,"0").split("").reverse().join("");let i=0;for(;i<n;)s[i]=parseInt(r.slice(i<<3,(i<<3)+8),2),i++;this.value=s.buffer}};bv.BitString=Wk});var zM=v(_v=>{"use strict";Object.defineProperty(_v,"__esModule",{value:!0});_v.OctetString=void 0;var aoe=(V(),H(F)),Xk=aoe.__importStar(Yc()),Jk=ri(),Yk=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):(0,Jk.isBufferSource)(e)?this.buffer=(0,Jk.toArrayBuffer)(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Xk.OctetString))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=(0,Jk.toArrayBuffer)(e.valueBlock.valueHex),this}toASN(){return new Xk.OctetString({valueHex:this.buffer})}toSchema(e){return new Xk.OctetString({name:e})}};_v.OctetString=Yk});var Qk=v(vv=>{"use strict";Object.defineProperty(vv,"__esModule",{value:!0});var LM=(V(),H(F));LM.__exportStar(jM(),vv);LM.__exportStar(zM(),vv)});var Ag=v(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.AsnNullConverter=Se.AsnGeneralizedTimeConverter=Se.AsnUTCTimeConverter=Se.AsnCharacterStringConverter=Se.AsnGeneralStringConverter=Se.AsnVisibleStringConverter=Se.AsnGraphicStringConverter=Se.AsnIA5StringConverter=Se.AsnVideotexStringConverter=Se.AsnTeletexStringConverter=Se.AsnPrintableStringConverter=Se.AsnNumericStringConverter=Se.AsnUniversalStringConverter=Se.AsnBmpStringConverter=Se.AsnUtf8StringConverter=Se.AsnConstructedOctetStringConverter=Se.AsnOctetStringConverter=Se.AsnBooleanConverter=Se.AsnObjectIdentifierConverter=Se.AsnBitStringConverter=Se.AsnIntegerBigIntConverter=Se.AsnIntegerArrayBufferConverter=Se.AsnEnumeratedConverter=Se.AsnIntegerConverter=Se.AsnAnyConverter=void 0;Se.defaultConverter=loe;var coe=(V(),H(F)),Pr=coe.__importStar(Yc()),wv=ri(),cn=Al(),uoe=Qk();Se.AsnAnyConverter={fromASN:t=>t instanceof Pr.Null?null:(0,wv.toArrayBuffer)(t.valueBeforeDecodeView),toASN:t=>{if(t===null)return new Pr.Null;let e=Pr.fromBER(t);if(e.result.error)throw new Error(e.result.error);return e.result}};Se.AsnIntegerConverter={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new Pr.Integer({value:+t})};Se.AsnEnumeratedConverter={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new Pr.Enumerated({value:t})};Se.AsnIntegerArrayBufferConverter={fromASN:t=>(0,wv.toArrayBuffer)(t.valueBlock.valueHexView),toASN:t=>new Pr.Integer({valueHex:t})};Se.AsnIntegerBigIntConverter={fromASN:t=>t.toBigInt(),toASN:t=>Pr.Integer.fromBigInt(t)};Se.AsnBitStringConverter={fromASN:t=>(0,wv.toArrayBuffer)(t.valueBlock.valueHexView),toASN:t=>new Pr.BitString({valueHex:t})};Se.AsnObjectIdentifierConverter={fromASN:t=>t.valueBlock.toString(),toASN:t=>new Pr.ObjectIdentifier({value:t})};Se.AsnBooleanConverter={fromASN:t=>t.valueBlock.value,toASN:t=>new Pr.Boolean({value:t})};Se.AsnOctetStringConverter={fromASN:t=>(0,wv.toArrayBuffer)(t.valueBlock.valueHexView),toASN:t=>new Pr.OctetString({valueHex:t})};Se.AsnConstructedOctetStringConverter={fromASN:t=>new uoe.OctetString(t.getValue()),toASN:t=>t.toASN()};function Ai(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}Se.AsnUtf8StringConverter=Ai(Pr.Utf8String);Se.AsnBmpStringConverter=Ai(Pr.BmpString);Se.AsnUniversalStringConverter=Ai(Pr.UniversalString);Se.AsnNumericStringConverter=Ai(Pr.NumericString);Se.AsnPrintableStringConverter=Ai(Pr.PrintableString);Se.AsnTeletexStringConverter=Ai(Pr.TeletexString);Se.AsnVideotexStringConverter=Ai(Pr.VideotexString);Se.AsnIA5StringConverter=Ai(Pr.IA5String);Se.AsnGraphicStringConverter=Ai(Pr.GraphicString);Se.AsnVisibleStringConverter=Ai(Pr.VisibleString);Se.AsnGeneralStringConverter=Ai(Pr.GeneralString);Se.AsnCharacterStringConverter=Ai(Pr.CharacterString);Se.AsnUTCTimeConverter={fromASN:t=>t.toDate(),toASN:t=>new Pr.UTCTime({valueDate:t})};Se.AsnGeneralizedTimeConverter={fromASN:t=>t.toDate(),toASN:t=>new Pr.GeneralizedTime({valueDate:t})};Se.AsnNullConverter={fromASN:()=>null,toASN:()=>new Pr.Null};function loe(t){switch(t){case cn.AsnPropTypes.Any:return Se.AsnAnyConverter;case cn.AsnPropTypes.BitString:return Se.AsnBitStringConverter;case cn.AsnPropTypes.BmpString:return Se.AsnBmpStringConverter;case cn.AsnPropTypes.Boolean:return Se.AsnBooleanConverter;case cn.AsnPropTypes.CharacterString:return Se.AsnCharacterStringConverter;case cn.AsnPropTypes.Enumerated:return Se.AsnEnumeratedConverter;case cn.AsnPropTypes.GeneralString:return Se.AsnGeneralStringConverter;case cn.AsnPropTypes.GeneralizedTime:return Se.AsnGeneralizedTimeConverter;case cn.AsnPropTypes.GraphicString:return Se.AsnGraphicStringConverter;case cn.AsnPropTypes.IA5String:return Se.AsnIA5StringConverter;case cn.AsnPropTypes.Integer:return Se.AsnIntegerConverter;case cn.AsnPropTypes.Null:return Se.AsnNullConverter;case cn.AsnPropTypes.NumericString:return Se.AsnNumericStringConverter;case cn.AsnPropTypes.ObjectIdentifier:return Se.AsnObjectIdentifierConverter;case cn.AsnPropTypes.OctetString:return Se.AsnOctetStringConverter;case cn.AsnPropTypes.PrintableString:return Se.AsnPrintableStringConverter;case cn.AsnPropTypes.TeletexString:return Se.AsnTeletexStringConverter;case cn.AsnPropTypes.UTCTime:return Se.AsnUTCTimeConverter;case cn.AsnPropTypes.UniversalString:return Se.AsnUniversalStringConverter;case cn.AsnPropTypes.Utf8String:return Se.AsnUtf8StringConverter;case cn.AsnPropTypes.VideotexString:return Se.AsnVideotexStringConverter;case cn.AsnPropTypes.VisibleString:return Se.AsnVisibleStringConverter;default:return null}}});var Sv=v(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});Eg.isConvertible=DM;Eg.isTypeOfArray=UM;Eg.isArrayEqual=doe;function DM(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:DM(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function UM(t){if(t){let e=Object.getPrototypeOf(t);return e?.prototype?.constructor===Array?!0:UM(e)}return!1}function doe(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<t.byteLength;s++)if(r[s]!==n[s])return!1;return!0}});var HM=v(Av=>{"use strict";Object.defineProperty(Av,"__esModule",{value:!0});Av.AsnSchemaStorage=void 0;var foe=(V(),H(F)),ni=foe.__importStar(Yc()),yh=Al(),qM=Sv(),eT=class{items=new WeakMap;has(e){return this.items.has(e)}get(e,r=!1){let n=this.items.get(e);if(!n)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(r&&!n.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){let r=this.get(e);r.schema||(r.schema=this.create(e,!0))}createDefault(e){let r={type:yh.AsnTypeTypes.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(r,n),r.items=Object.assign({},r.items,n.items)),r}create(e,r){let n=this.items.get(e)||this.createDefault(e),s=[];for(let i in n.items){let o=n.items[i],a=r?i:"",c;if(typeof o.type=="number"){let l=yh.AsnPropTypes[o.type],d=ni[l];if(!d)throw new Error(`Cannot get ASN1 class by name '${l}'`);c=new d({name:a})}else(0,qM.isConvertible)(o.type)?c=new o.type().toSchema(a):o.optional?this.get(o.type).type===yh.AsnTypeTypes.Choice?c=new ni.Any({name:a}):(c=this.create(o.type,!1),c.name=a):c=new ni.Any({name:a});let u=!!o.optional||o.defaultValue!==void 0;if(o.repeated){c.name="";let l=o.repeated==="set"?ni.Set:ni.Sequence;c=new l({name:"",value:[new ni.Repeated({name:a,value:c})]})}if(o.context!==null&&o.context!==void 0)if(o.implicit)if(typeof o.type=="number"||(0,qM.isConvertible)(o.type)){let l=o.repeated?ni.Constructed:ni.Primitive;s.push(new l({name:a,optional:u,idBlock:{tagClass:3,tagNumber:o.context}}))}else{this.cache(o.type);let l=!!o.repeated,d=l?c:this.get(o.type,!0).schema;d="valueBlock"in d?d.valueBlock.value:d.value,s.push(new ni.Constructed({name:l?"":a,optional:u,idBlock:{tagClass:3,tagNumber:o.context},value:d}))}else s.push(new ni.Constructed({optional:u,idBlock:{tagClass:3,tagNumber:o.context},value:[c]}));else c.optional=u,s.push(c)}switch(n.type){case yh.AsnTypeTypes.Sequence:return new ni.Sequence({value:s,name:""});case yh.AsnTypeTypes.Set:return new ni.Set({value:s,name:""});case yh.AsnTypeTypes.Choice:return new ni.Choice({value:s,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,r){return this.items.set(e,r),this}findParentSchema(e){let r=Object.getPrototypeOf(e);return r?this.items.get(r)||this.findParentSchema(r):null}};Av.AsnSchemaStorage=eT});var Cv=v(Ev=>{"use strict";Object.defineProperty(Ev,"__esModule",{value:!0});Ev.schemaStorage=void 0;var hoe=HM();Ev.schemaStorage=new hoe.AsnSchemaStorage});var FM=v(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.AsnProp=ys.AsnSequenceType=ys.AsnSetType=ys.AsnChoiceType=ys.AsnType=void 0;var poe=(V(),H(F)),moe=poe.__importStar(Ag()),tT=Al(),Qc=Cv(),goe=t=>e=>{let r;Qc.schemaStorage.has(e)?r=Qc.schemaStorage.get(e):(r=Qc.schemaStorage.createDefault(e),Qc.schemaStorage.set(e,r)),Object.assign(r,t)};ys.AsnType=goe;var yoe=()=>(0,ys.AsnType)({type:tT.AsnTypeTypes.Choice});ys.AsnChoiceType=yoe;var xoe=t=>(0,ys.AsnType)({type:tT.AsnTypeTypes.Set,...t});ys.AsnSetType=xoe;var boe=t=>(0,ys.AsnType)({type:tT.AsnTypeTypes.Sequence,...t});ys.AsnSequenceType=boe;var _oe=t=>(e,r)=>{let n;Qc.schemaStorage.has(e.constructor)?n=Qc.schemaStorage.get(e.constructor):(n=Qc.schemaStorage.createDefault(e.constructor),Qc.schemaStorage.set(e.constructor,n));let s=Object.assign({},t);if(typeof s.type=="number"&&!s.converter){let i=moe.defaultConverter(t.type);if(!i)throw new Error(`Cannot get default converter for property '${r}' of ${e.constructor.name}`);s.converter=i}s.raw=t.raw,n.items[r]=s};ys.AsnProp=_oe});var VM=v(kv=>{"use strict";Object.defineProperty(kv,"__esModule",{value:!0});kv.AsnSchemaValidationError=void 0;var rT=class extends Error{schemas=[]};kv.AsnSchemaValidationError=rT});var sT=v(nT=>{"use strict";Object.defineProperty(nT,"__esModule",{value:!0});var voe=(V(),H(F));voe.__exportStar(VM(),nT)});var aT=v(Tv=>{"use strict";Object.defineProperty(Tv,"__esModule",{value:!0});Tv.AsnParser=void 0;var KM=(V(),H(F)),Ps=KM.__importStar(Yc()),woe=ri(),eu=Al(),iT=KM.__importStar(Ag()),Cg=sT(),kg=Sv(),El=Cv(),oT=class{static parse(e,r,n){let s=Ps.fromBER((0,woe.toArrayBuffer)(e),n?.berOptions);if(s.result.error)throw new Error(s.result.error);return this.fromASN(s.result,r,n)}static fromASN(e,r,n){try{if((0,kg.isConvertible)(r))return new r().fromASN(e);let s=El.schemaStorage.get(r);El.schemaStorage.cache(r);let i=s.schema,o=this.handleChoiceTypes(e,s,r,i,n);if(o?.result)return o.result;o?.targetSchema&&(i=o.targetSchema);let a=this.handleSequenceTypes(e,s,r,i),c=new r;return(0,kg.isTypeOfArray)(r)?this.handleArrayTypes(e,s,r,n):(this.processSchemaItems(s,a,c,n),c)}catch(s){throw s instanceof Cg.AsnSchemaValidationError&&s.schemas.push(r.name),s}}static handleChoiceTypes(e,r,n,s,i){if(e.constructor===Ps.Constructed&&r.type===eu.AsnTypeTypes.Choice&&e.idBlock.tagClass===3)for(let o in r.items){let a=r.items[o];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&El.schemaStorage.has(a.type)){let c=El.schemaStorage.get(a.type);if(c&&c.type===eu.AsnTypeTypes.Sequence){let u=new Ps.Sequence;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in u.valueBlock){u.valueBlock.value=e.valueBlock.value;let l=this.fromASN(u,a.type,i),d=new n;return d[o]=l,{result:d}}}}}else if(e.constructor===Ps.Constructed&&r.type!==eu.AsnTypeTypes.Choice){let o=new Ps.Constructed({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:r.schema.valueBlock.value});for(let a in r.items)delete e[a];return{targetSchema:o}}return null}static handleSequenceTypes(e,r,n,s){if(r.type===eu.AsnTypeTypes.Sequence){let i=Ps.compareSchema({},e,s);if(!i.verified)throw new Cg.AsnSchemaValidationError(`Data does not match to ${n.name} ASN1 schema.${i.result.error?` ${i.result.error}`:""}`);return i}else{let i=Ps.compareSchema({},e,s);if(!i.verified)throw new Cg.AsnSchemaValidationError(`Data does not match to ${n.name} ASN1 schema.${i.result.error?` ${i.result.error}`:""}`);return i}}static processRepeatedField(e,r,n){let s=e.slice(r);if(s.length===1&&s[0].constructor.name==="Sequence"){let i=s[0];i.valueBlock&&i.valueBlock.value&&Array.isArray(i.valueBlock.value)&&(s=i.valueBlock.value)}if(typeof n.type=="number"){let i=iT.defaultConverter(n.type);if(!i)throw new Error(`No converter for ASN.1 type ${n.type}`);return s.filter(o=>o&&o.valueBlock).map(o=>{try{return i.fromASN(o)}catch{return}}).filter(o=>o!==void 0)}else return s.filter(i=>i&&i.valueBlock).map(i=>{try{return this.fromASN(i,n.type)}catch{return}}).filter(i=>i!==void 0)}static processPrimitiveField(e,r){let n=iT.defaultConverter(r.type);if(!n)throw new Error(`No converter for ASN.1 type ${r.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&El.schemaStorage.has(e.type)&&El.schemaStorage.get(e.type).type===eu.AsnTypeTypes.Choice}static processOptionalChoiceField(e,r){try{return{processed:!0,value:this.fromASN(e,r.type)}}catch(n){if(n instanceof Cg.AsnSchemaValidationError&&/Wrong values for Choice type/.test(n.message))return{processed:!1};throw n}}static handleArrayTypes(e,r,n,s){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let i=r.itemType;if(typeof i=="number"){let o=iT.defaultConverter(i);if(!o)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,a=>o.fromASN(a))}else return n.from(e.valueBlock.value,o=>this.fromASN(o,i,s))}static processSchemaItems(e,r,n,s){for(let i in e.items){let o=r.result[i];if(!o)continue;let a=e.items[i],c=a.type,u;typeof c=="number"||(0,kg.isConvertible)(c)?u=this.processPrimitiveSchemaItem(o,a,c,s):u=this.processComplexSchemaItem(o,a,c,s),u&&typeof u=="object"&&"value"in u&&"raw"in u?(n[i]=u.value,n[`${i}Raw`]=u.raw):n[i]=u}}static processPrimitiveSchemaItem(e,r,n,s){let i=r.converter??((0,kg.isConvertible)(n)?new n:null);if(!i)throw new Error("Converter is empty");return r.repeated?this.processRepeatedPrimitiveItem(e,r,i,s):this.processSinglePrimitiveItem(e,r,n,i,s)}static processRepeatedPrimitiveItem(e,r,n,s){if(r.implicit){let i=r.repeated==="sequence"?Ps.Sequence:Ps.Set,o=new i;o.valueBlock=e.valueBlock;let a=Ps.fromBER(o.toBER(!1),s?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let c=a.result.valueBlock.value;return Array.from(c,u=>n.fromASN(u))}else return Array.from(e,i=>n.fromASN(i))}static processSinglePrimitiveItem(e,r,n,s,i){let o=e;if(r.implicit){let a;if((0,kg.isConvertible)(n))a=new n().toSchema("");else{let c=eu.AsnPropTypes[n],u=Ps[c];if(!u)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new u}a.valueBlock=o.valueBlock,o=Ps.fromBER(a.toBER(!1),i?.berOptions).result}return s.fromASN(o)}static processComplexSchemaItem(e,r,n,s){if(r.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,i=>this.fromASN(i,n,s))}else{let i=this.handleImplicitTagging(e,r,n);if(this.isOptionalChoiceField(r))try{return this.fromASN(i,n,s)}catch(o){if(o instanceof Cg.AsnSchemaValidationError&&/Wrong values for Choice type/.test(o.message))return;throw o}else{let o=this.fromASN(i,n,s);return r.raw?{value:o,raw:e.valueBeforeDecodeView}:o}}}static handleImplicitTagging(e,r,n){if(r.implicit&&typeof r.context=="number"){let s=El.schemaStorage.get(n);if(s.type===eu.AsnTypeTypes.Sequence){let i=new Ps.Sequence;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in i.valueBlock)return i.valueBlock.value=e.valueBlock.value,i}else if(s.type===eu.AsnTypeTypes.Set){let i=new Ps.Set;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in i.valueBlock)return i.valueBlock.value=e.valueBlock.value,i}}return e}};Tv.AsnParser=oT});var lT=v(Pv=>{"use strict";Object.defineProperty(Pv,"__esModule",{value:!0});Pv.AsnSerializer=void 0;var GM=(V(),H(F)),Zi=GM.__importStar(Yc()),Soe=ri(),Aoe=GM.__importStar(Ag()),Iv=Al(),cT=Sv(),ZM=Cv(),uT=class t{static serialize(e){return e instanceof Zi.BaseBlock?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&(0,cT.isConvertible)(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");let r=e.constructor,n=ZM.schemaStorage.get(r);ZM.schemaStorage.cache(r);let s=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof n.itemType=="number"){let o=Aoe.defaultConverter(n.itemType);if(!o)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);s=e.map(a=>o.toASN(a))}else s=e.map(o=>this.toAsnItem({type:n.itemType},"[]",r,o))}else for(let o in n.items){let a=n.items[o],c=e[o];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&(0,cT.isArrayEqual)(this.serialize(a.defaultValue),this.serialize(c)))continue;let u=t.toAsnItem(a,o,r,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||(0,cT.isConvertible)(a.type))){let l={};l.valueHex=u instanceof Zi.Null?(0,Soe.toArrayBuffer)(u.valueBeforeDecodeView):u.valueBlock.toBER(),s.push(new Zi.Primitive({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...l}))}else s.push(new Zi.Constructed({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:u.valueBlock.value}));else s.push(new Zi.Constructed({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[u]}));else a.repeated?s=s.concat(u):s.push(u)}let i;switch(n.type){case Iv.AsnTypeTypes.Sequence:i=new Zi.Sequence({value:s});break;case Iv.AsnTypeTypes.Set:i=new Zi.Set({value:s});break;case Iv.AsnTypeTypes.Choice:if(!s[0])throw new Error(`Schema '${r.name}' has wrong data. Choice cannot be empty.`);i=s[0];break}return i}static toAsnItem(e,r,n,s){let i;if(typeof e.type=="number"){let o=e.converter;if(!o)throw new Error(`Property '${r}' doesn't have converter for type ${Iv.AsnPropTypes[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");let a=Array.from(s,u=>o.toASN(u)),c=e.repeated==="sequence"?Zi.Sequence:Zi.Set;i=new c({value:a})}else i=o.toASN(s)}else if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");let o=Array.from(s,c=>this.toASN(c)),a=e.repeated==="sequence"?Zi.Sequence:Zi.Set;i=new a({value:o})}else i=this.toASN(s);return i}};Pv.AsnSerializer=uT});var WM=v(Rv=>{"use strict";Object.defineProperty(Rv,"__esModule",{value:!0});Rv.AsnArray=void 0;var dT=class extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(let r of e)this.push(r)}}};Rv.AsnArray=dT});var JM=v(Ov=>{"use strict";Object.defineProperty(Ov,"__esModule",{value:!0});Ov.AsnConvert=void 0;var Eoe=(V(),H(F)),Coe=Eoe.__importStar(Yc()),XM=ri(),koe=aT(),Toe=lT(),fT=class t{static serialize(e){return Toe.AsnSerializer.serialize(e)}static parse(e,r,n){return koe.AsnParser.parse(e,r,n)}static toString(e,r){let n=(0,XM.isBufferSource)(e)?(0,XM.toArrayBuffer)(e):t.serialize(e),s=Coe.fromBER(n,r?.berOptions);if(s.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${s.result.error}`);return s.result.toString()}};Ov.AsnConvert=fT});var ne=v(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.AsnSerializer=Mr.AsnParser=Mr.AsnPropTypes=Mr.AsnTypeTypes=Mr.AsnSetType=Mr.AsnSequenceType=Mr.AsnChoiceType=Mr.AsnType=Mr.AsnProp=void 0;var Tg=(V(),H(F));Tg.__exportStar(Ag(),Mr);Tg.__exportStar(Qk(),Mr);var Ig=FM();Object.defineProperty(Mr,"AsnProp",{enumerable:!0,get:function(){return Ig.AsnProp}});Object.defineProperty(Mr,"AsnType",{enumerable:!0,get:function(){return Ig.AsnType}});Object.defineProperty(Mr,"AsnChoiceType",{enumerable:!0,get:function(){return Ig.AsnChoiceType}});Object.defineProperty(Mr,"AsnSequenceType",{enumerable:!0,get:function(){return Ig.AsnSequenceType}});Object.defineProperty(Mr,"AsnSetType",{enumerable:!0,get:function(){return Ig.AsnSetType}});var YM=Al();Object.defineProperty(Mr,"AsnTypeTypes",{enumerable:!0,get:function(){return YM.AsnTypeTypes}});Object.defineProperty(Mr,"AsnPropTypes",{enumerable:!0,get:function(){return YM.AsnPropTypes}});var Ioe=aT();Object.defineProperty(Mr,"AsnParser",{enumerable:!0,get:function(){return Ioe.AsnParser}});var Poe=lT();Object.defineProperty(Mr,"AsnSerializer",{enumerable:!0,get:function(){return Poe.AsnSerializer}});Tg.__exportStar(sT(),Mr);Tg.__exportStar(WM(),Mr);Tg.__exportStar(JM(),Mr)});var hT=v(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.binary=void 0;Cl.encode=QM;Cl.decode=ej;Cl.is=tj;var Roe=ri();function QM(t){let e=(0,Roe.toUint8Array)(t),r="";for(let n of e)r+=String.fromCharCode(n);return r}function ej(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function tj(t){return typeof t=="string"}Cl.binary={encode:QM,decode:ej,is:tj}});var aj=v(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.hex=si.formats=void 0;si.normalize=Pg;si.is=sj;si.encode=pT;si.decode=mT;si.parse=ij;si.format=oj;var Ooe=ri(),Noe=/^[0-9a-f]$/i,Boe=[" "," ",`
|
|
76
|
+
`,"\r",":","-","."];function $oe(t){return t.separators==="none"?[]:!t.separators||t.separators==="common"?Boe:t.separators}function Moe(t){if(!t)throw new TypeError("Hex separators must be non-empty strings")}function joe(t,e,r){for(let n of r)if(t.startsWith(n,e))return n}function zoe(t){let e=/[A-F]/.test(t),r=/[a-f]/.test(t);return e&&!r?"upper":"lower"}function Loe(t){let e=/\r\n|\n/.exec(t);if(e)return e[0]===`\r
|
|
77
|
+
`?`\r
|
|
78
|
+
`:`
|
|
79
|
+
`}function rj(t){return t.replace(/[^0-9a-f]/gi,"")}function Doe(t){let e=t.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;let r=e.filter((o,a)=>a%2===0),n=e.filter((o,a)=>a%2===1),s=n[0];if(!s||n.some(o=>o!==s)||r.some(o=>o.length===0||o.length%2!==0))return;let i=r[0]?.length??0;if(i&&!r.slice(0,-1).some(o=>o.length!==i)&&!((r[r.length-1]?.length??0)>i))return{size:i/2,separator:s}}function Uoe(t){let e=t.trim(),r=/^0x/i.test(e)?"0x":"",n=r?e.slice(2):e,s=Loe(n),i=n.split(/\r\n|\n/).filter(u=>u.length>0),o=i[0]?.trim()??"",a=Doe(o),c={case:zoe(e),prefix:r};if(a&&(c.group=a),s&&i.length>1){let u=rj(i[0]??"").length/2;u>0&&i.slice(0,-1).every(l=>rj(l).length/2===u)&&(c.line={bytesPerLine:u,separator:s})}return c}function qoe(t,e){let r=e.allowPrefix??!0,n=[...$oe(e)].sort((a,c)=>c.length-a.length);for(let a of n)Moe(a);let s=t.trim();if(/^0x/i.test(s)){if(!r)throw new TypeError("Hexadecimal text must not include a 0x prefix");s=s.slice(2)}let i="",o=!1;for(let a=0;a<s.length;){let c=s[a]??"";if(Noe.test(c)){i+=c,o=!1,a+=1;continue}let u=joe(s,a,n);if(!u)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(o||i.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");o=!0,a+=u.length}if(e.strict&&o&&i.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(i.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");i=`0${i}`}return i.toLowerCase()}function nj(t,e){if(!e)return t.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");let r=[];for(let n=0;n<t.length;n+=e.size)r.push(t.slice(n,n+e.size).join(""));return r.join(e.separator)}function Pg(t,e={}){return qoe(t,e)}function sj(t,e={}){if(typeof t!="string")return!1;try{return Pg(t,e),!0}catch{return!1}}function pT(t,e={}){let r=(0,Ooe.toUint8Array)(t),n=e.case??"lower",s=Array.from(r,o=>{let a=o.toString(16).padStart(2,"0");return n==="upper"?a.toUpperCase():a}),i="";if(e.line){let o=e.line.bytesPerLine;if(!Number.isInteger(o)||o<1)throw new RangeError("Hex bytesPerLine must be a positive integer");let a=e.line.separator??`
|
|
80
|
+
`,c=[];for(let u=0;u<s.length;u+=o)c.push(nj(s.slice(u,u+o),e.group));i=c.join(a)}else i=nj(s,e.group);return`${e.prefix??""}${i}`}function mT(t,e={}){let r=Pg(t,e),n=new Uint8Array(r.length/2);for(let s=0;s<r.length;s+=2)n[s/2]=Number.parseInt(r.slice(s,s+2),16);return n}function ij(t,e={}){let r=Pg(t,e);return{bytes:mT(r),format:Uoe(t),normalized:r}}function oj(t,e){return pT(t,e)}si.formats={compact:Object.freeze({}),upper:Object.freeze({case:"upper"}),colon:Object.freeze({group:{size:1,separator:":"}}),colonUpper:Object.freeze({case:"upper",group:{size:1,separator:":"}}),groupsOf4:Object.freeze({group:{size:4,separator:" "}}),prefixed:Object.freeze({prefix:"0x"})};si.hex={encode:pT,decode:mT,format:oj,formats:si.formats,is:sj,normalize:Pg,parse:ij}});var lj=v(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});xh.utf8=void 0;xh.encode=cj;xh.decode=uj;var Hoe=ri();function cj(t){return new TextEncoder().encode(t)}function uj(t){return new TextDecoder("utf-8",{fatal:!1}).decode((0,Hoe.toUint8Array)(t))}xh.utf8={encode:cj,decode:uj}});var hj=v(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});bh.utf16=void 0;bh.encode=dj;bh.decode=fj;var Foe=ri();function dj(t,e={}){let r=new ArrayBuffer(t.length*2),n=new DataView(r);for(let s=0;s<t.length;s++)n.setUint16(s*2,t.charCodeAt(s),e.littleEndian??!1);return new Uint8Array(r)}function fj(t,e={}){let r=(0,Foe.toArrayBuffer)(t),n=new DataView(r),s="";for(let i=0;i<r.byteLength;i+=2)s+=String.fromCharCode(n.getUint16(i,e.littleEndian??!1));return s}bh.utf16={encode:dj,decode:fj}});var yT=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.base64=void 0;qa.normalize=Nv;qa.pad=gj;qa.is=gT;qa.encode=yj;qa.decode=xj;var Voe=ri(),pj=hT(),Koe=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function mj(){return globalThis.Buffer}function Nv(t){return t.replace(/[\n\r\t ]/g,"")}function gj(t){let e=t.length%4;return e?t+"=".repeat(4-e):t}function gT(t){if(typeof t!="string")return!1;let e=Nv(t);return e===""||Koe.test(e)}function yj(t,e){let r=(0,Voe.toUint8Array)(t),n=mj();return n?n.from(r).toString("base64"):btoa((0,pj.encode)(r))}function xj(t,e){let r=Nv(t);if(!gT(r))throw new TypeError("Input is not valid Base64 text");let n=mj();return n?new Uint8Array(n.from(r,"base64")):(0,pj.decode)(atob(r))}qa.base64={encode:yj,decode:xj,is:gT,normalize:Nv,pad:gj}});var vj=v(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.base64url=void 0;tu.normalize=Bv;tu.is=bT;tu.encode=bj;tu.decode=_j;var xT=yT(),Zoe=/^[A-Za-z0-9_-]*$/;function Bv(t){return t.replace(/[\n\r\t ]/g,"")}function bT(t){return typeof t=="string"&&Zoe.test(Bv(t))}function bj(t,e){return xT.base64.encode(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function _j(t,e){let r=Bv(t);if(!bT(r))throw new TypeError("Input is not valid Base64Url text");return xT.base64.decode(xT.base64.pad(r.replace(/-/g,"+").replace(/_/g,"/")))}tu.base64url={encode:bj,decode:_j,is:bT,normalize:Bv}});var _T=v(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.base64url=Rs.base64=Rs.utf16=Rs.utf8=Rs.hex=Rs.binary=void 0;var _h=(V(),H(F));Rs.binary=_h.__importStar(hT());Rs.hex=_h.__importStar(aj());Rs.utf8=_h.__importStar(lj());Rs.utf16=_h.__importStar(hj());Rs.base64=_h.__importStar(yT());Rs.base64url=_h.__importStar(vj())});var wj=v($v=>{"use strict";Object.defineProperty($v,"__esModule",{value:!0});$v.IpConverter=void 0;var Goe=_T(),vT=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(n=>{let s=parseInt(n,10);if(isNaN(s)||s<0||s>255)throw new Error("Invalid IPv4 address part");return s})}static parseIPv6(e){let n=this.expandIPv6(e).split(":");if(n.length!==8)throw new Error("Invalid IPv6 address");return n.reduce((s,i)=>{let o=parseInt(i,16);if(isNaN(o)||o<0||o>65535)throw new Error("Invalid IPv6 address part");return s.push(o>>8&255),s.push(o&255),s},[])}static expandIPv6(e){if(!e.includes("::"))return e;let r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");let n=r[0]?r[0].split(":"):[],s=r[1]?r[1].split(":"):[],i=8-(n.length+s.length);if(i<0)throw new Error("Invalid IPv6 address");return[...n,...Array(i).fill("0"),...s].join(":")}static formatIPv6(e){let r=[];for(let n=0;n<16;n+=2)r.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){let r=e.split(":"),n=-1,s=0,i=-1,o=0;for(let a=0;a<r.length;a++)r[a]==="0"?(i===-1&&(i=a),o++):(o>s&&(n=i,s=o),i=-1,o=0);if(o>s&&(n=i,s=o),s>1){let a=r.slice(0,n).join(":"),c=r.slice(n+s).join(":");return`${a}::${c}`}return e}static parseCIDR(e){let[r,n]=e.split("/"),s=parseInt(n,10);if(this.isIPv4(r)){if(s<0||s>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),s]}else{if(s<0||s>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),s]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let r=parseInt(e.slice(8),16).toString(2).split("").reduce((s,i)=>s+ +i,0),n=e.slice(0,8).replace(/(.{2})/g,s=>`${parseInt(s,16)}.`);return n=n.slice(0,-1),`${n}/${r}`}static toString(e){let r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){let n=r.length/2,s=r.slice(0,n),i=r.slice(n);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";let a=i.reduce((c,u)=>c+(u.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(s).join(".")}/${a}`:`${this.formatIPv6(s)}/${a}`}return this.decodeIP(Goe.hex.encode(e))}static fromString(e){if(e.includes("/")){let[n,s]=this.parseCIDR(e),i=new Uint8Array(n.length),o=s;for(let c=0;c<i.length;c++)o>=8?(i[c]=255,o-=8):o>0&&(i[c]=255<<8-o,o=0);let a=new Uint8Array(n.length*2);return a.set(n,0),a.set(i,n.length),a.buffer}let r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}};$v.IpConverter=vT});var wh=v(En=>{"use strict";var wT,ST,AT;Object.defineProperty(En,"__esModule",{value:!0});En.Name=En.RDNSequence=En.RelativeDistinguishedName=En.AttributeTypeAndValue=En.AttributeValue=En.DirectoryString=void 0;var Os=(V(),H(F)),yr=ne(),Woe=_T(),Ha=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};En.DirectoryString=Ha;Os.__decorate([(0,yr.AsnProp)({type:yr.AsnPropTypes.TeletexString})],Ha.prototype,"teletexString",void 0);Os.__decorate([(0,yr.AsnProp)({type:yr.AsnPropTypes.PrintableString})],Ha.prototype,"printableString",void 0);Os.__decorate([(0,yr.AsnProp)({type:yr.AsnPropTypes.UniversalString})],Ha.prototype,"universalString",void 0);Os.__decorate([(0,yr.AsnProp)({type:yr.AsnPropTypes.Utf8String})],Ha.prototype,"utf8String",void 0);Os.__decorate([(0,yr.AsnProp)({type:yr.AsnPropTypes.BmpString})],Ha.prototype,"bmpString",void 0);En.DirectoryString=Ha=Os.__decorate([(0,yr.AsnType)({type:yr.AsnTypeTypes.Choice})],Ha);var kl=class extends Ha{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Woe.hex.encode(this.anyValue):super.toString())}};En.AttributeValue=kl;Os.__decorate([(0,yr.AsnProp)({type:yr.AsnPropTypes.IA5String})],kl.prototype,"ia5String",void 0);Os.__decorate([(0,yr.AsnProp)({type:yr.AsnPropTypes.Any})],kl.prototype,"anyValue",void 0);En.AttributeValue=kl=Os.__decorate([(0,yr.AsnType)({type:yr.AsnTypeTypes.Choice})],kl);var vh=class{type="";value=new kl;constructor(e={}){Object.assign(this,e)}};En.AttributeTypeAndValue=vh;Os.__decorate([(0,yr.AsnProp)({type:yr.AsnPropTypes.ObjectIdentifier})],vh.prototype,"type",void 0);Os.__decorate([(0,yr.AsnProp)({type:kl})],vh.prototype,"value",void 0);var Mv=wT=class extends yr.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,wT.prototype)}};En.RelativeDistinguishedName=Mv;En.RelativeDistinguishedName=Mv=wT=Os.__decorate([(0,yr.AsnType)({type:yr.AsnTypeTypes.Set,itemType:vh})],Mv);var jv=ST=class extends yr.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,ST.prototype)}};En.RDNSequence=jv;En.RDNSequence=jv=ST=Os.__decorate([(0,yr.AsnType)({type:yr.AsnTypeTypes.Sequence,itemType:Mv})],jv);var ET=AT=class extends jv{constructor(e){super(e),Object.setPrototypeOf(this,AT.prototype)}};En.Name=ET;En.Name=ET=AT=Os.__decorate([(0,yr.AsnType)({type:yr.AsnTypeTypes.Sequence})],ET)});var Tl=v(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.GeneralName=Ei.EDIPartyName=Ei.OtherName=Ei.AsnIpConverter=void 0;var Ns=(V(),H(F)),jr=ne(),Sj=wj(),zv=wh();Ei.AsnIpConverter={fromASN:t=>Sj.IpConverter.toString(jr.AsnOctetStringConverter.fromASN(t)),toASN:t=>jr.AsnOctetStringConverter.toASN(Sj.IpConverter.fromString(t))};var Sh=class{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};Ei.OtherName=Sh;Ns.__decorate([(0,jr.AsnProp)({type:jr.AsnPropTypes.ObjectIdentifier})],Sh.prototype,"typeId",void 0);Ns.__decorate([(0,jr.AsnProp)({type:jr.AsnPropTypes.Any,context:0})],Sh.prototype,"value",void 0);var Ah=class{nameAssigner;partyName=new zv.DirectoryString;constructor(e={}){Object.assign(this,e)}};Ei.EDIPartyName=Ah;Ns.__decorate([(0,jr.AsnProp)({type:zv.DirectoryString,optional:!0,context:0,implicit:!0})],Ah.prototype,"nameAssigner",void 0);Ns.__decorate([(0,jr.AsnProp)({type:zv.DirectoryString,context:1,implicit:!0})],Ah.prototype,"partyName",void 0);var Ci=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};Ei.GeneralName=Ci;Ns.__decorate([(0,jr.AsnProp)({type:Sh,context:0,implicit:!0})],Ci.prototype,"otherName",void 0);Ns.__decorate([(0,jr.AsnProp)({type:jr.AsnPropTypes.IA5String,context:1,implicit:!0})],Ci.prototype,"rfc822Name",void 0);Ns.__decorate([(0,jr.AsnProp)({type:jr.AsnPropTypes.IA5String,context:2,implicit:!0})],Ci.prototype,"dNSName",void 0);Ns.__decorate([(0,jr.AsnProp)({type:jr.AsnPropTypes.Any,context:3,implicit:!0})],Ci.prototype,"x400Address",void 0);Ns.__decorate([(0,jr.AsnProp)({type:zv.Name,context:4,implicit:!1})],Ci.prototype,"directoryName",void 0);Ns.__decorate([(0,jr.AsnProp)({type:Ah,context:5})],Ci.prototype,"ediPartyName",void 0);Ns.__decorate([(0,jr.AsnProp)({type:jr.AsnPropTypes.IA5String,context:6,implicit:!0})],Ci.prototype,"uniformResourceIdentifier",void 0);Ns.__decorate([(0,jr.AsnProp)({type:jr.AsnPropTypes.OctetString,context:7,implicit:!0,converter:Ei.AsnIpConverter})],Ci.prototype,"iPAddress",void 0);Ns.__decorate([(0,jr.AsnProp)({type:jr.AsnPropTypes.ObjectIdentifier,context:8,implicit:!0})],Ci.prototype,"registeredID",void 0);Ei.GeneralName=Ci=Ns.__decorate([(0,jr.AsnType)({type:jr.AsnTypeTypes.Choice})],Ci)});var Rr=v(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.id_ce=Ft.id_ad_caRepository=Ft.id_ad_timeStamping=Ft.id_ad_caIssuers=Ft.id_ad_ocsp=Ft.id_qt_unotice=Ft.id_qt_csp=Ft.id_ad=Ft.id_kp=Ft.id_qt=Ft.id_pe=Ft.id_pkix=void 0;Ft.id_pkix="1.3.6.1.5.5.7";Ft.id_pe=`${Ft.id_pkix}.1`;Ft.id_qt=`${Ft.id_pkix}.2`;Ft.id_kp=`${Ft.id_pkix}.3`;Ft.id_ad=`${Ft.id_pkix}.48`;Ft.id_qt_csp=`${Ft.id_qt}.1`;Ft.id_qt_unotice=`${Ft.id_qt}.2`;Ft.id_ad_ocsp=`${Ft.id_ad}.1`;Ft.id_ad_caIssuers=`${Ft.id_ad}.2`;Ft.id_ad_timeStamping=`${Ft.id_ad}.3`;Ft.id_ad_caRepository=`${Ft.id_ad}.5`;Ft.id_ce="2.5.29"});var IT=v(Fa=>{"use strict";var CT;Object.defineProperty(Fa,"__esModule",{value:!0});Fa.AuthorityInfoAccessSyntax=Fa.AccessDescription=Fa.id_pe_authorityInfoAccess=void 0;var TT=(V(),H(F)),Eh=ne(),Aj=Tl(),Xoe=Rr();Fa.id_pe_authorityInfoAccess=`${Xoe.id_pe}.1`;var Ch=class{accessMethod="";accessLocation=new Aj.GeneralName;constructor(e={}){Object.assign(this,e)}};Fa.AccessDescription=Ch;TT.__decorate([(0,Eh.AsnProp)({type:Eh.AsnPropTypes.ObjectIdentifier})],Ch.prototype,"accessMethod",void 0);TT.__decorate([(0,Eh.AsnProp)({type:Aj.GeneralName})],Ch.prototype,"accessLocation",void 0);var kT=CT=class extends Eh.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,CT.prototype)}};Fa.AuthorityInfoAccessSyntax=kT;Fa.AuthorityInfoAccessSyntax=kT=CT=TT.__decorate([(0,Eh.AsnType)({type:Eh.AsnTypeTypes.Sequence,itemType:Ch})],kT)});var RT=v(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.AuthorityKeyIdentifier=ru.KeyIdentifier=ru.id_ce_authorityKeyIdentifier=void 0;var PT=(V(),H(F)),kh=ne(),Joe=Tl(),Yoe=Rr();ru.id_ce_authorityKeyIdentifier=`${Yoe.id_ce}.35`;var Lv=class extends kh.OctetString{};ru.KeyIdentifier=Lv;var Th=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};ru.AuthorityKeyIdentifier=Th;PT.__decorate([(0,kh.AsnProp)({type:Lv,context:0,optional:!0,implicit:!0})],Th.prototype,"keyIdentifier",void 0);PT.__decorate([(0,kh.AsnProp)({type:Joe.GeneralName,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Th.prototype,"authorityCertIssuer",void 0);PT.__decorate([(0,kh.AsnProp)({type:kh.AsnPropTypes.Integer,context:2,optional:!0,implicit:!0,converter:kh.AsnIntegerArrayBufferConverter})],Th.prototype,"authorityCertSerialNumber",void 0)});var Cj=v(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});Ih.BasicConstraints=Ih.id_ce_basicConstraints=void 0;var Ej=(V(),H(F)),Dv=ne(),Qoe=Rr();Ih.id_ce_basicConstraints=`${Qoe.id_ce}.19`;var Rg=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};Ih.BasicConstraints=Rg;Ej.__decorate([(0,Dv.AsnProp)({type:Dv.AsnPropTypes.Boolean,defaultValue:!1})],Rg.prototype,"cA",void 0);Ej.__decorate([(0,Dv.AsnProp)({type:Dv.AsnPropTypes.Integer,optional:!0})],Rg.prototype,"pathLenConstraint",void 0)});var Ng=v(Og=>{"use strict";var OT;Object.defineProperty(Og,"__esModule",{value:!0});Og.GeneralNames=void 0;var eae=(V(),H(F)),NT=ne(),tae=Tl(),BT=OT=class extends NT.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,OT.prototype)}};Og.GeneralNames=BT;Og.GeneralNames=BT=OT=eae.__decorate([(0,NT.AsnType)({type:NT.AsnTypeTypes.Sequence,itemType:tae.GeneralName})],BT)});var Tj=v(Il=>{"use strict";var $T;Object.defineProperty(Il,"__esModule",{value:!0});Il.CertificateIssuer=Il.id_ce_certificateIssuer=void 0;var rae=(V(),H(F)),kj=ne(),nae=Ng(),sae=Rr();Il.id_ce_certificateIssuer=`${sae.id_ce}.29`;var MT=$T=class extends nae.GeneralNames{constructor(e){super(e),Object.setPrototypeOf(this,$T.prototype)}};Il.CertificateIssuer=MT;Il.CertificateIssuer=MT=$T=rae.__decorate([(0,kj.AsnType)({type:kj.AsnTypeTypes.Sequence})],MT)});var Ij=v(Vr=>{"use strict";var jT;Object.defineProperty(Vr,"__esModule",{value:!0});Vr.CertificatePolicies=Vr.PolicyInformation=Vr.PolicyQualifierInfo=Vr.Qualifier=Vr.UserNotice=Vr.NoticeReference=Vr.DisplayText=Vr.id_ce_certificatePolicies_anyPolicy=Vr.id_ce_certificatePolicies=void 0;var Dn=(V(),H(F)),dr=ne(),iae=Rr();Vr.id_ce_certificatePolicies=`${iae.id_ce}.32`;Vr.id_ce_certificatePolicies_anyPolicy=`${Vr.id_ce_certificatePolicies}.0`;var qo=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};Vr.DisplayText=qo;Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.IA5String})],qo.prototype,"ia5String",void 0);Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.VisibleString})],qo.prototype,"visibleString",void 0);Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.BmpString})],qo.prototype,"bmpString",void 0);Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.Utf8String})],qo.prototype,"utf8String",void 0);Vr.DisplayText=qo=Dn.__decorate([(0,dr.AsnType)({type:dr.AsnTypeTypes.Choice})],qo);var Ph=class{organization=new qo;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};Vr.NoticeReference=Ph;Dn.__decorate([(0,dr.AsnProp)({type:qo})],Ph.prototype,"organization",void 0);Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.Integer,repeated:"sequence"})],Ph.prototype,"noticeNumbers",void 0);var Rh=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};Vr.UserNotice=Rh;Dn.__decorate([(0,dr.AsnProp)({type:Ph,optional:!0})],Rh.prototype,"noticeRef",void 0);Dn.__decorate([(0,dr.AsnProp)({type:qo,optional:!0})],Rh.prototype,"explicitText",void 0);var Bg=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};Vr.Qualifier=Bg;Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.IA5String})],Bg.prototype,"cPSuri",void 0);Dn.__decorate([(0,dr.AsnProp)({type:Rh})],Bg.prototype,"userNotice",void 0);Vr.Qualifier=Bg=Dn.__decorate([(0,dr.AsnType)({type:dr.AsnTypeTypes.Choice})],Bg);var Oh=class{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};Vr.PolicyQualifierInfo=Oh;Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.ObjectIdentifier})],Oh.prototype,"policyQualifierId",void 0);Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.Any})],Oh.prototype,"qualifier",void 0);var Nh=class{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}};Vr.PolicyInformation=Nh;Dn.__decorate([(0,dr.AsnProp)({type:dr.AsnPropTypes.ObjectIdentifier})],Nh.prototype,"policyIdentifier",void 0);Dn.__decorate([(0,dr.AsnProp)({type:Oh,repeated:"sequence",optional:!0})],Nh.prototype,"policyQualifiers",void 0);var zT=jT=class extends dr.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,jT.prototype)}};Vr.CertificatePolicies=zT;Vr.CertificatePolicies=zT=jT=Dn.__decorate([(0,dr.AsnType)({type:dr.AsnTypeTypes.Sequence,itemType:Nh})],zT)});var LT=v(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.CRLNumber=Pl.id_ce_cRLNumber=void 0;var Pj=(V(),H(F)),Uv=ne(),oae=Rr();Pl.id_ce_cRLNumber=`${oae.id_ce}.20`;var qv=class{value;constructor(e=0){this.value=e}};Pl.CRLNumber=qv;Pj.__decorate([(0,Uv.AsnProp)({type:Uv.AsnPropTypes.Integer})],qv.prototype,"value",void 0);Pl.CRLNumber=qv=Pj.__decorate([(0,Uv.AsnType)({type:Uv.AsnTypeTypes.Choice})],qv)});var Oj=v(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.BaseCRLNumber=Rl.id_ce_deltaCRLIndicator=void 0;var aae=(V(),H(F)),Rj=ne(),cae=Rr(),uae=LT();Rl.id_ce_deltaCRLIndicator=`${cae.id_ce}.27`;var DT=class extends uae.CRLNumber{};Rl.BaseCRLNumber=DT;Rl.BaseCRLNumber=DT=aae.__decorate([(0,Rj.AsnType)({type:Rj.AsnTypeTypes.Choice})],DT)});var Fv=v(ss=>{"use strict";var UT;Object.defineProperty(ss,"__esModule",{value:!0});ss.CRLDistributionPoints=ss.DistributionPoint=ss.DistributionPointName=ss.Reason=ss.ReasonFlags=ss.id_ce_cRLDistributionPoints=void 0;var Nl=(V(),H(F)),Wi=ne(),lae=wh(),Nj=Tl(),dae=Rr();ss.id_ce_cRLDistributionPoints=`${dae.id_ce}.31`;var Gi;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(Gi||(ss.ReasonFlags=Gi={}));var Hv=class extends Wi.BitString{toJSON(){let e=[],r=this.toNumber();return r&Gi.aACompromise&&e.push("aACompromise"),r&Gi.affiliationChanged&&e.push("affiliationChanged"),r&Gi.cACompromise&&e.push("cACompromise"),r&Gi.certificateHold&&e.push("certificateHold"),r&Gi.cessationOfOperation&&e.push("cessationOfOperation"),r&Gi.keyCompromise&&e.push("keyCompromise"),r&Gi.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&Gi.superseded&&e.push("superseded"),r&Gi.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}};ss.Reason=Hv;var Bh=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};ss.DistributionPointName=Bh;Nl.__decorate([(0,Wi.AsnProp)({type:Nj.GeneralName,context:0,repeated:"sequence",implicit:!0})],Bh.prototype,"fullName",void 0);Nl.__decorate([(0,Wi.AsnProp)({type:lae.RelativeDistinguishedName,context:1,implicit:!0})],Bh.prototype,"nameRelativeToCRLIssuer",void 0);ss.DistributionPointName=Bh=Nl.__decorate([(0,Wi.AsnType)({type:Wi.AsnTypeTypes.Choice})],Bh);var Ol=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};ss.DistributionPoint=Ol;Nl.__decorate([(0,Wi.AsnProp)({type:Bh,context:0,optional:!0})],Ol.prototype,"distributionPoint",void 0);Nl.__decorate([(0,Wi.AsnProp)({type:Hv,context:1,optional:!0,implicit:!0})],Ol.prototype,"reasons",void 0);Nl.__decorate([(0,Wi.AsnProp)({type:Nj.GeneralName,context:2,optional:!0,repeated:"sequence",implicit:!0})],Ol.prototype,"cRLIssuer",void 0);var qT=UT=class extends Wi.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,UT.prototype)}};ss.CRLDistributionPoints=qT;ss.CRLDistributionPoints=qT=UT=Nl.__decorate([(0,Wi.AsnType)({type:Wi.AsnTypeTypes.Sequence,itemType:Ol})],qT)});var Mj=v(Bl=>{"use strict";var HT;Object.defineProperty(Bl,"__esModule",{value:!0});Bl.FreshestCRL=Bl.id_ce_freshestCRL=void 0;var fae=(V(),H(F)),Bj=ne(),hae=Rr(),$j=Fv();Bl.id_ce_freshestCRL=`${hae.id_ce}.46`;var FT=HT=class extends $j.CRLDistributionPoints{constructor(e){super(e),Object.setPrototypeOf(this,HT.prototype)}};Bl.FreshestCRL=FT;Bl.FreshestCRL=FT=HT=fae.__decorate([(0,Bj.AsnType)({type:Bj.AsnTypeTypes.Sequence,itemType:$j.DistributionPoint})],FT)});var zj=v($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});$h.IssuingDistributionPoint=$h.id_ce_issuingDistributionPoint=void 0;var Mh=(V(),H(F)),Ho=ne(),pae=Rr(),jj=Fv();$h.id_ce_issuingDistributionPoint=`${pae.id_ce}.28`;var ii=class t{static ONLY=!1;distributionPoint;onlyContainsUserCerts=t.ONLY;onlyContainsCACerts=t.ONLY;onlySomeReasons;indirectCRL=t.ONLY;onlyContainsAttributeCerts=t.ONLY;constructor(e={}){Object.assign(this,e)}};$h.IssuingDistributionPoint=ii;Mh.__decorate([(0,Ho.AsnProp)({type:jj.DistributionPointName,context:0,optional:!0})],ii.prototype,"distributionPoint",void 0);Mh.__decorate([(0,Ho.AsnProp)({type:Ho.AsnPropTypes.Boolean,context:1,defaultValue:ii.ONLY,implicit:!0})],ii.prototype,"onlyContainsUserCerts",void 0);Mh.__decorate([(0,Ho.AsnProp)({type:Ho.AsnPropTypes.Boolean,context:2,defaultValue:ii.ONLY,implicit:!0})],ii.prototype,"onlyContainsCACerts",void 0);Mh.__decorate([(0,Ho.AsnProp)({type:jj.Reason,context:3,optional:!0,implicit:!0})],ii.prototype,"onlySomeReasons",void 0);Mh.__decorate([(0,Ho.AsnProp)({type:Ho.AsnPropTypes.Boolean,context:4,defaultValue:ii.ONLY,implicit:!0})],ii.prototype,"indirectCRL",void 0);Mh.__decorate([(0,Ho.AsnProp)({type:Ho.AsnPropTypes.Boolean,context:5,defaultValue:ii.ONLY,implicit:!0})],ii.prototype,"onlyContainsAttributeCerts",void 0)});var Dj=v(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.CRLReason=Va.CRLReasons=Va.id_ce_cRLReasons=void 0;var Lj=(V(),H(F)),Vv=ne(),mae=Rr();Va.id_ce_cRLReasons=`${mae.id_ce}.21`;var $g;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})($g||(Va.CRLReasons=$g={}));var Kv=class{reason=$g.unspecified;constructor(e=$g.unspecified){this.reason=e}toJSON(){return $g[this.reason]}toString(){return this.toJSON()}};Va.CRLReason=Kv;Lj.__decorate([(0,Vv.AsnProp)({type:Vv.AsnPropTypes.Enumerated})],Kv.prototype,"reason",void 0);Va.CRLReason=Kv=Lj.__decorate([(0,Vv.AsnType)({type:Vv.AsnTypeTypes.Choice})],Kv)});var Uj=v(un=>{"use strict";var VT;Object.defineProperty(un,"__esModule",{value:!0});un.id_kp_OCSPSigning=un.id_kp_timeStamping=un.id_kp_emailProtection=un.id_kp_codeSigning=un.id_kp_clientAuth=un.id_kp_serverAuth=un.anyExtendedKeyUsage=un.ExtendedKeyUsage=un.id_ce_extKeyUsage=void 0;var gae=(V(),H(F)),Zv=ne(),$l=Rr();un.id_ce_extKeyUsage=`${$l.id_ce}.37`;var KT=VT=class extends Zv.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,VT.prototype)}};un.ExtendedKeyUsage=KT;un.ExtendedKeyUsage=KT=VT=gae.__decorate([(0,Zv.AsnType)({type:Zv.AsnTypeTypes.Sequence,itemType:Zv.AsnPropTypes.ObjectIdentifier})],KT);un.anyExtendedKeyUsage=`${un.id_ce_extKeyUsage}.0`;un.id_kp_serverAuth=`${$l.id_kp}.1`;un.id_kp_clientAuth=`${$l.id_kp}.2`;un.id_kp_codeSigning=`${$l.id_kp}.3`;un.id_kp_emailProtection=`${$l.id_kp}.4`;un.id_kp_timeStamping=`${$l.id_kp}.8`;un.id_kp_OCSPSigning=`${$l.id_kp}.9`});var Hj=v(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});Ml.InhibitAnyPolicy=Ml.id_ce_inhibitAnyPolicy=void 0;var qj=(V(),H(F)),Mg=ne(),yae=Rr();Ml.id_ce_inhibitAnyPolicy=`${yae.id_ce}.54`;var Gv=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};Ml.InhibitAnyPolicy=Gv;qj.__decorate([(0,Mg.AsnProp)({type:Mg.AsnPropTypes.Integer,converter:Mg.AsnIntegerArrayBufferConverter})],Gv.prototype,"value",void 0);Ml.InhibitAnyPolicy=Gv=qj.__decorate([(0,Mg.AsnType)({type:Mg.AsnTypeTypes.Choice})],Gv)});var Vj=v(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});jl.InvalidityDate=jl.id_ce_invalidityDate=void 0;var Fj=(V(),H(F)),Wv=ne(),xae=Rr();jl.id_ce_invalidityDate=`${xae.id_ce}.24`;var Xv=class{value=new Date;constructor(e){e&&(this.value=e)}};jl.InvalidityDate=Xv;Fj.__decorate([(0,Wv.AsnProp)({type:Wv.AsnPropTypes.GeneralizedTime})],Xv.prototype,"value",void 0);jl.InvalidityDate=Xv=Fj.__decorate([(0,Wv.AsnType)({type:Wv.AsnTypeTypes.Choice})],Xv)});var Zj=v(zl=>{"use strict";var ZT;Object.defineProperty(zl,"__esModule",{value:!0});zl.IssueAlternativeName=zl.id_ce_issuerAltName=void 0;var bae=(V(),H(F)),Kj=ne(),_ae=Ng(),vae=Rr();zl.id_ce_issuerAltName=`${vae.id_ce}.18`;var GT=ZT=class extends _ae.GeneralNames{constructor(e){super(e),Object.setPrototypeOf(this,ZT.prototype)}};zl.IssueAlternativeName=GT;zl.IssueAlternativeName=GT=ZT=bae.__decorate([(0,Kj.AsnType)({type:Kj.AsnTypeTypes.Sequence})],GT)});var Gj=v(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.KeyUsage=nu.KeyUsageFlags=nu.id_ce_keyUsage=void 0;var wae=ne(),Sae=Rr();nu.id_ce_keyUsage=`${Sae.id_ce}.15`;var Xi;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(Xi||(nu.KeyUsageFlags=Xi={}));var WT=class extends wae.BitString{toJSON(){let e=this.toNumber(),r=[];return e&Xi.cRLSign&&r.push("crlSign"),e&Xi.dataEncipherment&&r.push("dataEncipherment"),e&Xi.decipherOnly&&r.push("decipherOnly"),e&Xi.digitalSignature&&r.push("digitalSignature"),e&Xi.encipherOnly&&r.push("encipherOnly"),e&Xi.keyAgreement&&r.push("keyAgreement"),e&Xi.keyCertSign&&r.push("keyCertSign"),e&Xi.keyEncipherment&&r.push("keyEncipherment"),e&Xi.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}};nu.KeyUsage=WT});var Xj=v(Ji=>{"use strict";var XT;Object.defineProperty(Ji,"__esModule",{value:!0});Ji.NameConstraints=Ji.GeneralSubtrees=Ji.GeneralSubtree=Ji.id_ce_nameConstraints=void 0;var jh=(V(),H(F)),Fo=ne(),Wj=Tl(),Aae=Rr();Ji.id_ce_nameConstraints=`${Aae.id_ce}.30`;var Ll=class{base=new Wj.GeneralName;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};Ji.GeneralSubtree=Ll;jh.__decorate([(0,Fo.AsnProp)({type:Wj.GeneralName})],Ll.prototype,"base",void 0);jh.__decorate([(0,Fo.AsnProp)({type:Fo.AsnPropTypes.Integer,context:0,defaultValue:0,implicit:!0})],Ll.prototype,"minimum",void 0);jh.__decorate([(0,Fo.AsnProp)({type:Fo.AsnPropTypes.Integer,context:1,optional:!0,implicit:!0})],Ll.prototype,"maximum",void 0);var jg=XT=class extends Fo.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,XT.prototype)}};Ji.GeneralSubtrees=jg;Ji.GeneralSubtrees=jg=XT=jh.__decorate([(0,Fo.AsnType)({type:Fo.AsnTypeTypes.Sequence,itemType:Ll})],jg);var zg=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};Ji.NameConstraints=zg;jh.__decorate([(0,Fo.AsnProp)({type:jg,context:0,optional:!0,implicit:!0})],zg.prototype,"permittedSubtrees",void 0);jh.__decorate([(0,Fo.AsnProp)({type:jg,context:1,optional:!0,implicit:!0})],zg.prototype,"excludedSubtrees",void 0)});var Yj=v(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});Lh.PolicyConstraints=Lh.id_ce_policyConstraints=void 0;var Jj=(V(),H(F)),zh=ne(),Eae=Rr();Lh.id_ce_policyConstraints=`${Eae.id_ce}.36`;var Lg=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};Lh.PolicyConstraints=Lg;Jj.__decorate([(0,zh.AsnProp)({type:zh.AsnPropTypes.Integer,context:0,implicit:!0,optional:!0,converter:zh.AsnIntegerArrayBufferConverter})],Lg.prototype,"requireExplicitPolicy",void 0);Jj.__decorate([(0,zh.AsnProp)({type:zh.AsnPropTypes.Integer,context:1,implicit:!0,optional:!0,converter:zh.AsnIntegerArrayBufferConverter})],Lg.prototype,"inhibitPolicyMapping",void 0)});var Qj=v(Ka=>{"use strict";var JT;Object.defineProperty(Ka,"__esModule",{value:!0});Ka.PolicyMappings=Ka.PolicyMapping=Ka.id_ce_policyMappings=void 0;var QT=(V(),H(F)),Dl=ne(),Cae=Rr();Ka.id_ce_policyMappings=`${Cae.id_ce}.33`;var Dh=class{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}};Ka.PolicyMapping=Dh;QT.__decorate([(0,Dl.AsnProp)({type:Dl.AsnPropTypes.ObjectIdentifier})],Dh.prototype,"issuerDomainPolicy",void 0);QT.__decorate([(0,Dl.AsnProp)({type:Dl.AsnPropTypes.ObjectIdentifier})],Dh.prototype,"subjectDomainPolicy",void 0);var YT=JT=class extends Dl.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,JT.prototype)}};Ka.PolicyMappings=YT;Ka.PolicyMappings=YT=JT=QT.__decorate([(0,Dl.AsnType)({type:Dl.AsnTypeTypes.Sequence,itemType:Dh})],YT)});var tz=v(Ul=>{"use strict";var e6;Object.defineProperty(Ul,"__esModule",{value:!0});Ul.SubjectAlternativeName=Ul.id_ce_subjectAltName=void 0;var kae=(V(),H(F)),ez=ne(),Tae=Ng(),Iae=Rr();Ul.id_ce_subjectAltName=`${Iae.id_ce}.17`;var t6=e6=class extends Tae.GeneralNames{constructor(e){super(e),Object.setPrototypeOf(this,e6.prototype)}};Ul.SubjectAlternativeName=t6;Ul.SubjectAlternativeName=t6=e6=kae.__decorate([(0,ez.AsnType)({type:ez.AsnTypeTypes.Sequence})],t6)});var r6=v(Yv=>{"use strict";Object.defineProperty(Yv,"__esModule",{value:!0});Yv.Attribute=void 0;var rz=(V(),H(F)),Jv=ne(),Dg=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};Yv.Attribute=Dg;rz.__decorate([(0,Jv.AsnProp)({type:Jv.AsnPropTypes.ObjectIdentifier})],Dg.prototype,"type",void 0);rz.__decorate([(0,Jv.AsnProp)({type:Jv.AsnPropTypes.Any,repeated:"set"})],Dg.prototype,"values",void 0)});var nz=v(ql=>{"use strict";var n6;Object.defineProperty(ql,"__esModule",{value:!0});ql.SubjectDirectoryAttributes=ql.id_ce_subjectDirectoryAttributes=void 0;var Pae=(V(),H(F)),s6=ne(),Rae=r6(),Oae=Rr();ql.id_ce_subjectDirectoryAttributes=`${Oae.id_ce}.9`;var i6=n6=class extends s6.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,n6.prototype)}};ql.SubjectDirectoryAttributes=i6;ql.SubjectDirectoryAttributes=i6=n6=Pae.__decorate([(0,s6.AsnType)({type:s6.AsnTypeTypes.Sequence,itemType:Rae.Attribute})],i6)});var sz=v(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});Uh.SubjectKeyIdentifier=Uh.id_ce_subjectKeyIdentifier=void 0;var Nae=Rr(),Bae=RT();Uh.id_ce_subjectKeyIdentifier=`${Nae.id_ce}.14`;var o6=class extends Bae.KeyIdentifier{};Uh.SubjectKeyIdentifier=o6});var oz=v(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});qh.PrivateKeyUsagePeriod=qh.id_ce_privateKeyUsagePeriod=void 0;var iz=(V(),H(F)),Qv=ne(),$ae=Rr();qh.id_ce_privateKeyUsagePeriod=`${$ae.id_ce}.16`;var Ug=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};qh.PrivateKeyUsagePeriod=Ug;iz.__decorate([(0,Qv.AsnProp)({type:Qv.AsnPropTypes.GeneralizedTime,context:0,implicit:!0,optional:!0})],Ug.prototype,"notBefore",void 0);iz.__decorate([(0,Qv.AsnProp)({type:Qv.AsnPropTypes.GeneralizedTime,context:1,implicit:!0,optional:!0})],Ug.prototype,"notAfter",void 0)});var cz=v(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.EntrustVersionInfo=Vo.EntrustInfo=Vo.EntrustInfoFlags=Vo.id_entrust_entrustVersInfo=void 0;var az=(V(),H(F)),ew=ne();Vo.id_entrust_entrustVersInfo="1.2.840.113533.7.65.0";var qg;(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(qg||(Vo.EntrustInfoFlags=qg={}));var Hg=class extends ew.BitString{toJSON(){let e=[],r=this.toNumber();return r&qg.pKIXCertificate&&e.push("pKIXCertificate"),r&qg.newExtensions&&e.push("newExtensions"),r&qg.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}};Vo.EntrustInfo=Hg;var Fg=class{entrustVers="";entrustInfoFlags=new Hg;constructor(e={}){Object.assign(this,e)}};Vo.EntrustVersionInfo=Fg;az.__decorate([(0,ew.AsnProp)({type:ew.AsnPropTypes.GeneralString})],Fg.prototype,"entrustVers",void 0);az.__decorate([(0,ew.AsnProp)({type:Hg})],Fg.prototype,"entrustInfoFlags",void 0)});var uz=v(Hl=>{"use strict";var a6;Object.defineProperty(Hl,"__esModule",{value:!0});Hl.SubjectInfoAccessSyntax=Hl.id_pe_subjectInfoAccess=void 0;var Mae=(V(),H(F)),c6=ne(),jae=Rr(),zae=IT();Hl.id_pe_subjectInfoAccess=`${jae.id_pe}.11`;var u6=a6=class extends c6.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,a6.prototype)}};Hl.SubjectInfoAccessSyntax=u6;Hl.SubjectInfoAccessSyntax=u6=a6=Mae.__decorate([(0,c6.AsnType)({type:c6.AsnTypeTypes.Sequence,itemType:zae.AccessDescription})],u6)});var lz=v(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});var zr=(V(),H(F));zr.__exportStar(IT(),Ar);zr.__exportStar(RT(),Ar);zr.__exportStar(Cj(),Ar);zr.__exportStar(Tj(),Ar);zr.__exportStar(Ij(),Ar);zr.__exportStar(Oj(),Ar);zr.__exportStar(Fv(),Ar);zr.__exportStar(Mj(),Ar);zr.__exportStar(zj(),Ar);zr.__exportStar(LT(),Ar);zr.__exportStar(Dj(),Ar);zr.__exportStar(Uj(),Ar);zr.__exportStar(Hj(),Ar);zr.__exportStar(Vj(),Ar);zr.__exportStar(Zj(),Ar);zr.__exportStar(Gj(),Ar);zr.__exportStar(Xj(),Ar);zr.__exportStar(Yj(),Ar);zr.__exportStar(Qj(),Ar);zr.__exportStar(tz(),Ar);zr.__exportStar(nz(),Ar);zr.__exportStar(sz(),Ar);zr.__exportStar(oz(),Ar);zr.__exportStar(cz(),Ar);zr.__exportStar(uz(),Ar)});var Fl=v(rw=>{"use strict";Object.defineProperty(rw,"__esModule",{value:!0});rw.AlgorithmIdentifier=void 0;var dz=(V(),H(F)),tw=ne(),Lae=ri(),Vg=class t{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof t&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&(0,Lae.equal)(e.parameters,this.parameters)||e.parameters===this.parameters)}};rw.AlgorithmIdentifier=Vg;dz.__decorate([(0,tw.AsnProp)({type:tw.AsnPropTypes.ObjectIdentifier})],Vg.prototype,"algorithm",void 0);dz.__decorate([(0,tw.AsnProp)({type:tw.AsnPropTypes.Any,optional:!0})],Vg.prototype,"parameters",void 0)});var d6=v(nw=>{"use strict";Object.defineProperty(nw,"__esModule",{value:!0});nw.SubjectPublicKeyInfo=void 0;var fz=(V(),H(F)),l6=ne(),hz=Fl(),Kg=class{algorithm=new hz.AlgorithmIdentifier;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};nw.SubjectPublicKeyInfo=Kg;fz.__decorate([(0,l6.AsnProp)({type:hz.AlgorithmIdentifier})],Kg.prototype,"algorithm",void 0);fz.__decorate([(0,l6.AsnProp)({type:l6.AsnPropTypes.BitString})],Kg.prototype,"subjectPublicKey",void 0)});var sw=v(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});Gg.Time=void 0;var f6=(V(),H(F)),Hh=ne(),Zg=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){let r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};Gg.Time=Zg;f6.__decorate([(0,Hh.AsnProp)({type:Hh.AsnPropTypes.UTCTime})],Zg.prototype,"utcTime",void 0);f6.__decorate([(0,Hh.AsnProp)({type:Hh.AsnPropTypes.GeneralizedTime})],Zg.prototype,"generalTime",void 0);Gg.Time=Zg=f6.__decorate([(0,Hh.AsnType)({type:Hh.AsnTypeTypes.Choice})],Zg)});var h6=v(iw=>{"use strict";Object.defineProperty(iw,"__esModule",{value:!0});iw.Validity=void 0;var pz=(V(),H(F)),mz=ne(),Fh=sw(),Wg=class{notBefore=new Fh.Time(new Date);notAfter=new Fh.Time(new Date);constructor(e){e&&(this.notBefore=new Fh.Time(e.notBefore),this.notAfter=new Fh.Time(e.notAfter))}};iw.Validity=Wg;pz.__decorate([(0,mz.AsnProp)({type:Fh.Time})],Wg.prototype,"notBefore",void 0);pz.__decorate([(0,mz.AsnProp)({type:Fh.Time})],Wg.prototype,"notAfter",void 0)});var aw=v(Vl=>{"use strict";var p6;Object.defineProperty(Vl,"__esModule",{value:!0});Vl.Extensions=Vl.Extension=void 0;var ow=(V(),H(F)),Ko=ne(),su=class t{static CRITICAL=!1;extnID="";critical=t.CRITICAL;extnValue=new Ko.OctetString;constructor(e={}){Object.assign(this,e)}};Vl.Extension=su;ow.__decorate([(0,Ko.AsnProp)({type:Ko.AsnPropTypes.ObjectIdentifier})],su.prototype,"extnID",void 0);ow.__decorate([(0,Ko.AsnProp)({type:Ko.AsnPropTypes.Boolean,defaultValue:su.CRITICAL})],su.prototype,"critical",void 0);ow.__decorate([(0,Ko.AsnProp)({type:Ko.OctetString})],su.prototype,"extnValue",void 0);var m6=p6=class extends Ko.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,p6.prototype)}};Vl.Extensions=m6;Vl.Extensions=m6=p6=ow.__decorate([(0,Ko.AsnType)({type:Ko.AsnTypeTypes.Sequence,itemType:su})],m6)});var g6=v(cw=>{"use strict";Object.defineProperty(cw,"__esModule",{value:!0});cw.Version=void 0;var gz;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(gz||(cw.Version=gz={}))});var y6=v(lw=>{"use strict";Object.defineProperty(lw,"__esModule",{value:!0});lw.TBSCertificate=void 0;var Zo=(V(),H(F)),xs=ne(),yz=Fl(),uw=wh(),xz=d6(),bz=h6(),Dae=aw(),_z=g6(),oi=class{version=_z.Version.v1;serialNumber=new ArrayBuffer(0);signature=new yz.AlgorithmIdentifier;issuer=new uw.Name;validity=new bz.Validity;subject=new uw.Name;subjectPublicKeyInfo=new xz.SubjectPublicKeyInfo;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};lw.TBSCertificate=oi;Zo.__decorate([(0,xs.AsnProp)({type:xs.AsnPropTypes.Integer,context:0,defaultValue:_z.Version.v1})],oi.prototype,"version",void 0);Zo.__decorate([(0,xs.AsnProp)({type:xs.AsnPropTypes.Integer,converter:xs.AsnIntegerArrayBufferConverter})],oi.prototype,"serialNumber",void 0);Zo.__decorate([(0,xs.AsnProp)({type:yz.AlgorithmIdentifier})],oi.prototype,"signature",void 0);Zo.__decorate([(0,xs.AsnProp)({type:uw.Name})],oi.prototype,"issuer",void 0);Zo.__decorate([(0,xs.AsnProp)({type:bz.Validity})],oi.prototype,"validity",void 0);Zo.__decorate([(0,xs.AsnProp)({type:uw.Name})],oi.prototype,"subject",void 0);Zo.__decorate([(0,xs.AsnProp)({type:xz.SubjectPublicKeyInfo})],oi.prototype,"subjectPublicKeyInfo",void 0);Zo.__decorate([(0,xs.AsnProp)({type:xs.AsnPropTypes.BitString,context:1,implicit:!0,optional:!0})],oi.prototype,"issuerUniqueID",void 0);Zo.__decorate([(0,xs.AsnProp)({type:xs.AsnPropTypes.BitString,context:2,implicit:!0,optional:!0})],oi.prototype,"subjectUniqueID",void 0);Zo.__decorate([(0,xs.AsnProp)({type:Dae.Extensions,context:3,optional:!0})],oi.prototype,"extensions",void 0)});var Sz=v(fw=>{"use strict";Object.defineProperty(fw,"__esModule",{value:!0});fw.Certificate=void 0;var x6=(V(),H(F)),dw=ne(),vz=Fl(),wz=y6(),Vh=class{tbsCertificate=new wz.TBSCertificate;tbsCertificateRaw;signatureAlgorithm=new vz.AlgorithmIdentifier;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};fw.Certificate=Vh;x6.__decorate([(0,dw.AsnProp)({type:wz.TBSCertificate,raw:!0})],Vh.prototype,"tbsCertificate",void 0);x6.__decorate([(0,dw.AsnProp)({type:vz.AlgorithmIdentifier})],Vh.prototype,"signatureAlgorithm",void 0);x6.__decorate([(0,dw.AsnProp)({type:dw.AsnPropTypes.BitString})],Vh.prototype,"signatureValue",void 0)});var b6=v(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});Kh.TBSCertList=Kh.RevokedCertificate=void 0;var Wo=(V(),H(F)),ai=ne(),Az=Fl(),Ez=wh(),Xg=sw(),Cz=aw(),Kl=class{userCertificate=new ArrayBuffer(0);revocationDate=new Xg.Time;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};Kh.RevokedCertificate=Kl;Wo.__decorate([(0,ai.AsnProp)({type:ai.AsnPropTypes.Integer,converter:ai.AsnIntegerArrayBufferConverter})],Kl.prototype,"userCertificate",void 0);Wo.__decorate([(0,ai.AsnProp)({type:Xg.Time})],Kl.prototype,"revocationDate",void 0);Wo.__decorate([(0,ai.AsnProp)({type:Cz.Extension,optional:!0,repeated:"sequence"})],Kl.prototype,"crlEntryExtensions",void 0);var Go=class{version;signature=new Az.AlgorithmIdentifier;issuer=new Ez.Name;thisUpdate=new Xg.Time;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};Kh.TBSCertList=Go;Wo.__decorate([(0,ai.AsnProp)({type:ai.AsnPropTypes.Integer,optional:!0})],Go.prototype,"version",void 0);Wo.__decorate([(0,ai.AsnProp)({type:Az.AlgorithmIdentifier})],Go.prototype,"signature",void 0);Wo.__decorate([(0,ai.AsnProp)({type:Ez.Name})],Go.prototype,"issuer",void 0);Wo.__decorate([(0,ai.AsnProp)({type:Xg.Time})],Go.prototype,"thisUpdate",void 0);Wo.__decorate([(0,ai.AsnProp)({type:Xg.Time,optional:!0})],Go.prototype,"nextUpdate",void 0);Wo.__decorate([(0,ai.AsnProp)({type:Kl,repeated:"sequence",optional:!0})],Go.prototype,"revokedCertificates",void 0);Wo.__decorate([(0,ai.AsnProp)({type:Cz.Extension,optional:!0,context:0,repeated:"sequence"})],Go.prototype,"crlExtensions",void 0)});var Iz=v(pw=>{"use strict";Object.defineProperty(pw,"__esModule",{value:!0});pw.CertificateList=void 0;var _6=(V(),H(F)),hw=ne(),kz=Fl(),Tz=b6(),Zh=class{tbsCertList=new Tz.TBSCertList;tbsCertListRaw;signatureAlgorithm=new kz.AlgorithmIdentifier;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};pw.CertificateList=Zh;_6.__decorate([(0,hw.AsnProp)({type:Tz.TBSCertList,raw:!0})],Zh.prototype,"tbsCertList",void 0);_6.__decorate([(0,hw.AsnProp)({type:kz.AlgorithmIdentifier})],Zh.prototype,"signatureAlgorithm",void 0);_6.__decorate([(0,hw.AsnProp)({type:hw.AsnPropTypes.BitString})],Zh.prototype,"signature",void 0)});var Yt=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});var is=(V(),H(F));is.__exportStar(lz(),Bn);is.__exportStar(Fl(),Bn);is.__exportStar(r6(),Bn);is.__exportStar(Sz(),Bn);is.__exportStar(Iz(),Bn);is.__exportStar(aw(),Bn);is.__exportStar(Tl(),Bn);is.__exportStar(Ng(),Bn);is.__exportStar(wh(),Bn);is.__exportStar(Rr(),Bn);is.__exportStar(d6(),Bn);is.__exportStar(b6(),Bn);is.__exportStar(y6(),Bn);is.__exportStar(sw(),Bn);is.__exportStar(g6(),Bn);is.__exportStar(h6(),Bn)});var Yg=v(gw=>{"use strict";Object.defineProperty(gw,"__esModule",{value:!0});gw.IssuerAndSerialNumber=void 0;var Pz=(V(),H(F)),mw=ne(),Rz=Yt(),Jg=class{issuer=new Rz.Name;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};gw.IssuerAndSerialNumber=Jg;Pz.__decorate([(0,mw.AsnProp)({type:Rz.Name})],Jg.prototype,"issuer",void 0);Pz.__decorate([(0,mw.AsnProp)({type:mw.AsnPropTypes.Integer,converter:mw.AsnIntegerArrayBufferConverter})],Jg.prototype,"serialNumber",void 0)});var w6=v(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});ey.SignerIdentifier=void 0;var v6=(V(),H(F)),yw=ne(),Uae=Yt(),qae=Yg(),Qg=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};ey.SignerIdentifier=Qg;v6.__decorate([(0,yw.AsnProp)({type:Uae.SubjectKeyIdentifier,context:0,implicit:!0})],Qg.prototype,"subjectKeyIdentifier",void 0);v6.__decorate([(0,yw.AsnProp)({type:qae.IssuerAndSerialNumber})],Qg.prototype,"issuerAndSerialNumber",void 0);ey.SignerIdentifier=Qg=v6.__decorate([(0,yw.AsnType)({type:yw.AsnTypeTypes.Choice})],Qg)});var Xo=v(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.KeyDerivationAlgorithmIdentifier=ln.MessageAuthenticationCodeAlgorithm=ln.ContentEncryptionAlgorithmIdentifier=ln.KeyEncryptionAlgorithmIdentifier=ln.SignatureAlgorithmIdentifier=ln.DigestAlgorithmIdentifier=ln.CMSVersion=void 0;var Gh=(V(),H(F)),Wh=Yt(),ki=ne(),Oz;(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(Oz||(ln.CMSVersion=Oz={}));var S6=class extends Wh.AlgorithmIdentifier{};ln.DigestAlgorithmIdentifier=S6;ln.DigestAlgorithmIdentifier=S6=Gh.__decorate([(0,ki.AsnType)({type:ki.AsnTypeTypes.Sequence})],S6);var A6=class extends Wh.AlgorithmIdentifier{};ln.SignatureAlgorithmIdentifier=A6;ln.SignatureAlgorithmIdentifier=A6=Gh.__decorate([(0,ki.AsnType)({type:ki.AsnTypeTypes.Sequence})],A6);var E6=class extends Wh.AlgorithmIdentifier{};ln.KeyEncryptionAlgorithmIdentifier=E6;ln.KeyEncryptionAlgorithmIdentifier=E6=Gh.__decorate([(0,ki.AsnType)({type:ki.AsnTypeTypes.Sequence})],E6);var C6=class extends Wh.AlgorithmIdentifier{};ln.ContentEncryptionAlgorithmIdentifier=C6;ln.ContentEncryptionAlgorithmIdentifier=C6=Gh.__decorate([(0,ki.AsnType)({type:ki.AsnTypeTypes.Sequence})],C6);var k6=class extends Wh.AlgorithmIdentifier{};ln.MessageAuthenticationCodeAlgorithm=k6;ln.MessageAuthenticationCodeAlgorithm=k6=Gh.__decorate([(0,ki.AsnType)({type:ki.AsnTypeTypes.Sequence})],k6);var T6=class extends Wh.AlgorithmIdentifier{};ln.KeyDerivationAlgorithmIdentifier=T6;ln.KeyDerivationAlgorithmIdentifier=T6=Gh.__decorate([(0,ki.AsnType)({type:ki.AsnTypeTypes.Sequence})],T6)});var _w=v(bw=>{"use strict";Object.defineProperty(bw,"__esModule",{value:!0});bw.Attribute=void 0;var Nz=(V(),H(F)),xw=ne(),ty=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};bw.Attribute=ty;Nz.__decorate([(0,xw.AsnProp)({type:xw.AsnPropTypes.ObjectIdentifier})],ty.prototype,"attrType",void 0);Nz.__decorate([(0,xw.AsnProp)({type:xw.AsnPropTypes.Any,repeated:"set"})],ty.prototype,"attrValues",void 0)});var vw=v(Zl=>{"use strict";var I6;Object.defineProperty(Zl,"__esModule",{value:!0});Zl.SignerInfos=Zl.SignerInfo=void 0;var iu=(V(),H(F)),ci=ne(),Bz=w6(),ry=Xo(),$z=_w(),Yi=class{version=ry.CMSVersion.v0;sid=new Bz.SignerIdentifier;digestAlgorithm=new ry.DigestAlgorithmIdentifier;signedAttrs;signedAttrsRaw;signatureAlgorithm=new ry.SignatureAlgorithmIdentifier;signature=new ci.OctetString;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};Zl.SignerInfo=Yi;iu.__decorate([(0,ci.AsnProp)({type:ci.AsnPropTypes.Integer})],Yi.prototype,"version",void 0);iu.__decorate([(0,ci.AsnProp)({type:Bz.SignerIdentifier})],Yi.prototype,"sid",void 0);iu.__decorate([(0,ci.AsnProp)({type:ry.DigestAlgorithmIdentifier})],Yi.prototype,"digestAlgorithm",void 0);iu.__decorate([(0,ci.AsnProp)({type:$z.Attribute,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],Yi.prototype,"signedAttrs",void 0);iu.__decorate([(0,ci.AsnProp)({type:ry.SignatureAlgorithmIdentifier})],Yi.prototype,"signatureAlgorithm",void 0);iu.__decorate([(0,ci.AsnProp)({type:ci.OctetString})],Yi.prototype,"signature",void 0);iu.__decorate([(0,ci.AsnProp)({type:$z.Attribute,repeated:"set",context:1,implicit:!0,optional:!0})],Yi.prototype,"unsignedAttrs",void 0);var P6=I6=class extends ci.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,I6.prototype)}};Zl.SignerInfos=P6;Zl.SignerInfos=P6=I6=iu.__decorate([(0,ci.AsnType)({type:ci.AsnTypeTypes.Set,itemType:Yi})],P6)});var jz=v(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});Gl.CounterSignature=Gl.id_counterSignature=void 0;var Hae=(V(),H(F)),Mz=ne(),Fae=vw();Gl.id_counterSignature="1.2.840.113549.1.9.6";var R6=class extends Fae.SignerInfo{};Gl.CounterSignature=R6;Gl.CounterSignature=R6=Hae.__decorate([(0,Mz.AsnType)({type:Mz.AsnTypeTypes.Sequence})],R6)});var zz=v(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});Xh.MessageDigest=Xh.id_messageDigest=void 0;var Vae=ne();Xh.id_messageDigest="1.2.840.113549.1.9.4";var O6=class extends Vae.OctetString{};Xh.MessageDigest=O6});var Dz=v(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});Wl.SigningTime=Wl.id_signingTime=void 0;var Kae=(V(),H(F)),Zae=Yt(),Lz=ne();Wl.id_signingTime="1.2.840.113549.1.9.5";var N6=class extends Zae.Time{};Wl.SigningTime=N6;Wl.SigningTime=N6=Kae.__decorate([(0,Lz.AsnType)({type:Lz.AsnTypeTypes.Choice})],N6)});var Uz=v(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});Xl.id_contentType=void 0;var B6=(V(),H(F));B6.__exportStar(jz(),Xl);B6.__exportStar(zz(),Xl);B6.__exportStar(Dz(),Xl);Xl.id_contentType="1.2.840.113549.1.9.3"});var qz=v(Sw=>{"use strict";Object.defineProperty(Sw,"__esModule",{value:!0});Sw.ACClearAttrs=void 0;var $6=(V(),H(F)),ww=ne(),M6=Yt(),Jh=class{acIssuer=new M6.GeneralName;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};Sw.ACClearAttrs=Jh;$6.__decorate([(0,ww.AsnProp)({type:M6.GeneralName})],Jh.prototype,"acIssuer",void 0);$6.__decorate([(0,ww.AsnProp)({type:ww.AsnPropTypes.Integer})],Jh.prototype,"acSerial",void 0);$6.__decorate([(0,ww.AsnProp)({type:M6.Attribute,repeated:"sequence"})],Jh.prototype,"attrs",void 0)});var L6=v(ny=>{"use strict";var j6;Object.defineProperty(ny,"__esModule",{value:!0});ny.AttrSpec=void 0;var Gae=(V(),H(F)),Aw=ne(),z6=j6=class extends Aw.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,j6.prototype)}};ny.AttrSpec=z6;ny.AttrSpec=z6=j6=Gae.__decorate([(0,Aw.AsnType)({type:Aw.AsnTypeTypes.Sequence,itemType:Aw.AsnPropTypes.ObjectIdentifier})],z6)});var Fz=v(Cw=>{"use strict";Object.defineProperty(Cw,"__esModule",{value:!0});Cw.AAControls=void 0;var Ew=(V(),H(F)),Yh=ne(),Hz=L6(),Jl=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};Cw.AAControls=Jl;Ew.__decorate([(0,Yh.AsnProp)({type:Yh.AsnPropTypes.Integer,optional:!0})],Jl.prototype,"pathLenConstraint",void 0);Ew.__decorate([(0,Yh.AsnProp)({type:Hz.AttrSpec,implicit:!0,context:0,optional:!0})],Jl.prototype,"permittedAttrs",void 0);Ew.__decorate([(0,Yh.AsnProp)({type:Hz.AttrSpec,implicit:!0,context:1,optional:!0})],Jl.prototype,"excludedAttrs",void 0);Ew.__decorate([(0,Yh.AsnProp)({type:Yh.AsnPropTypes.Boolean,defaultValue:!0})],Jl.prototype,"permitUnSpecified",void 0)});var sy=v(kw=>{"use strict";Object.defineProperty(kw,"__esModule",{value:!0});kw.IssuerSerial=void 0;var D6=(V(),H(F)),Qh=ne(),Vz=Yt(),ep=class{issuer=new Vz.GeneralNames;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};kw.IssuerSerial=ep;D6.__decorate([(0,Qh.AsnProp)({type:Vz.GeneralNames})],ep.prototype,"issuer",void 0);D6.__decorate([(0,Qh.AsnProp)({type:Qh.AsnPropTypes.Integer,converter:Qh.AsnIntegerArrayBufferConverter})],ep.prototype,"serial",void 0);D6.__decorate([(0,Qh.AsnProp)({type:Qh.AsnPropTypes.BitString,optional:!0})],ep.prototype,"issuerUID",void 0)});var iy=v(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});tp.ObjectDigestInfo=tp.DigestedObjectType=void 0;var Tw=(V(),H(F)),Yl=ne(),Kz=Yt(),U6;(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(U6||(tp.DigestedObjectType=U6={}));var Ql=class{digestedObjectType=U6.publicKey;otherObjectTypeID;digestAlgorithm=new Kz.AlgorithmIdentifier;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};tp.ObjectDigestInfo=Ql;Tw.__decorate([(0,Yl.AsnProp)({type:Yl.AsnPropTypes.Enumerated})],Ql.prototype,"digestedObjectType",void 0);Tw.__decorate([(0,Yl.AsnProp)({type:Yl.AsnPropTypes.ObjectIdentifier,optional:!0})],Ql.prototype,"otherObjectTypeID",void 0);Tw.__decorate([(0,Yl.AsnProp)({type:Kz.AlgorithmIdentifier})],Ql.prototype,"digestAlgorithm",void 0);Tw.__decorate([(0,Yl.AsnProp)({type:Yl.AsnPropTypes.BitString})],Ql.prototype,"objectDigest",void 0)});var F6=v(Iw=>{"use strict";Object.defineProperty(Iw,"__esModule",{value:!0});Iw.V2Form=void 0;var q6=(V(),H(F)),H6=ne(),Wae=Yt(),Xae=sy(),Jae=iy(),rp=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};Iw.V2Form=rp;q6.__decorate([(0,H6.AsnProp)({type:Wae.GeneralNames,optional:!0})],rp.prototype,"issuerName",void 0);q6.__decorate([(0,H6.AsnProp)({type:Xae.IssuerSerial,context:0,implicit:!0,optional:!0})],rp.prototype,"baseCertificateID",void 0);q6.__decorate([(0,H6.AsnProp)({type:Jae.ObjectDigestInfo,context:1,implicit:!0,optional:!0})],rp.prototype,"objectDigestInfo",void 0)});var K6=v(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});ay.AttCertIssuer=void 0;var V6=(V(),H(F)),Pw=ne(),Yae=Yt(),Qae=F6(),oy=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};ay.AttCertIssuer=oy;V6.__decorate([(0,Pw.AsnProp)({type:Yae.GeneralName,repeated:"sequence"})],oy.prototype,"v1Form",void 0);V6.__decorate([(0,Pw.AsnProp)({type:Qae.V2Form,context:0,implicit:!0})],oy.prototype,"v2Form",void 0);ay.AttCertIssuer=oy=V6.__decorate([(0,Pw.AsnType)({type:Pw.AsnTypeTypes.Choice})],oy)});var Z6=v(Ow=>{"use strict";Object.defineProperty(Ow,"__esModule",{value:!0});Ow.AttCertValidityPeriod=void 0;var Zz=(V(),H(F)),Rw=ne(),cy=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};Ow.AttCertValidityPeriod=cy;Zz.__decorate([(0,Rw.AsnProp)({type:Rw.AsnPropTypes.GeneralizedTime})],cy.prototype,"notBeforeTime",void 0);Zz.__decorate([(0,Rw.AsnProp)({type:Rw.AsnPropTypes.GeneralizedTime})],cy.prototype,"notAfterTime",void 0)});var X6=v(Nw=>{"use strict";Object.defineProperty(Nw,"__esModule",{value:!0});Nw.Holder=void 0;var G6=(V(),H(F)),W6=ne(),ece=Yt(),tce=sy(),rce=iy(),np=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};Nw.Holder=np;G6.__decorate([(0,W6.AsnProp)({type:tce.IssuerSerial,implicit:!0,context:0,optional:!0})],np.prototype,"baseCertificateID",void 0);G6.__decorate([(0,W6.AsnProp)({type:ece.GeneralNames,implicit:!0,context:1,optional:!0})],np.prototype,"entityName",void 0);G6.__decorate([(0,W6.AsnProp)({type:rce.ObjectDigestInfo,implicit:!0,context:2,optional:!0})],np.prototype,"objectDigestInfo",void 0)});var Y6=v(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});sp.AttributeCertificateInfo=sp.AttCertVersion=void 0;var Za=(V(),H(F)),ui=ne(),Bw=Yt(),Gz=X6(),Wz=K6(),Xz=Z6(),J6;(function(t){t[t.v2=1]="v2"})(J6||(sp.AttCertVersion=J6={}));var Ti=class{version=J6.v2;holder=new Gz.Holder;issuer=new Wz.AttCertIssuer;signature=new Bw.AlgorithmIdentifier;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Xz.AttCertValidityPeriod;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};sp.AttributeCertificateInfo=Ti;Za.__decorate([(0,ui.AsnProp)({type:ui.AsnPropTypes.Integer})],Ti.prototype,"version",void 0);Za.__decorate([(0,ui.AsnProp)({type:Gz.Holder})],Ti.prototype,"holder",void 0);Za.__decorate([(0,ui.AsnProp)({type:Wz.AttCertIssuer})],Ti.prototype,"issuer",void 0);Za.__decorate([(0,ui.AsnProp)({type:Bw.AlgorithmIdentifier})],Ti.prototype,"signature",void 0);Za.__decorate([(0,ui.AsnProp)({type:ui.AsnPropTypes.Integer,converter:ui.AsnIntegerArrayBufferConverter})],Ti.prototype,"serialNumber",void 0);Za.__decorate([(0,ui.AsnProp)({type:Xz.AttCertValidityPeriod})],Ti.prototype,"attrCertValidityPeriod",void 0);Za.__decorate([(0,ui.AsnProp)({type:Bw.Attribute,repeated:"sequence"})],Ti.prototype,"attributes",void 0);Za.__decorate([(0,ui.AsnProp)({type:ui.AsnPropTypes.BitString,optional:!0})],Ti.prototype,"issuerUniqueID",void 0);Za.__decorate([(0,ui.AsnProp)({type:Bw.Extensions,optional:!0})],Ti.prototype,"extensions",void 0)});var Qz=v(Mw=>{"use strict";Object.defineProperty(Mw,"__esModule",{value:!0});Mw.AttributeCertificate=void 0;var Q6=(V(),H(F)),$w=ne(),Jz=Yt(),Yz=Y6(),ip=class{acinfo=new Yz.AttributeCertificateInfo;signatureAlgorithm=new Jz.AlgorithmIdentifier;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};Mw.AttributeCertificate=ip;Q6.__decorate([(0,$w.AsnProp)({type:Yz.AttributeCertificateInfo})],ip.prototype,"acinfo",void 0);Q6.__decorate([(0,$w.AsnProp)({type:Jz.AlgorithmIdentifier})],ip.prototype,"signatureAlgorithm",void 0);Q6.__decorate([(0,$w.AsnProp)({type:$w.AsnPropTypes.BitString})],ip.prototype,"signatureValue",void 0)});var tI=v(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});op.ClassList=op.ClassListFlags=void 0;var nce=ne(),eL;(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(eL||(op.ClassListFlags=eL={}));var eI=class extends nce.BitString{};op.ClassList=eI});var rI=v(zw=>{"use strict";Object.defineProperty(zw,"__esModule",{value:!0});zw.SecurityCategory=void 0;var tL=(V(),H(F)),jw=ne(),uy=class{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};zw.SecurityCategory=uy;tL.__decorate([(0,jw.AsnProp)({type:jw.AsnPropTypes.ObjectIdentifier,implicit:!0,context:0})],uy.prototype,"type",void 0);tL.__decorate([(0,jw.AsnProp)({type:jw.AsnPropTypes.Any,implicit:!0,context:1})],uy.prototype,"value",void 0)});var rL=v(Dw=>{"use strict";Object.defineProperty(Dw,"__esModule",{value:!0});Dw.Clearance=void 0;var nI=(V(),H(F)),Lw=ne(),ly=tI(),sce=rI(),ap=class{policyId="";classList=new ly.ClassList(ly.ClassListFlags.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};Dw.Clearance=ap;nI.__decorate([(0,Lw.AsnProp)({type:Lw.AsnPropTypes.ObjectIdentifier})],ap.prototype,"policyId",void 0);nI.__decorate([(0,Lw.AsnProp)({type:ly.ClassList,defaultValue:new ly.ClassList(ly.ClassListFlags.unclassified)})],ap.prototype,"classList",void 0);nI.__decorate([(0,Lw.AsnProp)({type:sce.SecurityCategory,repeated:"set"})],ap.prototype,"securityCategories",void 0)});var nL=v(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});cp.IetfAttrSyntax=cp.IetfAttrSyntaxValueChoices=void 0;var fy=(V(),H(F)),ou=ne(),ice=Yt(),ed=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};cp.IetfAttrSyntaxValueChoices=ed;fy.__decorate([(0,ou.AsnProp)({type:ou.OctetString})],ed.prototype,"cotets",void 0);fy.__decorate([(0,ou.AsnProp)({type:ou.AsnPropTypes.ObjectIdentifier})],ed.prototype,"oid",void 0);fy.__decorate([(0,ou.AsnProp)({type:ou.AsnPropTypes.Utf8String})],ed.prototype,"string",void 0);var dy=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};cp.IetfAttrSyntax=dy;fy.__decorate([(0,ou.AsnProp)({type:ice.GeneralNames,implicit:!0,context:0,optional:!0})],dy.prototype,"policyAuthority",void 0);fy.__decorate([(0,ou.AsnProp)({type:ed,repeated:"sequence"})],dy.prototype,"values",void 0)});var sL=v(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.id_at_clearance=Qt.id_at_role=Qt.id_at=Qt.id_aca_encAttrs=Qt.id_aca_group=Qt.id_aca_chargingIdentity=Qt.id_aca_accessIdentity=Qt.id_aca_authenticationInfo=Qt.id_aca=Qt.id_ce_targetInformation=Qt.id_pe_ac_proxying=Qt.id_pe_aaControls=Qt.id_pe_ac_auditIdentity=void 0;var hy=Yt();Qt.id_pe_ac_auditIdentity=`${hy.id_pe}.4`;Qt.id_pe_aaControls=`${hy.id_pe}.6`;Qt.id_pe_ac_proxying=`${hy.id_pe}.10`;Qt.id_ce_targetInformation=`${hy.id_ce}.55`;Qt.id_aca=`${hy.id_pkix}.10`;Qt.id_aca_authenticationInfo=`${Qt.id_aca}.1`;Qt.id_aca_accessIdentity=`${Qt.id_aca}.2`;Qt.id_aca_chargingIdentity=`${Qt.id_aca}.3`;Qt.id_aca_group=`${Qt.id_aca}.4`;Qt.id_aca_encAttrs=`${Qt.id_aca}.6`;Qt.id_at="2.5.4";Qt.id_at_role=`${Qt.id_at}.72`;Qt.id_at_clearance="2.5.1.5.55"});var aI=v(Jo=>{"use strict";var sI;Object.defineProperty(Jo,"__esModule",{value:!0});Jo.Targets=Jo.Target=Jo.TargetCert=void 0;var au=(V(),H(F)),Qi=ne(),oI=Yt(),iL=sy(),oce=iy(),td=class{targetCertificate=new iL.IssuerSerial;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};Jo.TargetCert=td;au.__decorate([(0,Qi.AsnProp)({type:iL.IssuerSerial})],td.prototype,"targetCertificate",void 0);au.__decorate([(0,Qi.AsnProp)({type:oI.GeneralName,optional:!0})],td.prototype,"targetName",void 0);au.__decorate([(0,Qi.AsnProp)({type:oce.ObjectDigestInfo,optional:!0})],td.prototype,"certDigestInfo",void 0);var rd=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};Jo.Target=rd;au.__decorate([(0,Qi.AsnProp)({type:oI.GeneralName,context:0,implicit:!0})],rd.prototype,"targetName",void 0);au.__decorate([(0,Qi.AsnProp)({type:oI.GeneralName,context:1,implicit:!0})],rd.prototype,"targetGroup",void 0);au.__decorate([(0,Qi.AsnProp)({type:td,context:2,implicit:!0})],rd.prototype,"targetCert",void 0);Jo.Target=rd=au.__decorate([(0,Qi.AsnType)({type:Qi.AsnTypeTypes.Choice})],rd);var iI=sI=class extends Qi.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,sI.prototype)}};Jo.Targets=iI;Jo.Targets=iI=sI=au.__decorate([(0,Qi.AsnType)({type:Qi.AsnTypeTypes.Sequence,itemType:rd})],iI)});var oL=v(py=>{"use strict";var cI;Object.defineProperty(py,"__esModule",{value:!0});py.ProxyInfo=void 0;var ace=(V(),H(F)),uI=ne(),cce=aI(),lI=cI=class extends uI.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,cI.prototype)}};py.ProxyInfo=lI;py.ProxyInfo=lI=cI=ace.__decorate([(0,uI.AsnType)({type:uI.AsnTypeTypes.Sequence,itemType:cce.Targets})],lI)});var lL=v(Uw=>{"use strict";Object.defineProperty(Uw,"__esModule",{value:!0});Uw.RoleSyntax=void 0;var aL=(V(),H(F)),cL=ne(),uL=Yt(),my=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};Uw.RoleSyntax=my;aL.__decorate([(0,cL.AsnProp)({type:uL.GeneralNames,implicit:!0,context:0,optional:!0})],my.prototype,"roleAuthority",void 0);aL.__decorate([(0,cL.AsnProp)({type:uL.GeneralName,implicit:!0,context:1})],my.prototype,"roleName",void 0)});var dL=v(Fw=>{"use strict";Object.defineProperty(Fw,"__esModule",{value:!0});Fw.SvceAuthInfo=void 0;var dI=(V(),H(F)),qw=ne(),Hw=Yt(),up=class{service=new Hw.GeneralName;ident=new Hw.GeneralName;authInfo;constructor(e={}){Object.assign(this,e)}};Fw.SvceAuthInfo=up;dI.__decorate([(0,qw.AsnProp)({type:Hw.GeneralName})],up.prototype,"service",void 0);dI.__decorate([(0,qw.AsnProp)({type:Hw.GeneralName})],up.prototype,"ident",void 0);dI.__decorate([(0,qw.AsnProp)({type:qw.OctetString,optional:!0})],up.prototype,"authInfo",void 0)});var fI=v(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});var xn=(V(),H(F));xn.__exportStar(qz(),dn);xn.__exportStar(Fz(),dn);xn.__exportStar(K6(),dn);xn.__exportStar(Z6(),dn);xn.__exportStar(L6(),dn);xn.__exportStar(Qz(),dn);xn.__exportStar(Y6(),dn);xn.__exportStar(tI(),dn);xn.__exportStar(rL(),dn);xn.__exportStar(X6(),dn);xn.__exportStar(nL(),dn);xn.__exportStar(sy(),dn);xn.__exportStar(iy(),dn);xn.__exportStar(sL(),dn);xn.__exportStar(oL(),dn);xn.__exportStar(lL(),dn);xn.__exportStar(rI(),dn);xn.__exportStar(dL(),dn);xn.__exportStar(aI(),dn);xn.__exportStar(F6(),dn)});var Vw=v(Yo=>{"use strict";var hI;Object.defineProperty(Yo,"__esModule",{value:!0});Yo.CertificateSet=Yo.CertificateChoices=Yo.OtherCertificateFormat=void 0;var sd=(V(),H(F)),Ii=ne(),uce=Yt(),lce=fI(),lp=class{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};Yo.OtherCertificateFormat=lp;sd.__decorate([(0,Ii.AsnProp)({type:Ii.AsnPropTypes.ObjectIdentifier})],lp.prototype,"otherCertFormat",void 0);sd.__decorate([(0,Ii.AsnProp)({type:Ii.AsnPropTypes.Any})],lp.prototype,"otherCert",void 0);var nd=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};Yo.CertificateChoices=nd;sd.__decorate([(0,Ii.AsnProp)({type:uce.Certificate})],nd.prototype,"certificate",void 0);sd.__decorate([(0,Ii.AsnProp)({type:lce.AttributeCertificate,context:2,implicit:!0})],nd.prototype,"v2AttrCert",void 0);sd.__decorate([(0,Ii.AsnProp)({type:lp,context:3,implicit:!0})],nd.prototype,"other",void 0);Yo.CertificateChoices=nd=sd.__decorate([(0,Ii.AsnType)({type:Ii.AsnTypeTypes.Choice})],nd);var pI=hI=class extends Ii.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,hI.prototype)}};Yo.CertificateSet=pI;Yo.CertificateSet=pI=hI=sd.__decorate([(0,Ii.AsnType)({type:Ii.AsnTypeTypes.Set,itemType:nd})],pI)});var hL=v(Zw=>{"use strict";Object.defineProperty(Zw,"__esModule",{value:!0});Zw.ContentInfo=void 0;var fL=(V(),H(F)),Kw=ne(),gy=class{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};Zw.ContentInfo=gy;fL.__decorate([(0,Kw.AsnProp)({type:Kw.AsnPropTypes.ObjectIdentifier})],gy.prototype,"contentType",void 0);fL.__decorate([(0,Kw.AsnProp)({type:Kw.AsnPropTypes.Any,context:0})],gy.prototype,"content",void 0)});var mI=v(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});id.EncapsulatedContentInfo=id.EncapsulatedContent=void 0;var xy=(V(),H(F)),Ga=ne(),dp=class{single;any;constructor(e={}){Object.assign(this,e)}};id.EncapsulatedContent=dp;xy.__decorate([(0,Ga.AsnProp)({type:Ga.OctetString})],dp.prototype,"single",void 0);xy.__decorate([(0,Ga.AsnProp)({type:Ga.AsnPropTypes.Any})],dp.prototype,"any",void 0);id.EncapsulatedContent=dp=xy.__decorate([(0,Ga.AsnType)({type:Ga.AsnTypeTypes.Choice})],dp);var yy=class{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}};id.EncapsulatedContentInfo=yy;xy.__decorate([(0,Ga.AsnProp)({type:Ga.AsnPropTypes.ObjectIdentifier})],yy.prototype,"eContentType",void 0);xy.__decorate([(0,Ga.AsnProp)({type:dp,context:0,optional:!0})],yy.prototype,"eContent",void 0)});var gI=v(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});od.EncryptedContentInfo=od.EncryptedContent=void 0;var pp=(V(),H(F)),eo=ne(),pL=Xo(),fp=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};od.EncryptedContent=fp;pp.__decorate([(0,eo.AsnProp)({type:eo.OctetString,context:0,implicit:!0,optional:!0})],fp.prototype,"value",void 0);pp.__decorate([(0,eo.AsnProp)({type:eo.OctetString,converter:eo.AsnConstructedOctetStringConverter,context:0,implicit:!0,optional:!0,repeated:"sequence"})],fp.prototype,"constructedValue",void 0);od.EncryptedContent=fp=pp.__decorate([(0,eo.AsnType)({type:eo.AsnTypeTypes.Choice})],fp);var hp=class{contentType="";contentEncryptionAlgorithm=new pL.ContentEncryptionAlgorithmIdentifier;encryptedContent;constructor(e={}){Object.assign(this,e)}};od.EncryptedContentInfo=hp;pp.__decorate([(0,eo.AsnProp)({type:eo.AsnPropTypes.ObjectIdentifier})],hp.prototype,"contentType",void 0);pp.__decorate([(0,eo.AsnProp)({type:pL.ContentEncryptionAlgorithmIdentifier})],hp.prototype,"contentEncryptionAlgorithm",void 0);pp.__decorate([(0,eo.AsnProp)({type:fp,optional:!0})],hp.prototype,"encryptedContent",void 0)});var yI=v(Ww=>{"use strict";Object.defineProperty(Ww,"__esModule",{value:!0});Ww.OtherKeyAttribute=void 0;var mL=(V(),H(F)),Gw=ne(),by=class{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}};Ww.OtherKeyAttribute=by;mL.__decorate([(0,Gw.AsnProp)({type:Gw.AsnPropTypes.ObjectIdentifier})],by.prototype,"keyAttrId",void 0);mL.__decorate([(0,Gw.AsnProp)({type:Gw.AsnPropTypes.Any,optional:!0})],by.prototype,"keyAttr",void 0)});var _I=v(Cn=>{"use strict";var xI;Object.defineProperty(Cn,"__esModule",{value:!0});Cn.KeyAgreeRecipientInfo=Cn.OriginatorIdentifierOrKey=Cn.OriginatorPublicKey=Cn.RecipientEncryptedKeys=Cn.RecipientEncryptedKey=Cn.KeyAgreeRecipientIdentifier=Cn.RecipientKeyIdentifier=void 0;var bn=(V(),H(F)),fr=ne(),vy=Yt(),bI=Xo(),gL=Yg(),dce=yI(),ad=class{subjectKeyIdentifier=new vy.SubjectKeyIdentifier;date;other;constructor(e={}){Object.assign(this,e)}};Cn.RecipientKeyIdentifier=ad;bn.__decorate([(0,fr.AsnProp)({type:vy.SubjectKeyIdentifier})],ad.prototype,"subjectKeyIdentifier",void 0);bn.__decorate([(0,fr.AsnProp)({type:fr.AsnPropTypes.GeneralizedTime,optional:!0})],ad.prototype,"date",void 0);bn.__decorate([(0,fr.AsnProp)({type:dce.OtherKeyAttribute,optional:!0})],ad.prototype,"other",void 0);var cd=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};Cn.KeyAgreeRecipientIdentifier=cd;bn.__decorate([(0,fr.AsnProp)({type:ad,context:0,implicit:!0,optional:!0})],cd.prototype,"rKeyId",void 0);bn.__decorate([(0,fr.AsnProp)({type:gL.IssuerAndSerialNumber,optional:!0})],cd.prototype,"issuerAndSerialNumber",void 0);Cn.KeyAgreeRecipientIdentifier=cd=bn.__decorate([(0,fr.AsnType)({type:fr.AsnTypeTypes.Choice})],cd);var mp=class{rid=new cd;encryptedKey=new fr.OctetString;constructor(e={}){Object.assign(this,e)}};Cn.RecipientEncryptedKey=mp;bn.__decorate([(0,fr.AsnProp)({type:cd})],mp.prototype,"rid",void 0);bn.__decorate([(0,fr.AsnProp)({type:fr.OctetString})],mp.prototype,"encryptedKey",void 0);var _y=xI=class extends fr.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,xI.prototype)}};Cn.RecipientEncryptedKeys=_y;Cn.RecipientEncryptedKeys=_y=xI=bn.__decorate([(0,fr.AsnType)({type:fr.AsnTypeTypes.Sequence,itemType:mp})],_y);var gp=class{algorithm=new vy.AlgorithmIdentifier;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};Cn.OriginatorPublicKey=gp;bn.__decorate([(0,fr.AsnProp)({type:vy.AlgorithmIdentifier})],gp.prototype,"algorithm",void 0);bn.__decorate([(0,fr.AsnProp)({type:fr.AsnPropTypes.BitString})],gp.prototype,"publicKey",void 0);var cu=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};Cn.OriginatorIdentifierOrKey=cu;bn.__decorate([(0,fr.AsnProp)({type:vy.SubjectKeyIdentifier,context:0,implicit:!0,optional:!0})],cu.prototype,"subjectKeyIdentifier",void 0);bn.__decorate([(0,fr.AsnProp)({type:gp,context:1,implicit:!0,optional:!0})],cu.prototype,"originatorKey",void 0);bn.__decorate([(0,fr.AsnProp)({type:gL.IssuerAndSerialNumber,optional:!0})],cu.prototype,"issuerAndSerialNumber",void 0);Cn.OriginatorIdentifierOrKey=cu=bn.__decorate([(0,fr.AsnType)({type:fr.AsnTypeTypes.Choice})],cu);var uu=class{version=bI.CMSVersion.v3;originator=new cu;ukm;keyEncryptionAlgorithm=new bI.KeyEncryptionAlgorithmIdentifier;recipientEncryptedKeys=new _y;constructor(e={}){Object.assign(this,e)}};Cn.KeyAgreeRecipientInfo=uu;bn.__decorate([(0,fr.AsnProp)({type:fr.AsnPropTypes.Integer})],uu.prototype,"version",void 0);bn.__decorate([(0,fr.AsnProp)({type:cu,context:0})],uu.prototype,"originator",void 0);bn.__decorate([(0,fr.AsnProp)({type:fr.OctetString,context:1,optional:!0})],uu.prototype,"ukm",void 0);bn.__decorate([(0,fr.AsnProp)({type:bI.KeyEncryptionAlgorithmIdentifier})],uu.prototype,"keyEncryptionAlgorithm",void 0);bn.__decorate([(0,fr.AsnProp)({type:_y})],uu.prototype,"recipientEncryptedKeys",void 0)});var wI=v(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});dd.KeyTransRecipientInfo=dd.RecipientIdentifier=void 0;var fd=(V(),H(F)),to=ne(),fce=Yt(),vI=Xo(),hce=Yg(),ud=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};dd.RecipientIdentifier=ud;fd.__decorate([(0,to.AsnProp)({type:fce.SubjectKeyIdentifier,context:0,implicit:!0})],ud.prototype,"subjectKeyIdentifier",void 0);fd.__decorate([(0,to.AsnProp)({type:hce.IssuerAndSerialNumber})],ud.prototype,"issuerAndSerialNumber",void 0);dd.RecipientIdentifier=ud=fd.__decorate([(0,to.AsnType)({type:to.AsnTypeTypes.Choice})],ud);var ld=class{version=vI.CMSVersion.v0;rid=new ud;keyEncryptionAlgorithm=new vI.KeyEncryptionAlgorithmIdentifier;encryptedKey=new to.OctetString;constructor(e={}){Object.assign(this,e)}};dd.KeyTransRecipientInfo=ld;fd.__decorate([(0,to.AsnProp)({type:to.AsnPropTypes.Integer})],ld.prototype,"version",void 0);fd.__decorate([(0,to.AsnProp)({type:ud})],ld.prototype,"rid",void 0);fd.__decorate([(0,to.AsnProp)({type:vI.KeyEncryptionAlgorithmIdentifier})],ld.prototype,"keyEncryptionAlgorithm",void 0);fd.__decorate([(0,to.AsnProp)({type:to.OctetString})],ld.prototype,"encryptedKey",void 0)});var AI=v(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});yp.KEKRecipientInfo=yp.KEKIdentifier=void 0;var pd=(V(),H(F)),li=ne(),pce=yI(),SI=Xo(),lu=class{keyIdentifier=new li.OctetString;date;other;constructor(e={}){Object.assign(this,e)}};yp.KEKIdentifier=lu;pd.__decorate([(0,li.AsnProp)({type:li.OctetString})],lu.prototype,"keyIdentifier",void 0);pd.__decorate([(0,li.AsnProp)({type:li.AsnPropTypes.GeneralizedTime,optional:!0})],lu.prototype,"date",void 0);pd.__decorate([(0,li.AsnProp)({type:pce.OtherKeyAttribute,optional:!0})],lu.prototype,"other",void 0);var hd=class{version=SI.CMSVersion.v4;kekid=new lu;keyEncryptionAlgorithm=new SI.KeyEncryptionAlgorithmIdentifier;encryptedKey=new li.OctetString;constructor(e={}){Object.assign(this,e)}};yp.KEKRecipientInfo=hd;pd.__decorate([(0,li.AsnProp)({type:li.AsnPropTypes.Integer})],hd.prototype,"version",void 0);pd.__decorate([(0,li.AsnProp)({type:lu})],hd.prototype,"kekid",void 0);pd.__decorate([(0,li.AsnProp)({type:SI.KeyEncryptionAlgorithmIdentifier})],hd.prototype,"keyEncryptionAlgorithm",void 0);pd.__decorate([(0,li.AsnProp)({type:li.OctetString})],hd.prototype,"encryptedKey",void 0)});var EI=v(Yw=>{"use strict";Object.defineProperty(Yw,"__esModule",{value:!0});Yw.PasswordRecipientInfo=void 0;var Jw=(V(),H(F)),md=ne(),Xw=Xo(),gd=class{version=Xw.CMSVersion.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Xw.KeyEncryptionAlgorithmIdentifier;encryptedKey=new md.OctetString;constructor(e={}){Object.assign(this,e)}};Yw.PasswordRecipientInfo=gd;Jw.__decorate([(0,md.AsnProp)({type:md.AsnPropTypes.Integer})],gd.prototype,"version",void 0);Jw.__decorate([(0,md.AsnProp)({type:Xw.KeyDerivationAlgorithmIdentifier,context:0,optional:!0})],gd.prototype,"keyDerivationAlgorithm",void 0);Jw.__decorate([(0,md.AsnProp)({type:Xw.KeyEncryptionAlgorithmIdentifier})],gd.prototype,"keyEncryptionAlgorithm",void 0);Jw.__decorate([(0,md.AsnProp)({type:md.OctetString})],gd.prototype,"encryptedKey",void 0)});var CI=v(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});yd.RecipientInfo=yd.OtherRecipientInfo=void 0;var fu=(V(),H(F)),ro=ne(),mce=_I(),gce=wI(),yce=AI(),xce=EI(),xp=class{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};yd.OtherRecipientInfo=xp;fu.__decorate([(0,ro.AsnProp)({type:ro.AsnPropTypes.ObjectIdentifier})],xp.prototype,"oriType",void 0);fu.__decorate([(0,ro.AsnProp)({type:ro.AsnPropTypes.Any})],xp.prototype,"oriValue",void 0);var du=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};yd.RecipientInfo=du;fu.__decorate([(0,ro.AsnProp)({type:gce.KeyTransRecipientInfo,optional:!0})],du.prototype,"ktri",void 0);fu.__decorate([(0,ro.AsnProp)({type:mce.KeyAgreeRecipientInfo,context:1,implicit:!0,optional:!0})],du.prototype,"kari",void 0);fu.__decorate([(0,ro.AsnProp)({type:yce.KEKRecipientInfo,context:2,implicit:!0,optional:!0})],du.prototype,"kekri",void 0);fu.__decorate([(0,ro.AsnProp)({type:xce.PasswordRecipientInfo,context:3,implicit:!0,optional:!0})],du.prototype,"pwri",void 0);fu.__decorate([(0,ro.AsnProp)({type:xp,context:4,implicit:!0,optional:!0})],du.prototype,"ori",void 0);yd.RecipientInfo=du=fu.__decorate([(0,ro.AsnType)({type:ro.AsnTypeTypes.Choice})],du)});var PI=v(wy=>{"use strict";var kI;Object.defineProperty(wy,"__esModule",{value:!0});wy.RecipientInfos=void 0;var bce=(V(),H(F)),TI=ne(),_ce=CI(),II=kI=class extends TI.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,kI.prototype)}};wy.RecipientInfos=II;wy.RecipientInfos=II=kI=bce.__decorate([(0,TI.AsnType)({type:TI.AsnTypeTypes.Set,itemType:_ce.RecipientInfo})],II)});var Qw=v($n=>{"use strict";var RI;Object.defineProperty($n,"__esModule",{value:!0});$n.RevocationInfoChoices=$n.RevocationInfoChoice=$n.OtherRevocationInfoFormat=$n.id_ri_scvp=$n.id_ri_ocsp_response=$n.id_ri=void 0;var Ay=(V(),H(F)),Qo=ne(),vce=Yt();$n.id_ri=`${vce.id_pkix}.16`;$n.id_ri_ocsp_response=`${$n.id_ri}.2`;$n.id_ri_scvp=`${$n.id_ri}.4`;var xd=class{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};$n.OtherRevocationInfoFormat=xd;Ay.__decorate([(0,Qo.AsnProp)({type:Qo.AsnPropTypes.ObjectIdentifier})],xd.prototype,"otherRevInfoFormat",void 0);Ay.__decorate([(0,Qo.AsnProp)({type:Qo.AsnPropTypes.Any})],xd.prototype,"otherRevInfo",void 0);var Sy=class{other=new xd;constructor(e={}){Object.assign(this,e)}};$n.RevocationInfoChoice=Sy;Ay.__decorate([(0,Qo.AsnProp)({type:xd,context:1,implicit:!0})],Sy.prototype,"other",void 0);$n.RevocationInfoChoice=Sy=Ay.__decorate([(0,Qo.AsnType)({type:Qo.AsnTypeTypes.Choice})],Sy);var OI=RI=class extends Qo.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,RI.prototype)}};$n.RevocationInfoChoices=OI;$n.RevocationInfoChoices=OI=RI=Ay.__decorate([(0,Qo.AsnType)({type:Qo.AsnTypeTypes.Set,itemType:Sy})],OI)});var NI=v(eS=>{"use strict";Object.defineProperty(eS,"__esModule",{value:!0});eS.OriginatorInfo=void 0;var yL=(V(),H(F)),xL=ne(),wce=Vw(),Sce=Qw(),Ey=class{certs;crls;constructor(e={}){Object.assign(this,e)}};eS.OriginatorInfo=Ey;yL.__decorate([(0,xL.AsnProp)({type:wce.CertificateSet,context:0,implicit:!0,optional:!0})],Ey.prototype,"certs",void 0);yL.__decorate([(0,xL.AsnProp)({type:Sce.RevocationInfoChoices,context:1,implicit:!0,optional:!0})],Ey.prototype,"crls",void 0)});var vL=v(bd=>{"use strict";var BI;Object.defineProperty(bd,"__esModule",{value:!0});bd.EnvelopedData=bd.UnprotectedAttributes=void 0;var bp=(V(),H(F)),Wa=ne(),Ace=Xo(),Ece=_w(),bL=PI(),Cce=NI(),_L=gI(),tS=BI=class extends Wa.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,BI.prototype)}};bd.UnprotectedAttributes=tS;bd.UnprotectedAttributes=tS=BI=bp.__decorate([(0,Wa.AsnType)({type:Wa.AsnTypeTypes.Set,itemType:Ece.Attribute})],tS);var hu=class{version=Ace.CMSVersion.v0;originatorInfo;recipientInfos=new bL.RecipientInfos;encryptedContentInfo=new _L.EncryptedContentInfo;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};bd.EnvelopedData=hu;bp.__decorate([(0,Wa.AsnProp)({type:Wa.AsnPropTypes.Integer})],hu.prototype,"version",void 0);bp.__decorate([(0,Wa.AsnProp)({type:Cce.OriginatorInfo,context:0,implicit:!0,optional:!0})],hu.prototype,"originatorInfo",void 0);bp.__decorate([(0,Wa.AsnProp)({type:bL.RecipientInfos})],hu.prototype,"recipientInfos",void 0);bp.__decorate([(0,Wa.AsnProp)({type:_L.EncryptedContentInfo})],hu.prototype,"encryptedContentInfo",void 0);bp.__decorate([(0,Wa.AsnProp)({type:tS,context:1,implicit:!0,optional:!0})],hu.prototype,"unprotectedAttrs",void 0)});var wL=v(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.id_authData=os.id_encryptedData=os.id_digestedData=os.id_envelopedData=os.id_signedData=os.id_data=os.id_ct_contentInfo=void 0;os.id_ct_contentInfo="1.2.840.113549.1.9.16.1.6";os.id_data="1.2.840.113549.1.7.1";os.id_signedData="1.2.840.113549.1.7.2";os.id_envelopedData="1.2.840.113549.1.7.3";os.id_digestedData="1.2.840.113549.1.7.5";os.id_encryptedData="1.2.840.113549.1.7.6";os.id_authData="1.2.840.113549.1.9.16.1.2"});var CL=v(_d=>{"use strict";var $I;Object.defineProperty(_d,"__esModule",{value:!0});_d.SignedData=_d.DigestAlgorithmIdentifiers=void 0;var vd=(V(),H(F)),ea=ne(),kce=Vw(),SL=Xo(),AL=mI(),Tce=Qw(),EL=vw(),Cy=$I=class extends ea.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,$I.prototype)}};_d.DigestAlgorithmIdentifiers=Cy;_d.DigestAlgorithmIdentifiers=Cy=$I=vd.__decorate([(0,ea.AsnType)({type:ea.AsnTypeTypes.Set,itemType:SL.DigestAlgorithmIdentifier})],Cy);var Xa=class{version=SL.CMSVersion.v0;digestAlgorithms=new Cy;encapContentInfo=new AL.EncapsulatedContentInfo;certificates;crls;signerInfos=new EL.SignerInfos;constructor(e={}){Object.assign(this,e)}};_d.SignedData=Xa;vd.__decorate([(0,ea.AsnProp)({type:ea.AsnPropTypes.Integer})],Xa.prototype,"version",void 0);vd.__decorate([(0,ea.AsnProp)({type:Cy})],Xa.prototype,"digestAlgorithms",void 0);vd.__decorate([(0,ea.AsnProp)({type:AL.EncapsulatedContentInfo})],Xa.prototype,"encapContentInfo",void 0);vd.__decorate([(0,ea.AsnProp)({type:kce.CertificateSet,context:0,implicit:!0,optional:!0})],Xa.prototype,"certificates",void 0);vd.__decorate([(0,ea.AsnProp)({type:Tce.RevocationInfoChoices,context:1,implicit:!0,optional:!0})],Xa.prototype,"crls",void 0);vd.__decorate([(0,ea.AsnProp)({type:EL.SignerInfos})],Xa.prototype,"signerInfos",void 0)});var ky=v(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});var hn=(V(),H(F));hn.__exportStar(Uz(),Qr);hn.__exportStar(_w(),Qr);hn.__exportStar(Vw(),Qr);hn.__exportStar(hL(),Qr);hn.__exportStar(mI(),Qr);hn.__exportStar(gI(),Qr);hn.__exportStar(vL(),Qr);hn.__exportStar(Yg(),Qr);hn.__exportStar(AI(),Qr);hn.__exportStar(_I(),Qr);hn.__exportStar(wI(),Qr);hn.__exportStar(wL(),Qr);hn.__exportStar(NI(),Qr);hn.__exportStar(EI(),Qr);hn.__exportStar(CI(),Qr);hn.__exportStar(PI(),Qr);hn.__exportStar(Qw(),Qr);hn.__exportStar(CL(),Qr);hn.__exportStar(w6(),Qr);hn.__exportStar(vw(),Qr);hn.__exportStar(Xo(),Qr)});var MI=v(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.id_sect571r1=dt.id_sect571k1=dt.id_secp521r1=dt.id_sect409r1=dt.id_sect409k1=dt.id_secp384r1=dt.id_sect283r1=dt.id_sect283k1=dt.id_secp256r1=dt.id_sect233r1=dt.id_sect233k1=dt.id_secp224r1=dt.id_sect163r2=dt.id_sect163k1=dt.id_secp192r1=dt.id_ecdsaWithSHA512=dt.id_ecdsaWithSHA384=dt.id_ecdsaWithSHA256=dt.id_ecdsaWithSHA224=dt.id_ecdsaWithSHA1=dt.id_ecMQV=dt.id_ecDH=dt.id_ecPublicKey=void 0;dt.id_ecPublicKey="1.2.840.10045.2.1";dt.id_ecDH="1.3.132.1.12";dt.id_ecMQV="1.3.132.1.13";dt.id_ecdsaWithSHA1="1.2.840.10045.4.1";dt.id_ecdsaWithSHA224="1.2.840.10045.4.3.1";dt.id_ecdsaWithSHA256="1.2.840.10045.4.3.2";dt.id_ecdsaWithSHA384="1.2.840.10045.4.3.3";dt.id_ecdsaWithSHA512="1.2.840.10045.4.3.4";dt.id_secp192r1="1.2.840.10045.3.1.1";dt.id_sect163k1="1.3.132.0.1";dt.id_sect163r2="1.3.132.0.15";dt.id_secp224r1="1.3.132.0.33";dt.id_sect233k1="1.3.132.0.26";dt.id_sect233r1="1.3.132.0.27";dt.id_secp256r1="1.2.840.10045.3.1.7";dt.id_sect283k1="1.3.132.0.16";dt.id_sect283r1="1.3.132.0.17";dt.id_secp384r1="1.3.132.0.34";dt.id_sect409k1="1.3.132.0.36";dt.id_sect409r1="1.3.132.0.37";dt.id_secp521r1="1.3.132.0.35";dt.id_sect571k1="1.3.132.0.38";dt.id_sect571r1="1.3.132.0.39"});var kL=v(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.ecdsaWithSHA512=Pi.ecdsaWithSHA384=Pi.ecdsaWithSHA256=Pi.ecdsaWithSHA224=Pi.ecdsaWithSHA1=void 0;var Ice=(V(),H(F)),Pce=Yt(),Ty=Ice.__importStar(MI());function Iy(t){return new Pce.AlgorithmIdentifier({algorithm:t})}Pi.ecdsaWithSHA1=Iy(Ty.id_ecdsaWithSHA1);Pi.ecdsaWithSHA224=Iy(Ty.id_ecdsaWithSHA224);Pi.ecdsaWithSHA256=Iy(Ty.id_ecdsaWithSHA256);Pi.ecdsaWithSHA384=Iy(Ty.id_ecdsaWithSHA384);Pi.ecdsaWithSHA512=Iy(Ty.id_ecdsaWithSHA512)});var LI=v(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.SpecifiedECDomain=Un.ECPVer=Un.Curve=Un.FieldElement=Un.ECPoint=Un.FieldID=void 0;var Bs=(V(),H(F)),_r=ne(),_p=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};Un.FieldID=_p;Bs.__decorate([(0,_r.AsnProp)({type:_r.AsnPropTypes.ObjectIdentifier})],_p.prototype,"fieldType",void 0);Bs.__decorate([(0,_r.AsnProp)({type:_r.AsnPropTypes.Any})],_p.prototype,"parameters",void 0);Un.FieldID=_p=Bs.__decorate([(0,_r.AsnType)({type:_r.AsnTypeTypes.Sequence})],_p);var rS=class extends _r.OctetString{};Un.ECPoint=rS;var jI=class extends _r.OctetString{};Un.FieldElement=jI;var wd=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};Un.Curve=wd;Bs.__decorate([(0,_r.AsnProp)({type:_r.AsnPropTypes.OctetString})],wd.prototype,"a",void 0);Bs.__decorate([(0,_r.AsnProp)({type:_r.AsnPropTypes.OctetString})],wd.prototype,"b",void 0);Bs.__decorate([(0,_r.AsnProp)({type:_r.AsnPropTypes.BitString,optional:!0})],wd.prototype,"seed",void 0);Un.Curve=wd=Bs.__decorate([(0,_r.AsnType)({type:_r.AsnTypeTypes.Sequence})],wd);var zI;(function(t){t[t.ecpVer1=1]="ecpVer1"})(zI||(Un.ECPVer=zI={}));var Ja=class{version=zI.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};Un.SpecifiedECDomain=Ja;Bs.__decorate([(0,_r.AsnProp)({type:_r.AsnPropTypes.Integer})],Ja.prototype,"version",void 0);Bs.__decorate([(0,_r.AsnProp)({type:_p})],Ja.prototype,"fieldID",void 0);Bs.__decorate([(0,_r.AsnProp)({type:wd})],Ja.prototype,"curve",void 0);Bs.__decorate([(0,_r.AsnProp)({type:rS})],Ja.prototype,"base",void 0);Bs.__decorate([(0,_r.AsnProp)({type:_r.AsnPropTypes.Integer,converter:_r.AsnIntegerArrayBufferConverter})],Ja.prototype,"order",void 0);Bs.__decorate([(0,_r.AsnProp)({type:_r.AsnPropTypes.Integer,optional:!0})],Ja.prototype,"cofactor",void 0);Un.SpecifiedECDomain=Ja=Bs.__decorate([(0,_r.AsnType)({type:_r.AsnTypeTypes.Sequence})],Ja)});var DI=v(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});Py.ECParameters=void 0;var nS=(V(),H(F)),Sd=ne(),Rce=LI(),vp=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};Py.ECParameters=vp;nS.__decorate([(0,Sd.AsnProp)({type:Sd.AsnPropTypes.ObjectIdentifier})],vp.prototype,"namedCurve",void 0);nS.__decorate([(0,Sd.AsnProp)({type:Sd.AsnPropTypes.Null})],vp.prototype,"implicitCurve",void 0);nS.__decorate([(0,Sd.AsnProp)({type:Rce.SpecifiedECDomain})],vp.prototype,"specifiedCurve",void 0);Py.ECParameters=vp=nS.__decorate([(0,Sd.AsnType)({type:Sd.AsnTypeTypes.Choice})],vp)});var TL=v(iS=>{"use strict";Object.defineProperty(iS,"__esModule",{value:!0});iS.ECPrivateKey=void 0;var sS=(V(),H(F)),pu=ne(),Oce=DI(),Ad=class{version=1;privateKey=new pu.OctetString;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};iS.ECPrivateKey=Ad;sS.__decorate([(0,pu.AsnProp)({type:pu.AsnPropTypes.Integer})],Ad.prototype,"version",void 0);sS.__decorate([(0,pu.AsnProp)({type:pu.OctetString})],Ad.prototype,"privateKey",void 0);sS.__decorate([(0,pu.AsnProp)({type:Oce.ECParameters,context:0,optional:!0})],Ad.prototype,"parameters",void 0);sS.__decorate([(0,pu.AsnProp)({type:pu.AsnPropTypes.BitString,context:1,optional:!0})],Ad.prototype,"publicKey",void 0)});var PL=v(oS=>{"use strict";Object.defineProperty(oS,"__esModule",{value:!0});oS.ECDSASigValue=void 0;var IL=(V(),H(F)),wp=ne(),Ry=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};oS.ECDSASigValue=Ry;IL.__decorate([(0,wp.AsnProp)({type:wp.AsnPropTypes.Integer,converter:wp.AsnIntegerArrayBufferConverter})],Ry.prototype,"r",void 0);IL.__decorate([(0,wp.AsnProp)({type:wp.AsnPropTypes.Integer,converter:wp.AsnIntegerArrayBufferConverter})],Ry.prototype,"s",void 0)});var RL=v(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});var Sp=(V(),H(F));Sp.__exportStar(kL(),mu);Sp.__exportStar(DI(),mu);Sp.__exportStar(TL(),mu);Sp.__exportStar(PL(),mu);Sp.__exportStar(MI(),mu);Sp.__exportStar(LI(),mu)});var Oy=v(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.id_mgf1=Me.id_md5=Me.id_md2=Me.id_sha512_256=Me.id_sha512_224=Me.id_sha512=Me.id_sha384=Me.id_sha256=Me.id_sha224=Me.id_sha1=Me.id_sha512_256WithRSAEncryption=Me.id_sha512_224WithRSAEncryption=Me.id_sha512WithRSAEncryption=Me.id_sha384WithRSAEncryption=Me.id_sha256WithRSAEncryption=Me.id_ssha224WithRSAEncryption=Me.id_sha224WithRSAEncryption=Me.id_sha1WithRSAEncryption=Me.id_md5WithRSAEncryption=Me.id_md2WithRSAEncryption=Me.id_RSASSA_PSS=Me.id_pSpecified=Me.id_RSAES_OAEP=Me.id_rsaEncryption=Me.id_pkcs_1=void 0;Me.id_pkcs_1="1.2.840.113549.1.1";Me.id_rsaEncryption=`${Me.id_pkcs_1}.1`;Me.id_RSAES_OAEP=`${Me.id_pkcs_1}.7`;Me.id_pSpecified=`${Me.id_pkcs_1}.9`;Me.id_RSASSA_PSS=`${Me.id_pkcs_1}.10`;Me.id_md2WithRSAEncryption=`${Me.id_pkcs_1}.2`;Me.id_md5WithRSAEncryption=`${Me.id_pkcs_1}.4`;Me.id_sha1WithRSAEncryption=`${Me.id_pkcs_1}.5`;Me.id_sha224WithRSAEncryption=`${Me.id_pkcs_1}.14`;Me.id_ssha224WithRSAEncryption=Me.id_sha224WithRSAEncryption;Me.id_sha256WithRSAEncryption=`${Me.id_pkcs_1}.11`;Me.id_sha384WithRSAEncryption=`${Me.id_pkcs_1}.12`;Me.id_sha512WithRSAEncryption=`${Me.id_pkcs_1}.13`;Me.id_sha512_224WithRSAEncryption=`${Me.id_pkcs_1}.15`;Me.id_sha512_256WithRSAEncryption=`${Me.id_pkcs_1}.16`;Me.id_sha1="1.3.14.3.2.26";Me.id_sha224="2.16.840.1.101.3.4.2.4";Me.id_sha256="2.16.840.1.101.3.4.2.1";Me.id_sha384="2.16.840.1.101.3.4.2.2";Me.id_sha512="2.16.840.1.101.3.4.2.3";Me.id_sha512_224="2.16.840.1.101.3.4.2.5";Me.id_sha512_256="2.16.840.1.101.3.4.2.6";Me.id_md2="1.2.840.113549.2.2";Me.id_md5="1.2.840.113549.2.5";Me.id_mgf1=`${Me.id_pkcs_1}.8`});var aS=v(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.sha512_256WithRSAEncryption=_t.sha512_224WithRSAEncryption=_t.sha512WithRSAEncryption=_t.sha384WithRSAEncryption=_t.sha256WithRSAEncryption=_t.sha224WithRSAEncryption=_t.sha1WithRSAEncryption=_t.md5WithRSAEncryption=_t.md2WithRSAEncryption=_t.rsaEncryption=_t.pSpecifiedEmpty=_t.mgf1SHA1=_t.sha512_256=_t.sha512_224=_t.sha512=_t.sha384=_t.sha256=_t.sha224=_t.sha1=_t.md4=_t.md2=void 0;var Nce=(V(),H(F)),UI=ne(),qI=Yt(),pn=Nce.__importStar(Oy());function kn(t){return new qI.AlgorithmIdentifier({algorithm:t,parameters:null})}_t.md2=kn(pn.id_md2);_t.md4=kn(pn.id_md5);_t.sha1=kn(pn.id_sha1);_t.sha224=kn(pn.id_sha224);_t.sha256=kn(pn.id_sha256);_t.sha384=kn(pn.id_sha384);_t.sha512=kn(pn.id_sha512);_t.sha512_224=kn(pn.id_sha512_224);_t.sha512_256=kn(pn.id_sha512_256);_t.mgf1SHA1=new qI.AlgorithmIdentifier({algorithm:pn.id_mgf1,parameters:UI.AsnConvert.serialize(_t.sha1)});_t.pSpecifiedEmpty=new qI.AlgorithmIdentifier({algorithm:pn.id_pSpecified,parameters:UI.AsnConvert.serialize(UI.AsnOctetStringConverter.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});_t.rsaEncryption=kn(pn.id_rsaEncryption);_t.md2WithRSAEncryption=kn(pn.id_md2WithRSAEncryption);_t.md5WithRSAEncryption=kn(pn.id_md5WithRSAEncryption);_t.sha1WithRSAEncryption=kn(pn.id_sha1WithRSAEncryption);_t.sha224WithRSAEncryption=kn(pn.id_sha512_224WithRSAEncryption);_t.sha256WithRSAEncryption=kn(pn.id_sha512_256WithRSAEncryption);_t.sha384WithRSAEncryption=kn(pn.id_sha384WithRSAEncryption);_t.sha512WithRSAEncryption=kn(pn.id_sha512WithRSAEncryption);_t.sha512_224WithRSAEncryption=kn(pn.id_sha512_224WithRSAEncryption);_t.sha512_256WithRSAEncryption=kn(pn.id_sha512_256WithRSAEncryption)});var NL=v(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});Ep.RSAES_OAEP=Ep.RsaEsOaepParams=void 0;var HI=(V(),H(F)),Ny=ne(),Ed=Yt(),OL=Oy(),Ap=aS(),Cd=class{hashAlgorithm=new Ed.AlgorithmIdentifier(Ap.sha1);maskGenAlgorithm=new Ed.AlgorithmIdentifier({algorithm:OL.id_mgf1,parameters:Ny.AsnConvert.serialize(Ap.sha1)});pSourceAlgorithm=new Ed.AlgorithmIdentifier(Ap.pSpecifiedEmpty);constructor(e={}){Object.assign(this,e)}};Ep.RsaEsOaepParams=Cd;HI.__decorate([(0,Ny.AsnProp)({type:Ed.AlgorithmIdentifier,context:0,defaultValue:Ap.sha1})],Cd.prototype,"hashAlgorithm",void 0);HI.__decorate([(0,Ny.AsnProp)({type:Ed.AlgorithmIdentifier,context:1,defaultValue:Ap.mgf1SHA1})],Cd.prototype,"maskGenAlgorithm",void 0);HI.__decorate([(0,Ny.AsnProp)({type:Ed.AlgorithmIdentifier,context:2,defaultValue:Ap.pSpecifiedEmpty})],Cd.prototype,"pSourceAlgorithm",void 0);Ep.RSAES_OAEP=new Ed.AlgorithmIdentifier({algorithm:OL.id_RSAES_OAEP,parameters:Ny.AsnConvert.serialize(new Cd)})});var $L=v(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});Cp.RSASSA_PSS=Cp.RsaSaPssParams=void 0;var uS=(V(),H(F)),gu=ne(),By=Yt(),BL=Oy(),cS=aS(),yu=class{hashAlgorithm=new By.AlgorithmIdentifier(cS.sha1);maskGenAlgorithm=new By.AlgorithmIdentifier({algorithm:BL.id_mgf1,parameters:gu.AsnConvert.serialize(cS.sha1)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};Cp.RsaSaPssParams=yu;uS.__decorate([(0,gu.AsnProp)({type:By.AlgorithmIdentifier,context:0,defaultValue:cS.sha1})],yu.prototype,"hashAlgorithm",void 0);uS.__decorate([(0,gu.AsnProp)({type:By.AlgorithmIdentifier,context:1,defaultValue:cS.mgf1SHA1})],yu.prototype,"maskGenAlgorithm",void 0);uS.__decorate([(0,gu.AsnProp)({type:gu.AsnPropTypes.Integer,context:2,defaultValue:20})],yu.prototype,"saltLength",void 0);uS.__decorate([(0,gu.AsnProp)({type:gu.AsnPropTypes.Integer,context:3,defaultValue:1})],yu.prototype,"trailerField",void 0);Cp.RSASSA_PSS=new By.AlgorithmIdentifier({algorithm:BL.id_RSASSA_PSS,parameters:gu.AsnConvert.serialize(new yu)})});var zL=v(dS=>{"use strict";Object.defineProperty(dS,"__esModule",{value:!0});dS.DigestInfo=void 0;var ML=(V(),H(F)),jL=Yt(),lS=ne(),$y=class{digestAlgorithm=new jL.AlgorithmIdentifier;digest=new lS.OctetString;constructor(e={}){Object.assign(this,e)}};dS.DigestInfo=$y;ML.__decorate([(0,lS.AsnProp)({type:jL.AlgorithmIdentifier})],$y.prototype,"digestAlgorithm",void 0);ML.__decorate([(0,lS.AsnProp)({type:lS.OctetString})],$y.prototype,"digest",void 0)});var LL=v(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});var FI=(V(),H(F));FI.__exportStar(NL(),My);FI.__exportStar($L(),My);FI.__exportStar(zL(),My)});var ZI=v(Td=>{"use strict";var VI;Object.defineProperty(Td,"__esModule",{value:!0});Td.OtherPrimeInfos=Td.OtherPrimeInfo=void 0;var fS=(V(),H(F)),Ri=ne(),kd=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};Td.OtherPrimeInfo=kd;fS.__decorate([(0,Ri.AsnProp)({type:Ri.AsnPropTypes.Integer,converter:Ri.AsnIntegerArrayBufferConverter})],kd.prototype,"prime",void 0);fS.__decorate([(0,Ri.AsnProp)({type:Ri.AsnPropTypes.Integer,converter:Ri.AsnIntegerArrayBufferConverter})],kd.prototype,"exponent",void 0);fS.__decorate([(0,Ri.AsnProp)({type:Ri.AsnPropTypes.Integer,converter:Ri.AsnIntegerArrayBufferConverter})],kd.prototype,"coefficient",void 0);var KI=VI=class extends Ri.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,VI.prototype)}};Td.OtherPrimeInfos=KI;Td.OtherPrimeInfos=KI=VI=fS.__decorate([(0,Ri.AsnType)({type:Ri.AsnTypeTypes.Sequence,itemType:kd})],KI)});var DL=v(hS=>{"use strict";Object.defineProperty(hS,"__esModule",{value:!0});hS.RSAPrivateKey=void 0;var ta=(V(),H(F)),Er=ne(),Bce=ZI(),di=class{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}};hS.RSAPrivateKey=di;ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer})],di.prototype,"version",void 0);ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer,converter:Er.AsnIntegerArrayBufferConverter})],di.prototype,"modulus",void 0);ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer,converter:Er.AsnIntegerArrayBufferConverter})],di.prototype,"publicExponent",void 0);ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer,converter:Er.AsnIntegerArrayBufferConverter})],di.prototype,"privateExponent",void 0);ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer,converter:Er.AsnIntegerArrayBufferConverter})],di.prototype,"prime1",void 0);ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer,converter:Er.AsnIntegerArrayBufferConverter})],di.prototype,"prime2",void 0);ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer,converter:Er.AsnIntegerArrayBufferConverter})],di.prototype,"exponent1",void 0);ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer,converter:Er.AsnIntegerArrayBufferConverter})],di.prototype,"exponent2",void 0);ta.__decorate([(0,Er.AsnProp)({type:Er.AsnPropTypes.Integer,converter:Er.AsnIntegerArrayBufferConverter})],di.prototype,"coefficient",void 0);ta.__decorate([(0,Er.AsnProp)({type:Bce.OtherPrimeInfos,optional:!0})],di.prototype,"otherPrimeInfos",void 0)});var qL=v(pS=>{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});pS.RSAPublicKey=void 0;var UL=(V(),H(F)),kp=ne(),jy=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};pS.RSAPublicKey=jy;UL.__decorate([(0,kp.AsnProp)({type:kp.AsnPropTypes.Integer,converter:kp.AsnIntegerArrayBufferConverter})],jy.prototype,"modulus",void 0);UL.__decorate([(0,kp.AsnProp)({type:kp.AsnPropTypes.Integer,converter:kp.AsnIntegerArrayBufferConverter})],jy.prototype,"publicExponent",void 0)});var GI=v(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});var Tp=(V(),H(F));Tp.__exportStar(LL(),xu);Tp.__exportStar(aS(),xu);Tp.__exportStar(Oy(),xu);Tp.__exportStar(ZI(),xu);Tp.__exportStar(DL(),xu);Tp.__exportStar(qL(),xu)});var mS={};$a(mS,{__assign:()=>XI,__asyncDelegator:()=>Zce,__asyncGenerator:()=>Kce,__asyncValues:()=>Gce,__await:()=>zy,__awaiter:()=>Dce,__classPrivateFieldGet:()=>Yce,__classPrivateFieldSet:()=>Qce,__createBinding:()=>qce,__decorate:()=>jce,__exportStar:()=>Hce,__extends:()=>$ce,__generator:()=>Uce,__importDefault:()=>Jce,__importStar:()=>Xce,__makeTemplateObject:()=>Wce,__metadata:()=>Lce,__param:()=>zce,__read:()=>HL,__rest:()=>Mce,__spread:()=>Fce,__spreadArrays:()=>Vce,__values:()=>JI});function $ce(t,e){WI(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Mce(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r}function jce(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i}function zce(t,e){return function(r,n){e(r,n,t)}}function Lce(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Dce(t,e,r,n){function s(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(l){try{u(n.next(l))}catch(d){o(d)}}function c(l){try{u(n.throw(l))}catch(d){o(d)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function Uce(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,s,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,s&&(i=u[0]&2?s.return:u[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,u[1])).done)return i;switch(s=0,i&&(u=[u[0]&2,i.value]),u[0]){case 0:case 1:i=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,s=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){r.label=u[1];break}if(u[0]===6&&r.label<i[1]){r.label=i[1],i=u;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(u);break}i[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],s=0}finally{n=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function qce(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Hce(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function JI(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function HL(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i}function Fce(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(HL(arguments[e]));return t}function Vce(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),s=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)n[s]=i[o];return n}function zy(t){return this instanceof zy?(this.v=t,this):new zy(t)}function Kce(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),s,i=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){n[f]&&(s[f]=function(p){return new Promise(function(m,y){i.push([f,p,m,y])>1||a(f,p)})})}function a(f,p){try{c(n[f](p))}catch(m){d(i[0][3],m)}}function c(f){f.value instanceof zy?Promise.resolve(f.value.v).then(u,l):d(i[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function d(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function Zce(t){var e,r;return e={},n("next"),n("throw",function(s){throw s}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(s,i){e[s]=t[s]?function(o){return(r=!r)?{value:zy(t[s](o)),done:s==="return"}:i?i(o):o}:i}}function Gce(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof JI=="function"?JI(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(u){i({value:u,done:a})},o)}}function Wce(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Xce(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Jce(t){return t&&t.__esModule?t:{default:t}}function Yce(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Qce(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var WI,XI,gS=mr(()=>{WI=function(t,e){return WI=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var s in n)n.hasOwnProperty(s)&&(r[s]=n[s])},WI(t,e)};XI=function(){return XI=Object.assign||function(e){for(var r,n=1,s=arguments.length;n<s;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},XI.apply(this,arguments)}});var e4=v(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});var YI;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(YI||(YI={}));QI.default=YI});var FL=v(t4=>{"use strict";Object.defineProperty(t4,"__esModule",{value:!0});var eue=e4();Object.defineProperty(t4,"Lifecycle",{enumerable:!0,get:function(){return eue.default}})});var Id=v(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.defineInjectionTokenMetadata=no.getParamInfo=no.INJECTION_TOKEN_METADATA_KEY=void 0;no.INJECTION_TOKEN_METADATA_KEY="injectionTokens";function tue(t){let e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata(no.INJECTION_TOKEN_METADATA_KEY,t)||{};return Object.keys(r).forEach(n=>{e[+n]=r[n]}),e}no.getParamInfo=tue;function rue(t,e){return function(r,n,s){let i=Reflect.getOwnMetadata(no.INJECTION_TOKEN_METADATA_KEY,r)||{};i[s]=e?{token:t,transform:e.transformToken,transformArgs:e.args||[]}:t,Reflect.defineMetadata(no.INJECTION_TOKEN_METADATA_KEY,i,r)}}no.defineInjectionTokenMetadata=rue});var r4=v(yS=>{"use strict";Object.defineProperty(yS,"__esModule",{value:!0});yS.isClassProvider=void 0;function nue(t){return!!t.useClass}yS.isClassProvider=nue});var n4=v(xS=>{"use strict";Object.defineProperty(xS,"__esModule",{value:!0});xS.isFactoryProvider=void 0;function sue(t){return!!t.useFactory}xS.isFactoryProvider=sue});var _S=v(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});Ip.delay=Ip.DelayedConstructor=void 0;var bS=class{constructor(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}createProxy(e){let r={},n=!1,s,i=()=>(n||(s=e(this.wrap()),n=!0),s);return new Proxy(r,this.createHandler(i))}createHandler(e){let r={},n=s=>{r[s]=(...i)=>{i[0]=e();let o=Reflect[s];return o(...i)}};return this.reflectMethods.forEach(n),r}};Ip.DelayedConstructor=bS;function iue(t){if(typeof t>"u")throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");return new bS(t)}Ip.delay=iue});var vS=v(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.isConstructorToken=ra.isTransformDescriptor=ra.isTokenDescriptor=ra.isNormalToken=void 0;var oue=_S();function aue(t){return typeof t=="string"||typeof t=="symbol"}ra.isNormalToken=aue;function cue(t){return typeof t=="object"&&"token"in t&&"multiple"in t}ra.isTokenDescriptor=cue;function uue(t){return typeof t=="object"&&"token"in t&&"transform"in t}ra.isTransformDescriptor=uue;function lue(t){return typeof t=="function"||t instanceof oue.DelayedConstructor}ra.isConstructorToken=lue});var s4=v(wS=>{"use strict";Object.defineProperty(wS,"__esModule",{value:!0});wS.isTokenProvider=void 0;function due(t){return!!t.useToken}wS.isTokenProvider=due});var i4=v(SS=>{"use strict";Object.defineProperty(SS,"__esModule",{value:!0});SS.isValueProvider=void 0;function fue(t){return t.useValue!=null}SS.isValueProvider=fue});var o4=v(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var hue=r4();Object.defineProperty(Pd,"isClassProvider",{enumerable:!0,get:function(){return hue.isClassProvider}});var pue=n4();Object.defineProperty(Pd,"isFactoryProvider",{enumerable:!0,get:function(){return pue.isFactoryProvider}});var mue=vS();Object.defineProperty(Pd,"isNormalToken",{enumerable:!0,get:function(){return mue.isNormalToken}});var gue=s4();Object.defineProperty(Pd,"isTokenProvider",{enumerable:!0,get:function(){return gue.isTokenProvider}});var yue=i4();Object.defineProperty(Pd,"isValueProvider",{enumerable:!0,get:function(){return yue.isValueProvider}})});var VL=v(AS=>{"use strict";Object.defineProperty(AS,"__esModule",{value:!0});AS.isProvider=void 0;var xue=r4(),bue=i4(),_ue=s4(),vue=n4();function wue(t){return xue.isClassProvider(t)||bue.isValueProvider(t)||_ue.isTokenProvider(t)||vue.isFactoryProvider(t)}AS.isProvider=wue});var u4=v(c4=>{"use strict";Object.defineProperty(c4,"__esModule",{value:!0});var a4=class{constructor(){this._registryMap=new Map}entries(){return this._registryMap.entries()}getAll(e){return this.ensure(e),this._registryMap.get(e)}get(e){this.ensure(e);let r=this._registryMap.get(e);return r[r.length-1]||null}set(e,r){this.ensure(e),this._registryMap.get(e).push(r)}setAll(e,r){this._registryMap.set(e,r)}has(e){return this.ensure(e),this._registryMap.get(e).length>0}clear(){this._registryMap.clear()}ensure(e){this._registryMap.has(e)||this._registryMap.set(e,[])}};c4.default=a4});var KL=v(d4=>{"use strict";Object.defineProperty(d4,"__esModule",{value:!0});var Sue=u4(),l4=class extends Sue.default{};d4.default=l4});var ZL=v(h4=>{"use strict";Object.defineProperty(h4,"__esModule",{value:!0});var f4=class{constructor(){this.scopedResolutions=new Map}};h4.default=f4});var p4=v(ES=>{"use strict";Object.defineProperty(ES,"__esModule",{value:!0});ES.formatErrorCtor=void 0;function Aue(t,e){return t===null?`at position #${e}`:`"${t.split(",")[e].trim()}" at position #${e}`}function Eue(t,e,r=" "){return[t,...e.message.split(`
|
|
81
|
+
`).map(n=>r+n)].join(`
|
|
82
|
+
`)}function Cue(t,e,r){let[,n=null]=t.toString().match(/constructor\(([\w, ]+)\)/)||[],s=Aue(n,e);return Eue(`Cannot inject the dependency ${s} of "${t.name}" constructor. Reason:`,r)}ES.formatErrorCtor=Cue});var GL=v(CS=>{"use strict";Object.defineProperty(CS,"__esModule",{value:!0});CS.isDisposable=void 0;function kue(t){return!(typeof t.dispose!="function"||t.dispose.length>0)}CS.isDisposable=kue});var XL=v(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});Rd.PostResolutionInterceptors=Rd.PreResolutionInterceptors=void 0;var WL=u4(),kS=class extends WL.default{};Rd.PreResolutionInterceptors=kS;var TS=class extends WL.default{};Rd.PostResolutionInterceptors=TS;var m4=class{constructor(){this.preResolution=new kS,this.postResolution=new TS}};Rd.default=m4});var bu=v(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.instance=Ya.typeInfo=void 0;var Tue=(gS(),H(mS)),bs=o4(),Iue=VL(),IS=vS(),Pue=KL(),$s=e4(),PS=ZL(),Rue=p4(),Oue=_S(),Nue=GL(),Bue=XL();Ya.typeInfo=new Map;var g4=class t{constructor(e){this.parent=e,this._registry=new Pue.default,this.interceptors=new Bue.default,this.disposed=!1,this.disposables=new Set}register(e,r,n={lifecycle:$s.default.Transient}){this.ensureNotDisposed();let s;if(Iue.isProvider(r)?s=r:s={useClass:r},bs.isTokenProvider(s)){let i=[e],o=s;for(;o!=null;){let a=o.useToken;if(i.includes(a))throw new Error(`Token registration cycle detected! ${[...i,a].join(" -> ")}`);i.push(a);let c=this._registry.get(a);c&&bs.isTokenProvider(c.provider)?o=c.provider:o=null}}if((n.lifecycle===$s.default.Singleton||n.lifecycle==$s.default.ContainerScoped||n.lifecycle==$s.default.ResolutionScoped)&&(bs.isValueProvider(s)||bs.isFactoryProvider(s)))throw new Error(`Cannot use lifecycle "${$s.default[n.lifecycle]}" with ValueProviders or FactoryProviders`);return this._registry.set(e,{provider:s,options:n}),this}registerType(e,r){return this.ensureNotDisposed(),bs.isNormalToken(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})}registerInstance(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})}registerSingleton(e,r){if(this.ensureNotDisposed(),bs.isNormalToken(e)){if(bs.isNormalToken(r))return this.register(e,{useToken:r},{lifecycle:$s.default.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:$s.default.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}let n=e;return r&&!bs.isNormalToken(r)&&(n=r),this.register(e,{useClass:n},{lifecycle:$s.default.Singleton})}resolve(e,r=new PS.default,n=!1){this.ensureNotDisposed();let s=this.getRegistration(e);if(!s&&bs.isNormalToken(e)){if(n)return;throw new Error(`Attempted to resolve unregistered dependency token: "${e.toString()}"`)}if(this.executePreResolutionInterceptor(e,"Single"),s){let i=this.resolveRegistration(s,r);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(IS.isConstructorToken(e)){let i=this.construct(e,r);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")}executePreResolutionInterceptor(e,r){if(this.interceptors.preResolution.has(e)){let n=[];for(let s of this.interceptors.preResolution.getAll(e))s.options.frequency!="Once"&&n.push(s),s.callback(e,r);this.interceptors.preResolution.setAll(e,n)}}executePostResolutionInterceptor(e,r,n){if(this.interceptors.postResolution.has(e)){let s=[];for(let i of this.interceptors.postResolution.getAll(e))i.options.frequency!="Once"&&s.push(i),i.callback(e,r,n);this.interceptors.postResolution.setAll(e,s)}}resolveRegistration(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===$s.default.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);let n=e.options.lifecycle===$s.default.Singleton,s=e.options.lifecycle===$s.default.ContainerScoped,i=n||s,o;return bs.isValueProvider(e.provider)?o=e.provider.useValue:bs.isTokenProvider(e.provider)?o=i?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):bs.isClassProvider(e.provider)?o=i?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):bs.isFactoryProvider(e.provider)?o=e.provider.useFactory(this):o=this.construct(e.provider,r),e.options.lifecycle===$s.default.ResolutionScoped&&r.scopedResolutions.set(e,o),o}resolveAll(e,r=new PS.default,n=!1){this.ensureNotDisposed();let s=this.getAllRegistrations(e);if(!s&&bs.isNormalToken(e)){if(n)return[];throw new Error(`Attempted to resolve unregistered dependency token: "${e.toString()}"`)}if(this.executePreResolutionInterceptor(e,"All"),s){let o=s.map(a=>this.resolveRegistration(a,r));return this.executePostResolutionInterceptor(e,o,"All"),o}let i=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,i,"All"),i}isRegistered(e,r=!1){return this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)}reset(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()}clearInstances(){this.ensureNotDisposed();for(let[e,r]of this._registry.entries())this._registry.setAll(e,r.filter(n=>!bs.isValueProvider(n.provider)).map(n=>(n.instance=void 0,n)))}createChildContainer(){this.ensureNotDisposed();let e=new t(this);for(let[r,n]of this._registry.entries())n.some(({options:s})=>s.lifecycle===$s.default.ContainerScoped)&&e._registry.setAll(r,n.map(s=>s.options.lifecycle===$s.default.ContainerScoped?{provider:s.provider,options:s.options}:s));return e}beforeResolution(e,r,n={frequency:"Always"}){this.interceptors.preResolution.set(e,{callback:r,options:n})}afterResolution(e,r,n={frequency:"Always"}){this.interceptors.postResolution.set(e,{callback:r,options:n})}dispose(){return Tue.__awaiter(this,void 0,void 0,function*(){this.disposed=!0;let e=[];this.disposables.forEach(r=>{let n=r.dispose();n&&e.push(n)}),yield Promise.all(e)})}getRegistration(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null}getAllRegistrations(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null}construct(e,r){if(e instanceof Oue.DelayedConstructor)return e.createProxy(s=>this.resolve(s,r));let n=(()=>{let s=Ya.typeInfo.get(e);if(!s||s.length===0){if(e.length===0)return new e;throw new Error(`TypeInfo not known for "${e.name}"`)}let i=s.map(this.resolveParams(r,e));return new e(...i)})();return Nue.isDisposable(n)&&this.disposables.add(n),n}resolveParams(e,r){return(n,s)=>{try{return IS.isTokenDescriptor(n)?IS.isTransformDescriptor(n)?n.multiple?this.resolve(n.transform).transform(this.resolveAll(n.token,new PS.default,n.isOptional),...n.transformArgs):this.resolve(n.transform).transform(this.resolve(n.token,e,n.isOptional),...n.transformArgs):n.multiple?this.resolveAll(n.token,new PS.default,n.isOptional):this.resolve(n.token,e,n.isOptional):IS.isTransformDescriptor(n)?this.resolve(n.transform,e).transform(this.resolve(n.token,e),...n.transformArgs):this.resolve(n,e)}catch(i){throw new Error(Rue.formatErrorCtor(r,s,i))}}}ensureNotDisposed(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")}};Ya.instance=new g4;Ya.default=Ya.instance});var JL=v(x4=>{"use strict";Object.defineProperty(x4,"__esModule",{value:!0});var $ue=Id(),Qa=bu(),y4=vS(),Mue=p4();function jue(){return function(t){let e=$ue.getParamInfo(t);return class extends t{constructor(...r){super(...r.concat(e.slice(r.length).map((n,s)=>{try{return y4.isTokenDescriptor(n)?y4.isTransformDescriptor(n)?n.multiple?Qa.instance.resolve(n.transform).transform(Qa.instance.resolveAll(n.token),...n.transformArgs):Qa.instance.resolve(n.transform).transform(Qa.instance.resolve(n.token),...n.transformArgs):n.multiple?Qa.instance.resolveAll(n.token):Qa.instance.resolve(n.token):y4.isTransformDescriptor(n)?Qa.instance.resolve(n.transform).transform(Qa.instance.resolve(n.token),...n.transformArgs):Qa.instance.resolve(n)}catch(i){let o=s+r.length;throw new Error(Mue.formatErrorCtor(t,o,i))}})))}}}}x4.default=jue});var YL=v(b4=>{"use strict";Object.defineProperty(b4,"__esModule",{value:!0});var zue=Id();function Lue(t,e){let r={token:t,multiple:!1,isOptional:e&&e.isOptional};return zue.defineInjectionTokenMetadata(r)}b4.default=Lue});var RS=v(_4=>{"use strict";Object.defineProperty(_4,"__esModule",{value:!0});var Due=Id(),Uue=bu(),QL=bu();function que(t){return function(e){Uue.typeInfo.set(e,Due.getParamInfo(e)),t&&t.token&&(Array.isArray(t.token)?t.token.forEach(r=>{QL.instance.register(r,e)}):QL.instance.register(t.token,e))}}_4.default=que});var eD=v(v4=>{"use strict";Object.defineProperty(v4,"__esModule",{value:!0});var Hue=(gS(),H(mS)),Fue=bu();function Vue(t=[]){return function(e){return t.forEach(r=>{var{token:n,options:s}=r,i=Hue.__rest(r,["token","options"]);return Fue.instance.register(n,i,s)}),e}}v4.default=Vue});var tD=v(w4=>{"use strict";Object.defineProperty(w4,"__esModule",{value:!0});var Kue=RS(),Zue=bu();function Gue(){return function(t){Kue.default()(t),Zue.instance.registerSingleton(t)}}w4.default=Gue});var rD=v(S4=>{"use strict";Object.defineProperty(S4,"__esModule",{value:!0});var Wue=Id();function Xue(t,e){let r={token:t,multiple:!0,isOptional:e&&e.isOptional};return Wue.defineInjectionTokenMetadata(r)}S4.default=Xue});var nD=v(A4=>{"use strict";Object.defineProperty(A4,"__esModule",{value:!0});var Jue=Id();function Yue(t,e,...r){let n={token:t,multiple:!0,transform:e,transformArgs:r};return Jue.defineInjectionTokenMetadata(n)}A4.default=Yue});var sD=v(E4=>{"use strict";Object.defineProperty(E4,"__esModule",{value:!0});var Que=Id();function ele(t,e,...r){return Que.defineInjectionTokenMetadata(t,{transformToken:e,args:r})}E4.default=ele});var iD=v(C4=>{"use strict";Object.defineProperty(C4,"__esModule",{value:!0});var tle=RS(),rle=bu();function nle(t,e){return function(r){tle.default()(r),rle.instance.register(e||r,r,{lifecycle:t})}}C4.default=nle});var oD=v(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});var sle=JL();Object.defineProperty(so,"autoInjectable",{enumerable:!0,get:function(){return sle.default}});var ile=YL();Object.defineProperty(so,"inject",{enumerable:!0,get:function(){return ile.default}});var ole=RS();Object.defineProperty(so,"injectable",{enumerable:!0,get:function(){return ole.default}});var ale=eD();Object.defineProperty(so,"registry",{enumerable:!0,get:function(){return ale.default}});var cle=tD();Object.defineProperty(so,"singleton",{enumerable:!0,get:function(){return cle.default}});var ule=rD();Object.defineProperty(so,"injectAll",{enumerable:!0,get:function(){return ule.default}});var lle=nD();Object.defineProperty(so,"injectAllWithTransform",{enumerable:!0,get:function(){return lle.default}});var dle=sD();Object.defineProperty(so,"injectWithTransform",{enumerable:!0,get:function(){return dle.default}});var fle=iD();Object.defineProperty(so,"scoped",{enumerable:!0,get:function(){return fle.default}})});var aD=v(k4=>{"use strict";Object.defineProperty(k4,"__esModule",{value:!0});function hle(t){let e;return r=>(e==null&&(e=t(r)),e)}k4.default=hle});var cD=v(T4=>{"use strict";Object.defineProperty(T4,"__esModule",{value:!0});function ple(t){let e=new WeakMap;return r=>{let n=e.get(r);return n==null&&(n=t(r),e.set(r,n)),n}}T4.default=ple});var uD=v(I4=>{"use strict";Object.defineProperty(I4,"__esModule",{value:!0});function mle(t,e,r,n=!0){let s,i;return o=>{let a=t(o);return(!n||i!==a)&&((i=a)?s=o.resolve(e):s=o.resolve(r)),s}}I4.default=mle});var lD=v(Ly=>{"use strict";Object.defineProperty(Ly,"__esModule",{value:!0});var gle=aD();Object.defineProperty(Ly,"instanceCachingFactory",{enumerable:!0,get:function(){return gle.default}});var yle=cD();Object.defineProperty(Ly,"instancePerContainerCachingFactory",{enumerable:!0,get:function(){return yle.default}});var xle=uD();Object.defineProperty(Ly,"predicateAwareClassFactory",{enumerable:!0,get:function(){return xle.default}})});var dD=v(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var P4=(gS(),H(mS));if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var ble=FL();Object.defineProperty(_u,"Lifecycle",{enumerable:!0,get:function(){return ble.Lifecycle}});P4.__exportStar(oD(),_u);P4.__exportStar(lD(),_u);P4.__exportStar(o4(),_u);var _le=_S();Object.defineProperty(_u,"delay",{enumerable:!0,get:function(){return _le.delay}});var vle=bu();Object.defineProperty(_u,"container",{enumerable:!0,get:function(){return vle.instance}})});var B4=v(Nd=>{"use strict";var R4;Object.defineProperty(Nd,"__esModule",{value:!0});Nd.PKCS12AttrSet=Nd.PKCS12Attribute=void 0;var N4=(V(),H(F)),Od=ne(),Pp=class{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}};Nd.PKCS12Attribute=Pp;N4.__decorate([(0,Od.AsnProp)({type:Od.AsnPropTypes.ObjectIdentifier})],Pp.prototype,"attrId",void 0);N4.__decorate([(0,Od.AsnProp)({type:Od.AsnPropTypes.Any,repeated:"set"})],Pp.prototype,"attrValues",void 0);var O4=R4=class extends Od.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,R4.prototype)}};Nd.PKCS12AttrSet=O4;Nd.PKCS12AttrSet=O4=R4=N4.__decorate([(0,Od.AsnType)({type:Od.AsnTypeTypes.Sequence,itemType:Pp})],O4)});var fD=v(Dy=>{"use strict";var $4;Object.defineProperty(Dy,"__esModule",{value:!0});Dy.AuthenticatedSafe=void 0;var wle=(V(),H(F)),M4=ne(),Sle=ky(),j4=$4=class extends M4.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,$4.prototype)}};Dy.AuthenticatedSafe=j4;Dy.AuthenticatedSafe=j4=$4=wle.__decorate([(0,M4.AsnType)({type:M4.AsnTypeTypes.Sequence,itemType:Sle.ContentInfo})],j4)});var z4=v(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.id_bagtypes=er.id_pbewithSHAAnd40BitRC2_CBC=er.id_pbeWithSHAAnd128BitRC2_CBC=er.id_pbeWithSHAAnd2_KeyTripleDES_CBC=er.id_pbeWithSHAAnd3_KeyTripleDES_CBC=er.id_pbeWithSHAAnd40BitRC4=er.id_pbeWithSHAAnd128BitRC4=er.id_pkcs_12PbeIds=er.id_pkcs_12=er.id_pkcs=er.id_rsadsi=void 0;er.id_rsadsi="1.2.840.113549";er.id_pkcs=`${er.id_rsadsi}.1`;er.id_pkcs_12=`${er.id_pkcs}.12`;er.id_pkcs_12PbeIds=`${er.id_pkcs_12}.1`;er.id_pbeWithSHAAnd128BitRC4=`${er.id_pkcs_12PbeIds}.1`;er.id_pbeWithSHAAnd40BitRC4=`${er.id_pkcs_12PbeIds}.2`;er.id_pbeWithSHAAnd3_KeyTripleDES_CBC=`${er.id_pkcs_12PbeIds}.3`;er.id_pbeWithSHAAnd2_KeyTripleDES_CBC=`${er.id_pkcs_12PbeIds}.4`;er.id_pbeWithSHAAnd128BitRC2_CBC=`${er.id_pkcs_12PbeIds}.5`;er.id_pbewithSHAAnd40BitRC2_CBC=`${er.id_pkcs_12PbeIds}.6`;er.id_bagtypes=`${er.id_pkcs_12}.10.1`});var OS=v(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.id_pkcs_9=as.id_SafeContents=as.id_SecretBag=as.id_CRLBag=as.id_certBag=as.id_pkcs8ShroudedKeyBag=as.id_keyBag=void 0;var Rp=z4();as.id_keyBag=`${Rp.id_bagtypes}.1`;as.id_pkcs8ShroudedKeyBag=`${Rp.id_bagtypes}.2`;as.id_certBag=`${Rp.id_bagtypes}.3`;as.id_CRLBag=`${Rp.id_bagtypes}.4`;as.id_SecretBag=`${Rp.id_bagtypes}.5`;as.id_SafeContents=`${Rp.id_bagtypes}.6`;as.id_pkcs_9="1.2.840.113549.1.9"});var pD=v(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.id_sdsiCertificate=Oi.id_x509Certificate=Oi.id_certTypes=Oi.CertBag=void 0;var hD=(V(),H(F)),NS=ne(),Ale=OS(),Uy=class{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};Oi.CertBag=Uy;hD.__decorate([(0,NS.AsnProp)({type:NS.AsnPropTypes.ObjectIdentifier})],Uy.prototype,"certId",void 0);hD.__decorate([(0,NS.AsnProp)({type:NS.AsnPropTypes.Any,context:0})],Uy.prototype,"certValue",void 0);Oi.id_certTypes=`${Ale.id_pkcs_9}.22`;Oi.id_x509Certificate=`${Oi.id_certTypes}.1`;Oi.id_sdsiCertificate=`${Oi.id_certTypes}.2`});var gD=v(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.id_x509CRL=ec.id_crlTypes=ec.CRLBag=void 0;var mD=(V(),H(F)),BS=ne(),Ele=OS(),qy=class{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};ec.CRLBag=qy;mD.__decorate([(0,BS.AsnProp)({type:BS.AsnPropTypes.ObjectIdentifier})],qy.prototype,"crlId",void 0);mD.__decorate([(0,BS.AsnProp)({type:BS.AsnPropTypes.Any,context:0})],qy.prototype,"crltValue",void 0);ec.id_crlTypes=`${Ele.id_pkcs_9}.23`;ec.id_x509CRL=`${ec.id_crlTypes}.1`});var bD=v(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});Op.EncryptedPrivateKeyInfo=Op.EncryptedData=void 0;var yD=(V(),H(F)),L4=ne(),xD=Yt(),Hy=class extends L4.OctetString{};Op.EncryptedData=Hy;var Fy=class{encryptionAlgorithm=new xD.AlgorithmIdentifier;encryptedData=new Hy;constructor(e={}){Object.assign(this,e)}};Op.EncryptedPrivateKeyInfo=Fy;yD.__decorate([(0,L4.AsnProp)({type:xD.AlgorithmIdentifier})],Fy.prototype,"encryptionAlgorithm",void 0);yD.__decorate([(0,L4.AsnProp)({type:Hy})],Fy.prototype,"encryptedData",void 0)});var _D=v(io=>{"use strict";var D4;Object.defineProperty(io,"__esModule",{value:!0});io.PrivateKeyInfo=io.Attributes=io.PrivateKey=io.Version=void 0;var Ky=(V(),H(F)),tc=ne(),q4=Yt(),U4;(function(t){t[t.v1=0]="v1"})(U4||(io.Version=U4={}));var Vy=class extends tc.OctetString{};io.PrivateKey=Vy;var $S=D4=class extends tc.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,D4.prototype)}};io.Attributes=$S;io.Attributes=$S=D4=Ky.__decorate([(0,tc.AsnType)({type:tc.AsnTypeTypes.Sequence,itemType:q4.Attribute})],$S);var Bd=class{version=U4.v1;privateKeyAlgorithm=new q4.AlgorithmIdentifier;privateKey=new Vy;attributes;constructor(e={}){Object.assign(this,e)}};io.PrivateKeyInfo=Bd;Ky.__decorate([(0,tc.AsnProp)({type:tc.AsnPropTypes.Integer})],Bd.prototype,"version",void 0);Ky.__decorate([(0,tc.AsnProp)({type:q4.AlgorithmIdentifier})],Bd.prototype,"privateKeyAlgorithm",void 0);Ky.__decorate([(0,tc.AsnProp)({type:Vy})],Bd.prototype,"privateKey",void 0);Ky.__decorate([(0,tc.AsnProp)({type:$S,implicit:!0,context:0,optional:!0})],Bd.prototype,"attributes",void 0)});var jS=v(MS=>{"use strict";Object.defineProperty(MS,"__esModule",{value:!0});var vD=(V(),H(F));vD.__exportStar(bD(),MS);vD.__exportStar(_D(),MS)});var SD=v(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});Zy.KeyBag=void 0;var Cle=(V(),H(F)),kle=jS(),wD=ne(),H4=class extends kle.PrivateKeyInfo{};Zy.KeyBag=H4;Zy.KeyBag=H4=Cle.__decorate([(0,wD.AsnType)({type:wD.AsnTypeTypes.Sequence})],H4)});var ED=v(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});Gy.PKCS8ShroudedKeyBag=void 0;var Tle=(V(),H(F)),Ile=jS(),AD=ne(),F4=class extends Ile.EncryptedPrivateKeyInfo{};Gy.PKCS8ShroudedKeyBag=F4;Gy.PKCS8ShroudedKeyBag=F4=Tle.__decorate([(0,AD.AsnType)({type:AD.AsnTypeTypes.Sequence})],F4)});var kD=v(LS=>{"use strict";Object.defineProperty(LS,"__esModule",{value:!0});LS.SecretBag=void 0;var CD=(V(),H(F)),zS=ne(),Wy=class{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};LS.SecretBag=Wy;CD.__decorate([(0,zS.AsnProp)({type:zS.AsnPropTypes.ObjectIdentifier})],Wy.prototype,"secretTypeId",void 0);CD.__decorate([(0,zS.AsnProp)({type:zS.AsnPropTypes.Any,context:0})],Wy.prototype,"secretValue",void 0)});var TD=v(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});var Np=(V(),H(F));Np.__exportStar(pD(),vu);Np.__exportStar(gD(),vu);Np.__exportStar(SD(),vu);Np.__exportStar(ED(),vu);Np.__exportStar(kD(),vu);Np.__exportStar(OS(),vu)});var K4=v(DS=>{"use strict";Object.defineProperty(DS,"__esModule",{value:!0});DS.MacData=void 0;var V4=(V(),H(F)),ID=GI(),Bp=ne(),$p=class{mac=new ID.DigestInfo;macSalt=new Bp.OctetString;iterations=1;constructor(e={}){Object.assign(this,e)}};DS.MacData=$p;V4.__decorate([(0,Bp.AsnProp)({type:ID.DigestInfo})],$p.prototype,"mac",void 0);V4.__decorate([(0,Bp.AsnProp)({type:Bp.OctetString})],$p.prototype,"macSalt",void 0);V4.__decorate([(0,Bp.AsnProp)({type:Bp.AsnPropTypes.Integer,defaultValue:1})],$p.prototype,"iterations",void 0)});var OD=v(qS=>{"use strict";Object.defineProperty(qS,"__esModule",{value:!0});qS.PFX=void 0;var Z4=(V(),H(F)),US=ne(),PD=ky(),RD=K4(),Mp=class{version=3;authSafe=new PD.ContentInfo;macData=new RD.MacData;constructor(e={}){Object.assign(this,e)}};qS.PFX=Mp;Z4.__decorate([(0,US.AsnProp)({type:US.AsnPropTypes.Integer})],Mp.prototype,"version",void 0);Z4.__decorate([(0,US.AsnProp)({type:PD.ContentInfo})],Mp.prototype,"authSafe",void 0);Z4.__decorate([(0,US.AsnProp)({type:RD.MacData,optional:!0})],Mp.prototype,"macData",void 0)});var ND=v(Md=>{"use strict";var G4;Object.defineProperty(Md,"__esModule",{value:!0});Md.SafeContents=Md.SafeBag=void 0;var HS=(V(),H(F)),wu=ne(),Ple=B4(),$d=class{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};Md.SafeBag=$d;HS.__decorate([(0,wu.AsnProp)({type:wu.AsnPropTypes.ObjectIdentifier})],$d.prototype,"bagId",void 0);HS.__decorate([(0,wu.AsnProp)({type:wu.AsnPropTypes.Any,context:0})],$d.prototype,"bagValue",void 0);HS.__decorate([(0,wu.AsnProp)({type:Ple.PKCS12Attribute,repeated:"set",optional:!0})],$d.prototype,"bagAttributes",void 0);var W4=G4=class extends wu.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,G4.prototype)}};Md.SafeContents=W4;Md.SafeContents=W4=G4=HS.__decorate([(0,wu.AsnType)({type:wu.AsnTypeTypes.Sequence,itemType:$d})],W4)});var BD=v(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var jd=(V(),H(F));jd.__exportStar(B4(),rc);jd.__exportStar(fD(),rc);jd.__exportStar(TD(),rc);jd.__exportStar(K4(),rc);jd.__exportStar(z4(),rc);jd.__exportStar(OD(),rc);jd.__exportStar(ND(),rc)});var $D=v(T=>{"use strict";var X4,J4,Y4;Object.defineProperty(T,"__esModule",{value:!0});T.DateOfBirth=T.UnstructuredAddress=T.UnstructuredName=T.EmailAddress=T.EncryptedPrivateKeyInfo=T.UserPKCS12=T.Pkcs7PDU=T.PKCS9String=T.id_at_pseudonym=T.crlTypes=T.id_certTypes=T.id_smime=T.id_pkcs9_mr_signingTimeMatch=T.id_pkcs9_mr_caseIgnoreMatch=T.id_pkcs9_sx_signingTime=T.id_pkcs9_sx_pkcs9String=T.id_pkcs9_at_countryOfResidence=T.id_pkcs9_at_countryOfCitizenship=T.id_pkcs9_at_gender=T.id_pkcs9_at_placeOfBirth=T.id_pkcs9_at_dateOfBirth=T.id_ietf_at=T.id_pkcs9_at_pkcs7PDU=T.id_pkcs9_at_sequenceNumber=T.id_pkcs9_at_randomNonce=T.id_pkcs9_at_encryptedPrivateKeyInfo=T.id_pkcs9_at_pkcs15Token=T.id_pkcs9_at_userPKCS12=T.id_pkcs9_at_localKeyId=T.id_pkcs9_at_friendlyName=T.id_pkcs9_at_smimeCapabilities=T.id_pkcs9_at_extensionRequest=T.id_pkcs9_at_signingDescription=T.id_pkcs9_at_extendedCertificateAttributes=T.id_pkcs9_at_unstructuredAddress=T.id_pkcs9_at_challengePassword=T.id_pkcs9_at_counterSignature=T.id_pkcs9_at_signingTime=T.id_pkcs9_at_messageDigest=T.id_pkcs9_at_contentType=T.id_pkcs9_at_unstructuredName=T.id_pkcs9_at_emailAddress=T.id_pkcs9_oc_naturalPerson=T.id_pkcs9_oc_pkcsEntity=T.id_pkcs9_mr=T.id_pkcs9_sx=T.id_pkcs9_at=T.id_pkcs9_oc=T.id_pkcs9_mo=T.id_pkcs9=void 0;T.SMIMECapabilities=T.SMIMECapability=T.SigningDescription=T.LocalKeyId=T.FriendlyName=T.ExtendedCertificateAttributes=T.ExtensionRequest=T.ChallengePassword=T.CounterSignature=T.SequenceNumber=T.RandomNonce=T.SigningTime=T.MessageDigest=T.ContentType=T.Pseudonym=T.CountryOfResidence=T.CountryOfCitizenship=T.Gender=T.PlaceOfBirth=void 0;var Vt=(V(),H(F)),je=ne(),y3=Vt.__importStar(ky()),Rle=Vt.__importStar(BD()),Ole=Vt.__importStar(jS()),nc=Vt.__importStar(Yt()),Nle=Vt.__importStar(fI());T.id_pkcs9="1.2.840.113549.1.9";T.id_pkcs9_mo=`${T.id_pkcs9}.0`;T.id_pkcs9_oc=`${T.id_pkcs9}.24`;T.id_pkcs9_at=`${T.id_pkcs9}.25`;T.id_pkcs9_sx=`${T.id_pkcs9}.26`;T.id_pkcs9_mr=`${T.id_pkcs9}.27`;T.id_pkcs9_oc_pkcsEntity=`${T.id_pkcs9_oc}.1`;T.id_pkcs9_oc_naturalPerson=`${T.id_pkcs9_oc}.2`;T.id_pkcs9_at_emailAddress=`${T.id_pkcs9}.1`;T.id_pkcs9_at_unstructuredName=`${T.id_pkcs9}.2`;T.id_pkcs9_at_contentType=`${T.id_pkcs9}.3`;T.id_pkcs9_at_messageDigest=`${T.id_pkcs9}.4`;T.id_pkcs9_at_signingTime=`${T.id_pkcs9}.5`;T.id_pkcs9_at_counterSignature=`${T.id_pkcs9}.6`;T.id_pkcs9_at_challengePassword=`${T.id_pkcs9}.7`;T.id_pkcs9_at_unstructuredAddress=`${T.id_pkcs9}.8`;T.id_pkcs9_at_extendedCertificateAttributes=`${T.id_pkcs9}.9`;T.id_pkcs9_at_signingDescription=`${T.id_pkcs9}.13`;T.id_pkcs9_at_extensionRequest=`${T.id_pkcs9}.14`;T.id_pkcs9_at_smimeCapabilities=`${T.id_pkcs9}.15`;T.id_pkcs9_at_friendlyName=`${T.id_pkcs9}.20`;T.id_pkcs9_at_localKeyId=`${T.id_pkcs9}.21`;T.id_pkcs9_at_userPKCS12="2.16.840.1.113730.3.1.216";T.id_pkcs9_at_pkcs15Token=`${T.id_pkcs9_at}.1`;T.id_pkcs9_at_encryptedPrivateKeyInfo=`${T.id_pkcs9_at}.2`;T.id_pkcs9_at_randomNonce=`${T.id_pkcs9_at}.3`;T.id_pkcs9_at_sequenceNumber=`${T.id_pkcs9_at}.4`;T.id_pkcs9_at_pkcs7PDU=`${T.id_pkcs9_at}.5`;T.id_ietf_at="1.3.6.1.5.5.7.9";T.id_pkcs9_at_dateOfBirth=`${T.id_ietf_at}.1`;T.id_pkcs9_at_placeOfBirth=`${T.id_ietf_at}.2`;T.id_pkcs9_at_gender=`${T.id_ietf_at}.3`;T.id_pkcs9_at_countryOfCitizenship=`${T.id_ietf_at}.4`;T.id_pkcs9_at_countryOfResidence=`${T.id_ietf_at}.5`;T.id_pkcs9_sx_pkcs9String=`${T.id_pkcs9_sx}.1`;T.id_pkcs9_sx_signingTime=`${T.id_pkcs9_sx}.2`;T.id_pkcs9_mr_caseIgnoreMatch=`${T.id_pkcs9_mr}.1`;T.id_pkcs9_mr_signingTimeMatch=`${T.id_pkcs9_mr}.2`;T.id_smime=`${T.id_pkcs9}.16`;T.id_certTypes=`${T.id_pkcs9}.22`;T.crlTypes=`${T.id_pkcs9}.23`;T.id_at_pseudonym=`${Nle.id_at}.65`;var Xy=class extends nc.DirectoryString{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};T.PKCS9String=Xy;Vt.__decorate([(0,je.AsnProp)({type:je.AsnPropTypes.IA5String})],Xy.prototype,"ia5String",void 0);T.PKCS9String=Xy=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],Xy);var Q4=class extends y3.ContentInfo{};T.Pkcs7PDU=Q4;T.Pkcs7PDU=Q4=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Sequence})],Q4);var e3=class extends Rle.PFX{};T.UserPKCS12=e3;T.UserPKCS12=e3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Sequence})],e3);var t3=class extends Ole.EncryptedPrivateKeyInfo{};T.EncryptedPrivateKeyInfo=t3;T.EncryptedPrivateKeyInfo=t3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Sequence})],t3);var FS=class{value;constructor(e=""){this.value=e}toString(){return this.value}};T.EmailAddress=FS;Vt.__decorate([(0,je.AsnProp)({type:je.AsnPropTypes.IA5String})],FS.prototype,"value",void 0);T.EmailAddress=FS=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],FS);var r3=class extends Xy{};T.UnstructuredName=r3;T.UnstructuredName=r3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],r3);var n3=class extends nc.DirectoryString{};T.UnstructuredAddress=n3;T.UnstructuredAddress=n3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],n3);var VS=class{value;constructor(e=new Date){this.value=e}};T.DateOfBirth=VS;Vt.__decorate([(0,je.AsnProp)({type:je.AsnPropTypes.GeneralizedTime})],VS.prototype,"value",void 0);T.DateOfBirth=VS=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],VS);var s3=class extends nc.DirectoryString{};T.PlaceOfBirth=s3;T.PlaceOfBirth=s3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],s3);var KS=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};T.Gender=KS;Vt.__decorate([(0,je.AsnProp)({type:je.AsnPropTypes.PrintableString})],KS.prototype,"value",void 0);T.Gender=KS=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],KS);var Jy=class{value;constructor(e=""){this.value=e}toString(){return this.value}};T.CountryOfCitizenship=Jy;Vt.__decorate([(0,je.AsnProp)({type:je.AsnPropTypes.PrintableString})],Jy.prototype,"value",void 0);T.CountryOfCitizenship=Jy=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],Jy);var i3=class extends Jy{};T.CountryOfResidence=i3;T.CountryOfResidence=i3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],i3);var o3=class extends nc.DirectoryString{};T.Pseudonym=o3;T.Pseudonym=o3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],o3);var ZS=class{value;constructor(e=""){this.value=e}toString(){return this.value}};T.ContentType=ZS;Vt.__decorate([(0,je.AsnProp)({type:je.AsnPropTypes.ObjectIdentifier})],ZS.prototype,"value",void 0);T.ContentType=ZS=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],ZS);var a3=class extends je.OctetString{};T.MessageDigest=a3;var c3=class extends nc.Time{};T.SigningTime=c3;T.SigningTime=c3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],c3);var u3=class extends je.OctetString{};T.RandomNonce=u3;var GS=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};T.SequenceNumber=GS;Vt.__decorate([(0,je.AsnProp)({type:je.AsnPropTypes.Integer})],GS.prototype,"value",void 0);T.SequenceNumber=GS=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],GS);var l3=class extends y3.SignerInfo{};T.CounterSignature=l3;T.CounterSignature=l3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Sequence})],l3);var d3=class extends nc.DirectoryString{};T.ChallengePassword=d3;T.ChallengePassword=d3=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],d3);var f3=X4=class extends nc.Extensions{constructor(e){super(e),Object.setPrototypeOf(this,X4.prototype)}};T.ExtensionRequest=f3;T.ExtensionRequest=f3=X4=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Sequence})],f3);var h3=J4=class extends je.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,J4.prototype)}};T.ExtendedCertificateAttributes=h3;T.ExtendedCertificateAttributes=h3=J4=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Set,itemType:y3.Attribute})],h3);var WS=class{value;constructor(e=""){this.value=e}toString(){return this.value}};T.FriendlyName=WS;Vt.__decorate([(0,je.AsnProp)({type:je.AsnPropTypes.BmpString})],WS.prototype,"value",void 0);T.FriendlyName=WS=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Choice})],WS);var p3=class extends je.OctetString{};T.LocalKeyId=p3;var m3=class extends nc.DirectoryString{};T.SigningDescription=m3;var XS=class extends nc.AlgorithmIdentifier{};T.SMIMECapability=XS;T.SMIMECapability=XS=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Sequence})],XS);var g3=Y4=class extends je.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,Y4.prototype)}};T.SMIMECapabilities=g3;T.SMIMECapabilities=g3=Y4=Vt.__decorate([(0,je.AsnType)({type:je.AsnTypeTypes.Sequence,itemType:XS})],g3)});var v3=v(Yy=>{"use strict";var x3;Object.defineProperty(Yy,"__esModule",{value:!0});Yy.Attributes=void 0;var Ble=(V(),H(F)),b3=ne(),$le=Yt(),_3=x3=class extends b3.AsnArray{constructor(e){super(e),Object.setPrototypeOf(this,x3.prototype)}};Yy.Attributes=_3;Yy.Attributes=_3=x3=Ble.__decorate([(0,b3.AsnType)({type:b3.AsnTypeTypes.Sequence,itemType:$le.Attribute})],_3)});var w3=v(QS=>{"use strict";Object.defineProperty(QS,"__esModule",{value:!0});QS.CertificationRequestInfo=void 0;var YS=(V(),H(F)),Qy=ne(),JS=Yt(),MD=v3(),zd=class{version=0;subject=new JS.Name;subjectPKInfo=new JS.SubjectPublicKeyInfo;attributes=new MD.Attributes;constructor(e={}){Object.assign(this,e)}};QS.CertificationRequestInfo=zd;YS.__decorate([(0,Qy.AsnProp)({type:Qy.AsnPropTypes.Integer})],zd.prototype,"version",void 0);YS.__decorate([(0,Qy.AsnProp)({type:JS.Name})],zd.prototype,"subject",void 0);YS.__decorate([(0,Qy.AsnProp)({type:JS.SubjectPublicKeyInfo})],zd.prototype,"subjectPKInfo",void 0);YS.__decorate([(0,Qy.AsnProp)({type:MD.Attributes,implicit:!0,context:0,optional:!0})],zd.prototype,"attributes",void 0)});var LD=v(t2=>{"use strict";Object.defineProperty(t2,"__esModule",{value:!0});t2.CertificationRequest=void 0;var S3=(V(),H(F)),e2=ne(),jD=Yt(),zD=w3(),jp=class{certificationRequestInfo=new zD.CertificationRequestInfo;certificationRequestInfoRaw;signatureAlgorithm=new jD.AlgorithmIdentifier;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};t2.CertificationRequest=jp;S3.__decorate([(0,e2.AsnProp)({type:zD.CertificationRequestInfo,raw:!0})],jp.prototype,"certificationRequestInfo",void 0);S3.__decorate([(0,e2.AsnProp)({type:jD.AlgorithmIdentifier})],jp.prototype,"signatureAlgorithm",void 0);S3.__decorate([(0,e2.AsnProp)({type:e2.AsnPropTypes.BitString})],jp.prototype,"signature",void 0)});var DD=v(ex=>{"use strict";Object.defineProperty(ex,"__esModule",{value:!0});var A3=(V(),H(F));A3.__exportStar(v3(),ex);A3.__exportStar(LD(),ex);A3.__exportStar(w3(),ex)});var AU=v(xe=>{"use strict";t7();var te=ne(),He=Yt(),le=jk(),re=(V(),H(F)),Mle=ky(),m2=RL(),js=GI(),kr=dD(),R3=$D(),g2=DD();function Hx(t){var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var ee=Hx(He),Ms=Hx(Mle),Lr=Hx(m2),Cr=Hx(js),Vp=Hx(R3),Xp="crypto.algorithm",y2=class{getAlgorithms(){return kr.container.resolveAll(Xp)}toAsnAlgorithm(e){({...e});for(let r of this.getAlgorithms()){let n=r.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){let r=new He.AlgorithmIdentifier({algorithm:e.name});if("parameters"in e){let n=e;r.parameters=n.parameters}return r}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let n of this.getAlgorithms()){let s=n.toWebAlgorithm(e);if(s)return s}return{name:e.algorithm,parameters:e.parameters}}},co="crypto.algorithmProvider";kr.container.registerSingleton(co,y2);var s2,Us="1.3.36.3.3.2.8.1.1",UD=`${Us}.1`,qD=`${Us}.2`,HD=`${Us}.3`,FD=`${Us}.4`,VD=`${Us}.5`,KD=`${Us}.6`,ZD=`${Us}.7`,GD=`${Us}.8`,WD=`${Us}.9`,XD=`${Us}.10`,JD=`${Us}.11`,YD=`${Us}.12`,QD=`${Us}.13`,eU=`${Us}.14`,tU="brainpoolP160r1",rU="brainpoolP160t1",nU="brainpoolP192r1",sU="brainpoolP192t1",iU="brainpoolP224r1",oU="brainpoolP224t1",aU="brainpoolP256r1",cU="brainpoolP256t1",uU="brainpoolP320r1",lU="brainpoolP320t1",dU="brainpoolP384r1",fU="brainpoolP384t1",hU="brainpoolP512r1",pU="brainpoolP512t1",en="ECDSA";xe.EcAlgorithm=s2=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case en.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Lr.ecdsaWithSHA1;case"sha-256":return Lr.ecdsaWithSHA256;case"sha-384":return Lr.ecdsaWithSHA384;case"sha-512":return Lr.ecdsaWithSHA512}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=Lr.id_secp256r1;break;case"K-256":r=s2.SECP256K1;break;case"P-384":r=Lr.id_secp384r1;break;case"P-521":r=Lr.id_secp521r1;break;case tU:r=UD;break;case rU:r=qD;break;case nU:r=HD;break;case sU:r=FD;break;case iU:r=VD;break;case oU:r=KD;break;case aU:r=ZD;break;case cU:r=GD;break;case uU:r=WD;break;case lU:r=XD;break;case dU:r=JD;break;case fU:r=YD;break;case hU:r=QD;break;case pU:r=eU;break}if(r)return new He.AlgorithmIdentifier({algorithm:Lr.id_ecPublicKey,parameters:te.AsnConvert.serialize(new Lr.ECParameters({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Lr.id_ecdsaWithSHA1:return{name:en,hash:{name:"SHA-1"}};case Lr.id_ecdsaWithSHA256:return{name:en,hash:{name:"SHA-256"}};case Lr.id_ecdsaWithSHA384:return{name:en,hash:{name:"SHA-384"}};case Lr.id_ecdsaWithSHA512:return{name:en,hash:{name:"SHA-512"}};case Lr.id_ecPublicKey:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(te.AsnConvert.parse(e.parameters,Lr.ECParameters).namedCurve){case Lr.id_secp256r1:return{name:en,namedCurve:"P-256"};case s2.SECP256K1:return{name:en,namedCurve:"K-256"};case Lr.id_secp384r1:return{name:en,namedCurve:"P-384"};case Lr.id_secp521r1:return{name:en,namedCurve:"P-521"};case UD:return{name:en,namedCurve:tU};case qD:return{name:en,namedCurve:rU};case HD:return{name:en,namedCurve:nU};case FD:return{name:en,namedCurve:sU};case VD:return{name:en,namedCurve:iU};case KD:return{name:en,namedCurve:oU};case ZD:return{name:en,namedCurve:aU};case GD:return{name:en,namedCurve:cU};case WD:return{name:en,namedCurve:uU};case XD:return{name:en,namedCurve:lU};case JD:return{name:en,namedCurve:dU};case YD:return{name:en,namedCurve:fU};case QD:return{name:en,namedCurve:hU};case eU:return{name:en,namedCurve:pU}}}}return null}};xe.EcAlgorithm.SECP256K1="1.3.132.0.10";xe.EcAlgorithm=s2=re.__decorate([kr.injectable()],xe.EcAlgorithm);kr.container.registerSingleton(Xp,xe.EcAlgorithm);var _U=Symbol("name"),vU=Symbol("value"),Dt=class{constructor(e,r={},n=""){this[_U]=e,this[vU]=n;for(let s in r)this[s]=r[s]}};Dt.NAME=_U;Dt.VALUE=vU;var x2=class{static toTextObject(e){let r=new Dt("Algorithm Identifier",{},Ni.toString(e.algorithm));if(e.parameters)if(e.algorithm===Lr.id_ecPublicKey){let n=new xe.EcAlgorithm().toWebAlgorithm(e);n&&"namedCurve"in n?r["Named Curve"]=n.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}},Ni=class{static toString(e){let r=this.items[e];return r||e}};Ni.items={[Cr.id_sha1]:"sha1",[Cr.id_sha224]:"sha224",[Cr.id_sha256]:"sha256",[Cr.id_sha384]:"sha384",[Cr.id_sha512]:"sha512",[Cr.id_rsaEncryption]:"rsaEncryption",[Cr.id_sha1WithRSAEncryption]:"sha1WithRSAEncryption",[Cr.id_sha224WithRSAEncryption]:"sha224WithRSAEncryption",[Cr.id_sha256WithRSAEncryption]:"sha256WithRSAEncryption",[Cr.id_sha384WithRSAEncryption]:"sha384WithRSAEncryption",[Cr.id_sha512WithRSAEncryption]:"sha512WithRSAEncryption",[Lr.id_ecPublicKey]:"ecPublicKey",[Lr.id_ecdsaWithSHA1]:"ecdsaWithSHA1",[Lr.id_ecdsaWithSHA224]:"ecdsaWithSHA224",[Lr.id_ecdsaWithSHA256]:"ecdsaWithSHA256",[Lr.id_ecdsaWithSHA384]:"ecdsaWithSHA384",[Lr.id_ecdsaWithSHA512]:"ecdsaWithSHA512",[ee.id_kp_serverAuth]:"TLS WWW server authentication",[ee.id_kp_clientAuth]:"TLS WWW client authentication",[ee.id_kp_codeSigning]:"Code Signing",[ee.id_kp_emailProtection]:"E-mail Protection",[ee.id_kp_timeStamping]:"Time Stamping",[ee.id_kp_OCSPSigning]:"OCSP Signing",[Ms.id_signedData]:"Signed Data"};var uo=class{static serialize(e){return this.serializeObj(e).join(`
|
|
83
|
+
`)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){let n=[],s=this.pad(r++),i="",o=e[Dt.VALUE];o&&(i=` ${o}`),n.push(`${s}${e[Dt.NAME]}:${i}`),s=this.pad(r);for(let a in e){if(typeof a=="symbol")continue;let c=e[a],u=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")n.push(`${s}${u}${c}`);else if(c instanceof Date)n.push(`${s}${u}${c.toUTCString()}`);else if(Array.isArray(c))for(let l of c)l[Dt.NAME]=a,n.push(...this.serializeObj(l,r));else if(c instanceof Dt)c[Dt.NAME]=a,n.push(...this.serializeObj(c,r));else if(le.BufferSourceConverter.isBufferSource(c))a?(n.push(`${s}${u}`),n.push(...this.serializeBufferSource(c,r+1))):n.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){let l=c.toTextObject();l[Dt.NAME]=a,n.push(...this.serializeObj(l,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return n}static serializeBufferSource(e,r=0){let n=this.pad(r),s=le.BufferSourceConverter.toUint8Array(e),i=[];for(let o=0;o<s.length;){let a=[];for(let c=0;c<16&&o<s.length;c++){c===8&&a.push("");let u=s[o++].toString(16).padStart(2,"0");a.push(u)}i.push(`${n}${a.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};uo.oidSerializer=Ni;uo.algorithmSerializer=x2;var zp,na=class t{get rawData(){return re.__classPrivateFieldGet(this,zp,"f")||re.__classPrivateFieldSet(this,zp,te.AsnConvert.serialize(this.asn),"f"),re.__classPrivateFieldGet(this,zp,"f")}constructor(...e){zp.set(this,void 0),le.BufferSourceConverter.isBufferSource(e[0])?(this.asn=te.AsnConvert.parse(e[0],e[1]),re.__classPrivateFieldSet(this,zp,le.BufferSourceConverter.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof t?le.isEqual(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return te.AsnConvert.toString(this.rawData);case"text":return uo.serialize(this.toTextObject());case"hex":return le.Convert.ToHex(this.rawData);case"base64":return le.Convert.ToBase64(this.rawData);case"base64url":return le.Convert.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Dt(this.getTextName(),{},e)}};zp=new WeakMap;na.NAME="ASN";var zs=class t extends na{constructor(...e){let r;le.BufferSourceConverter.isBufferSource(e[0])?r=le.BufferSourceConverter.toArrayBuffer(e[0]):r=te.AsnConvert.serialize(new He.Extension({extnID:e[0],critical:e[1],extnValue:new te.OctetString(le.BufferSourceConverter.toArrayBuffer(e[2]))})),super(r,He.Extension)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[Dt.NAME]===t.NAME&&(e[Dt.NAME]=Ni.toString(this.type)),e}},wU,Kp=class t{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[wU]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(t.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(t.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,r){return this.items.forEach(e,r)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=t.DEFAULT){let r=this.items.get(e.toLowerCase());if(!r)throw new Error(`Cannot get Crypto by name '${e}'`);return r}set(e,r){if(typeof e=="string"){if(!r)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),r)}else this.items.set(t.DEFAULT,e);return this}};wU=Symbol.toStringTag;Kp.DEFAULT="default";var Dr=new Kp,jle=/^[0-2](?:\.[1-9][0-9]*)+$/;function zle(t){return new RegExp(jle).test(t)}var Ix=class{constructor(e={}){this.items={};for(let r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return zle(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}},Ls=new Ix;Ls.register("CN","2.5.4.3");Ls.register("L","2.5.4.7");Ls.register("ST","2.5.4.8");Ls.register("O","2.5.4.10");Ls.register("OU","2.5.4.11");Ls.register("C","2.5.4.6");Ls.register("DC","0.9.2342.19200300.100.1.25");Ls.register("E","1.2.840.113549.1.9.1");Ls.register("G","2.5.4.42");Ls.register("I","2.5.4.43");Ls.register("SN","2.5.4.4");Ls.register("T","2.5.4.12");function Lle(t,e){return`\\${le.Convert.ToHex(le.Convert.FromUtf8String(e)).toUpperCase()}`}function Dle(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,Lle)}var Tn=class t{static isASCII(e){for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,r={}){this.extraNames=new Ix,this.asn=new He.Name;for(let n in r)if(Object.prototype.hasOwnProperty.call(r,n)){let s=r[n];this.extraNames.register(n,s)}typeof e=="string"?this.asn=this.fromString(e):e instanceof He.Name?this.asn=e:le.BufferSourceConverter.isBufferSource(e)?this.asn=te.AsnConvert.parse(e,He.Name):this.asn=this.fromJSON(e)}getField(e){let r=this.extraNames.findId(e)||Ls.findId(e),n=[];for(let s of this.asn)for(let i of s)i.type===r&&n.push(i.value.toString());return n}getName(e){return this.extraNames.get(e)||Ls.get(e)}toString(){return this.asn.map(e=>e.map(r=>{let n=this.getName(r.type)||r.type,s=r.value.anyValue?`#${le.Convert.ToHex(r.value.anyValue)}`:Dle(r.value.toString());return`${n}=${s}`}).join("+")).join(", ")}toJSON(){var e;let r=[];for(let n of this.asn){let s={};for(let i of n){let o=this.getName(i.type)||i.type;(e=s[o])!==null&&e!==void 0||(s[o]=[]),s[o].push(i.value.anyValue?`#${le.Convert.ToHex(i.value.anyValue)}`:i.value.toString())}r.push(s)}return r}fromString(e){let r=new He.Name,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,s=null,i=",";for(;s=n.exec(`${e},`);){let[,o,a]=s,c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),s[3]=c);let u=s[3];o=this.getTypeOid(o);let l=this.createAttribute(o,a);i==="+"?r[r.length-1].push(l):r.push(new He.RelativeDistinguishedName([l])),i=u}return r}fromJSON(e){let r=new He.Name;for(let n of e){let s=new He.RelativeDistinguishedName;for(let i in n){let o=this.getTypeOid(i),a=n[i];for(let c of a){let u=this.createAttribute(o,c);s.push(u)}}r.push(s)}return r}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,r){let n=new He.AttributeTypeAndValue({type:e});if(typeof r=="object")for(let s in r)switch(s){case"ia5String":n.value.ia5String=r[s];break;case"utf8String":n.value.utf8String=r[s];break;case"universalString":n.value.universalString=r[s];break;case"bmpString":n.value.bmpString=r[s];break;case"printableString":n.value.printableString=r[s];break}else if(r[0]==="#")n.value.anyValue=le.Convert.FromHex(r.slice(1));else{let s=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?n.value.ia5String=s:t.isPrintableString(s)?n.value.printableString=s:n.value.utf8String=s}return n}processStringValue(e){let r=/"(.*?[^\\])?"/.exec(e);return r&&(e=r[1]),e.replace(/\\0a/ig,`
|
|
84
|
+
`).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return te.AsnConvert.serialize(this.asn)}async getThumbprint(...e){var r;let n,s="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(s=e[0]||s,n=e[1]||Dr.get()):n=e[0]||Dr.get(),await n.subtle.digest(s,this.toArrayBuffer())}},SU="Cannot initialize GeneralName from ASN.1 data.",mU=`${SU} Unsupported string format in use.`,Ule=`${SU} Value doesn't match to GUID regular expression.`,gU=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,yU="1.3.6.1.4.1.311.25.1",xU="1.3.6.1.4.1.311.20.2.3",i2="dns",o2="dn",a2="email",c2="ip",u2="url",l2="guid",d2="upn",tx="id",oo=class extends na{constructor(...e){let r;if(e.length===2)switch(e[0]){case o2:{let n=new Tn(e[1]).toArrayBuffer(),s=te.AsnConvert.parse(n,ee.Name);r=new ee.GeneralName({directoryName:s});break}case i2:r=new ee.GeneralName({dNSName:e[1]});break;case a2:r=new ee.GeneralName({rfc822Name:e[1]});break;case l2:{let n=new RegExp(gU,"i").exec(e[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");let s=n.slice(1).map((i,o)=>o<3?le.Convert.ToHex(new Uint8Array(le.Convert.FromHex(i)).reverse()):i).join("");r=new ee.GeneralName({otherName:new ee.OtherName({typeId:yU,value:te.AsnConvert.serialize(new te.OctetString(le.Convert.FromHex(s)))})});break}case c2:r=new ee.GeneralName({iPAddress:e[1]});break;case tx:r=new ee.GeneralName({registeredID:e[1]});break;case d2:{r=new ee.GeneralName({otherName:new ee.OtherName({typeId:xU,value:te.AsnConvert.serialize(te.AsnUtf8StringConverter.toASN(e[1]))})});break}case u2:r=new ee.GeneralName({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else le.BufferSourceConverter.isBufferSource(e[0])?r=te.AsnConvert.parse(e[0],ee.GeneralName):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=i2,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=a2,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=c2,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=u2,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=tx,this.value=e.registeredID;else if(e.directoryName!=null)this.type=o2,this.value=new Tn(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===yU){this.type=l2;let r=te.AsnConvert.parse(e.otherName.value,te.OctetString),n=new RegExp(gU,"i").exec(le.Convert.ToHex(r));if(!n)throw new Error(Ule);this.value=n.slice(1).map((s,i)=>i<3?le.Convert.ToHex(new Uint8Array(le.Convert.FromHex(s)).reverse()):s).join("-")}else if(e.otherName.typeId===xU)this.type=d2,this.value=te.AsnConvert.parse(e.otherName.value,ee.DirectoryString).toString();else throw new Error(mU);else throw new Error(mU)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case o2:case i2:case l2:case c2:case tx:case d2:case u2:e=this.type.toUpperCase();break;case a2:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===tx&&(r=Ni.toString(r)),new Dt(e,void 0,r)}},sa=class extends na{constructor(e){let r;if(e instanceof ee.GeneralNames)r=e;else if(Array.isArray(e)){let n=[];for(let s of e)if(s instanceof ee.GeneralName)n.push(s);else{let i=te.AsnConvert.parse(new oo(s.type,s.value).rawData,ee.GeneralName);n.push(i)}r=new ee.GeneralNames(n)}else if(le.BufferSourceConverter.isBufferSource(e))r=te.AsnConvert.parse(e,ee.GeneralNames);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){let r=[];for(let n of e){let s=null;try{s=new oo(n)}catch{continue}r.push(s)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let r of this.items){let n=r.toTextObject(),s=e[n[Dt.NAME]];Array.isArray(s)||(s=[],e[n[Dt.NAME]]=s),s.push(n)}return e}};sa.NAME="GeneralNames";var Tx="-{5}",Px="\\n",qle=`[^${Px}]+`,Hle=`${Tx}BEGIN (${qle}(?=${Tx}))${Tx}`,Fle=`${Tx}END \\1${Tx}`,Zp="\\n",Vle=`[^:${Px}]+`,Kle=`(?:[^${Px}]+${Zp}(?: +[^${Px}]+${Zp})*)`,Zle="[a-zA-Z0-9=+/]+",Gle=`(?:${Zle}${Zp})+`,bU=`${Hle}${Zp}(?:((?:${Vle}: ${Kle})+))?${Zp}?(${Gle})${Fle}`,Mn=class{static isPem(e){return typeof e=="string"&&new RegExp(bU,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let r=new RegExp(bU,"g"),n=[],s=null;for(;s=r.exec(e);){let i=s[3].replace(new RegExp(`[${Px}]+`,"g"),""),o={type:s[1],headers:[],rawData:le.Convert.FromBase64(i)},a=s[2];if(a){let c=a.split(new RegExp(Zp,"g")),u=null;for(let l of c){let[d,f]=l.split(/:(.*)/);if(f===void 0){if(!u)throw new Error("Cannot parse PEM string. Incorrect header value");u.value+=d.trim()}else u&&o.headers.push(u),u={key:d,value:f.trim()}}u&&o.headers.push(u)}n.push(o)}return n}static decode(e){return this.decodeWithHeaders(e).map(n=>n.rawData)}static decodeFirst(e){let r=this.decode(e);if(!r.length)throw new RangeError("PEM string doesn't contain any objects");return r[0]}static encode(e,r){if(Array.isArray(e)){let n=new Array;return r?e.forEach(s=>{if(!le.BufferSourceConverter.isBufferSource(s))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");n.push(this.encodeStruct({type:r,rawData:le.BufferSourceConverter.toArrayBuffer(s)}))}):e.forEach(s=>{if(!("type"in s))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");n.push(this.encodeStruct(s))}),n.join(`
|
|
85
|
+
`)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:le.BufferSourceConverter.toArrayBuffer(e)})}}static encodeStruct(e){var r;let n=e.type.toLocaleUpperCase(),s=[];if(s.push(`-----BEGIN ${n}-----`),!((r=e.headers)===null||r===void 0)&&r.length){for(let u of e.headers)s.push(`${u.key}: ${u.value}`);s.push("")}let i=le.Convert.ToBase64(e.rawData),o,a=0,c=Array();for(;a<i.length&&(i.length-a<64?o=i.substring(a):(o=i.substring(a,a+64),a+=64),o.length!==0);)if(c.push(o),o.length<64)break;return s.push(...c),s.push(`-----END ${n}-----`),s.join(`
|
|
86
|
+
`)}};Mn.CertificateTag="CERTIFICATE";Mn.CrlTag="CRL";Mn.CertificateRequestTag="CERTIFICATE REQUEST";Mn.PublicKeyTag="PUBLIC KEY";Mn.PrivateKeyTag="PRIVATE KEY";var Ds=class t extends na{static isAsnEncoded(e){return le.BufferSourceConverter.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(Mn.isPem(e))return Mn.decode(e)[0];if(le.Convert.isHex(e))return le.Convert.FromHex(e);if(le.Convert.isBase64(e))return le.Convert.FromBase64(e);if(le.Convert.isBase64Url(e))return le.Convert.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{let r=le.BufferSourceConverter.toUint8Array(e);if(r.length>0&&r[0]===48)return le.BufferSourceConverter.toArrayBuffer(e);let n=le.Convert.ToBinary(e);if(Mn.isPem(n))return Mn.decode(n)[0];if(le.Convert.isHex(n))return le.Convert.FromHex(n);if(le.Convert.isBase64(n))return le.Convert.FromBase64(n);if(le.Convert.isBase64Url(n))return le.Convert.FromBase64Url(n);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){t.isAsnEncoded(e[0])?super(t.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?Mn.encode(this.rawData,this.tag):super.toString(e)}},ao=class t extends Ds{static async create(e,r=Dr.get()){if(e instanceof t)return e;if(Kp.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");let n=await r.subtle.exportKey("spki",e);return new t(n)}else{if(e.publicKey)return e.publicKey;if(le.BufferSourceConverter.isBufferSource(e))return new t(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){Ds.isAsnEncoded(e)?super(e,He.SubjectPublicKeyInfo):super(e),this.tag=Mn.PublicKeyTag}async export(...e){let r,n=["verify"],s={hash:"SHA-256",...this.algorithm};e.length>1?(s=e[0]||s,n=e[1]||n,r=e[2]||Dr.get()):r=e[0]||Dr.get();let i=this.rawData,o=te.AsnConvert.parse(this.rawData,He.SubjectPublicKeyInfo);return o.algorithm.algorithm===js.id_RSASSA_PSS&&(i=Wle(o,i)),r.subtle.importKey("spki",i,s,!0,n)}onInit(e){let r=kr.container.resolve(co),n=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===js.id_rsaEncryption){let s=te.AsnConvert.parse(e.subjectPublicKey,js.RSAPublicKey),i=le.BufferSourceConverter.toUint8Array(s.modulus);n.publicExponent=le.BufferSourceConverter.toUint8Array(s.publicExponent),n.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}async getThumbprint(...e){var r;let n,s="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(s=e[0]||s,n=e[1]||Dr.get()):n=e[0]||Dr.get(),await n.subtle.digest(s,this.rawData)}async getKeyIdentifier(...e){let r,n="SHA-1";e.length===1?typeof e[0]=="string"?(n=e[0],r=Dr.get()):r=e[0]:e.length===2?(n=e[0],r=e[1]):r=Dr.get();let s=te.AsnConvert.parse(this.rawData,He.SubjectPublicKeyInfo);return await r.subtle.digest(n,s.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),r=te.AsnConvert.parse(this.rawData,He.SubjectPublicKeyInfo);switch(e.Algorithm=uo.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case m2.id_ecPublicKey:e["EC Point"]=r.subjectPublicKey;break;case js.id_rsaEncryption:default:e["Raw Data"]=r.subjectPublicKey}return e}};function Wle(t,e){return t.algorithm=new He.AlgorithmIdentifier({algorithm:js.id_rsaEncryption,parameters:null}),e=te.AsnConvert.serialize(t),e}var Rx=class t extends zs{static async create(e,r=!1,n=Dr.get()){if("name"in e&&"serialNumber"in e)return new t(e,r);let i=await(await ao.create(e,n)).getKeyIdentifier(n);return new t(le.Convert.ToHex(i),r)}constructor(...e){if(le.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let r=new ee.AuthorityKeyIdentifier({keyIdentifier:new ee.KeyIdentifier(le.Convert.FromHex(e[0]))});super(ee.id_ce_authorityKeyIdentifier,e[1],te.AsnConvert.serialize(r))}else{let r=e[0],n=r.name instanceof sa?te.AsnConvert.parse(r.name.rawData,ee.GeneralNames):r.name,s=new ee.AuthorityKeyIdentifier({authorityCertIssuer:n,authorityCertSerialNumber:le.Convert.FromHex(r.serialNumber)});super(ee.id_ce_authorityKeyIdentifier,e[1],te.AsnConvert.serialize(s))}}onInit(e){super.onInit(e);let r=te.AsnConvert.parse(e.extnValue,ee.AuthorityKeyIdentifier);r.keyIdentifier&&(this.keyId=le.Convert.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?le.Convert.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),r=te.AsnConvert.parse(this.value,ee.AuthorityKeyIdentifier);return r.authorityCertIssuer&&(e["Authority Issuer"]=new sa(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}};Rx.NAME="Authority Key Identifier";var Ox=class extends zs{constructor(...e){if(le.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let r=te.AsnConvert.parse(this.value,He.BasicConstraints);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{let r=new He.BasicConstraints({cA:e[0],pathLenConstraint:e[1]});super(He.id_ce_basicConstraints,e[2],te.AsnConvert.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}};Ox.NAME="Basic Constraints";xe.ExtendedKeyUsage=void 0;(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(xe.ExtendedKeyUsage||(xe.ExtendedKeyUsage={}));var Nx=class extends zs{constructor(...e){if(le.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let r=te.AsnConvert.parse(this.value,ee.ExtendedKeyUsage);this.usages=r.map(n=>n)}else{let r=new ee.ExtendedKeyUsage(e[0]);super(ee.id_ce_extKeyUsage,e[1],te.AsnConvert.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Ni.toString(r)).join(", "),e}};Nx.NAME="Extended Key Usages";xe.KeyUsageFlags=void 0;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(xe.KeyUsageFlags||(xe.KeyUsageFlags={}));var Bx=class extends zs{constructor(...e){if(le.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let r=te.AsnConvert.parse(this.value,He.KeyUsage);this.usages=r.toNumber()}else{let r=new He.KeyUsage(e[0]);super(He.id_ce_keyUsage,e[1],te.AsnConvert.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=te.AsnConvert.parse(this.value,He.KeyUsage);return e[""]=r.toJSON().join(", "),e}};Bx.NAME="Key Usages";var $x=class t extends zs{static async create(e,r=!1,n=Dr.get()){let i=await(await ao.create(e,n)).getKeyIdentifier(n);return new t(le.Convert.ToHex(i),r)}constructor(...e){if(le.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let r=te.AsnConvert.parse(this.value,ee.SubjectKeyIdentifier);this.keyId=le.Convert.ToHex(r)}else{let r=typeof e[0]=="string"?le.Convert.FromHex(e[0]):e[0],n=new ee.SubjectKeyIdentifier(r);super(ee.id_ce_subjectKeyIdentifier,e[1],te.AsnConvert.serialize(n)),this.keyId=le.Convert.ToHex(r)}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=te.AsnConvert.parse(this.value,ee.SubjectKeyIdentifier);return e[""]=r,e}};$x.NAME="Subject Key Identifier";var Mx=class extends zs{constructor(...e){le.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(ee.id_ce_subjectAltName,e[1],new sa(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=te.AsnConvert.parse(e.extnValue,ee.SubjectAlternativeName);this.names=new sa(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let n in r)e[n]=r[n];return e}};Mx.NAME="Subject Alternative Name";var jn=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new zs(e),n=this.items.get(r.type);return n?new n(e):r}};jn.items=new Map;var jx=class extends zs{constructor(...e){var r;if(le.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let n=te.AsnConvert.parse(this.value,ee.CertificatePolicies);this.policies=n.map(s=>s.policyIdentifier)}else{let n=e[0],s=(r=e[1])!==null&&r!==void 0?r:!1,i=new ee.CertificatePolicies(n.map(o=>new ee.PolicyInformation({policyIdentifier:o})));super(ee.id_ce_certificatePolicies,s,te.AsnConvert.serialize(i)),this.policies=n}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new Dt("",{},Ni.toString(r))),e}};jx.NAME="Certificate Policies";jn.register(ee.id_ce_certificatePolicies,jx);var zx=class extends zs{constructor(...e){var r;if(le.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let s=e[0].map(o=>new ee.DistributionPoint({distributionPoint:new ee.DistributionPointName({fullName:[new ee.GeneralName({uniformResourceIdentifier:o})]})})),i=new ee.CRLDistributionPoints(s);super(ee.id_ce_cRLDistributionPoints,e[1],te.AsnConvert.serialize(i))}else{let n=new ee.CRLDistributionPoints(e[0]);super(ee.id_ce_cRLDistributionPoints,e[1],te.AsnConvert.serialize(n))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let r=te.AsnConvert.parse(e.extnValue,ee.CRLDistributionPoints);this.distributionPoints=r}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var n;let s={};return r.distributionPoint&&(s[""]=(n=r.distributionPoint.fullName)===null||n===void 0?void 0:n.map(i=>new oo(i).toString()).join(", ")),r.reasons&&(s.Reasons=r.reasons.toString()),r.cRLIssuer&&(s["CRL Issuer"]=r.cRLIssuer.map(i=>i.toString()).join(", ")),s}),e}};zx.NAME="CRL Distribution Points";var Lx=class extends zs{constructor(...e){var r,n,s,i;if(le.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof ee.AuthorityInfoAccessSyntax){let o=new ee.AuthorityInfoAccessSyntax(e[0]);super(ee.id_pe_authorityInfoAccess,e[1],te.AsnConvert.serialize(o))}else{let o=e[0],a=new ee.AuthorityInfoAccessSyntax;n2(a,o,ee.id_ad_ocsp,"ocsp"),n2(a,o,ee.id_ad_caIssuers,"caIssuers"),n2(a,o,ee.id_ad_timeStamping,"timeStamping"),n2(a,o,ee.id_ad_caRepository,"caRepository"),super(ee.id_pe_authorityInfoAccess,e[1],te.AsnConvert.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(n=this.caIssuers)!==null&&n!==void 0||(this.caIssuers=[]),(s=this.timeStamping)!==null&&s!==void 0||(this.timeStamping=[]),(i=this.caRepository)!==null&&i!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],te.AsnConvert.parse(e.extnValue,ee.AuthorityInfoAccessSyntax).forEach(n=>{switch(n.accessMethod){case ee.id_ad_ocsp:this.ocsp.push(new oo(n.accessLocation));break;case ee.id_ad_caIssuers:this.caIssuers.push(new oo(n.accessLocation));break;case ee.id_ad_timeStamping:this.timeStamping.push(new oo(n.accessLocation));break;case ee.id_ad_caRepository:this.caRepository.push(new oo(n.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&r2(e,"OCSP",this.ocsp),this.caIssuers.length&&r2(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&r2(e,"Time Stamping",this.timeStamping),this.caRepository.length&&r2(e,"CA Repository",this.caRepository),e}};Lx.NAME="Authority Info Access";function r2(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{let n=new Dt("");r.forEach((s,i)=>{let o=s.toTextObject(),a=`${o[Dt.NAME]} ${i+1}`,c=n[a];Array.isArray(c)||(c=[],n[a]=c),c.push(o)}),t[e]=n}}function n2(t,e,r,n){let s=e[n];s&&(Array.isArray(s)?s:[s]).forEach(o=>{typeof o=="string"&&(o=new oo("url",o)),t.push(new ee.AccessDescription({accessMethod:r,accessLocation:te.AsnConvert.parse(o.rawData,ee.GeneralName)}))})}var Dx=class extends zs{constructor(...e){le.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(ee.id_ce_issuerAltName,e[1],new sa(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=te.AsnConvert.parse(e.extnValue,ee.GeneralNames);this.names=new sa(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let n in r)e[n]=r[n];return e}};Dx.NAME="Issuer Alternative Name";var Ld=class t extends na{constructor(...e){let r;if(le.BufferSourceConverter.isBufferSource(e[0]))r=le.BufferSourceConverter.toArrayBuffer(e[0]);else{let n=e[0],s=Array.isArray(e[1])?e[1].map(i=>le.BufferSourceConverter.toArrayBuffer(i)):[];r=te.AsnConvert.serialize(new He.Attribute({type:n,values:s}))}super(r,He.Attribute)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new Dt("",{"":r})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[Dt.NAME]===t.NAME&&(e[Dt.NAME]=Ni.toString(this.type)),e}};Ld.NAME="Attribute";var Ux=class extends Ld{constructor(...e){var r;if(le.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let n=new Vp.ChallengePassword({printableString:e[0]});super(Vp.id_pkcs9_at_challengePassword,[te.AsnConvert.serialize(n)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let r=te.AsnConvert.parse(this.values[0],Vp.ChallengePassword);this.password=r.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Dt.VALUE]=this.password,e}};Ux.NAME="Challenge Password";var Gp=class extends Ld{constructor(...e){var r;if(le.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let n=e[0],s=new ee.Extensions;for(let i of n)s.push(te.AsnConvert.parse(i.rawData,ee.Extension));super(Vp.id_pkcs9_at_extensionRequest,[te.AsnConvert.serialize(s)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let r=te.AsnConvert.parse(this.values[0],ee.Extensions);this.items=r.map(n=>jn.create(te.AsnConvert.serialize(n)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.items.map(n=>n.toTextObject());for(let n of r)e[n[Dt.NAME]]=n;return e}};Gp.NAME="Extensions";var Dd=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new Ld(e),n=this.items.get(r.type);return n?new n(e):r}};Dd.items=new Map;var sc="crypto.signatureFormatter",b2=class{toAsnSignature(e,r){return le.BufferSourceConverter.toArrayBuffer(r)}toWebSignature(e,r){return le.BufferSourceConverter.toArrayBuffer(r)}},f2;xe.RsaAlgorithm=f2=class{static createPssParams(e,r){let n=f2.getHashAlgorithm(e);return n?new Cr.RsaSaPssParams({hashAlgorithm:n,maskGenAlgorithm:new He.AlgorithmIdentifier({algorithm:Cr.id_mgf1,parameters:te.AsnConvert.serialize(n)}),saltLength:r}):null}static getHashAlgorithm(e){let r=kr.container.resolve(co);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new He.AlgorithmIdentifier({algorithm:Cr.id_sha1WithRSAEncryption,parameters:null});case"sha-256":return new He.AlgorithmIdentifier({algorithm:Cr.id_sha256WithRSAEncryption,parameters:null});case"sha-384":return new He.AlgorithmIdentifier({algorithm:Cr.id_sha384WithRSAEncryption,parameters:null});case"sha-512":return new He.AlgorithmIdentifier({algorithm:Cr.id_sha512WithRSAEncryption,parameters:null})}}else return new He.AlgorithmIdentifier({algorithm:Cr.id_rsaEncryption,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");let r=f2.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new He.AlgorithmIdentifier({algorithm:Cr.id_RSASSA_PSS,parameters:te.AsnConvert.serialize(r)})}else return new He.AlgorithmIdentifier({algorithm:Cr.id_RSASSA_PSS,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Cr.id_rsaEncryption:return{name:"RSASSA-PKCS1-v1_5"};case Cr.id_sha1WithRSAEncryption:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Cr.id_sha256WithRSAEncryption:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Cr.id_sha384WithRSAEncryption:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Cr.id_sha512WithRSAEncryption:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case Cr.id_RSASSA_PSS:if(e.parameters){let r=te.AsnConvert.parse(e.parameters,Cr.RsaSaPssParams);return{name:"RSA-PSS",hash:kr.container.resolve(co).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};xe.RsaAlgorithm=f2=re.__decorate([kr.injectable()],xe.RsaAlgorithm);kr.container.registerSingleton(Xp,xe.RsaAlgorithm);xe.ShaAlgorithm=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new He.AlgorithmIdentifier({algorithm:js.id_sha1});case"sha-256":return new He.AlgorithmIdentifier({algorithm:js.id_sha256});case"sha-384":return new He.AlgorithmIdentifier({algorithm:js.id_sha384});case"sha-512":return new He.AlgorithmIdentifier({algorithm:js.id_sha512})}return null}toWebAlgorithm(e){switch(e.algorithm){case js.id_sha1:return{name:"SHA-1"};case js.id_sha256:return{name:"SHA-256"};case js.id_sha384:return{name:"SHA-384"};case js.id_sha512:return{name:"SHA-512"}}return null}};xe.ShaAlgorithm=re.__decorate([kr.injectable()],xe.ShaAlgorithm);kr.container.registerSingleton(Xp,xe.ShaAlgorithm);var ia=class t{addPadding(e,r){let n=le.BufferSourceConverter.toUint8Array(r),s=new Uint8Array(e);return s.set(n,e-n.length),s.buffer}removePadding(e,r=!1){let n=le.BufferSourceConverter.toUint8Array(e);for(let s=0;s<n.length;s++)if(n[s]){n=n.slice(s);break}if(r&&n[0]>127){let s=new Uint8Array(n.length+1);return s.set(n,1),s.buffer}return n.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){let n=e.namedCurve,s=t.namedCurveSize.get(n)||t.defaultNamedCurveSize,i=new m2.ECDSASigValue,o=le.BufferSourceConverter.toUint8Array(r);return i.r=this.removePadding(o.slice(0,s),!0),i.s=this.removePadding(o.slice(s,s+s),!0),te.AsnConvert.serialize(i)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){let n=te.AsnConvert.parse(r,m2.ECDSASigValue),s=e.namedCurve,i=t.namedCurveSize.get(s)||t.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(n.r)),a=this.addPadding(i,this.removePadding(n.s));return le.combine(o,a)}return null}};ia.namedCurveSize=new Map;ia.defaultNamedCurveSize=32;var h2="1.3.101.110",E3="1.3.101.111",p2="1.3.101.112",C3="1.3.101.113";xe.EdAlgorithm=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=p2;break;case"x25519":r=h2;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=p2;break;case"ed448":r=C3;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=h2;break;case"x448":r=E3;break}}return r?new He.AlgorithmIdentifier({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case p2:return{name:"Ed25519"};case C3:return{name:"EdDSA",namedCurve:"Ed448"};case h2:return{name:"X25519"};case E3:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};xe.EdAlgorithm=re.__decorate([kr.injectable()],xe.EdAlgorithm);kr.container.registerSingleton(Xp,xe.EdAlgorithm);var rx,nx,sx,ix,ox,ax,cx,Lp,qx=class extends Ds{get subjectName(){return re.__classPrivateFieldGet(this,nx,"f")||re.__classPrivateFieldSet(this,nx,new Tn(this.asn.certificationRequestInfo.subject),"f"),re.__classPrivateFieldGet(this,nx,"f")}get subject(){return re.__classPrivateFieldGet(this,sx,"f")||re.__classPrivateFieldSet(this,sx,this.subjectName.toString(),"f"),re.__classPrivateFieldGet(this,sx,"f")}get signatureAlgorithm(){if(!re.__classPrivateFieldGet(this,ix,"f")){let e=kr.container.resolve(co);re.__classPrivateFieldSet(this,ix,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return re.__classPrivateFieldGet(this,ix,"f")}get signature(){return re.__classPrivateFieldGet(this,ox,"f")||re.__classPrivateFieldSet(this,ox,this.asn.signature,"f"),re.__classPrivateFieldGet(this,ox,"f")}get publicKey(){return re.__classPrivateFieldGet(this,ax,"f")||re.__classPrivateFieldSet(this,ax,new ao(this.asn.certificationRequestInfo.subjectPKInfo),"f"),re.__classPrivateFieldGet(this,ax,"f")}get attributes(){return re.__classPrivateFieldGet(this,cx,"f")||re.__classPrivateFieldSet(this,cx,this.asn.certificationRequestInfo.attributes.map(e=>Dd.create(te.AsnConvert.serialize(e))),"f"),re.__classPrivateFieldGet(this,cx,"f")}get extensions(){if(!re.__classPrivateFieldGet(this,Lp,"f")){re.__classPrivateFieldSet(this,Lp,[],"f");let e=this.getAttribute(R3.id_pkcs9_at_extensionRequest);e instanceof Gp&&re.__classPrivateFieldSet(this,Lp,e.items,"f")}return re.__classPrivateFieldGet(this,Lp,"f")}get tbs(){return re.__classPrivateFieldGet(this,rx,"f")||re.__classPrivateFieldSet(this,rx,this.asn.certificationRequestInfoRaw||te.AsnConvert.serialize(this.asn.certificationRequestInfo),"f"),re.__classPrivateFieldGet(this,rx,"f")}constructor(e){let r=Ds.isAsnEncoded(e)?[e,g2.CertificationRequest]:[e];super(r[0],r[1]),rx.set(this,void 0),nx.set(this,void 0),sx.set(this,void 0),ix.set(this,void 0),ox.set(this,void 0),ax.set(this,void 0),cx.set(this,void 0),Lp.set(this,void 0),this.tag=Mn.CertificateRequestTag}onInit(e){}getAttribute(e){for(let r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(let r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=Dr.get()){let r={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(r,["verify"],e),s=kr.container.resolveAll(sc).reverse(),i=null;for(let a of s)if(i=a.toWebSignature(r,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,n,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),r=te.AsnConvert.parse(this.rawData,g2.CertificationRequest),n=r.certificationRequestInfo,s=new Dt("",{Version:`${He.Version[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let i=new Dt("");for(let o of this.attributes){let a=o.toTextObject();i[a[Dt.NAME]]=a}s.Attributes=i}return e.Data=s,e.Signature=new Dt("",{Algorithm:uo.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}};rx=new WeakMap,nx=new WeakMap,sx=new WeakMap,ix=new WeakMap,ox=new WeakMap,ax=new WeakMap,cx=new WeakMap,Lp=new WeakMap;qx.NAME="PKCS#10 Certificate Request";var k3=class{static async create(e,r=Dr.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");let n=await r.subtle.exportKey("spki",e.keys.publicKey),s=new g2.CertificationRequest({certificationRequestInfo:new g2.CertificationRequestInfo({subjectPKInfo:te.AsnConvert.parse(n,He.SubjectPublicKeyInfo)})});if(e.name){let d=e.name instanceof Tn?e.name:new Tn(e.name);s.certificationRequestInfo.subject=te.AsnConvert.parse(d.toArrayBuffer(),He.Name)}if(e.attributes)for(let d of e.attributes)s.certificationRequestInfo.attributes.push(te.AsnConvert.parse(d.rawData,He.Attribute));if(e.extensions&&e.extensions.length){let d=new He.Attribute({type:R3.id_pkcs9_at_extensionRequest}),f=new He.Extensions;for(let p of e.extensions)f.push(te.AsnConvert.parse(p.rawData,He.Extension));d.values.push(te.AsnConvert.serialize(f)),s.certificationRequestInfo.attributes.push(d)}let i={...e.signingAlgorithm,...e.keys.privateKey.algorithm},o=kr.container.resolve(co);s.signatureAlgorithm=o.toAsnAlgorithm(i);let a=te.AsnConvert.serialize(s.certificationRequestInfo),c=await r.subtle.sign(i,e.keys.privateKey,a),u=kr.container.resolveAll(sc).reverse(),l=null;for(let d of u)if(l=d.toAsnSignature(i,c),l)break;if(!l)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return s.signature=l,new qx(te.AsnConvert.serialize(s))}},ux,lx,dx,fx,hx,px,mx,gx,yx,xx,Dp,bx,Su=class extends Ds{get publicKey(){return re.__classPrivateFieldGet(this,bx,"f")||re.__classPrivateFieldSet(this,bx,new ao(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),re.__classPrivateFieldGet(this,bx,"f")}get serialNumber(){if(!re.__classPrivateFieldGet(this,lx,"f")){let e=this.asn.tbsCertificate,r=new Uint8Array(e.serialNumber);r.length>1&&r[0]===0&&r[1]>127&&(r=r.slice(1)),re.__classPrivateFieldSet(this,lx,le.Convert.ToHex(r),"f")}return re.__classPrivateFieldGet(this,lx,"f")}get subjectName(){return re.__classPrivateFieldGet(this,dx,"f")||re.__classPrivateFieldSet(this,dx,new Tn(this.asn.tbsCertificate.subject),"f"),re.__classPrivateFieldGet(this,dx,"f")}get subject(){return re.__classPrivateFieldGet(this,fx,"f")||re.__classPrivateFieldSet(this,fx,this.subjectName.toString(),"f"),re.__classPrivateFieldGet(this,fx,"f")}get issuerName(){return re.__classPrivateFieldGet(this,hx,"f")||re.__classPrivateFieldSet(this,hx,new Tn(this.asn.tbsCertificate.issuer),"f"),re.__classPrivateFieldGet(this,hx,"f")}get issuer(){return re.__classPrivateFieldGet(this,px,"f")||re.__classPrivateFieldSet(this,px,this.issuerName.toString(),"f"),re.__classPrivateFieldGet(this,px,"f")}get notBefore(){if(!re.__classPrivateFieldGet(this,mx,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");re.__classPrivateFieldSet(this,mx,e,"f")}return re.__classPrivateFieldGet(this,mx,"f")}get notAfter(){if(!re.__classPrivateFieldGet(this,gx,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");re.__classPrivateFieldSet(this,gx,e,"f")}return re.__classPrivateFieldGet(this,gx,"f")}get signatureAlgorithm(){if(!re.__classPrivateFieldGet(this,yx,"f")){let e=kr.container.resolve(co);re.__classPrivateFieldSet(this,yx,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return re.__classPrivateFieldGet(this,yx,"f")}get signature(){return re.__classPrivateFieldGet(this,xx,"f")||re.__classPrivateFieldSet(this,xx,this.asn.signatureValue,"f"),re.__classPrivateFieldGet(this,xx,"f")}get extensions(){return re.__classPrivateFieldGet(this,Dp,"f")||(re.__classPrivateFieldSet(this,Dp,[],"f"),this.asn.tbsCertificate.extensions&&re.__classPrivateFieldSet(this,Dp,this.asn.tbsCertificate.extensions.map(e=>jn.create(te.AsnConvert.serialize(e))),"f")),re.__classPrivateFieldGet(this,Dp,"f")}get tbs(){return re.__classPrivateFieldGet(this,ux,"f")||re.__classPrivateFieldSet(this,ux,this.asn.tbsCertificateRaw||te.AsnConvert.serialize(this.asn.tbsCertificate),"f"),re.__classPrivateFieldGet(this,ux,"f")}constructor(e){let r=Ds.isAsnEncoded(e)?[e,He.Certificate]:[e];super(r[0],r[1]),ux.set(this,void 0),lx.set(this,void 0),dx.set(this,void 0),fx.set(this,void 0),hx.set(this,void 0),px.set(this,void 0),mx.set(this,void 0),gx.set(this,void 0),yx.set(this,void 0),xx.set(this,void 0),Dp.set(this,void 0),bx.set(this,void 0),this.tag=Mn.CertificateTag}onInit(e){}getExtension(e){for(let r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=Dr.get()){let n,s,i=e.publicKey;try{if(!i)n={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(n,["verify"],r);else if("publicKey"in i)n={...i.publicKey.algorithm,...this.signatureAlgorithm},s=await i.publicKey.export(n,["verify"],r);else if(i instanceof ao)n={...i.algorithm,...this.signatureAlgorithm},s=await i.export(n,["verify"],r);else if(le.BufferSourceConverter.isBufferSource(i)){let u=new ao(i);n={...u.algorithm,...this.signatureAlgorithm},s=await u.export(n,["verify"],r)}else n={...i.algorithm,...this.signatureAlgorithm},s=i}catch{return!1}let o=kr.container.resolveAll(sc).reverse(),a=null;for(let u of o)if(a=u.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let c=await r.subtle.verify(this.signatureAlgorithm,s,a,this.tbs);if(e.signatureOnly)return c;{let l=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<l&&l<this.notAfter.getTime()}}async getThumbprint(...e){let r,n="SHA-1";return e[0]&&(e[0].subtle?r=e[0]:(n=e[0]||n,r=e[1])),r??(r=Dr.get()),await r.subtle.digest(n,this.rawData)}async isSelfSigned(e=Dr.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),r=te.AsnConvert.parse(this.rawData,He.Certificate),n=r.tbsCertificate,s=new Dt("",{Version:`${He.Version[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":uo.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new Dt("",{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(s["Issuer Unique ID"]=n.issuerUniqueID),n.subjectUniqueID&&(s["Subject Unique ID"]=n.subjectUniqueID),this.extensions.length){let i=new Dt("");for(let o of this.extensions){let a=o.toTextObject();i[a[Dt.NAME]]=a}s.Extensions=i}return e.Data=s,e.Signature=new Dt("",{Algorithm:uo.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}};ux=new WeakMap,lx=new WeakMap,dx=new WeakMap,fx=new WeakMap,hx=new WeakMap,px=new WeakMap,mx=new WeakMap,gx=new WeakMap,yx=new WeakMap,xx=new WeakMap,Dp=new WeakMap,bx=new WeakMap;Su.NAME="Certificate";var _2=class extends Array{constructor(e){if(super(),Ds.isAsnEncoded(e))this.import(e);else if(e instanceof Su)this.push(e);else if(Array.isArray(e))for(let r of e)this.push(r)}export(e){let r=new Ms.SignedData;r.version=1,r.encapContentInfo.eContentType=Ms.id_data,r.encapContentInfo.eContent=new Ms.EncapsulatedContent({single:new te.OctetString}),r.certificates=new Ms.CertificateSet(this.map(i=>new Ms.CertificateChoices({certificate:te.AsnConvert.parse(i.rawData,He.Certificate)})));let n=new Ms.ContentInfo({contentType:Ms.id_signedData,content:te.AsnConvert.serialize(r)}),s=te.AsnConvert.serialize(n);return e==="raw"?s:this.toString(e)}import(e){let r=Ds.toArrayBuffer(e),n=te.AsnConvert.parse(r,Ms.ContentInfo);if(n.contentType!==Ms.id_signedData)throw new TypeError("Cannot parse CMS package. Incoming data is not a SignedData object.");let s=te.AsnConvert.parse(n.content,Ms.SignedData);this.clear();for(let i of s.certificates||[])i.certificate&&this.push(new Su(i.certificate))}clear(){for(;this.pop(););}toString(e="pem"){let r=this.export("raw");switch(e){case"pem":return Mn.encode(r,"CMS");case"pem-chain":return this.map(n=>n.toString("pem")).join(`
|
|
87
|
+
`);case"asn":return te.AsnConvert.toString(r);case"hex":return le.Convert.ToHex(r);case"base64":return le.Convert.ToBase64(r);case"base64url":return le.Convert.ToBase64Url(r);case"text":return uo.serialize(this.toTextObject());default:throw TypeError("Argument 'format' is unsupported value")}}toTextObject(){let e=te.AsnConvert.parse(this.export("raw"),Ms.ContentInfo),r=te.AsnConvert.parse(e.content,Ms.SignedData);return new Dt("X509Certificates",{"Content Type":Ni.toString(e.contentType),Content:new Dt("",{Version:`${Ms.CMSVersion[r.version]} (${r.version})`,Certificates:new Dt("",{Certificate:this.map(s=>s.toTextObject())})})})}},T3=class{constructor(e={}){this.certificates=[],e.certificates&&(this.certificates=e.certificates)}async build(e,r=Dr.get()){let n=new _2(e),s=e;for(;s=await this.findIssuer(s,r);){let i=await s.getThumbprint(r);for(let o of n){let a=await o.getThumbprint(r);if(le.isEqual(i,a))throw new Error("Cannot build a certificate chain. Circular dependency.")}n.push(s)}return n}async findIssuer(e,r=Dr.get()){if(!await e.isSelfSigned(r)){let n=e.getExtension(ee.id_ce_authorityKeyIdentifier);for(let s of this.certificates)if(s.subject===e.issuer){if(n){if(n.keyId){let i=s.getExtension(ee.id_ce_subjectKeyIdentifier);if(i&&i.keyId!==n.keyId)continue}else if(n.certId){let i=s.getExtension(ee.id_ce_subjectAltName);if(i&&!(n.certId.serialNumber===s.serialNumber&&le.isEqual(te.AsnConvert.serialize(n.certId.name),te.AsnConvert.serialize(i))))continue}}try{let i={...s.publicKey.algorithm,...e.signatureAlgorithm},o=await s.publicKey.export(i,["verify"],r);if(!await e.verify({publicKey:o,signatureOnly:!0},r))continue}catch{continue}return s}}return null}};function O3(t,e=Dr.get()){let r=le.BufferSourceConverter.toUint8Array(le.Convert.FromHex(t||"")),n=r&&r.length&&r.some(i=>i>0)?new Uint8Array(r):void 0;n||(n=e.getRandomValues(new Uint8Array(16)));let s=0;for(;s<n.length-1&&n[s]===0;)s++;if(n=n.slice(s),n[0]>127){let i=new Uint8Array(n.length+1);i[0]=0,i.set(n,1),n=i}return n.buffer}var I3=class{static async createSelfSigned(e,r=Dr.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=Dr.get()){var n;let s;e.publicKey instanceof ao?s=e.publicKey.rawData:"publicKey"in e.publicKey?s=e.publicKey.publicKey.rawData:le.BufferSourceConverter.isBufferSource(e.publicKey)?s=e.publicKey:s=await r.subtle.exportKey("spki",e.publicKey);let i=O3(e.serialNumber,r),o=e.notBefore||new Date,a=e.notAfter||new Date(o.getTime()+31536e6),c=new ee.Certificate({tbsCertificate:new ee.TBSCertificate({version:ee.Version.v3,serialNumber:i,validity:new ee.Validity({notBefore:o,notAfter:a}),extensions:new ee.Extensions(((n=e.extensions)===null||n===void 0?void 0:n.map(_=>te.AsnConvert.parse(_.rawData,ee.Extension)))||[]),subjectPublicKeyInfo:te.AsnConvert.parse(s,ee.SubjectPublicKeyInfo)})});if(e.subject){let _=e.subject instanceof Tn?e.subject:new Tn(e.subject);c.tbsCertificate.subject=te.AsnConvert.parse(_.toArrayBuffer(),ee.Name)}if(e.issuer){let _=e.issuer instanceof Tn?e.issuer:new Tn(e.issuer);c.tbsCertificate.issuer=te.AsnConvert.parse(_.toArrayBuffer(),ee.Name)}let u={hash:"SHA-256"},l="signingKey"in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},d=kr.container.resolve(co);c.tbsCertificate.signature=c.signatureAlgorithm=d.toAsnAlgorithm(l);let f=te.AsnConvert.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(l,e.signingKey,f):e.signature,m=kr.container.resolveAll(sc).reverse(),y=null;for(let _ of m)if(y=_.toAsnSignature(l,p),y)break;if(!y)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=y,new Su(te.AsnConvert.serialize(c))}},_x,vx,Up,qp,Hp;xe.X509CrlReason=void 0;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(xe.X509CrlReason||(xe.X509CrlReason={}));var Wp=class extends na{get serialNumber(){return re.__classPrivateFieldGet(this,_x,"f")||re.__classPrivateFieldSet(this,_x,le.Convert.ToHex(this.asn.userCertificate),"f"),re.__classPrivateFieldGet(this,_x,"f")}get revocationDate(){return re.__classPrivateFieldGet(this,vx,"f")||re.__classPrivateFieldSet(this,vx,this.asn.revocationDate.getTime(),"f"),re.__classPrivateFieldGet(this,vx,"f")}get reason(){return re.__classPrivateFieldGet(this,Up,"f")===void 0&&this.extensions,re.__classPrivateFieldGet(this,Up,"f")}get invalidity(){return re.__classPrivateFieldGet(this,qp,"f")===void 0&&this.extensions,re.__classPrivateFieldGet(this,qp,"f")}get extensions(){return re.__classPrivateFieldGet(this,Hp,"f")||(re.__classPrivateFieldSet(this,Hp,[],"f"),this.asn.crlEntryExtensions&&re.__classPrivateFieldSet(this,Hp,this.asn.crlEntryExtensions.map(e=>{let r=jn.create(te.AsnConvert.serialize(e));switch(r.type){case He.id_ce_cRLReasons:re.__classPrivateFieldGet(this,Up,"f")===void 0&&re.__classPrivateFieldSet(this,Up,te.AsnConvert.parse(r.value,He.CRLReason).reason,"f");break;case He.id_ce_invalidityDate:re.__classPrivateFieldGet(this,qp,"f")===void 0&&re.__classPrivateFieldSet(this,qp,te.AsnConvert.parse(r.value,He.InvalidityDate).value,"f");break}return r}),"f")),re.__classPrivateFieldGet(this,Hp,"f")}constructor(...e){let r;if(le.BufferSourceConverter.isBufferSource(e[0])?r=le.BufferSourceConverter.toArrayBuffer(e[0]):typeof e[0]=="string"?r=te.AsnConvert.serialize(new He.RevokedCertificate({userCertificate:O3(e[0]),revocationDate:new He.Time(e[1]),crlEntryExtensions:e[2]})):e[0]instanceof He.RevokedCertificate&&(r=e[0]),!r)throw new TypeError("Cannot create X509CrlEntry instance. Wrong constructor arguments.");super(r,He.RevokedCertificate),_x.set(this,void 0),vx.set(this,void 0),Up.set(this,void 0),qp.set(this,void 0),Hp.set(this,void 0)}onInit(e){}};_x=new WeakMap,vx=new WeakMap,Up=new WeakMap,qp=new WeakMap,Hp=new WeakMap;var wx,Sx,Ax,Ex,Cx,kx,Fp,v2=class extends Ds{get version(){return this.asn.tbsCertList.version}get signatureAlgorithm(){if(!re.__classPrivateFieldGet(this,Sx,"f")){let e=kr.container.resolve(co);re.__classPrivateFieldSet(this,Sx,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return re.__classPrivateFieldGet(this,Sx,"f")}get signature(){return this.asn.signature}get issuer(){return this.issuerName.toString()}get issuerName(){return re.__classPrivateFieldGet(this,Ax,"f")||re.__classPrivateFieldSet(this,Ax,new Tn(this.asn.tbsCertList.issuer),"f"),re.__classPrivateFieldGet(this,Ax,"f")}get thisUpdate(){if(!re.__classPrivateFieldGet(this,Ex,"f")){let e=this.asn.tbsCertList.thisUpdate.getTime();if(!e)throw new Error("Cannot get 'thisUpdate' value");re.__classPrivateFieldSet(this,Ex,e,"f")}return re.__classPrivateFieldGet(this,Ex,"f")}get nextUpdate(){var e;return re.__classPrivateFieldGet(this,Cx,"f")===void 0&&re.__classPrivateFieldSet(this,Cx,((e=this.asn.tbsCertList.nextUpdate)===null||e===void 0?void 0:e.getTime())||void 0,"f"),re.__classPrivateFieldGet(this,Cx,"f")}get entries(){var e;return re.__classPrivateFieldGet(this,kx,"f")||re.__classPrivateFieldSet(this,kx,((e=this.asn.tbsCertList.revokedCertificates)===null||e===void 0?void 0:e.map(r=>new Wp(r)))||[],"f"),re.__classPrivateFieldGet(this,kx,"f")}get extensions(){return re.__classPrivateFieldGet(this,Fp,"f")||(re.__classPrivateFieldSet(this,Fp,[],"f"),this.asn.tbsCertList.crlExtensions&&re.__classPrivateFieldSet(this,Fp,this.asn.tbsCertList.crlExtensions.map(e=>jn.create(te.AsnConvert.serialize(e))),"f")),re.__classPrivateFieldGet(this,Fp,"f")}get tbs(){return re.__classPrivateFieldGet(this,wx,"f")||re.__classPrivateFieldSet(this,wx,this.asn.tbsCertListRaw||te.AsnConvert.serialize(this.asn.tbsCertList),"f"),re.__classPrivateFieldGet(this,wx,"f")}get tbsCertListSignatureAlgorithm(){return this.asn.tbsCertList.signature}get certListSignatureAlgorithm(){return this.asn.signatureAlgorithm}constructor(e){super(e,Ds.isAsnEncoded(e)?He.CertificateList:void 0),this.tag=Mn.CrlTag,wx.set(this,void 0),Sx.set(this,void 0),Ax.set(this,void 0),Ex.set(this,void 0),Cx.set(this,void 0),kx.set(this,void 0),Fp.set(this,void 0)}onInit(e){}getExtension(e){for(let r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e,r=Dr.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw new Error("algorithm identifier in the sequence tbsCertList and CertificateList mismatch");let n,s,i=e.publicKey;try{i instanceof Su?(n={...i.publicKey.algorithm,...i.signatureAlgorithm},s=await i.publicKey.export(n,["verify"])):i instanceof ao?(n={...i.algorithm,...this.signatureAlgorithm},s=await i.export(n,["verify"])):(n={...i.algorithm,...this.signatureAlgorithm},s=i)}catch{return!1}let o=kr.container.resolveAll(sc).reverse(),a=null;for(let c of o)if(a=c.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return await r.subtle.verify(this.signatureAlgorithm,s,a,this.tbs)}async getThumbprint(...e){let r,n="SHA-1";return e[0]&&(e[0].subtle?r=e[0]:(n=e[0]||n,r=e[1])),r??(r=Dr.get()),await r.subtle.digest(n,this.rawData)}findRevoked(e){let r=typeof e=="string"?e:e.serialNumber,n=O3(r);for(let s of this.asn.tbsCertList.revokedCertificates||[])if(le.BufferSourceConverter.isEqual(s.userCertificate,n))return new Wp(te.AsnConvert.serialize(s));return null}};wx=new WeakMap,Sx=new WeakMap,Ax=new WeakMap,Ex=new WeakMap,Cx=new WeakMap,kx=new WeakMap,Fp=new WeakMap;var P3=class{static async create(e,r=Dr.get()){var n;let s=e.issuer instanceof Tn?e.issuer:new Tn(e.issuer),i=new ee.CertificateList({tbsCertList:new ee.TBSCertList({version:ee.Version.v2,issuer:te.AsnConvert.parse(s.toArrayBuffer(),ee.Name),thisUpdate:new He.Time(e.thisUpdate||new Date)})});if(e.nextUpdate&&(i.tbsCertList.nextUpdate=new He.Time(e.nextUpdate)),e.extensions&&e.extensions.length&&(i.tbsCertList.crlExtensions=new ee.Extensions(e.extensions.map(f=>te.AsnConvert.parse(f.rawData,ee.Extension))||[])),e.entries&&e.entries.length){i.tbsCertList.revokedCertificates=[];for(let f of e.entries){let p=Ds.toArrayBuffer(f.serialNumber);if(i.tbsCertList.revokedCertificates.findIndex(_=>le.isEqual(_.userCertificate,p))>-1)throw new Error(`Certificate serial number ${f.serialNumber} already exists in tbsCertList`);let y=new He.RevokedCertificate({userCertificate:p,revocationDate:new He.Time(f.revocationDate||new Date)});if("extensions"in f&&(!((n=f.extensions)===null||n===void 0)&&n.length)?y.crlEntryExtensions=f.extensions.map(_=>te.AsnConvert.parse(_.rawData,ee.Extension)):y.crlEntryExtensions=[],!(f instanceof Wp)&&(f.reason&&y.crlEntryExtensions.push(new ee.Extension({extnID:ee.id_ce_cRLReasons,critical:!1,extnValue:new te.OctetString(te.AsnConvert.serialize(new ee.CRLReason(f.reason)))})),f.invalidity&&y.crlEntryExtensions.push(new ee.Extension({extnID:ee.id_ce_invalidityDate,critical:!1,extnValue:new te.OctetString(te.AsnConvert.serialize(new ee.InvalidityDate(f.invalidity)))})),f.issuer)){let _=e.issuer instanceof Tn?e.issuer:new Tn(e.issuer);y.crlEntryExtensions.push(new ee.Extension({extnID:ee.id_ce_certificateIssuer,critical:!1,extnValue:new te.OctetString(te.AsnConvert.serialize(te.AsnConvert.parse(_.toArrayBuffer(),ee.Name)))}))}i.tbsCertList.revokedCertificates.push(y)}}let o={...e.signingAlgorithm,...e.signingKey.algorithm},a=kr.container.resolve(co);i.tbsCertList.signature=i.signatureAlgorithm=a.toAsnAlgorithm(o);let c=te.AsnConvert.serialize(i.tbsCertList),u=await r.subtle.sign(o,e.signingKey,c),l=kr.container.resolveAll(sc).reverse(),d=null;for(let f of l)if(d=f.toAsnSignature(o,u),d)break;if(!d)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return i.signature=d,new v2(te.AsnConvert.serialize(i))}};jn.register(ee.id_ce_basicConstraints,Ox);jn.register(ee.id_ce_extKeyUsage,Nx);jn.register(ee.id_ce_keyUsage,Bx);jn.register(ee.id_ce_subjectKeyIdentifier,$x);jn.register(ee.id_ce_authorityKeyIdentifier,Rx);jn.register(ee.id_ce_subjectAltName,Mx);jn.register(ee.id_ce_cRLDistributionPoints,zx);jn.register(ee.id_pe_authorityInfoAccess,Lx);jn.register(ee.id_ce_issuerAltName,Dx);Dd.register(Vp.id_pkcs9_at_challengePassword,Ux);Dd.register(Vp.id_pkcs9_at_extensionRequest,Gp);kr.container.registerSingleton(sc,b2);kr.container.registerSingleton(sc,ia);ia.namedCurveSize.set("P-256",32);ia.namedCurveSize.set("K-256",32);ia.namedCurveSize.set("P-384",48);ia.namedCurveSize.set("P-521",66);xe.AlgorithmProvider=y2;xe.AsnData=na;xe.AsnDefaultSignatureFormatter=b2;xe.AsnEcSignatureFormatter=ia;xe.Attribute=Ld;xe.AttributeFactory=Dd;xe.AuthorityInfoAccessExtension=Lx;xe.AuthorityKeyIdentifierExtension=Rx;xe.BasicConstraintsExtension=Ox;xe.CRLDistributionPointsExtension=zx;xe.CertificatePolicyExtension=jx;xe.ChallengePasswordAttribute=Ux;xe.CryptoProvider=Kp;xe.DN=o2;xe.DNS=i2;xe.DefaultAlgorithmSerializer=x2;xe.EMAIL=a2;xe.ExtendedKeyUsageExtension=Nx;xe.Extension=zs;xe.ExtensionFactory=jn;xe.ExtensionsAttribute=Gp;xe.GUID=l2;xe.GeneralName=oo;xe.GeneralNames=sa;xe.IP=c2;xe.IssuerAlternativeNameExtension=Dx;xe.KeyUsagesExtension=Bx;xe.Name=Tn;xe.NameIdentifier=Ix;xe.OidSerializer=Ni;xe.PemConverter=Mn;xe.PemData=Ds;xe.Pkcs10CertificateRequest=qx;xe.Pkcs10CertificateRequestGenerator=k3;xe.PublicKey=ao;xe.REGISTERED_ID=tx;xe.SubjectAlternativeNameExtension=Mx;xe.SubjectKeyIdentifierExtension=$x;xe.TextConverter=uo;xe.TextObject=Dt;xe.UPN=d2;xe.URL=u2;xe.X509Certificate=Su;xe.X509CertificateGenerator=I3;xe.X509Certificates=_2;xe.X509ChainBuilder=T3;xe.X509Crl=v2;xe.X509CrlEntry=Wp;xe.X509CrlGenerator=P3;xe.cryptoProvider=Dr;xe.diAlgorithm=Xp;xe.diAlgorithmProvider=co;xe.diAsnSignatureFormatter=sc;xe.idEd25519=p2;xe.idEd448=C3;xe.idX25519=h2;xe.idX448=E3});var CU=v((W3e,EU)=>{"use strict";function Xle(t){return/^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(t)}EU.exports=Xle});var Fx=v((X3e,$U)=>{var kU=on("util"),RU=CU(),TU=/[\{\[]/,IU=/[\}\]]/,PU=["do","if","in","for","let","new","try","var","case","else","enum","eval","null","this","true","void","with","await","break","catch","class","const","false","super","throw","while","yield","delete","export","import","public","return","static","switch","typeof","default","extends","finally","package","private","continue","debugger","function","arguments","interface","protected","implements","instanceof","NaN","undefined"],OU={};for(w2=0;w2<PU.length;w2++)OU[PU[w2]]=!0;var w2,Jle=function(t){return RU(t)&&!OU.hasOwnProperty(t)},NU={s:function(t){return""+t},d:function(t){return""+Number(t)},o:function(t){return JSON.stringify(t)}},BU=function(){var t=[],e=0,r={},n=function(o){for(var a="";a.length<e*2;)a+=" ";t.push(a+o)},s=function(o){if(IU.test(o.trim()[0])&&TU.test(o[o.length-1])){e--,n(o),e++;return}if(TU.test(o[o.length-1])){n(o),e++;return}if(IU.test(o.trim()[0])){e--,n(o);return}n(o)},i=function(o){if(!o)return i;if(arguments.length===1&&o.indexOf(`
|
|
88
|
+
`)>-1)for(var a=o.trim().split(`
|
|
89
|
+
`),c=0;c<a.length;c++)s(a[c].trim());else s(kU.format.apply(kU,arguments));return i};return i.scope={},i.formats=NU,i.sym=function(o){return(!o||!Jle(o))&&(o="tmp"),r[o]||(r[o]=0),o+(r[o]++||"")},i.property=function(o,a){return arguments.length===1&&(a=o,o=""),a=a+"",RU(a)?o?o+"."+a:a:o?o+"["+JSON.stringify(a)+"]":JSON.stringify(a)},i.toString=function(){return t.join(`
|
|
90
|
+
`)},i.toFunction=function(o){o||(o={});var a="return ("+i.toString()+")";Object.keys(i.scope).forEach(function(l){o[l]||(o[l]=i.scope[l])});var c=Object.keys(o).map(function(l){return l}),u=c.map(function(l){return o[l]});return Function.apply(null,c.concat(a)).apply(null,u)},arguments.length&&i.apply(null,arguments),i};BU.formats=NU;$U.exports=BU});var jU=v((J3e,MU)=>{"use strict";var A2=class{constructor(){this.next=null,this.buffer=null}};MU.exports=class S2{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let r=new A2;r.buffer=e,this.length>0?this.tail.next=r:this.head=r,this.tail=r,this.length+=e.length,this.count+=1}unshift(e){let r=new A2;r.buffer=e,r.next=this.head,this.isEmpty()&&(this.tail=r),this.head=r,this.length+=e.length,this.count+=1}shift(){if(this.isEmpty())return null;let e=this.head.buffer;return this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.length-=e.length,this.length=Math.max(this.length,0),this.count-=1,e}get first(){return this.isEmpty()?null:this.head.buffer}get last(){return this.isEmpty()?null:this.tail.buffer}isEmpty(){return this.length===0}clear(){this.head=null,this.tail=null,this.length=0,this.count=0}slice(e,r){if(e<0||e>=this.length)return new S2;if(r<0||r>this.length||r<e)return new S2;let n=new S2,s=this.head,i=e,o=r;for(;s;){if(s.buffer.length>i){i===0&&s.buffer.length<=o?n.push(s.buffer):s.buffer.length>=o?n.push(s.buffer.slice(i,o)):n.push(s.buffer.slice(i));break}i-=s.buffer.length,o-=s.buffer.length,s=s.next}if(s.buffer.length<o)for(;s;){if(s.buffer.length===o){n.push(s.buffer);break}else if(s.buffer.length>o){n.push(s.buffer.slice(0,o));break}else i<0&&s.buffer.length<o&&n.push(s.buffer);i-=s.buffer.length,o-=s.buffer.length,s=s.next}return n}}});var UU=v((Y3e,DU)=>{"use strict";var E2=Fx(),Yle=jU(),Ud=class t{constructor(){this.queue=new Yle,this.offset=0}get length(){return this.queue.length-this.offset}append(e){if(Buffer.isBuffer(e)){if(this.offset>0){let r=this.queue.shift();this.queue.unshift(r.slice(this.offset)),this.offset=0}this.queue.push(e)}else if(Array.isArray(e))for(let r=0;r<e.length;r+=1)this.append(e[r]);else if(e instanceof t){if(this.offset>0){let n=this.queue.shift();this.queue.unshift(n.slice(this.offset)),this.offset=0}if(e.offset>0){let n=e.queue.shift();e.queue.unshift(n.slice(e.offset)),e.offset=0}let r=e.queue.head;for(;r;)this.queue.push(r.buffer),r=r.next}}get(e){let r=e;for(;r>=this.length;)r-=this.length;for(;r<0;)r+=this.length;let n=this.queue.head,{offset:s}=this;for(;n;){if(n.buffer.length-s>r)return n.buffer[r+s];r-=n.buffer.length-s,s=0,n=n.next}}slice(e,r){for(typeof e!="number"&&(e=0),typeof r!="number"&&(r=this.length);e<0;)e+=this.length;for(;r<0;)r+=this.length;if(r=Math.min(r,this.length),e>=this.length||r===0)return Buffer.alloc(0);let n=e;e=Math.min(n,r),r=Math.max(n,r);let s=this.queue.slice(e+this.offset,r+this.offset);if(s.count===1)return s.first;let i=s.head,o=Buffer.allocUnsafe(s.length),a=0;for(let c=0;c<s.count;c+=1)o.set(i.buffer,a),a+=i.buffer.length,i=i.next;return o}toString(e,r,n){return this.slice(r,n).toString(e)}consume(e){let r=e;for(;this.length>0;){let n=this.queue.first.length-this.offset;if(r>=n)this.queue.shift(),r-=n,this.offset=0;else{this.offset+=r;break}}}indexOf(e,r=0){if(!Number.isInteger(e))throw new TypeError("Invalid argument 1");if(e<0||e>255)throw new Error("Invalid argument 1");for(Number.isInteger(r)||(r=0);r>=this.length;)r-=this.length;for(;r<0;)r+=this.length;let n=this.queue.head,s=0,i=()=>{s+=n.buffer.length,n=n.next};for(;n;){let o=0;if(n===this.queue.head&&(o+=this.offset),r>=n.buffer.length-o){r-=n.buffer.length-o,i();continue}r<n.buffer.length&&(o+=r);let a=n.buffer.indexOf(e,o);if(a>-1)return a+s-this.offset;i(),o>this.offset&&(r=0)}return-1}},zU={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys(zU).forEach(t=>{let e=E2();e(`
|
|
91
|
+
function bufferlist_${t}(offset = 0) {
|
|
92
|
+
const start = offset + this.offset;
|
|
93
|
+
const head = this.queue.first;
|
|
94
|
+
const size = ${e.formats.d(zU[t])};
|
|
95
|
+
const isFirtsChunkEnough = head.length - start >= size;
|
|
96
|
+
|
|
97
|
+
return isFirtsChunkEnough
|
|
98
|
+
? head.${t}(start)
|
|
99
|
+
: this.slice(offset, offset + size).${t}(0)
|
|
100
|
+
}
|
|
101
|
+
`),Ud.prototype[t]=e.toFunction()});var Qle=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Qle.forEach(t=>{let e=E2();e(`
|
|
102
|
+
function bufferlist_${t}(size, offset = 0) {
|
|
103
|
+
const start = offset + this.offset;
|
|
104
|
+
const head = this.queue.first;
|
|
105
|
+
const isFirtsChunkEnough = head.length - start >= size;
|
|
106
|
+
|
|
107
|
+
return isFirtsChunkEnough
|
|
108
|
+
? head.${t}(start, size)
|
|
109
|
+
: this.slice(offset, offset + size).${t}(0, size)
|
|
110
|
+
}
|
|
111
|
+
`),Ud.prototype[t]=e.toFunction()});var LU={writeDoubleBE:8,writeDoubleLE:8,writeFloatBE:4,writeFloatLE:4,writeInt32BE:4,writeInt32LE:4,writeUInt32BE:4,writeUInt32LE:4,writeInt16BE:2,writeInt16LE:2,writeUInt16BE:2,writeUInt16LE:2,writeInt8:1,writeUInt8:1};Object.keys(LU).forEach(t=>{let e=E2();e(`
|
|
112
|
+
function bufferlist_${t}(value) {
|
|
113
|
+
const size = ${e.formats.d(LU[t])};
|
|
114
|
+
const buf = Buffer.allocUnsafe(size);
|
|
115
|
+
buf.${t}(value, 0);
|
|
116
|
+
this.append(buf);
|
|
117
|
+
}
|
|
118
|
+
`),Ud.prototype[t]=e.toFunction()});var ede=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];ede.forEach(t=>{let e=E2();e(`
|
|
119
|
+
function bufferlist_${t}(value, size) {
|
|
120
|
+
const buf = Buffer.allocUnsafe(size);
|
|
121
|
+
buf.${t}(value, 0, size);
|
|
122
|
+
this.append(buf);
|
|
123
|
+
}
|
|
124
|
+
`),Ud.prototype[t]=e.toFunction()});DU.exports=Ud});var Jp=v((ePe,qU)=>{"use strict";qU.exports=class extends Error{constructor(e,r){let n=`requested ${e} bytes but only ${r} available`;super(n),this.name="NotEnoughDataError"}}});var Vx=v((tPe,VU)=>{"use strict";var{Transform:tde}=on("stream"),C2=Fx(),rde=UU(),nde=Jp(),HU=Symbol("buffer"),qd=class extends tde{constructor(e={}){super(e),this[HU]=new rde}get buffer(){return this[HU]}get length(){return this.buffer.length}append(e){this.buffer.append(e)}get(e){return this.buffer.get(e)}slice(e,r){return this.buffer.slice(e,r)}consume(e){this.buffer.consume(e)}toString(e,r,n){return this.buffer.toString(e,r,n)}indexOf(e,r=0){return this.buffer.indexOf(e,r)}readBuffer(e){N3(e,this.length);let r=this.slice(0,e);return this.consume(e),r}writeBuffer(e){this.append(e)}},FU={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1},sde=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Object.keys(FU).forEach(t=>{let e=C2();e(`
|
|
125
|
+
function binary_${t}() {
|
|
126
|
+
const bytes = ${e.formats.d(FU[t])};
|
|
127
|
+
assertSize(bytes, this.length);
|
|
128
|
+
|
|
129
|
+
const res = this.buffer.${t}(0);
|
|
130
|
+
this.consume(bytes);
|
|
131
|
+
|
|
132
|
+
return res;
|
|
133
|
+
}
|
|
134
|
+
`),qd.prototype[t]=e.toFunction({assertSize:N3})});sde.forEach(t=>{let e=C2();e(`
|
|
135
|
+
function binary_${t}(size) {
|
|
136
|
+
assertSize(size, this.length);
|
|
137
|
+
|
|
138
|
+
const res = this.buffer.${t}(size, 0);
|
|
139
|
+
this.consume(size);
|
|
140
|
+
return res;
|
|
141
|
+
}
|
|
142
|
+
`),qd.prototype[t]=e.toFunction({assertSize:N3})});var ide=["writeDoubleBE","writeDoubleLE","writeFloatBE","writeFloatLE","writeInt32BE","writeInt32LE","writeUInt32BE","writeUInt32LE","writeInt16BE","writeInt16LE","writeUInt16BE","writeUInt16LE","writeInt8","writeUInt8"];ide.forEach(t=>{let e=C2();e(`
|
|
143
|
+
function binary_${t}(value) {
|
|
144
|
+
this.buffer.${t}(value);
|
|
145
|
+
}
|
|
146
|
+
`),qd.prototype[t]=e.toFunction()});var ode=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];ode.forEach(t=>{let e=C2();e(`
|
|
147
|
+
function binary_${t}(value, size) {
|
|
148
|
+
this.buffer.${t}(value, size);
|
|
149
|
+
}
|
|
150
|
+
`),qd.prototype[t]=e.toFunction()});function N3(t,e){if(t>e)throw new nde(t,e)}VU.exports=qd});var ZU=v((rPe,KU)=>{"use strict";KU.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var XU=v((nPe,WU)=>{"use strict";var ade=ZU();function GU(t){return ade(t)===!0&&Object.prototype.toString.call(t)==="[object Object]"}WU.exports=function(e){var r,n;return!(GU(e)===!1||(r=e.constructor,typeof r!="function")||(n=r.prototype,GU(n)===!1)||n.hasOwnProperty("isPrototypeOf")===!1)}});var oa=v((sPe,JU)=>{"use strict";var cde=XU();JU.exports={isType:ude,isUserType:cde,isFunction:Kx,isDecodeType:lde,isEncodeType:dde};function ude(t){return B3(t)&&Kx(t.encode)&&Kx(t.decode)}function Kx(t){return typeof t=="function"}function B3(t){return typeof t=="object"&&t!==null}function lde(t){return B3(t)&&Kx(t.decode)}function dde(t){return B3(t)&&Kx(t.encode)}});var Au=v((iPe,YU)=>{"use strict";var fde=Symbol("skip"),hde=Symbol("bytes");YU.exports={skip:fde,bytes:hde}});var Eu=v((oPe,eq)=>{"use strict";var QU=Au();eq.exports=class k2{constructor(){this[QU.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[QU.bytes]}static clone(e){let r=new k2;return e instanceof k2&&(r.node=e.node,r.current=e.current),r}static clean(e){e instanceof k2&&(e.node=void 0,e.current=void 0)}}});var Yp=v((aPe,iq)=>{"use strict";var{isType:pde,isUserType:mde,isDecodeType:gde}=oa(),yde=Vx(),$3=Au(),tq=Eu();iq.exports={decode:rq,decodeCommon:nq};function rq(t,e){let r=t;Buffer.isBuffer(t)&&(r=new yde,r.append(t));let n=new tq,s=nq(r,e,n);return rq.bytes=n.bytes,tq.clean(n),s}function nq(t,e,r){if(pde(e)){let n=e.decode.call(r,t);return r[$3.bytes]+=e.decode.bytes,n}return sq(t,e,r)}function sq(t,e,r){xde(e);let n=Object.create(null);r.node===void 0&&(r.node=n),r.current=n;let s=Object.keys(e);for(let i=0;i<s.length;i+=1){let o=s[i],a=e[o];if(!gde(a)){n[o]=sq(t,a,r),r.current=n;continue}let c=a.decode.call(r,t);r[$3.bytes]+=a.decode.bytes,a[$3.skip]!==!0&&(n[o]=c)}return n}function xde(t){if(!mde(t))throw new TypeError("Argument #2 should be a plain object.")}});var Zx=v((cPe,dq)=>{"use strict";var{isUserType:bde,isEncodeType:_de,isType:vde}=oa(),aq=Au(),oq=Eu(),M3=Vx();dq.exports={encode:cq,encodeCommon:uq};function cq(t,e,r){let n=new oq;if(e instanceof M3){let s=r;r=e,e=s}return r instanceof M3||(r=new M3),uq(t,r,e,n),cq.bytes=n.bytes,oq.clean(n),r}function uq(t,e,r,n){vde(r)?(r.encode.call(n,t,e),n[aq.bytes]+=r.encode.bytes):lq(t,e,r,n)}function lq(t,e,r,n){wde(r),n.node===void 0&&(n.node=t),n.current=t;let s=Object.keys(r);for(let i=0;i<s.length;i+=1){let o=s[i],a=r[o],c=t[o];if(!_de(a)){lq(c,e,a,n),n.current=t;continue}a.encode.call(n,c,e),n[aq.bytes]+=a.encode.bytes}}function wde(t){if(!bde(t))throw new TypeError("Argument `schema` should be a plain object.")}});var Gx=v((uPe,yq)=>{"use strict";var{isUserType:Sde,isType:hq}=oa(),fq=Eu(),pq=Au();yq.exports={encodingLength:Ade,encodingLengthCommon:mq};function Ade(t,e){let r=new fq;return mq(t,e,r),fq.clean(r),r.bytes}function mq(t,e,r){hq(e)?r[pq.bytes]+=e.encodingLength.call(r,t):gq(t,e,r)}function gq(t,e,r){if(!Sde(e))throw new TypeError("Argument `schema` should be a plain object.");r.node===void 0&&(r.node=t),r.current=t;let n=Object.keys(e);for(let s=0;s<n.length;s+=1){let i=n[s],o=e[i],a=t[i];if(!hq(o)){gq(a,o,r),r.current=t;continue}r[pq.bytes]+=o.encodingLength.call(r,a)}}});var Eq=v((lPe,Aq)=>{"use strict";var{decodeCommon:Sq}=Yp(),{encodeCommon:Ede}=Zx(),{encodingLengthCommon:xq}=Gx(),{isType:bq,isUserType:Cde,isFunction:kde}=oa(),Cu=Eu();Aq.exports=Tde;function Tde(t,e,r="count"){if(!bq(t)&&!Cde(t))throw new TypeError("Argument #1 should be a valid type.");let n=r==="bytes",s=typeof e=="number",i=bq(e),o=kde(e);if(!s&&!i&&!o)throw new TypeError("Unknown type of argument #1.");return{encode:a,decode:c,encodingLength:u};function a(l,d){_q(l);let f=Cu.clone(this);a.bytes=0;let p=0;if(i?p=l.length:s?p=e:o&&(p=e(f),vq(p)),n||wq(p,l.length),n){let m=Cu.clone(f);for(let y of l)xq(y,t,m);i&&(p=m.bytes),wq(m.bytes,p),Cu.clean(m)}i&&(e.encode.call(f,p,d),a.bytes+=e.encode.bytes),l.forEach(m=>{Ede(m,d,t,f)}),a.bytes+=f.bytes,Cu.clean(f)}function c(l){let d=0;c.bytes=0;let f=Cu.clone(this);s?d=e:i?(d=e.decode.call(f,l),c.bytes+=e.decode.bytes):o&&(d=e(f)),vq(d);let p;return n?p=Ide(t,d,l,f):p=Pde(t,d,l,f),c.bytes+=f.bytes,Cu.clean(f),p}function u(l){_q(l);let d=Cu.clone(this),f=0;if(s&&n)return e;i&&!n&&(f=e.encodingLength(l.length));for(let p of l)xq(p,t,d);return Cu.clean(d),f+=d.bytes,i&&n&&(f+=e.encodingLength(f)),f}}function _q(t){if(!Array.isArray(t))throw new TypeError("Argument #1 should be an Array.")}function vq(t){if(typeof t!="number")throw new TypeError("Length of an array should be a number.")}function wq(t,e){if(t!==e)throw new Error(`Argument #1 required length ${t} instead of ${e}`)}function Ide(t,e,r,n){let s=[],i=n.bytes,o=0;for(;o<e;)s.push(Sq(r,t,n)),o=n.bytes-i;if(o>e)throw new Error("Incorrect length of an array.");return s}function Pde(t,e,r,n){let s=new Array(e);for(let i=0;i<e;i+=1)s[i]=Sq(r,t,n);return s}});var Iq=v((dPe,Tq)=>{"use strict";var{isType:Rde,isFunction:Ode}=oa(),Nde=Jp(),Bde=Vx();Tq.exports=$de;function $de(t){let e=typeof t=="number",r=Rde(t),n=Ode(t),s=t===null;if(!e&&!r&&!n&&!s)throw new TypeError("Unknown type of argument #1.");return{encode:i,decode:o,encodingLength:a};function i(c,u){Cq(c),i.bytes=0;let l=this;if(e&&kq(t,c.length),r&&(t.encode.call(l,c.length,u),i.bytes+=t.encode.bytes),n){let d=t(l);j3(d),kq(d,c.length)}u.writeBuffer(Buffer.isBuffer(c)?c:c.buffer),i.bytes+=c.length,s&&(u.writeUInt8(0),i.bytes+=1)}function o(c){let u=0;o.bytes=0;let l=this;if(e)u=t;else if(r)u=t.decode.call(l,c),o.bytes+=t.decode.bytes,j3(u);else if(n)u=t(l),j3(u);else if(s&&(u=c.indexOf(0),u===-1))throw new Nde(c.length+1,c.length);let d=c.readBuffer(u);return o.bytes+=u,s&&(o.bytes+=1,c.consume(1)),d}function a(c){Cq(c);let u=0;return e?t:(s?u=1:r&&(u=t.encodingLength(c.length)),u+c.length)}}function Cq(t){if(!Buffer.isBuffer(t)&&!(t instanceof Bde))throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.")}function kq(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}function j3(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}});var Rq=v((fPe,Pq)=>{"use strict";var{isType:Mde}=oa();Pq.exports=jde;function jde(t){if(!Mde(t))throw new TypeError("Argument #1 should be valid type.");function e(n){let s=this,i=t.decode.call(s,n);return e.bytes=t.decode.bytes,!!i}function r(n,s){let i=this;t.encode.call(i,n?1:0,s),r.bytes=t.encode.bytes}return{encode:r,decode:e,encodingLength:t.encodingLength}}});var Nq=v((hPe,Oq)=>{"use strict";var{decodeCommon:zde}=Yp(),{encodeCommon:Lde}=Zx(),{encodingLengthCommon:Dde}=Gx(),{isType:Ude,isFunction:T2}=oa(),qde=Au(),ku=Eu();Oq.exports=Hde;function Hde(t,e=1){if(!Ude(t))throw new TypeError("Invalid data type.");if(!Number.isInteger(e)&&!T2(e))throw new TypeError("Argument #2 should be a valid integer or function.");return{[qde.skip]:!0,encodingLength:r,decode:n,encode:s};function r(i){let o=ku.clone(this),a=T2(e)?e(o):e;return Dde(i,t,o),ku.clean(o),o.bytes*a}function n(i){let o=ku.clone(this);n.bytes=0;let a=T2(e)?e(o):e;if(a===0){ku.clean(o);return}for(let c=a;c>0;c-=1)zde(i,t,o);n.bytes=o.bytes,ku.clean(o)}function s(i,o){s.bytes=0;let a=ku.clone(this),c=T2(e)?e(a):e;if(c===0){ku.clean(a);return}for(let u=c;u>0;u-=1)Lde(0,o,t,a);s.bytes=a.bytes,ku.clean(a)}}});var Mq=v((pPe,$q)=>{"use strict";var{isType:Fde}=oa(),Vde=Jp();$q.exports=Kde;function Kde(t,e="ascii"){if(!Buffer.isEncoding(e))throw new Error("Argument #2 should be an encoding name.");if(typeof t=="number")return{encode:Wde(t,e),decode:Xde(t,e),encodingLength:()=>t};if(Fde(t))return{encode:Jde(t,e),decode:Yde(t,e),encodingLength:Qde(t,e)};if(t===null)return{encode:Zde(e),decode:Gde(e),encodingLength(r){return Buffer.byteLength(r,e)+1}};if(typeof t=="function")return{encode:efe(t,e),decode:tfe(t,e),encodingLength(r){return Buffer.byteLength(r,e)}};throw new TypeError("Unknown type of argument #1.")}function Zde(t){return function e(r,n){let s=Buffer.from(r.toString(),t);n.writeBuffer(s),n.writeInt8(0),e.bytes=s.length+1}}function Gde(t){return function e(r){let n=r.indexOf(0);if(n===-1)throw new Vde(r.length+1,r.length);let s=n+1,i=r.readBuffer(s);return e.bytes=s,i.toString(t,0,n)}}function Wde(t,e){return function r(n,s){if(n=n.toString(),Buffer.byteLength(n,e)!==t)throw new Error(`Size of string should be ${t} in bytes.`);let i=Buffer.from(n,e);s.writeBuffer(i),r.bytes=i.length}}function Xde(t,e){return function r(n){let s=n.readBuffer(t);return r.bytes=t,s.toString(e)}}function Jde(t,e){return function r(n,s){n=n.toString();let i=this;t.encode.call(i,Buffer.byteLength(n,e),s),r.bytes=t.encode.bytes;let o=Buffer.from(n,e);s.writeBuffer(o),r.bytes+=o.length}}function Yde(t,e){return function r(n){let s=t.decode.call(this,n);if(typeof s!="number")throw new TypeError("Size of a string should be a number.");let i=n.readBuffer(s);return r.bytes=t.decode.bytes+i.length,i.toString(e)}}function Qde(t,e){return function(n){let s=Buffer.byteLength(n,e);return t.encodingLength(s)+s}}function efe(t,e){return function r(n,s){r.bytes=0;let o=t(this),a=Buffer.from(n.toString(),e);Bq(o),rfe(o,a.length),s.writeBuffer(a),r.bytes+=a.length}}function tfe(t,e){return function r(n){let s=t(this);Bq(s);let i=n.readBuffer(s);return r.bytes=s,i.toString(e)}}function Bq(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}function rfe(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}});var zq=v((mPe,jq)=>{"use strict";var I2=Fx();jq.exports={doublebe:qs(8,"writeDoubleBE","readDoubleBE"),doublele:qs(8,"writeDoubleLE","readDoubleLE"),floatbe:qs(4,"writeFloatBE","readFloatBE"),floatle:qs(4,"writeFloatLE","readFloatLE"),int8:qs(1,"writeInt8","readInt8"),uint8:qs(1,"writeUInt8","readUInt8"),int16be:qs(2,"writeInt16BE","readInt16BE"),uint16be:qs(2,"writeUInt16BE","readUInt16BE"),int16le:qs(2,"writeInt16LE","readInt16LE"),uint16le:qs(2,"writeUInt16LE","readUInt16LE"),int32be:qs(4,"writeInt32BE","readInt32BE"),uint32be:qs(4,"writeUInt32BE","readUInt32BE"),int32le:qs(4,"writeInt32LE","readInt32LE"),uint32le:qs(4,"writeUInt32LE","readUInt32LE"),int24be:Bi(3,"writeIntBE","readIntBE"),uint24be:Bi(3,"writeUIntBE","readUIntBE"),int24le:Bi(3,"writeIntLE","readIntLE"),uint24le:Bi(3,"writeUIntLE","readUIntLE"),int40be:Bi(5,"writeIntBE","readIntBE"),uint40be:Bi(5,"writeUIntBE","readUIntBE"),int40le:Bi(5,"writeIntLE","readIntLE"),uint40le:Bi(5,"writeUIntLE","readUIntLE"),int48be:Bi(6,"writeIntBE","readIntBE"),uint48be:Bi(6,"writeUIntBE","readUIntBE"),int48le:Bi(6,"writeIntLE","readIntLE"),uint48le:Bi(6,"writeUIntLE","readUIntLE")};function qs(t,e,r){let n=I2(),s=I2();return n(`
|
|
151
|
+
function decode_${r}(rstream) {
|
|
152
|
+
decode_${r}.bytes = ${n.formats.d(t)};
|
|
153
|
+
return rstream.${r}()
|
|
154
|
+
}
|
|
155
|
+
`),s(`
|
|
156
|
+
function encode_${e}(value, wstream) {
|
|
157
|
+
wstream.${e}(value);
|
|
158
|
+
encode_${e}.bytes = ${n.formats.d(t)};
|
|
159
|
+
}
|
|
160
|
+
`),{encodingLength:()=>t,encode:s.toFunction(),decode:n.toFunction()}}function Bi(t,e,r){let n=I2(),s=I2();return n(`
|
|
161
|
+
function decode_${r}(rstream) {
|
|
162
|
+
decode_${r}.bytes = ${n.formats.d(t)};
|
|
163
|
+
return rstream.${r}(${n.formats.d(t)})
|
|
164
|
+
}
|
|
165
|
+
`),s(`
|
|
166
|
+
function encode_${e}(value, wstream) {
|
|
167
|
+
wstream.${e}(value, ${n.formats.d(t)});
|
|
168
|
+
encode_${e}.bytes = ${n.formats.d(t)};
|
|
169
|
+
}
|
|
170
|
+
`),{encodingLength:()=>t,encode:s.toFunction(),decode:n.toFunction()}}});var Dq=v((gPe,Lq)=>{"use strict";var{isType:nfe,isFunction:z3,isUserType:sfe}=oa(),L3=Au(),{decodeCommon:ife}=Yp(),{encodeCommon:ofe}=Zx(),{encodingLengthCommon:afe}=Gx(),Tu=Eu();Lq.exports=cfe;function cfe(t,e){if(!nfe(e)&&!sfe(e))throw new TypeError("Argument #2 should be a valid type.");let r={encode:n,decode:s,encodingLength:i,[L3.skip]:!1};return r;function n(o,a){let c=Tu.clone(this);n.bytes=0;let u=z3(t)?!!t(c):!!t;if(r[L3.skip]=!u,!u){Tu.clean(c);return}ofe(o,a,e,c),n.bytes=c.bytes,Tu.clean(c)}function s(o){let a=Tu.clone(this);s.bytes=0;let c=z3(t)?!!t(a):!!t;if(r[L3.skip]=!c,!c){Tu.clean(a);return}let u=ife(o,e,a);return s.bytes=a.bytes,Tu.clean(a),u}function i(o){let a=Tu.clone(this);return(z3(t)?t(a):t)&&afe(o,e,a),Tu.clean(a),a.bytes}}});var Hq=v((yPe,qq)=>{"use strict";var P2=Au(),{decodeCommon:ufe}=Yp(),Uq=Eu();qq.exports=lfe;function lfe(...t){if(t.length===0)throw new TypeError("You should set at least one condition type.");let e={decode:r,encode:()=>{},[P2.skip]:!0};return e;function r(n){r.bytes=0;let s=Uq.clone(this);for(let i of t){let o=ufe(n,i,s);if(i[P2.skip]!==!0)return r.bytes=s.bytes,Uq.clean(s),e[P2.skip]=!1,o}e[P2.skip]=!0}}});var Zq=v((xPe,Kq)=>{"use strict";var Vq=Fx(),dfe=Jp(),Wx=class{constructor(e){this.stream=e,this.index=0}append(e){this.stream.append(e)}commit(){this.stream.consume(this.index)}get(e=0){return this.stream.get(this.index+e)}get length(){return this.stream.length}slice(e,r){return this.stream.slice(e,r)}toString(e,r,n){return this.stream.toString(e,r,n)}readBuffer(e){D3(this.index+e,this.length);let r=this.stream.slice(this.index,this.index+e);return this.index+=e,r}indexOf(e,r=0){return this.stream.indexOf(e,this.index+r)-this.index}},Fq={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys(Fq).forEach(t=>{let e=Vq(),r=Fq[t];e(`
|
|
171
|
+
function transaction_${t}() {
|
|
172
|
+
assertSize(this.index + ${e.formats.d(r)}, this.length);
|
|
173
|
+
const value = this.stream.buffer.${t}(this.index);
|
|
174
|
+
this.index += ${e.formats.d(r)};
|
|
175
|
+
return value;
|
|
176
|
+
}
|
|
177
|
+
`),Wx.prototype[t]=e.toFunction({assertSize:D3})});["readIntBE","readIntLE","readUIntBE","readUIntLE"].forEach(t=>{let e=Vq();e(`
|
|
178
|
+
function transaction_${t}(bytes) {
|
|
179
|
+
assertSize(this.index + bytes, this.length);
|
|
180
|
+
const value = this.stream.buffer.${t}(bytes, this.index);
|
|
181
|
+
this.index += bytes;
|
|
182
|
+
return value;
|
|
183
|
+
}
|
|
184
|
+
`),Wx.prototype[t]=e.toFunction({assertSize:D3})});Kq.exports=Wx;function D3(t,e){if(t>e)throw new dfe(t,e)}});var Kr=v((bPe,tH)=>{"use strict";var U3=Vx(),ffe=Eq(),hfe=Iq(),pfe=Rq(),mfe=Nq(),gfe=Mq(),Gq=zq(),yfe=Dq(),xfe=Hq(),{encode:Jq}=Zx(),{decode:Yq}=Yp(),{encodingLength:bfe}=Gx(),_fe=Zq(),Qq=Jp(),eH={array:ffe,bool:pfe,buffer:hfe,reserved:mfe,string:gfe,when:yfe,select:xfe};for(let t of Object.keys(Gq))eH[t]=Gq[t];var R2=Symbol("schema");function Wq(t){let e=new U3({readableObjectMode:!1,writableObjectMode:!0,transform:vfe});return e[R2]=t,e}function Xq(t){let e=null,r=Buffer.isBuffer(t);r||(e=t);let n=new U3({transform:wfe,readableObjectMode:!0,writableObjectMode:!1});return n[R2]=e,r&&n.append(t),n}function vfe(t,e,r){try{Jq(t,this[R2],this);let n=this.slice();this.consume(n.length),r(null,n)}catch(n){r(n)}}function wfe(t,e,r){this.append(t);try{for(;this.length>0;){let n=new _fe(this),s=Yq(n,this[R2]);n.commit(),this.push(s)}r()}catch(n){n instanceof Qq?r():r(n)}}tH.exports={createEncodeStream:Wq,createDecodeStream:Xq,encode:Jq,decode:Yq,encodingLength:bfe,createEncode:Wq,createDecode:Xq,types:eH,BinaryStream:U3,NotEnoughDataError:Qq}});import*as ic from"node:crypto";var Hd,rH=mr(()=>{Hd=ic&&typeof ic=="object"&&"webcrypto"in ic?ic.webcrypto:ic&&typeof ic=="object"&&"randomBytes"in ic?ic:void 0});function Fd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Xx(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function lo(t,...e){if(!Fd(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function O2(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Xx(t.outputLen),Xx(t.blockLen)}function e0(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function sH(t,e){lo(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ac(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function N2(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function fo(t,e){return t<<32-e|t>>>e}function cc(t){if(lo(t),iH)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Sfe[t[r]];return e}function nH(t){if(t>=oc._0&&t<=oc._9)return t-oc._0;if(t>=oc.A&&t<=oc.F)return t-(oc.A-10);if(t>=oc.a&&t<=oc.f)return t-(oc.a-10)}function Vd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(iH)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let s=0,i=0;s<r;s++,i+=2){let o=nH(t.charCodeAt(i)),a=nH(t.charCodeAt(i+1));if(o===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function oH(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Jx(t){return typeof t=="string"&&(t=oH(t)),lo(t),t}function ho(...t){let e=0;for(let n=0;n<t.length;n++){let s=t[n];lo(s),e+=s.length}let r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){let i=t[n];r.set(i,s),s+=i.length}return r}function B2(t){let e=n=>t().update(Jx(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function $2(t=32){if(Hd&&typeof Hd.getRandomValues=="function")return Hd.getRandomValues(new Uint8Array(t));if(Hd&&typeof Hd.randomBytes=="function")return Uint8Array.from(Hd.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}var iH,Sfe,oc,Qp,Kd=mr(()=>{rH();iH=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Sfe=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));oc={_0:48,_9:57,A:65,F:70,a:97,f:102};Qp=class{}});function Yx(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Iu(t,e,r=""){let n=Fd(t),s=t?.length,i=e!==void 0;if(!n||i&&s!==e){let o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Qx(t){let e=t.toString(16);return e.length&1?"0"+e:e}function aH(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?F3:BigInt("0x"+t)}function t0(t){return aH(cc(t))}function V3(t){return lo(t),aH(cc(Uint8Array.from(t).reverse()))}function M2(t,e){return Vd(t.toString(16).padStart(e*2,"0"))}function K3(t,e){return M2(t,e).reverse()}function cs(t,e,r){let n;if(typeof e=="string")try{n=Vd(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Fd(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let s=n.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return n}function cH(t,e,r){return q3(t)&&q3(e)&&q3(r)&&e<=t&&t<r}function uH(t,e,r,n){if(!cH(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function j2(t){let e;for(e=0;t>F3;t>>=H3,e+=1);return e}function lH(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),s=p=>Uint8Array.of(p),i=n(t),o=n(t),a=0,c=()=>{i.fill(1),o.fill(0),a=0},u=(...p)=>r(o,i,...p),l=(p=n(0))=>{o=u(s(0),p),i=u(),p.length!==0&&(o=u(s(1),p),i=u())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,m=[];for(;p<e;){i=u();let y=i.slice();m.push(y),p+=i.length}return ho(...m)};return(p,m)=>{c(),l(p);let y;for(;!(y=m(d()));)l();return c(),y}}function eb(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(s,i,o){let a=t[s];if(o&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([s,i])=>n(s,i,!1)),Object.entries(r).forEach(([s,i])=>n(s,i,!0))}function Z3(t){let e=new WeakMap;return(r,...n)=>{let s=e.get(r);if(s!==void 0)return s;let i=t(r,...n);return e.set(r,i),i}}var F3,H3,q3,Pu,z2=mr(()=>{Kd();Kd();F3=BigInt(0),H3=BigInt(1);q3=t=>typeof t=="bigint"&&F3<=t;Pu=t=>(H3<<BigInt(t))-H3});function po(t,e){let r=t%e;return r>=Hs?r:e+r}function dH(t,e){if(t===Hs)throw new Error("invert: expected non-zero number");if(e<=Hs)throw new Error("invert: expected positive modulus, got "+e);let r=po(t,e),n=e,s=Hs,i=us,o=us,a=Hs;for(;r!==Hs;){let u=n/r,l=n%r,d=s-o*u,f=i-a*u;n=r,r=l,s=o,i=a,o=d,a=f}if(n!==us)throw new Error("invert: does not exist");return po(s,e)}function G3(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function xH(t,e){let r=(t.ORDER+us)/pH,n=t.pow(e,r);return G3(t,n,e),n}function Cfe(t,e){let r=(t.ORDER-mH)/gH,n=t.mul(e,Zd),s=t.pow(n,r),i=t.mul(e,s),o=t.mul(t.mul(i,Zd),s),a=t.mul(i,t.sub(o,t.ONE));return G3(t,a,e),a}function kfe(t){let e=aa(t),r=bH(t),n=r(e,e.neg(e.ONE)),s=r(e,n),i=r(e,e.neg(n)),o=(t+Afe)/yH;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,n),d=a.mul(u,s),f=a.mul(u,i),p=a.eql(a.sqr(l),c),m=a.eql(a.sqr(d),c);u=a.cmov(u,l,p),l=a.cmov(f,d,m);let y=a.eql(a.sqr(l),c),_=a.cmov(u,l,y);return G3(a,_,c),_}}function bH(t){if(t<hH)throw new Error("sqrt is not defined for small field");let e=t-us,r=0;for(;e%Zd===Hs;)e/=Zd,r++;let n=Zd,s=aa(t);for(;fH(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return xH;let i=s.pow(n,e),o=(e+us)/Zd;return function(c,u){if(c.is0(u))return u;if(fH(c,u)!==1)throw new Error("Cannot find square root");let l=r,d=c.mul(c.ONE,i),f=c.pow(u,e),p=c.pow(u,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let m=1,y=c.sqr(f);for(;!c.eql(y,c.ONE);)if(m++,y=c.sqr(y),m===l)throw new Error("Cannot find square root");let _=us<<BigInt(l-m-1),S=c.pow(d,_);l=m,d=c.sqr(S),f=c.mul(f,d),p=c.mul(p,S)}return p}}function Tfe(t){return t%pH===hH?xH:t%gH===mH?Cfe:t%yH===Efe?kfe(t):bH(t)}function W3(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Ife.reduce((n,s)=>(n[s]="function",n),e);return eb(t,r),t}function Pfe(t,e,r){if(r<Hs)throw new Error("invalid exponent, negatives unsupported");if(r===Hs)return t.ONE;if(r===us)return e;let n=t.ONE,s=e;for(;r>Hs;)r&us&&(n=t.mul(n,s)),s=t.sqr(s),r>>=us;return n}function L2(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function fH(t,e){let r=(t.ORDER-us)/Zd,n=t.pow(e,r),s=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function D2(t,e){e!==void 0&&Xx(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function aa(t,e,r=!1,n={}){if(t<=Hs)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,i,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let f=e;f.BITS&&(s=f.BITS),f.sqrt&&(i=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(s=e),n.sqrt&&(i=n.sqrt);let{nBitLength:c,nByteLength:u}=D2(t,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,d=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:u,MASK:Pu(c),ZERO:Hs,ONE:us,allowedLengths:a,create:f=>po(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return Hs<=f&&f<t},is0:f=>f===Hs,isValidNot0:f=>!d.is0(f)&&d.isValid(f),isOdd:f=>(f&us)===us,neg:f=>po(-f,t),eql:(f,p)=>f===p,sqr:f=>po(f*f,t),add:(f,p)=>po(f+p,t),sub:(f,p)=>po(f-p,t),mul:(f,p)=>po(f*p,t),pow:(f,p)=>Pfe(d,f,p),div:(f,p)=>po(f*dH(p,t),t),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>dH(f,t),sqrt:i||(f=>(l||(l=Tfe(t)),l(d,f))),toBytes:f=>r?K3(f,u):M2(f,u),fromBytes:(f,p=!0)=>{if(a){if(!a.includes(f.length)||f.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let y=new Uint8Array(u);y.set(f,r?0:y.length-f.length),f=y}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let m=r?V3(f):t0(f);if(o&&(m=po(m,t)),!p&&!d.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:f=>L2(d,f),cmov:(f,p,m)=>m?p:f});return Object.freeze(d)}function _H(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function X3(t){let e=_H(t);return e+Math.ceil(e/2)}function vH(t,e,r=!1){let n=t.length,s=_H(e),i=X3(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let o=r?V3(t):t0(t),a=po(o,e-us)+us;return r?K3(a,s):M2(a,s)}var Hs,us,Zd,hH,pH,mH,Afe,gH,Efe,yH,Ife,U2=mr(()=>{z2();Hs=BigInt(0),us=BigInt(1),Zd=BigInt(2),hH=BigInt(3),pH=BigInt(4),mH=BigInt(5),Afe=BigInt(7),gH=BigInt(8),Efe=BigInt(9),yH=BigInt(16);Ife=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function Rfe(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function wH(t,e,r){return t&e^~t&r}function SH(t,e,r){return t&e^t&r^e&r}var tb,uc,qn,Hn,AH=mr(()=>{Kd();tb=class extends Qp{constructor(e,r,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=N2(this.buffer)}update(e){e0(this),e=Jx(e),lo(e);let{view:r,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){let a=Math.min(s-this.pos,i-o);if(a===s){let c=N2(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){e0(this),sH(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:s,isLE:i}=this,{pos:o}=this;r[o++]=128,ac(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let d=o;d<s;d++)r[d]=0;Rfe(n,s-8,BigInt(this.length*8),i),this.process(n,0);let a=N2(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,l[d],i)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},uc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qn=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Hn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function Ofe(t,e=!1){return e?{h:Number(t&q2),l:Number(t>>EH&q2)}:{h:Number(t>>EH&q2)|0,l:Number(t&q2)|0}}function CH(t,e=!1){let r=t.length,n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){let{h:o,l:a}=Ofe(t[i],e);[n[i],s[i]]=[o,a]}return[n,s]}function ca(t,e,r,n){let s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}var q2,EH,J3,Y3,Gd,Wd,rb,nb,kH,TH,IH,PH,RH,OH,NH=mr(()=>{q2=BigInt(4294967295),EH=BigInt(32);J3=(t,e,r)=>t>>>r,Y3=(t,e,r)=>t<<32-r|e>>>r,Gd=(t,e,r)=>t>>>r|e<<32-r,Wd=(t,e,r)=>t<<32-r|e>>>r,rb=(t,e,r)=>t<<64-r|e>>>r-32,nb=(t,e,r)=>t>>>r-32|e<<64-r;kH=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),TH=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,IH=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),PH=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0,RH=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0),OH=(t,e,r,n,s,i)=>e+r+n+s+i+(t/2**32|0)|0});var Bfe,Ru,Q3,BH,$fe,Mfe,Ou,Nu,H2,eP,$H,MH,jH,zH=mr(()=>{AH();NH();Kd();Bfe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ru=new Uint32Array(64),Q3=class extends tb{constructor(e=32){super(64,e,8,!1),this.A=uc[0]|0,this.B=uc[1]|0,this.C=uc[2]|0,this.D=uc[3]|0,this.E=uc[4]|0,this.F=uc[5]|0,this.G=uc[6]|0,this.H=uc[7]|0}get(){let{A:e,B:r,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[e,r,n,s,i,o,a,c]}set(e,r,n,s,i,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let d=0;d<16;d++,r+=4)Ru[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){let f=Ru[d-15],p=Ru[d-2],m=fo(f,7)^fo(f,18)^f>>>3,y=fo(p,17)^fo(p,19)^p>>>10;Ru[d]=y+Ru[d-7]+m+Ru[d-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:u,H:l}=this;for(let d=0;d<64;d++){let f=fo(a,6)^fo(a,11)^fo(a,25),p=l+f+wH(a,c,u)+Bfe[d]+Ru[d]|0,y=(fo(n,2)^fo(n,13)^fo(n,22))+SH(n,s,i)|0;l=u,u=c,c=a,a=o+p|0,o=i,i=s,s=n,n=p+y|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,s,i,o,a,c,u,l)}roundClean(){ac(Ru)}destroy(){this.set(0,0,0,0,0,0,0,0),ac(this.buffer)}},BH=CH(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),$fe=BH[0],Mfe=BH[1],Ou=new Uint32Array(80),Nu=new Uint32Array(80),H2=class extends tb{constructor(e=64){super(128,e,16,!1),this.Ah=Hn[0]|0,this.Al=Hn[1]|0,this.Bh=Hn[2]|0,this.Bl=Hn[3]|0,this.Ch=Hn[4]|0,this.Cl=Hn[5]|0,this.Dh=Hn[6]|0,this.Dl=Hn[7]|0,this.Eh=Hn[8]|0,this.El=Hn[9]|0,this.Fh=Hn[10]|0,this.Fl=Hn[11]|0,this.Gh=Hn[12]|0,this.Gl=Hn[13]|0,this.Hh=Hn[14]|0,this.Hl=Hn[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:s,Ch:i,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:d,Fl:f,Gh:p,Gl:m,Hh:y,Hl:_}=this;return[e,r,n,s,i,o,a,c,u,l,d,f,p,m,y,_]}set(e,r,n,s,i,o,a,c,u,l,d,f,p,m,y,_){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=s|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=d|0,this.Fl=f|0,this.Gh=p|0,this.Gl=m|0,this.Hh=y|0,this.Hl=_|0}process(e,r){for(let E=0;E<16;E++,r+=4)Ou[E]=e.getUint32(r),Nu[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){let B=Ou[E-15]|0,G=Nu[E-15]|0,se=Gd(B,G,1)^Gd(B,G,8)^J3(B,G,7),_e=Wd(B,G,1)^Wd(B,G,8)^Y3(B,G,7),he=Ou[E-2]|0,J=Nu[E-2]|0,ct=Gd(he,J,19)^rb(he,J,61)^J3(he,J,6),ut=Wd(he,J,19)^nb(he,J,61)^Y3(he,J,6),ze=IH(_e,ut,Nu[E-7],Nu[E-16]),z=PH(ze,se,ct,Ou[E-7],Ou[E-16]);Ou[E]=z|0,Nu[E]=ze|0}let{Ah:n,Al:s,Bh:i,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:d,El:f,Fh:p,Fl:m,Gh:y,Gl:_,Hh:S,Hl:C}=this;for(let E=0;E<80;E++){let B=Gd(d,f,14)^Gd(d,f,18)^rb(d,f,41),G=Wd(d,f,14)^Wd(d,f,18)^nb(d,f,41),se=d&p^~d&y,_e=f&m^~f&_,he=RH(C,G,_e,Mfe[E],Nu[E]),J=OH(he,S,B,se,$fe[E],Ou[E]),ct=he|0,ut=Gd(n,s,28)^rb(n,s,34)^rb(n,s,39),ze=Wd(n,s,28)^nb(n,s,34)^nb(n,s,39),z=n&i^n&a^i&a,$=s&o^s&c^o&c;S=y|0,C=_|0,y=p|0,_=m|0,p=d|0,m=f|0,{h:d,l:f}=ca(u|0,l|0,J|0,ct|0),u=a|0,l=c|0,a=i|0,c=o|0,i=n|0,o=s|0;let U=kH(ct,ze,$);n=TH(U,J,ut,z),s=U|0}({h:n,l:s}=ca(this.Ah|0,this.Al|0,n|0,s|0)),{h:i,l:o}=ca(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=ca(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ca(this.Dh|0,this.Dl|0,u|0,l|0),{h:d,l:f}=ca(this.Eh|0,this.El|0,d|0,f|0),{h:p,l:m}=ca(this.Fh|0,this.Fl|0,p|0,m|0),{h:y,l:_}=ca(this.Gh|0,this.Gl|0,y|0,_|0),{h:S,l:C}=ca(this.Hh|0,this.Hl|0,S|0,C|0),this.set(n,s,i,o,a,c,u,l,d,f,p,m,y,_,S,C)}roundClean(){ac(Ou,Nu)}destroy(){ac(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},eP=class extends H2{constructor(){super(48),this.Ah=qn[0]|0,this.Al=qn[1]|0,this.Bh=qn[2]|0,this.Bl=qn[3]|0,this.Ch=qn[4]|0,this.Cl=qn[5]|0,this.Dh=qn[6]|0,this.Dl=qn[7]|0,this.Eh=qn[8]|0,this.El=qn[9]|0,this.Fh=qn[10]|0,this.Fl=qn[11]|0,this.Gh=qn[12]|0,this.Gl=qn[13]|0,this.Hh=qn[14]|0,this.Hl=qn[15]|0}},$H=B2(()=>new Q3),MH=B2(()=>new H2),jH=B2(()=>new eP)});var F2,tP,LH=mr(()=>{Kd();F2=class extends Qp{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,O2(e);let n=Jx(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),ac(i)}update(e){return e0(this),this.iHash.update(e),this}digestInto(e){e0(this),lo(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:s,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},tP=(t,e,r)=>new F2(t,e).update(r).digest();tP.create=(t,e)=>new F2(t,e)});function sb(t,e){let r=e.negate();return t?r:e}function K2(t,e){let r=L2(t.Fp,e.map(n=>n.Z));return e.map((n,s)=>t.fromAffine(n.toAffine(r[s])))}function HH(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function rP(t,e){HH(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),s=2**t,i=Pu(t),o=BigInt(t);return{windows:r,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function DH(t,e,r){let{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r,a=Number(t&s),c=t>>o;a>n&&(a-=i,c+=Xd);let u=e*n,l=u+Math.abs(a)-1,d=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:d,isNeg:f,isNegF:p,offsetF:u}}function jfe(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function zfe(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}function sP(t){return FH.get(t)||1}function UH(t){if(t!==r0)throw new Error("invalid wNAF")}function VH(t,e,r,n){let s=e,i=t.ZERO,o=t.ZERO;for(;r>r0||n>r0;)r&Xd&&(i=i.add(s)),n&Xd&&(o=o.add(s)),s=s.double(),r>>=Xd,n>>=Xd;return{p1:i,p2:o}}function KH(t,e,r,n){jfe(r,t),zfe(n,e);let s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");let o=t.ZERO,a=j2(BigInt(s)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Pu(c),l=new Array(Number(u)+1).fill(o),d=Math.floor((e.BITS-1)/c)*c,f=o;for(let p=d;p>=0;p-=c){l.fill(o);for(let y=0;y<i;y++){let _=n[y],S=Number(_>>BigInt(p)&u);l[S]=l[S].add(r[y])}let m=o;for(let y=l.length-1,_=o;y>0;y--)_=_.add(l[y]),m=m.add(_);if(f=f.add(m),p!==0)for(let y=0;y<c;y++)f=f.double()}return f}function qH(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return W3(e),e}else return aa(t,{isLE:r})}function ZH(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>r0))throw new Error(`CURVE.${c} must be positive bigint`)}let s=qH(e.p,r.Fp,n),i=qH(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:i}}var r0,Xd,nP,FH,V2,GH=mr(()=>{z2();U2();r0=BigInt(0),Xd=BigInt(1);nP=new WeakMap,FH=new WeakMap;V2=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let s=e;for(;r>r0;)r&Xd&&(n=n.add(s)),s=s.double(),r>>=Xd;return n}precomputeWindow(e,r){let{windows:n,windowSize:s}=rP(r,this.bits),i=[],o=e,a=o;for(let c=0;c<n;c++){a=o,i.push(a);for(let u=1;u<s;u++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,i=this.BASE,o=rP(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:f,offsetF:p}=DH(n,a,o);n=c,l?i=i.add(sb(f,r[p])):s=s.add(sb(d,r[u]))}return UH(n),{p:s,f:i}}wNAFUnsafe(e,r,n,s=this.ZERO){let i=rP(e,this.bits);for(let o=0;o<i.windows&&n!==r0;o++){let{nextN:a,offset:c,isZero:u,isNeg:l}=DH(n,o,i);if(n=a,!u){let d=r[c];s=s.add(l?d.negate():d)}}return UH(n),s}getPrecomputes(e,r,n){let s=nP.get(r);return s||(s=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(s=n(s)),nP.set(r,s))),s}cached(e,r,n){let s=sP(e);return this.wNAF(s,this.getPrecomputes(s,e,n),r)}unsafe(e,r,n,s){let i=sP(e);return i===1?this._unsafeLadder(e,r,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),r,s)}createCache(e,r){HH(r,this.bits),FH.set(e,r),nP.delete(e)}hasCache(e){return sP(e)!==1}}});function Lfe(t,e,r){let[[n,s],[i,o]]=e,a=WH(o*t,r),c=WH(-s*t,r),u=t-a*n-c*i,l=-a*s-c*o,d=u<dc,f=l<dc;d&&(u=-u),f&&(l=-l);let p=Pu(Math.ceil(j2(r)/2))+s0;if(u<dc||u>=p||l<dc||l>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:d,k1:u,k2neg:f,k2:l}}function oP(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function iP(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Yx(r.lowS,"lowS"),Yx(r.prehash,"prehash"),r.format!==void 0&&oP(r.format),r}function n0(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let s=cs("private key",e);try{n=t.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Ufe(t,e={}){let r=ZH("weierstrass",t,e),{Fp:n,Fn:s}=r,i=r.CURVE,{h:o,n:a}=i;eb(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=YH(n,s);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(ze,z,$){let{x:U,y:be}=z.toAffine(),ke=n.toBytes(U);if(Yx($,"isCompressed"),$){l();let Le=!n.isOdd(be);return ho(JH(Le),ke)}else return ho(Uint8Array.of(4),ke,n.toBytes(be))}function f(ze){Iu(ze,void 0,"Point");let{publicKey:z,publicKeyUncompressed:$}=u,U=ze.length,be=ze[0],ke=ze.subarray(1);if(U===z&&(be===2||be===3)){let Le=n.fromBytes(ke);if(!n.isValid(Le))throw new Error("bad point: is not on curve, wrong x");let k=y(Le),P;try{P=n.sqrt(k)}catch(M){let fe=M instanceof Error?": "+M.message:"";throw new Error("bad point: is not on curve, sqrt error"+fe)}l();let Z=n.isOdd(P);return(be&1)===1!==Z&&(P=n.neg(P)),{x:Le,y:P}}else if(U===$&&be===4){let Le=n.BYTES,k=n.fromBytes(ke.subarray(0,Le)),P=n.fromBytes(ke.subarray(Le,Le*2));if(!_(k,P))throw new Error("bad point: is not on curve");return{x:k,y:P}}else throw new Error(`bad point: got length ${U}, expected compressed=${z} or uncompressed=${$}`)}let p=e.toBytes||d,m=e.fromBytes||f;function y(ze){let z=n.sqr(ze),$=n.mul(z,ze);return n.add(n.add($,n.mul(ze,i.a)),i.b)}function _(ze,z){let $=n.sqr(z),U=y(ze);return n.eql($,U)}if(!_(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(i.a,Z2),Dfe),C=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(S,C)))throw new Error("bad curve params: a or b");function E(ze,z,$=!1){if(!n.isValid(z)||$&&n.is0(z))throw new Error(`bad point coordinate ${ze}`);return z}function B(ze){if(!(ze instanceof J))throw new Error("ProjectivePoint expected")}function G(ze){if(!c||!c.basises)throw new Error("no endo");return Lfe(ze,c.basises,s.ORDER)}let se=Z3((ze,z)=>{let{X:$,Y:U,Z:be}=ze;if(n.eql(be,n.ONE))return{x:$,y:U};let ke=ze.is0();z==null&&(z=ke?n.ONE:n.inv(be));let Le=n.mul($,z),k=n.mul(U,z),P=n.mul(be,z);if(ke)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:Le,y:k}}),_e=Z3(ze=>{if(ze.is0()){if(e.allowInfinityPoint&&!n.is0(ze.Y))return;throw new Error("bad point: ZERO")}let{x:z,y:$}=ze.toAffine();if(!n.isValid(z)||!n.isValid($))throw new Error("bad point: x or y not field elements");if(!_(z,$))throw new Error("bad point: equation left != right");if(!ze.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function he(ze,z,$,U,be){return $=new J(n.mul($.X,ze),$.Y,$.Z),z=sb(U,z),$=sb(be,$),z.add($)}class J{constructor(z,$,U){this.X=E("x",z),this.Y=E("y",$,!0),this.Z=E("z",U),Object.freeze(this)}static CURVE(){return i}static fromAffine(z){let{x:$,y:U}=z||{};if(!z||!n.isValid($)||!n.isValid(U))throw new Error("invalid affine point");if(z instanceof J)throw new Error("projective point not allowed");return n.is0($)&&n.is0(U)?J.ZERO:new J($,U,n.ONE)}static fromBytes(z){let $=J.fromAffine(m(Iu(z,void 0,"point")));return $.assertValidity(),$}static fromHex(z){return J.fromBytes(cs("pointHex",z))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(z=8,$=!0){return ut.createCache(this,z),$||this.multiply(Z2),this}assertValidity(){_e(this)}hasEvenY(){let{y:z}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(z)}equals(z){B(z);let{X:$,Y:U,Z:be}=this,{X:ke,Y:Le,Z:k}=z,P=n.eql(n.mul($,k),n.mul(ke,be)),Z=n.eql(n.mul(U,k),n.mul(Le,be));return P&&Z}negate(){return new J(this.X,n.neg(this.Y),this.Z)}double(){let{a:z,b:$}=i,U=n.mul($,Z2),{X:be,Y:ke,Z:Le}=this,k=n.ZERO,P=n.ZERO,Z=n.ZERO,I=n.mul(be,be),M=n.mul(ke,ke),fe=n.mul(Le,Le),ye=n.mul(be,ke);return ye=n.add(ye,ye),Z=n.mul(be,Le),Z=n.add(Z,Z),k=n.mul(z,Z),P=n.mul(U,fe),P=n.add(k,P),k=n.sub(M,P),P=n.add(M,P),P=n.mul(k,P),k=n.mul(ye,k),Z=n.mul(U,Z),fe=n.mul(z,fe),ye=n.sub(I,fe),ye=n.mul(z,ye),ye=n.add(ye,Z),Z=n.add(I,I),I=n.add(Z,I),I=n.add(I,fe),I=n.mul(I,ye),P=n.add(P,I),fe=n.mul(ke,Le),fe=n.add(fe,fe),I=n.mul(fe,ye),k=n.sub(k,I),Z=n.mul(fe,M),Z=n.add(Z,Z),Z=n.add(Z,Z),new J(k,P,Z)}add(z){B(z);let{X:$,Y:U,Z:be}=this,{X:ke,Y:Le,Z:k}=z,P=n.ZERO,Z=n.ZERO,I=n.ZERO,M=i.a,fe=n.mul(i.b,Z2),ye=n.mul($,ke),xt=n.mul(U,Le),Rt=n.mul(be,k),cr=n.add($,U),zt=n.add(ke,Le);cr=n.mul(cr,zt),zt=n.add(ye,xt),cr=n.sub(cr,zt),zt=n.add($,be);let lr=n.add(ke,k);return zt=n.mul(zt,lr),lr=n.add(ye,Rt),zt=n.sub(zt,lr),lr=n.add(U,be),P=n.add(Le,k),lr=n.mul(lr,P),P=n.add(xt,Rt),lr=n.sub(lr,P),I=n.mul(M,zt),P=n.mul(fe,Rt),I=n.add(P,I),P=n.sub(xt,I),I=n.add(xt,I),Z=n.mul(P,I),xt=n.add(ye,ye),xt=n.add(xt,ye),Rt=n.mul(M,Rt),zt=n.mul(fe,zt),xt=n.add(xt,Rt),Rt=n.sub(ye,Rt),Rt=n.mul(M,Rt),zt=n.add(zt,Rt),ye=n.mul(xt,zt),Z=n.add(Z,ye),ye=n.mul(lr,zt),P=n.mul(cr,P),P=n.sub(P,ye),ye=n.mul(cr,xt),I=n.mul(lr,I),I=n.add(I,ye),new J(P,Z,I)}subtract(z){return this.add(z.negate())}is0(){return this.equals(J.ZERO)}multiply(z){let{endo:$}=e;if(!s.isValidNot0(z))throw new Error("invalid scalar: out of range");let U,be,ke=Le=>ut.cached(this,Le,k=>K2(J,k));if($){let{k1neg:Le,k1:k,k2neg:P,k2:Z}=G(z),{p:I,f:M}=ke(k),{p:fe,f:ye}=ke(Z);be=M.add(ye),U=he($.beta,I,fe,Le,P)}else{let{p:Le,f:k}=ke(z);U=Le,be=k}return K2(J,[U,be])[0]}multiplyUnsafe(z){let{endo:$}=e,U=this;if(!s.isValid(z))throw new Error("invalid scalar: out of range");if(z===dc||U.is0())return J.ZERO;if(z===s0)return U;if(ut.hasCache(this))return this.multiply(z);if($){let{k1neg:be,k1:ke,k2neg:Le,k2:k}=G(z),{p1:P,p2:Z}=VH(J,U,ke,k);return he($.beta,P,Z,be,Le)}else return ut.unsafe(U,z)}multiplyAndAddUnsafe(z,$,U){let be=this.multiplyUnsafe($).add(z.multiplyUnsafe(U));return be.is0()?void 0:be}toAffine(z){return se(this,z)}isTorsionFree(){let{isTorsionFree:z}=e;return o===s0?!0:z?z(J,this):ut.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:z}=e;return o===s0?this:z?z(J,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(z=!0){return Yx(z,"isCompressed"),this.assertValidity(),p(J,this,z)}toHex(z=!0){return cc(this.toBytes(z))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(z=!0){return this.toBytes(z)}_setWindowSize(z){this.precompute(z)}static normalizeZ(z){return K2(J,z)}static msm(z,$){return KH(J,s,z,$)}static fromPrivateKey(z){return J.BASE.multiply(n0(s,z))}}J.BASE=new J(i.Gx,i.Gy,n.ONE),J.ZERO=new J(n.ZERO,n.ONE,n.ZERO),J.Fp=n,J.Fn=s;let ct=s.BITS,ut=new V2(J,e.endo?Math.ceil(ct/2):ct);return J.BASE.precompute(8),J}function JH(t){return Uint8Array.of(t?2:3)}function YH(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function qfe(t,e={}){let{Fn:r}=t,n=e.randomBytes||$2,s=Object.assign(YH(t.Fp,r),{seed:X3(r.ORDER)});function i(p){try{return!!n0(r,p)}catch{return!1}}function o(p,m){let{publicKey:y,publicKeyUncompressed:_}=s;try{let S=p.length;return m===!0&&S!==y||m===!1&&S!==_?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=n(s.seed)){return vH(Iu(p,s.seed,"seed"),r.ORDER)}function c(p,m=!0){return t.BASE.multiply(n0(r,p)).toBytes(m)}function u(p){let m=a(p);return{secretKey:m,publicKey:c(m)}}function l(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;let{secretKey:m,publicKey:y,publicKeyUncompressed:_}=s;if(r.allowedLengths||m===y)return;let S=cs("key",p).length;return S===y||S===_}function d(p,m,y=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let _=n0(r,p);return t.fromHex(m).multiply(_).toBytes(y)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:u,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:p=>n0(r,p),precompute(p=8,m=t.BASE){return m.precompute(p,!1)}},lengths:s})}function Hfe(t,e,r={}){O2(e),eb(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||$2,s=r.hmac||(($,...U)=>tP(e,$,ho(...U))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:f,lengths:p}=qfe(t,r),m={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},y="compact";function _($){let U=a>>s0;return $>U}function S($,U){if(!o.isValidNot0(U))throw new Error(`invalid signature ${$}: out of range 1..Point.Fn.ORDER`);return U}function C($,U){oP(U);let be=p.signature,ke=U==="compact"?be:U==="recovered"?be+1:void 0;return Iu($,ke,`${U} signature`)}class E{constructor(U,be,ke){this.r=S("r",U),this.s=S("s",be),ke!=null&&(this.recovery=ke),Object.freeze(this)}static fromBytes(U,be=y){C(U,be);let ke;if(be==="der"){let{r:Z,s:I}=lc.toSig(Iu(U));return new E(Z,I)}be==="recovered"&&(ke=U[0],be="compact",U=U.subarray(1));let Le=o.BYTES,k=U.subarray(0,Le),P=U.subarray(Le,Le*2);return new E(o.fromBytes(k),o.fromBytes(P),ke)}static fromHex(U,be){return this.fromBytes(Vd(U),be)}addRecoveryBit(U){return new E(this.r,this.s,U)}recoverPublicKey(U){let be=i.ORDER,{r:ke,s:Le,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*XH<be&&k>1)throw new Error("recovery id is ambiguous for h>1 curve");let Z=k===2||k===3?ke+a:ke;if(!i.isValid(Z))throw new Error("recovery id 2 or 3 invalid");let I=i.toBytes(Z),M=t.fromBytes(ho(JH((k&1)===0),I)),fe=o.inv(Z),ye=G(cs("msgHash",U)),xt=o.create(-ye*fe),Rt=o.create(Le*fe),cr=t.BASE.multiplyUnsafe(xt).add(M.multiplyUnsafe(Rt));if(cr.is0())throw new Error("point at infinify");return cr.assertValidity(),cr}hasHighS(){return _(this.s)}toBytes(U=y){if(oP(U),U==="der")return Vd(lc.hexFromSig(this));let be=o.toBytes(this.r),ke=o.toBytes(this.s);if(U==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ho(Uint8Array.of(this.recovery),be,ke)}return ho(be,ke)}toHex(U){return cc(this.toBytes(U))}assertValidity(){}static fromCompact(U){return E.fromBytes(cs("sig",U),"compact")}static fromDER(U){return E.fromBytes(cs("sig",U),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return cc(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return cc(this.toBytes("compact"))}}let B=r.bits2int||function(U){if(U.length>8192)throw new Error("input is too large");let be=t0(U),ke=U.length*8-c;return ke>0?be>>BigInt(ke):be},G=r.bits2int_modN||function(U){return o.create(B(U))},se=Pu(c);function _e($){return uH("num < 2^"+c,$,dc,se),o.toBytes($)}function he($,U){return Iu($,void 0,"message"),U?Iu(e($),void 0,"prehashed message"):$}function J($,U,be){if(["recovered","canonical"].some(xt=>xt in be))throw new Error("sign() legacy options not supported");let{lowS:ke,prehash:Le,extraEntropy:k}=iP(be,m);$=he($,Le);let P=G($),Z=n0(o,U),I=[_e(Z),_e(P)];if(k!=null&&k!==!1){let xt=k===!0?n(p.secretKey):k;I.push(cs("extraEntropy",xt))}let M=ho(...I),fe=P;function ye(xt){let Rt=B(xt);if(!o.isValidNot0(Rt))return;let cr=o.inv(Rt),zt=t.BASE.multiply(Rt).toAffine(),lr=o.create(zt.x);if(lr===dc)return;let xi=o.create(cr*o.create(fe+lr*Z));if(xi===dc)return;let bi=(zt.x===lr?0:2)|Number(zt.y&s0),hl=xi;return ke&&_(xi)&&(hl=o.neg(xi),bi^=1),new E(lr,hl,bi)}return{seed:M,k2sig:ye}}function ct($,U,be={}){$=cs("message",$);let{seed:ke,k2sig:Le}=J($,U,be);return lH(e.outputLen,o.BYTES,s)(ke,Le)}function ut($){let U,be=typeof $=="string"||Fd($),ke=!be&&$!==null&&typeof $=="object"&&typeof $.r=="bigint"&&typeof $.s=="bigint";if(!be&&!ke)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(ke)U=new E($.r,$.s);else if(be){try{U=E.fromBytes(cs("sig",$),"der")}catch(Le){if(!(Le instanceof lc.Err))throw Le}if(!U)try{U=E.fromBytes(cs("sig",$),"compact")}catch{return!1}}return U||!1}function ze($,U,be,ke={}){let{lowS:Le,prehash:k,format:P}=iP(ke,m);if(be=cs("publicKey",be),U=he(cs("message",U),k),"strict"in ke)throw new Error("options.strict was renamed to lowS");let Z=P===void 0?ut($):E.fromBytes(cs("sig",$),P);if(Z===!1)return!1;try{let I=t.fromBytes(be);if(Le&&Z.hasHighS())return!1;let{r:M,s:fe}=Z,ye=G(U),xt=o.inv(fe),Rt=o.create(ye*xt),cr=o.create(M*xt),zt=t.BASE.multiplyUnsafe(Rt).add(I.multiplyUnsafe(cr));return zt.is0()?!1:o.create(zt.x)===M}catch{return!1}}function z($,U,be={}){let{prehash:ke}=iP(be,m);return U=he(U,ke),E.fromBytes($,"recovered").recoverPublicKey(U).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:d,utils:f,lengths:p,Point:t,sign:ct,verify:ze,recoverPublicKey:z,Signature:E,hash:e})}function Ffe(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0,s=aa(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),i={Fp:r,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function Vfe(t){let{CURVE:e,curveOpts:r}=Ffe(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function Kfe(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,D2(r.Fn.ORDER,r.Fn.BITS))})}function QH(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:s}=Vfe(t),i=Ufe(e,r),o=Hfe(i,n,s);return Kfe(t,o)}var WH,aP,lc,dc,s0,XH,Z2,Dfe,eF=mr(()=>{LH();Kd();z2();GH();U2();WH=(t,e)=>(t+(t>=0?e:-e)/XH)/e;aP=class extends Error{constructor(e=""){super(e)}},lc={Err:aP,_tlv:{encode:(t,e)=>{let{Err:r}=lc;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,s=Qx(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?Qx(s.length/2|128):"";return Qx(t)+i+s+e},decode(t,e){let{Err:r}=lc,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let s=e[n++],i=!!(s&128),o=0;if(!i)o=s;else{let c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of u)o=o<<8|l;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){let{Err:e}=lc;if(t<dc)throw new e("integer: negative integers are not allowed");let r=Qx(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=lc;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return t0(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=lc,s=cs("signature",t),{v:i,l:o}=n.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=lc,n=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),i=n+s;return e.encode(48,i)}},dc=BigInt(0),s0=BigInt(1),XH=BigInt(2),Z2=BigInt(3),Dfe=BigInt(4)});function G2(t,e){let r=n=>QH({...t,hash:n});return{...r(e),create:r}}var tF=mr(()=>{eF();});var rF,nF,sF,Zfe,Gfe,Wfe,iF,YPe,QPe,oF=mr(()=>{zH();tF();U2();rF={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},nF={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},sF={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Zfe=aa(rF.p),Gfe=aa(nF.p),Wfe=aa(sF.p),iF=G2({...rF,Fp:Zfe,lowS:!1},$H),YPe=G2({...nF,Fp:Gfe,lowS:!1},jH),QPe=G2({...sF,Fp:Wfe,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},MH)});var W2,aF=mr(()=>{oF();W2=iF});var uF=v(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.LEB128=Bu.SignedLEB128=Bu.UnsignedLEB128=void 0;var i0;(function(t){t[t.LOWER_7=127]="LOWER_7",t[t.UPPER_1=128]="UPPER_1"})(i0||(i0={}));var cF=t=>Number.isSafeInteger(t),Jd=class{static decode(e,r=0){let n=this.$scanForNullBytes(e,r),s=0,i=0;for(let o=0;o<=n-r;o++){let a=e[r+o]&i0.LOWER_7;s|=a<<i,i+=7}return s}static encode(e){if(this.check(e),e<0)throw new Error(`An unsigned number must NOT be negative, ${e} is!`);let r=[],n=e;do{let s=n&i0.LOWER_7;n>>=7,n&&(s=s|i0.UPPER_1),r.push(s)}while(n);return Uint8Array.from(r)}static check(e){if(!cF(e))throw new Error(`${e} is not a safe integer!`)}static $scanForNullBytes(e,r=0){let n=r,s=0;do{if(n>=e.byteLength)throw new Error("This is not a LEB128-encoded Uint8Array, no ending found!");s=e.slice(n,n+1)[0],n++}while(s&i0.UPPER_1);return n-1}static getLength(e,r=0){return this.$scanForNullBytes(e,r)-r}};Bu.UnsignedLEB128=Jd;var ib=class{static $ceil7mul(e){let r=e;for(;r%7;)r++;return r}static check(e){if(!cF(e))throw new Error(`${e} is not a safe integer!`)}static encode(e){if(this.check(e),e>=0)throw new Error(`A signed number must be negative, ${e} isn't!`);let r=Math.ceil(Math.log2(-e));return Jd.encode((1<<this.$ceil7mul(r))+e)}static decode(e,r=0){let n=Jd.decode(e,r);return-((1<<Math.ceil(Math.log2(n)))-n)}};Bu.SignedLEB128=ib;var ob=class{};Bu.LEB128=ob;ob.encode=t=>(t>=0?Jd:ib).encode(t);ob.decode=(t,e=0,r=!1)=>(r?ib:Jd).decode(t,e)});var dF=v((cP,lF)=>{(function(t){"use strict";function e(k){return parseInt(k)===k}function r(k){if(!e(k.length))return!1;for(var P=0;P<k.length;P++)if(!e(k[P])||k[P]<0||k[P]>255)return!1;return!0}function n(k,P){if(k.buffer&&k.name==="Uint8Array")return P&&(k.slice?k=k.slice():k=Array.prototype.slice.call(k)),k;if(Array.isArray(k)){if(!r(k))throw new Error("Array contains invalid value: "+k);return new Uint8Array(k)}if(e(k.length)&&r(k))return new Uint8Array(k);throw new Error("unsupported array-like object")}function s(k){return new Uint8Array(k)}function i(k,P,Z,I,M){(I!=null||M!=null)&&(k.slice?k=k.slice(I,M):k=Array.prototype.slice.call(k,I,M)),P.set(k,Z)}var o=(function(){function k(Z){var I=[],M=0;for(Z=encodeURI(Z);M<Z.length;){var fe=Z.charCodeAt(M++);fe===37?(I.push(parseInt(Z.substr(M,2),16)),M+=2):I.push(fe)}return n(I)}function P(Z){for(var I=[],M=0;M<Z.length;){var fe=Z[M];fe<128?(I.push(String.fromCharCode(fe)),M++):fe>191&&fe<224?(I.push(String.fromCharCode((fe&31)<<6|Z[M+1]&63)),M+=2):(I.push(String.fromCharCode((fe&15)<<12|(Z[M+1]&63)<<6|Z[M+2]&63)),M+=3)}return I.join("")}return{toBytes:k,fromBytes:P}})(),a=(function(){function k(I){for(var M=[],fe=0;fe<I.length;fe+=2)M.push(parseInt(I.substr(fe,2),16));return M}var P="0123456789abcdef";function Z(I){for(var M=[],fe=0;fe<I.length;fe++){var ye=I[fe];M.push(P[(ye&240)>>4]+P[ye&15])}return M.join("")}return{toBytes:k,fromBytes:Z}})(),c={16:10,24:12,32:14},u=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],l=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],d=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],f=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],p=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],m=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],y=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],_=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],S=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],C=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],E=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],B=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],G=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],se=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],_e=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function he(k){for(var P=[],Z=0;Z<k.length;Z+=4)P.push(k[Z]<<24|k[Z+1]<<16|k[Z+2]<<8|k[Z+3]);return P}var J=function(k){if(!(this instanceof J))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:n(k,!0)}),this._prepare()};J.prototype._prepare=function(){var k=c[this.key.length];if(k==null)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var P=0;P<=k;P++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);for(var Z=(k+1)*4,I=this.key.length/4,M=he(this.key),fe,P=0;P<I;P++)fe=P>>2,this._Ke[fe][P%4]=M[P],this._Kd[k-fe][P%4]=M[P];for(var ye=0,xt=I,Rt;xt<Z;){if(Rt=M[I-1],M[0]^=l[Rt>>16&255]<<24^l[Rt>>8&255]<<16^l[Rt&255]<<8^l[Rt>>24&255]^u[ye]<<24,ye+=1,I!=8)for(var P=1;P<I;P++)M[P]^=M[P-1];else{for(var P=1;P<I/2;P++)M[P]^=M[P-1];Rt=M[I/2-1],M[I/2]^=l[Rt&255]^l[Rt>>8&255]<<8^l[Rt>>16&255]<<16^l[Rt>>24&255]<<24;for(var P=I/2+1;P<I;P++)M[P]^=M[P-1]}for(var P=0,cr,zt;P<I&&xt<Z;)cr=xt>>2,zt=xt%4,this._Ke[cr][zt]=M[P],this._Kd[k-cr][zt]=M[P++],xt++}for(var cr=1;cr<k;cr++)for(var zt=0;zt<4;zt++)Rt=this._Kd[cr][zt],this._Kd[cr][zt]=B[Rt>>24&255]^G[Rt>>16&255]^se[Rt>>8&255]^_e[Rt&255]},J.prototype.encrypt=function(k){if(k.length!=16)throw new Error("invalid plaintext size (must be 16 bytes)");for(var P=this._Ke.length-1,Z=[0,0,0,0],I=he(k),M=0;M<4;M++)I[M]^=this._Ke[0][M];for(var fe=1;fe<P;fe++){for(var M=0;M<4;M++)Z[M]=f[I[M]>>24&255]^p[I[(M+1)%4]>>16&255]^m[I[(M+2)%4]>>8&255]^y[I[(M+3)%4]&255]^this._Ke[fe][M];I=Z.slice()}for(var ye=s(16),xt,M=0;M<4;M++)xt=this._Ke[P][M],ye[4*M]=(l[I[M]>>24&255]^xt>>24)&255,ye[4*M+1]=(l[I[(M+1)%4]>>16&255]^xt>>16)&255,ye[4*M+2]=(l[I[(M+2)%4]>>8&255]^xt>>8)&255,ye[4*M+3]=(l[I[(M+3)%4]&255]^xt)&255;return ye},J.prototype.decrypt=function(k){if(k.length!=16)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var P=this._Kd.length-1,Z=[0,0,0,0],I=he(k),M=0;M<4;M++)I[M]^=this._Kd[0][M];for(var fe=1;fe<P;fe++){for(var M=0;M<4;M++)Z[M]=_[I[M]>>24&255]^S[I[(M+3)%4]>>16&255]^C[I[(M+2)%4]>>8&255]^E[I[(M+1)%4]&255]^this._Kd[fe][M];I=Z.slice()}for(var ye=s(16),xt,M=0;M<4;M++)xt=this._Kd[P][M],ye[4*M]=(d[I[M]>>24&255]^xt>>24)&255,ye[4*M+1]=(d[I[(M+3)%4]>>16&255]^xt>>16)&255,ye[4*M+2]=(d[I[(M+2)%4]>>8&255]^xt>>8)&255,ye[4*M+3]=(d[I[(M+1)%4]&255]^xt)&255;return ye};var ct=function(k){if(!(this instanceof ct))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new J(k)};ct.prototype.encrypt=function(k){if(k=n(k),k.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var P=s(k.length),Z=s(16),I=0;I<k.length;I+=16)i(k,Z,0,I,I+16),Z=this._aes.encrypt(Z),i(Z,P,I);return P},ct.prototype.decrypt=function(k){if(k=n(k),k.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var P=s(k.length),Z=s(16),I=0;I<k.length;I+=16)i(k,Z,0,I,I+16),Z=this._aes.decrypt(Z),i(Z,P,I);return P};var ut=function(k,P){if(!(this instanceof ut))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Block Chaining",this.name="cbc",!P)P=s(16);else if(P.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastCipherblock=n(P,!0),this._aes=new J(k)};ut.prototype.encrypt=function(k){if(k=n(k),k.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var P=s(k.length),Z=s(16),I=0;I<k.length;I+=16){i(k,Z,0,I,I+16);for(var M=0;M<16;M++)Z[M]^=this._lastCipherblock[M];this._lastCipherblock=this._aes.encrypt(Z),i(this._lastCipherblock,P,I)}return P},ut.prototype.decrypt=function(k){if(k=n(k),k.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var P=s(k.length),Z=s(16),I=0;I<k.length;I+=16){i(k,Z,0,I,I+16),Z=this._aes.decrypt(Z);for(var M=0;M<16;M++)P[I+M]=Z[M]^this._lastCipherblock[M];i(k,this._lastCipherblock,0,I,I+16)}return P};var ze=function(k,P,Z){if(!(this instanceof ze))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Feedback",this.name="cfb",!P)P=s(16);else if(P.length!=16)throw new Error("invalid initialation vector size (must be 16 size)");Z||(Z=1),this.segmentSize=Z,this._shiftRegister=n(P,!0),this._aes=new J(k)};ze.prototype.encrypt=function(k){if(k.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var P=n(k,!0),Z,I=0;I<P.length;I+=this.segmentSize){Z=this._aes.encrypt(this._shiftRegister);for(var M=0;M<this.segmentSize;M++)P[I+M]^=Z[M];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(P,this._shiftRegister,16-this.segmentSize,I,I+this.segmentSize)}return P},ze.prototype.decrypt=function(k){if(k.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var P=n(k,!0),Z,I=0;I<P.length;I+=this.segmentSize){Z=this._aes.encrypt(this._shiftRegister);for(var M=0;M<this.segmentSize;M++)P[I+M]^=Z[M];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(k,this._shiftRegister,16-this.segmentSize,I,I+this.segmentSize)}return P};var z=function(k,P){if(!(this instanceof z))throw Error("AES must be instanitated with `new`");if(this.description="Output Feedback",this.name="ofb",!P)P=s(16);else if(P.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastPrecipher=n(P,!0),this._lastPrecipherIndex=16,this._aes=new J(k)};z.prototype.encrypt=function(k){for(var P=n(k,!0),Z=0;Z<P.length;Z++)this._lastPrecipherIndex===16&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),P[Z]^=this._lastPrecipher[this._lastPrecipherIndex++];return P},z.prototype.decrypt=z.prototype.encrypt;var $=function(k){if(!(this instanceof $))throw Error("Counter must be instanitated with `new`");k!==0&&!k&&(k=1),typeof k=="number"?(this._counter=s(16),this.setValue(k)):this.setBytes(k)};$.prototype.setValue=function(k){if(typeof k!="number"||parseInt(k)!=k)throw new Error("invalid counter value (must be an integer)");if(k>Number.MAX_SAFE_INTEGER)throw new Error("integer value out of safe range");for(var P=15;P>=0;--P)this._counter[P]=k%256,k=parseInt(k/256)},$.prototype.setBytes=function(k){if(k=n(k,!0),k.length!=16)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=k},$.prototype.increment=function(){for(var k=15;k>=0;k--)if(this._counter[k]===255)this._counter[k]=0;else{this._counter[k]++;break}};var U=function(k,P){if(!(this instanceof U))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",P instanceof $||(P=new $(P)),this._counter=P,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new J(k)};U.prototype.encrypt=function(k){for(var P=n(k,!0),Z=0;Z<P.length;Z++)this._remainingCounterIndex===16&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),P[Z]^=this._remainingCounter[this._remainingCounterIndex++];return P},U.prototype.decrypt=U.prototype.encrypt;function be(k){k=n(k,!0);var P=16-k.length%16,Z=s(k.length+P);i(k,Z);for(var I=k.length;I<Z.length;I++)Z[I]=P;return Z}function ke(k){if(k=n(k,!0),k.length<16)throw new Error("PKCS#7 invalid length");var P=k[k.length-1];if(P>16)throw new Error("PKCS#7 padding byte out of range");for(var Z=k.length-P,I=0;I<P;I++)if(k[Z+I]!==P)throw new Error("PKCS#7 invalid padding byte");var M=s(Z);return i(k,M,0,0,Z),M}var Le={AES:J,Counter:$,ModeOfOperation:{ecb:ct,cbc:ut,cfb:ze,ofb:z,ctr:U},utils:{hex:a,utf8:o},padding:{pkcs7:{pad:be,strip:ke}},_arrayTest:{coerceArray:n,createArray:s,copyArray:i}};typeof cP<"u"?lF.exports=Le:typeof define=="function"&&define.amd?define([],function(){return Le}):(t.aesjs&&(Le._aesjs=t.aesjs),t.aesjs=Le)})(cP)});function pF(t,e,r){var n=e?0:4,s=e?4:0,i=e?0:3,o=e?1:2,a=e?2:1,c=e?3:0,u=e?ehe:rhe,l=e?the:nhe,d=m.prototype,f="is"+t,p="_"+f;return d.buffer=void 0,d.offset=0,d[p]=!0,d.toNumber=C,d.toString=E,d.toJSON=C,d.toArray=Yfe,c0&&(d.toBuffer=Qfe),a0&&(d.toArrayBuffer=mF),m[f]=y,m;function m(se,_e,he,J){return this instanceof m?_(this,se,_e,he,J):new m(se,_e,he,J)}function y(se){return!!(se&&se[p])}function _(se,_e,he,J,ct){if(a0&&X2&&(_e instanceof X2&&(_e=new a0(_e)),J instanceof X2&&(J=new a0(J))),!_e&&!he&&!J&&!u0){se.buffer=gF(fF,0);return}if(!hF(_e,he)){var ut=u0||Array;ct=he,J=_e,he=0,_e=u0===c0?c0.alloc(8):new ut(8)}se.buffer=_e,se.offset=he|=0,J2!==typeof J&&(typeof J=="string"?S(_e,he,J,ct||10):hF(J,ct)?uP(_e,he,J,ct):typeof ct=="number"?(B(_e,he+n,J),B(_e,he+s,ct)):J>0?u(_e,he,J):J<0?l(_e,he,J):uP(_e,he,fF,0))}function S(se,_e,he,J){var ct=0,ut=he.length,ze=0,z=0;he[0]==="-"&&ct++;for(var $=ct;ct<ut;){var U=parseInt(he[ct++],J);if(!(U>=0))break;z=z*J+U,ze=ze*J+Math.floor(z/o0),z%=o0}$&&(ze=~ze,z?z=o0-z:ze++),B(se,_e+n,ze),B(se,_e+s,z)}function C(){var se=this.buffer,_e=this.offset,he=G(se,_e+n),J=G(se,_e+s);return r||(he|=0),he?he*o0+J:J}function E(se){var _e=this.buffer,he=this.offset,J=G(_e,he+n),ct=G(_e,he+s),ut="",ze=!r&&J&2147483648;for(ze&&(J=~J,ct=o0-ct),se=se||10;;){var z=J%se*o0+ct;if(J=Math.floor(J/se),ct=Math.floor(z/se),ut=(z%se).toString(se)+ut,!J&&!ct)break}return ze&&(ut="-"+ut),ut}function B(se,_e,he){se[_e+c]=he&255,he=he>>8,se[_e+a]=he&255,he=he>>8,se[_e+o]=he&255,he=he>>8,se[_e+i]=he&255}function G(se,_e){return se[_e+i]*Jfe+(se[_e+o]<<16)+(se[_e+a]<<8)+se[_e+c]}}function Yfe(t){var e=this.buffer,r=this.offset;return u0=null,t!==!1&&Xfe(e)?e.length===8?e:e.slice(r,r+8):gF(e,r)}function Qfe(t){var e=this.buffer,r=this.offset;return u0=c0,t!==!1&&c0.isBuffer(e)?e.length===8?e:e.slice(r,r+8):c0.from(mF.call(this,t))}function mF(t){var e=this.buffer,r=this.offset,n=e.buffer;if(u0=a0,t!==!1&&!e.offset&&n instanceof X2)return n.byteLength===8?n:n.slice(r,r+8);var s=new a0(8);return uP(s,0,e,r),s.buffer}function hF(t,e){var r=t&&t.length;return e|=0,r&&e+8<=r&&typeof t[e]!="string"}function uP(t,e,r,n){e|=0,n|=0;for(var s=0;s<8;s++)t[e++]=r[n++]&255}function gF(t,e){return Array.prototype.slice.call(t,e,e+8)}function ehe(t,e,r){for(var n=e+8;n>e;)t[--n]=r&255,r/=256}function the(t,e,r){var n=e+8;for(r++;n>e;)t[--n]=-r&255^255,r/=256}function rhe(t,e,r){for(var n=e+8;e<n;)t[e++]=r&255,r/=256}function nhe(t,e,r){var n=e+8;for(r++;e<n;)t[e++]=-r&255^255,r/=256}function she(t){return!!t&&Object.prototype.toString.call(t)=="[object Array]"}var J2,c0,a0,X2,fF,Xfe,o0,Jfe,u0,Y2,lP,Q2=mr(()=>{J2="undefined",c0=J2!==typeof Buffer&&Buffer,a0=J2!==typeof Uint8Array&&Uint8Array,X2=J2!==typeof ArrayBuffer&&ArrayBuffer,fF=[0,0,0,0,0,0,0,0],Xfe=Array.isArray||she,o0=4294967296,Jfe=16777216,Y2=pF("Uint64BE",!0,!0),lP=pF("Int64BE",!0,!1)});var fP=v(yF=>{var Qe=yF,{Buffer:eA}=on("buffer"),ihe=on("os");Qe.toBuffer=function(t,e,r){r=~~r;let n;if(this.isV4Format(t))n=e||eA.alloc(r+4),t.split(/\./g).map(s=>{n[r++]=parseInt(s,10)&255});else if(this.isV6Format(t)){let s=t.split(":",8),i;for(i=0;i<s.length;i++){let o=this.isV4Format(s[i]),a;o&&(a=this.toBuffer(s[i]),s[i]=a.slice(0,2).toString("hex")),a&&++i<8&&s.splice(i,0,a.slice(2,4).toString("hex"))}if(s[0]==="")for(;s.length<8;)s.unshift("0");else if(s[s.length-1]==="")for(;s.length<8;)s.push("0");else if(s.length<8){for(i=0;i<s.length&&s[i]!=="";i++);let o=[i,1];for(i=9-s.length;i>0;i--)o.push("0");s.splice(...o)}for(n=e||eA.alloc(r+16),i=0;i<s.length;i++){let o=parseInt(s[i],16);n[r++]=o>>8&255,n[r++]=o&255}}if(!n)throw Error(`Invalid ip address: ${t}`);return n};Qe.toString=function(t,e,r){e=~~e,r=r||t.length-e;let n=[];if(r===4){for(let s=0;s<r;s++)n.push(t[e+s]);n=n.join(".")}else if(r===16){for(let s=0;s<r;s+=2)n.push(t.readUInt16BE(e+s).toString(16));n=n.join(":"),n=n.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),n=n.replace(/:{3,4}/,"::")}return n};var ohe=/^(\d{1,3}\.){3,3}\d{1,3}$/,ahe=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;Qe.isV4Format=function(t){return ohe.test(t)};Qe.isV6Format=function(t){return ahe.test(t)};function ab(t){return t===4?"ipv4":t===6?"ipv6":t?t.toLowerCase():"ipv4"}Qe.fromPrefixLen=function(t,e){t>32?e="ipv6":e=ab(e);let r=4;e==="ipv6"&&(r=16);let n=eA.alloc(r);for(let s=0,i=n.length;s<i;++s){let o=8;t<8&&(o=t),t-=o,n[s]=~(255>>o)&255}return Qe.toString(n)};Qe.mask=function(t,e){t=Qe.toBuffer(t),e=Qe.toBuffer(e);let r=eA.alloc(Math.max(t.length,e.length)),n;if(t.length===e.length)for(n=0;n<t.length;n++)r[n]=t[n]&e[n];else if(e.length===4)for(n=0;n<e.length;n++)r[n]=t[t.length-4+n]&e[n];else{for(n=0;n<r.length-6;n++)r[n]=0;for(r[10]=255,r[11]=255,n=0;n<t.length;n++)r[n+12]=t[n]&e[n+12];n+=12}for(;n<r.length;n++)r[n]=0;return Qe.toString(r)};Qe.cidr=function(t){let e=t.split("/"),r=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${r}`);let n=Qe.fromPrefixLen(parseInt(e[1],10));return Qe.mask(r,n)};Qe.subnet=function(t,e){let r=Qe.toLong(Qe.mask(t,e)),n=Qe.toBuffer(e),s=0;for(let o=0;o<n.length;o++)if(n[o]===255)s+=8;else{let a=n[o]&255;for(;a;)a=a<<1&255,s++}let i=2**(32-s);return{networkAddress:Qe.fromLong(r),firstAddress:i<=2?Qe.fromLong(r):Qe.fromLong(r+1),lastAddress:i<=2?Qe.fromLong(r+i-1):Qe.fromLong(r+i-2),broadcastAddress:Qe.fromLong(r+i-1),subnetMask:e,subnetMaskLength:s,numHosts:i<=2?i:i-2,length:i,contains(o){return r===Qe.toLong(Qe.mask(o,e))}}};Qe.cidrSubnet=function(t){let e=t.split("/"),r=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${r}`);let n=Qe.fromPrefixLen(parseInt(e[1],10));return Qe.subnet(r,n)};Qe.not=function(t){let e=Qe.toBuffer(t);for(let r=0;r<e.length;r++)e[r]=255^e[r];return Qe.toString(e)};Qe.or=function(t,e){if(t=Qe.toBuffer(t),e=Qe.toBuffer(e),t.length===e.length){for(let i=0;i<t.length;++i)t[i]|=e[i];return Qe.toString(t)}let r=t,n=e;e.length>t.length&&(r=e,n=t);let s=r.length-n.length;for(let i=s;i<r.length;++i)r[i]|=n[i-s];return Qe.toString(r)};Qe.isEqual=function(t,e){if(t=Qe.toBuffer(t),e=Qe.toBuffer(e),t.length===e.length){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}if(e.length===4){let n=e;e=t,t=n}for(let n=0;n<10;n++)if(e[n]!==0)return!1;let r=e.readUInt16BE(10);if(r!==0&&r!==65535)return!1;for(let n=0;n<4;n++)if(t[n]!==e[n+12])return!1;return!0};Qe.isPrivate=function(t){if(Qe.isLoopback(t))return!0;if(!Qe.isV6Format(t)){let e=Qe.normalizeToLong(t);if(e<0)throw new Error("invalid ipv4 address");t=Qe.fromLong(e)}return/^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^f[cd][0-9a-f]{2}:/i.test(t)||/^fe80:/i.test(t)||/^::1$/.test(t)||/^::$/.test(t)};Qe.isPublic=function(t){return!Qe.isPrivate(t)};Qe.isLoopback=function(t){return!/\./.test(t)&&!/:/.test(t)&&(t=Qe.fromLong(Number(t))),/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(t)||/^0177\./.test(t)||/^0x7f\./i.test(t)||/^fe80::1$/i.test(t)||/^::1$/.test(t)||/^::$/.test(t)};Qe.loopback=function(t){if(t=ab(t),t!=="ipv4"&&t!=="ipv6")throw new Error("family must be ipv4 or ipv6");return t==="ipv4"?"127.0.0.1":"fe80::1"};Qe.address=function(t,e){let r=ihe.networkInterfaces();if(e=ab(e),t&&t!=="private"&&t!=="public"){let s=r[t].filter(i=>ab(i.family)===e);return s.length===0?void 0:s[0].address}let n=Object.keys(r).map(s=>{let i=r[s].filter(o=>(o.family=ab(o.family),o.family!==e||Qe.isLoopback(o.address)?!1:t?t==="public"?Qe.isPrivate(o.address):Qe.isPublic(o.address):!0));return i.length?i[0].address:void 0}).filter(Boolean);return n.length?n[0]:Qe.loopback(e)};Qe.toLong=function(t){let e=0;return t.split(".").forEach(r=>{e<<=8,e+=parseInt(r)}),e>>>0};Qe.fromLong=function(t){return`${t>>>24}.${t>>16&255}.${t>>8&255}.${t&255}`};Qe.normalizeToLong=function(t){let e=t.split(".").map(s=>s.startsWith("0x")||s.startsWith("0X")?parseInt(s,16):s.startsWith("0")&&s!=="0"&&/^[0-7]+$/.test(s)?parseInt(s,8):/^[1-9]\d*$/.test(s)||s==="0"?parseInt(s,10):NaN);if(e.some(isNaN))return-1;let r=0;switch(e.length){case 1:r=e[0];break;case 2:if(e[0]>255||e[1]>16777215)return-1;r=e[0]<<24|e[1]&16777215;break;case 3:if(e[0]>255||e[1]>255||e[2]>65535)return-1;r=e[0]<<24|e[1]<<16|e[2]&65535;break;case 4:if(e.some(s=>s>255))return-1;r=e[0]<<24|e[1]<<16|e[2]<<8|e[3];break;default:return-1}return r>>>0}});var tA=v((o8e,xF)=>{"use strict";xF.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,i;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[s]))return!1;for(s=n;s--!==0;){var o=i[s];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var bF=v(hP=>{"use strict";hP.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};hP.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var _F=v(pP=>{"use strict";pP.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};pP.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var vF=v(mP=>{"use strict";mP.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};mP.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var wF=v(gP=>{"use strict";gP.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};gP.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var SF=v(yP=>{"use strict";yP.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};yP.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var CF=v((EF,xP)=>{var AF=(function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=d,t.encode=l,t.familyOf=u,t.name=void 0,t.sizeOf=c,t.v6=t.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,r=4,n=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,s=16,i={name:"v4",size:r,isFormat:f=>e.test(f),encode(f,p,m){m=~~m,p=p||new Uint8Array(m+r);let y=f.length,_=0;for(let S=0;S<y;){let C=f.charCodeAt(S++);C===46?(p[m++]=_,_=0):_=_*10+(C-48)}return p[m]=_,p},decode(f,p){return p=~~p,`${f[p++]}.${f[p++]}.${f[p++]}.${f[p]}`}};t.v4=i;let o={name:"v6",size:s,isFormat:f=>f.length>0&&n.test(f),encode(f,p,m){m=~~m;let y=m+s,_=-1,S=0,C=0,E=!0,B=!1;p=p||new Uint8Array(m+s);for(let G=0;G<f.length;G++){let se=f.charCodeAt(G);se===58?(E?_!==-1?(m<y&&(p[m]=0),m<y-1&&(p[m+1]=0),m+=2):m<y&&(_=m):(B===!0?(m<y&&(p[m]=C),m++):(m<y&&(p[m]=S>>8),m<y-1&&(p[m+1]=S&255),m+=2),S=0,C=0),E=!0,B=!1):se===46?(m<y&&(p[m]=C),m++,C=0,S=0,E=!1,B=!0):(E=!1,se>=97?se-=87:se>=65?se-=55:(se-=48,C=C*10+se),S=(S<<4)+se)}if(E===!1)B===!0?(m<y&&(p[m]=C),m++):(m<y&&(p[m]=S>>8),m<y-1&&(p[m+1]=S&255),m+=2);else if(_===0)m<y&&(p[m]=0),m<y-1&&(p[m+1]=0),m+=2;else if(_!==-1){m+=2;for(let G=Math.min(m-1,y-1);G>=_+2;G--)p[G]=p[G-2];p[_]=0,p[_+1]=0,_=m}if(_!==m&&_!==-1)for(m>y-2&&(m=y-2);y>_;)p[--y]=m<y&&m>_?p[--m]:0;else for(;m<y;)p[m++]=0;return p},decode(f,p){p=~~p;let m="";for(let y=0;y<s;y+=2)y!==0&&(m+=":"),m+=(f[p+y]<<8|f[p+y+1]).toString(16);return m.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};t.v6=o;let a="ip";t.name=a;function c(f){if(i.isFormat(f))return i.size;if(o.isFormat(f))return o.size;throw Error(`Invalid ip address: ${f}`)}function u(f){return c(f)===i.size?1:2}function l(f,p,m){m=~~m;let y=c(f);return typeof p=="function"&&(p=p(m+y)),y===i.size?i.encode(f,p,m):o.encode(f,p,m)}function d(f,p,m){if(p=~~p,m=m||f.length-p,m===i.size)return i.decode(f,p,m);if(m===o.size)return o.decode(f,p,m);throw Error(`Invalid buffer size needs to be ${i.size} for v4 or ${o.size} for v6.`)}return"default"in t?t.default:t})({});typeof define=="function"&&define.amd?define([],function(){return AF}):typeof xP=="object"&&typeof EF=="object"&&(xP.exports=AF)});var IF=v(et=>{"use strict";var tt=on("buffer").Buffer,vc=bF(),che=_F(),uhe=vF(),nA=wF(),bP=SF(),Yd=CF(),lhe=0,kF=32768,_P=32768,dhe=~_P,TF=32768,fhe=~TF,Ce=et.name={};Ce.encode=function(t,e,r,{mail:n=!1}={}){e||(e=tt.alloc(Ce.encodingLength(t))),r||(r=0);let s=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let o=[];if(n){let a="";i.split(".").forEach(c=>{c.endsWith("\\")?a+=(a.length?".":"")+c.slice(0,-1):o.length===0&&a.length?o.push(a+"."+c):o.push(c)})}else o=i.split(".");for(let a=0;a<o.length;a++){let c=e.write(o[a],r+1);e[r]=c,r+=c+1}}return e[r++]=0,Ce.encode.bytes=r-s,e};Ce.encode.bytes=0;Ce.decode=function(t,e,{mail:r=!1}={}){e||(e=0);let n=[],s=e,i=0,o=0,a=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(o+=a?0:1,c===0)break;if((c&192)===0){if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");let u=t.toString("utf-8",e,e+c);r&&(u=u.replace(/\./g,"\\.")),n.push(u),e+=c,o+=a?0:c}else if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let u=t.readUInt16BE(e-1)-49152;if(u>=s)throw new Error("Cannot decode name (bad pointer)");e=u,s=u,o+=a?0:1,a=!0}else throw new Error("Cannot decode name (bad label)")}return Ce.decode.bytes=o,n.length===0?".":n.join(".")};Ce.decode.bytes=0;Ce.encodingLength=function(t){return t==="."||t===".."?1:tt.byteLength(t.replace(/^\.|\.$/gm,""))+2};var Mt={};Mt.encode=function(t,e,r){e||(e=tt.alloc(Mt.encodingLength(t))),r||(r=0);let n=e.write(t,r+1);return e[r]=n,Mt.encode.bytes=n+1,e};Mt.encode.bytes=0;Mt.decode=function(t,e){e||(e=0);let r=t[e],n=t.toString("utf-8",e+1,e+1+r);return Mt.decode.bytes=r+1,n};Mt.decode.bytes=0;Mt.encodingLength=function(t){return tt.byteLength(t)+1};var yo={};yo.encode=function(t,e,r){e||(e=yo.encodingLength(t)),r||(r=0);let n=(t.flags||0)&32767,s=t.type==="response"?kF:lhe;return e.writeUInt16BE(t.id||0,r),e.writeUInt16BE(n|s,r+2),e.writeUInt16BE(t.questions.length,r+4),e.writeUInt16BE(t.answers.length,r+6),e.writeUInt16BE(t.authorities.length,r+8),e.writeUInt16BE(t.additionals.length,r+10),e};yo.encode.bytes=12;yo.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:r&kF?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:uhe.toString(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:che.toString(r&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};yo.decode.bytes=12;yo.encodingLength=function(){return 12};var fc=et.unknown={};fc.encode=function(t,e,r){return e||(e=tt.alloc(fc.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),fc.encode.bytes=t.length+2,e};fc.encode.bytes=0;fc.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=t.slice(e+2,e+2+r);return fc.decode.bytes=r+2,n};fc.decode.bytes=0;fc.encodingLength=function(t){return t.length+2};var hc=et.ns={};hc.encode=function(t,e,r){return e||(e=tt.alloc(hc.encodingLength(t))),r||(r=0),Ce.encode(t,e,r+2),e.writeUInt16BE(Ce.encode.bytes,r),hc.encode.bytes=Ce.encode.bytes+2,e};hc.encode.bytes=0;hc.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=Ce.decode(t,e+2);return hc.decode.bytes=r+2,n};hc.decode.bytes=0;hc.encodingLength=function(t){return Ce.encodingLength(t)+2};var pc=et.soa={};pc.encode=function(t,e,r){e||(e=tt.alloc(pc.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ce.encode(t.mname,e,r),r+=Ce.encode.bytes,Ce.encode(t.rname,e,r,{mail:!0}),r+=Ce.encode.bytes,e.writeUInt32BE(t.serial||0,r),r+=4,e.writeUInt32BE(t.refresh||0,r),r+=4,e.writeUInt32BE(t.retry||0,r),r+=4,e.writeUInt32BE(t.expire||0,r),r+=4,e.writeUInt32BE(t.minimum||0,r),r+=4,e.writeUInt16BE(r-n-2,n),pc.encode.bytes=r-n,e};pc.encode.bytes=0;pc.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Ce.decode(t,e),e+=Ce.decode.bytes,n.rname=Ce.decode(t,e,{mail:!0}),e+=Ce.decode.bytes,n.serial=t.readUInt32BE(e),e+=4,n.refresh=t.readUInt32BE(e),e+=4,n.retry=t.readUInt32BE(e),e+=4,n.expire=t.readUInt32BE(e),e+=4,n.minimum=t.readUInt32BE(e),e+=4,pc.decode.bytes=e-r,n};pc.decode.bytes=0;pc.encodingLength=function(t){return 22+Ce.encodingLength(t.mname)+Ce.encodingLength(t.rname)};var mc=et.txt={};mc.encode=function(t,e,r){Array.isArray(t)||(t=[t]);for(let s=0;s<t.length;s++)if(typeof t[s]=="string"&&(t[s]=tt.from(t[s])),!tt.isBuffer(t[s]))throw new Error("Must be a Buffer");e||(e=tt.alloc(mc.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(s){e[r++]=s.length,s.copy(e,r,0,s.length),r+=s.length}),e.writeUInt16BE(r-n-2,n),mc.encode.bytes=r-n,e};mc.encode.bytes=0;mc.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let s=[];for(;n>0;){let i=t[e++];if(--n,n<i)throw new Error("Buffer overflow");s.push(t.slice(e,e+i)),e+=i,n-=i}return mc.decode.bytes=e-r,s};mc.decode.bytes=0;mc.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=tt.byteLength(r)+1:e+=r.length+1}),e};var gc=et.null={};gc.encode=function(t,e,r){e||(e=tt.alloc(gc.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=tt.from(t)),t||(t=tt.alloc(0));let n=r;r+=2;let s=t.length;return t.copy(e,r,0,s),r+=s,e.writeUInt16BE(r-n-2,n),gc.encode.bytes=r-n,e};gc.encode.bytes=0;gc.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let s=t.slice(e,e+n);return e+=n,gc.decode.bytes=e-r,s};gc.decode.bytes=0;gc.encodingLength=function(t){return t?(tt.isBuffer(t)?t.length:tt.byteLength(t))+2:2};var yc=et.hinfo={};yc.encode=function(t,e,r){e||(e=tt.alloc(yc.encodingLength(t))),r||(r=0);let n=r;return r+=2,Mt.encode(t.cpu,e,r),r+=Mt.encode.bytes,Mt.encode(t.os,e,r),r+=Mt.encode.bytes,e.writeUInt16BE(r-n-2,n),yc.encode.bytes=r-n,e};yc.encode.bytes=0;yc.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Mt.decode(t,e),e+=Mt.decode.bytes,n.os=Mt.decode(t,e),e+=Mt.decode.bytes,yc.decode.bytes=e-r,n};yc.decode.bytes=0;yc.encodingLength=function(t){return Mt.encodingLength(t.cpu)+Mt.encodingLength(t.os)+2};var mo=et.ptr={},hhe=et.cname=mo,phe=et.dname=mo;mo.encode=function(t,e,r){return e||(e=tt.alloc(mo.encodingLength(t))),r||(r=0),Ce.encode(t,e,r+2),e.writeUInt16BE(Ce.encode.bytes,r),mo.encode.bytes=Ce.encode.bytes+2,e};mo.encode.bytes=0;mo.decode=function(t,e){e||(e=0);let r=Ce.decode(t,e+2);return mo.decode.bytes=Ce.decode.bytes+2,r};mo.decode.bytes=0;mo.encodingLength=function(t){return Ce.encodingLength(t)+2};var xc=et.srv={};xc.encode=function(t,e,r){e||(e=tt.alloc(xc.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.priority||0,r+2),e.writeUInt16BE(t.weight||0,r+4),e.writeUInt16BE(t.port||0,r+6),Ce.encode(t.target,e,r+8);let n=Ce.encode.bytes+6;return e.writeUInt16BE(n,r),xc.encode.bytes=n+2,e};xc.encode.bytes=0;xc.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n={};return n.priority=t.readUInt16BE(e+2),n.weight=t.readUInt16BE(e+4),n.port=t.readUInt16BE(e+6),n.target=Ce.decode(t,e+8),xc.decode.bytes=r+2,n};xc.decode.bytes=0;xc.encodingLength=function(t){return 8+Ce.encodingLength(t.target)};var fi=et.caa={};fi.ISSUER_CRITICAL=128;fi.encode=function(t,e,r){let n=fi.encodingLength(t);return e||(e=tt.alloc(fi.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=fi.ISSUER_CRITICAL),e.writeUInt16BE(n-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,Mt.encode(t.tag,e,r),r+=Mt.encode.bytes,e.write(t.value,r),r+=tt.byteLength(t.value),fi.encode.bytes=n,e};fi.encode.bytes=0;fi.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e);e+=2;let n=e,s={};return s.flags=t.readUInt8(e),e+=1,s.tag=Mt.decode(t,e),e+=Mt.decode.bytes,s.value=t.toString("utf-8",e,n+r),s.issuerCritical=!!(s.flags&fi.ISSUER_CRITICAL),fi.decode.bytes=r+2,s};fi.decode.bytes=0;fi.encodingLength=function(t){return Mt.encodingLength(t.tag)+Mt.encodingLength(t.value)+2};var $u=et.mx={};$u.encode=function(t,e,r){e||(e=tt.alloc($u.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,Ce.encode(t.exchange,e,r),r+=Ce.encode.bytes,e.writeUInt16BE(r-n-2,n),$u.encode.bytes=r-n,e};$u.encode.bytes=0;$u.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=t.readUInt16BE(e),e+=2,n.exchange=Ce.decode(t,e),e+=Ce.decode.bytes,$u.decode.bytes=e-r,n};$u.encodingLength=function(t){return 4+Ce.encodingLength(t.exchange)};var bc=et.a={};bc.encode=function(t,e,r){return e||(e=tt.alloc(bc.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,Yd.v4.encode(t,e,r),bc.encode.bytes=6,e};bc.encode.bytes=0;bc.decode=function(t,e){e||(e=0),e+=2;let r=Yd.v4.decode(t,e);return bc.decode.bytes=6,r};bc.decode.bytes=0;bc.encodingLength=function(){return 6};var _c=et.aaaa={};_c.encode=function(t,e,r){return e||(e=tt.alloc(_c.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,Yd.v6.encode(t,e,r),_c.encode.bytes=18,e};_c.encode.bytes=0;_c.decode=function(t,e){e||(e=0),e+=2;let r=Yd.v6.decode(t,e);return _c.decode.bytes=18,r};_c.decode.bytes=0;_c.encodingLength=function(){return 18};var Fs=et.option={};Fs.encode=function(t,e,r){e||(e=tt.alloc(Fs.encodingLength(t))),r||(r=0);let n=r,s=bP.toCode(t.code);if(e.writeUInt16BE(s,r),r+=2,t.data)e.writeUInt16BE(t.data.length,r),r+=2,t.data.copy(e,r),r+=t.data.length;else switch(s){case 8:let i=t.sourcePrefixLength||0,o=t.family||Yd.familyOf(t.ip),a=Yd.encode(t.ip,tt.alloc),c=Math.ceil(i/8);e.writeUInt16BE(c+4,r),r+=2,e.writeUInt16BE(o,r),r+=2,e.writeUInt8(i,r++),e.writeUInt8(t.scopePrefixLength||0,r++),a.copy(e,r,0,c),r+=c;break;case 11:t.timeout?(e.writeUInt16BE(2,r),r+=2,e.writeUInt16BE(t.timeout,r),r+=2):(e.writeUInt16BE(0,r),r+=2);break;case 12:let u=t.length||0;e.writeUInt16BE(u,r),r+=2,e.fill(0,r,r+u),r+=u;break;case 14:let l=t.tags.length*2;e.writeUInt16BE(l,r),r+=2;for(let d of t.tags)e.writeUInt16BE(d,r),r+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return Fs.encode.bytes=r-n,e};Fs.encode.bytes=0;Fs.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=bP.toString(r.code),e+=2;let n=t.readUInt16BE(e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=t.readUInt16BE(e),e+=2,r.sourcePrefixLength=t.readUInt8(e++),r.scopePrefixLength=t.readUInt8(e++);let s=tt.alloc(r.family===1?4:16);t.copy(s,0,e,e+n-4),r.ip=Yd.decode(s);break;case 11:n>0&&(r.timeout=t.readUInt16BE(e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(t.readUInt16BE(e)),e+=2}return Fs.decode.bytes=n+4,r};Fs.decode.bytes=0;Fs.encodingLength=function(t){if(t.data)return t.data.length+4;switch(bP.toCode(t.code)){case 8:let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var pi=et.opt={};pi.encode=function(t,e,r){e||(e=tt.alloc(pi.encodingLength(t))),r||(r=0);let n=r,s=l0(t,Fs);return e.writeUInt16BE(s,r),r=cb(t,Fs,e,r+2),pi.encode.bytes=r-n,e};pi.encode.bytes=0;pi.decode=function(t,e){e||(e=0);let r=e,n=[],s=t.readUInt16BE(e);e+=2;let i=0;for(;s>0;)n[i++]=Fs.decode(t,e),e+=Fs.decode.bytes,s-=Fs.decode.bytes;return pi.decode.bytes=e-r,n};pi.decode.bytes=0;pi.encodingLength=function(t){return 2+l0(t||[],Fs)};var _s=et.dnskey={};_s.PROTOCOL_DNSSEC=3;_s.ZONE_KEY=128;_s.SECURE_ENTRYPOINT=32768;_s.encode=function(t,e,r){e||(e=tt.alloc(_s.encodingLength(t))),r||(r=0);let n=r,s=t.key;if(!tt.isBuffer(s))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(_s.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,s.copy(e,r,0,s.length),r+=s.length,_s.encode.bytes=r-n,e.writeUInt16BE(_s.encode.bytes-2,n),e};_s.encode.bytes=0;_s.decode=function(t,e){e||(e=0);let r=e;var n={},s=t.readUInt16BE(e);if(e+=2,n.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==_s.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t.readUInt8(e),e+=1,n.key=t.slice(e,r+s+2),e+=n.key.length,_s.decode.bytes=e-r,n};_s.decode.bytes=0;_s.encodingLength=function(t){return 6+tt.byteLength(t.key)};var ua=et.rrsig={};ua.encode=function(t,e,r){e||(e=tt.alloc(ua.encodingLength(t))),r||(r=0);let n=r,s=t.signature;if(!tt.isBuffer(s))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(vc.toType(t.typeCovered),r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.labels,r),r+=1,e.writeUInt32BE(t.originalTTL,r),r+=4,e.writeUInt32BE(t.expiration,r),r+=4,e.writeUInt32BE(t.inception,r),r+=4,e.writeUInt16BE(t.keyTag,r),r+=2,Ce.encode(t.signersName,e,r),r+=Ce.encode.bytes,s.copy(e,r,0,s.length),r+=s.length,ua.encode.bytes=r-n,e.writeUInt16BE(ua.encode.bytes-2,n),e};ua.encode.bytes=0;ua.decode=function(t,e){e||(e=0);let r=e;var n={},s=t.readUInt16BE(e);return e+=2,n.typeCovered=vc.toString(t.readUInt16BE(e)),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.labels=t.readUInt8(e),e+=1,n.originalTTL=t.readUInt32BE(e),e+=4,n.expiration=t.readUInt32BE(e),e+=4,n.inception=t.readUInt32BE(e),e+=4,n.keyTag=t.readUInt16BE(e),e+=2,n.signersName=Ce.decode(t,e),e+=Ce.decode.bytes,n.signature=t.slice(e,r+s+2),e+=n.signature.length,ua.decode.bytes=e-r,n};ua.decode.bytes=0;ua.encodingLength=function(t){return 20+Ce.encodingLength(t.signersName)+tt.byteLength(t.signature)};var la=et.rp={};la.encode=function(t,e,r){e||(e=tt.alloc(la.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ce.encode(t.mbox||".",e,r,{mail:!0}),r+=Ce.encode.bytes,Ce.encode(t.txt||".",e,r),r+=Ce.encode.bytes,la.encode.bytes=r-n,e.writeUInt16BE(la.encode.bytes-2,n),e};la.encode.bytes=0;la.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Ce.decode(t,e,{mail:!0})||".",e+=Ce.decode.bytes,n.txt=Ce.decode(t,e)||".",e+=Ce.decode.bytes,la.decode.bytes=e-r,n};la.decode.bytes=0;la.encodingLength=function(t){return 2+Ce.encodingLength(t.mbox||".")+Ce.encodingLength(t.txt||".")};var zn={};zn.encode=function(t,e,r){e||(e=tt.alloc(zn.encodingLength(t))),r||(r=0);let n=r;for(var s=[],i=0;i<t.length;i++){var o=vc.toType(t[i]);s[o>>8]===void 0&&(s[o>>8]=[]),s[o>>8][o>>3&31]|=1<<7-(o&7)}for(i=0;i<s.length;i++)if(s[i]!==void 0){var a=tt.from(s[i]);e.writeUInt8(i,r),r+=1,e.writeUInt8(a.length,r),r+=1,a.copy(e,r),r+=a.length}return zn.encode.bytes=r-n,e};zn.encode.bytes=0;zn.decode=function(t,e,r){e||(e=0);let n=e;for(var s=[];e-n<r;){var i=t.readUInt8(e);e+=1;var o=t.readUInt8(e);e+=1;for(var a=0;a<o;a++)for(var c=t.readUInt8(e+a),u=0;u<8;u++)if(c&1<<7-u){var l=vc.toString(i<<8|a<<3|u);s.push(l)}e+=o}return zn.decode.bytes=e-n,s};zn.decode.bytes=0;zn.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var n=vc.toType(t[r]);e[n>>8]=Math.max(e[n>>8]||0,n&255)}var s=0;for(r=0;r<e.length;r++)e[r]!==void 0&&(s+=2+Math.ceil((e[r]+1)/8));return s};var da=et.nsec={};da.encode=function(t,e,r){e||(e=tt.alloc(da.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ce.encode(t.nextDomain,e,r),r+=Ce.encode.bytes,zn.encode(t.rrtypes,e,r),r+=zn.encode.bytes,da.encode.bytes=r-n,e.writeUInt16BE(da.encode.bytes-2,n),e};da.encode.bytes=0;da.decode=function(t,e){e||(e=0);let r=e;var n={},s=t.readUInt16BE(e);return e+=2,n.nextDomain=Ce.decode(t,e),e+=Ce.decode.bytes,n.rrtypes=zn.decode(t,e,s-(e-r)),e+=zn.decode.bytes,da.decode.bytes=e-r,n};da.decode.bytes=0;da.encodingLength=function(t){return 2+Ce.encodingLength(t.nextDomain)+zn.encodingLength(t.rrtypes)};var fa=et.nsec3={};fa.encode=function(t,e,r){e||(e=tt.alloc(fa.encodingLength(t))),r||(r=0);let n=r,s=t.salt;if(!tt.isBuffer(s))throw new Error("salt must be a Buffer");let i=t.nextDomain;if(!tt.isBuffer(i))throw new Error("nextDomain must be a Buffer");return r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.flags,r),r+=1,e.writeUInt16BE(t.iterations,r),r+=2,e.writeUInt8(s.length,r),r+=1,s.copy(e,r,0,s.length),r+=s.length,e.writeUInt8(i.length,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,zn.encode(t.rrtypes,e,r),r+=zn.encode.bytes,fa.encode.bytes=r-n,e.writeUInt16BE(fa.encode.bytes-2,n),e};fa.encode.bytes=0;fa.decode=function(t,e){e||(e=0);let r=e;var n={},s=t.readUInt16BE(e);e+=2,n.algorithm=t.readUInt8(e),e+=1,n.flags=t.readUInt8(e),e+=1,n.iterations=t.readUInt16BE(e),e+=2;let i=t.readUInt8(e);e+=1,n.salt=t.slice(e,e+i),e+=i;let o=t.readUInt8(e);return e+=1,n.nextDomain=t.slice(e,e+o),e+=o,n.rrtypes=zn.decode(t,e,s-(e-r)),e+=zn.decode.bytes,fa.decode.bytes=e-r,n};fa.decode.bytes=0;fa.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+zn.encodingLength(t.rrtypes)};var ha=et.ds={};ha.encode=function(t,e,r){e||(e=tt.alloc(ha.encodingLength(t))),r||(r=0);let n=r,s=t.digest;if(!tt.isBuffer(s))throw new Error("Digest must be a Buffer");return r+=2,e.writeUInt16BE(t.keyTag,r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.digestType,r),r+=1,s.copy(e,r,0,s.length),r+=s.length,ha.encode.bytes=r-n,e.writeUInt16BE(ha.encode.bytes-2,n),e};ha.encode.bytes=0;ha.decode=function(t,e){e||(e=0);let r=e;var n={},s=t.readUInt16BE(e);return e+=2,n.keyTag=t.readUInt16BE(e),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.digestType=t.readUInt8(e),e+=1,n.digest=t.slice(e,r+s+2),e+=n.digest.length,ha.decode.bytes=e-r,n};ha.decode.bytes=0;ha.encodingLength=function(t){return 6+tt.byteLength(t.digest)};var hi=et.sshfp={};hi.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}};hi.encode=function(e,r,n){r||(r=tt.alloc(hi.encodingLength(e))),n||(n=0);let s=n;n+=2,r[n]=e.algorithm,n+=1,r[n]=e.hash,n+=1;let i=tt.from(e.fingerprint.toUpperCase(),"hex");if(i.length!==hi.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return i.copy(r,n),n+=i.byteLength,hi.encode.bytes=n-s,r.writeUInt16BE(hi.encode.bytes-2,s),r};hi.encode.bytes=0;hi.decode=function(e,r){r||(r=0);let n=r,s={};r+=2,s.algorithm=e[r],r+=1,s.hash=e[r],r+=1;let i=hi.getFingerprintLengthForHashType(s.hash);return s.fingerprint=e.slice(r,r+i).toString("hex").toUpperCase(),r+=i,hi.decode.bytes=r-n,s};hi.decode.bytes=0;hi.encodingLength=function(t){return 4+tt.from(t.fingerprint,"hex").byteLength};var pa=et.naptr={};pa.encode=function(t,e,r){e||(e=tt.alloc(pa.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.order||0,r),r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,Mt.encode(t.flags,e,r),r+=Mt.encode.bytes,Mt.encode(t.services,e,r),r+=Mt.encode.bytes,Mt.encode(t.regexp,e,r),r+=Mt.encode.bytes,Ce.encode(t.replacement,e,r),r+=Ce.encode.bytes,pa.encode.bytes=r-n,e.writeUInt16BE(pa.encode.bytes-2,n),e};pa.encode.bytes=0;pa.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.order=t.readUInt16BE(e),e+=2,n.preference=t.readUInt16BE(e),e+=2,n.flags=Mt.decode(t,e),e+=Mt.decode.bytes,n.services=Mt.decode(t,e),e+=Mt.decode.bytes,n.regexp=Mt.decode(t,e),e+=Mt.decode.bytes,n.replacement=Ce.decode(t,e),e+=Ce.decode.bytes,pa.decode.bytes=e-r,n};pa.decode.bytes=0;pa.encodingLength=function(t){return Mt.encodingLength(t.flags)+Mt.encodingLength(t.services)+Mt.encodingLength(t.regexp)+Ce.encodingLength(t.replacement)+6};var ma=et.tlsa={};ma.encode=function(t,e,r){e||(e=tt.alloc(ma.encodingLength(t))),r||(r=0);let n=r,s=t.certificate;if(!tt.isBuffer(s))throw new Error("Certificate must be a Buffer");return r+=2,e.writeUInt8(t.usage,r),r+=1,e.writeUInt8(t.selector,r),r+=1,e.writeUInt8(t.matchingType,r),r+=1,s.copy(e,r,0,s.length),r+=s.length,ma.encode.bytes=r-n,e.writeUInt16BE(ma.encode.bytes-2,n),e};ma.encode.bytes=0;ma.decode=function(t,e){e||(e=0);let r=e,n={},s=t.readUInt16BE(e);return e+=2,n.usage=t.readUInt8(e),e+=1,n.selector=t.readUInt8(e),e+=1,n.matchingType=t.readUInt8(e),e+=1,n.certificate=t.slice(e,r+s+2),e+=n.certificate.length,ma.decode.bytes=e-r,n};ma.decode.bytes=0;ma.encodingLength=function(t){return 5+tt.byteLength(t.certificate)};var vP=et.record=function(t){switch(t.toUpperCase()){case"A":return bc;case"PTR":return mo;case"CNAME":return hhe;case"DNAME":return phe;case"TXT":return mc;case"NULL":return gc;case"AAAA":return _c;case"SRV":return xc;case"HINFO":return yc;case"CAA":return fi;case"NS":return hc;case"SOA":return pc;case"MX":return $u;case"OPT":return pi;case"DNSKEY":return _s;case"RRSIG":return ua;case"RP":return la;case"NSEC":return da;case"NSEC3":return fa;case"SSHFP":return hi;case"DS":return ha;case"NAPTR":return pa;case"TLSA":return ma}return fc},Fn=et.answer={};Fn.encode=function(t,e,r){e||(e=tt.alloc(Fn.encodingLength(t))),r||(r=0);let n=r;if(Ce.encode(t.name,e,r),r+=Ce.encode.bytes,e.writeUInt16BE(vc.toType(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,r+2),e.writeUInt8(t.extendedRcode||0,r+4),e.writeUInt8(t.ednsVersion||0,r+5),e.writeUInt16BE(t.flags||0,r+6),r+=8,pi.encode(t.options||[],e,r),r+=pi.encode.bytes}else{let s=nA.toClass(t.class===void 0?"IN":t.class);t.flush&&(s|=_P),e.writeUInt16BE(s,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let i=vP(t.type);i.encode(t.data,e,r),r+=i.encode.bytes}return Fn.encode.bytes=r-n,e};Fn.encode.bytes=0;Fn.decode=function(t,e){e||(e=0);let r={},n=e;if(r.name=Ce.decode(t,e),e+=Ce.decode.bytes,r.type=vc.toString(t.readUInt16BE(e)),r.type==="OPT")r.udpPayloadSize=t.readUInt16BE(e+2),r.extendedRcode=t.readUInt8(e+4),r.ednsVersion=t.readUInt8(e+5),r.flags=t.readUInt16BE(e+6),r.flag_do=(r.flags>>15&1)===1,r.options=pi.decode(t,e+8),e+=8+pi.decode.bytes;else{let s=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=nA.toString(s&dhe),r.flush=!!(s&_P);let i=vP(r.type);r.data=i.decode(t,e+8),e+=8+i.decode.bytes}return Fn.decode.bytes=e-n,r};Fn.decode.bytes=0;Fn.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Ce.encodingLength(t.name)+8+vP(t.type).encodingLength(e)};var go=et.question={};go.encode=function(t,e,r){e||(e=tt.alloc(go.encodingLength(t))),r||(r=0);let n=r;return Ce.encode(t.name,e,r),r+=Ce.encode.bytes,e.writeUInt16BE(vc.toType(t.type),r),r+=2,e.writeUInt16BE(nA.toClass(t.class===void 0?"IN":t.class),r),r+=2,go.encode.bytes=r-n,t};go.encode.bytes=0;go.decode=function(t,e){e||(e=0);let r=e,n={};return n.name=Ce.decode(t,e),e+=Ce.decode.bytes,n.type=vc.toString(t.readUInt16BE(e)),e+=2,n.class=nA.toString(t.readUInt16BE(e)),e+=2,n.class&TF&&(n.class&=fhe),go.decode.bytes=e-r,n};go.decode.bytes=0;go.encodingLength=function(t){return Ce.encodingLength(t.name)+4};et.AUTHORITATIVE_ANSWER=1024;et.TRUNCATED_RESPONSE=512;et.RECURSION_DESIRED=256;et.RECURSION_AVAILABLE=128;et.AUTHENTIC_DATA=32;et.CHECKING_DISABLED=16;et.DNSSEC_OK=32768;et.encode=function(t,e,r){let n=!e;n&&(e=tt.alloc(et.encodingLength(t))),r||(r=0);let s=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),yo.encode(t,e,r),r+=yo.encode.bytes,r=cb(t.questions,go,e,r),r=cb(t.answers,Fn,e,r),r=cb(t.authorities,Fn,e,r),r=cb(t.additionals,Fn,e,r),et.encode.bytes=r-s,n&&et.encode.bytes!==e.length?e.slice(0,et.encode.bytes):e};et.encode.bytes=0;et.decode=function(t,e){e||(e=0);let r=e,n=yo.decode(t,e);return e+=yo.decode.bytes,e=rA(n.questions,go,t,e),e=rA(n.answers,Fn,t,e),e=rA(n.authorities,Fn,t,e),e=rA(n.additionals,Fn,t,e),et.decode.bytes=e-r,n};et.decode.bytes=0;et.encodingLength=function(t){return yo.encodingLength(t)+l0(t.questions||[],go)+l0(t.answers||[],Fn)+l0(t.authorities||[],Fn)+l0(t.additionals||[],Fn)};et.streamEncode=function(t){let e=et.encode(t),r=tt.alloc(2);r.writeUInt16BE(e.byteLength);let n=tt.concat([r,e]);return et.streamEncode.bytes=n.byteLength,n};et.streamEncode.bytes=0;et.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=et.decode(t.slice(2));return et.streamDecode.bytes=et.decode.bytes,r};et.streamDecode.bytes=0;function l0(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function cb(t,e,r,n){for(let s=0;s<t.length;s++)e.encode(t[s],r,n),n+=e.encode.bytes;return n}function rA(t,e,r,n){for(let s=0;s<t.length;s++)t[s]=e.decode(r,n),n+=e.decode.bytes;return n}});var OF=v((h8e,RF)=>{"use strict";var PF=_he;process.nextTick(bhe,42);RF.exports=mhe;function mhe(t){var e=n;return r;function r(s){e(s||yhe)}function n(s){var i=[s];e=o,t(a);function o(c){i.push(c)}function a(c){var u=arguments;for(e=ghe(c)?n:l;i.length;)l(i.shift());function l(d){PF(xhe,d,u)}}}}function ghe(t){return Object.prototype.toString.call(t)==="[object Error]"}function yhe(){}function xhe(t,e){t.apply(null,e)}function bhe(t){t===42&&(PF=process.nextTick)}function _he(t,e,r){process.nextTick(function(){t(e,r)})}});var $F=v((p8e,BF)=>{var wP=IF(),vhe=on("dgram"),whe=OF(),She=on("events"),AP=on("os"),SP=function(){};BF.exports=function(t){t||(t={});var e=new She.EventEmitter,r=typeof t.port=="number"?t.port:5353,n=t.type||"udp4",s=t.ip||t.host||(n==="udp4"?"224.0.0.251":null),i={address:s,port:r},o={},a=!1,c=null;if(n==="udp6"&&(!s||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var u=t.socket||vhe.createSocket({type:n,reuseAddr:t.reuseAddr!==!1,toString:function(){return n}});u.on("error",function(d){d.code==="EACCES"||d.code==="EADDRINUSE"?e.emit("error",d):e.emit("warning",d)}),u.on("message",function(d,f){try{d=wP.decode(d)}catch(p){e.emit("warning",p);return}e.emit("packet",d,f),d.type==="query"&&e.emit("query",d,f),d.type==="response"&&e.emit("response",d,f)}),u.on("listening",function(){r||(r=i.port=u.address().port),t.multicast!==!1&&(e.update(),c=setInterval(e.update,5e3),u.setMulticastTTL(t.ttl||255),u.setMulticastLoopback(t.loopback!==!1))});var l=whe(function(d){if(!r||t.bind===!1)return d(null);u.once("error",d),u.bind(r,t.bind||t.interface,function(){u.removeListener("error",d),d(null)})});return l(function(d){if(d)return e.emit("error",d);e.emit("ready")}),e.send=function(d,f,p){if(typeof f=="function")return e.send(d,null,f);p||(p=SP),f?!f.host&&!f.address&&(f.address=i.address):f=i,l(m);function m(y){if(a)return p();if(y)return p(y);var _=wP.encode(d);u.send(_,0,_.length,f.port,f.address||f.host,p)}},e.response=e.respond=function(d,f,p){Array.isArray(d)&&(d={answers:d}),d.type="response",d.flags=(d.flags||0)|wP.AUTHORITATIVE_ANSWER,e.send(d,f,p)},e.query=function(d,f,p,m){if(typeof f=="function")return e.query(d,null,null,f);if(typeof f=="object"&&f&&f.port)return e.query(d,null,f,p);if(typeof p=="function")return e.query(d,f,null,p);m||(m=SP),typeof d=="string"&&(d=[{name:d,type:f||"ANY"}]),Array.isArray(d)&&(d={type:"query",questions:d}),d.type="query",e.send(d,p,m)},e.destroy=function(d){if(d||(d=SP),a)return process.nextTick(d);a=!0,clearInterval(c);for(var f in o)try{u.dropMembership(s,f)}catch{}o={},u.close(d)},e.update=function(){for(var d=t.interface?[].concat(t.interface):Ehe(),f=!1,p=0;p<d.length;p++){var m=d[p];if(!o[m])try{u.addMembership(s,m),o[m]=!0,f=!0}catch(y){e.emit("warning",y)}}if(f){if(u.setMulticastInterface)try{u.setMulticastInterface(t.interface||Ahe())}catch(y){e.emit("warning",y)}e.emit("networkInterface")}},e};function Ahe(){for(var t=AP.networkInterfaces(),e=Object.keys(t),r=0;r<e.length;r++)for(var n=t[e[r]],s=0;s<n.length;s++){var i=n[s];if(NF(i.family)&&!i.internal)return AP.platform()==="darwin"&&e[r]==="en0"?i.address:"0.0.0.0"}return"127.0.0.1"}function Ehe(){for(var t=AP.networkInterfaces(),e=Object.keys(t),r=[],n=0;n<e.length;n++)for(var s=t[e[n]],i=0;i<s.length;i++){var o=s[i];if(NF(o.family)){r.push(o.address);break}}return r}function NF(t){return t===4||t==="IPv4"}});var kW={};$a(kW,{AV1Obu:()=>FK,AV1RtpPayload:()=>WP,AttributeKeys:()=>a0e,BitStream:()=>qu,BitWriter:()=>Bb,BitWriter2:()=>LA,BufferChain:()=>Ihe,CONSENT_FAILURES:()=>b8,CONSENT_INTERVAL:()=>hG,COOKIE:()=>GA,Candidate:()=>Vu,CandidatePair:()=>y8,CandidatePairState:()=>pG,CipherContext:()=>zb,CipherSuite:()=>CA,CipherSuiteList:()=>pK,Connection:()=>wG,ConnectionStates:()=>oge,CurveType:()=>G8,DEFAULT_MAX_MESSAGE_SIZE:()=>b0,DePacketizerBase:()=>Rpe,Directions:()=>mA,DtlsClient:()=>d8,DtlsServer:()=>FZ,DtlsSocket:()=>s5,DtlsStates:()=>yme,Event:()=>Be,EventDisposer:()=>uK,ExtensionProfiles:()=>Du,FINGERPRINT_LENGTH:()=>VZ,FINGERPRINT_XOR:()=>KZ,GenericNack:()=>Fb,GroupDescription:()=>S0,H264RtpPayload:()=>GK,HEADER_LENGTH:()=>Ac,HashAlgorithm:()=>jb,ICE_COMPLETED:()=>x8,ICE_FAILED:()=>Tb,INTEGRITY_LENGTH:()=>i5,IPV4_PROTOCOL:()=>o5,IPV6_PROTOCOL:()=>a5,IceCandidate:()=>P5,IceGathererStates:()=>Ame,IceTransportStates:()=>Sme,Inactive:()=>BG,Int:()=>Ub,MediaDescription:()=>jA,MediaStream:()=>MG,MediaStreamTrack:()=>Wb,MediaStreamTrackFactory:()=>ome,Message:()=>$i,NalUnitType:()=>Lu,NamedCurveAlgorithm:()=>Tc,NamedCurveAlgorithmList:()=>Z8,OpusRtpPayload:()=>XK,PacketChunk:()=>cZ,PacketResult:()=>lZ,PacketStatus:()=>uZ,PictureLossIndication:()=>qb,Profiles:()=>Epe,PromiseQueue:()=>jhe,ProtectionProfileAeadAes128Gcm:()=>hf,ProtectionProfileAes128CmHmacSha1_80:()=>R0,RETRY_MAX:()=>ZZ,RETRY_RTO:()=>GZ,RTCCertificate:()=>I5,RTCDataChannel:()=>p5,RTCDataChannelParameters:()=>m5,RTCDtlsFingerprint:()=>BA,RTCDtlsParameters:()=>$A,RTCDtlsTransport:()=>A8,RTCIceCandidate:()=>ZG,RTCIceGatherer:()=>VG,RTCIceParameters:()=>R5,RTCIceTransport:()=>FG,RTCP_HEADER_SIZE:()=>IA,RTCPeerConnection:()=>rge,RTCRtcpFeedback:()=>EG,RTCRtcpParameters:()=>B0e,RTCRtpCodecParameters:()=>Ku,RTCRtpCodingParameters:()=>kG,RTCRtpHeaderExtensionParameters:()=>wa,RTCRtpReceiver:()=>M5,RTCRtpRtxParameters:()=>CG,RTCRtpSender:()=>SW,RTCRtpSimulcastParameters:()=>g5,RTCRtpTransceiver:()=>NG,RTCSctpCapabilities:()=>N5,RTCSctpTransport:()=>xW,RTCSessionDescription:()=>vW,RTCStatsReport:()=>OG,RTP_EXTENSION_URI:()=>Ur,ReceiverEstimatedMaxBitrate:()=>Hb,RecvDelta:()=>Rb,Recvonly:()=>w5,Red:()=>t5,RedEncoder:()=>PZ,RedHandler:()=>RZ,RedHeader:()=>a8,RtcpHeader:()=>Rc,RtcpPacketConverter:()=>mZ,RtcpPayloadSpecificFeedback:()=>E0,RtcpReceiverInfo:()=>ZA,RtcpRrPacket:()=>C0,RtcpSenderInfo:()=>e5,RtcpSourceDescriptionPacket:()=>Kb,RtcpSrPacket:()=>uf,RtcpTransportLayerFeedback:()=>cf,RtpBuilder:()=>Xpe,RtpHeader:()=>Ic,RtpPacket:()=>Pc,RtpRouter:()=>wW,RunLengthChunk:()=>w0,SDPManager:()=>AW,Sendonly:()=>v5,Sendrecv:()=>S5,SessionDescription:()=>Nb,SignalingStates:()=>ige,SignatureAlgorithm:()=>va,SignatureScheme:()=>UP,SourceDescriptionChunk:()=>Y8,SourceDescriptionItem:()=>Q8,SrtcpSession:()=>UZ,SrtpAuthenticationError:()=>lf,SrtpContext:()=>Lb,SrtpSession:()=>qZ,SsrcDescription:()=>zA,StatusVectorChunk:()=>oZ,StunOverTurnProtocol:()=>iG,StunProtocol:()=>PA,TcpTransport:()=>fK,TransceiverManager:()=>CW,TransportWideCC:()=>Vb,TurnProtocol:()=>aG,UdpTransport:()=>EA,Vp8RtpPayload:()=>YK,Vp9RtpPayload:()=>eZ,WeriftError:()=>Lhe,addSDPHeader:()=>D8,andDirection:()=>C5,buffer2ArrayBuffer:()=>Rhe,bufferArrayXor:()=>khe,bufferReader:()=>ws,bufferWriter:()=>Zr,bufferWriterLE:()=>JV,bufferXor:()=>Che,candidateFoundation:()=>RA,candidateFromIce:()=>T0,candidateFromSdp:()=>$5,candidatePairPriority:()=>OA,candidatePriority:()=>Ob,candidateToIce:()=>KG,candidateToSdp:()=>B5,certificateTypes:()=>mK,classes:()=>c5,codecParametersFromString:()=>Yb,codecParametersToString:()=>Zme,compactNtp:()=>T5,crc32:()=>nK,crc32c:()=>V8,createBufferWriter:()=>Pb,createSelfSignedCertificate:()=>ime,createStunOverTurnClient:()=>m8,createTurnClient:()=>uG,dePacketizeRtpPackets:()=>Ope,debug:()=>wt,deepMerge:()=>qG,defaultOptions:()=>mG,defaultPeerConfig:()=>nge,depacketizerCodecs:()=>Npe,deserializeAbsSendTime:()=>EZ,deserializeAudioLevelIndication:()=>CZ,deserializeString:()=>SZ,deserializeUint16BE:()=>AZ,deserializeVideoOrientation:()=>kZ,dumpBuffer:()=>Phe,enumerate:()=>Bpe,findCodecByMimeType:()=>q8,findPort:()=>aK,fingerprint:()=>A5,generateStatsId:()=>vr,getBit:()=>Ae,getDataChannelMessageSize:()=>SG,getGlobalIp:()=>T0e,getHostAddresses:()=>vG,getStatsTimestamp:()=>Zu,growBufferSize:()=>XP,int:()=>_0,interfaceAddress:()=>UA,isDtls:()=>jG,isLinkLocalAddress:()=>_G,isMedia:()=>rZ,isRtcp:()=>gZ,keyLength:()=>DK,leb128decode:()=>KK,makeIntegrityKey:()=>lG,methods:()=>u5,microTime:()=>LG,milliTime:()=>k5,nodeIpAddress:()=>w8,normalizeFamilyNodeV18:()=>Mb,normalizeFingerprintAlgorithm:()=>E5,normalizeFingerprintValue:()=>NA,ntpTime:()=>DG,ntpTime2Sec:()=>pZ,paddingBits:()=>The,paddingByte:()=>$b,paddingLength:()=>h8,parseGroup:()=>SA,parseIceServers:()=>UG,parseMessage:()=>WA,random16:()=>F8,random32:()=>AA,randomPort:()=>K8,randomPorts:()=>zhe,reverseDirection:()=>zG,reverseSimulcastDirection:()=>nme,rtpHeaderExtensionsParser:()=>yZ,saltLength:()=>UK,serializeAbsSendTime:()=>wZ,serializeAudioLevelIndication:()=>Dpe,serializeRepairedRtpStreamId:()=>_Z,serializeSdesMid:()=>xZ,serializeSdesRTPStreamID:()=>bZ,serializeTransportWideCC:()=>vZ,serverReflexiveCandidate:()=>yG,signatures:()=>W8,sortCandidatePairs:()=>gG,supportedAudioCodecs:()=>M0e,supportedCodecs:()=>_5,supportedVideoCodecs:()=>$0e,timer:()=>$pe,timestampSeconds:()=>Xb,uint16Add:()=>Kn,uint16Gt:()=>DA,uint16Gte:()=>Mhe,uint24:()=>iK,uint32Add:()=>tf,uint32Gt:()=>xa,uint32Gte:()=>x0,uint8Add:()=>sK,unwrapRtx:()=>NZ,url2Address:()=>I0e,useAV1X:()=>PG,useAbsSendTime:()=>U0e,useAudioLevelIndication:()=>H0e,useDependencyDescriptor:()=>q0e,useFIR:()=>N0e,useH264:()=>TG,useNACK:()=>o1,useOPUS:()=>x5,usePCMU:()=>b5,usePLI:()=>N0,useREMB:()=>a1,useRepairedRtpStreamId:()=>L0e,useSdesMid:()=>j0e,useSdesRTPStreamId:()=>z0e,useTWCC:()=>AG,useTransportWideCC:()=>D0e,useVP8:()=>y5,useVP9:()=>IG,useVideoOrientation:()=>F0e,validateAddress:()=>v8,validateRemoteCandidate:()=>_8,wrapRtx:()=>BZ});import{randomBytes as XV}from"crypto";import{createSocket as oK}from"dgram";import{createSocket as Dhe}from"dgram";import*as lK from"node:net";import{connect as Uhe}from"node:net";import{createSign as qhe,randomBytes as Hhe,webcrypto as Fhe}from"crypto";import{createHash as Vhe,createHmac as Khe}from"crypto";import{randomBytes as cpe}from"crypto";import{setTimeout as upe}from"timers/promises";import{createCipheriv as _pe,createDecipheriv as vpe}from"crypto";import{createHmac as CP}from"crypto";import{createCipheriv as XF,createDecipheriv as JF,createHmac as YF,timingSafeEqual as Hpe}from"crypto";import{createCipheriv as rV,createDecipheriv as nV}from"crypto";import{setTimeout as Ype}from"timers/promises";import{randomBytes as n0e}from"crypto";import{createHmac as WZ}from"crypto";import{randomBytes as XZ}from"crypto";import{createHash as y0e}from"crypto";import{setTimeout as x0e}from"timers/promises";import{createHash as w0e}from"crypto";import{isIPv4 as bV}from"net";import{randomBytes as S0e}from"crypto";import{isIPv4 as _V}from"net";import*as g8 from"node:timers/promises";import{randomUUID as E0e}from"crypto";import*as xG from"node:os";import{EventEmitter as R0e}from"node:events";import{randomUUID as V0e}from"crypto";import{setTimeout as $P}from"timers/promises";import{createHash as K0e}from"crypto";import{createSocket as Z0e}from"dgram";import{performance as SV}from"perf_hooks";import{randomUUID as G0e}from"crypto";import{randomUUID as $G}from"crypto";import{setTimeout as ume}from"timers/promises";import{randomBytes as hme}from"crypto";import{isIPv4 as pme}from"net";import{randomUUID as mme}from"crypto";import{setTimeout as gme}from"timers/promises";import{randomUUID as wme}from"crypto";import{randomUUID as Eme}from"crypto";import{createHmac as BV,randomBytes as Cme}from"crypto";import{randomBytes as VV}from"crypto";import{randomUUID as KV}from"crypto";import{setTimeout as ZV}from"timers/promises";import{randomUUID as Jme}from"crypto";function F8(){return H8.jspack.Unpack("!H",XV(2))[0]}function AA(){return H8.jspack.Unpack("!L",XV(4))[0]}function Che(t,e){if(t.length!==e.length)throw new TypeError("[webrtc-stun] You can not XOR buffers which length are different");let r=t.length,n=Buffer.allocUnsafe(r);for(let s=0;s<r;s++)n[s]=t[s]^e[s];return n}function khe(t){let e=[...t].sort((n,s)=>n.length-s.length).reverse()[0].length,r=Buffer.allocUnsafe(e);for(let n=0;n<e;n++)r[n]=0,t.forEach(s=>{r[n]^=s[n]??0});return r}function Ae(t,e,r=1){let n=t.toString(2).split("");n=[...Array(8-n.length).fill("0"),...n];let s=n.slice(e,e+r).join("");return Number.parseInt(s,2)}function $b(t){let e=t.toString(2).split("");return[...[...Array(8-e.length)].map(()=>"0"),...e].join("")}function The(t,e){let r=t.toString(2);return[...[...Array(e-r.length)].map(()=>"0"),...r].join("")}function Zr(t,e){return Pb(t)(e)}function Pb(t,e){let r=t.reduce((s,i)=>s+i,0),n=e?Buffer.alloc(r):void 0;return s=>{let i=n||Buffer.alloc(r),o=0;return s.forEach((a,c)=>{let u=t[c];u===8?i.writeBigUInt64BE(a,o):i.writeUIntBE(a,o,u),o+=u}),i}}function JV(t,e){let r=t.reduce((i,o)=>i+o,0),n=Buffer.alloc(r),s=0;return e.forEach((i,o)=>{let a=t[o];a===8?n.writeBigUInt64LE(i,s):n.writeUIntLE(i,s,a),s+=a}),n}function ws(t,e){let r=0;return e.map(n=>{let s;return n===8?s=t.readBigUInt64BE(r):s=t.readUIntBE(r,n),r+=n,s})}function Rhe(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function YV(t){return typeof t!="string"}function QV(t){let e=new Array(256),r=0;for(let n=0;n<256;++n)r=n,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,e[n]=r;return new Int32Array(e)}function eK(t){let e=new Int32Array(4096),r=0,n=0,s=0;for(s=0;s<256;++s)e[s]=t[s];for(s=0;s<256;++s)for(n=t[s],r=256+s;r<4096;r+=256)n=e[r]=n>>>8^t[n&255];let i=[];for(s=1;s<16;++s)i[s-1]=e.subarray(s*256,s*256+256);return i}function tK(t,e,r){let n=e^-1,s=0,i=t.length,o=0,a=0;for(;s<i;)o=t.charCodeAt(s++),o<128?n=n>>>8^r[(n^o)&255]:o<2048?(n=n>>>8^r[(n^(192|o>>6&31))&255],n=n>>>8^r[(n^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,a=t.charCodeAt(s++)&1023,n=n>>>8^r[(n^(240|o>>8&7))&255],n=n>>>8^r[(n^(128|o>>2&63))&255],n=n>>>8^r[(n^(128|a>>6&15|(o&3)<<4))&255],n=n>>>8^r[(n^(128|a&63))&255]):(n=n>>>8^r[(n^(224|o>>12&15))&255],n=n>>>8^r[(n^(128|o>>6&63))&255],n=n>>>8^r[(n^(128|o&63))&255]);return~n>>>0}function rK(t,e,r,n){let[s,i,o,a,c,u,l,d,f,p,m,y,_,S,C]=n,E=e^-1,B=0,G=t.length-15;for(;B<G;)E=C[t[B++]^E&255]^S[t[B++]^E>>>8&255]^_[t[B++]^E>>>16&255]^y[t[B++]^E>>>24]^m[t[B++]]^p[t[B++]]^f[t[B++]]^d[t[B++]]^l[t[B++]]^u[t[B++]]^c[t[B++]]^a[t[B++]]^o[t[B++]]^i[t[B++]]^s[t[B++]]^r[t[B++]];for(G+=15;B<G;)E=E>>>8^r[(E^t[B++])&255];return~E>>>0}function nK(t,e=0){return YV(t)?rK(t,e,LP,Bhe):tK(t,e,LP)}function V8(t,e=0){return YV(t)?rK(t,e,DP,$he):tK(t,e,DP)}function sK(t,e){return t+e&255}function Kn(t,e){return t+e&65535}function tf(t,e){return Number(BigInt(t)+BigInt(e)&0xffffffffn)}function iK(t){return t&16777215}function DA(t,e){return t<e&&e-t>32768||t>e&&t-e<32768}function Mhe(t,e){return t===e||DA(t,e)}function xa(t,e){return t<e&&e-t>2147483648||t>e&&t-e<2147483648}function x0(t,e){return t===e||xa(t,e)}async function K8(t="udp4",e){let r=oK(t);setImmediate(()=>r.bind({port:0,address:UA(t,e)})),await new Promise(s=>{r.once("error",s),r.once("listening",s)});let n=r.address()?.port;return await new Promise(s=>r.close(()=>s())),n}async function zhe(t,e="udp4",r){return Promise.all([...Array(t)].map(()=>K8(e,r)))}async function aK(t,e,r="udp4",n){let s;for(let i=t;i<=e;i++){let o=oK(r);if(setImmediate(()=>o.bind({port:i,address:UA(r,n)})),await new Promise(c=>{o.once("error",u=>c(u)),o.once("listening",()=>c())})){await new Promise(c=>o.close(()=>c()));continue}if(s=o.address()?.port,await new Promise(c=>o.close(()=>c())),t<=s&&s<=e)break}if(!s)throw new Error("port not found");return s}function Mb(t){return t==="IPv4"?4:t==="IPv6"?6:t}function xK(t,e,r){switch(r){case Tc.secp256r1_23:return Ghe({publicKey:t,privateKey:e});case Tc.x25519_29:return Buffer.from(yK.default.scalarMult(e,t));default:throw new Error}}function jF(t,e,r){let n=Khe(t,e);return n.update(r),n.digest()}function Qb(t,e,r,n="sha256"){let s=r,i=[],o=e;do{o=jF(n,t,o);let a=jF(n,t,Buffer.concat([o,e]));i.push(a),r-=a.length}while(r>0);return Buffer.concat(i,s)}function bK(t,e,r){let n=Buffer.concat([Buffer.from("master secret"),e,r]);return Qb(t,n,48)}function _K(t,e){let r=vK("sha256",e);return Qb(t,Buffer.concat([Buffer.from("extended master secret"),r]),48)}function Whe(t,e,r,n,s,i){let o=i?n:s,a=i?s:n,c=Buffer.concat([Buffer.from(t),o,a]);return Qb(r,c,e)}function vK(t,e){return Vhe(t).update(e).digest()}function wK(t,e,r,n=12){let s=vK("sha256",e);return Qb(t,Buffer.concat([Buffer.from(r),s]),n)}function Xhe(t,e){return wK(t,e,"client finished")}function Jhe(t,e){return wK(t,e,"server finished")}function Yhe(t,e,r,n,s,i,o="sha256"){let a=n*2+s*2,c=t,u=Buffer.concat([r,e]),l=Qb(c,Buffer.concat([Buffer.from("key expansion"),u]),a,o),d=(0,gK.createDecode)(l),f=d.readBuffer(n),p=d.readBuffer(n),m=d.readBuffer(s),y=d.readBuffer(s),_=Buffer.alloc(i,0),S=Buffer.alloc(i,0);return m.copy(_,0),y.copy(S,0),{clientWriteKey:f,serverWriteKey:p,clientNonce:_,serverNonce:S}}function mpe(){let t=new s1;return t.id=n1.RSA,t.name="RSA",t.keyType=r1.RSA,t}function gpe(){let t=new s1;return t.id=n1.ECDHE_RSA,t.name="ECDHE_RSA",t.signType=HA.ECDHE,t.keyType=r1.RSA,t}function ype(){let t=new s1;return t.id=n1.ECDHE_ECDSA,t.name="ECDHE_ECDSA",t.signType=HA.ECDHE,t.keyType=r1.ECDSA,t}function xpe(){let t=new s1;return t.id=n1.PSK,t.name="PSK",t.signType=HA.NULL,t.keyType=r1.PSK,t}function bpe(){let t=new s1;return t.id=n1.ECDHE_PSK,t.name="ECDHE_PSK",t.signType=HA.ECDHE,t.keyType=r1.PSK,t}function IK(t){switch(t){case _n.TLS_RSA_WITH_AES_128_GCM_SHA256:return ga(_n.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",zF,ub);case _n.TLS_RSA_WITH_AES_256_GCM_SHA384:return ga(_n.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",zF,lb,"sha384");case _n.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return ga(_n.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",LF,ub);case _n.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return ga(_n.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",LF,lb,"sha384");case _n.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return ga(_n.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",DF,ub);case _n.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return ga(_n.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",DF,lb,"sha384");case _n.TLS_PSK_WITH_AES_128_GCM_SHA256:return ga(_n.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",UF,ub,"sha256");case _n.TLS_PSK_WITH_AES_256_GCM_SHA384:return ga(_n.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",UF,lb,"sha384");case _n.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return ga(_n.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",qF,ub,"sha256");case _n.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return ga(_n.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",qF,lb,"sha384");default:break}return null}function ga(t,e,r,n,s,i="sha256"){let o=new Spe;return o.id=t,o.name=e,o.blockAlgorithm=r,o.kx=n,o.hashAlgorithm=i,o.keyLength=s.K_LEN,o.nonceLength=s.N_MAX,o.nonceImplicitLength=4,o.nonceExplicitLength=8,o.ivLength=o.nonceImplicitLength,o.authTagLength=16,o}function RK(t){switch(t){case Tc.secp256r1_23:{let{privateKey:e,publicKey:r}=Zhe();return{curve:t,privateKey:e,publicKey:r}}case Tc.x25519_29:{let e=PK.default.box.keyPair();return{curve:t,privateKey:Buffer.from(e.secretKey.buffer),publicKey:Buffer.from(e.publicKey.buffer)}}default:throw new Error}}function Ape(t,e){return Buffer.from((0,zK.encode)(t,e).slice())}function KK(t){let e=0,r=0;for(let n=0;n<8;n++){let s=t.readUInt8(n);if(e|=(s&127)<<n*7,r++,!(s&128))break}return[e,r]}function Ope(t,e,r){let n=s=>{let i=[];for(let c of e){let u=s.deSerialize(c.payload,r);u.fragment?(r??=Buffer.alloc(0),r=u.fragment):u.payload&&(r=void 0),i.push(u)}let o=!!i.find(c=>c.isKeyframe),a=Buffer.concat(i.map(c=>c.payload).filter(c=>c));return{isKeyframe:o,data:a,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0,frameFragmentBuffer:r}};switch(t.toUpperCase()){case"AV1":{let s=e.map(a=>WP.deSerialize(a.payload)),i=!!s.find(a=>a.isKeyframe),o=WP.getFrame(s);return{isKeyframe:i,data:o,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0}}case"MPEG4/ISO/AVC":return n(GK);case"VP8":return n(YK);case"VP9":return n(eZ);case"OPUS":return n(XK);default:throw new Error}}function Bpe(t){return t.map((e,r)=>[r,e])}function XP(t,e){let r=Buffer.alloc(e);return t.copy(r),r}function Ub(t){return Number.parseInt(t.toString(),10)}function rZ(t){let e=t[0];return e>127&&e<192}function FF(t){return t%4==0?0:4-t%4}function gZ(t){return t.length>=2&&t[1]>=192&&t[1]<=208}function yZ(t,e){return t.map(r=>{let n=e[r.id];if(!n)return{uri:"unknown",value:r.payload};switch(n){case Ur.sdesMid:case Ur.sdesRTPStreamID:case Ur.repairedRtpStreamId:return{uri:n,value:SZ(r.payload)};case Ur.transportWideCC:return{uri:n,value:AZ(r.payload)};case Ur.absSendTime:return{uri:n,value:EZ(r.payload)};case Ur.audioLevelIndication:return{uri:n,value:CZ(r.payload)};case Ur.videoOrientation:return{uri:n,value:kZ(r.payload)};default:return{uri:n,value:r.payload}}}).reduce((r,n)=>(n&&(r[n.uri]=n.value),r),{})}function xZ(t){return Buffer.from(t)}function bZ(t){return Buffer.from(t)}function _Z(t){return Buffer.from(t)}function vZ(t){return Zr([2],[t])}function wZ(t){let e=Buffer.alloc(3),r=t>>14n&0x00ffffffn;return e.writeUIntBE(Number(r),0,3),e}function Dpe(t){let e=new qu(Buffer.alloc(1));return e.writeBits(1,1),e.writeBits(7,t),e.uint8Array}function SZ(t){return t.toString()}function AZ(t){return t.readUInt16BE()}function EZ(t){return ws(t,[3])[0]}function CZ(t){let e=new qu(t);return{v:e.readBits(1)===1,level:e.readBits(7)}}function kZ(t){let e=new qu(t);return e.readBits(4),{c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)}}function NZ(t,e,r){return new Pc(new Ic({payloadType:e,marker:t.header.marker,sequenceNumber:r5.jspack.Unpack("!H",t.payload.subarray(0,2))[0],timestamp:t.header.timestamp,ssrc:r}),t.payload.subarray(2))}function BZ(t,e,r,n){return new Pc(new Ic({payloadType:e,marker:t.header.marker,sequenceNumber:r,timestamp:t.header.timestamp,ssrc:n,csrc:t.header.csrc,extensions:t.header.extensions}),Buffer.concat([Buffer.from(r5.jspack.Pack("!H",[t.header.sequenceNumber])),t.payload]))}function n5(t,e,r="Failed to authenticate SRTP packet"){let n=t.length-e;Zb(t.length>=QF+e,r);let s=jZ(()=>Ic.deSerialize(t.subarray(0,n)),r);return s.paddingSize=0,Zb(s.payloadOffset>=QF&&s.payloadOffset<=n,r),s}function MZ(t,e,r,n="Failed to authenticate SRTCP packet"){return Zb(t.length>=Fpe+e+r,n),jZ(()=>Rc.deSerialize(t.subarray(0,IA)),n)}function Zb(t,e){if(!t)throw new lf(e)}function jZ(t,e){try{return t()}catch{throw new lf(e)}}function zZ(t,e,r="Failed to authenticate SRTP packet"){if(!t.padding)return t.paddingSize=0,t;Zb(e.length>t.payloadOffset,r);let n=e[e.length-1];return Zb(n>0&&n<=e.length-t.payloadOffset,r),t.paddingSize=n,t}function tV(t,e,r){if(t.length!==e.length||!Hpe(t,e))throw new lf(r)}function iV(t,e){try{t.final()}catch{throw new lf(`Failed to authenticate ${e} packet`)}}function fb(t){return XZ(t).toString("hex").substring(0,t)}function JZ(){return XZ(12)}function m0(t){let[e]=t,r=Gb.default.isV4Format(e)?o5:a5,n=Buffer.alloc(4);return n.writeUInt8(0,0),n.writeUInt8(r,1),n.writeUInt16BE(t[1],2),Buffer.concat([n,Gb.default.toBuffer(e)])}function c0e(t){if(t.length<4)throw new Error("STUN error code is less than 4 bytes");let e=t.readUInt8(2),r=t.readUInt8(3),n=t.slice(4).toString("utf8");return[e*100+r,n]}function g0(t){if(t.length<4)throw new Error("STUN address length is less than 4 bytes");let e=t.readUInt8(1),r=t.readUInt16BE(2),n=t.slice(4);switch(e){case o5:if(n.length!=4)throw new Error("STUN address has invalid length for IPv4");return[Gb.default.toString(n),r];case a5:if(n.length!=16)throw new Error("STUN address has invalid length for IPv6");return[Gb.default.toString(n),r];default:throw new Error("STUN address has unknown protocol")}}function YZ(t,e){let r=[...l5,...e],n=t.slice(0,2);for(let s=2;s<t.length;s++){let i=t[s]^r[s-2],o=Buffer.alloc(1);o.writeUIntBE(i,0,1),n=Buffer.concat([n,o])}return n}function dA(t,e){return g0(YZ(t,e))}function u0e(t){let e=Buffer.alloc(4);e.writeUInt16BE(0,0),e.writeUInt8(Math.floor(t[0]/100),2),e.writeUInt8(t[0]%100,3);let r=Buffer.from(t[1],"utf8");return Buffer.concat([e,r])}function fA(t,e){return YZ(m0(t),e)}function WA(t,e){if(t.length<Ac)return;let r=t.readUint16BE(2);if(t.length!==Ac+r)return;let n=t.readUint16BE(0),s=Buffer.from(t.slice(Ac-12,Ac)),i=new eG;for(let a=Ac;a<=t.length-4;){let c=t.readUInt16BE(a),u=t.readUInt16BE(a+2),l=t.slice(a+4,a+4+u),d=4*Math.floor((u+3)/4)-u;if(Object.keys(gV).includes(c.toString())){let[,p,,m]=gV[c];if(m.name===dA.name?i.setAttribute(p,m(l,s)):i.setAttribute(p,m(l)),p==="FINGERPRINT"){let y=tG(t.slice(0,a));if(i.getAttributeValue("FINGERPRINT")!==y)return}else if(p==="MESSAGE-INTEGRITY"&&e){let y=m0e(t.slice(0,a),e),_=i.getAttributeValue("MESSAGE-INTEGRITY");if(!y.equals(_))return}}a+=4+u+d}let o=i.getAttributes();return i.clear(),new $i(n&16111,n&272,s,o)}function tG(t){let e=d5(t,t.length-Ac+VZ);return(nK(e)^KZ)>>>0}function m0e(t,e){let r=d5(t,t.length-Ac+i5);return Buffer.from(WZ("sha1",e).update(r).digest("hex"),"hex")}function h8(t){let e=t%4;return e===0?0:4-e}async function uG({address:t,username:e,password:r},{lifetime:n,portRange:s,interfaceAddresses:i,transport:o}={}){n??=_0e,o??="udp";let a=o==="udp"?await EA.init("udp4",{portRange:s,interfaceAddresses:i}):await fK.init(t),c=new aG(t,e,r,n,a);return await c.connectionMade(),c}async function m8({address:t,username:e,password:r},{lifetime:n,portRange:s,interfaceAddresses:i,transport:o}={}){let a=await uG({address:t,username:e,password:r},{lifetime:n,portRange:s,interfaceAddresses:i,transport:o});return new iG(a)}function lG(t,e,r){return y0e("md5").update(Buffer.from([t,e,r].join(":"))).digest()}function xV(t){return(t[0]&192)==64}function RA(t,e,r){let n=`${t}|${e}|${r}`;return w0e("md5").update(n,"ascii").digest("hex").slice(7)}function Ob(t,e=65535){let n=0;return t==="host"?n=126:t==="prflx"?n=110:t==="srflx"?n=100:n=0,(1<<24)*n+256*e+255}function _8(t){if(!["host","relay","srflx"].includes(t.type))throw new Error(`Unexpected candidate type "${t.type}"`);return t}function gG(t,e){return t.sort((r,n)=>OA(r.localCandidate,r.remoteCandidate,e)-OA(n.localCandidate,n.remoteCandidate,e)).reverse()}function OA(t,e,r){let n=r&&t.priority||e.priority,s=r&&e.priority||t.priority;return 1*Math.min(n,s)+2*Math.max(n,s)+(n>s?1:0)}async function yG(t,e){let r=new $i(1,0);try{let[n]=await t.request(r,e),s=t.localCandidate;if(!s)throw new Error("not exist");return new Vu(RA("srflx","udp",s.host),s.component,s.transport,Ob("srflx"),n.getAttributeValue("XOR-MAPPED-ADDRESS")[0],n.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",s.host,s.port)}catch(n){C0e("error serverReflexiveCandidate",n)}}function v8(t){return t&&Number.isNaN(t[1])?[t[0],443]:t}async function T0e(t,e){let r=new PA;await r.connectionMade(!0,void 0,e);let n=new $i(1,0),[s]=await r.request(n,t??["stun.l.google.com",19302]);return await r.close(),s.getAttributeValue("XOR-MAPPED-ADDRESS")[0]}function _G(t){return Mb(t.family)===4&&t.address?.startsWith("169.254.")||Mb(t.family)===6&&t.address?.startsWith("fe80::")}function w8(t,{useLinkLocalAddress:e}={}){let r=["ipsec","tun","utun","tap"],n=["vmnet","veth"],s=xG.networkInterfaces();k0e(s);let i=Object.keys(s).map(o=>{for(let c of[...r,...n])if(o.startsWith(c))return{nic:o,addresses:[]};let a=s[o].filter(c=>Mb(c.family)===t&&!bG.default.isLoopback(c.address)&&(e?!0:!_G(c)));return{nic:o,addresses:a.map(c=>c.address)}}).filter(o=>!!o);return i.sort((o,a)=>o.nic.localeCompare(a.nic)),Object.values(i).flatMap(o=>o.addresses)}function vG(t,e,r={}){let n=[];return t&&n.push(...w8(4,r)),e&&n.push(...w8(6,r)),n}function wV(t){return t.map((e,r)=>[r,e])}function Sc(t,e){let r=t.split(e);return[r[0],r.slice(1).join(e)]}function SG(t){return Buffer.isBuffer(t)?t.length:Buffer.byteLength(t)}function j0e(){return new wa({uri:Ur.sdesMid})}function z0e(){return new wa({uri:Ur.sdesRTPStreamID})}function L0e(){return new wa({uri:Ur.repairedRtpStreamId})}function D0e(){return new wa({uri:Ur.transportWideCC})}function U0e(){return new wa({uri:Ur.absSendTime})}function q0e(){return new wa({uri:Ur.dependencyDescriptor})}function H0e(){return new wa({uri:Ur.audioLevelIndication})}function F0e(){return new wa({uri:Ur.videoOrientation})}function vr(t,...e){let r=e.filter(n=>n!==void 0);return`${t}_${r.join("_")}`}function Zu(){return performance.now()}function A5(t,e){let r=i=>i.toUpperCase(),n=i=>i.match(/(.{2})/g).join(":"),s=K0e(e).update(t).digest("hex");return n(r(s))}function E5(t){return rme[t.trim().toLowerCase()]}function NA(t){return t.replace(/[^0-9a-f]/gi,"").toLowerCase()}function jG(t){let e=t[0];return e>19&&e<64}function nme(t){return t==="recv"?"send":"recv"}function zG(t){return t==="sendonly"?"recvonly":t==="recvonly"?"sendonly":t}function UG(t){let e=a=>{if(!a)return;let[c,u]=a.split(":");return[c,Number.parseInt(u)]},r=e(t.find(({urls:a})=>a.includes("stun:"))?.urls.slice(5)),n=e(t.find(({urls:a})=>a.includes("turn:"))?.urls.slice(5)),{credential:s,username:i}=t.find(({urls:a})=>a.includes("turn:"))||{},o={stunServer:r,turnServer:n,turnUsername:i,turnPassword:s};return tme("iceOptions",o),o}function T0(t){let e=new P5(t.component,t.foundation,t.host,t.port,t.priority,t.transport,t.type,t.generation,t.ufrag);return e.relatedAddress=t.relatedAddress,e.relatedPort=t.relatedPort,e.tcpType=t.tcptype,e}function KG(t){return new Vu(t.foundation,t.component,t.protocol,t.priority,t.ip,t.port,t.type,t.relatedAddress,t.relatedPort,t.tcpType,t.generation,t.ufrag)}function u1(t){let e=t%4;return e?4-e:0}function pW(t){let e=Buffer.from(""),r=Buffer.from("");return t.forEach(([n,s])=>{let i=s.length+4,o=Buffer.alloc(4);o.writeUInt16BE(n,0),o.writeUInt16BE(i,2),e=Buffer.concat([e,r,o,s]),r=Buffer.concat([...Array(u1(i))].map(()=>Buffer.from("\0")))}),e}function mW(t){let e=[],r=0;for(;r<=t.length-4;){let n=t.readUInt16BE(r),s=t.readUInt16BE(r+2);e.push([n,t.slice(r+4,r+s)]),r+=s+u1(s)}return e}function Pme(t){if(t.length<12)throw new Error("SCTP packet length is less than 12 bytes");let e=t.readUInt16BE(0),r=t.readUInt16BE(2),n=t.readUInt32BE(4),s=t.readUInt32LE(8),i=V8(Buffer.concat([t.slice(0,8),Buffer.from("\0\0\0\0"),t.slice(12)]));if(s!==i)throw new Error("SCTP packet has invalid checksum");let o=[],a=12;for(;a+4<=t.length;){let c=t.readUInt8(a),u=t.readUInt8(a+1),l=t.readUInt16BE(a+2),d=t.slice(a+4,a+l),f=Ime[c.toString()];if(f)o.push(new f(u,d));else throw new Error("unknown");a+=l+u1(l)}return[e,r,n,o]}function Rme(t,e,r,n){let s=Buffer.alloc(8);s.writeUInt16BE(t,0),s.writeUInt16BE(e,2),s.writeUInt32BE(r,4);let i=n.bytes,o=V8(Buffer.concat([s,Buffer.from("\0\0\0\0"),i])),a=Buffer.alloc(4);return a.writeUInt32LE(o,0),Buffer.concat([s,a,i])}function Ome(t){return t.map((e,r)=>[r,e])}function Nme(t){return t.reduce((e,r)=>(e[r]=new Be,e),{})}function Qd(t){return(t-1)%MA}function y0(t){return(t+1)%MA}function MP(t){let e=t.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error("exception");return e[2]}function L8(t){return`IN IP${pme(t)?4:6} ${t}`}function B5(t){let e=`${t.foundation} ${t.component} ${t.protocol} ${t.priority} ${t.ip} ${t.port} typ ${t.type}`;return t.relatedAddress!=null&&(e+=` raddr ${t.relatedAddress}`),t.relatedPort!=null&&(e+=` rport ${t.relatedPort}`),t.tcpType!=null&&(e+=` tcptype ${t.tcpType}`),t.generation!=null&&(e+=` generation ${t.generation}`),t.ufrag!=null&&(e+=` ufrag ${t.ufrag}`),e}function Kme(t){let e=[],r=[],n=t.split(`\r
|
|
185
|
+
`);return n.length===1&&(n=t.split(`
|
|
186
|
+
`)),n.forEach(s=>{s.startsWith("m=")?r.push([s]):r.length>0?r[r.length-1].push(s):e.push(s)}),[e,r]}function jP(t){if(t.includes(":")){let e=Sc(t.slice(2),":");return[e[0],e[1]]}else return[t.slice(2),void 0]}function SA(t,e,r=n=>n.toString()){let n=e.split(" ");n.length>0&&t.push(new S0(n[0],n.slice(1).map(r)))}function $5(t){let e=Vu.fromSdp(t);return T0(e)}function D8(t,e){let n=new Y2(hme(64)).toString().slice(0,8),s=0;e.origin=`- ${n} ${s} IN IP4 0.0.0.0`,e.msidSemantic.push(new S0("WMS",["*"])),e.type=t}function Yb(t){let e={};return t.split(";").forEach(r=>{if(r.includes("=")){let[n,s]=Sc(r,"=");Q0e.includes(n)?e[n]=Number(s):e[n]=s}else if(r.includes(":")){let[n,s]=r.split(":");e[n]=Number.isNaN(Number(s))?s:Number(s)}else e[r]=void 0}),e}function Zme(t,e="="){let r=Object.entries(t).map(([n,s])=>s?`${n}${e}${s}`:n);if(r.length>0)return r.join(";")}function EW(){return{codecs:{audio:[x5(),b5()],video:[y5()]},headerExtensions:{audio:[],video:[]},iceTransportPolicy:"all",iceServers:[{urls:"stun:stun.l.google.com:19302"}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:"max-compat",debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:b0}}var H8,cK,qA,I0,v0,gK,yK,Vn,wo,AK,rf,Ec,PK,sf,Hu,of,P0,Fu,af,So,Ao,KA,vo,zK,qK,r5,uA,df,ef,_a,ba,ff,Gb,p8,hA,fG,bG,Jb,gA,yA,Cc,U8,Bb,LA,Ihe,Phe,qu,Ohe,Nhe,LP,Bhe,DP,$he,_0,jhe,UA,Lhe,wt,Be,uK,MF,EA,fK,va,jb,CA,pK,Tc,Z8,G8,UP,mK,W8,Zhe,Ghe,kc,Qhe,qP,zb,Lb,X8,SK,Mi,kA,epe,EK,tpe,Db,rpe,npe,HP,spe,ipe,ope,ape,J8,nf,CK,lpe,kK,TK,e1,VP,dpe,EP,t1,fpe,hpe,ppe,HA,r1,n1,s1,wpe,Spe,_n,ub,lb,zF,LF,DF,UF,qF,FA,VA,A0,TA,OK,NK,BK,ZP,$K,MK,jK,LK,R0,hf,Epe,DK,UK,Cpe,WP,FK,ZK,kpe,GK,Lu,Tpe,Ipe,Ppe,XK,YK,eZ,Rpe,Npe,$pe,IA,Rc,HF,qb,Hb,Mpe,E0,C0,ZA,sZ,Fb,jpe,Vb,w0,oZ,Rb,cZ,uZ,lZ,zpe,cf,Kb,Y8,Q8,uf,e5,pZ,Lpe,mZ,Ur,Upe,t5,a8,PZ,qpe,RZ,Du,VF,KF,ZF,GF,WF,Ic,Pc,$Z,lf,QF,Fpe,Vpe,eV,Kpe,kP,sV,LZ,db,oV,Zpe,Gpe,DZ,UZ,Wpe,qZ,Xpe,vs,Jpe,O0,HZ,Qpe,aV,e0e,u8,l8,cV,uV,TP,t0e,r0e,lV,dV,s5,IP,d8,ya,s0e,fV,i0e,k0,o0e,i1,d0,FZ,GA,VZ,KZ,Ac,i5,o5,a5,ZZ,GZ,a0e,c5,u5,hV,f8,l5,hb,pb,l0e,d0e,pV,mV,PP,RP,OP,NP,f0e,h0e,QZ,eG,gV,p0e,$i,d5,rG,nG,g0e,BP,f5,yV,PA,Vs,b0e,_0e,v0e,iG,aG,Vu,A0e,C0e,y8,x8,Tb,hG,b8,pG,mG,k0e,I0e,xr,wG,P0e,vV,h5,O0e,p5,m5,N0e,o1,N0,a1,AG,Ku,wa,B0e,EG,CG,kG,g5,TG,y5,IG,PG,x5,b5,_5,$0e,M0e,AV,EV,W0e,sA,CV,kV,X0e,J0e,Y0e,TV,S8,IV,Q0e,RG,PV,pA,eme,OG,NG,BG,v5,w5,S5,mA,Wb,MG,tme,rme,C5,k5,sme,LG,Xb,DG,T5,ime,ome,qG,ame,RV,cme,lme,dme,fme,xo,A8,yme,I5,BA,$A,xme,bme,_me,vme,OV,NV,FG,Sme,Ame,VG,ZG,P5,R5,Sa,O5,xA,E8,kme,bA,_A,C8,k8,c1,T8,vA,P8,sW,R8,O8,cW,lW,fW,Tme,Ime,N8,gW,iA,wA,$V,ur,Bme,$me,MV,bo,Ib,yW,j8,jV,Mme,zV,LV,DV,jme,zme,MA,Lme,Dme,UV,qV,HV,FV,Ume,qme,Hme,Fme,f0,b0,xW,N5,Vme,Nb,jA,S0,vW,zA,oA,M5,mb,wW,Gme,h0,Wme,Xme,zP,GV,WV,SW,Yme,Qme,AW,gb,ege,tge,_o,rge,q8,nge,sge,CW,ige,oge,TW=mr(()=>{H8=vt(Vc(),1),cK=vt(z$(),1),qA=vt(Ok(),1),I0=vt(AU(),1),v0=vt(Kr(),1),gK=vt(Kr(),1),yK=vt(j_(),1);aF();Vn=vt(Kr(),1),wo=vt(Kr(),1),AK=vt(Kr(),1),rf=vt(Kr(),1),Ec=vt(Kr(),1),PK=vt(j_(),1),sf=vt(Kr(),1),Hu=vt(Kr(),1),of=vt(Kr(),1),P0=vt(Kr(),1),Fu=vt(Kr(),1),af=vt(Kr(),1),So=vt(Kr(),1),Ao=vt(Kr(),1),KA=vt(Kr(),1),vo=vt(Kr(),1),zK=vt(Kr(),1),qK=vt(uF(),1),r5=vt(Vc(),1),uA=vt(dF(),1),df=vt(Kr(),1),ef=vt(Kr(),1),_a=vt(Kr(),1),ba=vt(Kr(),1),ff=vt(Kr(),1);Q2();Gb=vt(fP(),1),p8=vt(Vc(),1);Q2();hA=vt(tA(),1),fG=vt($F(),1),bG=vt(fP(),1);Q2();Jb=vt(Ok(),1),gA=vt(Vc(),1),yA=vt(Vc(),1),Cc=vt(Vc(),1),U8=vt(Vc(),1);Bb=class{constructor(t){this.bitLength=t}value=0;set(t,e,r){return r&=(1<<t)-1,this.value|=r<<this.bitLength-t-e,this}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}},LA=class{constructor(t){if(this.bitLength=t,t>32)throw new Error}_value=0n;offset=0n;set(t,e=1){let r=BigInt(t),n=BigInt(e);return r&=(1n<<n)-1n,this._value|=r<<BigInt(this.bitLength)-n-this.offset,this.offset+=n,this}get value(){return Number(this._value)}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}};Ihe=class{buffer;constructor(t){this.buffer=Buffer.alloc(t)}writeInt16BE(t,e){return this.buffer.writeInt16BE(t,e),this}writeUInt8(t,e){return this.buffer.writeUInt8(t,e),this}},Phe=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x");qu=class{constructor(t){this.uint8Array=t}position=0;bitsPending=0;writeBits(t,e){if(t==0)return this;e&=4294967295>>>32-t;let r;return this.bitsPending>0?this.bitsPending>t?(this.uint8Array[this.position-1]|=e<<this.bitsPending-t,r=t,this.bitsPending-=t):this.bitsPending==t?(this.uint8Array[this.position-1]|=e,r=t,this.bitsPending=0):(this.uint8Array[this.position-1]|=e>>t-this.bitsPending,r=this.bitsPending,this.bitsPending=0):(r=Math.min(8,t),this.bitsPending=8-r,this.uint8Array[this.position++]=e>>t-r<<this.bitsPending),t-=r,t>0&&this.writeBits(t,e),this}readBits(t){return this._readBits(t)}_readBits(t,e){if(typeof e>"u"&&(e=0),t==0)return e;let r,n;if(this.bitsPending>0){let s=this.uint8Array[this.position-1]&255>>8-this.bitsPending;n=Math.min(this.bitsPending,t),this.bitsPending-=n,r=s>>this.bitsPending}else n=Math.min(8,t),this.bitsPending=8-n,r=this.uint8Array[this.position++]>>this.bitsPending;return t-=n,e=e<<n|r,t>0?this._readBits(t,e):e}seekTo(t){this.position=t/8|0,this.bitsPending=t%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},Ohe=3988292384,Nhe=2197175160;LP=QV(Ohe),Bhe=eK(LP),DP=QV(Nhe),$he=eK(DP);_0=t=>Number.parseInt(t,10),jhe=class{queue=[];running=!1;push=t=>new Promise((e,r)=>{this.queue.push({promise:t,done:e,failed:r}),this.running||this.run()});async run(){let t=this.queue.shift();if(t){this.running=!0;try{let e=await t.promise();t.done(e)}catch(e){t.failed(e)}this.run()}else this.running=!1}cancel(){this.queue=[]}},UA=(t,e)=>e?e[t]:void 0;Lhe=class extends Error{message;payload;path;constructor(t){super(t.message)}toJSON(){return{message:this.message,payload:JSON.parse(JSON.stringify(this.payload)),path:this.path}}},wt=cK.default.debug,Be=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=t=>{};execute=(...t)=>{if(!this.ended){for(let e of this.event.stack)e.execute(...t);(async()=>{for(let e of this.event.promiseStack)await e.execute(...t)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let t of this.event.stack)t.complete&&t.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&(this.onended(),this.onended=void 0)}};error=t=>{if(!this.ended){for(let e of this.event.stack)e.error&&e.error(t);this.allUnsubscribe()}};allUnsubscribe=()=>{if(this.ended)throw new Error("event completed");this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(t,e,r)=>{let n=this.event.eventId;this.event.stack.push({execute:t,id:n,complete:e,error:r}),this.event.eventId++;let s=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==n&&o)};return{unSubscribe:s,disposer:o=>{o.push(s)}}};pipe(t){this.subscribe((...e)=>{t.execute(...e)})}queuingSubscribe=(t,e,r)=>{if(this.ended)throw new Error("event completed");let n=this.event.eventId;this.event.promiseStack.push({execute:t,id:n,complete:e,error:r}),this.event.eventId++;let s=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==n&&o)};return{unSubscribe:s,disposer:o=>{o.push(s)}}};once=(t,e,r)=>{let n=this.subscribe((...s)=>{n.unSubscribe(),t(...s)},e,r)};watch=(t,e)=>new Promise((r,n)=>{let s=e&&setTimeout(()=>{n("Event watch timeout")},e),{unSubscribe:i}=this.subscribe((...o)=>{t(...o)&&(s&&clearTimeout(s),i(),r(o))})});asPromise=t=>new Promise((e,r)=>{let n=t&&setTimeout(()=>{r("Event asPromise timeout")},t);this.once((...s)=>{n&&clearTimeout(n),e(s)},()=>{n&&clearTimeout(n),e([])},s=>{n&&clearTimeout(n),r(s)})});get returnTrigger(){let{execute:t,error:e,complete:r}=this;return{execute:t,error:e,complete:r}}get returnListener(){let{subscribe:t,once:e,asPromise:r}=this;return{subscribe:t,once:e,asPromise:r}}get length(){return this.event.stack.length}},uK=class{_disposer=[];push(t){this._disposer.push(t)}dispose(){this._disposer.forEach(t=>t()),this._disposer=[]}},MF=wt("werift-ice:packages/ice/src/transport.ts"),EA=class dK{constructor(e,r={}){this.socketType=e,this.options=r,this.socket=Dhe(e),this.socket.on("message",(n,s)=>{Mb(s.family)===6&&([s.address]=s.address.split("%")),this.rinfo=s;try{this.onData(n,[s.address,s.port])}catch(i){MF("onData error",i)}})}type="udp";socket;rinfo;onData=()=>{};closed=!1;static async init(e,r={}){let n=new dK(e,r);return await n.init(),n}async init(){let e=UA(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let r=await aK(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:r,address:e})}else this.socket.bind({address:e});await new Promise(r=>this.socket.once("listening",r))}send=async(e,r)=>{if(r&&!lK.isIP(r[0]))return new Promise((n,s)=>{this.socket.send(e,r[1],r[0],i=>{i?(MF("send error",r,e),s(i)):n()})});r=r??[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,r[1],r[0])};get address(){return this.socket.address()}get host(){return this.socket.address().address}get port(){return this.socket.address().port}close=()=>new Promise(e=>{this.closed=!0,this.socket.once("close",e);try{this.socket.close()}catch{e()}})},fK=class hK{constructor(e){this.addr=e,this.connect()}type="tcp";connecting;client;onData=()=>{};closed=!1;connect(){this.closed||(this.client&&this.client.destroy(),this.connecting=new Promise((e,r)=>{try{this.client=Uhe({port:this.addr[1],host:this.addr[0]},e)}catch(n){r(n)}}),this.client.on("data",e=>{let r=[this.client.remoteAddress,this.client.remotePort];this.onData(e,r)}),this.client.on("end",()=>{this.connect()}),this.client.on("error",e=>{console.log("error",e)}))}async init(){await this.connecting}static async init(e){let r=new hK(e);return await r.init(),r}get address(){return{}}send=async(e,r)=>{await this.connecting,this.client.write(e,n=>{n&&console.log("err",n)})};close=async()=>{this.closed=!0,this.client.destroy()}},va={rsa_1:1,ecdsa_3:3},jb={sha256_4:4},CA={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},pK=Object.values(CA),Tc={x25519_29:29,secp256r1_23:23},Z8=Object.values(Tc),G8={named_curve_3:3},UP={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},mK=[1,64],W8=[{hash:jb.sha256_4,signature:va.rsa_1},{hash:jb.sha256_4,signature:va.ecdsa_3}],Zhe=()=>{let t=W2.utils.randomPrivateKey(),e=W2.getPublicKey(t,!1),r=Buffer.from(t),n=Buffer.from(e);return{privateKey:r,publicKey:n}},Ghe=({publicKey:t,privateKey:e})=>{let r=W2.getSharedSecret(e,t);return Buffer.from(r).subarray(1)};kc={CLIENT:1,SERVER:2},Qhe=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...t){throw new Error("not implemented")}encrypt(...t){throw new Error("not implemented")}decrypt(...t){throw new Error("not implemented")}toString(){return this.name}},qP=Fhe;I0.cryptoProvider.set(qP);zb=class{constructor(t,e,r,n){this.sessionType=t,this.certPem=e,this.keyPem=r,e&&r&&n&&this.parseX509(e,r,n)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(t,e)=>{let r=(()=>{switch(t.signature){case va.rsa_1:return"RSASSA-PKCS1-v1_5";case va.ecdsa_3:return"ECDSA"}})(),n=(()=>{if(t.hash===jb.sha256_4)return"SHA-256"})(),s=(()=>{switch(e){case Tc.secp256r1_23:return"P-256";case Tc.x25519_29:return r==="ECDSA"?"P-256":"X25519";default:{if(r==="ECDSA")return"P-256";if(r==="RSASSA-PKCS1-v1_5")return"X25519"}}})(),i=(()=>{switch(r){case"ECDSA":return{name:r,hash:n,namedCurve:s};case"RSASSA-PKCS1-v1_5":return{name:r,hash:n,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),o=await qP.subtle.generateKey(i,!0,["sign","verify"]),c=(await I0.X509CertificateGenerator.createSelfSigned({serialNumber:Hhe(8).toString("hex"),name:"C=AU, ST=Some-State, O=Internet Widgits Pty Ltd",notBefore:new Date,notAfter:new Date(Date.now()+10*365*24*60*60*1e3),signingAlgorithm:i,keys:o})).toString("pem"),u=I0.PemConverter.encode(await qP.subtle.exportKey("pkcs8",o.privateKey),"private key");return{certPem:c,keyPem:u,signatureHash:t}};encryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor,n=this.cipher.encrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber});return t.fragment=n,t.recordLayerHeader.contentLen=n.length,t}decryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber})}verifyData(t){return this.sessionType===kc.CLIENT?Xhe(this.masterSecret,t):Jhe(this.masterSecret,t)}signatureData(t,e){let r=qhe(e).update(t),n=this.localPrivateKey.toPEM().toString();return r.sign(n)}generateKeySignature(t){let e=this.sessionType===kc.CLIENT?this.localRandom:this.remoteRandom,r=this.sessionType===kc.SERVER?this.localRandom:this.remoteRandom,n=this.valueKeySignature(e.serialize(),r.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(n,t)}parseX509(t,e,r){let n=qA.Certificate.fromPEM(Buffer.from(t)),s=qA.PrivateKey.fromPEM(Buffer.from(e));this.localCert=n.raw,this.localPrivateKey=s,this.signatureHashAlgorithm=r}valueKeySignature(t,e,r,n){let s=Buffer.from((0,v0.encode)({type:G8.named_curve_3,curve:n,len:r.length},{type:v0.types.uint8,curve:v0.types.uint16be,len:v0.types.uint8}).slice());return Buffer.concat([t,e,s,r])}},Lb=class{srtpProfile;static findMatchingSRTPProfile(t,e){for(let r of e)if(t.includes(r))return r}},X8=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x"),SK=t=>Object.entries({...t}).reduce((e,[r,n])=>((typeof n=="number"||typeof n=="string")&&(e[r]=n),Buffer.isBuffer(n)&&(e[r]=X8(n)),e),{}),Mi=class Mu{constructor(e,r,n,s,i,o){this.msg_type=e,this.length=r,this.message_seq=n,this.fragment_offset=s,this.fragment_length=i,this.fragment=o}static spec={msg_type:wo.types.uint8,length:wo.types.uint24be,message_seq:wo.types.uint16be,fragment_offset:wo.types.uint24be,fragment_length:wo.types.uint24be,fragment:wo.types.buffer(e=>e.current.fragment_length)};get summary(){return SK(this)}static createEmpty(){return new Mu(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new Mu(...Object.values((0,wo.decode)(e,Mu.spec)))}serialize(){let e=(0,wo.encode)(this,Mu.spec).slice();return Buffer.from(e)}chunk(e){let r=0,n=this.fragment.length;if(n===0)return[new Mu(this.msg_type,n,this.message_seq,r,0,this.fragment)];let s=[];for(e||(e=1240);r<n;){let i=Math.min(e,n-r),o=Buffer.from(this.fragment.slice(r,r+i));if(o.length<=0)throw new Error("Zero or less bytes processed while fragmenting handshake message.");s.push(new Mu(this.msg_type,n,this.message_seq,r,o.length,o)),r+=o.length}return s}static assemble(e){if(!e?.length)throw new Error("cannot reassemble handshake from empty array");e=e.sort((n,s)=>n.fragment_offset-s.fragment_offset);let r=Buffer.alloc(e[0].length);for(let n of e)n.fragment.copy(r,n.fragment_offset);return new Mu(e[0].msg_type,e[0].length,e[0].message_seq,0,r.length,r)}static findAllFragments(e,r){let n=e.find(s=>s.msg_type===r);return n?e?.length?e.filter(s=>s.msg_type===n.msg_type&&s.message_seq===n.message_seq&&s.length===n.length):[]:[]}},{uint16be:kA,uint24be:epe,buffer:EK,array:tpe,uint8:Db,string:rpe}=AK.types,npe={type:kA,data:EK(kA)},HP=tpe(npe,kA,"bytes"),spe=EK(epe),ipe=Db,ope=rpe(kA),ape={hash:Db,signature:Db},J8={major:Db,minor:Db},nf=class yb{constructor(e=Math.floor(Date.now()/1e3),r=cpe(28)){this.gmt_unix_time=e,this.random_bytes=r}static spec={gmt_unix_time:rf.types.uint32be,random_bytes:rf.types.buffer(28)};static deSerialize(e){return new yb(...Object.values((0,rf.decode)(e,yb.spec)))}static from(e){return new yb(...Object.values(e))}serialize(){let e=(0,rf.encode)(this,yb.spec).slice();return Buffer.from(e)}},CK=class xb{constructor(e,r,n,s,i,o,a){this.clientVersion=e,this.random=r,this.sessionId=n,this.cookie=s,this.cipherSuites=i,this.compressionMethods=o,this.extensions=a}msgType=1;messageSeq=0;static spec={clientVersion:{major:Vn.types.uint8,minor:Vn.types.uint8},random:nf.spec,sessionId:Vn.types.buffer(Vn.types.uint8),cookie:Vn.types.buffer(Vn.types.uint8),cipherSuites:Vn.types.array(Vn.types.uint16be,Vn.types.uint16be,"bytes"),compressionMethods:Vn.types.array(Vn.types.uint8,Vn.types.uint8,"bytes"),extensions:HP};static createEmpty(){return new xb(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new xb(...Object.values((0,Vn.decode)(e,xb.spec)))}serialize(){let e=(0,Vn.encode)(this,xb.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},lpe=class bb{constructor(e,r,n,s,i){this.epoch=e,this.sequenceNumber=r,this.contentType=n,this.protocolVersion=s,this.contentLen=i}static spec={epoch:Ec.types.uint16be,sequenceNumber:Ec.types.uint48be,contentType:Ec.types.uint8,protocolVersion:J8,contentLen:Ec.types.uint16be};static createEmpty(){return new bb(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new bb(...Object.values((0,Ec.decode)(e,bb.spec)))}serialize(){let e=(0,Ec.encode)(this,bb.spec).slice();return Buffer.from(e)}},kK=class FP{constructor(e,r){this.recordLayerHeader=e,this.fragment=r}get summary(){return{header:this.recordLayerHeader,fragment:X8(this.fragment)}}static createEmpty(){return new FP(void 0,void 0)}static deSerialize(e){if(e.length<13)throw new Error("Invalid DTLS record: buffer is too short");let r=e.readUInt8(0),n=e.readUInt8(1),s=e.readUInt8(2),i=e.readUInt16BE(3),o=e.slice(5,11).readUIntBE(0,6),a=e.readUInt16BE(11);if(e.length<13+a)throw new Error("Invalid DTLS record: fragment length exceeds buffer");let c=e.slice(13,13+a);return new FP({contentType:r,protocolVersion:{major:n,minor:s},epoch:i,sequenceNumber:o,contentLen:a},c)}serialize(){let e=this.fragment.length,r=13+e,n=Buffer.alloc(r);return n.writeUInt8(this.recordLayerHeader.contentType,0),n.writeUInt8(this.recordLayerHeader.protocolVersion.major,1),n.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2),n.writeUInt16BE(this.recordLayerHeader.epoch,3),n.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6),n.writeUInt16BE(e,11),this.fragment.copy(n,13),n}computeMACHeader(){return new lpe(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},TK=t=>e=>(t.lastFlight=e,e.flatMap(r=>(r.messageSeq=t.sequenceNumber++,r.toFragment().chunk()))),e1=t=>(e,r)=>e.map(n=>new kK({contentType:n.type,protocolVersion:t.version,epoch:t.epoch,sequenceNumber:r,contentLen:n.fragment.length},n.fragment)),VP=(t=>(t[t.CloseNotify=0]="CloseNotify",t[t.UnexpectedMessage=10]="UnexpectedMessage",t[t.BadRecordMac=20]="BadRecordMac",t[t.DecryptionFailed=21]="DecryptionFailed",t[t.RecordOverflow=22]="RecordOverflow",t[t.DecompressionFailure=30]="DecompressionFailure",t[t.HandshakeFailure=40]="HandshakeFailure",t[t.NoCertificate=41]="NoCertificate",t[t.BadCertificate=42]="BadCertificate",t[t.UnsupportedCertificate=43]="UnsupportedCertificate",t[t.CertificateRevoked=44]="CertificateRevoked",t[t.CertificateExpired=45]="CertificateExpired",t[t.CertificateUnknown=46]="CertificateUnknown",t[t.IllegalParameter=47]="IllegalParameter",t[t.UnknownCa=48]="UnknownCa",t[t.AccessDenied=49]="AccessDenied",t[t.DecodeError=50]="DecodeError",t[t.DecryptError=51]="DecryptError",t[t.ExportRestriction=60]="ExportRestriction",t[t.ProtocolVersion=70]="ProtocolVersion",t[t.InsufficientSecurity=71]="InsufficientSecurity",t[t.InternalError=80]="InternalError",t[t.UserCanceled=90]="UserCanceled",t[t.NoRenegotiation=100]="NoRenegotiation",t[t.UnsupportedExtension=110]="UnsupportedExtension",t))(VP||{}),dpe=wt("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),EP=wt("werift-dtls : packages/dtls/src/flight/flight.ts : err"),t1=class KP{constructor(e,r,n,s){this.transport=e,this.dtls=r,this.flight=n,this.nextFlight=s}state="PREPARING";static RetransmitCount=10;createPacket(e){let r=TK(this.dtls)(e);return this.dtls.bufferHandshakeCache(r,!0,this.flight),e1(this.dtls)(r.map(s=>({type:22,fragment:s.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let r=0;for(;r<=KP.RetransmitCount;r++){if(this.setState("SENDING"),this.send(e).catch(n=>{EP("fail to send",EP)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(await upe(1e3*((r+1)/2)),this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else dpe(this.dtls.sessionId,"retransmit",r,this.dtls.flight)}if(r>KP.RetransmitCount)throw EP(this.dtls.sessionId,"retransmit failed",r),new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(r=>this.transport.send(r)));setState(e){this.state=e}},fpe=class extends t1{constructor(t,e,r){super(t,e,1,3),this.cipher=r}async exec(t){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;let e=new CK({major:254,minor:253},new nf,Buffer.from([]),Buffer.from([]),pK,[0],t);this.dtls.version=e.clientVersion,this.cipher.localRandom=nf.from(e.random);let r=this.createPacket([e]),n=Buffer.concat(r.map(s=>s.serialize()));await this.transmit([n])}},hpe=wt("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),ppe=class extends t1{constructor(t,e){super(t,e,3,5)}async exec(t){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3,this.dtls.handshakeCache=[];let[e]=this.dtls.lastFlight;hpe("dtls version",e.clientVersion),e.cookie=t.cookie,this.dtls.cookie=t.cookie;let r=this.createPacket([e]),n=Buffer.concat(r.map(s=>s.serialize()));await this.transmit([n])}},HA={NULL:0,ECDHE:1},r1={NULL:0,RSA:1,ECDSA:2,PSK:3},n1={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},s1=class{id=0;name;signType;keyType;toString(){return this.name}};wpe=wt("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),Spe=class extends Qhe{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return SK(this)}init(t,e,r){let n=Yhe(t,r,e,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=n.clientWriteKey,this.serverWriteKey=n.serverWriteKey,this.clientNonce=n.clientNonce,this.serverNonce=n.serverNonce}encrypt(t,e,r){let n=t===kc.CLIENT,s=n?this.clientNonce:this.serverNonce,i=n?this.clientWriteKey:this.serverWriteKey;if(!s||!i)throw new Error;s.writeUInt16BE(r.epoch,this.nonceImplicitLength),s.writeUIntBE(r.sequenceNumber,this.nonceImplicitLength+2,6);let o=s.slice(this.nonceImplicitLength),a=this.encodeAdditionalBuffer(r,e.length),c=_pe(this.blockAlgorithm,i,s,{authTagLength:this.authTagLength});c.setAAD(a,{plaintextLength:e.length});let u=c.update(e),l=c.final(),d=c.getAuthTag();return Buffer.concat([o,u,l,d])}encodeAdditionalBuffer(t,e){let r=Buffer.alloc(13);return r.writeUInt16BE(t.epoch,0),r.writeUintBE(t.sequenceNumber,2,6),r.writeUInt8(t.type,8),r.writeUInt16BE(t.version,9),r.writeUInt16BE(e,11),r}decrypt(t,e,r){let n=t===kc.CLIENT,s=n?this.serverNonce:this.clientNonce,i=n?this.serverWriteKey:this.clientWriteKey;if(!s||!i)throw new Error;e.subarray(0,this.nonceExplicitLength).copy(s,this.nonceImplicitLength);let a=e.subarray(this.nonceExplicitLength,e.length-this.authTagLength),c=e.subarray(e.length-this.authTagLength),u=this.encodeAdditionalBuffer(r,a.length),l=vpe(this.blockAlgorithm,i,s,{authTagLength:this.authTagLength});l.setAuthTag(c),l.setAAD(u,{plaintextLength:a.length});let d=l.update(a);try{let f=l.final();return f.length>0?Buffer.concat([d,f]):d}catch(f){throw wpe("decrypt failed",f,t,X8(e),r,this.summary),f}}},_n={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395},ub={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},lb={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},zF=mpe(),LF=gpe(),DF=ype(),UF=xpe(),qF=bpe();FA=class{static type=23},VA=class p0{static type=65281;static spec={type:sf.types.uint16be,data:sf.types.uint8};type=p0.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new p0}static deSerialize(e){return new p0((0,sf.decode)(e,p0.spec))}serialize(){let e=(0,sf.encode)(this,p0.spec).slice();return Buffer.from(e)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},A0=class ju{static type=14;static spec={type:Hu.types.uint16be,data:Hu.types.buffer(Hu.types.uint16be)};type=ju.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(e,r){return new ju({profiles:e,mki:r})}static deSerialize(e){let r=new ju((0,Hu.decode)(e,ju.spec)),n=r.data.readUInt16BE(),s=new Array(n/2);for(let i=0;i<s.length;i++)s[i]=r.data.readUInt16BE(i*2+2);return r.profiles=s,r.mki=r.data.slice(n+2),r}serialize(){let e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);let r=Buffer.concat([e,...this.profiles.map(s=>{let i=Buffer.alloc(2);return i.writeUInt16BE(s),i}),this.mki]);this.data=r;let n=(0,Hu.encode)(this,ju.spec).slice();return Buffer.from(n)}static fromData(e){let r=Buffer.alloc(4);return r.writeUInt16BE(ju.type),r.writeUInt16BE(e.length,2),ju.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},TA=class _b{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:of.types.array(spe,of.types.uint24be,"bytes")};static createEmpty(){return new _b(void 0)}static deSerialize(e){return new _b(...Object.values((0,of.decode)(e,_b.spec)))}serialize(){let e=(0,of.encode)(this,_b.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},OK=class vb{constructor(e=1){this.type=e}static spec={type:P0.types.uint8};static createEmpty(){return new vb}static deSerialize(e){return new vb(...Object.values((0,P0.decode)(e,vb.spec)))}serialize(){let e=(0,P0.encode)(this,vb.spec).slice();return Buffer.from(e)}},NK=class wb{constructor(e,r){this.algorithm=e,this.signature=r}msgType=15;messageSeq;static spec={algorithm:Fu.types.uint16be,signature:Fu.types.buffer(Fu.types.uint16be)};static createEmpty(){return new wb(void 0,void 0)}static deSerialize(e){let r=(0,Fu.decode)(e,wb.spec);return new wb(...Object.values(r))}serialize(){let e=(0,Fu.encode)(this,wb.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},BK=class Sb{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:af.types.buffer(af.types.uint8)};static createEmpty(){return new Sb(void 0)}static deSerialize(e){let r=(0,af.decode)(e,Sb.spec);return new Sb(...Object.values(r))}serialize(){let e=(0,af.encode)(this,Sb.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},ZP=class GP{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new GP(void 0)}static deSerialize(e){return new GP(e)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},$K=class Ab{constructor(e,r,n){this.certificateTypes=e,this.signatures=r,this.authorities=n}msgType=13;messageSeq;static spec={certificateTypes:So.types.array(ipe,So.types.uint8,"bytes"),signatures:So.types.array(ape,So.types.uint16be,"bytes"),authorities:So.types.array(ope,So.types.uint16be,"bytes")};static createEmpty(){return new Ab(void 0,void 0,void 0)}static deSerialize(e){return new Ab(...Object.values((0,So.decode)(e,Ab.spec)))}serialize(){let e=(0,So.encode)(this,Ab.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},MK=class zu{constructor(e,r,n,s,i,o){this.serverVersion=e,this.random=r,this.sessionId=n,this.cipherSuite=s,this.compressionMethod=i,this.extensions=o}msgType=2;messageSeq;static spec={serverVersion:J8,random:nf.spec,sessionId:Ao.types.buffer(Ao.types.uint8),cipherSuite:Ao.types.uint16be,compressionMethod:Ao.types.uint8};static createEmpty(){return new zu(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Ao.decode)(e,zu.spec),n=new zu(...Object.values(r));return n.serialize().length<e.length?new zu(...Object.values((0,Ao.decode)(e,{...zu.spec,extensions:HP}))):n}serialize(){let e=this.extensions===void 0?(0,Ao.encode)(this,zu.spec).slice():(0,Ao.encode)(this,{...zu.spec,extensions:HP}).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},jK=class Eb{msgType=14;messageSeq;static spec={};static createEmpty(){return new Eb}static deSerialize(e){return new Eb(...Object.values((0,KA.decode)(e,Eb.spec)))}serialize(){let e=(0,KA.encode)(this,Eb.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}};LK=class Cb{constructor(e,r,n,s,i,o,a,c){this.ellipticCurveType=e,this.namedCurve=r,this.publicKeyLength=n,this.publicKey=s,this.hashAlgorithm=i,this.signatureAlgorithm=o,this.signatureLength=a,this.signature=c}msgType=12;messageSeq;static spec={ellipticCurveType:vo.types.uint8,namedCurve:vo.types.uint16be,publicKeyLength:vo.types.uint8,publicKey:vo.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:vo.types.uint8,signatureAlgorithm:vo.types.uint8,signatureLength:vo.types.uint16be,signature:vo.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new Cb(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,vo.decode)(e,Cb.spec);return new Cb(...Object.values(r))}serialize(){return Ape(this,Cb.spec)}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},R0=1,hf=7,Epe=[R0,hf],DK=t=>{switch(t){case R0:case hf:return 16}},UK=t=>{switch(t){case R0:return 14;case hf:return 12}},Cpe=wt("werift-rtp : packages/rtp/src/codec/av1.ts"),WP=class HK{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{let r=new HK,n=0;if(r.zBit_RtpStartsWithFragment=Ae(e[n],0),r.yBit_RtpEndsWithFragment=Ae(e[n],1),r.w_RtpNumObus=Ae(e[n],2,2),r.nBit_RtpStartsNewCodedVideoSequence=Ae(e[n],4),n++,r.nBit_RtpStartsNewCodedVideoSequence&&r.zBit_RtpStartsWithFragment)throw new Error;[...Array(r.w_RtpNumObus-1).keys()].forEach(i=>{let[o,a]=KK(e.subarray(n)),c=n+a,u=c+o,l=!1;r.zBit_RtpStartsWithFragment&&i===0&&(l=!0),r.obu_or_fragment.push({data:e.subarray(c,u),isFragment:l}),n+=a+o});let s=!1;return(r.yBit_RtpEndsWithFragment||r.w_RtpNumObus===1&&r.zBit_RtpStartsWithFragment)&&(s=!0),r.obu_or_fragment.push({data:e.subarray(n),isFragment:s}),r};static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){let r=[],n=e.flatMap(a=>a.obu_or_fragment).reduce((a,c,u)=>(a[u]=c,a),{}),s=Object.keys(n).length;for(let a of Object.keys(n).map(Number)){let c=n[a];if(!c)continue;let{data:u,isFragment:l}=c;if(l){let d=[];for(let f=a;f<s;f++){let p=n[f];if(p.isFragment)d.push(p.data),delete n[f];else break}d.length<=1&&(Cpe("fragment lost, maybe packet lost"),d=[]),r.push(Buffer.concat(d))}else r.push(u)}let i=r.map(a=>FK.deSerialize(a)),o=i.pop();return Buffer.concat([...i.map(a=>(a.obu_has_size_field=1,a.serialize())),o.serialize()])}},FK=class VK{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;payload;static deSerialize(e){let r=new VK,n=0;return r.obu_forbidden_bit=Ae(e[n],0),r.obu_type=ZK[Ae(e[n],1,4)],r.obu_extension_flag=Ae(e[n],5),r.obu_has_size_field=Ae(e[n],6),r.obu_reserved_1bit=Ae(e[n],7),n++,r.payload=e.subarray(n),r}serialize(){let e=new LA(8).set(this.obu_forbidden_bit).set(kpe[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer,r=Buffer.alloc(0);return this.obu_has_size_field&&(r=qK.LEB128.encode(this.payload.length)),Buffer.concat([e,r,this.payload])}};ZK={0:"Reserved",1:"OBU_SEQUENCE_HEADER",2:"OBU_TEMPORAL_DELIMITER",3:"OBU_FRAME_HEADER",4:"OBU_TILE_GROUP",5:"OBU_METADATA",6:"OBU_FRAME",7:"OBU_REDUNDANT_FRAME_HEADER",8:"OBU_TILE_LIST",15:"OBU_PADDING"},kpe=Object.entries(ZK).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),GK=class WK{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;payload;fragment;static deSerialize(e,r){let n=new WK,s=0,i=e[s];if(n.f=Ae(i,0),n.nri=Ae(i,1,2),n.nalUnitType=Ae(i,3,5),s++,n.s=Ae(e[s],0),n.e=Ae(e[s],1),n.r=Ae(e[s],2),n.nalUnitPayloadType=Ae(e[s],3,5),s++,0<n.nalUnitType&&n.nalUnitType<Lu.stap_a)n.payload=this.packaging(e);else if(n.nalUnitType===Lu.stap_a){let o=Ipe,a=Buffer.alloc(0);for(;o<e.length;){let c=e.readUInt16BE(o);o+=Ppe,a=Buffer.concat([a,this.packaging(e.subarray(o,o+c))]),o+=c}n.payload=a}else if(n.nalUnitType===Lu.fu_a){r||(r=Buffer.alloc(0));let o=e.subarray(s);if(n.fragment=Buffer.concat([r,o]),n.e){let a=new qu(Buffer.alloc(1)).writeBits(1,0).writeBits(2,n.nri).writeBits(5,n.nalUnitPayloadType),c=Buffer.concat([a.uint8Array,n.fragment]);n.fragment=void 0,n.payload=this.packaging(c)}}return n}static packaging(e){return Buffer.concat([Tpe,e])}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nalUnitType===Lu.idrSlice||this.nalUnitPayloadType===Lu.idrSlice}get isPartitionHead(){return this.nalUnitType===Lu.fu_a||this.nalUnitType===Lu.fu_b?this.s!==0:!0}},Lu={idrSlice:5,stap_a:24,stap_b:25,mtap16:26,mtap24:27,fu_a:28,fu_b:29},Tpe=Buffer.from([0,0,0,1]),Ipe=1,Ppe=2,XK=class JK{payload;static deSerialize(e){let r=new JK;return r.payload=e,r}static isDetectedFinalPacketInSequence(e){return!0}get isKeyframe(){return!0}static createCodecPrivate(e=48e3){return Buffer.concat([Buffer.from("OpusHead"),Zr([1,1],[1,2]),JV([2,4,2,1],[312,e,0,0])])}},YK=class QK{xBit;nBit;sBit;pid;iBit;lBit;tBit;kBit;mBit;pictureId;payload;size0=0;hBit;ver;pBit;size1=0;size2=0;static deSerialize(e){let r=new QK,n=0;if(r.xBit=Ae(e[n],0),r.nBit=Ae(e[n],2),r.sBit=Ae(e[n],3),r.pid=Ae(e[n],5,3),n++,r.xBit&&(r.iBit=Ae(e[n],0),r.lBit=Ae(e[n],1),r.tBit=Ae(e[n],2),r.kBit=Ae(e[n],3),n++),r.iBit)if(r.mBit=Ae(e[n],0),r.mBit){let s=$b(Ae(e[n],1,7)),i=$b(e[n+1]);r.pictureId=Number.parseInt(s+i,2),n+=2}else r.pictureId=Ae(e[n],1,7),n++;return r.lBit&&n++,(r.lBit||r.kBit)&&(r.tBit,r.kBit,n++),r.payload=e.subarray(n),r.payloadHeaderExist&&(r.size0=Ae(e[n],0,3),r.hBit=Ae(e[n],3),r.ver=Ae(e[n],4,3),r.pBit=Ae(e[n],7),n++,r.size1=e[n],n++,r.size2=e[n]),r}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.pBit===0}get isPartitionHead(){return this.sBit===1}get payloadHeaderExist(){return this.sBit===1&&this.pid===0}get size(){return this.payloadHeaderExist?this.size0+8*this.size1+2048*this.size2:0}},eZ=class tZ{iBit;pBit;lBit;fBit;bBit;eBit;vBit;zBit;m;pictureId;tid;u;sid;d;tl0PicIdx;pDiff=[];n_s;y;g;width=[];height=[];n_g=0;pgT=[];pgU=[];pgP_Diff=[];payload;static deSerialize(e){let{p:r,offset:n}=this.parseRtpPayload(e);return r.payload=e.subarray(n),r}static parseRtpPayload(e){let r=new tZ,n=0;if(r.iBit=Ae(e[n],0),r.pBit=Ae(e[n],1),r.lBit=Ae(e[n],2),r.fBit=Ae(e[n],3),r.bBit=Ae(e[n],4),r.eBit=Ae(e[n],5),r.vBit=Ae(e[n],6),r.zBit=Ae(e[n],7),n++,r.iBit)if(r.m=Ae(e[n],0),r.m){let s=$b(Ae(e[n],1,7)),i=$b(e[n+1]);r.pictureId=Number.parseInt(s+i,2),n+=2}else r.pictureId=Ae(e[n],1,7),n++;if(r.lBit&&(r.tid=Ae(e[n],0,3),r.u=Ae(e[n],3),r.sid=Ae(e[n],4,3),r.d=Ae(e[n],7),n++,r.fBit===0&&(r.tl0PicIdx=e[n],n++)),r.fBit&&r.pBit)for(;;){r.pDiff=[...r.pDiff,Ae(e[n],0,7)];let s=Ae(e[n],7);if(n++,s===0)break}return r.vBit&&(r.n_s=Ae(e[n],0,3),r.y=Ae(e[n],3),r.g=Ae(e[n],4),n++,r.y&&[...Array(r.n_s+1)].forEach(()=>{r.width.push(e.readUInt16BE(n)),n+=2,r.height.push(e.readUInt16BE(n)),n+=2}),r.g&&(r.n_g=e[n],n++),r.n_g>0&&[...Array(r.n_g).keys()].forEach(s=>{r.pgT.push(Ae(e[n],0,3)),r.pgU.push(Ae(e[n],3));let i=Ae(e[n],4,2);n++,r.pgP_Diff[s]=[],i>0&&[...Array(i)].forEach(()=>{r.pgP_Diff[s].push(e[n]),n++})})),{offset:n,p:r}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return!!(!this.pBit&&this.bBit&&(!this.sid||!this.lBit))}get isPartitionHead(){return this.bBit&&(!this.lBit||!this.d)}},Rpe=class{payload;fragment;static deSerialize(t,e){return{}}static isDetectedFinalPacketInSequence(t){return!0}get isKeyframe(){return!0}};Npe=["MPEG4/ISO/AVC","VP8","VP9","OPUS","AV1"];$pe={setTimeout:(...t)=>{let e=setTimeout(...t);return()=>clearTimeout(e)},setInterval:(...t)=>{let e=setInterval(()=>{t[0]()},...t.slice(1));return()=>clearInterval(e)}};IA=4,Rc=class JP{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(e,r,n,s){let o=new JP({type:e,count:r,version:2,length:s}).serialize();return Buffer.concat([o,n])}serialize(){let e=new Bb(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),Zr([1,1,2],[e.value,this.type,this.length])}static deSerialize(e){let[r,n,s]=ws(e,[1,1,2]),i=Ae(r,0,2),o=Ae(r,2,1)>0,a=Ae(r,3,5);return new JP({version:i,padding:o,count:a,type:n,length:s})}},HF=class YP{static count=4;count=YP.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(e){let[r,n]=ws(e,[4,4]),s=[];for(let i=8;i<e.length;i+=8)s.push({ssrc:e.readUInt32BE(i),sequenceNumber:e[i+4]});return new YP({senderSsrc:r,mediaSsrc:n,fir:s})}serialize(){let e=Zr([4,4],[this.senderSsrc,this.mediaSsrc]),r=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:n,sequenceNumber:s},i)=>{r.writeUInt32BE(n,i*8),r[i*8+4]=s}),Buffer.concat([e,r])}},qb=class QP{static count=1;count=QP.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,n]=ws(e,[4,4]);return new QP({senderSsrc:r,mediaSsrc:n})}serialize(){return Zr([4,4],[this.senderSsrc,this.mediaSsrc])}},Hb=class e8{static count=15;length;count=e8.count;senderSsrc;mediaSsrc;uniqueID="REMB";ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,n,s,i,o]=ws(e,[4,4,4,1,1]),a=Ae(o,0,6),c=(Ae(o,6,2)<<16)+(e[14]<<8)+e[15],u=a>46?18446744073709551615n:BigInt(c)<<BigInt(a),l=[];for(let d=16;d<e.length;d+=4){let f=e.slice(d).readUIntBE(0,4);l.push(f)}return new e8({senderSsrc:r,mediaSsrc:n,uniqueID:Zr([4],[s]).toString(),ssrcNum:i,brExp:a,brMantissa:c,ssrcFeedbacks:l,bitrate:u})}serialize(){let e=Buffer.concat([Zr([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),Zr([1],[this.ssrcNum])]),r=new Bb(24);r.set(6,0,this.brExp).set(18,6,this.brMantissa);let n=Buffer.concat(this.ssrcFeedbacks.map(i=>Zr([4],[i]))),s=Buffer.concat([e,Zr([3],[r.value]),n]);return this.length=s.length/4,s}},Mpe=wt("werift-rtp: /rtcp/psfb/index"),E0=class t8{static type=206;type=t8.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return Rc.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,r){let n;switch(r.count){case HF.count:n=HF.deSerialize(e);break;case qb.count:n=qb.deSerialize(e);break;case Hb.count:n=Hb.deSerialize(e);break;default:Mpe("unknown psfb packet",r.count);break}return new t8({feedback:n})}},C0=class aA{ssrc=0;reports=[];static type=201;type=aA.type;constructor(e={}){Object.assign(this,e)}serialize(){let e=Zr([4],[this.ssrc]);return e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),Rc.serialize(aA.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let[n]=ws(e,[4]),s=4,i=[];for(let o=0;o<r;o++)i.push(ZA.deSerialize(e.slice(s,s+24))),s+=24;return new aA({ssrc:n,reports:i})}},ZA=class nZ{ssrc;fractionLost;packetsLost;highestSequence;jitter;lsr;dlsr;constructor(e={}){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return Zr([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){let[r,n,s,i,o,a,c]=ws(e,[4,1,3,4,4,4,4]);return new nZ({ssrc:r,fractionLost:n,packetsLost:s,highestSequence:i,jitter:o,lsr:a,dlsr:c})}},sZ=205,Fb=class r8{static count=1;count=r8.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e),this.header||(this.header=new Rc({type:sZ,count:this.count,version:2}))}static deSerialize(e,r){let[n,s]=ws(e,[4,4]),i=[];for(let o=8;o<e.length;o+=4){let[a,c]=ws(e.subarray(o),[2,2]);i.push(a);for(let u=0;u<16;u++)c>>u&1&&i.push(a+u+1)}return new r8({header:r,senderSsrc:n,mediaSourceSsrc:s,lost:i})}serialize(){let e=Zr([4,4],[this.senderSsrc,this.mediaSourceSsrc]),r=[];if(this.lost.length>0){let s=this.lost[0],i=0;this.lost.slice(1).forEach(o=>{let a=o-s-1;a>=0&&a<16?i|=1<<a:(r.push(Zr([2,2],[s,i])),s=o,i=0)}),r.push(Zr([2,2],[s,i]))}let n=Buffer.concat([e,Buffer.concat(r)]);return this.header.length=n.length/4,Buffer.concat([this.header.serialize(),n])}},jpe=wt("werift/rtp/rtcp/rtpfb/twcc"),Vb=class n8{static count=15;count=n8.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||(this.header=new Rc({type:205,count:this.count,version:2}))}static deSerialize(e,r){let[n,s,i,o,a,c]=ws(e,[4,4,2,2,3,1]),u=[],l=[],d=16;for(let p=0;p<o;){let m=Ae(e.slice(d,d+1)[0],0,1),y;switch(m){case 0:{let _=w0.deSerialize(e.slice(d,d+2));y=_;let S=Math.min(o-p,_.runLength);if(_.packetStatus===1||_.packetStatus===2)for(let C=0;C<S;C++)l.push(new Rb({type:_.packetStatus}));p+=S}break;case 1:{let _=oZ.deSerialize(e.slice(d,d+2));y=_,_.symbolSize===0&&_.symbolList.forEach(S=>{S===1&&l.push(new Rb({type:1}))}),_.symbolSize===1&&_.symbolList.forEach(S=>{(S===1||S===2)&&l.push(new Rb({type:S}))}),p+=_.symbolList.length}break}if(!y)throw new Error;d+=2,u.push(y)}let f=d;return l.forEach(p=>{p.type===1&&(p.deSerialize(e.slice(f,f+1)),f++),p.type===2&&(p.deSerialize(e.slice(f,f+2)),f+=2)}),new n8({senderSsrc:n,mediaSourceSsrc:s,baseSequenceNumber:i,packetStatusCount:o,referenceTime:a,fbPktCount:c,recvDeltas:l,packetChunks:u,header:r})}serialize(){let e=Zr([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),r=Buffer.concat(this.packetChunks.map(i=>i.serialize())),n=Buffer.concat(this.recvDeltas.map(i=>{try{return i.serialize()}catch(o){jpe(o?.message);return}}).filter(i=>i)),s=Buffer.concat([e,r,n]);if(this.header.padding&&s.length%4!==0){let i=4-s.length%4,o=Buffer.alloc(i);return o[o.length-1]=o.length,this.header.length=Math.floor((s.length+o.length)/4),Buffer.concat([this.header.serialize(),s,o])}return this.header.length=Math.floor(s.length/4),Buffer.concat([this.header.serialize(),s])}get packetResults(){let e=this.baseSequenceNumber-1,r=this.packetChunks.filter(o=>o instanceof w0).flatMap(o=>o.results(e)),n=0,i=BigInt(this.referenceTime)*64n;for(let o of r){let a=this.recvDeltas[n];!o.received||!a||(i+=BigInt(a.delta)/1000n,o.delta=a.delta,o.receivedAtMs=Number(i),n++)}return r}},w0=class iZ{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(e){let r=Ae(e[0],1,2),n=(Ae(e[0],3,5)<<8)+e[1];return new iZ({type:0,packetStatus:r,runLength:n})}serialize(){return new LA(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let r=this.packetStatus===1||this.packetStatus===2,n=[];for(let s=0;s<=this.runLength;++s)n.push(new lZ({sequenceNumber:++e,received:r}));return n}},oZ=class aZ{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let n=Ae(e[0],1,1),s=[];function i(o,a){for(let c=0;c<o;c++)a(c)}switch(n){case 0:i(6,o=>s.push(Ae(e[0],2+o,1))),i(8,o=>s.push(Ae(e[1],o,1)));break;case 1:i(3,o=>s.push(Ae(e[0],2+o*2,2))),i(4,o=>s.push(Ae(e[1],o*2,2)));break;default:n=(Ae(e[0],2,6)<<8)+e[1]}return new aZ({type:1,symbolSize:n,symbolList:s})}serialize(){let e=Buffer.alloc(2),r=new LA(16).set(1).set(this.symbolSize),n=this.symbolSize===0?1:2;return this.symbolList.forEach(s=>{r.set(s,n)}),e.writeUInt16BE(r.value),e}},Rb=class s8{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r,n;if(e.length===1?(r=1,n=250*e[0]):e.length===2&&(r=2,n=250*e.readInt16BE()),r===void 0||n===void 0)throw new Error;return new s8({type:r,delta:n})}deSerialize(e){let r=s8.deSerialize(e);this.delta=r.delta}parsed=!1;parseDelta(){this.delta=Math.floor(this.delta/250),this.delta<0||this.delta>255?(this.delta>32767&&(this.delta=32767),this.delta<-32768&&(this.delta=-32768),this.type||(this.type=2)):this.type||(this.type=1),this.parsed=!0}serialize(){if(this.parsed||this.parseDelta(),this.type===1){let e=Buffer.alloc(1);return e.writeUInt8(this.delta),e}else if(this.type===2){let e=Buffer.alloc(2);return e.writeInt16BE(this.delta),e}throw new Error("errDeltaExceedLimit "+this.delta+" "+this.type)}},cZ=(t=>(t[t.TypeTCCRunLengthChunk=0]="TypeTCCRunLengthChunk",t[t.TypeTCCStatusVectorChunk=1]="TypeTCCStatusVectorChunk",t[t.packetStatusChunkLength=2]="packetStatusChunkLength",t))(cZ||{}),uZ=(t=>(t[t.TypeTCCPacketNotReceived=0]="TypeTCCPacketNotReceived",t[t.TypeTCCPacketReceivedSmallDelta=1]="TypeTCCPacketReceivedSmallDelta",t[t.TypeTCCPacketReceivedLargeDelta=2]="TypeTCCPacketReceivedLargeDelta",t[t.TypeTCCPacketReceivedWithoutDelta=3]="TypeTCCPacketReceivedWithoutDelta",t))(uZ||{}),lZ=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(t){Object.assign(this,t)}},zpe=wt("werift-rtp:packages/rtp/rtcp/rtpfb/index"),cf=class i8{static type=sZ;type=i8.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,r){let n;switch(r.count){case Fb.count:n=Fb.deSerialize(e,r);break;case Vb.count:n=Vb.deSerialize(e,r);break;default:zpe("unknown rtpfb packet",r.count);break}return new i8({feedback:n,header:r})}},Kb=class o8{static type=202;type=o8.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(r=>e+=r.length),e}serialize(){let e=Buffer.concat(this.chunks.map(r=>r.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return Rc.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,r){let n=[];for(let s=0;s<e.length;){let i=Y8.deSerialize(e.slice(s));n.push(i),s+=i.length}return new o8({chunks:n})}},Y8=class dZ{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(r=>e+=r.length),e+=1,e+=FF(e),e}serialize(){let e=Buffer.concat([Zr([4],[this.source]),Buffer.concat(this.items.map(n=>n.serialize()))]);return Buffer.concat([e,Buffer.alloc(FF(e.length))])}static deSerialize(e){let r=e.readUInt32BE(),n=[];for(let s=4;s<e.length&&e[s]!==0;){let o=Q8.deSerialize(e.slice(s));n.push(o),s+=o.length}return new dZ({source:r,items:n})}},Q8=class fZ{type;text;constructor(e){Object.assign(this,e)}get length(){return 2+Buffer.from(this.text).length}serialize(){let e=Buffer.from(this.text);return Buffer.concat([Zr([1,1],[this.type,e.length]),e])}static deSerialize(e){let r=e[0],n=e[1],s=e.slice(2,2+n).toString();return new fZ({type:r,text:s})}};uf=class cA{ssrc=0;senderInfo;reports=[];static type=200;type=cA.type;constructor(e){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.ssrc),e=Buffer.concat([e,this.senderInfo.serialize()]),e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),Rc.serialize(cA.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let n=e.readUInt32BE(),s=e5.deSerialize(e.subarray(4,24)),i=24,o=[];for(let c=0;c<r;c++)o.push(ZA.deSerialize(e.subarray(i,i+24))),i+=24;return new cA({ssrc:n,senderInfo:s,reports:o})}},e5=class hZ{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:pZ(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return Zr([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){let[r,n,s,i]=ws(e,[8,4,4,4]);return new hZ({ntpTimestamp:r,rtpTimestamp:n,packetCount:s,octetCount:i})}},pZ=t=>{let[e,r]=ws(Zr([8],[t]),[4,4]);return+`${e}.${r}`},Lpe=wt("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),mZ=class{static deSerialize(t){let e=0,r=[];for(;e<t.length;){let n=Rc.deSerialize(t.subarray(e,e+IA));e+=IA;let s=t.subarray(e);e+=n.length*4,n.padding&&(s=s.subarray(0,s.length-s.subarray(-1)[0]));try{switch(n.type){case uf.type:r.push(uf.deSerialize(s,n.count));break;case C0.type:r.push(C0.deSerialize(s,n.count));break;case Kb.type:r.push(Kb.deSerialize(s,n));break;case cf.type:r.push(cf.deSerialize(s,n));break;case E0.type:r.push(E0.deSerialize(s,n));break;default:break}}catch(i){Lpe("deSerialize RTCP",i)}}return r}};Ur={sdesMid:"urn:ietf:params:rtp-hdrext:sdes:mid",sdesRTPStreamID:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",repairedRtpStreamId:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",transportWideCC:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",absSendTime:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",dependencyDescriptor:"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension",audioLevelIndication:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",videoOrientation:"urn:3gpp:video-orientation"};Upe=wt("packages/rtp/src/rtp/red/packet.ts"),t5=class TZ{header;blocks=[];static deSerialize(e){let r=e instanceof ArrayBuffer?Buffer.from(e):e,n=new TZ,s=0;return[n.header,s]=a8.deSerialize(r),n.header.fields.forEach(({blockLength:i,timestampOffset:o,blockPT:a})=>{if(i&&o){let c=r.subarray(s,s+i);n.blocks.push({block:c,blockPT:a,timestampOffset:o}),s+=i}else{let c=r.subarray(s);n.blocks.push({block:c,blockPT:a})}}),n}serialize(){this.header=new a8;for(let{timestampOffset:r,blockPT:n,block:s}of this.blocks)r?this.header.fields.push({fBit:1,blockPT:n,blockLength:s.length,timestampOffset:r}):this.header.fields.push({fBit:0,blockPT:n});let e=this.header.serialize();for(let{block:r}of this.blocks)e=Buffer.concat([e,r]);return e}},a8=class IZ{fields=[];static deSerialize(e){let r=0,n=new IZ;for(;;){let s={};n.fields.push(s);let i=new qu(e.subarray(r));if(s.fBit=i.readBits(1),s.blockPT=i.readBits(7),r++,s.fBit===0)break;s.timestampOffset=i.readBits(14),s.blockLength=i.readBits(10),r+=3}return[n,r]}serialize(){let e=Buffer.alloc(0);for(let r of this.fields)try{if(r.timestampOffset&&r.blockLength){let n=new qu(Buffer.alloc(4)).writeBits(1,r.fBit).writeBits(7,r.blockPT).writeBits(14,r.timestampOffset).writeBits(10,r.blockLength);e=Buffer.concat([e,n.uint8Array])}else{let n=new qu(Buffer.alloc(1)).writeBits(1,0).writeBits(7,r.blockPT);e=Buffer.concat([e,n.uint8Array])}}catch(n){Upe(n?.message)}return e}},PZ=class{constructor(t=1){this.distance=t}cache=[];cacheSize=10;push(t){this.cache.push(t),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let t=new t5,e=this.cache.slice(-(this.distance+1)),r=e.pop();return r&&(e.forEach(n=>{let s=tf(r.timestamp,-n.timestamp);s>qpe||t.blocks.push({block:n.block,blockPT:n.blockPT,timestampOffset:s})}),t.blocks.push({block:r.block,blockPT:r.blockPT})),t}},qpe=16383,RZ=class{size=150;sequenceNumbers=[];push(t,e){let r=[];return t.blocks.forEach(({blockPT:s,timestampOffset:i,block:o},a)=>{let c=Kn(e.header.sequenceNumber,-(t.blocks.length-(a+1)));i?r.push(new Pc(new Ic({timestamp:tf(e.header.timestamp,-i),payloadType:s,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o)):r.push(new Pc(new Ic({timestamp:e.header.timestamp,payloadType:s,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o))}),r.filter(s=>this.sequenceNumbers.includes(s.header.sequenceNumber)?!1:(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(s.header.sequenceNumber),!0))}},Du={OneByte:48862,TwoByte:4096},VF=2,KF=4,ZF=8,GF=12,WF=4,Ic=class OZ{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=Du.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r=new OZ,n=0,s=e[n++];r.version=Ae(s,0,2),r.padding=Ae(s,2)>0,r.extension=Ae(s,3)>0,r.csrcLength=Ae(s,4,4),r.csrc=[...Array(r.csrcLength)].map(()=>{let o=e.readUInt32BE(n);return n+=4,o}),n+=GF-1;let i=e[1];r.marker=Ae(i,0)>0,r.payloadType=Ae(i,1,7),r.sequenceNumber=e.readUInt16BE(VF),r.timestamp=e.readUInt32BE(KF),r.ssrc=e.readUInt32BE(ZF);for(let o=0;o<r.csrc.length;o++){let a=GF+o*WF;r.csrc[o]=e.subarray(a).readUInt32BE()}if(r.extension){r.extensionProfile=e.subarray(n).readUInt16BE(),n+=2;let o=e.subarray(n).readUInt16BE()*4;switch(r.extensionLength=o,n+=2,r.extensionProfile){case Du.OneByte:{let a=n+o;for(;n<a;){if(e[n]===0){n++;continue}let c=e[n]>>4,u=(e[n]&(e[n]^240))+1;if(n++,c===15)break;let l={id:c,payload:e.subarray(n,n+u)};r.extensions=[...r.extensions,l],n+=u}}break;case Du.TwoByte:{let a=n+o;for(;n<a;){if(e[n]===0){n++;continue}let c=e[n];n++;let u=e[n];n++;let l={id:c,payload:e.subarray(n,n+u)};r.extensions=[...r.extensions,l],n+=u}}break;default:{let a={id:0,payload:e.subarray(n,n+o)};r.extensions=[...r.extensions,a],n+=r.extensions[0].payload.length}break}}return r.payloadOffset=n,r.padding&&(r.paddingSize=e[e.length-1]),r}get serializeSize(){let{csrc:e,extensionProfile:r,extensions:n}=this,s=12+e.length*WF;if(n.length>0||this.extension===!0){let i=4;switch(r){case Du.OneByte:for(let o of n)i+=1+o.payload.length;break;case Du.TwoByte:for(let o of n)i+=2+o.payload.length;break;default:i+=n[0].payload.length}s+=Math.floor((i+3)/4)*4}return s}serialize(e){let r=Buffer.alloc(e),n=0,s=new Bb(8);s.set(2,0,this.version),this.padding&&s.set(1,2,1),this.extensions.length>0&&(this.extension=!0),this.extension&&s.set(1,3,1),s.set(4,4,this.csrc.length),r.writeUInt8(s.value,n++);let i=new Bb(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),r.writeUInt8(i.value,n++),r.writeUInt16BE(this.sequenceNumber,VF),n+=2,r.writeUInt32BE(this.timestamp,KF),n+=4,r.writeUInt32BE(this.ssrc,ZF),n+=4;for(let o of this.csrc)r.writeUInt32BE(o,n),n+=4;if(this.extension){let o=n;r.writeUInt16BE(this.extensionProfile,n),n+=4;let a=n;switch(this.extensionProfile){case Du.OneByte:for(let l of this.extensions)r.writeUInt8(l.id<<4|l.payload.length-1,n++),l.payload.copy(r,n),n+=l.payload.length;break;case Du.TwoByte:for(let l of this.extensions)r.writeUInt8(l.id,n++),r.writeUInt8(l.payload.length,n++),l.payload.copy(r,n),n+=l.payload.length;break;default:{let l=this.extensions[0].payload.length;if(l%4!=0)throw new Error;this.extensions[0].payload.copy(r,n),n+=l}}let c=n-a,u=Math.trunc((c+3)/4)*4;r.writeUInt16BE(Math.trunc(u/4),o+2);for(let l=0;l<u-c;l++)r.writeUInt8(0,n),n++}return this.payloadOffset=n,r}},Pc=class c8{constructor(e,r){this.header=e,this.payload=r}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new c8(new Ic({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:r}=this.header;if(this.payload.copy(e,r),this.header.padding){let n=Buffer.alloc(this.header.paddingSize);n.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),e=Buffer.concat([e,n])}return e}static deSerialize(e){let r=Ic.deSerialize(e);return new c8(r,e.subarray(r.payloadOffset,e.length-r.paddingSize))}clear(){this.payload=null}};$Z=class{constructor(t,e,r,n){this.srtpSessionKey=t,this.srtpSessionSalt=e,this.srtcpSessionKey=r,this.srtcpSessionSalt=n}encryptRtp(t,e,r){return Buffer.from([])}decryptRtp(t,e,r){return[]}encryptRTCP(t,e){return Buffer.from([])}decryptRTCP(t){return[]}},lf=class extends Error{constructor(t){super(t),this.name="SrtpAuthenticationError"}},QF=12,Fpe=8;Vpe=class extends $Z{constructor(t,e,r,n,s,i){super(t,e,r,n),this.srtpSessionAuthTag=s,this.srtcpSessionAuthTag=i}authTagLength=10;encryptRtp(t,e,r){let n=t.serialize(t.serializeSize),s=this.generateCounter(t.sequenceNumber,r,t.ssrc,this.srtpSessionSalt),o=XF("aes-128-ctr",this.srtpSessionKey,s).update(e),a=this.generateSrtpAuthTag(r,n,o);return Buffer.concat([n,o,a])}decryptRtp(t,e,r=n5(t,this.authTagLength)){let n=t.length-this.authTagLength,s=t.subarray(0,n),i=t.subarray(n),o=this.generateSrtpAuthTag(e,s.subarray(0,r.payloadOffset),s.subarray(r.payloadOffset));tV(i,o,"Failed to authenticate SRTP packet");let a=this.generateCounter(r.sequenceNumber,e,r.ssrc,this.srtpSessionSalt),c=JF("aes-128-ctr",this.srtpSessionKey,a),u=s.subarray(r.payloadOffset),l=c.update(u),d=Buffer.concat([s.subarray(0,r.payloadOffset),l]);return[d,zZ(r,d,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=Buffer.from(t),n=r.readUInt32BE(4),s=this.generateCounter(e&65535,e>>16,n,this.srtcpSessionSalt);XF("aes-128-ctr",this.srtcpSessionKey,s).update(r.slice(8)).copy(r,8),r=Buffer.concat([r,Buffer.alloc(4)]),r.writeUInt32BE(e,r.length-4),r[r.length-4]|=128;let a=this.generateSrtcpAuthTag(r);return r=Buffer.concat([r,a]),r}decryptRTCP(t){let e=MZ(t,this.authTagLength,eV),r=t.length-(this.authTagLength+eV),n=t.subarray(0,t.length-this.authTagLength),s=t.subarray(t.length-this.authTagLength),i=this.generateSrtcpAuthTag(n);tV(s,i,"Failed to authenticate SRTCP packet");let o=Buffer.from(t).slice(0,r);if(t[r]>>>7===0)return[o,e];let c=t.readUInt32BE(r);c&=~(1<<31);let u=t.readUInt32BE(4),l=this.generateCounter(c&65535,c>>16,u,this.srtcpSessionSalt);return JF("aes-128-ctr",this.srtcpSessionKey,l).update(o.subarray(8)).copy(o,8),[o,e]}generateSrtcpAuthTag(t){return YF("sha1",this.srtcpSessionAuthTag).update(t).digest().slice(0,10)}generateCounter(t,e,r,n){let s=Buffer.alloc(16);s.writeUInt32BE(r,4),s.writeUInt32BE(e,8),s.writeUInt32BE(Number(BigInt(t)<<16n),12);for(let i=0;i<n.length;i++)s[i]^=n[i];return s}generateSrtpAuthTag(t,...e){let r=YF("sha1",this.srtpSessionAuthTag),n=Buffer.alloc(4);n.writeUInt32BE(t);for(let s of e)r.update(s);return r.update(n).digest().subarray(0,10)}},eV=4;Kpe=class extends $Z{aeadAuthTagLen=16;rtpIvWriter=Pb([2,4,4,2],!0);rtcpIvWriter=Pb([2,4,2,4],!0);aadWriter=Pb([4],!0);constructor(t,e,r,n){super(t,e,r,n)}encryptRtp(t,e,r){let n=t.serialize(t.serializeSize),s=this.rtpInitializationVector(t,r),i=rV("aes-128-gcm",this.srtpSessionKey,s);i.setAAD(n);let o=i.update(e);i.final();let a=i.getAuthTag();return Buffer.concat([n,o,a])}decryptRtp(t,e,r=n5(t,this.aeadAuthTagLen)){let n=t.subarray(0,r.payloadOffset),s=t.length-this.aeadAuthTagLen,i=t.subarray(s),o=Buffer.from([]);o=XP(o,t.length-this.aeadAuthTagLen),n.copy(o);let a=this.rtpInitializationVector(r,e),c=t.slice(r.payloadOffset,s),u=nV("aes-128-gcm",this.srtpSessionKey,a);u.setAAD(n),u.setAuthTag(i);let l=u.update(c);return iV(u,"SRTP"),l.copy(o,r.payloadOffset),[o,zZ(r,o,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=t.readUInt32BE(4),n=t.length+this.aeadAuthTagLen,s=Buffer.from([]);s=XP(s,n+kP),t.slice(0,8).copy(s);let i=this.rtcpInitializationVector(r,e),o=this.rtcpAdditionalAuthenticatedData(t,e),a=rV("aes-128-gcm",this.srtcpSessionKey,i);a.setAAD(o);let c=a.update(t.slice(8));return a.final(),c.copy(s,8),a.getAuthTag().copy(s,8+c.length),o.slice(8,12).copy(s,n),s}decryptRTCP(t){let e=MZ(t,this.aeadAuthTagLen,kP),r=t.length-kP,n=r-this.aeadAuthTagLen,s=t.readUInt32BE(4),i=t.readUInt32BE(r),o=i>>>31===1,a=i&~(sV<<24),c=this.rtcpInitializationVector(s,a),u=o?Buffer.concat([t.subarray(0,8),t.subarray(r)]):Buffer.concat([t.subarray(0,n),t.subarray(r)]),l=o?t.slice(8,n):Buffer.alloc(0),d=o?Buffer.alloc(n):Buffer.from(t.subarray(0,n));o&&t.slice(0,8).copy(d);let f=nV("aes-128-gcm",this.srtcpSessionKey,c);f.setAAD(u),f.setAuthTag(t.subarray(n,r));let p=f.update(l);return iV(f,"SRTCP"),o&&p.copy(d,8),[d,e]}rtpInitializationVector(t,e){let r=this.rtpIvWriter([0,t.ssrc,e,t.sequenceNumber]);for(let n=0;n<r.length;n++)r[n]^=this.srtpSessionSalt[n];return r}rtcpInitializationVector(t,e){let r=this.rtcpIvWriter([0,t,0,e]);for(let n=0;n<r.length;n++)r[n]^=this.srtcpSessionSalt[n];return r}rtcpAdditionalAuthenticatedData(t,e){let r=Buffer.concat([t.subarray(0,8),this.aadWriter([e])]);return r[8]|=sV,r}},kP=4,sV=128;LZ=class{constructor(t,e,r){this.masterKey=t,this.masterSalt=e,this.profile=r;{let n=14-e.length;n>0&&(this.masterSalt=Buffer.concat([e,Buffer.alloc(n)]))}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=CP("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=CP("sha1",this.srtcpSessionAuthTag),r){case R0:this.cipher=new Vpe(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case hf:this.cipher=new Kpe(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let s=r.length-1,i=e.length-1;s>=0;s--,i--)e[i]=e[i]^r[s];e=Buffer.concat([e,Buffer.from([0,0])]);let n=new uA.default.AES(this.masterKey);return Buffer.from(n.encrypt(e))}generateSessionSalt(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let s=r.length-1,i=e.length-1;s>=0;s--,i--)e[i]=e[i]^r[s];e=Buffer.concat([e,Buffer.from([0,0])]);let n=new uA.default.AES(this.masterKey);return e=Buffer.from(n.encrypt(e)),e.subarray(0,14)}generateSessionAuthTag(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let o=r.length-1,a=e.length-1;o>=0;o--,a--)e[a]=e[a]^r[o];let n=Buffer.concat([e,Buffer.from([0,0])]),s=Buffer.concat([e,Buffer.from([0,1])]),i=new uA.default.AES(this.masterKey);return n=Buffer.from(i.encrypt(n)),s=Buffer.from(i.encrypt(s)),Buffer.concat([n,s.subarray(0,4)])}getSrtpSsrcState(t){let e=this.srtpSSRCStates[t];return e||(e={ssrc:t,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[t]=e,e)}getSrtcpSsrcState(t){let e=this.srtcpSSRCStates[t];return e||(e={srtcpIndex:0,ssrc:t},this.srtcpSSRCStates[t]=e,e)}updateRolloverCount(t,e){e.rolloverHasProcessed?t===0?e.lastSequenceNumber>db&&e.rolloverCounter++:e.lastSequenceNumber<db&&t>oV-db?e.rolloverCounter>0&&e.rolloverCounter--:t<db&&e.lastSequenceNumber>oV-db&&e.rolloverCounter++:e.rolloverHasProcessed=!0,e.lastSequenceNumber=t}generateSrtpAuthTag(t,e){this.srtpSessionAuth=CP("sha1",this.srtpSessionAuthTag);let r=Buffer.alloc(4);return r.writeUInt32BE(e),this.srtpSessionAuth.update(t).update(r).digest().slice(0,10)}index(t){let e=this.srtcpSSRCStates[t];return e?e.srtcpIndex:0}setIndex(t,e){let r=this.getSrtcpSsrcState(t);r.srtcpIndex=e%2147483647}},db=100,oV=65535,Zpe=class extends LZ{constructor(t,e,r){super(t,e,r)}encryptRTCP(t){let e=t.readUInt32BE(4),r=this.getSrtcpSsrcState(e);return r.srtcpIndex++,r.srtcpIndex>>Gpe&&(r.srtcpIndex=0),this.cipher.encryptRTCP(t,r.srtcpIndex)}decryptRTCP(t){return this.cipher.decryptRTCP(t)}},Gpe=2147483647,DZ=class{constructor(t){this.ContextCls=t}localContext;remoteContext;onData;start(t,e,r,n,s){this.localContext=new this.ContextCls(t,e,s),this.remoteContext=new this.ContextCls(r,n,s)}},UZ=class extends DZ{constructor(t){super(Zpe),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRTCP(t);return e};encrypt(t){return this.localContext.encryptRTCP(t)}},Wpe=class extends LZ{constructor(t,e,r){super(t,e,r)}encryptRtp(t,e){let r=this.getSrtpSsrcState(e.ssrc);return this.updateRolloverCount(e.sequenceNumber,r),this.cipher.encryptRtp(e,t,r.rolloverCounter)}decryptRtp(t){let e=n5(t,this.rtpAuthTagLength),r=this.srtpSSRCStates[e.ssrc],n=r?{...r}:{ssrc:e.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(e.sequenceNumber,n);let s=this.cipher.decryptRtp(t,n.rolloverCounter,e);return r?Object.assign(r,n):this.srtpSSRCStates[e.ssrc]=n,s}get rtpAuthTagLength(){return this.profile===hf?16:10}},qZ=class extends DZ{constructor(t){super(Wpe),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRtp(t);return e};encrypt(t,e){return this.localContext.encryptRtp(t,e)}},Xpe=class{constructor(t){this.props=t}sequenceNumber=F8();timestamp=AA();create(t){this.sequenceNumber=Kn(this.sequenceNumber,1);let e=this.props.between*this.props.clockRate/1e3;this.timestamp=tf(this.timestamp,e);let r=new Ic({sequenceNumber:this.sequenceNumber,timestamp:Number(this.timestamp),payloadType:96,extension:!0,marker:!1,padding:!1});return new Pc(r,t)}},vs=wt("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"),Jpe=class extends t1{constructor(t,e,r,n){super(t,e,5,7),this.cipher=r,this.srtp=n}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,4);let e=(()=>{switch(t.msg_type){case 2:return MK.deSerialize(t.fragment);case 11:return TA.deSerialize(t.fragment);case 12:return LK.deSerialize(t.fragment);case 13:return $K.deSerialize(t.fragment);case 14:return jK.deSerialize(t.fragment)}})();e&&O0[e.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(e)}async exec(){if(this.dtls.flight===5){vs(this.dtls.sessionId,"flight5 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let t=this.dtls.requestedCertificateTypes.length>0;vs(this.dtls.sessionId,"send flight5",t);let e=[t&&this.sendCertificate(),this.sendClientKeyExchange(),t&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(r=>r);this.dtls.lastMessage=e,await this.transmit(e)}sendCertificate(){let t=new TA([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(n=>n.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;let t=new BK(this.cipher.localKeyPair.publicKey),e=this.createPacket([t]),r=Buffer.concat(e.map(a=>a.serialize())),n=this.cipher.localKeyPair,s=this.cipher.remoteKeyPair;if(!s.publicKey)throw new Error("not exist");let i=xK(s.publicKey,n.privateKey,n.curve);vs(this.dtls.sessionId,"extendedMasterSecret",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let o=Buffer.concat(this.dtls.sortedHandshakeCache.map(a=>a.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?_K(i,o):bK(i,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=IK(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),vs(this.dtls.sessionId,"cipher",this.cipher.cipher.summary),r}sendCertificateVerify(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize())),e=this.cipher.signatureData(t,"sha256"),r=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case va.ecdsa_3:return UP.ecdsa_secp256r1_sha256;case va.rsa_1:return UP.rsa_pkcs1_sha256}})();if(!r)throw new Error;vs(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,r);let n=new NK(r,e),s=this.createPacket([n]);return Buffer.concat(s.map(o=>o.serialize()))}sendChangeCipherSpec(){let t=OK.createEmpty().serialize(),e=e1(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(n=>n.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(t),r=new ZP(e);this.dtls.epoch=1;let[n]=this.createPacket([r]);this.dtls.recordSequenceNumber=0;let s=this.cipher.encryptPacket(n).serialize();return vs(this.dtls.sessionId,"finished",this.cipher.cipher.summary),s}},O0={};O0[2]=({cipher:t,srtp:e,dtls:r})=>n=>{vs(r.sessionId,"serverHello",n.cipherSuite),t.remoteRandom=nf.from(n.random),t.cipherSuite=n.cipherSuite,vs(r.sessionId,"selected cipherSuite",t.cipherSuite),n.extensions&&n.extensions.forEach(s=>{switch(s.type){case A0.type:{let i=A0.fromData(s.data),o=Lb.findMatchingSRTPProfile(i.profiles,r.options.srtpProfiles||[]);if(vs(r.sessionId,"selected srtp profile",o),o==null)return;e.srtpProfile=o}break;case FA.type:r.remoteExtendedMasterSecret=!0;break;case VA.type:vs(r.sessionId,"RenegotiationIndication");break}})};O0[11]=({cipher:t,dtls:e})=>r=>{vs(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};O0[12]=({cipher:t,dtls:e})=>r=>{if(!t.localRandom||!t.remoteRandom)throw new Error;vs(e.sessionId,"ServerKeyExchange",r),vs(e.sessionId,"selected curve",r.namedCurve),t.remoteKeyPair={curve:r.namedCurve,publicKey:r.publicKey},t.localKeyPair=RK(r.namedCurve)};O0[13]=({dtls:t})=>e=>{vs(t.sessionId,"certificate_request",e),t.requestedCertificateTypes=e.certificateTypes,t.requestedSignatureAlgorithms=e.signatures};O0[14]=({dtls:t})=>e=>{vs(t.sessionId,"server_hello_done",e)};HZ=class kb{constructor(e,r){this.serverVersion=e,this.cookie=r}msgType=3;messageSeq;static spec={serverVersion:J8,cookie:df.types.buffer(df.types.uint8)};static createEmpty(){return new kb(void 0,void 0)}static deSerialize(e){return new kb(...Object.values((0,df.decode)(e,kb.spec)))}serialize(){let e=(0,df.encode)(this,kb.spec).slice();return Buffer.from(e)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let e=this.serialize();return new Mi(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Qpe=wt("werift-dtls : packages/dtls/src/context/dtls.ts : log"),aV=class{constructor(t,e){this.options=t,this.sessionType=e}version={major:254,minor:253};lastFlight=[];lastMessage=[];recordSequenceNumber=0;sequenceNumber=0;epoch=0;flight=0;handshakeCache={};cookie;requestedCertificateTypes=[];requestedSignatureAlgorithms=[];remoteExtendedMasterSecret=!1;get sessionId(){return this.cookie?this.cookie.toString("hex").slice(0,10):""}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([t],[e])=>Number(t)-Number(e)).flatMap(([,{data:t}])=>t.sort((e,r)=>e.message_seq-r.message_seq))}checkHandshakesExist=t=>!t.find(e=>this.sortedHandshakeCache.find(r=>r.msg_type===e)==null);bufferHandshakeCache(t,e,r){this.handshakeCache[r]||(this.handshakeCache[r]={data:[],isLocal:e,flight:r});let n=t.filter(s=>{let i=this.handshakeCache[r].data.find(o=>o.msg_type===s.msg_type);return i?(Qpe(this.sessionId,"exist",i.summary,e,r),!1):!0});this.handshakeCache[r].data=[...this.handshakeCache[r].data,...n]}},e0e=class{constructor(t){this.socket=t}send=t=>this.socket.send(t)},u8=class wc{static type=10;static spec={type:_a.types.uint16be,data:_a.types.array(_a.types.uint16be,_a.types.uint16be,"bytes")};type=wc.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new wc}static fromData(e){return new wc({type:wc.type,data:(0,_a.decode)(e,wc.spec.data)})}static deSerialize(e){return new wc((0,_a.decode)(e,wc.spec))}serialize(){return Buffer.from((0,_a.encode)(this,wc.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},l8=class Uu{static type=13;static spec={type:ba.types.uint16be,data:ba.types.array({hash:ba.types.uint8,signature:ba.types.uint8},ba.types.uint16be,"bytes")};type=Uu.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new Uu}static deSerialize(e){return new Uu((0,ba.decode)(e,Uu.spec))}serialize(){let e=(0,ba.encode)(this,Uu.spec).slice();return Buffer.from(e)}static fromData(e){let r=Buffer.alloc(2);return r.writeUInt16BE(Uu.type),Uu.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},cV=class lA{constructor(e,r){this.level=e,this.description=r}static spec={level:ff.types.uint8,description:ff.types.uint8};static deSerialize(e){return new lA(...Object.values((0,ff.decode)(e,lA.spec)))}serialize(){let e=(0,ff.encode)(this,lA.spec).slice();return Buffer.from(e)}},uV=wt("werift-dtls : packages/dtls/record/receive.ts : log"),TP=wt("werift-dtls : packages/dtls/record/receive.ts : err"),t0e=t=>{let e=0,r=[];for(;t.length>e;){let n=t.readUInt16BE(e+11);if(t.length<e+(12+n))break;let s=kK.deSerialize(t.subarray(e));r.push(s),e+=13+n}return r},r0e=(t,e)=>r=>{switch(r.recordLayerHeader.contentType){case 20:return uV(t.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let s=r.fragment;try{r.recordLayerHeader.epoch>0&&(uV(t.sessionId,"decrypt handshake"),s=e.decryptPacket(r))}catch(i){throw TP(t.sessionId,"decrypt failed",i),i}try{let i=0,o=[];for(;s.length>i;){let a=Mi.deSerialize(s.subarray(i));o.push({type:22,data:a}),i+=a.fragment_length+12}return o}catch(i){throw TP(t.sessionId,"decSerialize failed",i,s),i}}case 23:return[{type:23,data:e.decryptPacket(r)}];case 21:{let s=cV.deSerialize(r.fragment);if(VP[s.description]==null){let i=e.decryptPacket(r);s=cV.deSerialize(i)}if(TP(t.sessionId,"ContentType.alert",s,VP[s.description],"flight",t.flight,"lastFlight",t.lastFlight),s.level>1)throw new Error("alert fatal error");return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},lV=wt("werift-dtls : packages/dtls/src/socket.ts : log"),dV=wt("werift-dtls : packages/dtls/src/socket.ts : err"),s5=class{constructor(t,e){this.options=t,this.sessionType=e,this.dtls=new aV(this.options,this.sessionType),this.cipher=new zb(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new e0e(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new Be;onData=new Be;onError=new Be;onClose=new Be;transport;cipher;dtls;srtp=new Lb;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){lV("renegotiation",this.sessionType),this.connected=!1,this.cipher=new zb(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new aV(this.options,this.sessionType),this.srtp=new Lb,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=t=>{let e=t0e(t);for(let r of e)try{let n=r0e(this.dtls,this.cipher)(r);for(let s of n)switch(s.type){case 22:{let i=s.data,o=this.handleFragmentHandshake([i]),a=Object.values(o.reduce((c,u)=>(c[u.msg_type]||(c[u.msg_type]=[]),c[u.msg_type].push(u),c),{})).map(c=>Mi.assemble(c)).sort((c,u)=>c.msg_type-u.msg_type);this.onHandleHandshakes(a).catch(c=>{dV(this.dtls.sessionId,"onHandleHandshakes error",c),this.onError.execute(c)})}break;case 23:this.onData.execute(s.data);break;case 21:this.onClose.execute();break}}catch(n){dV(this.dtls.sessionId,"catch udpOnMessage error",n)}};setupExtensions(){if(lV(this.dtls.sessionId,"support srtpProfiles",this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let t=A0.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(t.extension)}{let t=u8.createEmpty();t.data=Z8,this.extensions.push(t.extension)}{let t=l8.createEmpty();t.data=W8,this.extensions.push(t.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:FA.type,data:Buffer.alloc(0)});{let t=VA.createEmpty();this.extensions.push(t.extension)}}waitForReady=t=>new Promise(async(e,r)=>{for(let n=0;n<10;n++)if(t()){e();break}else await Ype(100*n);r("waitForReady timeout")});handleFragmentHandshake(t){let e=t.filter(r=>r.fragment_length!==r.length?(this.bufferFragmentedHandshakes.push(r),!1):!0);if(this.bufferFragmentedHandshakes.length>1){let[r]=this.bufferFragmentedHandshakes.slice(-1);r.fragment_offset+r.fragment_length===r.length&&(e=[...this.bufferFragmentedHandshakes,...e],this.bufferFragmentedHandshakes=[])}return e}send=async t=>{let e=e1(this.dtls)([{type:23,fragment:t}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(e).serialize())};close(){this.transport.socket.close()}extractSessionKeys(t,e){let r=this.exportKeyingMaterial("EXTRACTOR-dtls_srtp",t*2+e*2),{clientKey:n,serverKey:s,clientSalt:i,serverSalt:o}=(0,ef.decode)(r,{clientKey:ef.types.buffer(t),serverKey:ef.types.buffer(t),clientSalt:ef.types.buffer(e),serverSalt:ef.types.buffer(e)});return this.sessionType===kc.CLIENT?{localKey:n,localSalt:i,remoteKey:s,remoteSalt:o}:{localKey:s,localSalt:o,remoteKey:n,remoteSalt:i}}exportKeyingMaterial(t,e){return Whe(t,e,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===kc.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},IP=wt("werift-dtls : packages/dtls/src/client.ts : log"),d8=class extends s5{constructor(t){super(t,kc.CLIENT),this.onHandleHandshakes=this.handleHandshakes,IP(this.dtls.sessionId,"start client")}async connect(){await new fpe(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async t=>{IP(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 3:{let r=HZ.deSerialize(e.fragment);await new ppe(this.transport,this.dtls).exec(r)}break;case 2:{if(this.connected)return;this.flight5=new Jpe(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(e)}break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);let r=[11,12,this.options.certificateRequest&&13].filter(n=>typeof n=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),IP(this.dtls.sessionId,"dtls connected");break}}},ya=wt("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),s0e=(t,e,r,n)=>s=>{ya("dtls version",s.clientVersion),e.flight=2,e.recordSequenceNumber=0,e.sequenceNumber=0,s.extensions.forEach(d=>{switch(d.type){case u8.type:{let f=u8.fromData(d.data).data;ya(e.sessionId,"curves",f);let p=f.filter(m=>Z8.includes(m))[0];r.namedCurve=p,ya(e.sessionId,"curve selected",r.namedCurve)}break;case l8.type:{if(!r.signatureHashAlgorithm)throw new Error("need to set certificate");let f=l8.fromData(d.data).data;ya(e.sessionId,"hash,signature",f);let p=f.find(y=>y.signature===r.signatureHashAlgorithm?.signature)?.signature,m=f.find(y=>y.hash===r.signatureHashAlgorithm?.hash)?.hash;if(p==null||m==null)throw new Error("invalid signatureHash")}break;case A0.type:{if(!e.options?.srtpProfiles||e.options.srtpProfiles.length===0)return;let f=A0.fromData(d.data);ya(e.sessionId,"srtp profiles",f.profiles);let p=Lb.findMatchingSRTPProfile(f.profiles,e.options?.srtpProfiles);if(!p)throw new Error;n.srtpProfile=p,ya(e.sessionId,"srtp profile selected",n.srtpProfile)}break;case FA.type:e.remoteExtendedMasterSecret=!0;break;case VA.type:ya(e.sessionId,"RenegotiationIndication",d.data);break;case 43:{let p=[...d.data.subarray(1)].map(m=>m.toString(10));ya("dtls supported version",p)}break}}),r.localRandom=new nf,r.remoteRandom=nf.from(s.random);let i=s.cipherSuites;ya(e.sessionId,"cipher suites",i);let o=(()=>{switch(r.signatureHashAlgorithm?.signature){case va.ecdsa_3:return CA.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case va.rsa_1:return CA.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!i.includes(o))throw new Error("dtls cipher suite negotiation failed");r.cipherSuite=o,ya(e.sessionId,"selected cipherSuite",r.cipherSuite),r.localKeyPair=RK(r.namedCurve),e.cookie||=n0e(20);let a=new HZ({major:254,minor:253},e.cookie),c=TK(e)([a]),l=e1(e)(c.map(d=>({type:22,fragment:d.serialize()})),++e.recordSequenceNumber).map(d=>d.serialize());for(let d of l)t.send(d)},fV=wt("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),i0e=class extends t1{constructor(t,e,r,n){super(t,e,4,6),this.cipher=r,this.srtp=n}async exec(t,e=!1){if(this.dtls.flight===4){fV(this.dtls.sessionId,"flight4 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([t],!1,4);let r=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),e&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(n=>n);this.dtls.lastMessage=r,await this.transmit(r)}sendServerHello(){let t=[];this.srtp.srtpProfile&&t.push(A0.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&t.push({type:FA.type,data:Buffer.alloc(0)});let e=VA.createEmpty();t.push(e.extension);let r=new MK(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,t),n=this.createPacket([r]);return Buffer.concat(n.map(s=>s.serialize()))}sendCertificate(){let t=new TA([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerKeyExchange(){let t=this.cipher.generateKeySignature("sha256");if(!this.cipher.signatureHashAlgorithm)throw new Error("not exist");let e=new LK(G8.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,t.length,t),r=this.createPacket([e]);return Buffer.concat(r.map(n=>n.serialize()))}sendCertificateRequest(){let t=new $K(mK,W8,[]);fV(this.dtls.sessionId,"sendCertificateRequest",t);let e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerHelloDone(){let t=new jK,e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}},k0=wt("werift-dtls : packages/dtls/flight/server/flight6.ts"),o0e=class extends t1{constructor(t,e,r){super(t,e,6),this.cipher=r}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,5);let e=(()=>{switch(t.msg_type){case 11:return TA.deSerialize(t.fragment);case 15:return NK.deSerialize(t.fragment);case 16:return BK.deSerialize(t.fragment);case 20:return ZP.deSerialize(t.fragment)}})();if(e){let r=i1[e.msgType];if(!r)return;r({dtls:this.dtls,cipher:this.cipher})(e)}}async exec(){if(this.dtls.flight===6){k0(this.dtls.sessionId,"flight6 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let t=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=t,await this.transmit(t)}sendChangeCipherSpec(){let t=OK.createEmpty().serialize(),e=e1(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(n=>n.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(t),r=new ZP(e);this.dtls.epoch=1;let[n]=this.createPacket([r]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(n).serialize()}},i1={};i1[16]=({cipher:t,dtls:e})=>r=>{if(t.remoteKeyPair={curve:t.namedCurve,publicKey:r.publicKey},!t.remoteKeyPair.publicKey||!t.localKeyPair||!t.remoteRandom||!t.localRandom)throw new Error("not exist");let n=xK(t.remoteKeyPair.publicKey,t.localKeyPair.privateKey,t.localKeyPair.curve);k0(e.sessionId,"extendedMasterSecret",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);let s=Buffer.concat(e.sortedHandshakeCache.map(i=>i.serialize()));t.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?_K(n,s):bK(n,t.remoteRandom.serialize(),t.localRandom.serialize()),t.cipher=IK(t.cipherSuite),t.cipher.init(t.masterSecret,t.localRandom.serialize(),t.remoteRandom.serialize()),k0(e.sessionId,"setup cipher",t.cipher.summary)};i1[11]=({cipher:t,dtls:e})=>r=>{k0(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};i1[15]=({cipher:t,dtls:e})=>r=>{if(!t.remoteCertificate)throw new Error("client certificate missing before certificate verify");k0(e.sessionId,"certificate_verify",r.algorithm)};i1[20]=({dtls:t})=>e=>{k0(t.sessionId,"finished",e)};d0=wt("werift-dtls : packages/dtls/src/server.ts : log"),FZ=class extends s5{constructor(t){super(t,kc.SERVER),this.onHandleHandshakes=this.handleHandshakes,d0(this.dtls.sessionId,"start server")}flight6;handleHandshakes=async t=>{d0(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 1:{this.connected&&this.renegotiation();let r=CK.deSerialize(e.fragment);r.cookie.length===0?(d0(this.dtls.sessionId,"send flight2"),s0e(this.transport,this.dtls,this.cipher,this.srtp)(r)):this.dtls.cookie&&r.cookie.equals(this.dtls.cookie)?(d0(this.dtls.sessionId,"send flight4"),await new i0e(this.transport,this.dtls,this.cipher,this.srtp).exec(e,this.options.certificateRequest)):d0("wrong state",{dtlsCookie:this.dtls.cookie?.toString("hex").slice(10),helloCookie:r.cookie.toString("hex").slice(10)})}break;case 11:case 15:case 16:{if(this.connected)return;this.flight6=new o0e(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(e)}break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(e);let r=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(n=>typeof n=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),d0(this.dtls.sessionId,"dtls connected")}break}}},GA=554869826,VZ=8,KZ=1398035790,Ac=20,i5=24,o5=1,a5=2,ZZ=6,GZ=50,a0e=["FINGERPRINT","MESSAGE-INTEGRITY","CHANGE-REQUEST","PRIORITY","USERNAME","ICE-CONTROLLING","SOURCE-ADDRESS","USE-CANDIDATE","ICE-CONTROLLED","ERROR-CODE","XOR-MAPPED-ADDRESS","CHANGED-ADDRESS","LIFETIME","REQUESTED-TRANSPORT","NONCE","REALM","XOR-RELAYED-ADDRESS","CHANNEL-NUMBER","XOR-PEER-ADDRESS","DATA","SOFTWARE","MAPPED-ADDRESS","RESPONSE-ORIGIN","OTHER-ADDRESS"],c5=(t=>(t[t.REQUEST=0]="REQUEST",t[t.INDICATION=16]="INDICATION",t[t.RESPONSE=256]="RESPONSE",t[t.ERROR=272]="ERROR",t))(c5||{}),u5=(t=>(t[t.BINDING=1]="BINDING",t[t.SHARED_SECRET=2]="SHARED_SECRET",t[t.ALLOCATE=3]="ALLOCATE",t[t.REFRESH=4]="REFRESH",t[t.SEND=6]="SEND",t[t.DATA=7]="DATA",t[t.CREATE_PERMISSION=8]="CREATE_PERMISSION",t[t.CHANNEL_BIND=9]="CHANNEL_BIND",t))(u5||{});hV=class{queue=[];wait=new Be;put(t){this.queue.push(t),this.queue.length===1&&this.wait.execute(t)}get(){let t=this.queue.shift();return t||new Promise(e=>{this.wait.subscribe(r=>{this.queue.shift(),e(r)})})}},f8=t=>{let e,r,n=new Promise((i,o)=>{e=i,r=o});n.then(()=>{s.execute(void 0),s.complete()}).catch(i=>{s.execute(i??new Error),s.complete()});let s=new Be;return t(e,r,s).catch(()=>{}),{awaitable:n,resolve:e,reject:r}};l5=Buffer.alloc(6);l5.writeUInt16BE(GA>>16,0);l5.writeUInt32BE(GA,2);hb=t=>{let e=Buffer.alloc(4);return e.writeUInt32BE(t,0),e},pb=t=>t.readUInt32BE(0),l0e=t=>{let e=Buffer.alloc(4);return e.writeUInt16BE(t,0),e},d0e=t=>t.readUInt16BE(0),pV=t=>new lP(t.toString()).toBuffer(),mV=t=>{let e=new lP(t);return BigInt(e.toString())},PP=t=>Buffer.from(t,"utf8"),RP=t=>t.toString("utf8"),OP=t=>t,NP=t=>t,f0e=t=>Buffer.from([]),h0e=t=>null,QZ=[[1,"MAPPED-ADDRESS",m0,g0],[3,"CHANGE-REQUEST",hb,pb],[4,"SOURCE-ADDRESS",m0,g0],[5,"CHANGED-ADDRESS",m0,g0],[6,"USERNAME",PP,RP],[8,"MESSAGE-INTEGRITY",OP,NP],[9,"ERROR-CODE",u0e,c0e],[12,"CHANNEL-NUMBER",l0e,d0e],[13,"LIFETIME",hb,pb],[18,"XOR-PEER-ADDRESS",fA,dA],[19,"DATA",OP,NP],[20,"REALM",PP,RP],[21,"NONCE",OP,NP],[22,"XOR-RELAYED-ADDRESS",fA,dA],[25,"REQUESTED-TRANSPORT",hb,pb],[32,"XOR-MAPPED-ADDRESS",fA,dA],[36,"PRIORITY",hb,pb],[37,"USE-CANDIDATE",f0e,h0e],[32802,"SOFTWARE",PP,RP],[32808,"FINGERPRINT",hb,pb],[32809,"ICE-CONTROLLED",pV,mV],[32810,"ICE-CONTROLLING",pV,mV],[32811,"RESPONSE-ORIGIN",m0,g0],[32812,"OTHER-ADDRESS",m0,g0]],eG=class{constructor(t=[]){this.attributes=t}getAttributes(){return this.attributes}setAttribute(t,e){let r=this.attributes.find(n=>n[0]===t);return r?r[1]=e:this.attributes.push([t,e]),this}getAttributeValue(t){let e=this.attributes.find(r=>r[0]===t);if(e)return e[1]}get attributesKeys(){return this.attributes.map(t=>t[0])}clear(){this.attributes=[]}},gV=QZ.reduce((t,e)=>(t[e[0]]=e,t),{}),p0e=QZ.reduce((t,e)=>(t[e[1]]=e,t),{});$i=class extends eG{constructor(t,e,r=JZ(),n=[]){super(n),this.messageMethod=t,this.messageClass=e,this.transactionId=r}toJSON(){return this.json}get json(){return{messageMethod:u5[this.messageMethod],messageClass:c5[this.messageClass],attributes:this.attributes}}get transactionIdHex(){return this.transactionId.toString("hex")}get bytes(){let t=Buffer.from([]);for(let r of this.attributesKeys){let n=this.getAttributeValue(r),[s,,i]=p0e[r],o=i.name===fA.name?i(n,this.transactionId):i(n),a=o.length,c=4*Math.floor((a+3)/4)-a,u=Buffer.alloc(4);u.writeUInt16BE(s,0),u.writeUInt16BE(a,2),t=Buffer.concat([t,u,o,Buffer.alloc(c,0)])}let e=Buffer.alloc(8);return e.writeUInt16BE(this.messageMethod|this.messageClass,0),e.writeUInt16BE(t.length,2),e.writeUInt32BE(GA,4),Buffer.concat([e,this.transactionId,t])}addMessageIntegrity(t){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(t)),this}messageIntegrity(t){let e=d5(this.bytes,this.bytes.length-Ac+i5);return Buffer.from(WZ("sha1",t).update(e).digest("hex"),"hex")}addFingerprint(){this.setAttribute("FINGERPRINT",tG(this.bytes))}},d5=(t,e)=>{let r=Buffer.alloc(t.length);return t.copy(r,0,0,2),r.writeUInt16BE(e,2),t.copy(r,4,4),r};rG=class extends Error{response;addr},nG=class extends rG{constructor(t,e){super(),this.response=t,this.addr=e}get str(){let t="STUN transaction failed",e=this.response.getAttributeValue("ERROR-CODE");if(e){let[r,n]=e;t+=` (${r} - ${n})`}return t}},g0e=class extends rG{get str(){return"STUN transaction timed out"}},BP=wt("werift-ice:packages/ice/src/stun/transaction.ts"),f5=class{constructor(t,e,r,n){this.request=t,this.addr=e,this.protocol=r,this.retransmissions=n,this.triesMax=1+(this.retransmissions?this.retransmissions:ZZ)}timeoutDelay=GZ;ended=!1;tries=0;triesMax;onResponse=new Be;responseReceived=(t,e)=>{this.onResponse.length>0&&(t.messageClass===256?(this.onResponse.execute(t,e),this.onResponse.complete()):this.onResponse.error(new nG(t,e)))};run=async()=>{try{return this.retry().catch(e=>{BP("retry failed",e)}),await this.onResponse.asPromise()}catch(t){throw t}finally{this.cancel()}};retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.protocol.sendStun(this.request,this.addr).catch(t=>{BP("send stun failed",t)}),await new Promise(t=>setTimeout(t,this.timeoutDelay)),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&(BP(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.onResponse.error(new g0e))};cancel(){this.ended=!0}},yV=wt("werift-ice : packages/ice/src/stun/protocol.ts"),PA=class sG{static type="stun";type=sG.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new Be;onDataReceived=new Be;constructor(){}connectionMade=async(e,r,n)=>{e?this.transport=await EA.init("udp4",{portRange:r,interfaceAddresses:n}):this.transport=await EA.init("udp6",{portRange:r,interfaceAddresses:n}),this.transport.onData=(s,i)=>{this.datagramReceived(s,i)}};datagramReceived(e,r){try{let n=WA(e);if(!n){this.localCandidate&&this.onDataReceived.execute(e);return}(n.messageClass===256||n.messageClass===272)&&this.transactionsKeys.includes(n.transactionIdHex)?this.transactions[n.transactionIdHex].responseReceived(n,r):n.messageClass===0&&this.onRequestReceived.execute(n,r,e)}catch(n){yV("datagramReceived error",n)}}getExtraInfo(){let{address:e,port:r}=this.transport.address;return[e,r]}async sendStun(e,r){if(this.transport.closed)return;let n=e.bytes;await this.transport.send(n,r).catch(()=>{yV("sendStun failed",r,e)})}async sendData(e,r){this.transport.closed||await this.transport.send(e,r)}async request(e,r,n,s){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error("already request ed");n&&(e.addMessageIntegrity(n),e.addFingerprint());let i=new f5(e,r,this,s);this.transactions[e.transactionIdHex]=i;try{return await i.run()}catch(o){throw o}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()}),await this.transport.close(),this.onRequestReceived.complete(),this.onDataReceived.complete()}},Vs=wt("werift-ice:packages/ice/src/turn/protocol.ts"),b0e=500,_0e=600,v0e=285212672,iG=class oG{constructor(e){this.turn=e,e.onData.subscribe((r,n)=>{this.handleStunMessage(r,n)}).disposer(this.disposer)}static type="turn";type=oG.type;localCandidate;disposer=new uK;onRequestReceived=new Be;onDataReceived=new Be;handleStunMessage=(e,r)=>{try{let n=WA(e);if(!n){this.onDataReceived.execute(e);return}if(n.messageClass===256||n.messageClass===272){let s=this.turn.transactions[n.transactionIdHex];s&&s.responseReceived(n,r)}else n.messageClass===0&&this.onRequestReceived.execute(n,r,e)}catch(n){Vs("datagramReceived error",n)}};async request(e,r,n){if(this.turn.transactions[e.transactionIdHex])throw new Error("exist");n&&(e.addMessageIntegrity(n),e.addFingerprint());let s=new f5(e,r,this);this.turn.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(i){throw i}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,r){await this.turn.sendData(e,r)}async sendStun(e,r){await this.turn.sendData(e.bytes,r)}async close(){return this.disposer.dispose(),this.turn.close()}},aG=class cG{constructor(e,r,n,s,i,o={}){this.server=e,this.username=r,this.password=n,this.lifetime=s,this.transport=i,this.options=o,this.channelRefreshTime=this.options.channelRefreshTime??b0e}static type="turn";type=cG.type;onData=new Be;onRequestReceived=new Be;onDataReceived=new Be;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBinding;channelRefreshAt=0;tcpBuffer=Buffer.alloc(0);permissionByAddr={};creatingPermission=Promise.resolve();async connectionMade(){this.transport.onData=(s,i)=>{this.dataReceived(s,i)};let e=new $i(3,0);e.setAttribute("LIFETIME",this.lifetime).setAttribute("REQUESTED-TRANSPORT",v0e);let[r]=await this.requestWithRetry(e,this.server).catch(s=>{throw Vs("connect error",s),s});this.relayedAddress=r.getAttributeValue("XOR-RELAYED-ADDRESS"),this.mappedAddress=r.getAttributeValue("XOR-MAPPED-ADDRESS");let n=r.getAttributeValue("LIFETIME");Vs("connect",this.relayedAddress,this.mappedAddress,{exp:n}),this.refresh(n)}handleChannelData(e){let[r,n]=p8.jspack.Unpack("!HH",e.slice(0,4)),s=this.addrByChannel[r];if(s){let i=e.subarray(4,4+n);this.onData.execute(i,s)}}handleSTUNMessage(e,r){try{let n=WA(e);if(!n)throw new Error("not stun message");if(n.messageClass===256||n.messageClass===272){let s=this.transactions[n.transactionIdHex];s&&s.responseReceived(n,r)}else n.messageClass===0&&this.onData.execute(e,r);if(n.getAttributeValue("DATA")){let s=n.getAttributeValue("DATA");this.onData.execute(s,r)}}catch{Vs("parse error",e.toString())}}dataReceived(e,r){let n=(s,i)=>{s.length>=4&&xV(s)?this.handleChannelData(s):this.handleSTUNMessage(s,i)};if(this.transport.type==="tcp")for(this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);this.tcpBuffer.length>=4;){let[,s]=ws(this.tcpBuffer.subarray(0,4),[2,2]);s+=h8(s);let i=xV(this.tcpBuffer)?4+s:20+s;if(this.tcpBuffer.length<i)break;n(this.tcpBuffer.subarray(0,i),r),this.tcpBuffer=this.tcpBuffer.subarray(i)}else n(e,r)}async send(e,r){if(!this.transport.closed)if(this.transport.type==="tcp"){let n=h8(e.length);await this.transport.send(n>0?Buffer.concat([e,Buffer.alloc(n)]):e,r)}else await this.transport.send(e,r)}async createPermission(e){let r=new $i(8,0);r.setAttribute("XOR-PEER-ADDRESS",e).setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce),await this.request(r,this.server).catch(n=>{throw n})}refresh=e=>{this.refreshHandle=f8(async(r,n,s)=>{let i=!0;for(s.once(()=>{i=!1});i;){let o=.8333333333333334*e*1e3;Vs("refresh delay",o,{exp:e}),await x0e(o);let a=new $i(4,0);a.setAttribute("LIFETIME",e);try{let[c]=await this.requestWithRetry(a,this.server);e=c.getAttributeValue("LIFETIME"),Vs("refresh",{exp:e})}catch(c){Vs("refresh error",c)}}})};async request(e,r){if(this.transactions[e.transactionIdHex])throw new Error("exist");this.integrityKey&&e.setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let n=new f5(e,r,this);this.transactions[e.transactionIdHex]=n;try{return await n.run()}catch(s){throw s}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,r){let n,s;try{[n,s]=await this.request(e,r)}catch(i){if(!(i instanceof nG))throw Vs("requestWithRetry error",i),i;this.server=i.addr;let[o]=i.response.getAttributeValue("ERROR-CODE"),a=i.response.getAttributeValue("NONCE"),c=i.response.getAttributeValue("REALM");if((o===401&&c||o===438&&this.realm)&&a)Vs("retry with nonce",o),this.nonce=a,o===401&&(this.realm=c),this.integrityKey=lG(this.username,this.realm,this.password),e.transactionId=JZ(),[n,s]=await this.request(e,this.server);else throw i}return[n,s]}async sendData(e,r){let n=await this.getChannel(r).catch(i=>new Error("channelBind error"));if(n instanceof Error){await this.getPermission(r);let i=new $i(6,16).setAttribute("DATA",e).setAttribute("XOR-PEER-ADDRESS",r);await this.sendStun(i,this.server);return}let s=p8.jspack.Pack("!HH",[n.number,e.length]);await this.send(Buffer.concat([Buffer.from(s),e]),this.server)}async getPermission(e){await this.creatingPermission,this.permissionByAddr[e.join(":")]||(this.creatingPermission=this.createPermission(e),this.permissionByAddr[e.join(":")]=!0,await this.creatingPermission.catch(n=>{throw Vs("createPermission error",n),n}))}async getChannel(e){this.channelBinding&&await this.channelBinding;let r=this.channelByAddr[e.join(":")];return r?this.channelRefreshAt<_0(Date.now()/1e3)&&(this.channelBinding=this.channelBind(r.number,e),this.channelRefreshAt=_0(Date.now()/1e3)+this.channelRefreshTime,await this.channelBinding.catch(n=>{throw Vs("channelBind error",n),n}),this.channelBinding=void 0,Vs("channelBind refresh",r)):(this.channelByAddr[e.join(":")]={number:this.channelNumber++,address:e},r=this.channelByAddr[e.join(":")],this.addrByChannel[r.number]=e,this.channelBinding=this.channelBind(r.number,e),await this.channelBinding.catch(n=>{throw Vs("channelBind error",n),n}),this.channelRefreshAt=_0(Date.now()/1e3)+this.channelRefreshTime,this.channelBinding=void 0,Vs("channelBind",r)),r}async channelBind(e,r){let n=new $i(9,0);n.setAttribute("CHANNEL-NUMBER",e).setAttribute("XOR-PEER-ADDRESS",r);let[s]=await this.requestWithRetry(n,this.server);if(s.messageMethod!==9)throw new Error("should be CHANNEL_BIND")}async sendStun(e,r){await this.send(e.bytes,r)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};Vu=class dG{constructor(e,r,n,s,i,o,a,c,u,l,d,f){this.foundation=e,this.component=r,this.transport=n,this.priority=s,this.host=i,this.port=o,this.type=a,this.relatedAddress=c,this.relatedPort=u,this.tcptype=l,this.generation=d,this.ufrag=f}static fromSdp(e){let r=e.split(" ");if(r.length<8)throw new Error("SDP does not have enough properties");let n={foundation:r[0],component:Number(r[1]),transport:r[2],priority:Number(r[3]),host:r[4],port:Number(r[5]),type:r[7]};for(let d=8,f=r.length-1;d<f;d+=2)r[d]==="raddr"?n.related_address=r[d+1]:r[d]==="rport"?n.related_port=Number(r[d+1]):r[d]==="tcptype"?n.tcptype=r[d+1]:r[d]==="generation"?n.generation=Number(r[d+1]):r[d]==="ufrag"&&(n.ufrag=r[d+1]);let{foundation:s,component:i,transport:o,priority:a,host:c,port:u,type:l}=n;return new dG(s,i,o,a,c,u,l,n.related_address,n.related_port,n.tcptype,n.generation,n.ufrag)}canPairWith(e){let r=bV(this.host),n=bV(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&r===n}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;return this.relatedAddress&&(e+=` raddr ${this.relatedAddress}`),this.relatedPort!=null&&(e+=` rport ${this.relatedPort}`),this.tcptype&&(e+=` tcptype ${this.tcptype}`),this.generation!=null&&(e+=` generation ${this.generation}`),this.ufrag!=null&&(e+=` ufrag ${this.ufrag}`),e}};A0e=class{cache=new Map;mdnsInstance=(0,fG.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(t){return new Promise((e,r)=>{let n=()=>{this.mdnsInstance.removeListener("response",i),clearTimeout(s)},s=setTimeout(()=>{n(),r(new Error("No mDNS response"))},1e4),i=o=>{let a=o.answers?.[0];a?.type==="A"&&a.name===t&&(n(),e(a.data))};this.mdnsInstance.on("response",i),this.mdnsInstance.query(t,"A")})}close(){this.mdnsInstance.destroy()}},C0e=wt("werift-ice : packages/ice/src/ice.ts : log"),y8=class{constructor(t,e,r){this.protocol=t,this.remoteCandidate=e,this.iceControlling=r}id=E0e().toString();handle;nominated=!1;remoteNominated=!1;_state=0;get state(){return this._state}packetsSent=0;packetsReceived=0;bytesSent=0;bytesReceived=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(t){this._state=t}get localCandidate(){if(!this.protocol.localCandidate)throw new Error("localCandidate not exist");return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return OA(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}},x8=1,Tb=2,hG=5,b8=6,pG=(t=>(t[t.FROZEN=0]="FROZEN",t[t.WAITING=1]="WAITING",t[t.IN_PROGRESS=2]="IN_PROGRESS",t[t.SUCCEEDED=3]="SUCCEEDED",t[t.FAILED=4]="FAILED",t))(pG||{}),mG={useIpv4:!0,useIpv6:!0};k0e=wt("werift-ice : packages/ice/src/utils.ts");I0e=t=>{if(!t)return;let[e,r]=t.split(":");return[e,Number.parseInt(r)]},xr=wt("werift-ice : packages/ice/src/ice.ts : log"),wG=class{constructor(t,e){this._iceControlling=t,this.options={...mG,...e};let{stunServer:r,turnServer:n}=this.options;this.stunServer=v8(r)??["stun.l.google.com",19302],this.turnServer=v8(n),this.restart(),xr("new Connection",this.options)}localUsername=fb(4);localPassword=fb(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=BigInt(new Y2(S0e(64)).toString());state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new hV;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;onData=new Be;stateChanged=new Be;onIceCandidate=new Be;get iceControlling(){return this._iceControlling}set iceControlling(t){if(!(this.generation>0||this.nominated)){this._iceControlling=t;for(let e of this.checkList)e.iceControlling=t}}async restart(){this.generation++,this.localUsername=fb(4),this.localPassword=fb(22),this.options.localPasswordPrefix&&(this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length)),this.userHistory[this.localUsername]=this.localPassword,this.remoteUsername="",this.remotePassword="",this.localCandidates=[],this._remoteCandidates=[],this.remoteCandidatesEnd=!1,this.localCandidatesEnd=!1,this.state="new",this.lookup?.close?.(),this.lookup=void 0,this.nominated=void 0,this.nominating=!1,this.checkList=[],this.checkListDone=!1,this.checkListState=new hV,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let t of this.protocols)t.localCandidate&&(t.localCandidate.generation=this.generation,t.localCandidate.ufrag=this.localUsername);this.queryConsentHandle?.resolve?.(),this.queryConsentHandle=void 0}resetNominatedPair(){xr("resetNominatedPair"),this.nominated=void 0,this.nominating=!1}setRemoteParams({iceLite:t,usernameFragment:e,password:r}){xr("setRemoteParams",{iceLite:t,usernameFragment:e,password:r}),this.remoteIsLite=t,this.remoteUsername=e,this.remotePassword=r}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;let t=vG(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:e}=this.options;if(e){let n=t.filter(s=>Object.values(e).includes(s));n.length&&(t=n)}this.options.additionalHostAddresses&&(t=Array.from(new Set([...this.options.additionalHostAddresses,...t])));let r=this.getCandidatePromises(t,5);await Promise.allSettled(r),this.localCandidatesEnd=!0}this.setState("completed")}appendLocalCandidate(t){this.localCandidates.push(t),this.onIceCandidate.execute(t)}ensureProtocol(t){t.onRequestReceived.subscribe((e,r,n)=>{if(e.messageMethod!==1){this.respondError(e,r,t,[400,"Bad Request"]);return}let s=e.getAttributeValue("USERNAME"),{remoteUsername:i}=vV(s),o=this.userHistory[i]??this.localPassword,{iceControlling:a}=this;if(a&&e.attributesKeys.includes("ICE-CONTROLLING"))if(this.tieBreaker>=e.getAttributeValue("ICE-CONTROLLING")){this.respondError(e,r,t,[487,"Role Conflict"]);return}else this.switchRole(!1);else if(!a&&e.attributesKeys.includes("ICE-CONTROLLED"))if(this.tieBreaker<e.getAttributeValue("ICE-CONTROLLED"))this.respondError(e,r,t,[487,"Role Conflict"]);else{this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(e,r,t))return;let c=new $i(1,256,e.transactionId);c.setAttribute("XOR-MAPPED-ADDRESS",r).addMessageIntegrity(Buffer.from(o,"utf8")).addFingerprint(),t.sendStun(c,r).catch(u=>{xr("sendStun error",u)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([e,r,t]):this.checkIncoming(e,r,t)}),t.onDataReceived.subscribe(e=>{try{let r=this.nominated;r&&r.protocol===t&&(r.packetsReceived++,r.bytesReceived+=e.length),this.onData.execute(e)}catch(r){xr("dataReceived",r)}})}getCandidatePromises(t,e=5){let r=[];t=t.filter(c=>!this.protocols.find(u=>u.localIp===c));let n=t.map(async c=>{let u=new PA;this.ensureProtocol(u);try{await u.connectionMade(_V(c),this.options.portRange,this.options.interfaceAddresses),u.localIp=c,this.protocols.push(u),xr("protocol",u.localIp);let l=[c,u.getExtraInfo()[1]];return u.localCandidate=new Vu(RA("host","udp",l[0]),1,"udp",Ob("host"),l[0],l[1],"host",void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(u),this.appendLocalCandidate(u.localCandidate),u}catch(l){xr("error protocol STUN",l)}});r.push(...n.map(c=>c.then(u=>u?.localCandidate)));let{stunServer:s,turnServer:i}=this;if(s){let c=n.map(async u=>{let l=await u;return l?new Promise(async(f,p)=>{let m=setTimeout(p,e*1e3);if(l.localCandidate?.host&&_V(l.localCandidate?.host)){let y=await yG(l,s).catch(_=>{xr("error",_)});y&&this.appendLocalCandidate(y),clearTimeout(m),f(y)}else clearTimeout(m),f()}).catch(f=>{xr("query STUN server",f)}):void 0});r.push(...c)}let{turnUsername:o,turnPassword:a}=this.options;if(i&&o&&a){let c=(async()=>{let u=await m8({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:this.options.turnTransport==="tcp"?"tcp":"udp"}).catch(async f=>{if(this.options.turnTransport!=="tcp")return await m8({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:"tcp"});throw f});this.ensureProtocol(u),this.protocols.push(u);let l=u.turn.relayedAddress,d=u.turn.mappedAddress;return xr("turn candidateAddress",l),u.localCandidate=new Vu(RA("relay","udp",l[0]),1,"udp",Ob("relay"),l[0],l[1],"relay",d[0],d[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(u.localCandidate),u.localCandidate})().catch(u=>{xr("query TURN server",u)});this.options.forceTurn&&(r=[]),r.push(c)}return r}async connect(){if(xr("start connect ice"),!this.localCandidatesEnd&&!this.localCandidatesStart)throw new Error("Local candidates gathering was not performed");if(!this.remoteUsername||!this.remotePassword)throw new Error("Remote username or password is missing");for(let e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList(),this.unfreezeInitial(),xr("earlyChecks",this.localPassword,this.earlyChecks.length);for(let e of this.earlyChecks)this.checkIncoming(...e);for(this.earlyChecks=[],this.earlyChecksDone=!0;!(this.state==="closed"||!this.schedulingChecks());)await g8.setTimeout(20);let t=Tb;for(;this.checkList.length>0&&t===Tb;)t=await this.checkListState.get(),xr("checkListState",t);for(let e of this.checkList)e.handle?.resolve?.();if(t!==x8)throw new Error("ICE negotiation failed");this.queryConsent(),this.setState("connected")}unfreezeInitial(){let[t]=this.checkList;if(!t)return;t.state===0&&t.updateState(1);let e=new Set(t.localCandidate.foundation);for(let r of this.checkList)r.component===t.component&&!e.has(r.localCandidate.foundation)&&r.state===0&&(r.updateState(1),e.add(r.localCandidate.foundation))}schedulingChecks(){{let t=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===PA.type)).find(e=>e.state===1);if(t)return t.handle=this.checkStart(t),!0}{let t=this.checkList.find(e=>e.state===0);if(t)return t.handle=this.checkStart(t),!0}return this.remoteCandidatesEnd?!1:!this.checkListDone}queryConsent=()=>{this.queryConsentHandle&&this.queryConsentHandle.resolve(),this.queryConsentHandle=f8(async(t,e,r)=>{let n=0,s=!1,i=new AbortController;r.once(()=>{s=!0,n+=b8,i.abort(),this.queryConsentHandle=void 0});let{localUsername:o,remoteUsername:a,iceControlling:c}=this;try{for(;this.state!=="closed"&&!s;){await g8.setTimeout(hG*(.8+.4*Math.random())*1e3,void 0,{signal:i.signal});let u=this.nominated;if(!u||s)break;let l=this.buildRequest({nominate:!1,localUsername:o,remoteUsername:a,iceControlling:c});try{await u.protocol.request(l,u.remoteAddr,Buffer.from(this.remotePassword,"utf8"),0),n=0,this.state==="disconnected"&&this.setState("connected")}catch{if(u.id===this.nominated?.id){xr("no stun response"),n++,this.setState("disconnected");break}}if(n>=b8){xr("Consent to send expired"),this.queryConsentHandle=void 0,this.setState("closed");break}}}catch{}})};async close(){this.setState("closed"),this.queryConsentHandle?.resolve?.(),this.checkList&&!this.checkListDone&&this.checkListState.put(new Promise(t=>{t(Tb)})),this.nominated=void 0;for(let t of this.protocols)t.close&&await t.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(t){this.state=t,this.stateChanged.execute(t)}async addRemoteCandidate(t){if(!t){this.remoteCandidatesEnd=!0;return}if(t.host.includes(".local"))try{this.lookup||(this.lookup=new A0e);let e=await this.lookup.lookup(t.host);t.host=e}catch{return}try{_8(t)}catch{return}xr("addRemoteCandidate",t),this._remoteCandidates.push(t),this.pairRemoteCandidate(t),this.sortCheckList()}send=async t=>{let e=this.nominated;if(e)await e.protocol.sendData(t,e.remoteAddr),e.packetsSent++,e.bytesSent+=t.length;else return};getDefaultCandidate(){let t=this.localCandidates.sort((r,n)=>r.priority-n.priority),[e]=t;return e}set remoteCandidates(t){if(this.remoteCandidatesEnd)throw new Error("Cannot set remote candidates after end-of-candidates.");this._remoteCandidates=[];for(let e of t){try{_8(e)}catch{continue}this._remoteCandidates.push(e)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){gG(this.checkList,this.iceControlling)}findPair(t,e){return this.checkList.find(n=>(0,hA.default)(n.protocol,t)&&(0,hA.default)(n.remoteCandidate,e))}switchRole(t){xr("switch role",t),this.iceControlling=t,this.sortCheckList()}checkComplete(t){if(t.handle=void 0,t.state===3){if(t.nominated&&(t.remoteCandidate.generation==null||t.remoteCandidate.generation===this.generation)&&this.nominated==null){xr("nominated",t.toJSON()),this.nominated=t,this.nominating=!1;for(let e of this.checkList)e.component===t.component&&[1,0].includes(e.state)&&e.updateState(4)}if(this.nominated){this.checkListDone||(xr("ICE completed"),this.checkListState.put(new Promise(e=>e(x8))),this.checkListDone=!0);return}xr("not completed",t.toJSON());for(let e of this.checkList)e.localCandidate.foundation===t.localCandidate.foundation&&e.state===0&&e.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:r})=>!e.includes(r)))return}!this.iceControlling&&this.checkList.find(({state:r})=>r===3)||this.checkListDone||(xr("ICE failed"),this.checkListState.put(new Promise(e=>{e(Tb)})))}checkStart=t=>f8(async e=>{xr("check start",t.toJSON()),t.updateState(2);let r={},{remotePassword:n,remoteUsername:s,generation:i}=this,o=t.localCandidate.ufrag??this.localUsername,a=this.iceControlling&&!this.remoteIsLite,c=this.buildRequest({nominate:a,localUsername:o,remoteUsername:s,iceControlling:this.iceControlling}),u=performance.now();try{let[l,d]=await t.protocol.request(c,t.remoteAddr,Buffer.from(n,"utf8"),4),p=(performance.now()-u)/1e3;t.rtt=p,t.totalRoundTripTime+=p,t.roundTripTimeMeasurements++,xr("response received",c.toJSON(),l.toJSON(),d,{localUsername:o,remoteUsername:s,remotePassword:n,generation:i,rtt:p}),r.response=l,r.addr=d}catch(l){let d=l;if(xr("failure case",c.toJSON(),d.response?JSON.stringify(d.response.toJSON(),null,2):l,{localUsername:o,remoteUsername:s,remotePassword:n,generation:i},t.remoteAddr),d.response?.getAttributeValue("ERROR-CODE")[0]===487){c.attributesKeys.includes("ICE-CONTROLLED")?this.switchRole(!0):c.attributesKeys.includes("ICE-CONTROLLING")&&this.switchRole(!1),await this.checkStart(t).awaitable,e();return}if(d.response?.getAttributeValue("ERROR-CODE")[0]===401){xr("retry 401",t.toJSON()),await this.checkStart(t).awaitable,e();return}else{xr("checkStart CandidatePairState.FAILED",t.toJSON()),t.updateState(4),this.checkComplete(t),e();return}}if(!(0,hA.default)(r.addr,t.remoteAddr)){t.updateState(4),this.checkComplete(t),e();return}if(a||t.remoteNominated)t.nominated=!0;else if(this.iceControlling&&!this.nominating){this.nominating=!0;let l=this.buildRequest({nominate:!0,localUsername:o,remoteUsername:s,iceControlling:this.iceControlling});try{await t.protocol.request(l,t.remoteAddr,Buffer.from(this.remotePassword,"utf8"))}catch{t.updateState(4),this.checkComplete(t);return}t.nominated=!0}t.updateState(3),this.checkComplete(t),e()});addPair(t){this.checkList.push(t),this.sortCheckList()}checkIncoming(t,e,r){let n=t.getAttributeValue("USERNAME"),{remoteUsername:s}=vV(n),i,[o,a]=e;for(let u of this.remoteCandidates)if(u.host===o&&u.port===a){i=u;break}i||(i=new Vu(fb(10),1,"udp",t.getAttributeValue("PRIORITY"),o,a,"prflx",void 0,void 0,void 0,void 0,void 0),this._remoteCandidates.push(i));let c=this.findPair(r,i);c||(c=new y8(r,i,this.iceControlling),c.updateState(1),this.addPair(c)),c.localCandidate.ufrag=s,xr("Triggered Checks",t.toJSON(),c.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),[1,4].includes(c.state)&&(c.handle=this.checkStart(c)),t.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling&&(c.remoteNominated=!0,c.state===3&&(c.nominated=!0,this.checkComplete(c)))}tryPair(t,e){if(t.localCandidate?.canPairWith(e)&&!this.findPair(t,e)){let r=new y8(t,e,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(r))return;r.updateState(1),this.addPair(r)}}pairLocalProtocol(t){for(let e of this.remoteCandidates)this.tryPair(t,e)}pairRemoteCandidate=t=>{for(let e of this.protocols)this.tryPair(e,t)};buildRequest({nominate:t,remoteUsername:e,localUsername:r,iceControlling:n}){let s=P0e({remoteUsername:e,localUsername:r}),i=new $i(1,0);return i.setAttribute("USERNAME",s).setAttribute("PRIORITY",Ob("prflx")),n?(i.setAttribute("ICE-CONTROLLING",this.tieBreaker),t&&i.setAttribute("USE-CANDIDATE",null)):i.setAttribute("ICE-CONTROLLED",this.tieBreaker),i}respondError(t,e,r,n){let s=new $i(t.messageMethod,272,t.transactionId);s.setAttribute("ERROR-CODE",n).addMessageIntegrity(Buffer.from(this.localPassword,"utf8")).addFingerprint(),r.sendStun(s,e).catch(i=>{xr("sendStun error",i)})}},P0e=({remoteUsername:t,localUsername:e})=>`${t}:${e}`,vV=t=>{let[e,r]=t.split(":");return{remoteUsername:e,localUsername:r}};h5=class extends R0e{addEventListener=(t,e)=>{this.addListener(t,e)};removeEventListener=(t,e)=>{this.removeListener(t,e)}},O0e=wt("werift:packages/webrtc/src/dataChannel.ts");p5=class extends h5{constructor(t,e,r=!0){if(super(),this.sctp=t,this.parameters=e,this.sendOpen=r,this.id=this.parameters.id,e.negotiated){if(this.id==null||this.id<0||this.id>65534)throw new Error("ID must be in range 0-65534 if data channel is negotiated out-of-band");this.sctp.dataChannelAddNegotiated(this)}else r&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}stateChange=new Be;stateChanged=new Be;onMessage=new Be;error=new Be;bufferedAmountLow=new Be;onopen;onclose;onclosing;onmessage;onerror;isCreatedByRemote=!1;id;readyState="connecting";bufferedAmount=0;_bufferedAmountLowThreshold=0;messagesSent=0;bytesSent=0;messagesReceived=0;bytesReceived=0;get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(t){if(t<0||t>4294967295)throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");this._bufferedAmountLowThreshold=t}setId(t){this.id=t}setReadyState(t){if(t!==this.readyState){switch(this.readyState=t,this.stateChange.execute(t),this.stateChanged.execute(t),t){case"open":this.onopen&&this.onopen(),this.emit("open");break;case"closed":this.onclose&&this.onclose(),this.emit("close");break;case"closing":this.onclosing&&this.onclosing();break}O0e("change state",t)}}addBufferedAmount(t){let e=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+t<=this.bufferedAmountLowThreshold;this.bufferedAmount+=t,e&&(this.bufferedAmountLow.execute(),this.emit("bufferedamountlow"))}send(t){let e=this.sctp.datachannelSend(this,t);this.messagesSent++,this.bytesSent+=e}close(){this.sctp.dataChannelClose(this)}},m5=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(t={}){Object.assign(this,t)}},N0e=()=>({type:"ccm",parameter:"fir"}),o1=()=>({type:"nack"}),N0=()=>({type:"nack",parameter:"pli"}),a1=()=>({type:"goog-remb"}),AG=()=>({type:"transport-cc"}),Ku=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction="all";constructor(t){Object.assign(this,t)}get name(){return this.mimeType.split("/")[1]}get contentType(){return this.mimeType.split("/")[0]}get str(){let t=`${this.name}/${this.clockRate}`;return this.channels===2&&(t+="/2"),t}},wa=class{id;uri;constructor(t){Object.assign(this,t)}},B0e=class{cname;mux=!1;ssrc;constructor(t={}){Object.assign(this,t)}},EG=class{type;parameter;constructor(t={}){Object.assign(this,t)}},CG=class{ssrc;constructor(t={}){Object.assign(this,t)}},kG=class{ssrc;payloadType;rtx;constructor(t){Object.assign(this,t)}},g5=class{rid;direction;constructor(t){Object.assign(this,t)}},TG=(t={})=>new Ku({mimeType:"video/h264",clockRate:9e4,rtcpFeedback:[o1(),N0(),a1()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...t}),y5=(t={})=>new Ku({mimeType:"video/VP8",clockRate:9e4,rtcpFeedback:[o1(),N0(),a1()],...t}),IG=(t={})=>new Ku({mimeType:"video/VP9",clockRate:9e4,rtcpFeedback:[o1(),N0(),a1()],...t}),PG=(t={})=>new Ku({mimeType:"video/AV1X",clockRate:9e4,rtcpFeedback:[o1(),N0(),a1()],...t}),x5=(t={})=>new Ku({mimeType:"audio/OPUS",clockRate:48e3,channels:2,...t}),b5=(t={})=>new Ku({mimeType:"audio/PCMU",clockRate:8e3,channels:1,payloadType:0,...t}),_5=[PG(),IG(),y5(),TG(),x5(),b5()].map(t=>t.mimeType),$0e=_5.filter(t=>t.toLowerCase().startsWith("video/")),M0e=_5.filter(t=>t.toLowerCase().startsWith("audio/"));AV=2,EV=3,W0e=0,sA=50,CV=51,kV=53,X0e=56,J0e=57,Y0e="0.0.0.0",TV=9,S8={auto:"actpass",client:"active",server:"passive"},IV=Object.keys(S8).reduce((t,e)=>{let r=S8[e];return t[r]=e,t},{}),Q0e=["apt","max-fr","max-fs","maxplaybackrate","minptime","stereo","useinbandfec"],RG=["cname","msid","mslabel","label"],PV={SRTP_AES128_CM_HMAC_SHA1_80:R0,SRTP_AEAD_AES_128_GCM:hf},pA=["sendonly","sendrecv"],eme=["sendrecv","recvonly"],OG=class extends Map{constructor(t){if(super(),t)for(let e of t)this.set(e.id,e)}};NG=class{constructor(t,e,r,n,s){this.kind=t,this.receiver=r,this.sender=n,this._direction=s,e&&this.setDtlsTransport(e)}id=G0e().toString();onTrack=new Be;mid;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(t){this._codecs=t}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}setDirection(t){this._direction=t,pA.includes(this._currentDirection??"")&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection}setCurrentDirection(t){this._currentDirection=t}setDtlsTransport(t){this.receiver.setDtlsTransport(t),this.sender.setDtlsTransport(t)}get msid(){return`${this.sender.streamId} ${this.sender.trackId}`}addTrack(t){this.receiver.addTrack(t)&&this.onTrack.execute(t,this)}stop(){this.stopping||(this.stopping=!0)}getPayloadType(t){return this.codecs.find(e=>e.mimeType.toLowerCase().includes(t.toLowerCase()))?.payloadType}getCodecStats(){let t=Zu(),e=[];if(!this.dtlsTransport)return e;let r=vr("transport",this.dtlsTransport.id);for(let n of this.codecs){let s={type:"codec",id:vr("codec",n.payloadType,r),timestamp:t,payloadType:n.payloadType,transportId:r,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,sdpFmtpLine:n.parameters};e.push(s)}return e}},BG="inactive",v5="sendonly",w5="recvonly",S5="sendrecv",mA=[BG,v5,w5,S5],Wb=class extends h5{uuid=$G().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new Be;onReceiveRtcp=new Be;onSourceChanged=new Be;stopped=!1;muted=!0;constructor(t){super(),Object.assign(this,t),this.onReceiveRtp.subscribe(e=>{this.muted=!1,this.header=e.header}),this.label=`${this.remote?"remote":"local"} ${this.kind}`}stop=()=>{this.stopped=!0,this.muted=!0,this.onReceiveRtp.complete(),this.emit("ended")};writeRtp=t=>{if(this.remote)throw new Error("this is remoteTrack");if(this.stopped)return;let e=Buffer.isBuffer(t)?Pc.deSerialize(t):t;e.header.payloadType=this.codec?.payloadType??e.header.payloadType,this.onReceiveRtp.execute(e)}},MG=class{id;tracks=[];constructor(t){Array.isArray(t)?this.tracks=t:Object.assign(this,t),this.id??=$G().toString()}addTrack(t){t.streamId=this.id,this.tracks.push(t)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(t=>t.kind==="audio")}getVideoTracks(){return this.tracks.filter(t=>t.kind==="video")}},tme=wt("werift:packages/webrtc/src/utils.ts");rme={sha1:"sha1","sha-1":"sha1",sha224:"sha224","sha-224":"sha224",sha256:"sha256","sha-256":"sha256",sha384:"sha384","sha-384":"sha384",sha512:"sha512","sha-512":"sha512"};C5=(t,e)=>mA[mA.indexOf(t)&mA.indexOf(e)];k5=Date.now,sme=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,LG=()=>sme+process.hrtime.bigint()/1000n,Xb=()=>Date.now()/1e3,DG=()=>{let e=(SV.timeOrigin+SV.now()-Date.UTC(1900,0,1))/1e3,[r,n]=e.toString().split(".").map(Number);return Zr([4,4],[r,n]).readBigUInt64BE()},T5=t=>{let e=Zr([8],[t]),[,r,n]=ws(e,[2,2,2,2]);return Zr([2,2],[r,n]).readUInt32BE()};ime=zb.createSelfSignedCertificateWithKey,ome=class{static async rtpSource({port:t,kind:e,cb:r}){t??=await K8();let n=new Wb({kind:e}),s=Z0e("udp4");s.bind(t);let i=a=>{r&&(a=r(a)),n.writeRtp(a)};return s.addListener("message",i),[n,t,()=>{s.removeListener("message",i);try{s.close()}catch{}}]}},qG=(t,e)=>{if(!t||typeof t!="object")return e!==null&&typeof e=="object"?e:t;if(!e||typeof e!="object")return e??t;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];n!=null&&(t[r]=n)}return t},ame=wt("werift:packages/webrtc/src/media/receiver/nack.ts"),RV=150,cme=class{constructor(t){this.receiver=t}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new Be;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(t){return this._lost[t]}setLost(t,e){this._lost[t]=e,!(this.nackLoop||this.closed)&&(this.nackLoop=setInterval(async()=>{try{await this.sendNack(),Object.keys(this._lost).length||(clearInterval(this.nackLoop),this.nackLoop=void 0)}catch(r){ame("failed to send nack",r)}},5))}removeLost(t){delete this._lost[t]}addPacket(t){let{sequenceNumber:e,ssrc:r}=t.header;if(this.mediaSourceSsrc=r,this.newEstSeqNum===0){this.newEstSeqNum=e;return}if(this.getLost(e)){this.removeLost(e);return}if(e===Kn(this.newEstSeqNum,1))this.newEstSeqNum=e;else if(e>Kn(this.newEstSeqNum,1)){for(let n=Kn(this.newEstSeqNum,1);n<e;n=Kn(n,1))this.setLost(n,1);this.newEstSeqNum=e,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>RV&&(this._lost=Object.entries(this._lost).slice(-RV).reduce((t,[e,r])=>(t[e]=r,t),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(t=>{if(this._lost[t]++>this.retryCount)return this.removeLost(t),t})}sendNack=()=>new Promise((t,e)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let r=new Fb({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),n=new cf({feedback:r});this.receiver.dtlsTransport.sendRtcp([n]).then(t).catch(e),this.updateRetryCount(),this.onPacketLost.execute(r)}})},lme=wt("werift:packages/webrtc/media/receiver/receiverTwcc"),dme=class{constructor(t,e,r){this.dtlsTransport=t,this.rtcpSsrc=e,this.mediaSourceSsrc=r,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(t){this.extensionInfo[t]={tsn:t,timestamp:LG()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await ume(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let t=Object.values(this.extensionInfo).sort((l,d)=>l.tsn-d.tsn),e=t[0].tsn,r=t.slice(-1)[0].tsn,n=[],s=t[0].tsn,i=Kn(r-e,1),o,a,c=[];for(let l=e;l<=r;l++){let d=this.extensionInfo[l]?.timestamp;if(d){this.lastTimestamp||(this.lastTimestamp=d),o||(o=this.lastTimestamp);let f=d-this.lastTimestamp;this.lastTimestamp=d;let p=new Rb({delta:Number(f)});p.parseDelta(),c.push(p),a!=null&&a.status!==p.type&&(n.push(new w0({packetStatus:a.status,runLength:l-a.minTSN})),a={minTSN:l,status:p.type}),l===r&&(a!=null?n.push(new w0({packetStatus:a.status,runLength:l-a.minTSN+1})):n.push(new w0({packetStatus:p.type,runLength:1}))),a==null&&(a={minTSN:l,status:p.type})}}if(!o)return;let u=new cf({feedback:new Vb({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:s,packetStatusCount:i,referenceTime:iK(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:n})});this.dtlsTransport.sendRtcp([u]).catch(l=>{lme(l)}),this.extensionInfo={},this.fbPktCount=sK(this.fbPktCount,1)}},fme=class{base_seq;max_seq;cycles=0;packets_received=0;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(t){this.clockRate=t}add(t,e=Date.now()/1e3){let r=this.max_seq==null||DA(t.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.base_seq==null&&(this.base_seq=t.header.sequenceNumber),r){let n=_0(e*this.clockRate);if(this.max_seq!=null&&t.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=t.header.sequenceNumber,t.header.timestamp!==this.last_timestamp&&this.packets_received>1){let s=Math.abs(n-(this.last_arrival??0)-(t.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=s-(this.jitter_q4+8>>4)}this.last_arrival=n,this.last_timestamp=t.header.timestamp}}get fraction_lost(){let t=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let e=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let r=t-e;return t==0||r<=0?0:Math.floor((r<<8)/t)}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){let t=this.packets_expected-this.packets_received;return t<0?0:t}},xo=wt("werift:packages/webrtc/src/transport/dtls.ts"),A8=class HG{constructor(e,r,n,s=[]){this.config=e,this.iceTransport=r,this.localCertificate=n,this.srtpProfiles=s,this.localCertificate??=HG.localCertificate}id=mme().toString();state="new";role="auto";srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new Be;onRtcp=new Be;onRtp=new Be;static localCertificate;static localCertificatePromise;remoteParameters;get localParameters(){return new $A(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){return this.localCertificate?this.localCertificate:this.localCertificatePromise?this.localCertificatePromise:(this.localCertificatePromise=(async()=>{let{certPem:e,keyPem:r,signatureHash:n}=await zb.createSelfSignedCertificateWithKey({signature:va.ecdsa_3,hash:jb.sha256_4},Tc.secp256r1_23);return this.localCertificate=new I5(r,e,n),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let r=xme([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),n=e.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new $A(r,n)}async start(){if(this.state!=="new")throw new Error("state must be new");if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");this.role==="auto"&&(this.iceTransport.role==="controlling"?this.role="server":this.role="client"),this.setState("connecting"),await new Promise(async(e,r)=>{this.role==="server"?this.dtls=new FZ({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:OV(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):this.dtls=new d8({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:OV(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0}),this.dtls.onData.subscribe(n=>{this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random()||this.dataReceiver(n)}),this.dtls.onClose.subscribe(()=>{this.state!=="failed"&&this.setState("closed")}),this.dtls.onConnect.once(e),this.dtls.onError.once(n=>{this.setState("failed"),xo("dtls failed",n),r(n)}),this.dtls instanceof d8&&(await gme(100),this.dtls.connect().catch(n=>{this.setState("failed"),xo("dtls connect failed",n),r(n)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState("failed"),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState("connected"),xo("dtls connected")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");let e=this.dtls?.remoteCertificate;if(!e)throw new Error("remote certificate not available");let r=this.remoteParameters.fingerprints.flatMap(({algorithm:a,value:c})=>{let u=E5(a);if(!u)return[];let l=NA(c);if(!l)throw new Error("remote fingerprint value is empty");return[{normalizedAlgorithm:u,normalizedValue:l}]});if(r.length===0)throw new Error("no supported remote fingerprint algorithms");let n=_me(r),s=r.filter(({normalizedAlgorithm:a})=>a===n),i=s.reduce((a,{normalizedAlgorithm:c})=>(a.has(c)||a.set(c,NA(A5(e,c))),a),new Map);if(!s.some(({normalizedAlgorithm:a,normalizedValue:c})=>i.get(a)===c))throw new Error("remote certificate fingerprint mismatch")}updateSrtpSession(){if(!this.dtls)throw new Error;let e=this.dtls.srtp.srtpProfile;if(!e)throw new Error("need srtpProfile");xo("selected SRTP Profile",e);let{localKey:r,localSalt:n,remoteKey:s,remoteSalt:i}=this.dtls.extractSessionKeys(DK(e),UK(e)),o={keys:{localMasterKey:r,localMasterSalt:n,remoteMasterKey:s,remoteMasterSalt:i},profile:e};this.srtp=new qZ(o),this.srtcp=new UZ(o)}startSrtp(){this.srtpStarted||(this.srtpStarted=!0,this.updateSrtpSession(),this.iceTransport.connection.onData.subscribe(e=>{if(!(this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random())&&rZ(e))if(this.bytesReceived+=e.length,this.packetsReceived++,gZ(e)){let r;try{r=this.srtcp.decrypt(e)}catch(s){if(s instanceof lf){xo("dropping invalid SRTCP packet",s);return}throw s}let n;try{n=mZ.deSerialize(r)}catch(s){xo("dropping malformed SRTCP packet",s);return}for(let s of n)try{this.onRtcp.execute(s)}catch(i){xo("RTCP error",i)}}else{let r;try{r=this.srtp.decrypt(e)}catch(s){if(s instanceof lf){xo("dropping invalid SRTP packet",s);return}throw s}let n;try{n=Pc.deSerialize(r)}catch(s){xo("dropping malformed SRTP packet",s);return}try{this.onRtp.execute(n)}catch(s){xo("RTP error",s)}}}))}sendData=async e=>{if(!(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())){if(!this.dtls)throw new Error("dtls not established");await this.dtls.send(e)}};async sendRtp(e,r){try{let n=this.srtp.encrypt(e,r);return this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random()||(this.bytesSent+=n.length,this.packetsSent++,await this.iceTransport.connection.send(n).catch(()=>{})),n.length}catch(n){return xo("failed to send",n),0}}async sendRtcp(e){let r=Buffer.concat(e.map(s=>s.serialize())),n=this.srtcp.encrypt(r);if(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())return n.length;this.bytesSent+=n.length,this.packetsSent++,await this.iceTransport.connection.send(n).catch(()=>{})}setState(e){e!=this.state&&(this.state=e,this.onStateChange.execute(e))}async stop(){this.setState("closed"),await this.iceTransport.stop()}async getStats(){let e=Zu(),r=[],s={type:"transport",id:vr("transport",this.id),timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,selectedCandidatePairId:this.iceTransport.connection.nominated?vr("candidate-pair",this.iceTransport.connection.nominated.localCandidate.foundation,this.iceTransport.connection.nominated.remoteCandidate.foundation):void 0,localCertificateId:this.localCertificate?vr("certificate","local"):void 0,remoteCertificateId:this.remoteParameters?vr("certificate","remote"):void 0,dtlsRole:this.role==="auto"?void 0:this.role};if(r.push(s),this.localCertificate){let o=this.localCertificate.getFingerprints();if(o.length>0){let a={type:"certificate",id:vr("certificate","local"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString("base64")};r.push(a)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0){let o={type:"certificate",id:vr("certificate","remote"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:""};r.push(o)}let i=await this.iceTransport.getStats();return r.push(...i),r}},yme=["new","connecting","connected","closed","failed"],I5=class{constructor(t,e,r){this.certPem=e,this.signatureHash=r;let n=Jb.Certificate.fromPEM(Buffer.from(e));this.publicKey=n.publicKey.toPEM(),this.privateKey=Jb.PrivateKey.fromPEM(Buffer.from(t)).toPEM()}publicKey;privateKey;getFingerprints(){return[new BA("sha-256",A5(Jb.Certificate.fromPEM(Buffer.from(this.certPem)).raw,"sha256"))]}},BA=class{constructor(t,e){this.algorithm=t,this.value=e}},$A=class{constructor(t=[],e){this.fingerprints=t,this.role=e}},xme=t=>{let e=new Set;return t.filter(({algorithm:r,value:n})=>{let s=`${E5(r)??r.trim().toLowerCase()}:${NA(n)}`;return e.has(s)?!1:(e.add(s),!0)})},bme=["sha512","sha384","sha256","sha224","sha1"],_me=t=>bme.find(e=>t.some(({normalizedAlgorithm:r})=>r===e))??t[0].normalizedAlgorithm,vme=class{constructor(t){this.ice=t,t.onData.subscribe(e=>{jG(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type="ice";send=t=>this.ice.send(t);async close(){this.closed=!0,this.ice.close()}},OV=t=>new vme(t),NV=wt("werift:packages/webrtc/src/transport/ice.ts"),FG=class{constructor(t){this.iceGather=t,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)}}id=wme().toString();connection;state="new";waitStart;renominating=!1;onStateChange=new Be;onIceCandidate=new Be;onNegotiationNeeded=new Be;get role(){return this.connection.iceControlling?"controlling":"controlled"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}setState(t){t!==this.state&&(this.state=t,this.onStateChange.execute(t))}gather(){return this.iceGather.gather()}addRemoteCandidate=t=>{if(!this.connection.remoteCandidatesEnd)return t?this.connection.addRemoteCandidate(KG(t)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(t,e=!1){e&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==t.usernameFragment||this.connection.remotePassword!==t.password)&&(this.renominating?(NV("renomination",t),this.connection.resetNominatedPair(),this.renominating=!1):(NV("restart",t),this.restart())),this.connection.setRemoteParams(t)}restart(){this.connection.restart(),this.setState("new"),this.iceGather.gatheringState="new",this.waitStart=void 0,this.onNegotiationNeeded.execute()}async start(){if(this.state==="closed")throw new Error("RTCIceTransport is closed");if(!this.connection.remotePassword||!this.connection.remoteUsername)throw new Error("remoteParams missing");this.waitStart&&await this.waitStart.asPromise(),this.waitStart=new Be,this.setState("checking");try{await this.connection.connect()}catch(t){throw this.setState("failed"),t}this.waitStart.execute(),this.waitStart.complete(),this.waitStart=void 0}async stop(){this.state!=="closed"&&(this.setState("closed"),await this.connection.close()),this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(){let t=Zu(),e=[];for(let n of this.localCandidates){let s={type:"local-candidate",id:vr("local-candidate",n.foundation),timestamp:t,transportId:vr("transport",this.id),address:n.ip,port:n.port,protocol:n.protocol,candidateType:n.type,priority:n.priority,foundation:n.foundation};e.push(s)}for(let n of this.connection.remoteCandidates){let s=T0(n),i={type:"remote-candidate",id:vr("remote-candidate",s.foundation),timestamp:t,transportId:vr("transport",this.id),address:s.ip,port:s.port,protocol:s.protocol,candidateType:s.type,priority:s.priority,foundation:s.foundation};e.push(i)}let r=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(n=>n.nominated),...this.connection.candidatePairs.filter(n=>!n.nominated)]:[];for(let n of r){let s={type:"candidate-pair",id:vr("candidate-pair",n.foundation),timestamp:t,transportId:vr("transport",this.id),localCandidateId:vr("local-candidate",n.localCandidate.foundation),remoteCandidateId:vr("remote-candidate",n.remoteCandidate.foundation),state:n.state,nominated:n.nominated,packetsSent:n.packetsSent,packetsReceived:n.packetsReceived,bytesSent:n.bytesSent,bytesReceived:n.bytesReceived,currentRoundTripTime:n.rtt};e.push(s)}return e}},Sme=["new","checking","connected","completed","disconnected","failed","closed"],Ame=["new","gathering","complete"],VG=class{constructor(t={}){this.options=t,this.connection=new wG(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(T0(e))})}onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new Be;async gather(){this.gatheringState==="new"&&(this.setState("gathering"),await this.connection.gatherCandidates(),this.onIceCandidate(void 0),this.setState("complete"))}get localCandidates(){return this.connection.localCandidates.map(T0)}get localParameters(){return new R5({usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(t){t!==this.gatheringState&&(this.gatheringState=t,this.onGatheringStateChange.execute(t))}};ZG=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(t){Object.assign(this,t)}static fromSdp(t){let e=Vu.fromSdp(t);return T0(e).toJSON()}static isThis(t){if(typeof t?.candidate=="string")return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},P5=class{constructor(t,e,r,n,s,i,o,a,c){this.component=t,this.foundation=e,this.ip=r,this.port=n,this.priority=s,this.protocol=i,this.type=o,this.generation=a,this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new ZG({candidate:B5(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(t){try{if(!t.candidate)throw new Error("candidate is required");let e=$5(t.candidate);return e.sdpMLineIndex=t.sdpMLineIndex??void 0,e.sdpMid=t.sdpMid??void 0,e}catch{}}},R5=class{iceLite=!1;usernameFragment;password;constructor(t={}){Object.assign(this,t)}},Sa=class GG{constructor(e=0,r=Buffer.from("")){this.flags=e,this._body=r}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return GG.type}get bytes(){if(!this.body)throw new Error;let e=Buffer.alloc(4);return e.writeUInt8(this.type,0),e.writeUInt8(this.flags,1),e.writeUInt16BE(this.body.length+4,2),Buffer.concat([e,this.body,...[...Array(u1(this.body.length))].map(()=>Buffer.from("\0"))])}},O5=class extends Sa{constructor(t=0,e){super(t,e),this.flags=t,e?(this.initiateTag=e.readUInt32BE(0),this.advertisedRwnd=e.readUInt32BE(4),this.outboundStreams=e.readUInt16BE(8),this.inboundStreams=e.readUInt16BE(10),this.initialTsn=e.readUInt32BE(12),this.params=mW(e.slice(16))):(this.initiateTag=0,this.advertisedRwnd=0,this.outboundStreams=0,this.inboundStreams=0,this.initialTsn=0,this.params=[])}initiateTag;advertisedRwnd;outboundStreams;inboundStreams;initialTsn;params;get body(){let t=Buffer.alloc(16);return t.writeUInt32BE(this.initiateTag,0),t.writeUInt32BE(this.advertisedRwnd,4),t.writeUInt16BE(this.outboundStreams,8),t.writeUInt16BE(this.inboundStreams,10),t.writeUInt32BE(this.initialTsn,12),Buffer.concat([t,pW(this.params)])}},xA=class WG extends O5{static type=1;get type(){return WG.type}},E8=class XG extends O5{static type=2;get type(){return XG.type}},kme=class JG extends O5{static type=130;get type(){return JG.type}},bA=class YG extends Sa{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0);let n=4;for(;n<r.length;)this.streams.push([r.readUInt16BE(n),r.readUInt16BE(n+2)]),n+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return YG.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([r,n])=>{let s=Buffer.alloc(4);return s.writeUInt16BE(r,0),s.writeUInt16BE(n,2),s})])}},_A=class QG extends Sa{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.tsn=r.readUInt32BE(0),this.streamId=r.readUInt16BE(4),this.streamSeqNum=r.readUInt16BE(6),this.protocol=r.readUInt32BE(8),this.userData=r.slice(12))}static type=0;get type(){return QG.type}tsn=0;streamId=0;streamSeqNum=0;protocol=0;userData=Buffer.from("");abandoned=!1;acked=!1;misses=0;retransmit=!1;sentCount=0;bookSize=0;expiry;maxRetransmits;sentTime;get bytes(){let e=16+this.userData.length,r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.tsn,4),r.writeUInt16BE(this.streamId,8),r.writeUInt16BE(this.streamSeqNum,10),r.writeUInt32BE(this.protocol,12);let n=Buffer.concat([r,this.userData]);return e%4&&(n=Buffer.concat([n,...[...Array(u1(e))].map(()=>Buffer.from("\0"))])),n}},C8=class eW extends Sa{static type=10;get type(){return eW.type}},k8=class tW extends Sa{static type=11;get type(){return tW.type}},c1=class extends Sa{constructor(t=0,e=void 0){super(t,e),this.flags=t,e&&(this.params=mW(e))}params=[];get body(){return pW(this.params)}},T8=class rW extends c1{static type=6;get type(){return rW.type}},vA=class I8 extends c1{static type=9;static CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13};get type(){return I8.type}get descriptions(){return this.params.map(([e,r])=>({name:(Object.entries(I8.CODE).find(([,s])=>s===e)||[])[0],body:r}))}},P8=class nW extends c1{static type=4;get type(){return nW.type}},sW=class iW extends c1{static type=5;get type(){return iW.type}},R8=class oW extends c1{static type=130;get type(){return oW.type}},O8=class aW extends Sa{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0),this.advertisedRwnd=r.readUInt32BE(4);let n=r.readUInt16BE(8),s=r.readUInt16BE(10),i=12;[...Array(n)].forEach(()=>{this.gaps.push([r.readUInt16BE(i),r.readUInt16BE(i+2)]),i+=4}),[...Array(s)].forEach(()=>{this.duplicates.push(r.readUInt32BE(i)),i+=4})}}static type=3;get type(){return aW.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.cumulativeTsn,4),r.writeUInt32BE(this.advertisedRwnd,8),r.writeUInt16BE(this.gaps.length,12),r.writeUInt16BE(this.duplicates.length,14);let n=Buffer.concat([r,...this.gaps.map(s=>{let i=Buffer.alloc(4);return i.writeUInt16BE(s[0],0),i.writeUInt16BE(s[1],2),i})]);return n=Buffer.concat([n,...this.duplicates.map(s=>{let i=Buffer.alloc(4);return i.writeUInt32BE(s,0),i})]),n}},cW=class uW extends Sa{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.cumulativeTsn=r.readUInt32BE(0))}static type=7;get type(){return uW.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},lW=class dW extends Sa{static type=8;get type(){return dW.type}},fW=class hW extends Sa{static type=14;get type(){return hW.type}},Tme=[_A,xA,E8,O8,P8,sW,T8,cW,lW,vA,C8,k8,fW,R8,bA],Ime=Tme.reduce((t,e)=>(t[e.type]=e,t),{});N8=class B8{constructor(e,r,n,s){this.requestSequence=e,this.responseSequence=r,this.lastTsn=n,this.streams=s}static type=13;get type(){return B8.type}get bytes(){let e=Buffer.from(Cc.jspack.Pack("!LLL",[this.requestSequence,this.responseSequence,this.lastTsn]));return Buffer.concat([e,...this.streams.map(r=>Buffer.from(Cc.jspack.Pack("!H",[r])))])}static parse(e){let[r,n,s]=Cc.jspack.Unpack("!LLL",e),i=[];for(let o=12;o<e.length;o+=2)i.push(Cc.jspack.Unpack("!H",e.slice(o))[0]);return new B8(r,n,s,i)}},gW=class $8{constructor(e,r){this.requestSequence=e,this.newStreams=r}static type=17;get type(){return $8.type}get bytes(){return Buffer.from(Cc.jspack.Pack("!LHH",[this.requestSequence,this.newStreams,0]))}static parse(e){let[r,n]=Cc.jspack.Unpack("!LHH",e);return new $8(r,n)}},iA={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},wA=class M8{constructor(e,r){this.responseSequence=e,this.result=r}static type=16;get type(){return M8.type}get bytes(){return Buffer.from(Cc.jspack.Pack("!LL",[this.responseSequence,this.result]))}static parse(e){let[r,n]=Cc.jspack.Unpack("!LL",e);return new M8(r,n)}},$V={13:N8,16:wA,17:gW},ur=wt("werift/sctp/sctp"),Bme=24,$me=60,MV=65535,bo=1200,Ib=1,yW=2,j8=4,jV=10,Mme=8,zV=1/8,LV=1/4,DV=3,jme=1,zme=60,MA=2**32,Lme=200,Dme=30,UV=135,qV=7,HV=32776,FV=49152,Ume=["new","closed","connected","connecting"],qme=class z8{constructor(e,r=5e3){this.transport=e,this.port=r,this.localPort=this.port,this.transport.onData=n=>{this.handleData(n)}}flush=new Be;stateChanged=Nme(Ume);onReconfigStreams=new Be;onReceive=new Be;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=Cme(16);localPartialReliability=!0;localPort;localVerificationTag=AA();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1024*1024;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=MV;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*bo;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=MV;localTsn=Number(AA());lastSackedTsn=Qd(this.localTsn);advancedPeerAckTsn=Qd(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=DV;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=Dme;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(e,r=5e3){let n=new z8(e,r);return n.isServer=!1,n}static server(e,r=5e3){let n=new z8(e,r);return n.isServer=!0,n}async handleData(e){if(this.isStopped)return;let r,[,,n,s]=Pme(e);if(s.filter(o=>o.type===xA.type).length>0){if(s.length!=1)throw new Error;r=0}else r=this.localVerificationTag;if(n===r){this.sackHasNewDataInPacket=!1;for(let o of s)await this.receiveChunk(o);this.sackNeeded&&(this.sackHasNewDataInPacket&&this.sackPacketCount++,this.sackPacketCount>=2&&(this.sackImmediate=!0),await this.scheduleSack())}}async scheduleSack(){if(!this.isStopped&&this.sackNeeded){if(this.sackImmediate){this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),await this.sendSack();return}this.sackTimeout||(this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch(e=>{ur("send delayed sack failed",e.message)})},Lme))}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],r;[...this.sackMisOrdered].sort().forEach(s=>{let i=(s-this.lastReceivedTsn)%MA;s===r?e[e.length-1][1]=i:e.push([i,i]),r=y0(s)});let n=new O8(0,void 0);n.cumulativeTsn=this.lastReceivedTsn,n.advertisedRwnd=Math.max(0,this.advertisedRwnd),n.duplicates=[...this.sackDuplicates],n.gaps=e,await this.sendChunk(n).catch(s=>{ur("send sack failed",s.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case _A.type:this.receiveDataChunk(e);break;case xA.type:{if(!this.isServer)return;let r=e;ur("receive init",r),this.lastReceivedTsn=Qd(r.initialTsn),this.reconfigResponseSeq=Qd(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let n=new E8;n.initiateTag=this.localVerificationTag,n.advertisedRwnd=this.advertisedRwnd,n.outboundStreams=this._outboundStreamsCount,n.inboundStreams=this._inboundStreamsCount,n.initialTsn=this.localTsn,this.setExtensions(n.params);let s=Date.now()/1e3,i=Buffer.from(yA.jspack.Pack("!L",[s]));i=Buffer.concat([i,BV("sha1",this.hmacKey).update(i).digest()]),n.params.push([qV,i]),ur("send initAck",n),await this.sendChunk(n).catch(o=>{ur("send initAck failed",o.message)})}break;case E8.type:{if(this.associationState!=2)return;let r=e;this.timer1Cancel(),this.lastReceivedTsn=Qd(r.initialTsn),this.reconfigResponseSeq=Qd(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let n=new C8;for(let[s,i]of r.params)if(s===qV){n.body=i;break}await this.sendChunk(n).catch(s=>{ur("send echo failed",s.message)}),this.timer1Start(n),this.setState(3)}break;case O8.type:await this.receiveSackChunk(e);break;case P8.type:{let r=new sW;r.params=e.params,await this.sendChunk(r).catch(n=>{ur("send heartbeat ack failed",n.message)})}break;case T8.type:this.setState(1);break;case cW.type:{this.timer2Cancel(),this.setState(7);let r=new lW;await this.sendChunk(r).catch(n=>{ur("send shutdown ack failed",n.message)}),this.t2Start(r),this.setState(6)}break;case vA.type:ur("ErrorChunk",e.descriptions);break;case C8.type:{if(!this.isServer)return;let n=e.body,s=BV("sha1",this.hmacKey).update(n.slice(0,4)).digest();if(n?.length!=Bme||!n.slice(4).equals(s)){ur("x State cookie is invalid");return}let i=Date.now()/1e3,o=yA.jspack.Unpack("!L",n)[0];if(o<i-$me||o>i){let c=new vA(0,void 0);c.params.push([vA.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from("\0")))]),await this.sendChunk(c).catch(u=>{ur("send errorChunk failed",u.message)});return}let a=new k8;await this.sendChunk(a).catch(c=>{ur("send cookieAck failed",c.message)}),this.setState(4)}break;case k8.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case fW.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case R8.type:{if(this.associationState!=4)return;let r=e;for(let[n,s]of r.params){let i=$V[n];i&&await this.receiveReconfigParam(i.parse(s))}}break;case bA.type:this.receiveForwardTsnChunk(e);break}}getExtensions(e){for(let[r,n]of e)r===FV?this.remotePartialReliability=!0:r===HV&&(this.remoteExtensions=[...n])}async receiveReconfigParam(e){switch(ur("receiveReconfigParam",$V[e.type]),e.type){case N8.type:{let r=e,n=new wA(r.requestSequence,iA.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(n),await Promise.all(r.streams.map(async s=>{delete this.inboundStreams[s],this.outboundStreamSeq[s]&&(this.reconfigQueue.includes(s)||this.reconfigQueue.push(s))})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(r.streams)}break;case wA.type:{let r=e;if(r.result!==iA.ReconfigResultSuccessPerformed)ur("OutgoingSSNResetRequestParam failed",Object.keys(iA).find(n=>iA[n]===r.result));else if(r.responseSequence===this.reconfigRequest?.requestSequence){let n=this.reconfigRequest.streams.map(s=>(delete this.outboundStreamSeq[s],s));this.onReconfigStreams.execute(n),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=DV,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case gW.type:{let r=e;this._inboundStreamsCount+=r.newStreams;let n=new wA(r.requestSequence,1);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(n)}break}}receiveDataChunk(e){if(this.sackNeeded=!0,this.markReceived(e.tsn)){this.sackImmediate=!0;return}this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(e.flags&Ib)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let r=this.getInboundStream(e.streamId);r.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let n of r.popMessages())this.advertisedRwnd+=n[2].length,this.receive(...n)}async receiveSackChunk(e){if(xa(this.lastSackedTsn,e.cumulativeTsn))return;let r=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let n=this.flightSize>=this.cwnd,s=0,i=0;for(;this.sentQueue.length>0&&x0(this.lastSackedTsn,this.sentQueue[0].tsn);){let a=this.sentQueue.shift();s++,a?.acked||(i+=a.bookSize,this.flightSizeDecrease(a)),s===1&&a.sentCount===1&&this.updateRto(r-a.sentTime)}this.sentQueue.length||(this.sentQueue=[]);let o=!1;if(e.gaps.length>0){let a=new Set,c;e.gaps.forEach(l=>{for(let d=l[0];d<l[1]+1;d++)c=(e.cumulativeTsn+d)%MA,a.add(c)});let u=e.cumulativeTsn;for(let l of this.sentQueue){if(xa(l.tsn,c))break;a.has(l.tsn)&&!l.acked&&(i+=l.bookSize,l.acked=!0,this.flightSizeDecrease(l),u=l.tsn)}for(let l of this.sentQueue){if(xa(l.tsn,u))break;a.has(l.tsn)||(l.misses++,l.misses===3&&(l.misses=0,this.maybeAbandon(l)||(l.retransmit=!0),l.acked=!1,this.flightSizeDecrease(l),o=!0))}}this.fastRecoveryExit===void 0?(s&&n&&(this.cwnd<=this.ssthresh?this.cwnd+=Math.min(i,bo):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=bo))),o&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*bo),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):x0(e.cumulativeTsn,this.fastRecoveryExit)&&(this.fastRecoveryExit=void 0),this.sentQueue.length===0?this.timer3Cancel():s>0&&this.timer3Restart(),this.peerAdvertisedRwnd=e.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(e){if(this.sackNeeded=!0,this.sackImmediate=!0,x0(this.lastReceivedTsn,e.cumulativeTsn))return;let r=n=>xa(n,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let n of[...this.sackMisOrdered].sort())if(n===y0(this.lastReceivedTsn))this.lastReceivedTsn=n;else break;this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let[n,s]of e.streams){let i=this.getInboundStream(n);i.streamSequenceNumber=Kn(s,1);for(let o of i.popMessages())this.advertisedRwnd+=o[2].length,this.receive(...o)}Object.values(this.inboundStreams).forEach(n=>{this.advertisedRwnd+=n.pruneChunks(this.lastReceivedTsn)})}updateRto(e){this.srtt?(this.rttvar=(1-LV)*this.rttvar+LV*Math.abs(this.srtt-e),this.srtt=(1-zV)*this.srtt+zV*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(jme,Math.min(this.srtt+4*this.rttvar,zme))}receive(e,r,n){this.onReceive.execute(e,r,n)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new Hme),this.inboundStreams[e]}markReceived(e){if(x0(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e))return this.sackDuplicates.push(e),!0;this.sackMisOrdered.add(e);for(let n of[...this.sackMisOrdered].sort())if(n===y0(this.lastReceivedTsn))this.lastReceivedTsn=n;else break;let r=n=>xa(n,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r)),!1}send=async(e,r,n,{expiry:s,maxRetransmits:i,ordered:o}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let a=o&&this.outboundStreamSeq[e]||0,c=Math.ceil(n.length/bo),u=0,l=[];for(let d=0;d<c;d++){let f=new _A(0,void 0);f.flags=0,o||(f.flags=j8),d===0&&(f.flags|=yW),d===c-1&&(f.flags|=Ib),f.tsn=this.localTsn,f.streamId=e,f.streamSeqNum=a,f.protocol=r,f.userData=n.slice(u,u+bo),f.bookSize=f.userData.length,f.expiry=s,f.maxRetransmits=i,u+=bo,this.localTsn=y0(this.localTsn),l.push(f)}for(l.forEach(d=>{this.outboundQueue.push(d)}),o&&(this.outboundStreamSeq[e]=Kn(a,1)),await this.transmit();this.outboundQueue.length;)await this.flush.asPromise()};async transmit(){if(!this.isStopped){if(this.transmitting){this.transmitRequested=!0;return}this.transmitting=!0;try{do this.transmitRequested=!1,await this.transmitOnce();while(this.transmitRequested)}finally{this.transmitting=!1}}}async transmitOnce(){if(this.isStopped)return;this.forwardTsnChunk&&(await this.sendChunk(this.forwardTsnChunk).catch(s=>{ur("send forwardTsn failed",s.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit!=null?2*bo:4*bo,r=Math.min(this.flightSize+e,this.cwnd),n=!0;for(let s of this.sentQueue){if(s.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=r)break;this.flightSizeIncrease(s),s.misses=0,s.retransmit=!1,s.sentCount++,await this.sendChunk(s).catch(i=>{ur("send data failed",i.message)}),n&&this.timer3Restart()}n=!1}for(;this.outboundQueue.length>0&&this.flightSize<r&&this.peerRwnd>0;){let s=this.outboundQueue.shift();if(!s)break;if(s.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(s);break}this.sentQueue.push(s),this.flightSizeIncrease(s),s.sentCount++,s.sentTime=Date.now()/1e3,await this.sendChunk(s).catch(i=>{ur("send data outboundQueue failed",i.message)}),this.timer3Handle||this.timer3Start()}this.outboundQueue.length||(this.outboundQueue=[]),this.flush.execute()}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===4&&!this.reconfigRequest){let e=[...new Set(this.reconfigQueue)],r=e.slice(0,UV);this.reconfigQueue=e.slice(UV);let n=new N8(this.reconfigRequestSeq,this.reconfigResponseSeq,Qd(this.localTsn),r);this.reconfigRequestSeq=y0(this.reconfigRequestSeq),this.reconfigRequest=n,await this.sendReconfigParam(n),this.timerReconfigHandleStart()}}async sendReconfigParam(e){ur("sendReconfigParam",e);let r=new R8;r.params.push([e.type,e.bytes]),await this.sendChunk(r).catch(n=>{ur("send reconfig failed",n.message)})}async sendResetRequest(e){ur("sendResetRequest",e);let r=new _A(0,void 0);r.streamId=e,this.outboundQueue.push(r),this.timer3Handle||await this.transmit()}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e,this.timer1Failures=0,this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Expired=()=>{if(!this.isStopped)if(this.timer1Failures++,this.timer1Handle=void 0,this.timer1Failures>Mme)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{ur("send timer1 chunk failed",e.message)})}),this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};timer1Cancel(){this.timer1Handle&&(clearTimeout(this.timer1Handle),this.timer1Handle=void 0,this.timer1Chunk=void 0)}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e,this.timer2Failures=0,this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Expired=()=>{if(!this.isStopped)if(this.timer2Failures++,this.timer2Handle=void 0,this.timer2Failures>jV)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{ur("send timer2Chunk failed",e.message)})}),this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};timer2Cancel(){this.timer2Handle&&(clearTimeout(this.timer2Handle),this.timer2Handle=void 0,this.timer2Chunk=void 0)}timer3Start(){if(!this.isStopped){if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}}timer3Restart(){this.isStopped||(this.timer3Cancel(),this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3))}timer3Expired=()=>{this.isStopped||(this.timer3Handle=void 0,this.sentQueue.forEach(e=>{this.maybeAbandon(e)||(e.retransmit=!0)}),this.updateAdvancedPeerAckPoint(),this.fastRecoveryExit=void 0,this.flightSize=0,this.partialBytesAcked=0,this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*bo),this.cwnd=bo,this.transmit())};timer3Cancel(){this.timer3Handle&&(clearTimeout(this.timer3Handle),this.timer3Handle=void 0)}timerReconfigHandleStart(){this.isStopped||this.timerReconfigHandle||(ur("timerReconfigHandleStart",{rto:this.rto}),this.timerReconfigFailures=0,this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3))}timerReconfigHandleExpired=async()=>{if(!this.isStopped){if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>jV)ur("timerReconfigFailures",this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(ur("timerReconfigHandleExpired",this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(ur("timerReconfigCancel"),clearTimeout(this.timerReconfigHandle),this.timerReconfigHandle=void 0,this.timerReconfigFailures=0)}heartbeatStart(){this.timerHeartbeatHandle||this.associationState!==4||(this.timerHeartbeatHandle=setTimeout(this.timerHeartbeatExpired,(this.rto+this.heartbeatInterval)*1e3))}heartbeatRestart(){this.heartbeatCancel(),this.heartbeatStart()}heartbeatCancel(){this.timerHeartbeatHandle&&(clearTimeout(this.timerHeartbeatHandle),this.timerHeartbeatHandle=void 0)}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState===4){if(this.flightSize===0&&this.outboundQueue.length===0){let e=new P8;e.params.push([1,Buffer.from(yA.jspack.Pack("!L",[Math.floor(Date.now()/1e3)]))]),await this.sendChunk(e).catch(r=>{ur("send heartbeat failed",r.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw new Error("heartbeat interval must be > 0");this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){xa(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,r={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let n=this.sentQueue.shift();this.advancedPeerAckTsn=n.tsn,e++,n.flags&j8||(r[n.streamId]=n.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new bA(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(r).map(([n,s])=>[Number(n),s]))}maybeAbandon(e){if(e.abandoned)return!0;if(!(!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3))return!1;let n=this.sentQueue.findIndex(s=>s.type===e.type);for(let s=n;s>=0;s--){let i=this.sentQueue[s];if(i.abandoned=!0,i.retransmit=!1,i.flags&Ib)break}for(let s=n;s<this.sentQueue.length;s++){let i=this.sentQueue[s];if(i.abandoned=!0,i.retransmit=!1,i.flags&Ib)break}return!0}static getCapabilities(){return new Fme(65536)}setRemotePort(e){this.remotePort=e}async start(e){this.started||(this.started=!0,this.setConnectionState("connecting"),e&&this.setRemotePort(e),this.isServer||await this.init())}async init(){let e=new xA;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),ur("send init",e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(r){ur("send init failed",r.message)}}setExtensions(e){let r=[];this.localPartialReliability&&(e.push([FV,Buffer.from("")]),r.push(bA.type)),r.push(kme.type),e.push([HV,Buffer.from(r)])}async sendChunk(e){if(this.state==="closed")return;if(this.remotePort===void 0)throw new Error("invalid remote port");let r=Rme(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(r)}setState(e){e!=this.associationState&&(this.associationState=e),e===4?(this.isStopping=!1,this.isClosed=!1,this.setConnectionState("connected"),this.heartbeatStart()):e===1&&(this.isClosed=!0,this.timer1Cancel(),this.timer2Cancel(),this.timer3Cancel(),this.timerReconfigCancel(),this.heartbeatCancel(),this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.setConnectionState("closed"),this.removeAllListeners())}setConnectionState(e){this.state=e,ur("setConnectionState",e),this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(1);return}this.isStopping=!0,this.transport.onData=void 0,this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.associationState!==1&&await this.abort(),this.setState(1),clearTimeout(this.timer1Handle),clearTimeout(this.timer2Handle),clearTimeout(this.timer3Handle),clearTimeout(this.timerReconfigHandle),clearTimeout(this.timerHeartbeatHandle),clearTimeout(this.sackTimeout)}async abort(){let e=new T8;await this.sendChunk(e).catch(r=>{ur("send abort failed",r.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},Hme=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(t){if(this.reassembly.length===0||xa(t.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(t);return}for(let[e,r]of Ome(this.reassembly)){if(r.tsn===t.tsn)throw new Error("duplicate chunk in reassembly");if(xa(r.tsn,t.tsn)){this.reassembly.splice(e,0,t);break}}}*popMessages(){let t=0,e,r,n;for(;t<this.reassembly.length;){let s=this.reassembly[t];if(e===void 0){if(n=!(s.flags&j8),!(s.flags&yW)){if(n)break;t++;continue}if(n&&DA(s.streamSeqNum,this.streamSequenceNumber))break;r=s.tsn,e=t}else if(s.tsn!==r){if(n)break;e=void 0,t++;continue}if(s.flags&Ib){let i=this.reassembly.slice(e,t+1).map(a=>a.userData).reduce((a,c)=>(a.push(c),a.push(Buffer.from("")),a),[]);i.pop();let o=Buffer.concat(i);this.reassembly=[...this.reassembly.slice(0,e),...this.reassembly.slice(t+1)],n&&s.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=Kn(this.streamSequenceNumber,1)),t=e,yield[s.streamId,s.protocol,o]}else t++;r=y0(r)}}pruneChunks(t){let e=-1,r=0;for(let[n,s]of this.reassembly.entries())if(x0(t,s.tsn))e=n,r+=s.userData.length;else break;return this.reassembly=this.reassembly.slice(e+1),r}},Fme=class{constructor(t){this.maxMessageSize=t}};f0=wt("werift:packages/webrtc/src/transport/sctp.ts"),b0=65536,xW=class bW{constructor(e=5e3,r=b0){this.port=e,this.maxMessageSize=r}dtlsTransport;sctp;onDataChannel=new Be;id=Eme().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=b0;dataChannelQueue=[];dataChannelId;eventDisposer=[];setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(r=>r()),this.dtlsTransport=e,this.sctp=new qme(new Vme(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(r=>{r.forEach(n=>{let s=this.dataChannels[n];s&&(s.setReadyState("closing"),s.setReadyState("closed"),delete this.dataChannels[n])})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.negotiated&&r.readyState!=="open"&&r.setReadyState("open")}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.setReadyState("closed")}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(r=>{r==="closed"&&this.sctp.setState(1)})].map(r=>r.unSubscribe),()=>this.sctp.onSackReceived=async()=>{}],this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()})}get isServer(){return this.dtlsTransport.iceTransport.role!=="controlling"}channelByLabel(e){return Object.values(this.dataChannels).find(r=>r.label===e)}datachannelReceive=async(e,r,n)=>{if(r===sA&&n.length>0)switch(f0("DCEP",e,r,n),n[0]){case EV:{if(n.length<12){f0("DATA_CHANNEL_OPEN data.length not enough");return}if(Object.keys(this.dataChannels).includes(e.toString()))f0("datachannel already opened","retransmit ack");else{let[,i,,o,a,c]=gA.jspack.Unpack("!BBHLHH",n),u=12,l=n.slice(u,u+a).toString("utf8");u+=a;let d=n.slice(u,u+c).toString("utf8");f0("DATA_CHANNEL_OPEN",{channelType:i,reliability:o,streamId:e,label:l,protocol:d});let f=(i&3)===1?o:void 0,p=(i&3)===2?o:void 0,m=new m5({label:l,ordered:(i&128)===0,maxPacketLifeTime:p,maxRetransmits:f,protocol:d,id:e}),y=new p5(this,m,!1);y.isCreatedByRemote=!0,this.dataChannels[e]=y,this.onDataChannel.execute(y),y.setReadyState("open")}let s=this.dataChannels[e];this.dataChannelQueue.push([s,sA,Buffer.from(gA.jspack.Pack("!B",[AV]))]),await this.dataChannelFlush()}break;case AV:{f0("DATA_CHANNEL_ACK",e,r);let s=this.dataChannels[e];if(!s)throw new Error("channel not found");s.setReadyState("open")}break}else{let s=this.dataChannels[e];if(s){let i=(()=>{switch(r){case CV:return n.toString("utf8");case X0e:return"";case kV:return n;case J0e:return Buffer.from([]);default:throw new Error}})();s.messagesReceived++,s.bytesReceived+=n.length,s.onMessage.execute(i),s.emit("message",{data:i}),s.onmessage&&s.onmessage({data:i})}}};dataChannelAddNegotiated(e){if(e.id==null)throw new Error;if(this.dataChannels[e.id])throw new Error;this.dataChannels[e.id]=e,this.sctp.associationState===4&&e.setReadyState("open")}dataChannelOpen(e){if(e.id){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let r=W0e,n=0,s=0;e.ordered||(r=128),e.maxRetransmits?(r=1,s=e.maxRetransmits):e.maxPacketLifeTime&&(r=2,s=e.maxPacketLifeTime);let i=gA.jspack.Pack("!BBHLHH",[EV,r,n,s,e.label.length,e.protocol.length]),o=Buffer.concat([Buffer.from(i),Buffer.from(e.label,"utf8"),Buffer.from(e.protocol,"utf8")]);this.dataChannelQueue.push([e,sA,o]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,r,n]=this.dataChannelQueue.shift(),s=e.id;if(s===void 0){for(s=this.dataChannelId;Object.keys(this.dataChannels).includes(s.toString());)s+=2;this.dataChannels[s]=e,e.setId(s)}if(r===sA)await this.sctp.send(s,r,n,{ordered:!0});else{let i=e.maxPacketLifeTime?Date.now()+e.maxPacketLifeTime/1e3:void 0;await this.sctp.send(s,r,n,{expiry:i,maxRetransmits:e.maxRetransmits,ordered:e.ordered}),e.addBufferedAmount(-n.length)}}this.dataChannelQueue=[]}}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,r)=>{let n=Buffer.isBuffer(r)?r:Buffer.from(r),s=SG(r);return this.assertSendableMessageSize(s),e.addBufferedAmount(s),this.dataChannelQueue.push(typeof r=="string"?[e,CV,n]:[e,kV,n]),this.sctp.associationState!==4&&f0("sctp not established",this.sctp.associationState),this.dataChannelFlush(),s};getCapabilities(){return bW.getCapabilities(this.maxMessageSize)}static getCapabilities(e=b0){return new N5(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??b0}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.isServer?this.dataChannelId=0:this.dataChannelId=1,this.sctp.isServer=this.isServer,await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{},await this.sctp.stop()}dataChannelClose(e){["closing","closed"].includes(e.readyState)||(e.setReadyState("closing"),this.sctp.associationState===4?(this.sctp.reconfigQueue.includes(e.id)||this.sctp.reconfigQueue.push(e.id),this.sctp.reconfigQueue.length===1&&this.sctp.transmitReconfigRequest()):(this.dataChannelQueue=this.dataChannelQueue.filter(r=>r[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(r=>r!==e.id),e.id&&delete this.dataChannels[e.id],e.setReadyState("closed")))}},N5=class{constructor(t){this.maxMessageSize=t}},Vme=class{constructor(t){this.dtls=t}set onData(t){this.dtls.dataReceiver=t}send=t=>this.dtls.sendData(t);close(){}},Nb=class _W{version=0;origin;name="-";time="0 0";host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];static parse(e){let[r,n]=Kme(e),s=new _W;r.forEach(o=>{if(o.startsWith("v="))s.version=Number.parseInt(o.slice(2),10);else if(o.startsWith("o="))s.origin=o.slice(2);else if(o.startsWith("s="))s.name=o.slice(2);else if(o.startsWith("c="))s.host=MP(o.slice(2));else if(o.startsWith("t="))s.time=o.slice(2);else if(o.startsWith("a=")){let[a,c]=jP(o);switch(a){case"fingerprint":{let[u,l]=c?.split(" ")||[];s.dtlsFingerprints.push(new BA(u,l))}break;case"ice-lite":s.iceLite=!0;break;case"ice-options":s.iceOptions=c;break;case"ice-pwd":s.icePassword=c;break;case"ice-ufrag":s.iceUsernameFragment=c;break;case"group":SA(s.group,c);break;case"msid-semantic":SA(s.msidSemantic,c);break;case"setup":s.dtlsRole=IV[c];break;case"extmap-allow-mixed":s.extMapAllowMixed=!0;break}}});let i=s.group.find(o=>o.semantic==="BUNDLE");return n.forEach(o=>{let c=o[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!c)throw new Error("m line not found");let u=c[1],l=c[4].split(" "),d=["audio","video"].includes(u)?l.map(m=>Number(m)):void 0,f=new jA(u,Number.parseInt(c[2]),c[3],d||l);if(f.dtlsParams=new $A([...s.dtlsFingerprints],s.dtlsRole),f.iceParams=new R5({iceLite:s.iceLite,usernameFragment:s.iceUsernameFragment,password:s.icePassword}),f.iceOptions=s.iceOptions,s.media.push(f),o.slice(1).forEach(m=>{if(m.startsWith("c="))f.host=MP(m.slice(2));else if(m.startsWith("a=")){let[y,_]=jP(m);switch(y){case"candidate":if(!_)throw new Error;f.iceCandidates.push($5(_));break;case"end-of-candidates":f.iceCandidatesComplete=!0;break;case"extmap":{let[S,C]=_.split(" ");S.includes("/")&&([S]=S.split("/")),f.rtp.headerExtensions.push(new wa({id:Number.parseInt(S),uri:C}))}break;case"fingerprint":{if(!_)throw new Error;let[S,C]=_.split(" ");f.dtlsParams?.fingerprints.push(new BA(S,C))}break;case"ice-options":f.iceOptions=_;break;case"ice-pwd":f.iceParams.password=_;break;case"ice-ufrag":f.iceParams.usernameFragment=_;break;case"ice-lite":f.iceParams.iceLite=!0;break;case"max-message-size":f.sctpCapabilities=new N5(Number.parseInt(_,10));break;case"mid":f.rtp.muxId=_;break;case"msid":f.msid=_;break;case"rtcp":{let[S,C]=Sc(_," ");f.rtcpPort=Number.parseInt(S),f.rtcpHost=MP(C)}break;case"rtcp-mux":f.rtcpMux=!0;break;case"setup":f.dtlsParams.role=IV[_];break;case"recvonly":case"sendonly":case"sendrecv":case"inactive":f.direction=y;break;case"rtpmap":{let[S,C]=Sc(_," "),[E,B,G]=C.split("/"),se;f.kind==="audio"&&(se=G?Number.parseInt(G):1);let _e=new Ku({mimeType:f.kind+"/"+E,channels:se,clockRate:Number.parseInt(B),payloadType:Number.parseInt(S)});f.rtp.codecs.push(_e)}break;case"sctpmap":{if(!_)throw new Error;let[S,C]=Sc(_," ");f.sctpMap[Number.parseInt(S)]=C,f.sctpPort=Number.parseInt(S)}break;case"sctp-port":if(!_)throw new Error;f.sctpPort=Number.parseInt(_);break;case"ssrc":{let[S,C]=Sc(_," "),E=Number.parseInt(S),[B,G]=Sc(C,":"),se=f.ssrc.find(_e=>_e.ssrc===E);se||(se=new zA({ssrc:E}),f.ssrc.push(se)),RG.includes(B)&&(se[B]=G)}break;case"ssrc-group":SA(f.ssrcGroup,_);break;case"rid":{let[S,C]=Sc(_," ");f.simulcastParameters.push(new g5({rid:S,direction:C}))}break}}}),(!f.iceParams.usernameFragment||!f.iceParams.password)&&f.rtp.muxId&&i&&i.items.includes(f.rtp.muxId))for(let m=0;m<i.items.length;m++){if(!i.items.includes(m.toString()))continue;let y=s.media[m];if(y.iceParams?.usernameFragment&&y.iceParams.password){f.iceParams={...y.iceParams};break}}f.dtlsParams.role||(f.dtlsParams=void 0);let p=m=>f.rtp.codecs.find(y=>y.payloadType===m);o.slice(1).forEach(m=>{if(m.startsWith("a=")){let[y,_]=jP(m);if(y==="fmtp"){let[S,C]=Sc(_," "),E=p(Number(S));E.parameters=C}else if(y==="rtcp-fb"){let[S,C,E]=_.split(" ");f.rtp.codecs.forEach(B=>{["*",B.payloadType.toString()].includes(S)&&B.rtcpFeedback.push(new EG({type:C,parameter:E}))})}}})}),s}webrtcTrackId(e){if(e.msid?.includes(" ")){let r=e.msid.split(" ");for(let n of this.msidSemantic)if(n.semantic==="WMS"&&(n.items.includes(r[0])||n.items.includes("*")))return r[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${L8(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(s=>e.push(`a=group:${s.str}`)),this.extMapAllowMixed&&e.push("a=extmap-allow-mixed"),this.msidSemantic.forEach(s=>e.push(`a=msid-semantic:${s.str}`));let r=this.media.map(s=>s.toString()).join("");return e.join(`\r
|
|
187
|
+
`)+`\r
|
|
188
|
+
`+r}toJSON(){return new vW(this.string,this.type)}toSdp(){return{type:this.type,sdp:this.string}}},jA=class{constructor(t,e,r,n){this.kind=t,this.port=e,this.profile=r,this.fmt=n}host;direction;msid;rtcpPort;rtcpHost;rtcpMux=!1;ssrc=[];ssrcGroup=[];rtp={codecs:[],headerExtensions:[]};sctpCapabilities;sctpMap={};sctpPort;dtlsParams;iceParams;iceCandidates=[];iceCandidatesComplete=!1;iceOptions;simulcastParameters=[];toString(){let t=[];if(t.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(e=>e.toString()).join(" ")}`),this.host&&t.push(`c=${L8(this.host)}`),this.iceCandidates.forEach(e=>{t.push(`a=candidate:${B5(e)}`)}),this.iceCandidatesComplete&&t.push("a=end-of-candidates"),this.iceParams?.usernameFragment&&t.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`),this.iceParams?.password&&t.push(`a=ice-pwd:${this.iceParams.password}`),this.iceParams?.iceLite&&t.push("a=ice-lite"),this.iceOptions&&t.push(`a=ice-options:${this.iceOptions}`),this.dtlsParams&&(this.dtlsParams.fingerprints.forEach(e=>{t.push(`a=fingerprint:${e.algorithm} ${e.value}`)}),t.push(`a=setup:${S8[this.dtlsParams.role]}`)),this.direction&&t.push(`a=${this.direction}`),this.rtp.muxId&&t.push(`a=mid:${this.rtp.muxId}`),this.msid&&t.push(`a=msid:${this.msid}`),this.rtcpPort&&this.rtcpHost&&(t.push(`a=rtcp:${this.rtcpPort} ${L8(this.rtcpHost)}`),this.rtcpMux&&t.push("a=rtcp-mux")),this.ssrcGroup.forEach(e=>{t.push(`a=ssrc-group:${e.str}`)}),this.ssrc.forEach(e=>{RG.forEach(r=>{let n=e[r];n!==void 0&&t.push(`a=ssrc:${e.ssrc} ${r}:${n}`)})}),this.rtp.codecs.forEach(e=>{t.push(`a=rtpmap:${e.payloadType} ${e.str}`),e.rtcpFeedback.forEach(r=>{let n=r.type;r.parameter&&(n+=` ${r.parameter}`),t.push(`a=rtcp-fb:${e.payloadType} ${n}`)}),e.parameters&&t.push(`a=fmtp:${e.payloadType} ${e.parameters}`)}),Object.keys(this.sctpMap).forEach(e=>{let r=this.sctpMap[Number(e)];t.push(`a=sctpmap:${e} ${r}`)}),this.sctpPort&&t.push(`a=sctp-port:${this.sctpPort}`),this.sctpCapabilities&&t.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`),this.rtp.headerExtensions.forEach(e=>t.push(`a=extmap:${e.id} ${e.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach(s=>{t.push(`a=rid:${s.rid} ${s.direction}`)});let e="a=simulcast:",r=this.simulcastParameters.filter(s=>s.direction==="recv");r.length&&(e+=`recv ${r.map(s=>s.rid).join(";")} `);let n=this.simulcastParameters.filter(s=>s.direction==="send");n.length&&(e+=`send ${n.map(s=>s.rid).join(";")}`),t.push(e)}return t.join(`\r
|
|
189
|
+
`)+`\r
|
|
190
|
+
`}},S0=class{constructor(t,e){this.semantic=t,this.items=e}get str(){return`${this.semantic} ${this.items.join(" ")}`}};vW=class{constructor(t,e){this.sdp=t,this.type=e}static isThis(t){if(typeof t?.sdp=="string")return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};zA=class{ssrc;cname;msid;msLabel;label;constructor(t){Object.assign(this,t)}},oA=wt("werift:packages/webrtc/src/media/rtpReceiver.ts"),M5=class{constructor(t,e,r){this.config=t,this.kind=e,this.rtcpSsrc=r}codecs={};get codecArray(){return Object.values(this.codecs).sort((t,e)=>t.payloadType-e.payloadType)}ssrcByRtx={};nack=new cme(this);audioRedHandler=new RZ;type="receiver";uuid=V0e().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new Be;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};setDtlsTransport(t){this.dtlsTransport=t}get track(){return this.tracks[0]??new Wb({kind:this.kind})}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type==="nack")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===AG().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===N0().type)}prepareReceive(t){t.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),t.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(t){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new dme(this.dtlsTransport,this.rtcpSsrc,t))}addTrack(t){return this.tracks.find(r=>{if(r.rid)return r.rid===t.rid;if(r.ssrc)return r.ssrc===t.ssrc})?!1:(this.tracks.push(t),t.ssrc&&(this.trackBySSRC[t.ssrc]=t),t.rid&&(this.trackByRID[t.rid]=t),!0)}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.receiverTWCC&&(this.receiverTWCC.twccRunning=!1),this.nack.close()}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await $P(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=Object.entries(this.remoteStreams).map(([r,n])=>{let s=0,i=0;if(this.lastSRtimestamp[r]){s=this.lastSRtimestamp[r];let o=Xb()-this.receiveLastSRTimestamp[r];o>0&&o<65536&&(i=_0(o*65536))}return new ZA({ssrc:Number(r),fractionLost:n.fraction_lost,packetsLost:n.packets_lost,highestSequence:n.max_seq,jitter:n.jitter,lsr:s,dlsr:i})}),e=new C0({ssrc:this.rtcpSsrc,reports:t});try{this.config.debug.receiverReportDelay&&await $P(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([e])}catch(r){oA("sendRtcp failed",r),await $P(500+Math.random()*1e3)}}}catch{}}}async getStats(){let t=Zu(),e=[];if(!this.dtlsTransport)return e;let r=vr("transport",this.dtlsTransport.id);for(let n of this.tracks){if(!n.ssrc)continue;let s=this.remoteStreams[n.ssrc];if(!s)continue;let i={type:"inbound-rtp",id:vr("inbound-rtp",n.ssrc),timestamp:t,ssrc:n.ssrc,kind:this.kind,transportId:r,codecId:this.codecs[0]?vr("codec",this.codecs[0].payloadType,r):void 0,mid:this.sdesMid,trackIdentifier:n.id,packetsReceived:s.packets_received,packetsLost:s.packets_lost,jitter:s.jitter};if(e.push(i),this.lastSRtimestamp[n.ssrc]){let o={type:"remote-outbound-rtp",id:vr("remote-outbound-rtp",n.ssrc),timestamp:t,ssrc:n.ssrc,kind:this.kind,transportId:r,codecId:i.codecId,localId:i.id,remoteTimestamp:this.receiveLastSRTimestamp[n.ssrc]*1e3};e.push(o)}}return e}async sendRtcpPLI(t){if(!this.pliEnabled){oA("pli not supported",{mediaSsrc:t});return}if(this.stopped)return;oA("sendRtcpPLI",{mediaSsrc:t});let e=new E0({feedback:new qb({senderSsrc:this.rtcpSsrc,mediaSsrc:t})});try{await this.dtlsTransport.sendRtcp([e])}catch(r){oA(r)}}handleRtcpPacket(t){switch(t.type){case uf.type:{let e=t;this.lastSRtimestamp[e.ssrc]=T5(e.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[e.ssrc]=Xb();let r=this.trackBySSRC[t.ssrc];r&&r.onReceiveRtcp.execute(t)}break}this.onRtcp.execute(t)}handleRtpBySsrc=(t,e)=>{let r=this.trackBySSRC[t.header.ssrc];this.handleRTP(t,e,r)};handleRtpByRid=(t,e,r)=>{let n=this.trackByRID[e];this.trackBySSRC[t.header.ssrc]||(this.trackBySSRC[t.header.ssrc]=n),this.handleRTP(t,r,n)};handleRTP(t,e,r){if(this.stopped)return;let n=this.codecs[t.header.payloadType];if(!n)return;if(this.remoteStreams[t.header.ssrc]=this.remoteStreams[t.header.ssrc]??new fme(n.clockRate),this.remoteStreams[t.header.ssrc].add(t),this.receiverTWCC){let i=e[Ur.transportWideCC];if(!i==null)throw new Error("undefined");this.receiverTWCC.handleTWCC(i)}else this.twccEnabled&&this.setupTWCC(t.header.ssrc);if(n.name.toLowerCase()==="rtx"){let i=this.ssrcByRtx[t.header.ssrc],o=Yb(n.parameters??""),a=this.codecs[o.apt];if(t.payload.length<2)return;t=NZ(t,a.payloadType,i),r=this.trackBySSRC[i]}let s;if(!(n.name.toLowerCase()==="red"&&(s=t5.deSerialize(t.payload),!Object.keys(this.codecs).includes(s.header.fields[0].blockPT.toString())))){if(r?.kind==="video"&&this.nackEnabled&&this.nack.addPacket(t),r)if(s){if(r.kind==="audio"){let i=this.audioRedHandler.push(s,t);for(let o of i)r.onReceiveRtp.execute(o.clone(),e)}}else r.onReceiveRtp.execute(t.clone(),e);this.runRtcp()}}},mb=wt("werift:packages/webrtc/src/media/router.ts"),wW=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(t){this.ssrcTable[t.ssrc]=t}registerRtpReceiver(t,e){mb("registerRtpReceiver",e),this.ssrcTable[e]=t}registerRtpReceiverBySsrc(t,e){mb("registerRtpReceiverBySsrc",e),e.encodings.filter(r=>r.ssrc!=null).forEach((r,n)=>{this.registerRtpReceiver(t.receiver,r.ssrc),t.addTrack(new Wb({ssrc:r.ssrc,kind:t.kind,id:t.sender.trackId,remote:!0,codec:e.codecs[n]})),r.rtx&&this.registerRtpReceiver(t.receiver,r.rtx.ssrc)}),e.headerExtensions.forEach(r=>{this.extIdUriMap[r.id]=r.uri})}registerRtpReceiverByRid(t,e,r){let[n]=r.codecs;mb("registerRtpReceiverByRid",e),t.addTrack(new Wb({rid:e.rid,kind:t.kind,id:t.sender.trackId,remote:!0,codec:n})),this.ridTable[e.rid]=t.receiver}routeRtp=t=>{let e=yZ(t.header.extensions,this.extIdUriMap),r=this.ssrcTable[t.header.ssrc],n=e[Ur.sdesRTPStreamID];if(typeof n=="string"?(r=this.ridTable[n],r.latestRid=n,r.handleRtpByRid(t,n,e)):r?r.handleRtpBySsrc(t,e):(r=Object.values(this.ridTable).filter(o=>o instanceof M5).find(o=>o.trackBySSRC[t.header.ssrc]),r&&(mb("simulcast register receiver by ssrc",t.header.ssrc),this.registerRtpReceiver(r,t.header.ssrc),r.handleRtpBySsrc(t,e))),!r){mb("ssrcReceiver not found");return}let s=e[Ur.sdesMid];typeof s=="string"&&(r.sdesMid=s);let i=e[Ur.repairedRtpStreamId];typeof i=="string"&&(r.latestRepairedRid=i)};routeRtcp=t=>{let e=[];switch(t.type){case uf.type:t=t,e.push(this.ssrcTable[t.ssrc]);break;case C0.type:t=t,t.reports.forEach(r=>{e.push(this.ssrcTable[r.ssrc])});break;case Kb.type:{let r=t}break;case cf.type:{let r=t;r.feedback&&e.push(this.ssrcTable[r.feedback.mediaSourceSsrc])}break;case E0.type:{let r=t;switch(r.feedback.count){case Hb.count:{let n=r.feedback;e.push(this.ssrcTable[n.ssrcFeedbacks[0]])}break;default:e.push(this.ssrcTable[r.feedback.senderSsrc]||this.ssrcTable[r.feedback.mediaSsrc])}}break}e.filter(r=>r).forEach(r=>r.handleRtcpPacket(t))}},Gme=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(t,e,r){this.numPackets===0?(this.firstPacketSentAtMs=e,this.firstPacketReceivedAtMs=r,this.lastPacketSentAtMs=e,this.lastPacketReceivedAtMs=r):(e<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=e),r<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=r),e>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=e),r>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=r)),this.numPackets++,this.totalSize+=t}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let t=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs,e=this.totalSize/t*8*1e3;return Ub(e)}get sendBitrate(){let t=this.lastPacketSentAtMs-this.firstPacketSentAtMs,e=this.totalSize/t*8*1e3;return Ub(e)}},h0=20,Wme=10,Xme=class{congestion=!1;onAvailableBitrate=new Be;onCongestion=new Be;onCongestionScore=new Be;congestionCounter=0;cumulativeResult=new Gme;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(t){this._congestionScore=t,this.onCongestionScore.execute(t)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(t){this._availableBitrate=t,this.onAvailableBitrate.execute(t)}constructor(){}receiveTWCC(t){let r=k5()-this.cumulativeResult.firstPacketSentAtMs;r>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<h0?this.congestionCounter++:this.congestionScore<Wme&&this.congestionScore++,this.congestionCounter>=h0&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let n of t.packetResults){if(!n.received)continue;let s=n.sequenceNumber,i=this.sentInfos[s];i&&n.receivedAtMs&&this.cumulativeResult.addPacket(i.size,i.sendingAtMs,n.receivedAtMs)}if(r>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-h0){let n=Ub(h0/2)+1,s=Ub(h0/4)+1,i=n-(n-s)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-i}this.congestionCounter<=-h0&&(this.congestionScore>1&&(this.congestionScore--,this.onCongestion.execute(!1)),this.congestionCounter=0),this.congestionCounter<=0&&this.congestion&&(this.congestion=!1,this.onCongestion.execute(this.congestion))}}rtpPacketSent(t){Object.keys(t).map(e=>Number(e)).sort().filter(e=>e<t.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[t.wideSeq]=t}},zP=wt("werift:packages/webrtc/src/media/rtpSender.ts"),GV=128,WV=.85,SW=class{constructor(t){this.trackOrKind=t,this.kind=typeof this.trackOrKind=="string"?this.trackOrKind:this.trackOrKind.kind,typeof t!="string"&&(t.streamId&&(this.streamId=t.streamId),this.registerTrack(t))}type="sender";kind;ssrc=U8.jspack.Unpack("!L",VV(4))[0];rtxSsrc=U8.jspack.Unpack("!L",VV(4))[0];streamId=KV().toString();trackId=KV().toString();onReady=new Be;onRtcp=new Be;onPictureLossIndication=new Be;onGenericNack=new Be;senderBWE=new Xme;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=F8();redRedundantPayloadType;_redDistance=2;redEncoder=new PZ(this._redDistance);headerExtensions=[];disposeTrack;lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;rtt;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpCache=[];codec;dtlsTransport;dtlsDisposer=[];track;stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;setDtlsTransport(t){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=t,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e==="connected"&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(t){this._redDistance=t,this.redEncoder.distance=t}prepareSend(t){this.cname=t.rtcp?.cname,this.mid=t.muxId,this.headerExtensions=t.headerExtensions,this.rtpStreamId=t.rtpStreamId,this.repairedRtpStreamId=t.repairedRtpStreamId,this.codec=t.codecs[0],this.track&&(this.track.codec=this.codec),t.codecs.forEach(e=>{let r=Yb(e.parameters??"");e.name.toLowerCase()==="rtx"&&r.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()==="red"&&(this.redRedundantPayloadType=Number((e.parameters??"").split("/")[0]))})}registerTrack(t){if(t.stopped)throw new Error("track is ended");this.disposeTrack&&this.disposeTrack(),t.id=this.trackId;let{unSubscribe:e}=t.onReceiveRtp.subscribe(async r=>{await this.sendRtp(r)});this.track=t,this.disposeTrack=e,this.codec&&(t.codec=this.codec),t.onSourceChanged.subscribe(r=>{this.replaceRTP(r)})}async replaceTrack(t){if(t!==null){if(t.stopped)throw new Error("track is ended");if(this.sequenceNumber!=null){let e=t.header||(await t.onReceiveRtp.asPromise())[0].header;this.replaceRTP(e)}this.registerTrack(t),zP("replaceTrack","ssrc",t.ssrc,"rid",t.rid)}}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack&&this.disposeTrack(),this.track=void 0}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await ZV(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=[new uf({ssrc:this.ssrc,senderInfo:new e5({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=T5(this.ntpTimestamp),this.lastSentSRTimestamp=Xb(),this.cname&&t.push(new Kb({chunks:[new Y8({source:this.ssrc,items:[new Q8({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(t)}catch(e){zP("sendRtcp failed",e),await ZV(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:t,timestamp:e},r=!1){this.sequenceNumber!=null&&(this.seqOffset=Kn(this.sequenceNumber,-t),r&&(this.seqOffset=Kn(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=tf(this.timestamp,-e),r&&(this.timestampOffset=Kn(this.timestampOffset,1))),this.rtpCache=[],zP("replaceRTP",this.sequenceNumber,t,this.seqOffset)}async sendRtp(t){if(this.dtlsTransport.state!=="connected"||!this.codec)return;t=Buffer.isBuffer(t)?Pc.deSerialize(t):t;let{header:e,payload:r}=t;e.ssrc=this.ssrc,e.payloadType=this.codec.payloadType,e.timestamp=tf(e.timestamp,this.timestampOffset),e.sequenceNumber=Kn(e.sequenceNumber,this.seqOffset),this.timestamp=e.timestamp,this.sequenceNumber=e.sequenceNumber;let n=DG(),s=[...e.extensions];e.extensions=this.headerExtensions.map(u=>{let l=(()=>{switch(u.uri){case Ur.sdesMid:return this.mid?xZ(this.mid):void 0;case Ur.sdesRTPStreamID:return this.rtpStreamId?bZ(this.rtpStreamId):void 0;case Ur.repairedRtpStreamId:return this.repairedRtpStreamId?_Z(this.repairedRtpStreamId):void 0;case Ur.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Kn(this.dtlsTransport.transportSequenceNumber,1),vZ(this.dtlsTransport.transportSequenceNumber);case Ur.absSendTime:return wZ(n)}})();if(l)return{id:u.id,payload:l}}).filter(u=>u);for(let u of s){let l=e.extensions.find(d=>d.id===u.id);l?l.payload=u.payload:e.extensions.push(u)}e.extensions=e.extensions.sort((u,l)=>u.id-l.id),this.ntpTimestamp=n,this.rtpTimestamp=e.timestamp,this.octetCount+=r.length,this.packetCount=tf(this.packetCount,1),this.rtpCache[e.sequenceNumber%GV]=t;let i=r;this.redRedundantPayloadType&&(this.redEncoder.push({block:i,timestamp:e.timestamp,blockPT:this.redRedundantPayloadType}),i=this.redEncoder.build().serialize());let o=await this.dtlsTransport.sendRtp(i,e);this.runRtcp();let a=k5(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:a,sentAtMs:a};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(t){switch(t.type){case uf.type:case C0.type:t.reports.filter(r=>r.ssrc===this.ssrc).forEach(r=>{if(this.lastSRtimestamp===r.lsr&&r.dlsr&&this.lastSentSRTimestamp){let n=Xb()-this.lastSentSRTimestamp-r.dlsr/65536;this.rtt===void 0?this.rtt=n:this.rtt=WV*this.rtt+(1-WV)*n}});break;case cf.type:{let e=t;switch(e.feedback.count){case Vb.count:{let r=e.feedback;this.senderBWE.receiveTWCC(r)}break;case Fb.count:{let r=e.feedback;r.lost.forEach(async n=>{let s=this.rtpCache[n%GV];s&&s.header.sequenceNumber!==n&&(s=void 0),s&&(this.rtxPayloadType!=null&&(s=BZ(s,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Kn(this.rtxSequenceNumber,1)),await this.dtlsTransport.sendRtp(s.payload,s.header))}),this.onGenericNack.execute(r)}break}}break;case E0.type:{let e=t;switch(e.feedback.count){case Hb.count:{let r=e.feedback;this.receiverEstimatedMaxBitrate=r.bitrate}break;case qb.count:this.onPictureLossIndication.execute();break}}break}this.onRtcp.execute(t)}getParameters(){return{encodings:[]}}setParameters(t){}async getStats(){let t=Zu(),e=[];if(!this.dtlsTransport)return e;let r=vr("transport",this.dtlsTransport.id),n={type:"outbound-rtp",id:vr("outbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:this.codec?vr("codec",this.codec.payloadType,r):void 0,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0};if(e.push(n),this.track){let s={type:"media-source",id:vr("media-source",this.trackId),timestamp:t,trackIdentifier:this.trackId,kind:this.kind};e.push(s)}if(this.rtt!==void 0){let s={type:"remote-inbound-rtp",id:vr("remote-inbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:n.codecId,localId:n.id,roundTripTime:this.rtt};e.push(s)}return e}},Yme=wt("werift:packages/webrtc/src/transport/sctpManager.ts"),Qme=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new Be;constructor(){}createSctpTransport(t){let e=new xW(5e3,t);return e.mid=void 0,e.onDataChannel.subscribe(r=>{this.dataChannelsOpened++,this.dataChannels.push(r),this.onDataChannel.execute(r)}),this.sctpTransport=e,e}createDataChannel(t,e={}){let n={...{protocol:"",ordered:!0,negotiated:!1},...e};if(n.maxPacketLifeTime&&n.maxRetransmits)throw new Error("can not select both");this.sctpTransport||(this.sctpTransport=this.createSctpTransport());let s=new m5({id:n.id,label:t,maxPacketLifeTime:n.maxPacketLifeTime,maxRetransmits:n.maxRetransmits,negotiated:n.negotiated,ordered:n.ordered,protocol:n.protocol}),i=new p5(this.sctpTransport,s);return this.dataChannelsOpened++,this.dataChannels.push(i),i.stateChange.subscribe(o=>{if(o==="closed"){this.dataChannelsClosed++;let a=this.dataChannels.indexOf(i);a!==-1&&this.dataChannels.splice(a,1)}}),i}async connectSctp(){!this.sctpTransport||!this.sctpRemotePort||(await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),Yme("sctp connected"))}setRemoteSCTP(t,e){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(t.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=t.sctpPort,!this.sctpRemotePort)throw new Error("sctpRemotePort not exist");this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=e,this.sctpTransport.mid||(this.sctpTransport.mid=t.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(){let t=Zu(),e=[];for(let r of this.dataChannels){let n={type:"data-channel",id:vr("data-channel",r.id),timestamp:t,label:r.label,protocol:r.protocol,dataChannelIdentifier:r.id,state:r.readyState,messagesSent:r.messagesSent||0,bytesSent:r.bytesSent||0,messagesReceived:r.messagesReceived||0,bytesReceived:r.bytesReceived||0};e.push(n)}return e}},AW=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:t,midSuffix:e,bundlePolicy:r}){this.cname=t,this.midSuffix=e??!1,this.bundlePolicy=r}get localDescription(){if(this._localDescription)return this._localDescription.toJSON()}get remoteDescription(){if(this._remoteDescription)return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(t=>t.direction==="inactive")}createMediaDescriptionForTransceiver(t,e){let r=new jA(t.kind,9,"UDP/TLS/RTP/SAVPF",t.codecs.map(n=>n.payloadType));return r.direction=e,r.msid=t.msid,r.rtp={codecs:t.codecs,headerExtensions:t.headerExtensions,muxId:t.mid},r.rtcpHost="0.0.0.0",r.rtcpPort=9,r.rtcpMux=!0,r.ssrc=[new zA({ssrc:t.sender.ssrc,cname:this.cname})],t.options.simulcast&&(r.simulcastParameters=t.options.simulcast.map(n=>new g5(n))),r.rtp.codecs.find(n=>n.name.toLowerCase()==="rtx")&&(r.ssrc.push(new zA({ssrc:t.sender.rtxSsrc,cname:this.cname})),r.ssrcGroup=[new S0("FID",[t.sender.ssrc.toString(),t.sender.rtxSsrc.toString()])]),this.addTransportDescription(r,t.dtlsTransport),r}createMediaDescriptionForSctp(t){let e=new jA("application",TV,"UDP/DTLS/SCTP",["webrtc-datachannel"]);return e.sctpPort=t.port,e.rtp.muxId=t.mid,e.sctpCapabilities=t.getCapabilities(),this.addTransportDescription(e,t.dtlsTransport),e}addTransportDescription(t,e){let r=e.iceTransport;t.iceCandidates=r.localCandidates,t.iceCandidatesComplete=r.gatheringState==="complete",t.iceParams=r.localParameters,t.iceOptions="trickle",t.host=Y0e,t.port=TV,t.direction==="inactive"&&(t.port=0,t.msid=void 0),t.dtlsParams||(t.dtlsParams=e.localParameters,t.dtlsParams.fingerprints||(t.dtlsParams.fingerprints=e.localParameters.fingerprints))}allocateMid(t=""){let e="";for(let r=0;e=(r++).toString()+t,!!this.seenMid.has(e););return this.seenMid.add(e),e}parseSdp({sdp:t,isLocal:e,signalingState:r,type:n}){let s=Nb.parse(t);return this.validateDescription({description:s,isLocal:e,signalingState:r}),s.type=n,s}validateDescription({description:t,isLocal:e,signalingState:r}){if(e){if(t.type==="offer"){if(!["stable","have-local-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}else if(t.type==="offer"){if(!["stable","have-remote-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-local-offer","have-remote-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}buildOfferSdp(t,e){let r=new Nb;D8("offer",r),(this.currentLocalDescription?.media??[]).forEach((s,i)=>{let o=s.rtp.muxId;if(o)if(s.kind==="application"){if(!e)throw new Error("sctpTransport not found");e.mLineIndex=i,r.media.push(this.createMediaDescriptionForSctp(e))}else{let a=t.find(c=>c.mid===o);if(!a){if(s.direction==="inactive"){r.media.push(s);return}throw new Error("transceiver not found")}a.mLineIndex=i,r.media.push(this.createMediaDescriptionForTransceiver(a,a.direction))}});for(let s of t.filter(i=>!r.media.find(o=>o.rtp.muxId===i.mid))){s.mid==null&&(s.mid=this.allocateMid(this.midSuffix?"av":""));let i=this.createMediaDescriptionForTransceiver(s,s.direction);s.mLineIndex===void 0?(s.mLineIndex=r.media.length,r.media.push(i)):r.media[s.mLineIndex]=i}if(e&&!r.media.find(s=>s.kind==="application")&&(e.mLineIndex=r.media.length,e.mid==null&&(e.mid=this.allocateMid(this.midSuffix?"dc":"")),r.media.push(this.createMediaDescriptionForSctp(e))),this.bundlePolicy!=="disable"){let s=r.media.map(i=>i.rtp.muxId).filter(i=>i);if(s.length){let i=new S0("BUNDLE",s);r.group.push(i)}}return r}buildAnswerSdp({transceivers:t,sctpTransport:e,signalingState:r}){if(!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("createAnswer failed");if(!this._remoteDescription)throw new Error("wrong state");let n=new Nb;D8("answer",n);for(let s of this._remoteDescription.media){let i,o;if(["audio","video"].includes(s.kind)){let a=t.find(c=>c.mid===s.rtp.muxId);if(!a)throw new Error(`Transceiver with mid=${s.rtp.muxId} not found`);o=this.createMediaDescriptionForTransceiver(a,C5(a.direction,a.offerDirection)),i=a.dtlsTransport}else if(s.kind==="application"){if(!e||!e.mid)throw new Error("sctpTransport not found");o=this.createMediaDescriptionForSctp(e),i=e.dtlsTransport}else throw new Error("invalid kind");o.dtlsParams&&(i.role==="auto"?o.dtlsParams.role="client":o.dtlsParams.role=i.role),s.simulcastParameters&&s.simulcastParameters.length>0&&(o.simulcastParameters=s.simulcastParameters.map(a=>({...a,direction:a.direction==="send"?"recv":"send"}))),n.media.push(o)}if(this.bundlePolicy!=="disable"){let s=new S0("BUNDLE",[]);for(let i of n.media)i.rtp.muxId&&s.items.push(i.rtp.muxId);n.group.push(s)}return n}setLocalDescription(t){this.currentLocalDescription=t,t.type==="answer"?this.pendingLocalDescription=void 0:this.pendingLocalDescription=t}setRemoteDescription(t,e){if(!t.sdp||!t.type||t.type==="rollback"||t.type==="pranswer")throw new Error("invalid sessionDescription");let r=this.parseSdp({sdp:t.sdp,isLocal:!1,signalingState:e,type:t.type});return r.type==="answer"?(this.currentRemoteDescription=r,this.pendingRemoteDescription=void 0):this.pendingRemoteDescription=r,r}registerMid(t){this.seenMid.add(t)}get remoteIsBundled(){let t=this._remoteDescription;return t?t.group.find(r=>r.semantic==="BUNDLE"&&this.bundlePolicy!=="disable"):void 0}setLocal(t,e,r){let n=new Map(e.map(o=>[o?.mLineIndex,o])),s=e.find(o=>o?.dtlsTransport)?.dtlsTransport??r?.dtlsTransport;t.media.filter(o=>["audio","video"].includes(o.kind)).forEach((o,a)=>{let u=(n.get(a)??e[a])?.dtlsTransport??s;if(!u)throw new Error(`dtls transport not found for media index ${a}`);this.addTransportDescription(o,u)});let i=t.media.find(o=>o.kind==="application");r&&i&&this.addTransportDescription(i,r.dtlsTransport),this.setLocalDescription(t)}},gb=wt("werift:packages/webrtc/src/transport/secureTransportManager.ts"),ege=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new Be;iceConnectionStateChange=new Be;onIceCandidate=new Be;connectionStateChange=new Be;config;transceiverManager;sctpManager;constructor({config:t,transceiverManager:e,sctpManager:r}){if(this.config=t,this.transceiverManager=e,this.sctpManager=r,this.config.dtls){let{keys:n}=this.config.dtls;n&&this.setupCertificate(n)}}get dtlsTransports(){return[...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport].filter(e=>e!=null).reduce((e,r)=>(e.map(n=>n.id).includes(r.id)||e.push(r),e),[])}get iceTransports(){return this.dtlsTransports.map(t=>t.iceTransport)}setupCertificate(t){this.certificate=new I5(t.keyPem,t.certPem,t.signatureHash)}createTransport(){let t=this.iceTransports.find(s=>s.state!=="closed"),e=new VG({...UG(this.config.iceServers),forceTurn:this.config.iceTransportPolicy==="relay",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,turnTransport:this.config.forceTurnTCP===!0?"tcp":"udp",useLinkLocalAddress:this.config.iceUseLinkLocalAddress});t&&(e.connection.localUsername=t.connection.localUsername,e.connection.localPassword=t.connection.localPassword),e.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let r=new FG(e);return r.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new A8(this.config,r,this.certificate,tge)}handleNewIceCandidate({candidate:t,media:e,remoteIsBundled:r,transceiver:n,sctpTransport:s,bundlePolicy:i}){return i==="max-bundle"||r?(t.sdpMLineIndex=0,e&&(t.sdpMid=e.rtp.muxId)):(n&&(t.sdpMLineIndex=n.mLineIndex,t.sdpMid=n.mid),s&&(t.sdpMLineIndex=s.mLineIndex,t.sdpMid=s.mid)),t.foundation&&!t.foundation.startsWith("candidate:")&&(t.foundation="candidate:"+t.foundation),this.onIceCandidate.execute(t),t}async addIceCandidate(t,e){let r=P5.fromJSON(e);if(!r)return;let n;typeof r.sdpMid=="number"&&(n=this.getTransportByMid(r.sdpMid)),!n&&typeof r.sdpMLineIndex=="number"&&(n=this.getTransportByMLineIndex(t,r.sdpMLineIndex)),n||(n=this.iceTransports[0]),n?await n.addRemoteCandidate(r):gb("iceTransport not found for candidate",r)}getTransportByMid(t){let e,r=this.transceiverManager.getTransceivers().find(n=>n.mid===t);return r?e=r.dtlsTransport.iceTransport:!e&&this.sctpManager.sctpTransport?.mid===t&&(e=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),e}getTransportByMLineIndex(t,e){let r=t.media[e];return r?this.getTransportByMid(r.rtp.muxId):void 0}restartIce(){for(let t of this.iceTransports)t.restart()}setLocalRole({type:t,role:e}){for(let r of this.dtlsTransports){let n=r.iceTransport;t==="offer"?n.connection.iceControlling=!0:n.connection.iceControlling=!1,n.connection.remoteIsLite&&(n.connection.iceControlling=!0),t==="answer"&&e&&(r.role=e)}}updateIceGatheringState(){let t=this.iceTransports;function e(...n){return t.filter(s=>n.includes(s.gatheringState)).length===t.length}let r;t.length&&e("complete")?r="complete":!t.length||e("new","complete")?r="new":t.map(n=>n.gatheringState).includes("gathering")?r="gathering":r="new",this.iceGatheringState!==r&&(this.iceGatheringState=r,this.iceGatheringStateChange.execute(r))}updateIceConnectionState(){let t=this.iceTransports,e;function r(...s){return t.filter(i=>s.includes(i.state)).length===t.length}function n(...s){return t.some(i=>s.includes(i.state))}this.connectionState==="closed"?e="closed":n("failed")?e="failed":n("disconnected")?e="disconnected":r("new","closed")?e="new":n("new","checking")?e="checking":r("completed","closed")?e="completed":r("connected","completed","closed")?e="connected":e="new",this.iceConnectionState!==e&&(gb("iceConnectionStateChange",e),this.iceConnectionState=e,this.iceConnectionStateChange.execute(e))}async gatherCandidates(t){let e=this.iceTransports.find(r=>r.state==="connected"||r.state==="completed");t&&e?gb("skipping ICE gathering for bundled connection"):await Promise.allSettled(this.iceTransports.map(r=>r.gather())).catch(r=>{gb("gatherCandidates failed",r)})}setConnectionState(t){gb("connectionStateChange",t),this.connectionState=t,this.connectionStateChange.execute(t)}async getStats(){let t=[];for(let e of this.dtlsTransports){let r=await e.getStats();r&&t.push(...r)}return t}async ensureCerts(){this.certificate||(this.certificate=await A8.SetupCertificate());for(let t of this.dtlsTransports)t.localCertificate=this.certificate}async close(){this.setConnectionState("closed"),await Promise.allSettled([...this.dtlsTransports.map(t=>t.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},tge=[PV.SRTP_AEAD_AES_128_GCM,PV.SRTP_AES128_CM_HMAC_SHA1_80],_o=wt("werift:packages/webrtc/src/peerConnection.ts"),rge=class extends h5{cname=Jme().toString();config=EW();signalingState="stable";negotiationneeded=!1;needRestart=!1;router=new wW;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;remoteBundleNegotiated=!1;iceGatheringStateChange=new Be;iceConnectionStateChange=new Be;signalingStateChange=new Be;connectionStateChange=new Be;onDataChannel=new Be;onRemoteTransceiverAdded=new Be;onTransceiverAdded=new Be;onIceCandidate=new Be;onNegotiationneeded=new Be;onTrack=new Be;ondatachannel;onicecandidate;onicecandidateerror;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;onconnectionstatechange;oniceconnectionstatechange;constructor(t={}){super(),this.setConfiguration(t),this.sdpManager=new AW({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new CW(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:e,stream:r,transceiver:n})=>{let s={track:e,streams:[r],transceiver:n,receiver:n.receiver};this.onTrack.execute(e),this.emit("track",s),this.ontrack&&this.ontrack(s)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new Qme,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let r={channel:e};this.ondatachannel?.(r),this.emit("datachannel",r)}),this.secureManager=new ege({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.secureManager.iceGatheringStateChange.pipe(this.iceGatheringStateChange),this.secureManager.iceConnectionStateChange.subscribe(e=>{e==="closed"&&this.close(),this.iceConnectionStateChange.execute(e)}),this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e),this.onconnectionstatechange?.(),this.emit("connectionstatechange")}),this.secureManager.onIceCandidate.subscribe(e=>{let r=e?e.toJSON():void 0;this.onIceCandidate.execute(r),this.onicecandidate?.({candidate:r}),this.emit("icecandidate",{candidate:r})})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription}get remoteDescription(){return this.sdpManager.remoteDescription}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(t){if(qG(this.config,t),this.config.icePortRange){let[e,r]=this.config.icePortRange;if(e===r)throw new Error("should not be same value");if(e>=r)throw new Error("The min must be less than max")}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw new Error("maxMessageSize must be a non-negative integer");this.sctpManager?.sctpTransport&&(this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize);for(let[e,r]of wV([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(r.payloadType==null)switch(r.payloadType=96+e,r.name.toLowerCase()){case"rtx":r.parameters=`apt=${r.payloadType-1}`;break;case"red":if(r.contentType==="audio"){let n=r.payloadType+1;r.parameters=`${n}/${n}`,r.payloadType=63}break}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,r)=>{e.id=1+r})}getConfiguration(){return this.config}async createOffer({iceRestart:t}={}){(t||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let r of this.transceiverManager.getTransceivers())r.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(r),r.headerExtensions.length===0&&(r.headerExtensions=this.config.headerExtensions[r.kind]??[]);return this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON()}createSctpTransport(){let t=this.sctpManager.createSctpTransport(this.config.maxMessageSize),e=this.findOrCreateTransport();return t.setDtlsTransport(e),t}createDataChannel(t,e={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let r=this.sctpManager.createDataChannel(t,e);if(!r.sctp.dtlsTransport){let n=this.findOrCreateTransport();r.sctp.setDtlsTransport(n)}return r}removeTrack(t){if(this.isClosed)throw new Error("peer closed");this.transceiverManager.removeTrack(t),this.needNegotiation()}needNegotiation=async()=>{this.shouldNegotiationneeded=!0,!(this.negotiationneeded||this.signalingState!=="stable")&&(this.shouldNegotiationneeded=!1,setImmediate(()=>{this.negotiationneeded=!0,this.onNegotiationneeded.execute(),this.onnegotiationneeded&&this.onnegotiationneeded({})}))};findOrCreateTransport(){let t=this.dtlsTransports.find(s=>s.state!=="closed"),e=t?.iceTransport;if((this.sdpManager.bundlePolicy==="max-bundle"||this.sdpManager.bundlePolicy!=="disable"&&(this.remoteIsBundled||this.remoteBundleNegotiated))&&t)return t;let r=this.secureManager.createTransport();r.onRtp.subscribe(s=>{this.router.routeRtp(s)}),r.onRtcp.subscribe(s=>{this.router.routeRtcp(s)});let n=r.iceTransport;return n.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),n.onIceCandidate.subscribe(s=>{if(!this.localDescription){_o("localDescription not found when ice candidate was gathered");return}if(!s){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport),this.onIceCandidate.execute(void 0),this.onicecandidate&&this.onicecandidate({candidate:void 0}),this.emit("icecandidate",{candidate:void 0});return}if(!this._localDescription){_o("localDescription not found when ice candidate was gathered");return}this.secureManager.handleNewIceCandidate({candidate:s,bundlePolicy:this.sdpManager.bundlePolicy,remoteIsBundled:!!this.sdpManager.remoteIsBundled,media:this._localDescription.media[0],transceiver:this.transceiverManager.getTransceivers().find(i=>i?.dtlsTransport?.iceTransport.id===n.id),sctpTransport:this.sctpTransport?.dtlsTransport.iceTransport.id===n.id?this.sctpTransport:void 0})}),r}async setLocalDescription(t){t=t??(["stable","have-local-offer","have-remote-pranswer"].includes(this.signalingState)?await this.createOffer():await this.createAnswer());let r=this.sdpManager.parseSdp({sdp:t.sdp,isLocal:!0,signalingState:this.signalingState,type:t.type});r.type==="offer"?this.setSignalingState("have-local-offer"):r.type==="answer"&&this.setSignalingState("stable");for(let[s,i]of wV(r.media)){let o=i.rtp.muxId;if(this.sdpManager.registerMid(o),["audio","video"].includes(i.kind)){let a=this.transceiverManager.getTransceiverByMLineIndex(s);a&&(a.mid=o)}i.kind==="application"&&this.sctpTransport&&(this.sctpTransport.mid=o)}let n=r.media.find(s=>s.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:r.type,role:n}),["answer","pranswer"].includes(r.type))for(let s of this.transceiverManager.getTransceivers()){let i=C5(s.direction,s.offerDirection);s.setCurrentDirection(i)}return this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(s=>{_o("gatherCandidates failed",s)}),r.type==="answer"&&this.connect().catch(s=>{_o("connect failed",s),this.secureManager.setConnectionState("failed")}),this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),r}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(t){let e=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);await this.secureManager.addIceCandidate(e,t)}async connect(){_o("start connect"),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:r}=e;if(r.state==="connected")return;let n=()=>e.state==="connected";n()||(this.secureManager.setConnectionState("connecting"),await r.start().catch(s=>{throw _o("iceTransport.start failed",s),s}),!n()&&(await e.start().catch(s=>{throw _o("dtlsTransport.start failed",s),s}),this.sctpTransport&&this.sctpTransport.dtlsTransport.id===e.id&&await this.sctpManager.connectSctp()))}))).find(e=>e.status==="rejected")?this.secureManager.setConnectionState("failed"):this.secureManager.setConnectionState("connected")}restartIce(){this.needRestart=!0,this.needNegotiation()}async setRemoteDescription(t){t instanceof Nb&&(t=t.toSdp());let e=this.sdpManager.setRemoteDescription(t,this.signalingState);e.group.some(o=>o.semantic==="BUNDLE"&&o.items.length>0)&&(this.remoteBundleNegotiated=!0);let r,n=(o,a)=>o.kind===a.kind&&[void 0,a.rtp.muxId].includes(o.mid),s=e.media.map((o,a)=>{let c;if(["audio","video"].includes(o.kind)){let l=this.transceiverManager.getTransceivers().find(d=>n(d,o));if(!l)l=this.addTransceiver(o.kind,{direction:"recvonly"}),l.mid=o.rtp.muxId,this.onRemoteTransceiverAdded.execute(l);else if(l.direction==="inactive"&&l.stopping){l.stopped=!0,t.type==="answer"&&l.setCurrentDirection("inactive");return}this.sdpManager.remoteIsBundled&&(r?l.setDtlsTransport(r):r=l.dtlsTransport),c=l.dtlsTransport,this.transceiverManager.setRemoteRTP(l,o,e.type,a)}else if(o.kind==="application"){let l=this.sctpTransport;l||(l=this.createSctpTransport(),l.mid=o.rtp.muxId),this.sdpManager.remoteIsBundled&&(r?l.setDtlsTransport(r):r=l.dtlsTransport),c=l.dtlsTransport,this.sctpManager.setRemoteSCTP(o,a)}else throw new Error("invalid media kind");let u=c.iceTransport;if(o.iceParams){let l=!!this.sdpManager.inactiveRemoteMedia;u.setRemoteParams(o.iceParams,l),o.iceParams?.iceLite&&(u.connection.iceControlling=!0)}return o.dtlsParams&&c.setRemoteParams(o.dtlsParams),o.iceCandidates.forEach(u.addRemoteCandidate),o.iceCandidatesComplete&&u.addRemoteCandidate(void 0),e.type==="answer"&&o.dtlsParams?.role&&(c.role=o.dtlsParams.role==="client"?"server":"client"),u});s=s.filter(o=>!!o);let i=this.transceiverManager.getTransceivers().filter(o=>e.media.find(a=>n(o,a))==null);if(t.type==="answer")for(let o of i)o.stop(),o.stopped=!0;e.type==="offer"?this.setSignalingState("have-remote-offer"):e.type==="answer"&&this.setSignalingState("stable"),e.type==="answer"&&(_o("caller start connect"),this.connect().catch(o=>{_o("connect failed",o),this.secureManager.setConnectionState("failed")})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation()}addTransceiver(t,e={}){let r=this.findOrCreateTransport(),n=this.transceiverManager.addTransceiver(t,r,e);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),n}addTrack(t,e){if(this.isClosed)throw new Error("is closed");let r=this.transceiverManager.addTrack(t,e);if(!r.dtlsTransport){let n=this.findOrCreateTransport();r.setDtlsTransport(n)}return this.needNegotiation(),r.sender}async createAnswer(){return this.assertNotClosed(),await this.secureManager.ensureCerts(),this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON()}assertNotClosed(){if(this.isClosed)throw new Error("RTCPeerConnection is closed")}setSignalingState(t){_o("signalingStateChange",t),this.signalingState=t,this.signalingStateChange.execute(t),this.onsignalingstatechange&&this.onsignalingstatechange({})}createPeerConnectionStats(){let t=Zu();return{type:"peer-connection",id:vr("peer-connection"),timestamp:t,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(t){let e=[];e.push(this.createPeerConnectionStats());let r=await this.transceiverManager.getStats(t);e.push(...r);let n=await this.secureManager.getStats();if(e.push(...n),this.sctpTransport){let s=await this.sctpManager.getStats();s&&e.push(...s)}return new OG(e)}async close(){this.isClosed||(this.isClosed=!0,this.setSignalingState("closed"),this.transceiverManager.close(),await this.secureManager.close(),await this.sctpManager.close(),this.onDataChannel.allUnsubscribe(),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.signalingStateChange.allUnsubscribe(),this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),_o("peerConnection closed"))}},q8=(t,e)=>t.find(r=>r.mimeType.toLowerCase()===e.mimeType.toLowerCase())?e:void 0;nge=EW(),sge=wt("werift:packages/webrtc/src/media/rtpTransceiverManager.ts"),CW=class{constructor(t,e,r){this.cname=t,this.config=e,this.router=r}transceivers=[];onTransceiverAdded=new Be;onRemoteTransceiverAdded=new Be;onTrack=new Be;onNegotiationNeeded=new Be;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(t=>t.sender)}getReceivers(){return this.getTransceivers().map(t=>t.receiver)}getTransceiverByMLineIndex(t){return this.transceivers.find(e=>e.mLineIndex===t)}pushTransceiver(t){this.transceivers.push(t)}replaceTransceiver(t,e){this.transceivers[e]=t}addTransceiver(t,e,r={}){let n=typeof t=="string"?t:t.kind,s=r.direction||"sendrecv",i=new SW(t),o=new M5(this.config,n,i.ssrc),a=new NG(n,e,o,i,s);a.options=r,this.router.registerRtpSender(a.sender);let c=this.transceivers.findIndex(l=>l.currentDirection==="inactive"&&!l.usedForSender),u=this.transceivers.find(l=>l.currentDirection==="inactive"&&!l.usedForSender);return c>-1&&u?(this.replaceTransceiver(a,c),a.mLineIndex=u.mLineIndex,a.mid=u.mid,u.setCurrentDirection(void 0)):this.pushTransceiver(a),this.onTransceiverAdded.execute(a),a}addTrack(t,e){if(this.getSenders().find(s=>s.track?.uuid===t.uuid))throw new Error("Track already added");let r=this.transceivers.find(s=>s.sender.track==null&&s.kind===t.kind&&pA.includes(s.direction)===!0);if(r)return r.sender.registerTrack(t),r;let n=this.transceivers.find(s=>s.sender.track==null&&s.kind===t.kind&&pA.includes(s.direction)===!1&&!s.usedForSender);if(n){switch(n.sender.registerTrack(t),n.direction){case"recvonly":n.setDirection("sendrecv");break;case"inactive":n.setDirection("sendonly");break}return n}else return this.addTransceiver(t,void 0,{direction:"sendrecv"})}removeTrack(t){if(!this.getSenders().find(({ssrc:r})=>t.ssrc===r))throw new Error("Sender does not exist");let e=this.transceivers.find(({sender:{ssrc:r}})=>t.ssrc===r);if(!e)throw new Error("No matching transceiver found");if(t.stop(),e.currentDirection==="recvonly"){this.onNegotiationNeeded.execute();return}e.stopping||e.stopped?e.setDirection("inactive"):e.direction==="sendrecv"?e.setDirection("recvonly"):(e.direction==="sendonly"||e.direction==="recvonly")&&e.setDirection("inactive")}assignTransceiverCodecs(t){let e=this.config.codecs[t.kind].filter(r=>{switch(r.direction){case"recvonly":return!!eme.includes(t.direction);case"sendonly":return!!pA.includes(t.direction);case"sendrecv":return!![S5,w5,v5].includes(t.direction);case"all":return!0;default:return!1}});t.codecs=e}getLocalRtpParams(t){if(t.mid==null)throw new Error("mid not assigned");return{codecs:t.codecs,muxId:t.mid,headerExtensions:t.headerExtensions,rtcp:{cname:this.cname,ssrc:t.sender.ssrc,mux:!0}}}getRemoteRtpParams(t,e){return{muxId:t.rtp.muxId,rtcp:t.rtp.rtcp,codecs:e.codecs,headerExtensions:e.headerExtensions,encodings:Object.values(e.codecs.reduce((n,s)=>{if(s.name.toLowerCase()==="rtx"){let i=Yb(s.parameters??""),o=n[i.apt];return o&&t.ssrc.length===2&&(o.rtx=new CG({ssrc:t.ssrc[1].ssrc})),n}return n[s.payloadType]=new kG({ssrc:t.ssrc[0]?.ssrc,payloadType:s.payloadType}),n},{}))}}setRemoteRTP(t,e,r,n){if(t.mid||(t.mid=e.rtp.muxId),t.mLineIndex=n,t.codecs=e.rtp.codecs.filter(a=>{let c=this.config.codecs[e.kind]||[],u=q8(c,a);if(!u)return!1;if(u?.name.toLowerCase()==="rtx"){let d=Yb(u.parameters??"").apt,f=e.rtp.codecs.find(p=>p.payloadType===d);return f?!!q8(c,f):!1}return!0}),sge("negotiated codecs",t.codecs),t.codecs.length===0)throw new Error("negotiate codecs failed.");t.headerExtensions=e.rtp.headerExtensions.filter(a=>(this.config.headerExtensions[e.kind]||[]).find(c=>c.uri===a.uri));let s=e.direction??"inactive",i=zG(s);["answer","pranswer"].includes(r)?t.setCurrentDirection(i):t.offerDirection=i;let o=this.getLocalRtpParams(t);if(t.sender.prepareSend(o),["recvonly","sendrecv"].includes(t.direction)){let a=this.getRemoteRtpParams(e,t);for(let c of e.simulcastParameters)this.router.registerRtpReceiverByRid(t,c,a);t.receiver.prepareReceive(a),this.router.registerRtpReceiverBySsrc(t,a)}if(["sendonly","sendrecv"].includes(s)){if(e.msid){let[a,c]=e.msid.split(" ");t.receiver.remoteStreamId=a,t.receiver.remoteTrackId=c}this.onTrack.execute({track:t.receiver.track,transceiver:t,stream:new MG({id:t.receiver.remoteStreamId,tracks:[t.receiver.track]})})}e.ssrc[0]?.ssrc&&t.receiver.setupTWCC(e.ssrc[0].ssrc)}async getStats(t){let e=[];for(let r of this.transceivers){let n=!t||r.sender.track===t||r.receiver.track===t;if(r.sender){let s=await r.sender.getStats();if(s)for(let i of s)i.type==="outbound-rtp"||i.type==="media-source"?n&&e.push(i):e.push(i)}if(r.receiver){let s=await r.receiver.getStats();if(s)for(let i of s)i.type==="inbound-rtp"||i.type==="remote-outbound-rtp"?n&&e.push(i):e.push(i)}if(n){let s=r.getCodecStats();s&&e.push(...s)}}return e}close(){for(let t of this.transceivers)t.receiver.stop(),t.sender.stop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}},ige=["stable","have-local-offer","have-remote-offer","have-local-pranswer","have-remote-pranswer","closed"],oge=["closed","failed","disconnected","new","connecting","connected"]});var UW={};$a(UW,{SERVICE_TYPE:()=>L5,accountFingerprint:()=>D5,advertise:()=>gge,browse:()=>DW,osTag:()=>jW,scan:()=>yge});function jW(){let t=process.platform;return t==="darwin"?"mac":t==="win32"?"win":t==="linux"?"linux":"other"}function zW(t){return JSON.stringify(["oioxo-advert",t.v,t.acct,t.dev,t.os,t.name,t.nonce])}async function D5(t){let e=new TextEncoder().encode("oioxo-acct:"+t),r=await crypto.subtle.digest("SHA-256",e);return Buffer.from(new Uint8Array(r)).toString("base64url").slice(0,22)}async function LW(){try{let e=await import("bonjour-service");return e.Bonjour??e.default??null}catch{return null}}async function gge(t){let e=await LW();if(!e)return{stop:()=>{}};let r=await D5(t.accountKey),n=Buffer.from(crypto.getRandomValues(new Uint8Array(8))).toString("base64url"),s={v:2,acct:r,dev:t.identity.deviceId,os:jW(),name:t.label,nonce:n},i=await t.identity.sign(zW(s)),o=new e,a=o.publish({name:"OIOXO "+t.identity.deviceId.slice(0,6),type:L5,protocol:"tcp",port:t.port,txt:{v:String(2),acct:r,dev:s.dev,os:s.os,name:t.label,nonce:n,sig:i}});return{stop:()=>{try{a.stop(()=>o.destroy())}catch{}}}}async function DW(t){let e=await LW();if(!e)return{stop:()=>{}};let r=await D5(t.accountKey),n=new e,s=new Set,i=n.find({type:L5,protocol:"tcp"},o=>{(async()=>{let a=o.txt;if(!a||a.acct!==r)return;let c=a.dev;if(!c||s.has(c)||!a.sig||!a.name||!a.nonce)return;let u=zW({v:Number(a.v)||2,acct:a.acct,dev:c,os:a.os||"other",name:a.name,nonce:a.nonce}),l=await t.verify(c,a.sig,u).catch(()=>!1);s.add(c);let d=o.referer?.address||o.addresses&&o.addresses[0]||"",f=["mac","win","linux"].includes(a.os)?a.os:"other";t.onDevice({deviceId:c,label:a.name,os:f,host:d,port:o.port,trusted:l})})()});return{stop:()=>{try{i.stop(),n.destroy()}catch{}}}}async function yge(t){let e=[],{stop:r}=await DW({accountKey:t.accountKey,verify:t.verify,onDevice:n=>e.push(n)});return await new Promise(n=>setTimeout(n,t.ms??2500)),r(),e}var L5,qW=mr(()=>{"use strict";L5="oioxo"});var U1=v(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.regexpCode=ar.getEsmExportName=ar.getProperty=ar.safeStringify=ar.stringify=ar.strConcat=ar.addCodeArg=ar.str=ar._=ar.nil=ar._Code=ar.Name=ar.IDENTIFIER=ar._CodeOrName=void 0;var L1=class{};ar._CodeOrName=L1;ar.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var zf=class extends L1{constructor(e){if(super(),!ar.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ar.Name=zf;var qi=class extends L1{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof zf&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ar._Code=qi;ar.nil=new qi("");function GY(t,...e){let r=[t[0]],n=0;for(;n<e.length;)E9(r,e[n]),r.push(t[++n]);return new qi(r)}ar._=GY;var A9=new qi("+");function WY(t,...e){let r=[D1(t[0])],n=0;for(;n<e.length;)r.push(A9),E9(r,e[n]),r.push(A9,D1(t[++n]));return x_e(r),new qi(r)}ar.str=WY;function E9(t,e){e instanceof qi?t.push(...e._items):e instanceof zf?t.push(e):t.push(v_e(e))}ar.addCodeArg=E9;function x_e(t){let e=1;for(;e<t.length-1;){if(t[e]===A9){let r=b_e(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function b_e(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof zf||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof zf))return`"${t}${e.slice(1)}`}function __e(t,e){return e.emptyStr()?t:t.emptyStr()?e:WY`${t}${e}`}ar.strConcat=__e;function v_e(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:D1(Array.isArray(t)?t.join(","):t)}function w_e(t){return new qi(D1(t))}ar.stringify=w_e;function D1(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ar.safeStringify=D1;function S_e(t){return typeof t=="string"&&ar.IDENTIFIER.test(t)?new qi(`.${t}`):GY`[${t}]`}ar.getProperty=S_e;function A_e(t){if(typeof t=="string"&&ar.IDENTIFIER.test(t))return new qi(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ar.getEsmExportName=A_e;function E_e(t){return new qi(t.toString())}ar.regexpCode=E_e});var T9=v(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.ValueScope=Js.ValueScopeName=Js.Scope=Js.varKinds=Js.UsedValueState=void 0;var Xs=U1(),C9=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},rC;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(rC||(Js.UsedValueState=rC={}));Js.varKinds={const:new Xs.Name("const"),let:new Xs.Name("let"),var:new Xs.Name("var")};var nC=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Xs.Name?e:this.name(e)}name(e){return new Xs.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Js.Scope=nC;var sC=class extends Xs.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Xs._)`.${new Xs.Name(r)}[${n}]`}};Js.ValueScopeName=sC;var C_e=(0,Xs._)`\n`,k9=class extends nC{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?C_e:Xs.nil}}get(){return this._scope}name(e){return new sC(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:i}=s,o=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let l=a.get(o);if(l)return l}else a=this._values[i]=new Map;a.set(o,s);let c=this._scope[i]||(this._scope[i]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:i,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Xs._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let i=Xs.nil;for(let o in e){let a=e[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,rC.Started);let l=r(u);if(l){let d=this.opts.es5?Js.varKinds.var:Js.varKinds.const;i=(0,Xs._)`${i}${d} ${u} = ${l};${this.opts._n}`}else if(l=s?.(u))i=(0,Xs._)`${i}${l}${this.opts._n}`;else throw new C9(u);c.set(u,rC.Completed)})}return i}};Js.ValueScope=k9});var Bt=v(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.or=jt.and=jt.not=jt.CodeGen=jt.operators=jt.varKinds=jt.ValueScopeName=jt.ValueScope=jt.Scope=jt.Name=jt.regexpCode=jt.stringify=jt.getProperty=jt.nil=jt.strConcat=jt.str=jt._=void 0;var Wt=U1(),Io=T9(),sl=U1();Object.defineProperty(jt,"_",{enumerable:!0,get:function(){return sl._}});Object.defineProperty(jt,"str",{enumerable:!0,get:function(){return sl.str}});Object.defineProperty(jt,"strConcat",{enumerable:!0,get:function(){return sl.strConcat}});Object.defineProperty(jt,"nil",{enumerable:!0,get:function(){return sl.nil}});Object.defineProperty(jt,"getProperty",{enumerable:!0,get:function(){return sl.getProperty}});Object.defineProperty(jt,"stringify",{enumerable:!0,get:function(){return sl.stringify}});Object.defineProperty(jt,"regexpCode",{enumerable:!0,get:function(){return sl.regexpCode}});Object.defineProperty(jt,"Name",{enumerable:!0,get:function(){return sl.Name}});var cC=T9();Object.defineProperty(jt,"Scope",{enumerable:!0,get:function(){return cC.Scope}});Object.defineProperty(jt,"ValueScope",{enumerable:!0,get:function(){return cC.ValueScope}});Object.defineProperty(jt,"ValueScopeName",{enumerable:!0,get:function(){return cC.ValueScopeName}});Object.defineProperty(jt,"varKinds",{enumerable:!0,get:function(){return cC.varKinds}});jt.operators={GT:new Wt._Code(">"),GTE:new Wt._Code(">="),LT:new Wt._Code("<"),LTE:new Wt._Code("<="),EQ:new Wt._Code("==="),NEQ:new Wt._Code("!=="),NOT:new Wt._Code("!"),OR:new Wt._Code("||"),AND:new Wt._Code("&&"),ADD:new Wt._Code("+")};var jc=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},I9=class extends jc{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Io.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Y0(this.rhs,e,r)),this}get names(){return this.rhs instanceof Wt._CodeOrName?this.rhs.names:{}}},iC=class extends jc{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Wt.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Y0(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Wt.Name?{}:{...this.lhs.names};return aC(e,this.rhs)}},P9=class extends iC{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},R9=class extends jc{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},O9=class extends jc{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},N9=class extends jc{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},B9=class extends jc{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Y0(this.code,e,r),this}get names(){return this.code instanceof Wt._CodeOrName?this.code.names:{}}},q1=class extends jc{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let i=n[s];i.optimizeNames(e,r)||(k_e(e,i.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Uf(e,r.names),{})}},zc=class extends q1{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},$9=class extends q1{},J0=class extends zc{};J0.kind="else";var Lf=class t extends zc{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new J0(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(XY(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Y0(this.condition,e,r),this}get names(){let e=super.names;return aC(e,this.condition),this.else&&Uf(e,this.else.names),e}};Lf.kind="if";var Df=class extends zc{};Df.kind="for";var M9=class extends Df{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Y0(this.iteration,e,r),this}get names(){return Uf(super.names,this.iteration.names)}},j9=class extends Df{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?Io.varKinds.var:this.varKind,{name:n,from:s,to:i}=this;return`for(${r} ${n}=${s}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){let e=aC(super.names,this.from);return aC(e,this.to)}},oC=class extends Df{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Y0(this.iterable,e,r),this}get names(){return Uf(super.names,this.iterable.names)}},H1=class extends zc{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};H1.kind="func";var F1=class extends q1{render(e){return"return "+super.render(e)}};F1.kind="return";var z9=class extends zc{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Uf(e,this.catch.names),this.finally&&Uf(e,this.finally.names),e}},V1=class extends zc{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};V1.kind="catch";var K1=class extends zc{render(e){return"finally"+super.render(e)}};K1.kind="finally";var L9=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
191
|
+
`:""},this._extScope=e,this._scope=new Io.Scope({parent:e}),this._nodes=[new $9]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let i=this._scope.toName(r);return n!==void 0&&s&&(this._constants[i.str]=n),this._leafNode(new I9(e,i,n)),i}const(e,r,n){return this._def(Io.varKinds.const,e,r,n)}let(e,r,n){return this._def(Io.varKinds.let,e,r,n)}var(e,r,n){return this._def(Io.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new iC(e,r,n))}add(e,r){return this._leafNode(new P9(e,jt.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Wt.nil&&this._leafNode(new B9(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,Wt.addCodeArg)(r,s));return r.push("}"),new Wt._Code(r)}if(e,r,n){if(this._blockNode(new Lf(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Lf(e))}else(){return this._elseNode(new J0)}endIf(){return this._endBlockNode(Lf,J0)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new M9(e),r)}forRange(e,r,n,s,i=this.opts.es5?Io.varKinds.var:Io.varKinds.let){let o=this._scope.toName(e);return this._for(new j9(i,o,r,n),()=>s(o))}forOf(e,r,n,s=Io.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let o=r instanceof Wt.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Wt._)`${o}.length`,a=>{this.var(i,(0,Wt._)`${o}[${a}]`),n(i)})}return this._for(new oC("of",s,i,r),()=>n(i))}forIn(e,r,n,s=this.opts.es5?Io.varKinds.var:Io.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Wt._)`Object.keys(${r})`,n);let i=this._scope.toName(e);return this._for(new oC("in",s,i,r),()=>n(i))}endFor(){return this._endBlockNode(Df)}label(e){return this._leafNode(new R9(e))}break(e){return this._leafNode(new O9(e))}return(e){let r=new F1;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(F1)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new z9;if(this._blockNode(s),this.code(e),r){let i=this.name("e");this._currNode=s.catch=new V1(i),r(i)}return n&&(this._currNode=s.finally=new K1,this.code(n)),this._endBlockNode(V1,K1)}throw(e){return this._leafNode(new N9(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Wt.nil,n,s){return this._blockNode(new H1(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(H1)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Lf))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};jt.CodeGen=L9;function Uf(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function aC(t,e){return e instanceof Wt._CodeOrName?Uf(t,e.names):t}function Y0(t,e,r){if(t instanceof Wt.Name)return n(t);if(!s(t))return t;return new Wt._Code(t._items.reduce((i,o)=>(o instanceof Wt.Name&&(o=n(o)),o instanceof Wt._Code?i.push(...o._items):i.push(o),i),[]));function n(i){let o=r[i.str];return o===void 0||e[i.str]!==1?i:(delete e[i.str],o)}function s(i){return i instanceof Wt._Code&&i._items.some(o=>o instanceof Wt.Name&&e[o.str]===1&&r[o.str]!==void 0)}}function k_e(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function XY(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Wt._)`!${D9(t)}`}jt.not=XY;var T_e=JY(jt.operators.AND);function I_e(...t){return t.reduce(T_e)}jt.and=I_e;var P_e=JY(jt.operators.OR);function R_e(...t){return t.reduce(P_e)}jt.or=R_e;function JY(t){return(e,r)=>e===Wt.nil?r:r===Wt.nil?e:(0,Wt._)`${D9(e)} ${t} ${D9(r)}`}function D9(t){return t instanceof Wt.Name?t:(0,Wt._)`(${t})`}});var tr=v(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.checkStrictMode=Ut.getErrorPath=Ut.Type=Ut.useFunc=Ut.setEvaluated=Ut.evaluatedPropsToName=Ut.mergeEvaluated=Ut.eachItem=Ut.unescapeJsonPointer=Ut.escapeJsonPointer=Ut.escapeFragment=Ut.unescapeFragment=Ut.schemaRefOrVal=Ut.schemaHasRulesButRef=Ut.schemaHasRules=Ut.checkUnknownRules=Ut.alwaysValidSchema=Ut.toHash=void 0;var Tr=Bt(),O_e=U1();function N_e(t){let e={};for(let r of t)e[r]=!0;return e}Ut.toHash=N_e;function B_e(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(eQ(t,e),!tQ(e,t.self.RULES.all))}Ut.alwaysValidSchema=B_e;function eQ(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let i in e)s[i]||sQ(t,`unknown keyword: "${i}"`)}Ut.checkUnknownRules=eQ;function tQ(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Ut.schemaHasRules=tQ;function $_e(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Ut.schemaHasRulesButRef=$_e;function M_e({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Tr._)`${r}`}return(0,Tr._)`${t}${e}${(0,Tr.getProperty)(n)}`}Ut.schemaRefOrVal=M_e;function j_e(t){return rQ(decodeURIComponent(t))}Ut.unescapeFragment=j_e;function z_e(t){return encodeURIComponent(q9(t))}Ut.escapeFragment=z_e;function q9(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Ut.escapeJsonPointer=q9;function rQ(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Ut.unescapeJsonPointer=rQ;function L_e(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Ut.eachItem=L_e;function YY({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,i,o,a)=>{let c=o===void 0?i:o instanceof Tr.Name?(i instanceof Tr.Name?t(s,i,o):e(s,i,o),o):i instanceof Tr.Name?(e(s,o,i),i):r(i,o);return a===Tr.Name&&!(c instanceof Tr.Name)?n(s,c):c}}Ut.mergeEvaluated={props:YY({mergeNames:(t,e,r)=>t.if((0,Tr._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Tr._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Tr._)`${r} || {}`).code((0,Tr._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Tr._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Tr._)`${r} || {}`),H9(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:nQ}),items:YY({mergeNames:(t,e,r)=>t.if((0,Tr._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Tr._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Tr._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Tr._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function nQ(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Tr._)`{}`);return e!==void 0&&H9(t,r,e),r}Ut.evaluatedPropsToName=nQ;function H9(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Tr._)`${e}${(0,Tr.getProperty)(n)}`,!0))}Ut.setEvaluated=H9;var QY={};function D_e(t,e){return t.scopeValue("func",{ref:e,code:QY[e.code]||(QY[e.code]=new O_e._Code(e.code))})}Ut.useFunc=D_e;var U9;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(U9||(Ut.Type=U9={}));function U_e(t,e,r){if(t instanceof Tr.Name){let n=e===U9.Num;return r?n?(0,Tr._)`"[" + ${t} + "]"`:(0,Tr._)`"['" + ${t} + "']"`:n?(0,Tr._)`"/" + ${t}`:(0,Tr._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Tr.getProperty)(t).toString():"/"+q9(t)}Ut.getErrorPath=U_e;function sQ(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Ut.checkStrictMode=sQ});var Lc=v(F9=>{"use strict";Object.defineProperty(F9,"__esModule",{value:!0});var ds=Bt(),q_e={data:new ds.Name("data"),valCxt:new ds.Name("valCxt"),instancePath:new ds.Name("instancePath"),parentData:new ds.Name("parentData"),parentDataProperty:new ds.Name("parentDataProperty"),rootData:new ds.Name("rootData"),dynamicAnchors:new ds.Name("dynamicAnchors"),vErrors:new ds.Name("vErrors"),errors:new ds.Name("errors"),this:new ds.Name("this"),self:new ds.Name("self"),scope:new ds.Name("scope"),json:new ds.Name("json"),jsonPos:new ds.Name("jsonPos"),jsonLen:new ds.Name("jsonLen"),jsonPart:new ds.Name("jsonPart")};F9.default=q_e});var Z1=v(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.extendErrors=fs.resetErrorsCount=fs.reportExtraError=fs.reportError=fs.keyword$DataError=fs.keywordError=void 0;var rr=Bt(),uC=tr(),Es=Lc();fs.keywordError={message:({keyword:t})=>(0,rr.str)`must pass "${t}" keyword validation`};fs.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,rr.str)`"${t}" keyword must be ${e} ($data)`:(0,rr.str)`"${t}" keyword is invalid ($data)`};function H_e(t,e=fs.keywordError,r,n){let{it:s}=t,{gen:i,compositeRule:o,allErrors:a}=s,c=aQ(t,e,r);n??(o||a)?iQ(i,c):oQ(s,(0,rr._)`[${c}]`)}fs.reportError=H_e;function F_e(t,e=fs.keywordError,r){let{it:n}=t,{gen:s,compositeRule:i,allErrors:o}=n,a=aQ(t,e,r);iQ(s,a),i||o||oQ(n,Es.default.vErrors)}fs.reportExtraError=F_e;function V_e(t,e){t.assign(Es.default.errors,e),t.if((0,rr._)`${Es.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,rr._)`${Es.default.vErrors}.length`,e),()=>t.assign(Es.default.vErrors,null)))}fs.resetErrorsCount=V_e;function K_e({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:i}){if(s===void 0)throw new Error("ajv implementation error");let o=t.name("err");t.forRange("i",s,Es.default.errors,a=>{t.const(o,(0,rr._)`${Es.default.vErrors}[${a}]`),t.if((0,rr._)`${o}.instancePath === undefined`,()=>t.assign((0,rr._)`${o}.instancePath`,(0,rr.strConcat)(Es.default.instancePath,i.errorPath))),t.assign((0,rr._)`${o}.schemaPath`,(0,rr.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,rr._)`${o}.schema`,r),t.assign((0,rr._)`${o}.data`,n))})}fs.extendErrors=K_e;function iQ(t,e){let r=t.const("err",e);t.if((0,rr._)`${Es.default.vErrors} === null`,()=>t.assign(Es.default.vErrors,(0,rr._)`[${r}]`),(0,rr._)`${Es.default.vErrors}.push(${r})`),t.code((0,rr._)`${Es.default.errors}++`)}function oQ(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,rr._)`new ${t.ValidationError}(${e})`):(r.assign((0,rr._)`${n}.errors`,e),r.return(!1))}var qf={keyword:new rr.Name("keyword"),schemaPath:new rr.Name("schemaPath"),params:new rr.Name("params"),propertyName:new rr.Name("propertyName"),message:new rr.Name("message"),schema:new rr.Name("schema"),parentSchema:new rr.Name("parentSchema")};function aQ(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,rr._)`{}`:Z_e(t,e,r)}function Z_e(t,e,r={}){let{gen:n,it:s}=t,i=[G_e(s,r),W_e(t,r)];return X_e(t,e,i),n.object(...i)}function G_e({errorPath:t},{instancePath:e}){let r=e?(0,rr.str)`${t}${(0,uC.getErrorPath)(e,uC.Type.Str)}`:t;return[Es.default.instancePath,(0,rr.strConcat)(Es.default.instancePath,r)]}function W_e({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,rr.str)`${e}/${t}`;return r&&(s=(0,rr.str)`${s}${(0,uC.getErrorPath)(r,uC.Type.Str)}`),[qf.schemaPath,s]}function X_e(t,{params:e,message:r},n){let{keyword:s,data:i,schemaValue:o,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([qf.keyword,s],[qf.params,typeof e=="function"?e(t):e||(0,rr._)`{}`]),c.messages&&n.push([qf.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([qf.schema,o],[qf.parentSchema,(0,rr._)`${l}${d}`],[Es.default.data,i]),u&&n.push([qf.propertyName,u])}});var uQ=v(Q0=>{"use strict";Object.defineProperty(Q0,"__esModule",{value:!0});Q0.boolOrEmptySchema=Q0.topBoolOrEmptySchema=void 0;var J_e=Z1(),Y_e=Bt(),Q_e=Lc(),eve={message:"boolean schema is false"};function tve(t){let{gen:e,schema:r,validateName:n}=t;r===!1?cQ(t,!1):typeof r=="object"&&r.$async===!0?e.return(Q_e.default.data):(e.assign((0,Y_e._)`${n}.errors`,null),e.return(!0))}Q0.topBoolOrEmptySchema=tve;function rve(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),cQ(t)):r.var(e,!0)}Q0.boolOrEmptySchema=rve;function cQ(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,J_e.reportError)(s,eve,void 0,e)}});var V9=v(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.getRules=em.isJSONType=void 0;var nve=["string","number","integer","boolean","null","object","array"],sve=new Set(nve);function ive(t){return typeof t=="string"&&sve.has(t)}em.isJSONType=ive;function ove(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}em.getRules=ove});var K9=v(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});il.shouldUseRule=il.shouldUseGroup=il.schemaHasRulesForType=void 0;function ave({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&lQ(t,n)}il.schemaHasRulesForType=ave;function lQ(t,e){return e.rules.some(r=>dQ(t,r))}il.shouldUseGroup=lQ;function dQ(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}il.shouldUseRule=dQ});var G1=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.reportTypeError=hs.checkDataTypes=hs.checkDataType=hs.coerceAndCheckDataType=hs.getJSONTypes=hs.getSchemaTypes=hs.DataType=void 0;var cve=V9(),uve=K9(),lve=Z1(),Pt=Bt(),fQ=tr(),tm;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(tm||(hs.DataType=tm={}));function dve(t){let e=hQ(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}hs.getSchemaTypes=dve;function hQ(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(cve.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}hs.getJSONTypes=hQ;function fve(t,e){let{gen:r,data:n,opts:s}=t,i=hve(e,s.coerceTypes),o=e.length>0&&!(i.length===0&&e.length===1&&(0,uve.schemaHasRulesForType)(t,e[0]));if(o){let a=G9(e,n,s.strictNumbers,tm.Wrong);r.if(a,()=>{i.length?pve(t,e,i):W9(t)})}return o}hs.coerceAndCheckDataType=fve;var pQ=new Set(["string","number","integer","boolean","null"]);function hve(t,e){return e?t.filter(r=>pQ.has(r)||e==="array"&&r==="array"):[]}function pve(t,e,r){let{gen:n,data:s,opts:i}=t,o=n.let("dataType",(0,Pt._)`typeof ${s}`),a=n.let("coerced",(0,Pt._)`undefined`);i.coerceTypes==="array"&&n.if((0,Pt._)`${o} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,Pt._)`${s}[0]`).assign(o,(0,Pt._)`typeof ${s}`).if(G9(e,s,i.strictNumbers),()=>n.assign(a,s))),n.if((0,Pt._)`${a} !== undefined`);for(let u of r)(pQ.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);n.else(),W9(t),n.endIf(),n.if((0,Pt._)`${a} !== undefined`,()=>{n.assign(s,a),mve(t,a)});function c(u){switch(u){case"string":n.elseIf((0,Pt._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,Pt._)`"" + ${s}`).elseIf((0,Pt._)`${s} === null`).assign(a,(0,Pt._)`""`);return;case"number":n.elseIf((0,Pt._)`${o} == "boolean" || ${s} === null
|
|
192
|
+
|| (${o} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,Pt._)`+${s}`);return;case"integer":n.elseIf((0,Pt._)`${o} === "boolean" || ${s} === null
|
|
193
|
+
|| (${o} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,Pt._)`+${s}`);return;case"boolean":n.elseIf((0,Pt._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,Pt._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Pt._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Pt._)`${o} === "string" || ${o} === "number"
|
|
194
|
+
|| ${o} === "boolean" || ${s} === null`).assign(a,(0,Pt._)`[${s}]`)}}}function mve({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Pt._)`${e} !== undefined`,()=>t.assign((0,Pt._)`${e}[${r}]`,n))}function Z9(t,e,r,n=tm.Correct){let s=n===tm.Correct?Pt.operators.EQ:Pt.operators.NEQ,i;switch(t){case"null":return(0,Pt._)`${e} ${s} null`;case"array":i=(0,Pt._)`Array.isArray(${e})`;break;case"object":i=(0,Pt._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=o((0,Pt._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=o();break;default:return(0,Pt._)`typeof ${e} ${s} ${t}`}return n===tm.Correct?i:(0,Pt.not)(i);function o(a=Pt.nil){return(0,Pt.and)((0,Pt._)`typeof ${e} == "number"`,a,r?(0,Pt._)`isFinite(${e})`:Pt.nil)}}hs.checkDataType=Z9;function G9(t,e,r,n){if(t.length===1)return Z9(t[0],e,r,n);let s,i=(0,fQ.toHash)(t);if(i.array&&i.object){let o=(0,Pt._)`typeof ${e} != "object"`;s=i.null?o:(0,Pt._)`!${e} || ${o}`,delete i.null,delete i.array,delete i.object}else s=Pt.nil;i.number&&delete i.integer;for(let o in i)s=(0,Pt.and)(s,Z9(o,e,r,n));return s}hs.checkDataTypes=G9;var gve={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Pt._)`{type: ${t}}`:(0,Pt._)`{type: ${e}}`};function W9(t){let e=yve(t);(0,lve.reportError)(e,gve)}hs.reportTypeError=W9;function yve(t){let{gen:e,data:r,schema:n}=t,s=(0,fQ.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var gQ=v(lC=>{"use strict";Object.defineProperty(lC,"__esModule",{value:!0});lC.assignDefaults=void 0;var rm=Bt(),xve=tr();function bve(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)mQ(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,i)=>mQ(t,i,s.default))}lC.assignDefaults=bve;function mQ(t,e,r){let{gen:n,compositeRule:s,data:i,opts:o}=t;if(r===void 0)return;let a=(0,rm._)`${i}${(0,rm.getProperty)(e)}`;if(s){(0,xve.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,rm._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,rm._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,rm._)`${a} = ${(0,rm.stringify)(r)}`)}});var Hi=v(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.validateUnion=Sr.validateArray=Sr.usePattern=Sr.callValidateCode=Sr.schemaProperties=Sr.allSchemaProperties=Sr.noPropertyInData=Sr.propertyInData=Sr.isOwnProperty=Sr.hasPropFunc=Sr.reportMissingProp=Sr.checkMissingProp=Sr.checkReportMissingProp=void 0;var Hr=Bt(),X9=tr(),ol=Lc(),_ve=tr();function vve(t,e){let{gen:r,data:n,it:s}=t;r.if(Y9(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Hr._)`${e}`},!0),t.error()})}Sr.checkReportMissingProp=vve;function wve({gen:t,data:e,it:{opts:r}},n,s){return(0,Hr.or)(...n.map(i=>(0,Hr.and)(Y9(t,e,i,r.ownProperties),(0,Hr._)`${s} = ${i}`)))}Sr.checkMissingProp=wve;function Sve(t,e){t.setParams({missingProperty:e},!0),t.error()}Sr.reportMissingProp=Sve;function yQ(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Hr._)`Object.prototype.hasOwnProperty`})}Sr.hasPropFunc=yQ;function J9(t,e,r){return(0,Hr._)`${yQ(t)}.call(${e}, ${r})`}Sr.isOwnProperty=J9;function Ave(t,e,r,n){let s=(0,Hr._)`${e}${(0,Hr.getProperty)(r)} !== undefined`;return n?(0,Hr._)`${s} && ${J9(t,e,r)}`:s}Sr.propertyInData=Ave;function Y9(t,e,r,n){let s=(0,Hr._)`${e}${(0,Hr.getProperty)(r)} === undefined`;return n?(0,Hr.or)(s,(0,Hr.not)(J9(t,e,r))):s}Sr.noPropertyInData=Y9;function xQ(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Sr.allSchemaProperties=xQ;function Eve(t,e){return xQ(e).filter(r=>!(0,X9.alwaysValidSchema)(t,e[r]))}Sr.schemaProperties=Eve;function Cve({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:i},it:o},a,c,u){let l=u?(0,Hr._)`${t}, ${e}, ${n}${s}`:e,d=[[ol.default.instancePath,(0,Hr.strConcat)(ol.default.instancePath,i)],[ol.default.parentData,o.parentData],[ol.default.parentDataProperty,o.parentDataProperty],[ol.default.rootData,ol.default.rootData]];o.opts.dynamicRef&&d.push([ol.default.dynamicAnchors,ol.default.dynamicAnchors]);let f=(0,Hr._)`${l}, ${r.object(...d)}`;return c!==Hr.nil?(0,Hr._)`${a}.call(${c}, ${f})`:(0,Hr._)`${a}(${f})`}Sr.callValidateCode=Cve;var kve=(0,Hr._)`new RegExp`;function Tve({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,i=s(r,n);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,Hr._)`${s.code==="new RegExp"?kve:(0,_ve.useFunc)(t,s)}(${r}, ${n})`})}Sr.usePattern=Tve;function Ive(t){let{gen:e,data:r,keyword:n,it:s}=t,i=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(i,!0),o(()=>e.break()),i;function o(a){let c=e.const("len",(0,Hr._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:X9.Type.Num},i),e.if((0,Hr.not)(i),a)})}}Sr.validateArray=Ive;function Pve(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,X9.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(o,(0,Hr._)`${o} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Hr.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}Sr.validateUnion=Pve});var vQ=v(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.validateKeywordUsage=Ta.validSchemaType=Ta.funcKeywordCode=Ta.macroKeywordCode=void 0;var Cs=Bt(),Hf=Lc(),Rve=Hi(),Ove=Z1();function Nve(t,e){let{gen:r,keyword:n,schema:s,parentSchema:i,it:o}=t,a=e.macro.call(o.self,s,i,o),c=_Q(r,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Cs.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ta.macroKeywordCode=Nve;function Bve(t,e){var r;let{gen:n,keyword:s,schema:i,parentSchema:o,$data:a,it:c}=t;Mve(c,e);let u=!a&&e.compile?e.compile.call(c.self,i,o,c):e.validate,l=_Q(n,s,u),d=n.let("valid");t.block$data(d,f),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function f(){if(e.errors===!1)y(),e.modifying&&bQ(t),_(()=>t.error());else{let S=e.async?p():m();e.modifying&&bQ(t),_(()=>$ve(t,S))}}function p(){let S=n.let("ruleErrs",null);return n.try(()=>y((0,Cs._)`await `),C=>n.assign(d,!1).if((0,Cs._)`${C} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,Cs._)`${C}.errors`),()=>n.throw(C))),S}function m(){let S=(0,Cs._)`${l}.errors`;return n.assign(S,null),y(Cs.nil),S}function y(S=e.async?(0,Cs._)`await `:Cs.nil){let C=c.opts.passContext?Hf.default.this:Hf.default.self,E=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Cs._)`${S}${(0,Rve.callValidateCode)(t,l,C,E)}`,e.modifying)}function _(S){var C;n.if((0,Cs.not)((C=e.valid)!==null&&C!==void 0?C:d),S)}}Ta.funcKeywordCode=Bve;function bQ(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Cs._)`${n.parentData}[${n.parentDataProperty}]`))}function $ve(t,e){let{gen:r}=t;r.if((0,Cs._)`Array.isArray(${e})`,()=>{r.assign(Hf.default.vErrors,(0,Cs._)`${Hf.default.vErrors} === null ? ${e} : ${Hf.default.vErrors}.concat(${e})`).assign(Hf.default.errors,(0,Cs._)`${Hf.default.vErrors}.length`),(0,Ove.extendErrors)(t)},()=>t.error())}function Mve({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function _Q(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Cs.stringify)(r)})}function jve(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ta.validSchemaType=jve;function zve({schema:t,opts:e,self:r,errSchemaPath:n},s,i){if(Array.isArray(s.keyword)?!s.keyword.includes(i):s.keyword!==i)throw new Error("ajv implementation error");let o=s.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${o.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ta.validateKeywordUsage=zve});var SQ=v(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.extendSubschemaMode=al.extendSubschemaData=al.getSubschema=void 0;var Ia=Bt(),wQ=tr();function Lve(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:i,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ia._)`${t.schemaPath}${(0,Ia.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ia._)`${t.schemaPath}${(0,Ia.getProperty)(e)}${(0,Ia.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,wQ.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||i===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:o,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}al.getSubschema=Lve;function Dve(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:i,propertyName:o}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,Ia._)`${e.data}${(0,Ia.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Ia.str)`${u}${(0,wQ.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ia._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Ia.Name?s:a.let("data",s,!0);c(u),o!==void 0&&(t.propertyName=o)}i&&(t.dataTypes=i);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}al.extendSubschemaData=Dve;function Uve(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:i}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=r}al.extendSubschemaMode=Uve});var EQ=v((O7e,AQ)=>{"use strict";var cl=AQ.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};dC(e,n,s,t,"",t)};cl.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};cl.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};cl.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};cl.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function dC(t,e,r,n,s,i,o,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,i,o,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in cl.arrayKeywords)for(var f=0;f<d.length;f++)dC(t,e,r,d[f],s+"/"+l+"/"+f,i,s,l,n,f)}else if(l in cl.propsKeywords){if(d&&typeof d=="object")for(var p in d)dC(t,e,r,d[p],s+"/"+l+"/"+qve(p),i,s,l,n,p)}else(l in cl.keywords||t.allKeys&&!(l in cl.skipKeywords))&&dC(t,e,r,d,s+"/"+l,i,s,l,n)}r(n,s,i,o,a,c,u)}}function qve(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var W1=v(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.getSchemaRefs=Ys.resolveUrl=Ys.normalizeId=Ys._getFullPath=Ys.getFullPath=Ys.inlineRef=void 0;var Hve=tr(),Fve=tA(),Vve=EQ(),Kve=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Zve(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Q9(t):e?CQ(t)<=e:!1}Ys.inlineRef=Zve;var Gve=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Q9(t){for(let e in t){if(Gve.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Q9)||typeof r=="object"&&Q9(r))return!0}return!1}function CQ(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Kve.has(r)&&(typeof t[r]=="object"&&(0,Hve.eachItem)(t[r],n=>e+=CQ(n)),e===1/0))return 1/0}return e}function kQ(t,e="",r){r!==!1&&(e=nm(e));let n=t.parse(e);return TQ(t,n)}Ys.getFullPath=kQ;function TQ(t,e){return t.serialize(e).split("#")[0]+"#"}Ys._getFullPath=TQ;var Wve=/#\/?$/;function nm(t){return t?t.replace(Wve,""):""}Ys.normalizeId=nm;function Xve(t,e,r){return r=nm(r),t.resolve(e,r)}Ys.resolveUrl=Xve;var Jve=/^[a-z_][-a-z0-9._]*$/i;function Yve(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=nm(t[r]||e),i={"":s},o=kQ(n,s,!1),a={},c=new Set;return Vve(t,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let y=o+f,_=i[m];typeof d[r]=="string"&&(_=S.call(this,d[r])),C.call(this,d.$anchor),C.call(this,d.$dynamicAnchor),i[f]=_;function S(E){let B=this.opts.uriResolver.resolve;if(E=nm(_?B(_,E):E),c.has(E))throw l(E);c.add(E);let G=this.refs[E];return typeof G=="string"&&(G=this.refs[G]),typeof G=="object"?u(d,G.schema,E):E!==nm(y)&&(E[0]==="#"?(u(d,a[E],E),a[E]=d):this.refs[E]=y),E}function C(E){if(typeof E=="string"){if(!Jve.test(E))throw new Error(`invalid anchor "${E}"`);S.call(this,`#${E}`)}}}),a;function u(d,f,p){if(f!==void 0&&!Fve(d,f))throw l(p)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ys.getSchemaRefs=Yve});var Y1=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.getData=ul.KeywordCxt=ul.validateFunctionCode=void 0;var NQ=uQ(),IQ=G1(),tN=K9(),fC=G1(),Qve=gQ(),J1=vQ(),eN=SQ(),Je=Bt(),yt=Lc(),ewe=W1(),Dc=tr(),X1=Z1();function twe(t){if(MQ(t)&&(jQ(t),$Q(t))){swe(t);return}BQ(t,()=>(0,NQ.topBoolOrEmptySchema)(t))}ul.validateFunctionCode=twe;function BQ({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},i){s.code.es5?t.func(e,(0,Je._)`${yt.default.data}, ${yt.default.valCxt}`,n.$async,()=>{t.code((0,Je._)`"use strict"; ${PQ(r,s)}`),nwe(t,s),t.code(i)}):t.func(e,(0,Je._)`${yt.default.data}, ${rwe(s)}`,n.$async,()=>t.code(PQ(r,s)).code(i))}function rwe(t){return(0,Je._)`{${yt.default.instancePath}="", ${yt.default.parentData}, ${yt.default.parentDataProperty}, ${yt.default.rootData}=${yt.default.data}${t.dynamicRef?(0,Je._)`, ${yt.default.dynamicAnchors}={}`:Je.nil}}={}`}function nwe(t,e){t.if(yt.default.valCxt,()=>{t.var(yt.default.instancePath,(0,Je._)`${yt.default.valCxt}.${yt.default.instancePath}`),t.var(yt.default.parentData,(0,Je._)`${yt.default.valCxt}.${yt.default.parentData}`),t.var(yt.default.parentDataProperty,(0,Je._)`${yt.default.valCxt}.${yt.default.parentDataProperty}`),t.var(yt.default.rootData,(0,Je._)`${yt.default.valCxt}.${yt.default.rootData}`),e.dynamicRef&&t.var(yt.default.dynamicAnchors,(0,Je._)`${yt.default.valCxt}.${yt.default.dynamicAnchors}`)},()=>{t.var(yt.default.instancePath,(0,Je._)`""`),t.var(yt.default.parentData,(0,Je._)`undefined`),t.var(yt.default.parentDataProperty,(0,Je._)`undefined`),t.var(yt.default.rootData,yt.default.data),e.dynamicRef&&t.var(yt.default.dynamicAnchors,(0,Je._)`{}`)})}function swe(t){let{schema:e,opts:r,gen:n}=t;BQ(t,()=>{r.$comment&&e.$comment&&LQ(t),uwe(t),n.let(yt.default.vErrors,null),n.let(yt.default.errors,0),r.unevaluated&&iwe(t),zQ(t),fwe(t)})}function iwe(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Je._)`${r}.evaluated`),e.if((0,Je._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Je._)`${t.evaluated}.props`,(0,Je._)`undefined`)),e.if((0,Je._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Je._)`${t.evaluated}.items`,(0,Je._)`undefined`))}function PQ(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Je._)`/*# sourceURL=${r} */`:Je.nil}function owe(t,e){if(MQ(t)&&(jQ(t),$Q(t))){awe(t,e);return}(0,NQ.boolOrEmptySchema)(t,e)}function $Q({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function MQ(t){return typeof t.schema!="boolean"}function awe(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&LQ(t),lwe(t),dwe(t);let i=n.const("_errs",yt.default.errors);zQ(t,i),n.var(e,(0,Je._)`${i} === ${yt.default.errors}`)}function jQ(t){(0,Dc.checkUnknownRules)(t),cwe(t)}function zQ(t,e){if(t.opts.jtd)return RQ(t,[],!1,e);let r=(0,IQ.getSchemaTypes)(t.schema),n=(0,IQ.coerceAndCheckDataType)(t,r);RQ(t,r,!n,e)}function cwe(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Dc.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function uwe(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Dc.checkStrictMode)(t,"default is ignored in the schema root")}function lwe(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,ewe.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function dwe(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function LQ({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let i=r.$comment;if(s.$comment===!0)t.code((0,Je._)`${yt.default.self}.logger.log(${i})`);else if(typeof s.$comment=="function"){let o=(0,Je.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Je._)`${yt.default.self}.opts.$comment(${i}, ${o}, ${a}.schema)`)}}function fwe(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:i}=t;r.$async?e.if((0,Je._)`${yt.default.errors} === 0`,()=>e.return(yt.default.data),()=>e.throw((0,Je._)`new ${s}(${yt.default.vErrors})`)):(e.assign((0,Je._)`${n}.errors`,yt.default.vErrors),i.unevaluated&&hwe(t),e.return((0,Je._)`${yt.default.errors} === 0`))}function hwe({gen:t,evaluated:e,props:r,items:n}){r instanceof Je.Name&&t.assign((0,Je._)`${e}.props`,r),n instanceof Je.Name&&t.assign((0,Je._)`${e}.items`,n)}function RQ(t,e,r,n){let{gen:s,schema:i,data:o,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,Dc.schemaHasRulesButRef)(i,l))){s.block(()=>UQ(t,"$ref",l.all.$ref.definition));return}c.jtd||pwe(t,e),s.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,tN.shouldUseGroup)(i,f)&&(f.type?(s.if((0,fC.checkDataType)(f.type,o,c.strictNumbers)),OQ(t,f),e.length===1&&e[0]===f.type&&r&&(s.else(),(0,fC.reportTypeError)(t)),s.endIf()):OQ(t,f),a||s.if((0,Je._)`${yt.default.errors} === ${n||0}`))}}function OQ(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,Qve.assignDefaults)(t,e.type),r.block(()=>{for(let i of e.rules)(0,tN.shouldUseRule)(n,i)&&UQ(t,i.keyword,i.definition,e.type)})}function pwe(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(mwe(t,e),t.opts.allowUnionTypes||gwe(t,e),ywe(t,t.dataTypes))}function mwe(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{DQ(t.dataTypes,r)||rN(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),bwe(t,e)}}function gwe(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&rN(t,"use allowUnionTypes to allow union type keyword")}function ywe(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,tN.shouldUseRule)(t.schema,s)){let{type:i}=s.definition;i.length&&!i.some(o=>xwe(e,o))&&rN(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function xwe(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function DQ(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function bwe(t,e){let r=[];for(let n of t.dataTypes)DQ(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function rN(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Dc.checkStrictMode)(t,e,t.opts.strictTypes)}var hC=class{constructor(e,r,n){if((0,J1.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Dc.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",qQ(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,J1.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",yt.default.errors))}result(e,r,n){this.failResult((0,Je.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Je.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,Je._)`${r} !== undefined && (${(0,Je.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?X1.reportExtraError:X1.reportError)(this,this.def.error,r)}$dataError(){(0,X1.reportError)(this,this.def.$dataError||X1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,X1.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Je.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Je.nil,r=Je.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:i,def:o}=this;n.if((0,Je.or)((0,Je._)`${s} === undefined`,r)),e!==Je.nil&&n.assign(e,!0),(i.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Je.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:i}=this;return(0,Je.or)(o(),a());function o(){if(n.length){if(!(r instanceof Je.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Je._)`${(0,fC.checkDataTypes)(c,r,i.opts.strictNumbers,fC.DataType.Wrong)}`}return Je.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,Je._)`!${c}(${r})`}return Je.nil}}subschema(e,r){let n=(0,eN.getSubschema)(this.it,e);(0,eN.extendSubschemaData)(n,this.it,e),(0,eN.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return owe(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Dc.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Dc.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,Je.Name)),!0}};ul.KeywordCxt=hC;function UQ(t,e,r,n){let s=new hC(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,J1.funcKeywordCode)(s,r):"macro"in r?(0,J1.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,J1.funcKeywordCode)(s,r)}var _we=/^\/(?:[^~]|~0|~1)*$/,vwe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function qQ(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,i;if(t==="")return yt.default.rootData;if(t[0]==="/"){if(!_we.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,i=yt.default.rootData}else{let u=vwe.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(s=u[2],s==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(i=r[e-l],!s)return i}let o=i,a=s.split("/");for(let u of a)u&&(i=(0,Je._)`${i}${(0,Je.getProperty)((0,Dc.unescapeJsonPointer)(u))}`,o=(0,Je._)`${o} && ${i}`);return o;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}ul.getData=qQ});var pC=v(sN=>{"use strict";Object.defineProperty(sN,"__esModule",{value:!0});var nN=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};sN.default=nN});var Q1=v(aN=>{"use strict";Object.defineProperty(aN,"__esModule",{value:!0});var iN=W1(),oN=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,iN.resolveUrl)(e,r,n),this.missingSchema=(0,iN.normalizeId)((0,iN.getFullPath)(e,this.missingRef))}};aN.default=oN});var gC=v(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.resolveSchema=Fi.getCompilingSchema=Fi.resolveRef=Fi.compileSchema=Fi.SchemaEnv=void 0;var Po=Bt(),wwe=pC(),Ff=Lc(),Ro=W1(),HQ=tr(),Swe=Y1(),sm=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Ro.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Fi.SchemaEnv=sm;function uN(t){let e=FQ.call(this,t);if(e)return e;let r=(0,Ro.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:i}=this.opts,o=new Po.CodeGen(this.scope,{es5:n,lines:s,ownProperties:i}),a;t.$async&&(a=o.scopeValue("Error",{ref:wwe.default,code:(0,Po._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");t.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:Ff.default.data,parentData:Ff.default.parentData,parentDataProperty:Ff.default.parentDataProperty,dataNames:[Ff.default.data],dataPathArr:[Po.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Po.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Po.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Po._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Swe.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let d=o.toString();l=`${o.scopeRefs(Ff.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let p=new Function(`${Ff.default.self}`,`${Ff.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:y}=u;p.evaluated={props:m instanceof Po.Name?void 0:m,items:y instanceof Po.Name?void 0:y,dynamicProps:m instanceof Po.Name,dynamicItems:y instanceof Po.Name},p.source&&(p.source.evaluated=(0,Po.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}Fi.compileSchema=uN;function Awe(t,e,r){var n;r=(0,Ro.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let i=kwe.call(this,t,r);if(i===void 0){let o=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;o&&(i=new sm({schema:o,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[r]=Ewe.call(this,i)}Fi.resolveRef=Awe;function Ewe(t){return(0,Ro.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:uN.call(this,t)}function FQ(t){for(let e of this._compilations)if(Cwe(e,t))return e}Fi.getCompilingSchema=FQ;function Cwe(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function kwe(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||mC.call(this,t,e)}function mC(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Ro._getFullPath)(this.opts.uriResolver,r),s=(0,Ro.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return cN.call(this,r,t);let i=(0,Ro.normalizeId)(n),o=this.refs[i]||this.schemas[i];if(typeof o=="string"){let a=mC.call(this,t,o);return typeof a?.schema!="object"?void 0:cN.call(this,r,a)}if(typeof o?.schema=="object"){if(o.validate||uN.call(this,o),i===(0,Ro.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,Ro.resolveUrl)(this.opts.uriResolver,s,u)),new sm({schema:a,schemaId:c,root:t,baseId:s})}return cN.call(this,r,o)}}Fi.resolveSchema=mC;var Twe=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function cN(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,HQ.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Twe.has(a)&&u&&(e=(0,Ro.resolveUrl)(this.opts.uriResolver,e,u))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,HQ.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ro.resolveUrl)(this.opts.uriResolver,e,r.$ref);i=mC.call(this,n,a)}let{schemaId:o}=this.opts;if(i=i||new sm({schema:r,schemaId:o,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var VQ=v((z7e,Iwe)=>{Iwe.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var fN=v((L7e,JQ)=>{"use strict";var Pwe=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ZQ=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),lN=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),GQ=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Rwe=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function dN(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var Owe=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function KQ(t){return t.length=0,!0}function Nwe(t,e,r){if(t.length){let n=dN(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Bwe(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],i=!1,o=!1,a=Nwe;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(i===!0&&(o=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=KQ}else{s.push(u);continue}}return s.length&&(a===KQ?r.zone=s.join(""):o?n.push(s.join("")):n.push(dN(s))),r.address=n.join(""),r}function WQ(t){if($we(t,":")<2)return{host:t,isIPV6:!1};let e=Bwe(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function $we(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Mwe(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var jwe={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},zwe=/[@/?#:]/g,Lwe=/[@/?#]/g;function XQ(t,e){let r=e?Lwe:zwe;return r.lastIndex=0,t.replace(r,n=>jwe[n])}function Dwe(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(lN(s)){let i=s.toUpperCase(),o=String.fromCharCode(parseInt(i,16));e&&GQ(o)?r+=o:r+="%"+i,n+=2;continue}}r+=t[n]}return r}function Uwe(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(lN(n)){let s=n.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&GQ(i)?e+=i:e+="%"+s,r+=2;continue}}Rwe(t[r])?e+=t[r]:e+=escape(t[r])}return e}function qwe(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(lN(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Hwe(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!ZQ(r)){let n=WQ(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=XQ(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}JQ.exports={nonSimpleDomain:Owe,recomposeAuthority:Hwe,reescapeHostDelimiters:XQ,normalizePercentEncoding:Dwe,normalizePathEncoding:Uwe,escapePreservingEscapes:qwe,removeDotSegments:Mwe,isIPv4:ZQ,isUUID:Pwe,normalizeIPv6:WQ,stringArrayToHexStripped:dN}});var ree=v((D7e,tee)=>{"use strict";var{isUUID:Fwe}=fN(),Vwe=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Kwe=["http","https","ws","wss","urn","urn:uuid"];function Zwe(t){return Kwe.indexOf(t)!==-1}function hN(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function YQ(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function QQ(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Gwe(t){return t.secure=hN(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Wwe(t){if((t.port===(hN(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function Xwe(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Vwe);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,i=pN(s);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Jwe(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,i=pN(s);i&&(t=i.serialize(t,e));let o=t,a=t.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function Ywe(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Fwe(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Qwe(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var eee={scheme:"http",domainHost:!0,parse:YQ,serialize:QQ},eSe={scheme:"https",domainHost:eee.domainHost,parse:YQ,serialize:QQ},yC={scheme:"ws",domainHost:!0,parse:Gwe,serialize:Wwe},tSe={scheme:"wss",domainHost:yC.domainHost,parse:yC.parse,serialize:yC.serialize},rSe={scheme:"urn",parse:Xwe,serialize:Jwe,skipNormalize:!0},nSe={scheme:"urn:uuid",parse:Ywe,serialize:Qwe,skipNormalize:!0},xC={http:eee,https:eSe,ws:yC,wss:tSe,urn:rSe,"urn:uuid":nSe};Object.setPrototypeOf(xC,null);function pN(t){return t&&(xC[t]||xC[t.toLowerCase()])||void 0}tee.exports={wsIsSecure:hN,SCHEMES:xC,isValidSchemeName:Zwe,getSchemeHandler:pN}});var cee=v((U7e,bC)=>{"use strict";var{normalizeIPv6:sSe,removeDotSegments:e_,recomposeAuthority:iSe,normalizePercentEncoding:oSe,normalizePathEncoding:aSe,escapePreservingEscapes:cSe,reescapeHostDelimiters:uSe,isIPv4:lSe,nonSimpleDomain:dSe}=fN(),{SCHEMES:fSe,getSchemeHandler:see}=ree();function hSe(t,e){return typeof t=="string"?t=xSe(t,e):typeof t=="object"&&(t=im(Vf(t,e),e)),t}function pSe(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=iee(im(t,n),im(e,n),n,!0);return n.skipEscape=!0,Vf(s,n)}function iee(t,e,r,n){let s={};return n||(t=im(Vf(t,r),r),e=im(Vf(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=e_(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=e_(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=e_(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=e_(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function mSe(t,e,r){let n=nee(t,r),s=nee(e,r);return n!==void 0&&s!==void 0&&n.toLowerCase()===s.toLowerCase()}function Vf(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],i=see(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=oSe(r.path):(r.path=cSe(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let o=iSe(r);if(o!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(o),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=e_(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var gSe=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ySe(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function oee(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(gSe);if(o){n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]);let a=ySe(n,o);if(a!==void 0&&(n.error=n.error||a,s=!0),n.host)if(lSe(n.host)===!1){let l=sSe(n.host);n.host=l.host.toLowerCase(),i=l.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let c=see(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&dSe(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!c||c&&!c.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=uSe(unescape(n.host),i))),n.path&&(n.path=aSe(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:s}}function im(t,e){return oee(t,e).parsed}function xSe(t,e){return aee(t,e).normalized}function aee(t,e){let{parsed:r,malformedAuthorityOrPort:n}=oee(t,e);return{normalized:n?t:Vf(r,e),malformedAuthorityOrPort:n}}function nee(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=aee(t,e);return n?void 0:r}if(typeof t=="object")return Vf(t,e)}var mN={SCHEMES:fSe,normalize:hSe,resolve:pSe,resolveComponent:iee,equal:mSe,serialize:Vf,parse:im};bC.exports=mN;bC.exports.default=mN;bC.exports.fastUri=mN});var lee=v(gN=>{"use strict";Object.defineProperty(gN,"__esModule",{value:!0});var uee=cee();uee.code='require("ajv/dist/runtime/uri").default';gN.default=uee});var xee=v(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.CodeGen=Jn.Name=Jn.nil=Jn.stringify=Jn.str=Jn._=Jn.KeywordCxt=void 0;var bSe=Y1();Object.defineProperty(Jn,"KeywordCxt",{enumerable:!0,get:function(){return bSe.KeywordCxt}});var om=Bt();Object.defineProperty(Jn,"_",{enumerable:!0,get:function(){return om._}});Object.defineProperty(Jn,"str",{enumerable:!0,get:function(){return om.str}});Object.defineProperty(Jn,"stringify",{enumerable:!0,get:function(){return om.stringify}});Object.defineProperty(Jn,"nil",{enumerable:!0,get:function(){return om.nil}});Object.defineProperty(Jn,"Name",{enumerable:!0,get:function(){return om.Name}});Object.defineProperty(Jn,"CodeGen",{enumerable:!0,get:function(){return om.CodeGen}});var _Se=pC(),mee=Q1(),vSe=V9(),t_=gC(),wSe=Bt(),r_=W1(),_C=G1(),xN=tr(),dee=VQ(),SSe=lee(),gee=(t,e)=>new RegExp(t,e);gee.code="new RegExp";var ASe=["removeAdditional","useDefaults","coerceTypes"],ESe=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),CSe={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},kSe={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},fee=200;function TSe(t){var e,r,n,s,i,o,a,c,u,l,d,f,p,m,y,_,S,C,E,B,G,se,_e,he,J;let ct=t.strict,ut=(e=t.code)===null||e===void 0?void 0:e.optimize,ze=ut===!0||ut===void 0?1:ut||0,z=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:gee,$=(s=t.uriResolver)!==null&&s!==void 0?s:SSe.default;return{strictSchema:(o=(i=t.strictSchema)!==null&&i!==void 0?i:ct)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ct)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ct)!==null&&l!==void 0?l:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:ct)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=t.strictRequired)!==null&&p!==void 0?p:ct)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:ze,regExp:z}:{optimize:ze,regExp:z},loopRequired:(y=t.loopRequired)!==null&&y!==void 0?y:fee,loopEnum:(_=t.loopEnum)!==null&&_!==void 0?_:fee,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(C=t.messages)!==null&&C!==void 0?C:!0,inlineRefs:(E=t.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(B=t.schemaId)!==null&&B!==void 0?B:"$id",addUsedSchema:(G=t.addUsedSchema)!==null&&G!==void 0?G:!0,validateSchema:(se=t.validateSchema)!==null&&se!==void 0?se:!0,validateFormats:(_e=t.validateFormats)!==null&&_e!==void 0?_e:!0,unicodeRegExp:(he=t.unicodeRegExp)!==null&&he!==void 0?he:!0,int32range:(J=t.int32range)!==null&&J!==void 0?J:!0,uriResolver:$}}var n_=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...TSe(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new wSe.ValueScope({scope:{},prefixes:ESe,es5:r,lines:n}),this.logger=BSe(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,vSe.getRules)(),hee.call(this,CSe,e,"NOT SUPPORTED"),hee.call(this,kSe,e,"DEPRECATED","warn"),this._metaOpts=OSe.call(this),e.formats&&PSe.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&RSe.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),ISe.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=dee;n==="id"&&(s={...dee},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(l,d){await i.call(this,l.$schema);let f=this._addSchema(l,d);return f.validate||o.call(this,f)}async function i(l){l&&!this.getSchema(l)&&await s.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof mee.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),o.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await i.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,s);return this}let i;if(typeof e=="object"){let{schemaId:o}=this.opts;if(i=e[o],i!==void 0&&typeof i!="string")throw new Error(`schema ${o} must be string`)}return r=(0,r_.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return s}getSchema(e){let r;for(;typeof(r=pee.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new t_.SchemaEnv({schema:{},schemaId:n});if(r=t_.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=pee.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,r_.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(MSe.call(this,n,r),!r)return(0,xN.eachItem)(n,i=>yN.call(this,i)),this;zSe.call(this,r);let s={...r,type:(0,_C.getJSONTypes)(r.type),schemaType:(0,_C.getJSONTypes)(r.schemaType)};return(0,xN.eachItem)(n,s.type.length===0?i=>yN.call(this,i,s):i=>s.type.forEach(o=>yN.call(this,i,s,o))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(i=>i.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,i)=>s+r+i)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let i=s.split("/").slice(1),o=e;for(let a of i)o=o[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=o[a];u&&l&&(o[a]=yee(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,i=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,r_.normalizeId)(o||n);let u=r_.getSchemaRefs.call(this,e,n);return c=new t_.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):t_.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{t_.compileSchema.call(this,e)}finally{this.opts=r}}};n_.ValidationError=_Se.default;n_.MissingRefError=mee.default;Jn.default=n_;function hee(t,e,r,n="error"){for(let s in t){let i=s;i in e&&this.logger[n](`${r}: option ${s}. ${t[i]}`)}}function pee(t){return t=(0,r_.normalizeId)(t),this.schemas[t]||this.refs[t]}function ISe(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function PSe(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function RSe(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function OSe(){let t={...this.opts};for(let e of ASe)delete t[e];return t}var NSe={log(){},warn(){},error(){}};function BSe(t){if(t===!1)return NSe;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var $Se=/^[a-z_$][a-z0-9_$:-]*$/i;function MSe(t,e){let{RULES:r}=this;if((0,xN.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!$Se.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function yN(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,o=s?i.post:i.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},i.rules.push(o)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,_C.getJSONTypes)(e.type),schemaType:(0,_C.getJSONTypes)(e.schemaType)}};e.before?jSe.call(this,o,a,e.before):o.rules.push(a),i.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function jSe(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function zSe(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=yee(e)),t.validateSchema=this.compile(e,!0))}var LSe={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function yee(t){return{anyOf:[t,LSe]}}});var bee=v(bN=>{"use strict";Object.defineProperty(bN,"__esModule",{value:!0});var DSe={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};bN.default=DSe});var See=v(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});Kf.callRef=Kf.getValidate=void 0;var USe=Q1(),_ee=Hi(),Qs=Bt(),am=Lc(),vee=gC(),vC=tr(),qSe={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:i,validateName:o,opts:a,self:c}=n,{root:u}=i;if((r==="#"||r==="#/")&&s===u.baseId)return d();let l=vee.resolveRef.call(c,u,s,r);if(l===void 0)throw new USe.default(n.opts.uriResolver,s,r);if(l instanceof vee.SchemaEnv)return f(l);return p(l);function d(){if(i===u)return wC(t,o,i,i.$async);let m=e.scopeValue("root",{ref:u});return wC(t,(0,Qs._)`${m}.validate`,u,u.$async)}function f(m){let y=wee(t,m);wC(t,y,m,m.$async)}function p(m){let y=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Qs.stringify)(m)}:{ref:m}),_=e.name("valid"),S=t.subschema({schema:m,dataTypes:[],schemaPath:Qs.nil,topSchemaRef:y,errSchemaPath:r},_);t.mergeEvaluated(S),t.ok(_)}}};function wee(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qs._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Kf.getValidate=wee;function wC(t,e,r,n){let{gen:s,it:i}=t,{allErrors:o,schemaEnv:a,opts:c}=i,u=c.passContext?am.default.this:Qs.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,Qs._)`await ${(0,_ee.callValidateCode)(t,e,u)}`),p(e),o||s.assign(m,!0)},y=>{s.if((0,Qs._)`!(${y} instanceof ${i.ValidationError})`,()=>s.throw(y)),f(y),o||s.assign(m,!1)}),t.ok(m)}function d(){t.result((0,_ee.callValidateCode)(t,e,u),()=>p(e),()=>f(e))}function f(m){let y=(0,Qs._)`${m}.errors`;s.assign(am.default.vErrors,(0,Qs._)`${am.default.vErrors} === null ? ${y} : ${am.default.vErrors}.concat(${y})`),s.assign(am.default.errors,(0,Qs._)`${am.default.vErrors}.length`)}function p(m){var y;if(!i.opts.unevaluated)return;let _=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=vC.mergeEvaluated.props(s,_.props,i.props));else{let S=s.var("props",(0,Qs._)`${m}.evaluated.props`);i.props=vC.mergeEvaluated.props(s,S,i.props,Qs.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=vC.mergeEvaluated.items(s,_.items,i.items));else{let S=s.var("items",(0,Qs._)`${m}.evaluated.items`);i.items=vC.mergeEvaluated.items(s,S,i.items,Qs.Name)}}}Kf.callRef=wC;Kf.default=qSe});var Aee=v(_N=>{"use strict";Object.defineProperty(_N,"__esModule",{value:!0});var HSe=bee(),FSe=See(),VSe=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",HSe.default,FSe.default];_N.default=VSe});var Eee=v(vN=>{"use strict";Object.defineProperty(vN,"__esModule",{value:!0});var SC=Bt(),ll=SC.operators,AC={maximum:{okStr:"<=",ok:ll.LTE,fail:ll.GT},minimum:{okStr:">=",ok:ll.GTE,fail:ll.LT},exclusiveMaximum:{okStr:"<",ok:ll.LT,fail:ll.GTE},exclusiveMinimum:{okStr:">",ok:ll.GT,fail:ll.LTE}},KSe={message:({keyword:t,schemaCode:e})=>(0,SC.str)`must be ${AC[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,SC._)`{comparison: ${AC[t].okStr}, limit: ${e}}`},ZSe={keyword:Object.keys(AC),type:"number",schemaType:"number",$data:!0,error:KSe,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,SC._)`${r} ${AC[e].fail} ${n} || isNaN(${r})`)}};vN.default=ZSe});var Cee=v(wN=>{"use strict";Object.defineProperty(wN,"__esModule",{value:!0});var s_=Bt(),GSe={message:({schemaCode:t})=>(0,s_.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,s_._)`{multipleOf: ${t}}`},WSe={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:GSe,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,i=s.opts.multipleOfPrecision,o=e.let("res"),a=i?(0,s_._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${i}`:(0,s_._)`${o} !== parseInt(${o})`;t.fail$data((0,s_._)`(${n} === 0 || (${o} = ${r}/${n}, ${a}))`)}};wN.default=WSe});var Tee=v(SN=>{"use strict";Object.defineProperty(SN,"__esModule",{value:!0});function kee(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}SN.default=kee;kee.code='require("ajv/dist/runtime/ucs2length").default'});var Iee=v(AN=>{"use strict";Object.defineProperty(AN,"__esModule",{value:!0});var Zf=Bt(),XSe=tr(),JSe=Tee(),YSe={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Zf.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Zf._)`{limit: ${t}}`},QSe={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:YSe,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,i=e==="maxLength"?Zf.operators.GT:Zf.operators.LT,o=s.opts.unicode===!1?(0,Zf._)`${r}.length`:(0,Zf._)`${(0,XSe.useFunc)(t.gen,JSe.default)}(${r})`;t.fail$data((0,Zf._)`${o} ${i} ${n}`)}};AN.default=QSe});var Pee=v(EN=>{"use strict";Object.defineProperty(EN,"__esModule",{value:!0});var e2e=Hi(),t2e=tr(),cm=Bt(),r2e={message:({schemaCode:t})=>(0,cm.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,cm._)`{pattern: ${t}}`},n2e={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:r2e,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:i,it:o}=t,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,u=c.code==="new RegExp"?(0,cm._)`new RegExp`:(0,t2e.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,cm._)`${u}(${i}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,cm._)`!${l}`)}else{let c=(0,e2e.usePattern)(t,s);t.fail$data((0,cm._)`!${c}.test(${r})`)}}};EN.default=n2e});var Ree=v(CN=>{"use strict";Object.defineProperty(CN,"__esModule",{value:!0});var i_=Bt(),s2e={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,i_.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,i_._)`{limit: ${t}}`},i2e={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:s2e,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?i_.operators.GT:i_.operators.LT;t.fail$data((0,i_._)`Object.keys(${r}).length ${s} ${n}`)}};CN.default=i2e});var Oee=v(kN=>{"use strict";Object.defineProperty(kN,"__esModule",{value:!0});var o_=Hi(),a_=Bt(),o2e=tr(),a2e={message:({params:{missingProperty:t}})=>(0,a_.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,a_._)`{missingProperty: ${t}}`},c2e={keyword:"required",type:"object",schemaType:"array",$data:!0,error:a2e,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:i,it:o}=t,{opts:a}=o;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(o.allErrors?u():l(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:m}=t.it;for(let y of r)if(p?.[y]===void 0&&!m.has(y)){let _=o.schemaEnv.baseId+o.errSchemaPath,S=`required property "${y}" is not defined at "${_}" (strictRequired)`;(0,o2e.checkStrictMode)(o,S,o.opts.strictRequired)}}function u(){if(c||i)t.block$data(a_.nil,d);else for(let p of r)(0,o_.checkReportMissingProp)(t,p)}function l(){let p=e.let("missing");if(c||i){let m=e.let("valid",!0);t.block$data(m,()=>f(p,m)),t.ok(m)}else e.if((0,o_.checkMissingProp)(t,r,p)),(0,o_.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,o_.noPropertyInData)(e,s,p,a.ownProperties),()=>t.error())})}function f(p,m){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,o_.propertyInData)(e,s,p,a.ownProperties)),e.if((0,a_.not)(m),()=>{t.error(),e.break()})},a_.nil)}}};kN.default=c2e});var Nee=v(TN=>{"use strict";Object.defineProperty(TN,"__esModule",{value:!0});var c_=Bt(),u2e={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,c_.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,c_._)`{limit: ${t}}`},l2e={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:u2e,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?c_.operators.GT:c_.operators.LT;t.fail$data((0,c_._)`${r}.length ${s} ${n}`)}};TN.default=l2e});var EC=v(IN=>{"use strict";Object.defineProperty(IN,"__esModule",{value:!0});var Bee=tA();Bee.code='require("ajv/dist/runtime/equal").default';IN.default=Bee});var $ee=v(RN=>{"use strict";Object.defineProperty(RN,"__esModule",{value:!0});var PN=G1(),Yn=Bt(),d2e=tr(),f2e=EC(),h2e={message:({params:{i:t,j:e}})=>(0,Yn.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Yn._)`{i: ${t}, j: ${e}}`},p2e={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:h2e,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:i,schemaCode:o,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=i.items?(0,PN.getSchemaTypes)(i.items):[];t.block$data(c,l,(0,Yn._)`${o} === false`),t.ok(c);function l(){let m=e.let("i",(0,Yn._)`${r}.length`),y=e.let("j");t.setParams({i:m,j:y}),e.assign(c,!0),e.if((0,Yn._)`${m} > 1`,()=>(d()?f:p)(m,y))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function f(m,y){let _=e.name("item"),S=(0,PN.checkDataTypes)(u,_,a.opts.strictNumbers,PN.DataType.Wrong),C=e.const("indices",(0,Yn._)`{}`);e.for((0,Yn._)`;${m}--;`,()=>{e.let(_,(0,Yn._)`${r}[${m}]`),e.if(S,(0,Yn._)`continue`),u.length>1&&e.if((0,Yn._)`typeof ${_} == "string"`,(0,Yn._)`${_} += "_"`),e.if((0,Yn._)`typeof ${C}[${_}] == "number"`,()=>{e.assign(y,(0,Yn._)`${C}[${_}]`),t.error(),e.assign(c,!1).break()}).code((0,Yn._)`${C}[${_}] = ${m}`)})}function p(m,y){let _=(0,d2e.useFunc)(e,f2e.default),S=e.name("outer");e.label(S).for((0,Yn._)`;${m}--;`,()=>e.for((0,Yn._)`${y} = ${m}; ${y}--;`,()=>e.if((0,Yn._)`${_}(${r}[${m}], ${r}[${y}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};RN.default=p2e});var Mee=v(NN=>{"use strict";Object.defineProperty(NN,"__esModule",{value:!0});var ON=Bt(),m2e=tr(),g2e=EC(),y2e={message:"must be equal to constant",params:({schemaCode:t})=>(0,ON._)`{allowedValue: ${t}}`},x2e={keyword:"const",$data:!0,error:y2e,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:i}=t;n||i&&typeof i=="object"?t.fail$data((0,ON._)`!${(0,m2e.useFunc)(e,g2e.default)}(${r}, ${s})`):t.fail((0,ON._)`${i} !== ${r}`)}};NN.default=x2e});var jee=v(BN=>{"use strict";Object.defineProperty(BN,"__esModule",{value:!0});var u_=Bt(),b2e=tr(),_2e=EC(),v2e={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,u_._)`{allowedValues: ${t}}`},w2e={keyword:"enum",schemaType:"array",$data:!0,error:v2e,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:i,it:o}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=o.opts.loopEnum,c,u=()=>c??(c=(0,b2e.useFunc)(e,_2e.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let p=e.const("vSchema",i);l=(0,u_.or)(...s.map((m,y)=>f(p,y)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",i,p=>e.if((0,u_._)`${u()}(${r}, ${p})`,()=>e.assign(l,!0).break()))}function f(p,m){let y=s[m];return typeof y=="object"&&y!==null?(0,u_._)`${u()}(${r}, ${p}[${m}])`:(0,u_._)`${r} === ${y}`}}};BN.default=w2e});var zee=v($N=>{"use strict";Object.defineProperty($N,"__esModule",{value:!0});var S2e=Eee(),A2e=Cee(),E2e=Iee(),C2e=Pee(),k2e=Ree(),T2e=Oee(),I2e=Nee(),P2e=$ee(),R2e=Mee(),O2e=jee(),N2e=[S2e.default,A2e.default,E2e.default,C2e.default,k2e.default,T2e.default,I2e.default,P2e.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},R2e.default,O2e.default];$N.default=N2e});var jN=v(l_=>{"use strict";Object.defineProperty(l_,"__esModule",{value:!0});l_.validateAdditionalItems=void 0;var Gf=Bt(),MN=tr(),B2e={message:({params:{len:t}})=>(0,Gf.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Gf._)`{limit: ${t}}`},$2e={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:B2e,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,MN.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Lee(t,n)}};function Lee(t,e){let{gen:r,schema:n,data:s,keyword:i,it:o}=t;o.items=!0;let a=r.const("len",(0,Gf._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Gf._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,MN.alwaysValidSchema)(o,n)){let u=r.var("valid",(0,Gf._)`${a} <= ${e.length}`);r.if((0,Gf.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:i,dataProp:l,dataPropType:MN.Type.Num},u),o.allErrors||r.if((0,Gf.not)(u),()=>r.break())})}}l_.validateAdditionalItems=Lee;l_.default=$2e});var zN=v(d_=>{"use strict";Object.defineProperty(d_,"__esModule",{value:!0});d_.validateTuple=void 0;var Dee=Bt(),CC=tr(),M2e=Hi(),j2e={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Uee(t,"additionalItems",e);r.items=!0,!(0,CC.alwaysValidSchema)(r,e)&&t.ok((0,M2e.validateArray)(t))}};function Uee(t,e,r=t.schema){let{gen:n,parentSchema:s,data:i,keyword:o,it:a}=t;l(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=CC.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Dee._)`${i}.length`);r.forEach((d,f)=>{(0,CC.alwaysValidSchema)(a,d)||(n.if((0,Dee._)`${u} > ${f}`,()=>t.subschema({keyword:o,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:p}=a,m=r.length,y=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(f.strictTuples&&!y){let _=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,CC.checkStrictMode)(a,_,f.strictTuples)}}}d_.validateTuple=Uee;d_.default=j2e});var qee=v(LN=>{"use strict";Object.defineProperty(LN,"__esModule",{value:!0});var z2e=zN(),L2e={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,z2e.validateTuple)(t,"items")};LN.default=L2e});var Fee=v(DN=>{"use strict";Object.defineProperty(DN,"__esModule",{value:!0});var Hee=Bt(),D2e=tr(),U2e=Hi(),q2e=jN(),H2e={message:({params:{len:t}})=>(0,Hee.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Hee._)`{limit: ${t}}`},F2e={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:H2e,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,D2e.alwaysValidSchema)(n,e)&&(s?(0,q2e.validateAdditionalItems)(t,s):t.ok((0,U2e.validateArray)(t)))}};DN.default=F2e});var Vee=v(UN=>{"use strict";Object.defineProperty(UN,"__esModule",{value:!0});var Vi=Bt(),kC=tr(),V2e={message:({params:{min:t,max:e}})=>e===void 0?(0,Vi.str)`must contain at least ${t} valid item(s)`:(0,Vi.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Vi._)`{minContains: ${t}}`:(0,Vi._)`{minContains: ${t}, maxContains: ${e}}`},K2e={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:V2e,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:i}=t,o,a,{minContains:c,maxContains:u}=n;i.opts.next?(o=c===void 0?1:c,a=u):o=1;let l=e.const("len",(0,Vi._)`${s}.length`);if(t.setParams({min:o,max:a}),a===void 0&&o===0){(0,kC.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,kC.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,kC.alwaysValidSchema)(i,r)){let y=(0,Vi._)`${l} >= ${o}`;a!==void 0&&(y=(0,Vi._)`${y} && ${l} <= ${a}`),t.pass(y);return}i.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,Vi._)`${s}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let y=e.name("_valid"),_=e.let("count",0);p(y,()=>e.if(y,()=>m(_)))}function p(y,_){e.forRange("i",0,l,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:kC.Type.Num,compositeRule:!0},y),_()})}function m(y){e.code((0,Vi._)`${y}++`),a===void 0?e.if((0,Vi._)`${y} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Vi._)`${y} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Vi._)`${y} >= ${o}`,()=>e.assign(d,!0)))}}};UN.default=K2e});var Gee=v(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.validateSchemaDeps=Pa.validatePropertyDeps=Pa.error=void 0;var qN=Bt(),Z2e=tr(),f_=Hi();Pa.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,qN.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,qN._)`{property: ${t},
|
|
46
195
|
missingProperty: ${n},
|
|
47
196
|
depsCount: ${e},
|
|
48
|
-
deps: ${r}}`};var yP={keyword:"dependencies",type:"object",schemaType:"object",error:xt.error,code(t){let[e,r]=_P(t);gy(t,e),yy(t,r)}};function _P({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function gy(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Mo.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Mo.checkReportMissingProp)(t,u)}):(r.if((0,od._)`${c} && (${(0,Mo.checkMissingProp)(t,a,s)})`),(0,Mo.reportMissingProp)(t,s),r.else())}}xt.validatePropertyDeps=gy;function yy(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,gP.alwaysValidSchema)(s,e[a])||(r.if((0,Mo.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}xt.validateSchemaDeps=yy;xt.default=yP});var xy=S(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var vy=U(),vP=G(),xP={message:"property name must be valid",params:({params:t})=>(0,vy._)`{propertyName: ${t.propertyName}}`},wP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:xP,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,vP.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,vy.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};sd.default=wP});var ad=S(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var bi=rt(),pt=U(),bP=Rt(),$i=G(),$P={message:"must NOT have additional properties",params:({params:t})=>(0,pt._)`{additionalProperty: ${t.additionalProperty}}`},kP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$P,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,$i.alwaysValidSchema)(i,r))return;let u=(0,bi.allSchemaProperties)(n.properties),l=(0,bi.allSchemaProperties)(n.patternProperties);d(),t.ok((0,pt._)`${s} === ${bP.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?p(g):e.if(f(g),()=>p(g))})}function f(g){let w;if(u.length>8){let v=(0,$i.schemaRefOrVal)(i,n.properties,"properties");w=(0,bi.isOwnProperty)(e,v,g)}else u.length?w=(0,pt.or)(...u.map(v=>(0,pt._)`${g} === ${v}`)):w=pt.nil;return l.length&&(w=(0,pt.or)(w,...l.map(v=>(0,pt._)`${(0,bi.usePattern)(t,v)}.test(${g})`))),(0,pt.not)(w)}function m(g){e.code((0,pt._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,$i.alwaysValidSchema)(i,r)){let w=e.name("valid");c.removeAdditional==="failing"?(h(g,w,!1),e.if((0,pt.not)(w),()=>{t.reset(),m(g)})):(h(g,w),a||e.if((0,pt.not)(w),()=>e.break()))}}function h(g,w,v){let x={keyword:"additionalProperties",dataProp:g,dataPropType:$i.Type.Str};v===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,w)}}};id.default=kP});var $y=S(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var SP=ko(),wy=rt(),cd=G(),by=ad(),zP={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&by.default.code(new SP.KeywordCxt(s,by.default,"additionalProperties"));let i=(0,wy.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=cd.mergeEvaluated.props(e,(0,cd.toHash)(i),s.props));let a=i.filter(d=>!(0,cd.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,wy.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};ud.default=zP});var Ty=S(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var ky=rt(),ki=U(),Sy=G(),zy=G(),TP={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,ky.allSchemaProperties)(r),c=a.filter(h=>(0,Sy.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof ki.Name)&&(s.props=(0,zy.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)u&&m(h),s.allErrors?p(h):(e.var(l,!0),p(h),e.if(l))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,Sy.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,ki._)`${(0,ky.usePattern)(t,h)}.test(${g})`,()=>{let w=c.includes(h);w||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:zy.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,ki._)`${d}[${g}]`,!0):!w&&!s.allErrors&&e.if((0,ki.not)(l),()=>e.break())})})}}};ld.default=TP});var Py=S(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var PP=G(),OP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,PP.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};dd.default=OP});var Oy=S(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var EP=rt(),IP={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:EP.validateUnion,error:{message:"must match a schema in anyOf"}};pd.default=IP});var Ey=S(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var Si=U(),RP=G(),jP={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Si._)`{passingSchemas: ${t.passing}}`},NP={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:jP,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let f;(0,RP.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Si._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Si._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Si.Name)})})}}};fd.default=NP});var Iy=S(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var CP=G(),ZP={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,CP.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};md.default=ZP});var Ny=S(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var zi=U(),jy=G(),AP={message:({params:t})=>(0,zi.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,zi._)`{failingKeyword: ${t.ifClause}}`},MP={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:AP,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,jy.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Ry(n,"then"),s=Ry(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,zi.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,zi._)`${l}`):t.setParams({ifClause:l})}}}};function Ry(t,e){let r=t.schema[e];return r!==void 0&&!(0,jy.alwaysValidSchema)(t,r)}hd.default=MP});var Cy=S(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var DP=G(),LP={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,DP.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};gd.default=LP});var Zy=S(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var qP=Ql(),UP=py(),FP=ed(),VP=my(),HP=hy(),KP=_y(),BP=xy(),XP=ad(),JP=$y(),GP=Ty(),WP=Py(),YP=Oy(),QP=Ey(),eO=Iy(),tO=Ny(),rO=Cy();function nO(t=!1){let e=[WP.default,YP.default,QP.default,eO.default,tO.default,rO.default,BP.default,XP.default,KP.default,JP.default,GP.default];return t?e.push(UP.default,VP.default):e.push(qP.default,FP.default),e.push(HP.default),e}yd.default=nO});var Ay=S(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var ge=U(),oO={message:({schemaCode:t})=>(0,ge.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ge._)`{format: ${t}}`},sO={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:oO,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?f():m();function f(){let p=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ge._)`${p}[${i}]`),g=r.let("fType"),w=r.let("format");r.if((0,ge._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,ge._)`${h}.type || "string"`).assign(w,(0,ge._)`${h}.validate`),()=>r.assign(g,(0,ge._)`"string"`).assign(w,h)),t.fail$data((0,ge.or)(v(),x()));function v(){return c.strictSchema===!1?ge.nil:(0,ge._)`${i} && !${w}`}function x(){let T=l.$async?(0,ge._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,ge._)`${w}(${n})`,N=(0,ge._)`(typeof ${w} == "function" ? ${T} : ${w}.test(${n}))`;return(0,ge._)`${w} && ${w} !== true && ${g} === ${e} && !${N}`}}function m(){let p=d.formats[s];if(!p){v();return}if(p===!0)return;let[h,g,w]=x(p);h===e&&t.pass(T());function v(){if(c.strictSchema===!1){d.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(N){let he=N instanceof RegExp?(0,ge.regexpCode)(N):c.code.formats?(0,ge._)`${c.code.formats}${(0,ge.getProperty)(s)}`:void 0,He=r.scopeValue("formats",{key:s,ref:N,code:he});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,ge._)`${He}.validate`]:["string",N,He]}function T(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ge._)`await ${w}(${n})`}return typeof g=="function"?(0,ge._)`${w}(${n})`:(0,ge._)`${w}.test(${n})`}}}};_d.default=sO});var My=S(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var iO=Ay(),aO=[iO.default];vd.default=aO});var Dy=S(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.contentVocabulary=xn.metadataVocabulary=void 0;xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var qy=S(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var cO=Xg(),uO=cy(),lO=Zy(),dO=My(),Ly=Dy(),pO=[cO.default,uO.default,(0,lO.default)(),dO.default,Ly.metadataVocabulary,Ly.contentVocabulary];xd.default=pO});var Fy=S(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.DiscrError=void 0;var Uy;(function(t){t.Tag="tag",t.Mapping="mapping"})(Uy||(Ti.DiscrError=Uy={}))});var Hy=S(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var wn=U(),wd=Fy(),Vy=li(),fO=So(),mO=G(),hO={message:({params:{discrError:t,tagName:e}})=>t===wd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,wn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},gO={keyword:"discriminator",type:"object",schemaType:"object",error:hO,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,wn._)`${r}${(0,wn.getProperty)(a)}`);e.if((0,wn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:wd.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=f();e.if(!1);for(let p in m)e.elseIf((0,wn._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:wd.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},p);return t.mergeEvaluated(h,wn.Name),p}function f(){var m;let p={},h=w(o),g=!0;for(let T=0;T<i.length;T++){let N=i[T];if(N?.$ref&&!(0,mO.schemaHasRulesButRef)(N,s.self.RULES)){let He=N.$ref;if(N=Vy.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,He),N instanceof Vy.SchemaEnv&&(N=N.schema),N===void 0)throw new fO.default(s.opts.uriResolver,s.baseId,He)}let he=(m=N?.properties)===null||m===void 0?void 0:m[a];if(typeof he!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||w(N)),v(he,T)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function w({required:T}){return Array.isArray(T)&&T.includes(a)}function v(T,N){if(T.const)x(T.const,N);else if(T.enum)for(let he of T.enum)x(he,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(T,N){if(typeof T!="string"||T in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[T]=N}}}};bd.default=gO});var Ky=S((mZ,yO)=>{yO.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var kd=S((ce,$d)=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.MissingRefError=ce.ValidationError=ce.CodeGen=ce.Name=ce.nil=ce.stringify=ce.str=ce._=ce.KeywordCxt=ce.Ajv=void 0;var _O=Ug(),vO=qy(),xO=Hy(),By=Ky(),wO=["/properties"],Pi="http://json-schema.org/draft-07/schema",bn=class extends _O.default{_addVocabularies(){super._addVocabularies(),vO.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(xO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(By,wO):By;this.addMetaSchema(e,Pi,!1),this.refs["http://json-schema.org/schema"]=Pi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Pi)?Pi:void 0)}};ce.Ajv=bn;$d.exports=ce=bn;$d.exports.Ajv=bn;Object.defineProperty(ce,"__esModule",{value:!0});ce.default=bn;var bO=ko();Object.defineProperty(ce,"KeywordCxt",{enumerable:!0,get:function(){return bO.KeywordCxt}});var $n=U();Object.defineProperty(ce,"_",{enumerable:!0,get:function(){return $n._}});Object.defineProperty(ce,"str",{enumerable:!0,get:function(){return $n.str}});Object.defineProperty(ce,"stringify",{enumerable:!0,get:function(){return $n.stringify}});Object.defineProperty(ce,"nil",{enumerable:!0,get:function(){return $n.nil}});Object.defineProperty(ce,"Name",{enumerable:!0,get:function(){return $n.Name}});Object.defineProperty(ce,"CodeGen",{enumerable:!0,get:function(){return $n.CodeGen}});var $O=ci();Object.defineProperty(ce,"ValidationError",{enumerable:!0,get:function(){return $O.default}});var kO=So();Object.defineProperty(ce,"MissingRefError",{enumerable:!0,get:function(){return kO.default}})});var t_=S(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.formatNames=bt.fastFormats=bt.fullFormats=void 0;function wt(t,e){return{validate:t,compare:e}}bt.fullFormats={date:wt(Wy,Pd),time:wt(zd(!0),Od),"date-time":wt(Xy(!0),Qy),"iso-time":wt(zd(),Yy),"iso-date-time":wt(Xy(),e_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:EO,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:AO,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:IO,int32:{type:"number",validate:NO},int64:{type:"number",validate:CO},float:{type:"number",validate:Gy},double:{type:"number",validate:Gy},password:!0,binary:!0};bt.fastFormats={...bt.fullFormats,date:wt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pd),time:wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Od),"date-time":wt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Qy),"iso-time":wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Yy),"iso-date-time":wt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,e_),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};bt.formatNames=Object.keys(bt.fullFormats);function SO(t){return t%4===0&&(t%100!==0||t%400===0)}var zO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,TO=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Wy(t){let e=zO.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&SO(r)?29:TO[n])}function Pd(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Sd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function zd(t){return function(r){let n=Sd.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,f=o-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function Od(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Yy(t,e){if(!(t&&e))return;let r=Sd.exec(t),n=Sd.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Td=/t|\s/i;function Xy(t){let e=zd(t);return function(n){let o=n.split(Td);return o.length===2&&Wy(o[0])&&e(o[1])}}function Qy(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function e_(t,e){if(!(t&&e))return;let[r,n]=t.split(Td),[o,s]=e.split(Td),i=Pd(r,o);if(i!==void 0)return i||Od(n,s)}var PO=/\/|:/,OO=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function EO(t){return PO.test(t)&&OO.test(t)}var Jy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function IO(t){return Jy.lastIndex=0,Jy.test(t)}var RO=-(2**31),jO=2**31-1;function NO(t){return Number.isInteger(t)&&t<=jO&&t>=RO}function CO(t){return Number.isInteger(t)}function Gy(){return!0}var ZO=/[^\\]\\Z/;function AO(t){if(ZO.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var r_=S(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.formatLimitDefinition=void 0;var MO=kd(),ft=U(),er=ft.operators,Oi={formatMaximum:{okStr:"<=",ok:er.LTE,fail:er.GT},formatMinimum:{okStr:">=",ok:er.GTE,fail:er.LT},formatExclusiveMaximum:{okStr:"<",ok:er.LT,fail:er.GTE},formatExclusiveMinimum:{okStr:">",ok:er.GT,fail:er.LTE}},DO={message:({keyword:t,schemaCode:e})=>(0,ft.str)`should be ${Oi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ft._)`{comparison: ${Oi[t].okStr}, limit: ${e}}`};kn.formatLimitDefinition={keyword:Object.keys(Oi),type:"string",schemaType:"string",$data:!0,error:DO,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new MO.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,ft._)`${f}[${c.schemaCode}]`);t.fail$data((0,ft.or)((0,ft._)`typeof ${m} != "object"`,(0,ft._)`${m} instanceof RegExp`,(0,ft._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let f=c.schema,m=a.formats[f];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let p=e.scopeValue("formats",{key:f,ref:m,code:i.code.formats?(0,ft._)`${i.code.formats}${(0,ft.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,ft._)`${f}.compare(${r}, ${n}) ${Oi[o].fail} 0`}},dependencies:["format"]};var LO=t=>(t.addKeyword(kn.formatLimitDefinition),t);kn.default=LO});var i_=S((Do,s_)=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});var Sn=t_(),qO=r_(),Ed=U(),n_=new Ed.Name("fullFormats"),UO=new Ed.Name("fastFormats"),Id=(t,e={keywords:!0})=>{if(Array.isArray(e))return o_(t,e,Sn.fullFormats,n_),t;let[r,n]=e.mode==="fast"?[Sn.fastFormats,UO]:[Sn.fullFormats,n_],o=e.formats||Sn.formatNames;return o_(t,o,r,n),e.keywords&&(0,qO.default)(t),t};Id.get=(t,e="full")=>{let n=(e==="fast"?Sn.fastFormats:Sn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function o_(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Ed._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}s_.exports=Do=Id;Object.defineProperty(Do,"__esModule",{value:!0});Do.default=Id});import{createRequire as tE}from"node:module";import*as Jd from"node:http";import{randomBytes as D_}from"node:crypto";import{spawn as Li}from"node:child_process";import{promises as rr}from"node:fs";import*as On from"node:path";import*as Hd from"node:os";import{randomBytes as R_}from"node:crypto";import{execFile as j_}from"node:child_process";import{promisify as N_}from"node:util";var C_=N_(j_),kt=process.env.OIOXO_CONTROL_PLANE?.replace(/\/$/,"")||"https://oioxo.com",Pn=process.env.OIOXO_HOME||On.join(Hd.homedir(),".oioxo"),Uo=On.join(Pn,"credentials.json");async function or(){try{let t=JSON.parse(await rr.readFile(Uo,"utf8"));return t?.token?t:null}catch{return null}}async function Z_(t){if(process.platform!=="win32")return;let e=process.env.USERNAME||process.env.USER;if(e)try{await C_("icacls",[t,"/inheritance:r","/grant:r",`${e}:F`],{windowsHide:!0})}catch{}}async function Kd(t){await rr.mkdir(Pn,{recursive:!0}),await rr.writeFile(Uo,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),await Z_(Uo)}async function Bd(){try{await rr.unlink(Uo)}catch{}}async function Di(){let t=await or();if(t?.device)return t.device;try{let r=await rr.readFile(On.join(Pn,"device"),"utf8");if(r.trim())return r.trim()}catch{}let e=R_(16).toString("base64url");return await rr.mkdir(Pn,{recursive:!0}),await rr.writeFile(On.join(Pn,"device"),e,"utf8"),e}function A_(){return`cli-${process.platform==="win32"?"windows":process.platform==="darwin"?"mac":"linux"}`}async function M_(){let t=await or(),e=await Di(),r={"content-type":"application/json","x-oioxo-client":A_(),"x-oioxo-device":e};return t?.token&&t.expiresAt>Date.now()&&(r.authorization=`Bearer ${t.token}`),r}async function Ie(t,e){try{let r=await fetch(`${kt}/api/usage/save`,{method:"POST",headers:await M_(),body:JSON.stringify(t==="report"?{action:t,savedTokens:e}:{action:t})});return r.ok?await r.json():null}catch{return null}}async function Nt(){let t=await or();return!!t&&t.expiresAt>Date.now()}var nr="https://oioxo.com/?upgrade=pro",En="Run `oioxo-mcp login` in a terminal to connect your OIOXO account.";async function Xd(){if(!await Nt())return{ok:!1,message:`OIOXO: sign in to use the coding agent. ${En}
|
|
49
|
-
Free accounts include a monthly allowance; OIOXO Pro is unlimited \u2192 ${nr}`};let t=await Ie("check");return t?t.optimize?{ok:!0,state:t}:t.tier==="anon"?{ok:!1,message:`Your OIOXO session expired. ${En}`}:{ok:!1,message:`You've used your monthly OIOXO allowance. OIOXO Pro is unlimited \u2192 ${nr}`}:{ok:!1,message:"OIOXO could not verify your plan (oioxo.com unreachable). The coding agent is paused until the connection returns."}}var L_=5*6e4,q_=`<!doctype html><html><head><meta charset="utf-8"><title>OIOXO CLI connected</title></head>
|
|
197
|
+
deps: ${r}}`};var G2e={keyword:"dependencies",type:"object",schemaType:"object",error:Pa.error,code(t){let[e,r]=W2e(t);Kee(t,e),Zee(t,r)}};function W2e({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function Kee(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let i=r.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,f_.propertyInData)(r,n,o,s.opts.ownProperties);t.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,f_.checkReportMissingProp)(t,u)}):(r.if((0,qN._)`${c} && (${(0,f_.checkMissingProp)(t,a,i)})`),(0,f_.reportMissingProp)(t,i),r.else())}}Pa.validatePropertyDeps=Kee;function Zee(t,e=t.schema){let{gen:r,data:n,keyword:s,it:i}=t,o=r.name("valid");for(let a in e)(0,Z2e.alwaysValidSchema)(i,e[a])||(r.if((0,f_.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},o);t.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),t.ok(o))}Pa.validateSchemaDeps=Zee;Pa.default=G2e});var Xee=v(HN=>{"use strict";Object.defineProperty(HN,"__esModule",{value:!0});var Wee=Bt(),X2e=tr(),J2e={message:"property name must be valid",params:({params:t})=>(0,Wee._)`{propertyName: ${t.propertyName}}`},Y2e={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:J2e,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,X2e.alwaysValidSchema)(s,r))return;let i=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},i),e.if((0,Wee.not)(i),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(i)}};HN.default=Y2e});var VN=v(FN=>{"use strict";Object.defineProperty(FN,"__esModule",{value:!0});var TC=Hi(),Oo=Bt(),Q2e=Lc(),IC=tr(),eAe={message:"must NOT have additional properties",params:({params:t})=>(0,Oo._)`{additionalProperty: ${t.additionalProperty}}`},tAe={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:eAe,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:i,it:o}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,IC.alwaysValidSchema)(o,r))return;let u=(0,TC.allSchemaProperties)(n.properties),l=(0,TC.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Oo._)`${i} === ${Q2e.default.errors}`);function d(){e.forIn("key",s,_=>{!u.length&&!l.length?m(_):e.if(f(_),()=>m(_))})}function f(_){let S;if(u.length>8){let C=(0,IC.schemaRefOrVal)(o,n.properties,"properties");S=(0,TC.isOwnProperty)(e,C,_)}else u.length?S=(0,Oo.or)(...u.map(C=>(0,Oo._)`${_} === ${C}`)):S=Oo.nil;return l.length&&(S=(0,Oo.or)(S,...l.map(C=>(0,Oo._)`${(0,TC.usePattern)(t,C)}.test(${_})`))),(0,Oo.not)(S)}function p(_){e.code((0,Oo._)`delete ${s}[${_}]`)}function m(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(_);return}if(r===!1){t.setParams({additionalProperty:_}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,IC.alwaysValidSchema)(o,r)){let S=e.name("valid");c.removeAdditional==="failing"?(y(_,S,!1),e.if((0,Oo.not)(S),()=>{t.reset(),p(_)})):(y(_,S),a||e.if((0,Oo.not)(S),()=>e.break()))}}function y(_,S,C){let E={keyword:"additionalProperties",dataProp:_,dataPropType:IC.Type.Str};C===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(E,S)}}};FN.default=tAe});var Qee=v(ZN=>{"use strict";Object.defineProperty(ZN,"__esModule",{value:!0});var rAe=Y1(),Jee=Hi(),KN=tr(),Yee=VN(),nAe={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:i}=t;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Yee.default.code(new rAe.KeywordCxt(i,Yee.default,"additionalProperties"));let o=(0,Jee.allSchemaProperties)(r);for(let d of o)i.definedProperties.add(d);i.opts.unevaluated&&o.length&&i.props!==!0&&(i.props=KN.mergeEvaluated.props(e,(0,KN.toHash)(o),i.props));let a=o.filter(d=>!(0,KN.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Jee.propertyInData)(e,s,d,i.opts.ownProperties)),l(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};ZN.default=nAe});var nte=v(GN=>{"use strict";Object.defineProperty(GN,"__esModule",{value:!0});var ete=Hi(),PC=Bt(),tte=tr(),rte=tr(),sAe={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:i}=t,{opts:o}=i,a=(0,ete.allSchemaProperties)(r),c=a.filter(y=>(0,tte.alwaysValidSchema)(i,r[y]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&s.properties,l=e.name("valid");i.props!==!0&&!(i.props instanceof PC.Name)&&(i.props=(0,rte.evaluatedPropsToName)(e,i.props));let{props:d}=i;f();function f(){for(let y of a)u&&p(y),i.allErrors?m(y):(e.var(l,!0),m(y),e.if(l))}function p(y){for(let _ in u)new RegExp(y).test(_)&&(0,tte.checkStrictMode)(i,`property ${_} matches pattern ${y} (use allowMatchingProperties)`)}function m(y){e.forIn("key",n,_=>{e.if((0,PC._)`${(0,ete.usePattern)(t,y)}.test(${_})`,()=>{let S=c.includes(y);S||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:_,dataPropType:rte.Type.Str},l),i.opts.unevaluated&&d!==!0?e.assign((0,PC._)`${d}[${_}]`,!0):!S&&!i.allErrors&&e.if((0,PC.not)(l),()=>e.break())})})}}};GN.default=sAe});var ste=v(WN=>{"use strict";Object.defineProperty(WN,"__esModule",{value:!0});var iAe=tr(),oAe={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,iAe.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};WN.default=oAe});var ite=v(XN=>{"use strict";Object.defineProperty(XN,"__esModule",{value:!0});var aAe=Hi(),cAe={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:aAe.validateUnion,error:{message:"must match a schema in anyOf"}};XN.default=cAe});var ote=v(JN=>{"use strict";Object.defineProperty(JN,"__esModule",{value:!0});var RC=Bt(),uAe=tr(),lAe={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,RC._)`{passingSchemas: ${t.passing}}`},dAe={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:lAe,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let i=r,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(o,()=>t.reset(),()=>t.error(!0));function u(){i.forEach((l,d)=>{let f;(0,uAe.alwaysValidSchema)(s,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,RC._)`${c} && ${o}`).assign(o,!1).assign(a,(0,RC._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&t.mergeEvaluated(f,RC.Name)})})}}};JN.default=dAe});var ate=v(YN=>{"use strict";Object.defineProperty(YN,"__esModule",{value:!0});var fAe=tr(),hAe={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((i,o)=>{if((0,fAe.alwaysValidSchema)(n,i))return;let a=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(a)})}};YN.default=hAe});var lte=v(QN=>{"use strict";Object.defineProperty(QN,"__esModule",{value:!0});var OC=Bt(),ute=tr(),pAe={message:({params:t})=>(0,OC.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,OC._)`{failingKeyword: ${t.ifClause}}`},mAe={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:pAe,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,ute.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=cte(n,"then"),i=cte(n,"else");if(!s&&!i)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&i){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else s?e.if(a,u("then")):e.if((0,OC.not)(a),u("else"));t.pass(o,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let f=t.subschema({keyword:l},a);e.assign(o,a),t.mergeValidEvaluated(f,o),d?e.assign(d,(0,OC._)`${l}`):t.setParams({ifClause:l})}}}};function cte(t,e){let r=t.schema[e];return r!==void 0&&!(0,ute.alwaysValidSchema)(t,r)}QN.default=mAe});var dte=v(eB=>{"use strict";Object.defineProperty(eB,"__esModule",{value:!0});var gAe=tr(),yAe={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,gAe.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};eB.default=yAe});var fte=v(tB=>{"use strict";Object.defineProperty(tB,"__esModule",{value:!0});var xAe=jN(),bAe=qee(),_Ae=zN(),vAe=Fee(),wAe=Vee(),SAe=Gee(),AAe=Xee(),EAe=VN(),CAe=Qee(),kAe=nte(),TAe=ste(),IAe=ite(),PAe=ote(),RAe=ate(),OAe=lte(),NAe=dte();function BAe(t=!1){let e=[TAe.default,IAe.default,PAe.default,RAe.default,OAe.default,NAe.default,AAe.default,EAe.default,SAe.default,CAe.default,kAe.default];return t?e.push(bAe.default,vAe.default):e.push(xAe.default,_Ae.default),e.push(wAe.default),e}tB.default=BAe});var hte=v(rB=>{"use strict";Object.defineProperty(rB,"__esModule",{value:!0});var mn=Bt(),$Ae={message:({schemaCode:t})=>(0,mn.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,mn._)`{format: ${t}}`},MAe={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$Ae,code(t,e){let{gen:r,data:n,$data:s,schema:i,schemaCode:o,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;s?f():p();function f(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=r.const("fDef",(0,mn._)`${m}[${o}]`),_=r.let("fType"),S=r.let("format");r.if((0,mn._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(_,(0,mn._)`${y}.type || "string"`).assign(S,(0,mn._)`${y}.validate`),()=>r.assign(_,(0,mn._)`"string"`).assign(S,y)),t.fail$data((0,mn.or)(C(),E()));function C(){return c.strictSchema===!1?mn.nil:(0,mn._)`${o} && !${S}`}function E(){let B=l.$async?(0,mn._)`(${y}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,mn._)`${S}(${n})`,G=(0,mn._)`(typeof ${S} == "function" ? ${B} : ${S}.test(${n}))`;return(0,mn._)`${S} && ${S} !== true && ${_} === ${e} && !${G}`}}function p(){let m=d.formats[i];if(!m){C();return}if(m===!0)return;let[y,_,S]=E(m);y===e&&t.pass(B());function C(){if(c.strictSchema===!1){d.logger.warn(G());return}throw new Error(G());function G(){return`unknown format "${i}" ignored in schema at path "${u}"`}}function E(G){let se=G instanceof RegExp?(0,mn.regexpCode)(G):c.code.formats?(0,mn._)`${c.code.formats}${(0,mn.getProperty)(i)}`:void 0,_e=r.scopeValue("formats",{key:i,ref:G,code:se});return typeof G=="object"&&!(G instanceof RegExp)?[G.type||"string",G.validate,(0,mn._)`${_e}.validate`]:["string",G,_e]}function B(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,mn._)`await ${S}(${n})`}return typeof _=="function"?(0,mn._)`${S}(${n})`:(0,mn._)`${S}.test(${n})`}}}};rB.default=MAe});var pte=v(nB=>{"use strict";Object.defineProperty(nB,"__esModule",{value:!0});var jAe=hte(),zAe=[jAe.default];nB.default=zAe});var mte=v(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});um.contentVocabulary=um.metadataVocabulary=void 0;um.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];um.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var yte=v(sB=>{"use strict";Object.defineProperty(sB,"__esModule",{value:!0});var LAe=Aee(),DAe=zee(),UAe=fte(),qAe=pte(),gte=mte(),HAe=[LAe.default,DAe.default,(0,UAe.default)(),qAe.default,gte.metadataVocabulary,gte.contentVocabulary];sB.default=HAe});var bte=v(NC=>{"use strict";Object.defineProperty(NC,"__esModule",{value:!0});NC.DiscrError=void 0;var xte;(function(t){t.Tag="tag",t.Mapping="mapping"})(xte||(NC.DiscrError=xte={}))});var vte=v(oB=>{"use strict";Object.defineProperty(oB,"__esModule",{value:!0});var lm=Bt(),iB=bte(),_te=gC(),FAe=Q1(),VAe=tr(),KAe={message:({params:{discrError:t,tagName:e}})=>t===iB.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,lm._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},ZAe={keyword:"discriminator",type:"object",schemaType:"object",error:KAe,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:i}=t,{oneOf:o}=s;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,lm._)`${r}${(0,lm.getProperty)(a)}`);e.if((0,lm._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:iB.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let p=f();e.if(!1);for(let m in p)e.elseIf((0,lm._)`${u} === ${m}`),e.assign(c,d(p[m]));e.else(),t.error(!1,{discrError:iB.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:p},m);return t.mergeEvaluated(y,lm.Name),m}function f(){var p;let m={},y=S(s),_=!0;for(let B=0;B<o.length;B++){let G=o[B];if(G?.$ref&&!(0,VAe.schemaHasRulesButRef)(G,i.self.RULES)){let _e=G.$ref;if(G=_te.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,_e),G instanceof _te.SchemaEnv&&(G=G.schema),G===void 0)throw new FAe.default(i.opts.uriResolver,i.baseId,_e)}let se=(p=G?.properties)===null||p===void 0?void 0:p[a];if(typeof se!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(y||S(G)),C(se,B)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return m;function S({required:B}){return Array.isArray(B)&&B.includes(a)}function C(B,G){if(B.const)E(B.const,G);else if(B.enum)for(let se of B.enum)E(se,G);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(B,G){if(typeof B!="string"||B in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[B]=G}}}};oB.default=ZAe});var wte=v((IMe,GAe)=>{GAe.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var cB=v((Fr,aB)=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.MissingRefError=Fr.ValidationError=Fr.CodeGen=Fr.Name=Fr.nil=Fr.stringify=Fr.str=Fr._=Fr.KeywordCxt=Fr.Ajv=void 0;var WAe=xee(),XAe=yte(),JAe=vte(),Ste=wte(),YAe=["/properties"],BC="http://json-schema.org/draft-07/schema",dm=class extends WAe.default{_addVocabularies(){super._addVocabularies(),XAe.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(JAe.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ste,YAe):Ste;this.addMetaSchema(e,BC,!1),this.refs["http://json-schema.org/schema"]=BC}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(BC)?BC:void 0)}};Fr.Ajv=dm;aB.exports=Fr=dm;aB.exports.Ajv=dm;Object.defineProperty(Fr,"__esModule",{value:!0});Fr.default=dm;var QAe=Y1();Object.defineProperty(Fr,"KeywordCxt",{enumerable:!0,get:function(){return QAe.KeywordCxt}});var fm=Bt();Object.defineProperty(Fr,"_",{enumerable:!0,get:function(){return fm._}});Object.defineProperty(Fr,"str",{enumerable:!0,get:function(){return fm.str}});Object.defineProperty(Fr,"stringify",{enumerable:!0,get:function(){return fm.stringify}});Object.defineProperty(Fr,"nil",{enumerable:!0,get:function(){return fm.nil}});Object.defineProperty(Fr,"Name",{enumerable:!0,get:function(){return fm.Name}});Object.defineProperty(Fr,"CodeGen",{enumerable:!0,get:function(){return fm.CodeGen}});var eEe=pC();Object.defineProperty(Fr,"ValidationError",{enumerable:!0,get:function(){return eEe.default}});var tEe=Q1();Object.defineProperty(Fr,"MissingRefError",{enumerable:!0,get:function(){return tEe.default}})});var Rte=v(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.formatNames=Oa.fastFormats=Oa.fullFormats=void 0;function Ra(t,e){return{validate:t,compare:e}}Oa.fullFormats={date:Ra(kte,fB),time:Ra(lB(!0),hB),"date-time":Ra(Ate(!0),Ite),"iso-time":Ra(lB(),Tte),"iso-date-time":Ra(Ate(),Pte),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:aEe,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:pEe,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:cEe,int32:{type:"number",validate:dEe},int64:{type:"number",validate:fEe},float:{type:"number",validate:Cte},double:{type:"number",validate:Cte},password:!0,binary:!0};Oa.fastFormats={...Oa.fullFormats,date:Ra(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,fB),time:Ra(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,hB),"date-time":Ra(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ite),"iso-time":Ra(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Tte),"iso-date-time":Ra(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Pte),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Oa.formatNames=Object.keys(Oa.fullFormats);function rEe(t){return t%4===0&&(t%100!==0||t%400===0)}var nEe=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,sEe=[0,31,28,31,30,31,30,31,31,30,31,30,31];function kte(t){let e=nEe.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&rEe(r)?29:sEe[n])}function fB(t,e){if(t&&e)return t>e?1:t<e?-1:0}var uB=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function lB(t){return function(r){let n=uB.exec(r);if(!n)return!1;let s=+n[1],i=+n[2],o=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(s<=23&&i<=59&&o<60)return!0;let d=i-l*c,f=s-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function hB(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Tte(t,e){if(!(t&&e))return;let r=uB.exec(t),n=uB.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var dB=/t|\s/i;function Ate(t){let e=lB(t);return function(n){let s=n.split(dB);return s.length===2&&kte(s[0])&&e(s[1])}}function Ite(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Pte(t,e){if(!(t&&e))return;let[r,n]=t.split(dB),[s,i]=e.split(dB),o=fB(r,s);if(o!==void 0)return o||hB(n,i)}var iEe=/\/|:/,oEe=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function aEe(t){return iEe.test(t)&&oEe.test(t)}var Ete=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function cEe(t){return Ete.lastIndex=0,Ete.test(t)}var uEe=-(2**31),lEe=2**31-1;function dEe(t){return Number.isInteger(t)&&t<=lEe&&t>=uEe}function fEe(t){return Number.isInteger(t)}function Cte(){return!0}var hEe=/[^\\]\\Z/;function pEe(t){if(hEe.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ote=v(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});hm.formatLimitDefinition=void 0;var mEe=cB(),No=Bt(),dl=No.operators,$C={formatMaximum:{okStr:"<=",ok:dl.LTE,fail:dl.GT},formatMinimum:{okStr:">=",ok:dl.GTE,fail:dl.LT},formatExclusiveMaximum:{okStr:"<",ok:dl.LT,fail:dl.GTE},formatExclusiveMinimum:{okStr:">",ok:dl.GT,fail:dl.LTE}},gEe={message:({keyword:t,schemaCode:e})=>(0,No.str)`should be ${$C[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,No._)`{comparison: ${$C[t].okStr}, limit: ${e}}`};hm.formatLimitDefinition={keyword:Object.keys($C),type:"string",schemaType:"string",$data:!0,error:gEe,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:i}=t,{opts:o,self:a}=i;if(!o.validateFormats)return;let c=new mEe.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,No._)`${f}[${c.schemaCode}]`);t.fail$data((0,No.or)((0,No._)`typeof ${p} != "object"`,(0,No._)`${p} instanceof RegExp`,(0,No._)`typeof ${p}.compare != "function"`,d(p)))}function l(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${s}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,No._)`${o.code.formats}${(0,No.getProperty)(f)}`:void 0});t.fail$data(d(m))}function d(f){return(0,No._)`${f}.compare(${r}, ${n}) ${$C[s].fail} 0`}},dependencies:["format"]};var yEe=t=>(t.addKeyword(hm.formatLimitDefinition),t);hm.default=yEe});var Mte=v((h_,$te)=>{"use strict";Object.defineProperty(h_,"__esModule",{value:!0});var pm=Rte(),xEe=Ote(),pB=Bt(),Nte=new pB.Name("fullFormats"),bEe=new pB.Name("fastFormats"),mB=(t,e={keywords:!0})=>{if(Array.isArray(e))return Bte(t,e,pm.fullFormats,Nte),t;let[r,n]=e.mode==="fast"?[pm.fastFormats,bEe]:[pm.fullFormats,Nte],s=e.formats||pm.formatNames;return Bte(t,s,r,n),e.keywords&&(0,xEe.default)(t),t};mB.get=(t,e="full")=>{let n=(e==="fast"?pm.fastFormats:pm.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Bte(t,e,r,n){var s,i;(s=(i=t.opts.code).formats)!==null&&s!==void 0||(i.formats=(0,pB._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)t.addFormat(o,r[o])}$te.exports=h_=mB;Object.defineProperty(h_,"__esModule",{value:!0});h_.default=mB});import{createRequire as OEe}from"node:module";$o();import*as RB from"node:http";import{randomBytes as hre}from"node:crypto";import{spawn as ZC}from"node:child_process";var pre=5*6e4,mre=`<!doctype html><html><head><meta charset="utf-8"><title>OIOXO CLI connected</title></head>
|
|
50
198
|
<body style="margin:0;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fafafa;font-family:ui-sans-serif,system-ui,Segoe UI,sans-serif">
|
|
51
199
|
<div style="background:#fff;border-radius:16px;box-shadow:0 10px 30px rgba(0,0,0,.08);padding:28px;max-width:380px">
|
|
52
200
|
<div style="display:flex;align-items:center;gap:8px;margin-bottom:18px">
|
|
@@ -54,129 +202,153 @@ Free accounts include a monthly allowance; OIOXO Pro is unlimited \u2192 ${nr}`}
|
|
|
54
202
|
<span style="font-family:ui-monospace,monospace;font-size:13px;font-weight:500;color:#232327">OIOXO</span></div>
|
|
55
203
|
<h1 style="font-size:17px;margin:0 0 8px;color:#232327">OIOXO CLI connected</h1>
|
|
56
204
|
<p style="font-size:13.5px;line-height:1.6;color:#71717a;margin:0">You can close this tab and return to your terminal.</p>
|
|
57
|
-
</div></body></html>`;function
|
|
205
|
+
</div></body></html>`;function gre(t){let e=process.platform;e==="win32"?ZC("explorer.exe",[t],{detached:!0,stdio:"ignore"}).unref():e==="darwin"?ZC("open",[t],{detached:!0,stdio:"ignore"}).unref():ZC("xdg-open",[t],{detached:!0,stdio:"ignore"}).unref()}async function b_(){let t=hre(24).toString("base64url"),e=await Cm(),r=new Promise((o,a)=>{let c=RB.createServer((u,l)=>{let d=new URL(gn).origin;if(l.setHeader("Access-Control-Allow-Origin",d),l.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),l.setHeader("Access-Control-Allow-Headers","content-type"),l.setHeader("Access-Control-Allow-Private-Network","true"),u.method==="OPTIONS"){l.writeHead(204).end();return}if(u.method!=="POST"||u.url!=="/oioxo/token"){l.writeHead(404).end();return}let f="";u.on("data",p=>{f+=p,f.length>64e3&&u.destroy()}),u.on("end",()=>{try{let p=u.headers["content-type"]??"",m;if(p.includes("application/json"))m=JSON.parse(f);else{let y=new URLSearchParams(f);m={state:y.get("state")??void 0,token:y.get("token")??void 0,expiresInSeconds:y.get("expiresInSeconds")?Number(y.get("expiresInSeconds")):void 0}}if(m.state!==t||!m.token){l.writeHead(400,{"content-type":"text/html"}).end("<p>OIOXO: invalid or expired login request. Run <code>oioxo-mcp login</code> again.</p>"),c.close(),a(new Error("Invalid or expired login request"));return}l.writeHead(200,{"content-type":"text/html"}).end(mre),c.close(),o({token:m.token,expiresInSeconds:m.expiresInSeconds})}catch{l.writeHead(400).end(),c.close(),a(new Error("Failed to parse login response"))}}),u.on("error",()=>{c.close(),a(new Error("Connection lost during login"))})});c.on("error",a),c.listen(0,"127.0.0.1",()=>{let u=c.address(),l=typeof u=="object"&&u?u.port:0,d=`${gn}/cli-auth?port=${l}&state=${t}`;console.log(`
|
|
58
206
|
OIOXO \u2014 connect your account`),console.log(`Opening ${d}`),console.log(`If the browser does not open, paste the URL yourself.
|
|
59
|
-
`),process.env.OIOXO_NO_BROWSER!=="1"&&
|
|
60
|
-
`,"utf8")}async function
|
|
207
|
+
`),process.env.OIOXO_NO_BROWSER!=="1"&&gre(d)}),setTimeout(()=>{c.close(),a(new Error("timeout"))},pre).unref()}),{token:n,expiresInSeconds:s}=await r;await TB({token:n,expiresAt:Date.now()+(s??720*3600)*1e3,device:e});let i=await ms("check");if(i?.tier==="pro")console.log("Connected \u2014 OIOXO Pro: unlimited context engine. \u2713");else if(i?.tier==="free"){let o=i.remainingTokens?.toLocaleString()??"\u2014";console.log(`Connected \u2014 OIOXO Free: ${o} saved-tokens remaining this month. Pro is unlimited \u2192 https://oioxo.com/?upgrade=pro \u2713`)}else console.log("Connected. \u2713")}import{promises as ks}from"node:fs";import*as Yr from"node:path";import*as JC from"node:os";import{spawnSync as yre}from"node:child_process";var GC=t=>{try{let e=process.platform==="win32"?"where":"which";return yre(e,[t],{stdio:"ignore",timeout:4e3}).status===0}catch{return!1}},km=async t=>{try{return(await ks.stat(t)).isDirectory()}catch{return!1}},OB=[{id:"claude-code",display:"Claude Code",kind:"json",key:"mcpServers",file:t=>Yr.join(t,".mcp.json"),detect:async()=>GC("claude")},{id:"vscode-copilot",display:"VS Code / GitHub Copilot",kind:"json",key:"servers",file:t=>Yr.join(t,".vscode","mcp.json"),detect:async t=>await km(Yr.join(t,".vscode"))||GC("code")},{id:"cursor",display:"Cursor",kind:"json",key:"mcpServers",file:t=>Yr.join(t,".cursor","mcp.json"),detect:async t=>await km(Yr.join(t,".cursor"))||GC("cursor")},{id:"windsurf",display:"Windsurf",kind:"json",key:"mcpServers",global:!0,file:(t,e)=>Yr.join(e,".codeium","windsurf","mcp_config.json"),detect:async(t,e)=>km(Yr.join(e,".codeium","windsurf"))},{id:"gemini-cli",display:"Gemini CLI",kind:"json",key:"mcpServers",global:!0,file:(t,e)=>Yr.join(e,".gemini","settings.json"),detect:async(t,e)=>km(Yr.join(e,".gemini"))},{id:"codex",display:"Codex CLI",kind:"toml",global:!0,file:(t,e)=>Yr.join(e,".codex","config.toml"),detect:async(t,e)=>km(Yr.join(e,".codex"))}];function xre(t){if(t){let[e,...r]=t.split(" ");return{command:e,args:[...r,"serve"]}}return{command:"npx",args:["-y","oioxo-mcp","serve"]}}async function bre(t,e,r){let n={};try{n=JSON.parse(await ks.readFile(t,"utf8"))}catch{}let s=n[e]??{};s.oioxo=r,n[e]=s,await ks.mkdir(Yr.dirname(t),{recursive:!0}),await ks.writeFile(t,JSON.stringify(n,null,2)+`
|
|
208
|
+
`,"utf8")}async function _re(t,e){let r="";try{r=await ks.readFile(t,"utf8")}catch{}if(/^\s*\[mcp_servers\.oioxo\]/m.test(r))return!1;let n=`
|
|
61
209
|
[mcp_servers.oioxo]
|
|
62
210
|
command = "${e.command}"
|
|
63
|
-
args = [${e.args.map(
|
|
64
|
-
`;return await
|
|
211
|
+
args = [${e.args.map(s=>`"${s}"`).join(", ")}]
|
|
212
|
+
`;return await ks.mkdir(Yr.dirname(t),{recursive:!0}),await ks.writeFile(t,r+n,"utf8"),!0}var NB="<!-- oioxo:start -->",XC="<!-- oioxo:end -->",WC=`${NB}
|
|
65
213
|
## OIOXO context engine (use it FIRST)
|
|
66
214
|
This project is wired to the OIOXO MCP server. BEFORE reading, searching or listing files yourself, ALWAYS call the \`get_context\` tool from the \`oioxo\` MCP server with the task as the query \u2014 it returns the minimal relevant code slice (10-20x fewer tokens than reading files). Use \`get_impact\` before refactors, \`get_skeleton\` to learn an API cheaply, and \`remember\` to persist durable project facts.
|
|
67
|
-
${
|
|
68
|
-
|
|
69
|
-
`+
|
|
70
|
-
`:
|
|
71
|
-
`;try{await
|
|
72
|
-
`,"utf8"),!0)}async function
|
|
73
|
-
OIOXO \u2014 wiring the context engine into your agents`);for(let
|
|
74
|
-
Restart your agent (or reload the window) and it will call OIOXO before reading files.`),console.log("Not connected yet? Run `oioxo-mcp login`.")}async function
|
|
75
|
-
`);for(let a=0;a<
|
|
76
|
-
`).slice(0,4e3);if(u.trim()){let l
|
|
77
|
-
`);for(let a=0;a<
|
|
215
|
+
${XC}`;async function vre(t){let e="";try{e=await ks.readFile(t,"utf8")}catch{}let r=e.indexOf(NB),n=e.indexOf(XC),s;r>=0&&n>r?s=e.slice(0,r)+WC+e.slice(n+XC.length):s=e?e.trimEnd()+`
|
|
216
|
+
|
|
217
|
+
`+WC+`
|
|
218
|
+
`:WC+`
|
|
219
|
+
`;try{await ks.mkdir(Yr.dirname(t),{recursive:!0}),await ks.writeFile(t,s,"utf8")}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`OIOXO: could not write ${t} (${o}). Check that the directory is writable.`)}}async function wre(t){let e=[Yr.join(t,".github","copilot-instructions.md"),Yr.join(t,"CLAUDE.md"),Yr.join(t,".cursor","rules","oioxo.mdc")];for(let r of e)await vre(r);return e}var Sre="OIOXO reminder",Are=`node -e "console.log('OIOXO reminder: before reading or searching project files for a code task, call the oioxo MCP get_context tool with the task as the query - it returns the minimal relevant slice at about 90 percent fewer context tokens. Use get_skeleton to learn an API cheaply and get_impact before refactors.')"`;async function Ere(t){let e=Yr.join(t,".claude","settings.json"),r={};try{r=JSON.parse(await ks.readFile(e,"utf8"))}catch{}let n=r.hooks??{},s=Array.isArray(n.UserPromptSubmit)?n.UserPromptSubmit:[];return s.some(o=>Array.isArray(o?.hooks)&&o.hooks.some(a=>typeof a?.command=="string"&&a.command.includes(Sre)))?!1:(s.push({hooks:[{type:"command",command:Are}]}),n.UserPromptSubmit=s,r.hooks=n,await ks.mkdir(Yr.dirname(e),{recursive:!0}),await ks.writeFile(e,JSON.stringify(r,null,2)+`
|
|
220
|
+
`,"utf8"),!0)}async function BB(t,e={}){let r=e.home??JC.homedir(),n=xre(e.command),s=0;console.log(`
|
|
221
|
+
OIOXO \u2014 wiring the context engine into your agents`);for(let i of OB){if(!(i.global?await i.detect(t,r):e.all||await i.detect(t,r))){console.log(` \xB7 ${i.display}: not detected${i.global?"":" (use --all to force)"}`);continue}let a=i.file(t,r);if(i.kind==="toml"){let c=await _re(a,n);console.log(c?` \u2713 ${i.display}: ${a}`:` \u2713 ${i.display}: already configured (${a})`)}else await bre(a,i.key,n),console.log(` \u2713 ${i.display}: ${i.global?a:Yr.relative(t,a)}`);s++}if(!s){console.log(" No agents detected. Run with --all to write the project configs anyway.");return}await wre(t),console.log(" \u2713 Agent instructions: .github/copilot-instructions.md, CLAUDE.md, .cursor/rules/oioxo.mdc"),await Ere(t)&&console.log(" \u2713 Claude Code hook: .claude/settings.json (per-prompt OIOXO reminder)"),console.log(`
|
|
222
|
+
Restart your agent (or reload the window) and it will call OIOXO before reading files.`),console.log("Not connected yet? Run `oioxo-mcp login`.")}async function YC(t,e=JC.homedir()){let r=[];for(let n of OB){let s=!1;try{await ks.access(n.file(t,e)),s=!0}catch{}r.push({id:n.id,display:n.display,detected:await n.detect(t,e),configured:s})}return r}import{writeFile as Ine,mkdir as Pne,readFile as Rne}from"node:fs/promises";import Nm from"node:path";import{createInterface as y$}from"node:readline/promises";import{spawn as Wre}from"node:child_process";import{mkdtemp as Xre,writeFile as Jre,mkdir as Yre,readFile as tk,rm as Qre}from"node:fs/promises";import{tmpdir as ene}from"node:os";import Hc from"node:path";import{promises as QC}from"node:fs";import*as Tm from"node:path";var Cre=1500,kre=256*1024,Tre=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".py",".go",".rs",".java",".rb",".php",".c",".h",".cpp",".cs",".swift",".kt",".vue",".svelte",".css",".scss",".html",".json",".md",".yml",".yaml",".sql",".sh"]),Ire=new Set(["node_modules",".git","dist","build","out",".next","coverage","vendor",".oioxo",".vscode",".cursor",".idea","__pycache__",".venv","venv"]);function Pre(t){let e=Math.min(t.length,1024);for(let r=0;r<e;r++)if(t.charCodeAt(r)===0)return!0;return!1}var Rre=t=>/\.min\.[a-z]+$/.test(t);async function Ore(t,e={}){let r=e.maxFiles??Cre,n=[],s=[""];for(;s.length&&n.length<r;){let i=s.shift(),o;try{o=await QC.readdir(Tm.join(t,i),{withFileTypes:!0})}catch{continue}o.sort((a,c)=>a.name.localeCompare(c.name));for(let a of o){if(n.length>=r)break;let c=i?`${i}/${a.name}`:a.name;a.isDirectory()?!Ire.has(a.name)&&!a.name.startsWith(".")&&s.push(c):a.isFile()&&Tre.has(Tm.extname(a.name).toLowerCase())&&!Rre(a.name)&&n.push(c)}}return n}async function Nre(t,e){let r=Tm.join(t,e);try{if((await QC.stat(r)).size>kre)return null;let s=await QC.readFile(r,"utf8");return!s||Pre(s)?null:{path:e.replace(/\\/g,"/"),content:s}}catch{return null}}async function Yf(t,e={}){let r=await Ore(t,e),n=[];for(let s of r){let i=await Nre(t,s);i&&n.push(i)}return n}function $B(t){let e=t.toLowerCase().match(/[a-z0-9_]+/g)??[],r=[];for(let n of e){r.push(n);for(let s of n.split("_"))s&&s!==n&&r.push(s)}for(let n of t.match(/[A-Za-z][a-z0-9]+|[A-Z]+(?![a-z])/g)??[]){let s=n.toLowerCase();s.length>1&&r.push(s)}return r.filter(n=>n.length>1&&n.length<40)}var qc=class{chunks=[];df=new Map;avgLen=0;_status={files:0,chunks:0};status(){return this._status}build(e){let r=[];for(let i of e){let o=i.content.split(`
|
|
223
|
+
`);for(let a=0;a<o.length;a+=48){let u=o.slice(a,a+60).join(`
|
|
224
|
+
`).slice(0,4e3);if(u.trim()){let l=$B(u);if(l.length){let d=new Map;for(let f of l)d.set(f,(d.get(f)??0)+1);r.push({path:i.path,startLine:a+1,endLine:Math.min(a+60,o.length),text:u,tf:d,len:l.length})}}if(a+60>=o.length)break}}let n=new Map,s=0;for(let i of r){s+=i.len;for(let o of i.tf.keys())n.set(o,(n.get(o)??0)+1)}return this.chunks=r,this.df=n,this.avgLen=r.length?s/r.length:0,this._status={files:e.length,chunks:r.length},this._status}retrieve(e,r=6){if(!this.chunks.length)return[];let n=$B(e);if(!n.length)return[];let s=this.chunks.length,i=1.5,o=.75,a=this.chunks.map(c=>{let u=0;for(let l of n){let d=c.tf.get(l);if(!d)continue;let f=this.df.get(l)??0,p=Math.log(1+(s-f+.5)/(f+.5)),m=d+i*(1-o+o*(c.len/(this.avgLen||1)));u+=p*(d*(i+1)/m)}return{c,score:u}}).filter(c=>c.score>0);return a.sort((c,u)=>u.score-c.score),a.slice(0,r).map(({c,score:u})=>({path:c.path,startLine:c.startLine,endLine:c.endLine,text:c.text,score:u}))}};var Bre=/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;function $re(t){let e=[],r=[/import\s+[^'"]*?from\s*['"]([^'"]+)['"]/g,/import\s*['"]([^'"]+)['"]/g,/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/export\s+[^'"]*?from\s*['"]([^'"]+)['"]/g];for(let n of r){let s;for(;s=n.exec(t);)e.push(s[1])}return e}function Mre(t){let e=t.split("/"),r=[];for(let n of e)n===""||n==="."||(n===".."?r.pop():r.push(n));return r.join("/")}var jre=t=>t.split("/").slice(0,-1).join("/");function zre(t,e,r){if(!t.startsWith("."))return null;let n=Mre(jre(e)+"/"+t),s=["",".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"];for(let i of s)if(r.has(n+i))return n+i;for(let i of s.slice(1))if(r.has(n+"/index"+i))return n+"/index"+i;return null}function __(t){let e=t.filter(i=>Bre.test(i.path)),r=new Set(e.map(i=>i.path)),n=new Map,s=new Map;for(let i of e){let o=[];for(let a of $re(i.content)){let c=zre(a,i.path,r);c&&c!==i.path&&!o.includes(c)&&o.push(c)}n.set(i.path,o);for(let a of o){let c=s.get(a)??[];c.includes(i.path)||c.push(i.path),s.set(a,c)}}return{deps:n,dependents:s}}function MB(t,e,r={}){let n=r.hops??2,s=r.max??12,i=new Set(e),o=[...e];for(let a=0;a<n&&i.size<s;a++){let c=[];for(let u of o){for(let l of t.deps.get(u)??[])if(!i.has(l)&&(i.add(l),c.push(l),i.size>=s))break;if(r.includeDependents&&a===0){for(let l of t.dependents.get(u)??[])if(!i.has(l)&&(i.add(l),c.push(l),i.size>=s))break}if(i.size>=s)break}o=c}return[...e,...Array.from(i).filter(a=>!e.includes(a))].slice(0,s)}var Lre={test:/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,patterns:[{re:/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*(?<name>[A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\([^)]*\)?[^{;]*/,kind:"function"},{re:/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+(?<name>[A-Za-z_$][\w$]*)[^{]*/,kind:"class"},{re:/^\s*(?:export\s+)?interface\s+(?<name>[A-Za-z_$][\w$]*)[^{]*/,kind:"interface"},{re:/^\s*(?:export\s+)?type\s+(?<name>[A-Za-z_$][\w$]*)\s*=?.*/,kind:"type"},{re:/^\s*(?:export\s+)?enum\s+(?<name>[A-Za-z_$][\w$]*).*/,kind:"enum"},{re:/^\s*export\s+(?:const|let|var)\s+(?<name>[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=?.*/,kind:"const"}]},Dre={test:/\.py$/,patterns:[{re:/^\s*(?:async\s+)?def\s+(?<name>\w+)\s*\([^)]*\)?[^:]*/,kind:"function"},{re:/^\s*class\s+(?<name>\w+).*/,kind:"class"}]},Ure={test:/\.go$/,patterns:[{re:/^\s*func\s+(?:\([^)]+\)\s*)?(?<name>\w+)\s*\([^)]*\)?[^{]*/,kind:"func"},{re:/^\s*type\s+(?<name>\w+)\s+(?:struct|interface).*/,kind:"type"}]},qre={test:/\.rs$/,patterns:[{re:/^\s*(?:pub\s+)?(?:async\s+)?fn\s+(?<name>\w+)\s*(?:<[^>]*>)?\([^)]*\)?[^{]*/,kind:"fn"},{re:/^\s*(?:pub\s+)?(?:struct|enum|trait)\s+(?<name>\w+).*/,kind:"type"},{re:/^\s*impl(?:<[^>]*>)?\s+(?<name>[\w:]+).*/,kind:"impl"}]},Hre={test:/\.(java|cs|kt|swift|c|h|cpp|php|rb)$/,patterns:[{re:/^\s*(?:public|private|protected|internal|static|final|abstract|override|\s)*\s*(?:class|interface|struct|enum|trait|module)\s+(?<name>\w+).*/,kind:"class"},{re:/^\s*(?:public|private|protected|internal|static|final|virtual|override|async|func|def|\s)+[\w<>\[\],\s*&]*?\b(?<name>\w+)\s*\([^)]*\)?\s*[^{;]*/,kind:"method"}]},Fre=[Lre,Dre,Ure,qre,Hre],Vre=t=>t.replace(/\s+/g," ").trim().slice(0,240);function Kre(t,e,r=80){let n=Fre.find(a=>a.test.test(t));if(!n)return[];let s=[],i=e.split(`
|
|
225
|
+
`);for(let a=0;a<i.length&&s.length<r;a++){let c=i[a];if(!(!c.trim()||c.trim().startsWith("//")||c.trim().startsWith("#")||c.trim().startsWith("*")))for(let{re:u,kind:l}of n.patterns){let d=u.exec(c),f=d?.groups?.name;if(d&&f){let p=c;if(p.includes("(")&&!p.includes(")"))for(let y=a+1;y<Math.min(a+4,i.length)&&(p+=" "+i[y],!i[y].includes(")"));y++);let m=p.indexOf("{");m>0&&(p=p.slice(0,m)),s.push({file:t,name:f,kind:l,signature:Vre(p),line:a+1});break}}}let o=new Set;return s.filter(a=>{let c=`${a.name}:${a.line}`;return o.has(c)?!1:(o.add(c),!0)})}function v_(t,e){let r=Kre(t,e);if(!r.length){let n=e.split(`
|
|
78
226
|
`).slice(0,12).join(`
|
|
79
227
|
`);return`// ${t} (excerpt)
|
|
80
228
|
${n}`}return`// ${t} \u2014 API surface (bodies omitted)
|
|
81
229
|
${r.map(n=>`${n.kind} ${n.signature} [L${n.line}]`).join(`
|
|
82
|
-
`)}`}var
|
|
83
|
-
${
|
|
84
|
-
|
|
85
|
-
`),files:e.map(
|
|
86
|
-
`);
|
|
87
|
-
${
|
|
88
|
-
${
|
|
89
|
-
`)}`)}for(let
|
|
90
|
-
|
|
91
|
-
`);
|
|
92
|
-
// \u2026 capsule truncated`);let
|
|
93
|
-
[timed out]`})},r);
|
|
94
|
-
`+String(c)})})})}function
|
|
95
|
-
`),n=/\b(error|fail(ed|ing)?|exception|expected|received|assert|cannot find|is not|undefined|TypeError|SyntaxError|TS\d{3,})\b/i,
|
|
96
|
-
`).slice(0,3e3)}var
|
|
97
|
-
\xB7 ${f===0?"drafting":`repair ${f}`} with ${t.coder.label}\u2026`);let
|
|
98
|
-
OIOXO config (~/.oioxo/config.json):`);for(let
|
|
230
|
+
`)}`}var Zre=4;function w_(t,e,r,n={}){let s=n.topChunks??6,i=n.maxFiles??10,o=n.maxChars??24e3,a=new Map(e.map(C=>[C.path,C])),c=e.reduce((C,E)=>C+E.content.length,0);if(c>0&&c<=o*.8)return{text:e.map(E=>`// ${E.path}
|
|
231
|
+
${E.content}`).join(`
|
|
232
|
+
|
|
233
|
+
`),files:e.map(E=>E.path),savedTokens:0,chunks:[]};let u=r.retrieve(t,s),l=[];for(let C of u)l.includes(C.path)||l.push(C.path);let d=l.slice(0,i);try{let C=__(e);d=MB(C,l.slice(0,3),{hops:2,includeDependents:!0,max:i});for(let E of l)!d.includes(E)&&d.length<i&&d.push(E)}catch{}let f=[],p=new Set(l),m=new Map;for(let C of u){let E=m.get(C.path)??[];E.push({start:C.startLine,end:C.endLine}),m.set(C.path,E)}for(let[C,E]of m){let B=a.get(C);if(!B)continue;let G=B.content.split(`
|
|
234
|
+
`);E.sort((he,J)=>he.start-J.start);let se=[];for(let he of E){let J=se[se.length-1];J&&he.start<=J.end+1?J.end=Math.max(J.end,he.end):se.push({...he})}if(se.reduce((he,J)=>he+(J.end-J.start+1),0)>=G.length*.7)f.push(`// ${C} (full)
|
|
235
|
+
${B.content}`);else for(let he of se)f.push(`// ${C}:${he.start}-${he.end}
|
|
236
|
+
${G.slice(he.start-1,he.end).join(`
|
|
237
|
+
`)}`)}for(let C of d){if(p.has(C))continue;let E=a.get(C);if(!E)continue;let B=v_(E.path,E.content);B.length<E.content.length*.8&&f.push(B)}let y=f.join(`
|
|
238
|
+
|
|
239
|
+
`);y.length>o&&(y=y.slice(0,o)+`
|
|
240
|
+
// \u2026 capsule truncated`);let _=0;for(let C of d.length?d:l)_+=a.get(C)?.content.length??0;let S=Math.max(0,Math.round((_-y.length)/Zre));return{text:y,files:d.length?d:l,savedTokens:S,chunks:u}}S_();function tne(t,e,r=18e4){return r=r??18e4,new Promise(n=>{let s=Wre(t,{cwd:e,shell:!0}),i="",o=c=>{i+=c.toString(),i.length>2e5&&(i=i.slice(-2e5))};s.stdout.on("data",o),s.stderr.on("data",o);let a=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}n({code:124,out:i+`
|
|
241
|
+
[timed out]`})},r);s.on("close",c=>{clearTimeout(a),n({code:c??1,out:i})}),s.on("error",c=>{clearTimeout(a),n({code:1,out:i+`
|
|
242
|
+
`+String(c)})})})}function rne(t,e=40){let r=t.split(`
|
|
243
|
+
`),n=/\b(error|fail(ed|ing)?|exception|expected|received|assert|cannot find|is not|undefined|TypeError|SyntaxError|TS\d{3,})\b/i,s=[];for(let i=0;i<r.length&&s.length<e;i++)if(n.test(r[i]))for(let o=Math.max(0,i-1);o<=Math.min(r.length-1,i+1);o++)s.includes(r[o])||s.push(r[o]);return(s.length?s:r.slice(-e)).join(`
|
|
244
|
+
`).slice(0,3e3)}var nne=new RegExp("(^|/)(package\\.json|package-lock\\.json|pnpm-lock\\.yaml|yarn\\.lock|\\.npmrc|\\.yarnrc|\\.yarnrc\\.yml|Makefile|[^/]+\\.config\\.(c|m)?(j|t)s|(jest|vitest|vite|playwright|cypress|ava|karma|webpack|rollup|babel|eslint|prettier|tailwind|postcss|next|nuxt|svelte|astro)\\.config\\.(c|m)?(j|t)s|\\.(babelrc|mocharc|eslintrc|prettierrc|stylelintrc|swcrc)\\.(c|m)?(j|t)s)$","i");async function HB(t,e,r={}){let n=[],s=r.containRoot?Hc.resolve(r.containRoot):null;for(let i of e){let o=Hc.resolve(t,i.path);if(s&&o!==s&&!o.startsWith(s+Hc.sep)){n.push(i.path);continue}if(!r.seed&&nne.test(i.path.replace(/\\/g,"/"))){n.push(i.path);continue}await Yre(Hc.dirname(o),{recursive:!0}),await Jre(o,i.content,"utf8")}return n}async function sne(t){try{let e=JSON.parse(await tk(Hc.join(t,"package.json"),"utf8"));if(e.scripts?.test&&!/no test specified/i.test(e.scripts.test))return"npm test";if(e.scripts?.typecheck)return"npm run typecheck"}catch{}try{return await tk(Hc.join(t,"tsconfig.json"),"utf8"),await tk(Hc.join(t,"node_modules",".bin",process.platform==="win32"?"tsc.cmd":"tsc"),"utf8"),"npm exec --no -- tsc --noEmit"}catch{}return""}async function FB(t){let e=t.onNote??(()=>{}),r=Math.max(1,t.maxIters??4),n=t.verifyCmd??await sne(t.root);e("\xB7 reading the repo + building the OIOXO context capsule\u2026");let s=await Yf(t.root),i=new qc;i.build(s);let o=w_(t.task,s,i,{maxChars:24e3});e(`\xB7 capsule: ${o.files.length} files, ~${o.savedTokens.toLocaleString()} tokens saved vs reading them whole`),e(n?`\xB7 verify command: ${n}`:"\xB7 no test/typecheck found \u2014 running a single pass without a verify oracle");let a=await Xre(Hc.join(ene(),"oioxo-code-"));try{await HB(a,s.map(f=>({path:f.path,content:f.content})),{containRoot:a,seed:!0});let c={edits:[],out:"",ok:!1},u,l=!n,d=!1;for(let f=0;f<r;f++){e(`
|
|
245
|
+
\xB7 ${f===0?"drafting":`repair ${f}`} with ${t.coder.label}\u2026`);let p;try{p=await t.coder.generate({task:t.task,grounding:o.text,error:u,attempt:f})}catch(C){let E=String(C.message||C);return{ok:!1,edits:c.edits,iters:f,savedTokens:o.savedTokens,lastOutput:E,coderError:E}}if(!p.length){if(e("\xB7 the coder proposed no changes."),f===0)break;break}e(`\xB7 proposed ${p.length} file change${p.length===1?"":"s"}: ${p.map(C=>C.path).join(", ")}`);let m=await HB(a,p,{containRoot:a});m.length&&e(`\xB7 \u26A0 refused ${m.length} unsafe edit(s) (path escape or executable manifest): ${m.join(", ")}`);let y=p.filter(C=>!m.includes(C.path));if(c.edits=ine(c.edits,y),!n){c={edits:c.edits,out:"\u2713 (no verify oracle configured)",ok:!0};break}if(d||(d=!0,l=t.onConfirmRun?await t.onConfirmRun(n).catch(()=>!1):!0,l||e("\xB7 skipping verification (not approved) \u2014 the diff is shown unverified.")),!l){c={edits:c.edits,out:"(verification skipped \u2014 not approved)",ok:!1};break}e("\xB7 verifying on your machine\u2026");let{code:_,out:S}=await tne(n,a,bl()?.verifyTimeoutMs);if(_===0){e("\xB7 \u2713 verified green."),c={edits:c.edits,out:S,ok:!0};break}u=rne(S),e(`\xB7 \u2717 verify failed (exit ${_}) \u2014 feeding the error back.`),c={edits:c.edits,out:S,ok:!1}}return{ok:c.ok,edits:c.edits,iters:r,savedTokens:o.savedTokens,lastOutput:c.out}}finally{await Qre(a,{recursive:!0,force:!0}).catch(()=>{})}}function ine(t,e){let r=new Map(t.map(n=>[n.path,n.content]));for(let n of e)r.set(n.path,n.content);return[...r].map(([n,s])=>({path:n,content:s}))}A_();$o();import{promises as E_}from"node:fs";import*as uk from"node:path";import*as h$ from"node:os";var p$=process.env.OIOXO_HOME||uk.join(h$.homedir(),".oioxo"),ck=uk.join(p$,"config.json"),_l=["provider","model","baseUrl","apiKey"],Tne=new Set(["apiKey"]);async function vl(){try{let t=JSON.parse(await E_.readFile(ck,"utf8"));return t&&typeof t=="object"?t:{}}catch{return{}}}async function C_(t){await E_.mkdir(p$,{recursive:!0}),await E_.writeFile(ck,JSON.stringify(t,null,2),{mode:384});try{await E_.chmod(ck,384)}catch{}}function Om(t,e){return Tne.has(t)?e.length<=8?"\u2022\u2022\u2022\u2022":e.slice(0,4)+"\u2026"+e.slice(-2):e}async function m$(t){let[e,r,...n]=t,s=await vl();if(!e||e==="list"){let i=_l.filter(o=>s[o]!=null);if(i.length===0){console.log("No OIOXO config set. Try: oioxo config set provider anthropic");return}console.log(`
|
|
246
|
+
OIOXO config (~/.oioxo/config.json):`);for(let o of i)console.log(` ${o.padEnd(10)} ${Om(o,String(s[o]))}`);return}if(e==="get"){if(!ak(r))return Rm(`Unknown key "${r}". Known: ${_l.join(", ")}`);let i=s[r];console.log(i==null?"":Om(r,String(i)));return}if(e==="set"){if(!ak(r))return Rm(`Unknown key "${r}". Known: ${_l.join(", ")}`);let i=n.join(" ");if(!i)return Rm(`Usage: oioxo config set ${r} <value>`);s[r]=i,await C_(s),console.log(`Set ${r} = ${Om(r,i)}`);return}if(e==="unset"){if(!ak(r))return Rm(`Unknown key "${r}". Known: ${_l.join(", ")}`);delete s[r],await C_(s),console.log(`Unset ${r}`);return}Rm(`Unknown config command "${e}". Use: set | get | list | unset`)}function ak(t){return!!t&&_l.includes(t)}function Rm(t){console.error(`oioxo config: ${t}`),process.exitCode=1}function One(t){let e={task:"",yes:!1,local:!1},r=[];for(let n=0;n<t.length;n++){let s=t[n];s==="--yes"||s==="-y"?e.yes=!0:s==="--local"?e.local=!0:s==="--verify"?e.verify=t[++n]:s==="--max-iters"?e.maxIters=Number(t[++n])||void 0:r.push(s)}return e.task=r.join(" ").trim(),e}function Nne(t,e){if(!t)return{add:e.split(`
|
|
99
247
|
`).length,del:0,isNew:!0};let r=new Set(t.split(`
|
|
100
248
|
`)),n=new Set(e.split(`
|
|
101
|
-
`)),
|
|
102
|
-
`+n.message),process.exitCode=1;return}let
|
|
103
|
-
`+
|
|
104
|
-
OIOXO coding agent \xB7 writer: ${
|
|
249
|
+
`)),s=0,i=0;for(let o of n)r.has(o)||s++;for(let o of r)n.has(o)||i++;return{add:s,del:i,isNew:!1}}async function Bne(t,e){try{return await Rne(Nm.join(t,e),"utf8")}catch{return""}}async function x$(t,e){let r=One(e);if(!r.task){console.log('Usage: oioxo code "<what you want done>" [--verify "<cmd>"] [--yes] [--max-iters N]');return}if(!await Uc()&&process.stdin.isTTY&&process.stdout.isTTY){let u=y$({input:process.stdin,output:process.stdout}),l=(await u.question("OIOXO: sign in to run the coding agent? Opens your browser. [Y/n] ")).trim().toLowerCase();if(u.close(),l===""||l==="y"||l==="yes")try{await b_()}catch{}}let n=await PB();if(!n.ok){console.error(`
|
|
250
|
+
`+n.message),process.exitCode=1;return}let s=await vl(),i=Pm({local:r.local,config:s,onNote:u=>console.log(u)});if("error"in i){console.error(`
|
|
251
|
+
`+i.error),process.exitCode=1;return}let o=i.coder;console.log(`
|
|
252
|
+
OIOXO coding agent \xB7 writer: ${o.label}`);let a=await FB({root:t,task:r.task,coder:o,verifyCmd:r.verify,maxIters:r.maxIters,onNote:u=>console.log(u),onConfirmRun:async u=>r.yes?!0:g$(`
|
|
105
253
|
Run the verify command on your machine? ${u}`)});if(a.coderError){console.error(`
|
|
106
254
|
`+a.coderError),process.exitCode=1;return}if(!a.edits.length){console.log(`
|
|
107
255
|
No changes were produced. Try rephrasing the task or pointing it at a specific file.`);return}console.log(`
|
|
108
|
-
${a.ok?"\u2713 verified green":"\u26A0 best attempt (did not fully verify)"} \u2014 ${a.edits.length} file(s):`);let c=new Map;for(let u of a.edits){let l=await
|
|
256
|
+
${a.ok?"\u2713 verified green":"\u26A0 best attempt (did not fully verify)"} \u2014 ${a.edits.length} file(s):`);let c=new Map;for(let u of a.edits){let l=await Bne(t,u.path);c.set(u.path,l);let d=Nne(l,u.content);console.log(` ${d.isNew?"new ":" "}${u.path} ${d.isNew?`(+${d.add})`:`+${d.add} -${d.del}`}`)}if(a.ok||console.log(`
|
|
109
257
|
(verify did not pass \u2014 review carefully before applying)`),console.log(`
|
|
110
|
-
OIOXO saved ~${a.savedTokens.toLocaleString()} tokens of context on this task.`),!r.yes&&!await
|
|
111
|
-
Apply these changes to your files?`)){console.log("Discarded. Nothing was written.");return}await
|
|
112
|
-
\u2713 applied ${a.edits.length} file(s).${a.ok?"":" (unverified \u2014 run your tests)"}`),await Ie("report",a.savedTokens).catch(()=>{})}async function Vv(t,e){let r=Cn.resolve(t);for(let n of e){if(!Yi(n.path)){console.error(` \u26A0 skipped unsafe path: ${n.path}`);continue}let o=Cn.resolve(r,n.path);if(o!==r&&!o.startsWith(r+Cn.sep)){console.error(` \u26A0 skipped path escaping repo: ${n.path}`);continue}await Dv(Cn.dirname(o),{recursive:!0}),await Mv(o,n.content,"utf8")}}async function pp(t){if(!process.stdin.isTTY)return console.log(`${t} (no TTY \u2014 pass --yes to apply non-interactively)`),!1;let e=fp({input:process.stdin,output:process.stdout});try{let r=(await e.question(`${t} [y/N] `)).trim().toLowerCase();return r==="y"||r==="yes"}finally{e.close()}}import*as na from"node:os";var ra=[{id:"openai",note:"set OPENAI_API_KEY or config apiKey"},{id:"anthropic",note:"set ANTHROPIC_API_KEY or config apiKey"},{id:"groq",note:"set GROQ_API_KEY or config apiKey"},{id:"mistral",note:"config apiKey"},{id:"together",note:"config apiKey"},{id:"ollama",note:"local, no key \u2014 config model qwen2.5-coder"},{id:"custom",note:"any OpenAI-compatible base \u2014 config baseUrl + apiKey"}];async function hp(t){let[e,...r]=t;if(!e||e==="list"){console.log(`
|
|
258
|
+
OIOXO saved ~${a.savedTokens.toLocaleString()} tokens of context on this task.`),!r.yes&&!await g$(`
|
|
259
|
+
Apply these changes to your files?`)){console.log("Discarded. Nothing was written.");return}await $ne(t,a.edits),console.log(`
|
|
260
|
+
\u2713 applied ${a.edits.length} file(s).${a.ok?"":" (unverified \u2014 run your tests)"}`),await ms("report",a.savedTokens).catch(()=>{})}async function $ne(t,e){let r=Nm.resolve(t);for(let n of e){if(!Fc(n.path)){console.error(` \u26A0 skipped unsafe path: ${n.path}`);continue}let s=Nm.resolve(r,n.path);if(s!==r&&!s.startsWith(r+Nm.sep)){console.error(` \u26A0 skipped path escaping repo: ${n.path}`);continue}await Pne(Nm.dirname(s),{recursive:!0}),await Ine(s,n.content,"utf8")}}async function g$(t){if(!process.stdin.isTTY)return console.log(`${t} (no TTY \u2014 pass --yes to apply non-interactively)`),!1;let e=y$({input:process.stdin,output:process.stdout});try{let r=(await e.question(`${t} [y/N] `)).trim().toLowerCase();return r==="y"||r==="yes"}finally{e.close()}}import{createInterface as xge}from"node:readline";I_();function w$(t,e,r){return JSON.stringify(["hello",t,e,r])}var P_=16*1024,zne=3e4,S$=1500,Lne=4e3;async function dk(t,e){let r=e.now??(()=>Date.now()),n=e.setTimer??((S,C)=>setTimeout(S,C)),s=e.clearTimer??(S=>clearTimeout(S)),i=e.rand??(()=>Math.random().toString(36).slice(2)+r().toString(36)),o=lk(e.keyLookup),a=r(),c=!1,u=new Map,l=new Map,d={},f=null;function p(S){if(c)return;let C=JSON.stringify(S);if(C.length<=P_){t.send(C);return}let E=i(),B=Math.ceil(C.length/P_);for(let G=0;G<B;G++)t.send(JSON.stringify({t:"chunk",id:E,i:G,total:B,part:C.slice(G*P_,(G+1)*P_)}))}let m=i(),y=await e.identity.sign(w$(e.identity.deviceId,t.channelId,m)),_={t:"hello",v:1,profile:e.profile,publicKeyJwk:e.identity.publicKeyJwk,nonce:m,sig:y};return await new Promise((S,C)=>{let E=null,B=null,G=new Set,se=!1;function _e(){if(!se){se=!0,c=!0,B&&s(B);for(let ut of u.values())ut.reject(new Error("link lost"));u.clear();try{t.close()}catch{}for(let ut of G)try{ut()}catch{}}}function he(ut){if(!c){c=!0,B&&s(B);for(let ze of u.values())ze.reject(new Error("link closed"));u.clear(),t.close(),C(new Error(ut))}}function J(ut,ze){return{peerId:ut,profile:ze,idleMs:()=>r()-a,sendProject:$=>p({t:"project",v:1,code:$}),onProject:$=>{f=$},serve:$=>{d=$},onLost:$=>{se?$():G.add($)},call:(($,U)=>new Promise((be,ke)=>{let Le=i(),k=n(()=>{u.delete(Le),ke(new Error(`rpc ${$} timed out`))},zne);u.set(Le,{resolve:P=>{s(k),be(P)},reject:P=>{s(k),ke(P)}}),p({t:"rpc",v:1,id:Le,method:$,arg:U})})),close:()=>{_e()}}}async function ct(ut){a=r();let ze;try{ze=JSON.parse(ut)}catch{return}if(ze.t==="chunk"){let $=ze,U=l.get($.id)??{total:$.total,parts:new Array($.total).fill("")};U.parts[$.i]=$.part,l.set($.id,U),U.parts.every(be=>be!=="")&&(l.delete($.id),await ct(U.parts.join("")));return}let z=ze;switch(z.t){case"hello":{if(E)return;let $=await rh(z.publicKeyJwk).catch(()=>null);if(!$)return he("hello: bad key");if(!await o(w$($,t.channelId,z.nonce),z.sig,$))return he("hello: signature/identity rejected");E={peerId:$,profile:z.profile};let be=J($,z.profile);B=n(function ke(){if(!c){if(r()-a>Lne){_e();return}p({t:"ping",v:1,ts:r()}),B=n(ke,S$)}},S$),S(be);return}case"ping":return p({t:"pong",v:1,ts:z.ts});case"pong":return;case"project":{f?.(z.code);return}case"rpc":{try{if(z.method==="generate"){if(!d.generate)throw new Error("generate not served here");let $=await d.generate(z.arg);p({t:"rpc-result",v:1,id:z.id,result:$.result,receipt:$.receipt})}else{if(!d.verify)throw new Error("verify not served here");let $=await d.verify(z.arg);p({t:"rpc-result",v:1,id:z.id,result:$.result})}}catch($){p({t:"rpc-error",v:1,id:z.id,error:String($?.message??$)})}return}case"rpc-result":{let $=u.get(z.id);if(!$)return;u.delete(z.id),$.resolve({result:z.result,receipt:z.receipt});return}case"rpc-error":{let $=u.get(z.id);if(!$)return;u.delete(z.id),$.reject(new Error(z.error));return}}}t.onClose(()=>{E?_e():he("channel closed before handshake")}),t.onMessage(ut=>{ct(ut)}),p(_)})}T_();T_();import{gzipSync as qne,gunzipSync as Hne}from"zlib";var Dne=1;function Une(t){try{let e=JSON.parse(b$(t.trim()));if(!Array.isArray(e)||e[0]!==Dne)return null;let[r,n,s,i,o,a]=e;return n!=="offer"&&n!=="answer"||typeof s!="string"||!s||typeof i!="string"||typeof o!="string"||!o?null:{v:r,role:n,sdp:s,token:i,deviceId:o,label:a||void 0}}catch{return null}}function A$(t,e){let r=t.token,n=e;if(r.length!==n.length)return!1;let s=0;for(let i=0;i<r.length;i++)s|=r.charCodeAt(i)^n.charCodeAt(i);return s===0}var fk="oiop1";function hk(t){let e=new TextEncoder().encode(JSON.stringify([t.v,t.role,t.sdp,t.token,t.deviceId,t.label??""]));return fk+k_(qne(Buffer.from(e)))}function E$(t){let e=t.trim();if(!e.startsWith(fk))return Une(e);try{let r=Hne(Buffer.from(Bm(e.slice(fk.length)))).toString("utf8"),n=JSON.parse(r);if(!Array.isArray(n)||n[0]!==1)return null;let[s,i,o,a,c,u]=n;return i!=="offer"&&i!=="answer"||typeof o!="string"||!o||typeof a!="string"||typeof c!="string"||!c?null:{v:s,role:i,sdp:o,token:a,deviceId:c,label:u||void 0}}catch{return null}}var l1;async function age(){if(l1!==void 0)return l1;try{l1=await Promise.resolve().then(()=>(TW(),kW))}catch{l1=null}return l1}function IW(t,e=3e3){return t.iceGatheringState==="complete"?Promise.resolve():new Promise(r=>{let n=setTimeout(r,e);t.iceGatheringStateChange.subscribe(()=>{t.iceGatheringState==="complete"&&(clearTimeout(n),r())})})}function PW(t){let e=null,r=[];return t.onMessage.subscribe(n=>{let s=typeof n=="string"?n:n.toString();e?e(s):r.push(s)}),{channelId:t.label||"oioxo-mesh",send:n=>t.send(n),onMessage:n=>{e=n;let s=r.splice(0);for(let i of s)n(i)},onClose:n=>t.stateChanged.subscribe(s=>{s==="closed"&&n()}),close:()=>{try{t.close()}catch{}}}}var XA=class{deps;constructor(e){this.deps=e}async newPc(){let e=await age();if(!e)throw new Error("mesh transport unavailable (werift not installed)");return new e.RTCPeerConnection({iceServers:[]})}async hostOffer(){let e=await this.newPc(),r=e.createDataChannel("oioxo-mesh"),n=this.linkWhenOpen(r);return await e.setLocalDescription(await e.createOffer()),await IW(e),{offerCode:hk({v:1,role:"offer",sdp:e.localDescription.sdp,token:this.deps.token,deviceId:this.deps.identity.deviceId}),pending:{pc:e,link:n}}}async joinFromOffer(e){let r=this.accept(e,"offer"),n=await this.newPc(),s=new Promise((o,a)=>{n.onDataChannel.subscribe(c=>{dk(PW(c),this.linkDeps()).then(o,a)})});return await n.setRemoteDescription({sdp:r.sdp,type:"offer"}),await n.setLocalDescription(await n.createAnswer()),await IW(n),{answerCode:hk({v:1,role:"answer",sdp:n.localDescription.sdp,token:this.deps.token,deviceId:this.deps.identity.deviceId}),link:s}}async completeWithAnswer(e,r){let n=this.accept(r,"answer");return await e.pc.setRemoteDescription({sdp:n.sdp,type:"answer"}),e.link}accept(e,r){let n=E$(e);if(!n||n.role!==r)throw new Error("invalid pairing code");if(!A$(n,this.deps.token))throw new Error("this code is for a different account");return n}linkWhenOpen(e){return new Promise((r,n)=>{let s=()=>dk(PW(e),this.linkDeps()).then(r,n);e.readyState==="open"?s():e.stateChanged.subscribe(i=>{i==="open"&&s()})})}linkDeps(){return{identity:this.deps.identity,profile:this.deps.profile,keyLookup:this.deps.keyLookup}}};import cge from"node:os";import BW from"node:path";import{readFile as uge,writeFile as lge,mkdir as dge}from"node:fs/promises";var $W=process.env.OIOXO_HOME||BW.join(cge.homedir(),".oioxo"),RW=BW.join($W,"mesh-identity.json"),j5={name:"ECDSA",namedCurve:"P-256"},fge={name:"ECDSA",hash:"SHA-256"},hge=new TextEncoder;function OW(t){return Buffer.from(new Uint8Array(t)).toString("base64url")}async function NW(t,e){let r=await crypto.subtle.importKey("jwk",t,j5,!0,["verify"]),n=await crypto.subtle.importKey("jwk",e,j5,!1,["sign"]);return{deviceId:OW(await crypto.subtle.digest("SHA-256",await crypto.subtle.exportKey("raw",r))),publicKeyJwk:t,sign:async i=>OW(await crypto.subtle.sign(fge,n,hge.encode(i)))}}async function z5(){try{let n=JSON.parse(await uge(RW,"utf8"));if(n.pub&&n.priv)return NW(n.pub,n.priv)}catch{}let t=await crypto.subtle.generateKey(j5,!0,["sign","verify"]),e=await crypto.subtle.exportKey("jwk",t.publicKey),r=await crypto.subtle.exportKey("jwk",t.privateKey);try{await dge($W,{recursive:!0}),await lge(RW,JSON.stringify({pub:e,priv:r}),{mode:384})}catch{}return NW(e,r)}I_();function pge(t){return JSON.stringify([t.v,t.deviceId,t.seq,t.nonce,t.jobHash,t.servedSec,t.tokensOut,t.issuedAt])}async function MW(t,e){let r={v:1,deviceId:t.deviceId,seq:t.seq,nonce:(t.nonce??mge)(),jobHash:t.jobHash,servedSec:Math.max(0,Math.round(t.servedSec)),tokensOut:Math.max(0,Math.round(t.tokensOut)),issuedAt:(t.now??Date.now)()},n=await e(pge(r));return{...r,sig:n}}var tOe={secPerServedSec:1,secPerToken:.02,maxPerReceiptSec:300,dailyCapSec:3600,maxAgeMs:168*3600*1e3};function mge(){let t=new Uint8Array(8);(globalThis.crypto??globalThis.crypto)?.getRandomValues(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}A_();$o();function JA(t){let e=xge({input:process.stdin,output:process.stdout});return new Promise(r=>e.question(t,n=>{e.close(),r(n.trim())}))}async function VW(t){return Buffer.from(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))).toString("base64url")}async function YA(){return(await Ma())?.token??null}async function KW(t){let e={},r=await YA(),n={"content-type":"application/json",...r?{authorization:`Bearer ${r}`}:{}};try{await fetch(`${gn}/api/devices/register`,{method:"POST",headers:n,body:JSON.stringify({publicKeyJwk:t,label:"CLI peer"})});let s=await fetch(`${gn}/api/devices/register`,{headers:n});if(s.ok){let i=await s.json();for(let o of i.devices??[])e[o.deviceId]=o.publicKeyJwk}}catch{}return e}var bge=0,QA=new Set;function HW(t,e,r,n){let s=Pm();QA.add(t),t.onLost(()=>{QA.delete(t)}),t.serve({generate:async({ctx:i})=>{if("error"in s)return{result:[]};let o=Date.now(),a=await s.coder.generate({task:i.task,grounding:_ge(i),error:i.error,attempt:i.attempt}).catch(()=>[]),c;try{if(a.length){let u=await VW(JSON.stringify([i.task,a.map(l=>[l.path,l.content]).sort()]));c=await MW({deviceId:n,seq:++bge,jobHash:u,servedSec:(Date.now()-o)/1e3,tokensOut:Math.ceil(a.reduce((l,d)=>l+d.content.length,0)/4)},r)}}catch{}return{result:a,receipt:c}}}),console.log(` \u2713 connected \u2014 lending "${e}" to ${t.profile.label??t.peerId.slice(0,8)}.`)}function _ge(t){return(t.files??[]).map(e=>`--- ${e.path} ---
|
|
261
|
+
${e.content}`).join(`
|
|
262
|
+
|
|
263
|
+
`)}async function eE(t){let e=t[0];if(e==="host"&&(e="invite"),e==="help"&&(e="join"),e==="devices"||e==="scan"){await vge();return}if(e!=="invite"&&e!=="join"){console.log(`Compute Mesh \u2014 lend this machine's compute to a device that has a project (same
|
|
264
|
+
account + same Wi-Fi). This machine is the HELPER; its OIOXO coder serves the build.
|
|
265
|
+
|
|
266
|
+
Usage:
|
|
267
|
+
oioxo devices scan the Wi-Fi for your other OIOXO devices (no code typing)
|
|
268
|
+
oioxo invite show a code; the device with the project scans it
|
|
269
|
+
oioxo join scan/paste the code from the device with the project
|
|
270
|
+
oioxo stop-helping stop lending and exit
|
|
271
|
+
`);return}let r=await z5(),n=Pm(),s="error"in n?"OIOXO coder":n.coder.label,i=await YA()?await VW("oioxo-mesh:"+await YA()):"oioxo-mesh",o=await KW(r.publicKeyJwk),a=l=>o[l]??null,c=new XA({identity:r,profile:{id:r.deviceId,caps:["generate"],tier:"high",label:"CLI ("+s+")"},token:i.slice(0,22),keyLookup:a}),u=async l=>{let d=JSON.parse(l);o[await rh(d)]=d};if(console.log(`Compute Mesh \u2014 this machine will help by lending "${s}". Same account + same Wi-Fi only.
|
|
272
|
+
`),e==="invite"){let{offerCode:l,pending:d}=await c.hostOffer();console.log(`1) On the device that has the project, open Add a device \u2192 "Join a device", then paste THIS:
|
|
273
|
+
`),console.log(" "+l+`
|
|
274
|
+
`),console.log(` (it also needs this device-key line:)
|
|
275
|
+
`+JSON.stringify(r.publicKeyJwk)+`
|
|
276
|
+
`);let f=await JA("2) Paste the device-key line it shows back: ");await u(f).catch(()=>{});let p=await JA("3) Paste its reply code: "),m=await c.completeWithAnswer(d,p);HW(m,s,r.sign,r.deviceId),await FW()}else{let l=await JA('1) On the device with the project, choose "Invite a device". Paste its code here: '),d=await JA("2) Paste its device-key line: ");await u(d).catch(()=>{});let{answerCode:f,link:p}=await c.joinFromOffer(l);console.log(`
|
|
277
|
+
3) Back on that device, paste THIS device-key line, then the reply code:
|
|
278
|
+
`),console.log(" "+JSON.stringify(r.publicKeyJwk)+`
|
|
279
|
+
`),console.log(" "+f+`
|
|
280
|
+
`);let m=await p;HW(m,s,r.sign,r.deviceId),await FW()}}async function vge(){let{scan:t}=await Promise.resolve().then(()=>(qW(),UW)),{makeVerifier:e}=await Promise.resolve().then(()=>(I_(),v$)),r=await z5(),s=await YA()??"oioxo-mesh",i=await KW(r.publicKeyJwk),o=e(l=>i[l]??null),a=async(l,d,f)=>{try{return await o(f,d,l)}catch{return!1}};console.log(`Scanning the Wi-Fi for your OIOXO devices\u2026 (same account, same network)
|
|
281
|
+
`);let u=(await t({accountKey:s,verify:a,ms:3e3})).filter(l=>l.deviceId!==r.deviceId);if(!u.length){console.log("No other OIOXO devices found on this network yet."),console.log("Make sure the other device is on the same Wi-Fi with OIOXO open, then try again,"),console.log("or pair manually with `oioxo invite` / `oioxo join`.");return}console.log(`Found ${u.length} device${u.length===1?"":"s"}:
|
|
282
|
+
`);for(let l of u){let d=l.trusted?"\u2713":"\u2022",f=l.host?` ${l.host}:${l.port}`:"";console.log(` ${d} ${l.label} (${l.os})${f}${l.trusted?"":" \u2014 confirm at pair time"}`)}console.log("\nTo lend your compute to one of them, run `oioxo join` and pair with its code.")}function FW(){let t=QA.size;return console.log(`
|
|
283
|
+
Helping ${t} device${t===1?"":"s"} \u2014 your OIOXO coder is lending power. Ctrl+C to stop helping.`),process.on("SIGINT",()=>{for(let e of QA)try{e.close()}catch{}console.log(`
|
|
284
|
+
Stopped helping. Goodbye.`),process.exit(0)}),new Promise(()=>{})}$o();import*as q5 from"node:os";var U5=[{id:"openai",note:"set OPENAI_API_KEY or config apiKey"},{id:"anthropic",note:"set ANTHROPIC_API_KEY or config apiKey"},{id:"groq",note:"set GROQ_API_KEY or config apiKey"},{id:"mistral",note:"config apiKey"},{id:"together",note:"config apiKey"},{id:"ollama",note:"local, no key \u2014 config model qwen2.5-coder"},{id:"custom",note:"any OpenAI-compatible base \u2014 config baseUrl + apiKey"}];async function ZW(t){let[e,...r]=t;if(!e||e==="list"){console.log(`
|
|
113
285
|
OIOXO coding agent \u2014 how to run it:
|
|
114
|
-
`),console.log(" Providers (bring your own key):");for(let
|
|
115
|
-
Local & private:`),console.log(" ollama keyless, on your machine"),console.log(" --local built-in on-device coder (coming next)");let n=await
|
|
286
|
+
`),console.log(" Providers (bring your own key):");for(let s of U5)console.log(` ${s.id.padEnd(10)} ${s.note}`);console.log(`
|
|
287
|
+
Local & private:`),console.log(" ollama keyless, on your machine"),console.log(" --local built-in on-device coder (coming next)");let n=await vl();n.provider&&console.log(`
|
|
116
288
|
Current pin: ${n.provider}${n.model?" / "+n.model:""}`),console.log(`
|
|
117
|
-
Pin one with: oioxo model use <provider> [model]`);return}if(e==="use"){let[n,
|
|
289
|
+
Pin one with: oioxo model use <provider> [model]`);return}if(e==="use"){let[n,s]=r;if(!n){console.error("Usage: oioxo model use <provider> [model]"),process.exitCode=1;return}if(!U5.some(o=>o.id===n)){console.error(`Unknown provider "${n}". Known: ${U5.map(o=>o.id).join(", ")}`),process.exitCode=1;return}let i=await vl();i.provider=n,s&&(i.model=s),await C_(i),console.log(`Pinned ${n}${s?" / "+s:""}. ${n!=="ollama"&&n!=="custom"?"Set your key with `oioxo config set apiKey <key>` or the provider env var.":""}`);return}console.error(`Unknown model command "${e}". Use: list | use`),process.exitCode=1}async function GW(t){let[e]=t;if(e&&e!=="list"&&e!=="status"){console.error(`Unknown mcp command "${e}". Use: list`),process.exitCode=1;return}let r=process.cwd(),n=await YC(r,q5.homedir());console.log(`
|
|
118
290
|
OIOXO context engine \u2014 agent wiring (this project + machine):
|
|
119
|
-
`);for(let
|
|
120
|
-
Wire one (or all): oioxo init [--all]`)}async function
|
|
121
|
-
Signed in${t.email?` as ${t.email}`:""} (credential valid ~${e}d).`);let r=await
|
|
122
|
-
OIOXO usage`),console.log(` Plan : ${
|
|
291
|
+
`);for(let s of n){let i=s.configured?"\u2713 wired":s.detected?"\xB7 detected, not wired":"\xB7 not detected";console.log(` ${s.display.padEnd(26)} ${i}`)}console.log(`
|
|
292
|
+
Wire one (or all): oioxo init [--all]`)}async function WW(){let t=await Ma();if(!t||t.expiresAt<=Date.now()){console.log("Not signed in. Run `oioxo login` to connect your OIOXO account.");return}let e=Math.max(0,Math.round((t.expiresAt-Date.now())/864e5));console.log(`
|
|
293
|
+
Signed in${t.email?` as ${t.email}`:""} (credential valid ~${e}d).`);let r=await ms("check");r&&console.log(`Plan: ${H5(r)}`)}async function XW(t){if(!await Uc()){console.log("Not signed in. Run `oioxo login`.");return}let e=await ms("check");if(!e){console.error("Could not reach oioxo.com to read your usage."),process.exitCode=1;return}if(t.includes("--json")){console.log(JSON.stringify(e));return}console.log(`
|
|
294
|
+
OIOXO usage`),console.log(` Plan : ${H5(e)}`),e.tier==="free"&&(console.log(` Saved : ${(e.savedThisMonth??0).toLocaleString()} tokens this month`),console.log(` Remaining : ${(e.remainingTokens??0).toLocaleString()} of ${(e.capTokens??0).toLocaleString()}`),e.resetsAt&&console.log(` Resets : ${new Date(e.resetsAt).toUTCString()}`),console.log(` Upgrade : ${xl}`))}async function JW(){console.log(`
|
|
123
295
|
OIOXO doctor
|
|
124
|
-
`);let t=process.versions.node,e=Number(t.split(".")[0])>=18;
|
|
125
|
-
OIOXO CLI ${t}`),console.log("Update to the latest with:"),console.log(" npm : npm i -g oioxo-mcp@latest"),console.log(" npx : npx oioxo-mcp@latest <command> (always runs the newest)")}function oa(t){return t.tier==="pro"?"OIOXO Pro \u2014 unlimited":t.tier==="free"?"OIOXO Free \u2014 monthly allowance":t.tier}function Jo(t,e,r){console.log(` ${t?"\u2713":"\u2717"} ${e}${r?` \u2014 ${r}`:""}`)}var $r={};qo($r,{BRAND:()=>gx,DIRTY:()=>ar,EMPTY_PATH:()=>Xv,INVALID:()=>C,NEVER:()=>Qx,OK:()=>Te,ParseStatus:()=>we,Schema:()=>q,ZodAny:()=>Dt,ZodArray:()=>Pt,ZodBigInt:()=>ur,ZodBoolean:()=>lr,ZodBranded:()=>An,ZodCatch:()=>wr,ZodDate:()=>dr,ZodDefault:()=>xr,ZodDiscriminatedUnion:()=>Yo,ZodEffects:()=>We,ZodEnum:()=>_r,ZodError:()=>Ae,ZodFirstPartyTypeKind:()=>$,ZodFunction:()=>es,ZodIntersection:()=>hr,ZodIssueCode:()=>b,ZodLazy:()=>gr,ZodLiteral:()=>yr,ZodMap:()=>Jr,ZodNaN:()=>Wr,ZodNativeEnum:()=>vr,ZodNever:()=>st,ZodNull:()=>fr,ZodNullable:()=>gt,ZodNumber:()=>cr,ZodObject:()=>De,ZodOptional:()=>Me,ZodParsedType:()=>z,ZodPipeline:()=>Mn,ZodPromise:()=>Lt,ZodReadonly:()=>br,ZodRecord:()=>Qo,ZodSchema:()=>q,ZodSet:()=>Gr,ZodString:()=>Mt,ZodSymbol:()=>Br,ZodTransformer:()=>We,ZodTuple:()=>ht,ZodType:()=>q,ZodUndefined:()=>pr,ZodUnion:()=>mr,ZodUnknown:()=>Tt,ZodVoid:()=>Xr,addIssueToContext:()=>k,any:()=>Sx,array:()=>Ox,bigint:()=>xx,boolean:()=>Ip,coerce:()=>Yx,custom:()=>Pp,date:()=>wx,datetimeRegex:()=>zp,defaultErrorMap:()=>St,discriminatedUnion:()=>Rx,effect:()=>Vx,enum:()=>qx,function:()=>Mx,getErrorMap:()=>Vr,getParsedType:()=>mt,instanceof:()=>_x,intersection:()=>jx,isAborted:()=>Go,isAsync:()=>Hr,isDirty:()=>Wo,isValid:()=>At,late:()=>yx,lazy:()=>Dx,literal:()=>Lx,makeIssue:()=>Zn,map:()=>Zx,nan:()=>vx,nativeEnum:()=>Ux,never:()=>Tx,null:()=>kx,nullable:()=>Kx,number:()=>Ep,object:()=>ca,objectUtil:()=>sa,oboolean:()=>Wx,onumber:()=>Gx,optional:()=>Hx,ostring:()=>Jx,pipeline:()=>Xx,preprocess:()=>Bx,promise:()=>Fx,quotelessJson:()=>Hv,record:()=>Cx,set:()=>Ax,setErrorMap:()=>Bv,strictObject:()=>Ex,string:()=>Op,symbol:()=>bx,transformer:()=>Vx,tuple:()=>Nx,undefined:()=>$x,union:()=>Ix,unknown:()=>zx,util:()=>H,void:()=>Px});var H;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(H||(H={}));var sa;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(sa||(sa={}));var z=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mt=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var b=H.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Hv=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ae=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ae.create=t=>new Ae(t);var Kv=(t,e)=>{let r;switch(t.code){case b.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case b.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,H.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:r=`Unrecognized key(s) in object: ${H.joinValues(t.keys,", ")}`;break;case b.invalid_union:r="Invalid input";break;case b.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${H.joinValues(t.options)}`;break;case b.invalid_enum_value:r=`Invalid enum value. Expected ${H.joinValues(t.options)}, received '${t.received}'`;break;case b.invalid_arguments:r="Invalid function arguments";break;case b.invalid_return_type:r="Invalid function return type";break;case b.invalid_date:r="Invalid date";break;case b.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:H.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case b.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case b.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case b.custom:r="Invalid input";break;case b.invalid_intersection_types:r="Intersection results could not be merged";break;case b.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case b.not_finite:r="Number must be finite";break;default:r=e.defaultError,H.assertNever(t)}return{message:r}},St=Kv;var wp=St;function Bv(t){wp=t}function Vr(){return wp}var Zn=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},Xv=[];function k(t,e){let r=Vr(),n=Zn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===St?void 0:St].filter(o=>!!o)});t.common.issues.push(n)}var we=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return C;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return C;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},C=Object.freeze({status:"aborted"}),ar=t=>({status:"dirty",value:t}),Te=t=>({status:"valid",value:t}),Go=t=>t.status==="aborted",Wo=t=>t.status==="dirty",At=t=>t.status==="valid",Hr=t=>typeof Promise<"u"&&t instanceof Promise;var O;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(O||(O={}));var Ge=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},bp=(t,e)=>{if(At(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ae(t.common.issues);return this._error=r,this._error}}};function D(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var q=class{get description(){return this._def.description}_getType(e){return mt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:mt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new we,ctx:{common:e.parent.common,data:e.data,parsedType:mt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Hr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return bp(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return At(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>At(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Hr(o)?o:Promise.resolve(o));return bp(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:b.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new We({schema:this,typeName:$.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Me.create(this,this._def)}nullable(){return gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Pt.create(this)}promise(){return Lt.create(this,this._def)}or(e){return mr.create([this,e],this._def)}and(e){return hr.create(this,e,this._def)}transform(e){return new We({...D(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new xr({...D(this._def),innerType:this,defaultValue:r,typeName:$.ZodDefault})}brand(){return new An({typeName:$.ZodBranded,type:this,...D(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new wr({...D(this._def),innerType:this,catchValue:r,typeName:$.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Mn.create(this,e)}readonly(){return br.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Jv=/^c[^\s-]{8,}$/i,Gv=/^[0-9a-z]+$/,Wv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yv=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Qv=/^[a-z0-9_-]{21}$/i,ex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tx=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rx=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nx="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ia,ox=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ix=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ax=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cx=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ux=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,kp="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",lx=new RegExp(`^${kp}$`);function Sp(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function dx(t){return new RegExp(`^${Sp(t)}$`)}function zp(t){let e=`${kp}T${Sp(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function px(t,e){return!!((e==="v4"||!e)&&ox.test(t)||(e==="v6"||!e)&&ix.test(t))}function fx(t,e){if(!ex.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function mx(t,e){return!!((e==="v4"||!e)&&sx.test(t)||(e==="v6"||!e)&&ax.test(t))}var Mt=class t extends q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return k(s,{code:b.invalid_type,expected:z.string,received:s.parsedType}),C}let n=new we,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?k(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&k(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")rx.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"email",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ia||(ia=new RegExp(nx,"u")),ia.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"emoji",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Yv.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"uuid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Qv.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"nanoid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Jv.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Gv.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid2",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Wv.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ulid",code:b.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),k(o,{validation:"url",code:b.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"regex",code:b.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),k(o,{code:b.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:b.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:b.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?zp(s).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:b.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?lx.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:b.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?dx(s).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:b.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?tx.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"duration",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?px(e.data,s.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ip",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?fx(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"jwt",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?mx(e.data,s.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cidr",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?cx.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64",code:b.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ux.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64url",code:b.invalid_string,message:s.message}),n.dirty()):H.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:b.invalid_string,...O.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...O.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...O.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...O.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...O.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...O.errToObj(r)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Mt.create=t=>new Mt({checks:[],typeName:$.ZodString,coerce:t?.coerce??!1,...D(t)});function hx(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var cr=class t extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return k(s,{code:b.invalid_type,expected:z.number,received:s.parsedType}),C}let n,o=new we;for(let s of this._def.checks)s.kind==="int"?H.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),k(n,{code:b.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),k(n,{code:b.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),k(n,{code:b.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?hx(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),k(n,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),k(n,{code:b.not_finite,message:s.message}),o.dirty()):H.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,O.toString(r))}gt(e,r){return this.setLimit("min",e,!1,O.toString(r))}lte(e,r){return this.setLimit("max",e,!0,O.toString(r))}lt(e,r){return this.setLimit("max",e,!1,O.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:O.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&H.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};cr.create=t=>new cr({checks:[],typeName:$.ZodNumber,coerce:t?.coerce||!1,...D(t)});var ur=class t extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new we;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),k(n,{code:b.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),k(n,{code:b.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),k(n,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):H.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return k(r,{code:b.invalid_type,expected:z.bigint,received:r.parsedType}),C}gte(e,r){return this.setLimit("min",e,!0,O.toString(r))}gt(e,r){return this.setLimit("min",e,!1,O.toString(r))}lte(e,r){return this.setLimit("max",e,!0,O.toString(r))}lt(e,r){return this.setLimit("max",e,!1,O.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:O.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ur.create=t=>new ur({checks:[],typeName:$.ZodBigInt,coerce:t?.coerce??!1,...D(t)});var lr=class extends q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return k(n,{code:b.invalid_type,expected:z.boolean,received:n.parsedType}),C}return Te(e.data)}};lr.create=t=>new lr({typeName:$.ZodBoolean,coerce:t?.coerce||!1,...D(t)});var dr=class t extends q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return k(s,{code:b.invalid_type,expected:z.date,received:s.parsedType}),C}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return k(s,{code:b.invalid_date}),C}let n=new we,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:b.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:b.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):H.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};dr.create=t=>new dr({checks:[],coerce:t?.coerce||!1,typeName:$.ZodDate,...D(t)});var Br=class extends q{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return k(n,{code:b.invalid_type,expected:z.symbol,received:n.parsedType}),C}return Te(e.data)}};Br.create=t=>new Br({typeName:$.ZodSymbol,...D(t)});var pr=class extends q{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return k(n,{code:b.invalid_type,expected:z.undefined,received:n.parsedType}),C}return Te(e.data)}};pr.create=t=>new pr({typeName:$.ZodUndefined,...D(t)});var fr=class extends q{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return k(n,{code:b.invalid_type,expected:z.null,received:n.parsedType}),C}return Te(e.data)}};fr.create=t=>new fr({typeName:$.ZodNull,...D(t)});var Dt=class extends q{constructor(){super(...arguments),this._any=!0}_parse(e){return Te(e.data)}};Dt.create=t=>new Dt({typeName:$.ZodAny,...D(t)});var Tt=class extends q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Te(e.data)}};Tt.create=t=>new Tt({typeName:$.ZodUnknown,...D(t)});var st=class extends q{_parse(e){let r=this._getOrReturnCtx(e);return k(r,{code:b.invalid_type,expected:z.never,received:r.parsedType}),C}};st.create=t=>new st({typeName:$.ZodNever,...D(t)});var Xr=class extends q{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return k(n,{code:b.invalid_type,expected:z.void,received:n.parsedType}),C}return Te(e.data)}};Xr.create=t=>new Xr({typeName:$.ZodVoid,...D(t)});var Pt=class t extends q{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return k(r,{code:b.invalid_type,expected:z.array,received:r.parsedType}),C;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(k(r,{code:i?b.too_big:b.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(k(r,{code:b.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(k(r,{code:b.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Ge(r,i,r.path,a)))).then(i=>we.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Ge(r,i,r.path,a)));return we.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:O.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:O.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:O.toString(r)}})}nonempty(e){return this.min(1,e)}};Pt.create=(t,e)=>new Pt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...D(e)});function Kr(t){if(t instanceof De){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Me.create(Kr(n))}return new De({...t._def,shape:()=>e})}else return t instanceof Pt?new Pt({...t._def,type:Kr(t.element)}):t instanceof Me?Me.create(Kr(t.unwrap())):t instanceof gt?gt.create(Kr(t.unwrap())):t instanceof ht?ht.create(t.items.map(e=>Kr(e))):t}var De=class t extends q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=H.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return k(u,{code:b.invalid_type,expected:z.object,received:u.parsedType}),C}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof st&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ge(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof st){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(k(o,{code:b.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ge(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>we.mergeObjectSync(n,u)):we.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:O.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:$.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of H.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of H.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Kr(this)}partial(e){let r={};for(let n of H.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of H.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Me;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Tp(H.objectKeys(this.shape))}};De.create=(t,e)=>new De({shape:()=>t,unknownKeys:"strip",catchall:st.create(),typeName:$.ZodObject,...D(e)});De.strictCreate=(t,e)=>new De({shape:()=>t,unknownKeys:"strict",catchall:st.create(),typeName:$.ZodObject,...D(e)});De.lazycreate=(t,e)=>new De({shape:t,unknownKeys:"strip",catchall:st.create(),typeName:$.ZodObject,...D(e)});var mr=class extends q{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ae(a.ctx.common.issues));return k(r,{code:b.invalid_union,unionErrors:i}),C}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ae(c));return k(r,{code:b.invalid_union,unionErrors:a}),C}}get options(){return this._def.options}};mr.create=(t,e)=>new mr({options:t,typeName:$.ZodUnion,...D(e)});var zt=t=>t instanceof gr?zt(t.schema):t instanceof We?zt(t.innerType()):t instanceof yr?[t.value]:t instanceof _r?t.options:t instanceof vr?H.objectValues(t.enum):t instanceof xr?zt(t._def.innerType):t instanceof pr?[void 0]:t instanceof fr?[null]:t instanceof Me?[void 0,...zt(t.unwrap())]:t instanceof gt?[null,...zt(t.unwrap())]:t instanceof An||t instanceof br?zt(t.unwrap()):t instanceof wr?zt(t._def.innerType):[],Yo=class t extends q{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return k(r,{code:b.invalid_type,expected:z.object,received:r.parsedType}),C;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(k(r,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=zt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:$.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...D(n)})}};function aa(t,e){let r=mt(t),n=mt(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=H.objectKeys(e),s=H.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=aa(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=aa(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var hr=class extends q{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Go(s)||Go(i))return C;let a=aa(s.value,i.value);return a.valid?((Wo(s)||Wo(i))&&r.dirty(),{status:r.value,value:a.data}):(k(n,{code:b.invalid_intersection_types}),C)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};hr.create=(t,e,r)=>new hr({left:t,right:e,typeName:$.ZodIntersection,...D(r)});var ht=class t extends q{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return k(n,{code:b.invalid_type,expected:z.array,received:n.parsedType}),C;if(n.data.length<this._def.items.length)return k(n,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&n.data.length>this._def.items.length&&(k(n,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ge(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>we.mergeArray(r,i)):we.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ht.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ht({items:t,typeName:$.ZodTuple,rest:null,...D(e)})};var Qo=class t extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return k(n,{code:b.invalid_type,expected:z.object,received:n.parsedType}),C;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Ge(n,a,n.path,a)),value:i._parse(new Ge(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?we.mergeObjectAsync(r,o):we.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof q?new t({keyType:e,valueType:r,typeName:$.ZodRecord,...D(n)}):new t({keyType:Mt.create(),valueType:e,typeName:$.ZodRecord,...D(r)})}},Jr=class extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return k(n,{code:b.invalid_type,expected:z.map,received:n.parsedType}),C;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Ge(n,a,n.path,[u,"key"])),value:s._parse(new Ge(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return C;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return C;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Jr.create=(t,e,r)=>new Jr({valueType:e,keyType:t,typeName:$.ZodMap,...D(r)});var Gr=class t extends q{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return k(n,{code:b.invalid_type,expected:z.set,received:n.parsedType}),C;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(k(n,{code:b.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(k(n,{code:b.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return C;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Ge(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:O.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:O.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gr.create=(t,e)=>new Gr({valueType:t,minSize:null,maxSize:null,typeName:$.ZodSet,...D(e)});var es=class t extends q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return k(r,{code:b.invalid_type,expected:z.function,received:r.parsedType}),C;function n(a,c){return Zn({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vr(),St].filter(u=>!!u),issueData:{code:b.invalid_arguments,argumentsError:c}})}function o(a,c){return Zn({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vr(),St].filter(u=>!!u),issueData:{code:b.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Lt){let a=this;return Te(async function(...c){let u=new Ae([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return Te(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ae([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ae([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ht.create(e).rest(Tt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||ht.create([]).rest(Tt.create()),returns:r||Tt.create(),typeName:$.ZodFunction,...D(n)})}},gr=class extends q{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};gr.create=(t,e)=>new gr({getter:t,typeName:$.ZodLazy,...D(e)});var yr=class extends q{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return k(r,{received:r.data,code:b.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:e.data}}get value(){return this._def.value}};yr.create=(t,e)=>new yr({value:t,typeName:$.ZodLiteral,...D(e)});function Tp(t,e){return new _r({values:t,typeName:$.ZodEnum,...D(e)})}var _r=class t extends q{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return k(r,{expected:H.joinValues(n),received:r.parsedType,code:b.invalid_type}),C}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return k(r,{received:r.data,code:b.invalid_enum_value,options:n}),C}return Te(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};_r.create=Tp;var vr=class extends q{_parse(e){let r=H.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=H.objectValues(r);return k(n,{expected:H.joinValues(o),received:n.parsedType,code:b.invalid_type}),C}if(this._cache||(this._cache=new Set(H.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=H.objectValues(r);return k(n,{received:n.data,code:b.invalid_enum_value,options:o}),C}return Te(e.data)}get enum(){return this._def.values}};vr.create=(t,e)=>new vr({values:t,typeName:$.ZodNativeEnum,...D(e)});var Lt=class extends q{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return k(r,{code:b.invalid_type,expected:z.promise,received:r.parsedType}),C;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return Te(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Lt.create=(t,e)=>new Lt({type:t,typeName:$.ZodPromise,...D(e)});var We=class extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{k(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return C;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?C:c.status==="dirty"?ar(c.value):r.value==="dirty"?ar(c.value):c});{if(r.value==="aborted")return C;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?C:a.status==="dirty"?ar(a.value):r.value==="dirty"?ar(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?C:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?C:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!At(i))return C;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>At(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):C);H.assertNever(o)}};We.create=(t,e,r)=>new We({schema:t,typeName:$.ZodEffects,effect:e,...D(r)});We.createWithPreprocess=(t,e,r)=>new We({schema:e,effect:{type:"preprocess",transform:t},typeName:$.ZodEffects,...D(r)});var Me=class extends q{_parse(e){return this._getType(e)===z.undefined?Te(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Me.create=(t,e)=>new Me({innerType:t,typeName:$.ZodOptional,...D(e)});var gt=class extends q{_parse(e){return this._getType(e)===z.null?Te(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(t,e)=>new gt({innerType:t,typeName:$.ZodNullable,...D(e)});var xr=class extends q{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};xr.create=(t,e)=>new xr({innerType:t,typeName:$.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...D(e)});var wr=class extends q{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Hr(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ae(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ae(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};wr.create=(t,e)=>new wr({innerType:t,typeName:$.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...D(e)});var Wr=class extends q{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return k(n,{code:b.invalid_type,expected:z.nan,received:n.parsedType}),C}return{status:"valid",value:e.data}}};Wr.create=t=>new Wr({typeName:$.ZodNaN,...D(t)});var gx=Symbol("zod_brand"),An=class extends q{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Mn=class t extends q{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?C:s.status==="dirty"?(r.dirty(),ar(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?C:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:$.ZodPipeline})}},br=class extends q{_parse(e){let r=this._def.innerType._parse(e),n=o=>(At(o)&&(o.value=Object.freeze(o.value)),o);return Hr(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};br.create=(t,e)=>new br({innerType:t,typeName:$.ZodReadonly,...D(e)});function $p(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Pp(t,e={},r){return t?Dt.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=$p(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=$p(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Dt.create()}var yx={object:De.lazycreate},$;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})($||($={}));var _x=(t,e={message:`Input not instance of ${t.name}`})=>Pp(r=>r instanceof t,e),Op=Mt.create,Ep=cr.create,vx=Wr.create,xx=ur.create,Ip=lr.create,wx=dr.create,bx=Br.create,$x=pr.create,kx=fr.create,Sx=Dt.create,zx=Tt.create,Tx=st.create,Px=Xr.create,Ox=Pt.create,ca=De.create,Ex=De.strictCreate,Ix=mr.create,Rx=Yo.create,jx=hr.create,Nx=ht.create,Cx=Qo.create,Zx=Jr.create,Ax=Gr.create,Mx=es.create,Dx=gr.create,Lx=yr.create,qx=_r.create,Ux=vr.create,Fx=Lt.create,Vx=We.create,Hx=Me.create,Kx=gt.create,Bx=We.createWithPreprocess,Xx=Mn.create,Jx=()=>Op().optional(),Gx=()=>Ep().optional(),Wx=()=>Ip().optional(),Yx={string:(t=>Mt.create({...t,coerce:!0})),number:(t=>cr.create({...t,coerce:!0})),boolean:(t=>lr.create({...t,coerce:!0})),bigint:(t=>ur.create({...t,coerce:!0})),date:(t=>dr.create({...t,coerce:!0}))};var Qx=C;var ew=Object.freeze({status:"aborted"});function _(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Ot=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ts={};function Be(t){return t&&Object.assign(ts,t),ts}var K={};qo(K,{BIGINT_FORMAT_RANGES:()=>jp,Class:()=>la,NUMBER_FORMAT_RANGES:()=>ya,aborted:()=>Sr,allowsEval:()=>ma,assert:()=>sw,assertEqual:()=>tw,assertIs:()=>nw,assertNever:()=>ow,assertNotEqual:()=>rw,assignProp:()=>fa,cached:()=>qn,captureStackTrace:()=>ns,cleanEnum:()=>_w,cleanRegex:()=>Fn,clone:()=>Xe,createTransparentProxy:()=>dw,defineLazy:()=>ne,esc:()=>kr,escapeRegex:()=>qt,extend:()=>mw,finalizeIssue:()=>it,floatSafeRemainder:()=>pa,getElementAtPath:()=>iw,getEnumValues:()=>Ln,getLengthableOrigin:()=>Vn,getParsedType:()=>lw,getSizableOrigin:()=>Np,isObject:()=>Yr,isPlainObject:()=>Qr,issue:()=>_a,joinValues:()=>rs,jsonStringifyReplacer:()=>da,merge:()=>hw,normalizeParams:()=>Z,nullish:()=>Un,numKeys:()=>uw,omit:()=>fw,optionalKeys:()=>ga,partial:()=>gw,pick:()=>pw,prefixIssues:()=>yt,primitiveTypes:()=>Rp,promiseAllObject:()=>aw,propertyKeyTypes:()=>ha,randomString:()=>cw,required:()=>yw,stringifyPrimitive:()=>os,unwrapMessage:()=>Dn});function tw(t){return t}function rw(t){return t}function nw(t){}function ow(t){throw new Error}function sw(t){}function Ln(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function rs(t,e="|"){return t.map(r=>os(r)).join(e)}function da(t,e){return typeof e=="bigint"?e.toString():e}function qn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Un(t){return t==null}function Fn(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function pa(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function ne(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function fa(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function iw(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function aw(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function cw(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function kr(t){return JSON.stringify(t)}var ns=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Yr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var ma=qn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Qr(t){if(Yr(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Yr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function uw(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var lw=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ha=new Set(["string","number","symbol"]),Rp=new Set(["string","number","bigint","boolean","symbol","undefined"]);function qt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xe(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Z(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function dw(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function os(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ga(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var ya={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},jp={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pw(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Xe(t,{...t._zod.def,shape:r,checks:[]})}function fw(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Xe(t,{...t._zod.def,shape:r,checks:[]})}function mw(t,e){if(!Qr(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return fa(this,"shape",n),n},checks:[]};return Xe(t,r)}function hw(t,e){return Xe(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return fa(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function gw(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Xe(e,{...e._zod.def,shape:o,checks:[]})}function yw(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Xe(e,{...e._zod.def,shape:o,checks:[]})}function Sr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function yt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Dn(t){return typeof t=="string"?t:t?.message}function it(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Dn(t.inst?._zod.def?.error?.(t))??Dn(e?.error?.(t))??Dn(r.customError?.(t))??Dn(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Np(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Vn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _a(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function _w(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var la=class{constructor(...e){}};var Cp=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,da,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ss=_("$ZodError",Cp),Hn=_("$ZodError",Cp,{Parent:Error});function va(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function xa(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var wa=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ot;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>it(c,s,Be())));throw ns(a,o?.callee),a}return i.value},ba=wa(Hn),$a=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>it(c,s,Be())));throw ns(a,o?.callee),a}return i.value},ka=$a(Hn),Sa=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ot;return s.issues.length?{success:!1,error:new(t??ss)(s.issues.map(i=>it(i,o,Be())))}:{success:!0,data:s.value}},zr=Sa(Hn),za=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>it(i,o,Be())))}:{success:!0,data:s.value}},Tr=za(Hn);var Zp=/^[cC][^\s-]{8,}$/,Ap=/^[0-9a-z]+$/,Mp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dp=/^[0-9a-vA-V]{20}$/,Lp=/^[A-Za-z0-9]{27}$/,qp=/^[a-zA-Z0-9_-]{21}$/,Up=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Fp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ta=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var Vp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var xw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Hp(){return new RegExp(xw,"u")}var Kp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Bp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Xp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Jp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Gp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pa=/^[A-Za-z0-9_-]*$/,Wp=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Yp=/^\+(?:[0-9]){6,14}[0-9]$/,Qp="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ef=new RegExp(`^${Qp}$`);function tf(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function rf(t){return new RegExp(`^${tf(t)}$`)}function nf(t){let e=tf({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Qp}T(?:${n})$`)}var of=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var sf=/^\d+$/,af=/^-?\d+(?:\.\d+)?/i,cf=/true|false/i,uf=/null/i;var lf=/^[^A-Z]*$/,df=/^[^a-z]*$/;var be=_("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),pf={number:"number",bigint:"bigint",object:"date"},Oa=_("$ZodCheckLessThan",(t,e)=>{be.init(t,e);let r=pf[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ea=_("$ZodCheckGreaterThan",(t,e)=>{be.init(t,e);let r=pf[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),ff=_("$ZodCheckMultipleOf",(t,e)=>{be.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):pa(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),mf=_("$ZodCheckNumberFormat",(t,e)=>{be.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=ya[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=sf)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var hf=_("$ZodCheckMaxLength",(t,e)=>{var r;be.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Un(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Vn(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),gf=_("$ZodCheckMinLength",(t,e)=>{var r;be.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Un(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Vn(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),yf=_("$ZodCheckLengthEquals",(t,e)=>{var r;be.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Un(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Vn(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Kn=_("$ZodCheckStringFormat",(t,e)=>{var r,n;be.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),_f=_("$ZodCheckRegex",(t,e)=>{Kn.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),vf=_("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=lf),Kn.init(t,e)}),xf=_("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=df),Kn.init(t,e)}),wf=_("$ZodCheckIncludes",(t,e)=>{be.init(t,e);let r=qt(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),bf=_("$ZodCheckStartsWith",(t,e)=>{be.init(t,e);let r=new RegExp(`^${qt(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),$f=_("$ZodCheckEndsWith",(t,e)=>{be.init(t,e);let r=new RegExp(`.*${qt(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var kf=_("$ZodCheckOverwrite",(t,e)=>{be.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var as=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
126
|
-
`).filter(
|
|
127
|
-
`))}};var
|
|
128
|
-
if (${
|
|
129
|
-
if (input[${
|
|
130
|
-
if (${
|
|
131
|
-
newResult[${
|
|
296
|
+
`);let t=process.versions.node,e=Number(t.split(".")[0])>=18;tE(e,`Node ${t}`,e?"":"OIOXO needs Node \u2265 18.17"),console.log(` \xB7 Control plane: ${gn}`);let r=!1;try{r=(await fetch(gn+"/api/version",{signal:AbortSignal.timeout(6e3)})).ok}catch{r=!1}tE(r,"Control plane reachable",r?"":"could not reach oioxo.com (offline or blocked)");let n=await Uc();if(tE(n,n?"Signed in":"Not signed in",n?"":"run `oioxo login`"),n){let c=await ms("check");c&&console.log(` \xB7 Plan: ${H5(c)}`)}let s=await vl(),i=_l.filter(c=>s[c]!=null);if(i.length)console.log(` \xB7 Coder pin: ${i.map(c=>`${c}=${Om(c,String(s[c]))}`).join(" ")}`);else{let c=["OIOXO_PROVIDER","OPENAI_API_KEY","ANTHROPIC_API_KEY","GROQ_API_KEY"].filter(u=>process.env[u]);console.log(` \xB7 Coder: ${c.length?"from env ("+c.join(", ")+")":"not configured \u2014 `oioxo model use <provider>` or set a key"}`)}let a=(await YC(process.cwd(),q5.homedir())).filter(c=>c.configured);tE(a.length>0,`Agents wired: ${a.length?a.map(c=>c.display).join(", "):"none"}`,a.length?"":"run `oioxo init` to wire your AI agent"),console.log("")}function YW(t){console.log(`
|
|
297
|
+
OIOXO CLI ${t}`),console.log("Update to the latest with:"),console.log(" npm : npm i -g oioxo-mcp@latest"),console.log(" npx : npx oioxo-mcp@latest <command> (always runs the newest)")}function H5(t){return t.tier==="pro"?"OIOXO Pro \u2014 unlimited":t.tier==="free"?"OIOXO Free \u2014 monthly allowance":t.tier}function tE(t,e,r){console.log(` ${t?"\u2713":"\u2717"} ${e}${r?` \u2014 ${r}`:""}`)}var Pf={};$a(Pf,{BRAND:()=>Zge,DIRTY:()=>pf,EMPTY_PATH:()=>Ege,INVALID:()=>st,NEVER:()=>Pye,OK:()=>ls,ParseStatus:()=>Zn,Schema:()=>Nt,ZodAny:()=>Xu,ZodArray:()=>$c,ZodBigInt:()=>gf,ZodBoolean:()=>yf,ZodBranded:()=>f1,ZodCatch:()=>Tf,ZodDate:()=>xf,ZodDefault:()=>kf,ZodDiscriminatedUnion:()=>sE,ZodEffects:()=>zi,ZodEnum:()=>Ef,ZodError:()=>Ks,ZodFirstPartyTypeKind:()=>de,ZodFunction:()=>oE,ZodIntersection:()=>wf,ZodIssueCode:()=>ce,ZodLazy:()=>Sf,ZodLiteral:()=>Af,ZodMap:()=>L0,ZodNaN:()=>U0,ZodNativeEnum:()=>Cf,ZodNever:()=>Eo,ZodNull:()=>_f,ZodNullable:()=>Ca,ZodNumber:()=>mf,ZodObject:()=>Gs,ZodOptional:()=>Zs,ZodParsedType:()=>Ie,ZodPipeline:()=>h1,ZodPromise:()=>Ju,ZodReadonly:()=>If,ZodRecord:()=>iE,ZodSchema:()=>Nt,ZodSet:()=>D0,ZodString:()=>Wu,ZodSymbol:()=>j0,ZodTransformer:()=>zi,ZodTuple:()=>Ea,ZodType:()=>Nt,ZodUndefined:()=>bf,ZodUnion:()=>vf,ZodUnknown:()=>Bc,ZodVoid:()=>z0,addIssueToContext:()=>ve,any:()=>rye,array:()=>oye,bigint:()=>Jge,boolean:()=>uX,coerce:()=>Iye,custom:()=>oX,date:()=>Yge,datetimeRegex:()=>sX,defaultErrorMap:()=>Oc,discriminatedUnion:()=>uye,effect:()=>vye,enum:()=>xye,function:()=>mye,getErrorMap:()=>B0,getParsedType:()=>Aa,instanceof:()=>Wge,intersection:()=>lye,isAborted:()=>rE,isAsync:()=>$0,isDirty:()=>nE,isValid:()=>Gu,late:()=>Gge,lazy:()=>gye,literal:()=>yye,makeIssue:()=>d1,map:()=>hye,nan:()=>Xge,nativeEnum:()=>bye,never:()=>sye,null:()=>tye,nullable:()=>Sye,number:()=>cX,object:()=>Z5,objectUtil:()=>F5,oboolean:()=>Tye,onumber:()=>kye,optional:()=>wye,ostring:()=>Cye,pipeline:()=>Eye,preprocess:()=>Aye,promise:()=>_ye,quotelessJson:()=>wge,record:()=>fye,set:()=>pye,setErrorMap:()=>Age,strictObject:()=>aye,string:()=>aX,symbol:()=>Qge,transformer:()=>vye,tuple:()=>dye,undefined:()=>eye,union:()=>cye,unknown:()=>nye,util:()=>Ht,void:()=>iye});var Ht;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ht||(Ht={}));var F5;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(F5||(F5={}));var Ie=Ht.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Aa=t=>{switch(typeof t){case"undefined":return Ie.undefined;case"string":return Ie.string;case"number":return Number.isNaN(t)?Ie.nan:Ie.number;case"boolean":return Ie.boolean;case"function":return Ie.function;case"bigint":return Ie.bigint;case"symbol":return Ie.symbol;case"object":return Array.isArray(t)?Ie.array:t===null?Ie.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Ie.promise:typeof Map<"u"&&t instanceof Map?Ie.map:typeof Set<"u"&&t instanceof Set?Ie.set:typeof Date<"u"&&t instanceof Date?Ie.date:Ie.object;default:return Ie.unknown}};var ce=Ht.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wge=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ks=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ht.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];r[i]=r[i]||[],r[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ks.create=t=>new Ks(t);var Sge=(t,e)=>{let r;switch(t.code){case ce.invalid_type:t.received===Ie.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case ce.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ht.jsonStringifyReplacer)}`;break;case ce.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ht.joinValues(t.keys,", ")}`;break;case ce.invalid_union:r="Invalid input";break;case ce.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ht.joinValues(t.options)}`;break;case ce.invalid_enum_value:r=`Invalid enum value. Expected ${Ht.joinValues(t.options)}, received '${t.received}'`;break;case ce.invalid_arguments:r="Invalid function arguments";break;case ce.invalid_return_type:r="Invalid function return type";break;case ce.invalid_date:r="Invalid date";break;case ce.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ht.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case ce.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case ce.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case ce.custom:r="Invalid input";break;case ce.invalid_intersection_types:r="Intersection results could not be merged";break;case ce.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case ce.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ht.assertNever(t)}return{message:r}},Oc=Sge;var QW=Oc;function Age(t){QW=t}function B0(){return QW}var d1=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,i=[...r,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Ege=[];function ve(t,e){let r=B0(),n=d1({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Oc?void 0:Oc].filter(s=>!!s)});t.common.issues.push(n)}var Zn=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return st;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return st;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},st=Object.freeze({status:"aborted"}),pf=t=>({status:"dirty",value:t}),ls=t=>({status:"valid",value:t}),rE=t=>t.status==="aborted",nE=t=>t.status==="dirty",Gu=t=>t.status==="valid",$0=t=>typeof Promise<"u"&&t instanceof Promise;var Ze;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Ze||(Ze={}));var ji=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},eX=(t,e)=>{if(Gu(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ks(t.common.issues);return this._error=r,this._error}}};function Tt(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}var Nt=class{get description(){return this._def.description}_getType(e){return Aa(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Aa(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Zn,ctx:{common:e.parent.common,data:e.data,parsedType:Aa(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if($0(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)},s=this._parseSync({data:e,path:n.path,parent:n});return eX(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Gu(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Gu(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Aa(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await($0(s)?s:Promise.resolve(s));return eX(n,i)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:ce.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new zi({schema:this,typeName:de.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Zs.create(this,this._def)}nullable(){return Ca.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $c.create(this)}promise(){return Ju.create(this,this._def)}or(e){return vf.create([this,e],this._def)}and(e){return wf.create(this,e,this._def)}transform(e){return new zi({...Tt(this._def),schema:this,typeName:de.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new kf({...Tt(this._def),innerType:this,defaultValue:r,typeName:de.ZodDefault})}brand(){return new f1({typeName:de.ZodBranded,type:this,...Tt(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Tf({...Tt(this._def),innerType:this,catchValue:r,typeName:de.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return h1.create(this,e)}readonly(){return If.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Cge=/^c[^\s-]{8,}$/i,kge=/^[0-9a-z]+$/,Tge=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ige=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Pge=/^[a-z0-9_-]{21}$/i,Rge=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Oge=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Nge=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Bge="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",V5,$ge=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mge=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,jge=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,zge=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Lge=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Dge=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rX="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Uge=new RegExp(`^${rX}$`);function nX(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function qge(t){return new RegExp(`^${nX(t)}$`)}function sX(t){let e=`${rX}T${nX(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Hge(t,e){return!!((e==="v4"||!e)&&$ge.test(t)||(e==="v6"||!e)&&jge.test(t))}function Fge(t,e){if(!Rge.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Vge(t,e){return!!((e==="v4"||!e)&&Mge.test(t)||(e==="v6"||!e)&&zge.test(t))}var Wu=class t extends Nt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Ie.string){let i=this._getOrReturnCtx(e);return ve(i,{code:ce.invalid_type,expected:Ie.string,received:i.parsedType}),st}let n=new Zn,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?ve(s,{code:ce.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&ve(s,{code:ce.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Nge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"email",code:ce.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")V5||(V5=new RegExp(Bge,"u")),V5.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"emoji",code:ce.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Ige.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"uuid",code:ce.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Pge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"nanoid",code:ce.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Cge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"cuid",code:ce.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")kge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"cuid2",code:ce.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Tge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"ulid",code:ce.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ve(s,{validation:"url",code:ce.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"regex",code:ce.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?sX(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Uge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?qge(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Oge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"duration",code:ce.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Hge(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"ip",code:ce.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Fge(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"jwt",code:ce.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Vge(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"cidr",code:ce.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Lge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"base64",code:ce.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Dge.test(e.data)||(s=this._getOrReturnCtx(e,s),ve(s,{validation:"base64url",code:ce.invalid_string,message:i.message}),n.dirty()):Ht.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:ce.invalid_string,...Ze.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Ze.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ze.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ze.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ze.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ze.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ze.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ze.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ze.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ze.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ze.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ze.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ze.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ze.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Ze.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Ze.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Ze.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Ze.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...Ze.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Ze.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Ze.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Ze.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Ze.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Ze.errToObj(r)})}nonempty(e){return this.min(1,Ze.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Wu.create=t=>new Wu({checks:[],typeName:de.ZodString,coerce:t?.coerce??!1,...Tt(t)});function Kge(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var mf=class t extends Nt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Ie.number){let i=this._getOrReturnCtx(e);return ve(i,{code:ce.invalid_type,expected:Ie.number,received:i.parsedType}),st}let n,s=new Zn;for(let i of this._def.checks)i.kind==="int"?Ht.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),ve(n,{code:ce.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),ve(n,{code:ce.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),ve(n,{code:ce.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Kge(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),ve(n,{code:ce.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),ve(n,{code:ce.not_finite,message:i.message}),s.dirty()):Ht.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Ze.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Ze.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Ze.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Ze.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Ze.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Ze.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ze.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ze.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ze.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ze.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Ze.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Ze.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ze.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ze.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ht.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};mf.create=t=>new mf({checks:[],typeName:de.ZodNumber,coerce:t?.coerce||!1,...Tt(t)});var gf=class t extends Nt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Ie.bigint)return this._getInvalidInput(e);let n,s=new Zn;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),ve(n,{code:ce.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),ve(n,{code:ce.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),ve(n,{code:ce.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Ht.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return ve(r,{code:ce.invalid_type,expected:Ie.bigint,received:r.parsedType}),st}gte(e,r){return this.setLimit("min",e,!0,Ze.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Ze.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Ze.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Ze.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Ze.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ze.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ze.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ze.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ze.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Ze.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};gf.create=t=>new gf({checks:[],typeName:de.ZodBigInt,coerce:t?.coerce??!1,...Tt(t)});var yf=class extends Nt{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Ie.boolean){let n=this._getOrReturnCtx(e);return ve(n,{code:ce.invalid_type,expected:Ie.boolean,received:n.parsedType}),st}return ls(e.data)}};yf.create=t=>new yf({typeName:de.ZodBoolean,coerce:t?.coerce||!1,...Tt(t)});var xf=class t extends Nt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Ie.date){let i=this._getOrReturnCtx(e);return ve(i,{code:ce.invalid_type,expected:Ie.date,received:i.parsedType}),st}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return ve(i,{code:ce.invalid_date}),st}let n=new Zn,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),ve(s,{code:ce.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Ht.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Ze.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Ze.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};xf.create=t=>new xf({checks:[],coerce:t?.coerce||!1,typeName:de.ZodDate,...Tt(t)});var j0=class extends Nt{_parse(e){if(this._getType(e)!==Ie.symbol){let n=this._getOrReturnCtx(e);return ve(n,{code:ce.invalid_type,expected:Ie.symbol,received:n.parsedType}),st}return ls(e.data)}};j0.create=t=>new j0({typeName:de.ZodSymbol,...Tt(t)});var bf=class extends Nt{_parse(e){if(this._getType(e)!==Ie.undefined){let n=this._getOrReturnCtx(e);return ve(n,{code:ce.invalid_type,expected:Ie.undefined,received:n.parsedType}),st}return ls(e.data)}};bf.create=t=>new bf({typeName:de.ZodUndefined,...Tt(t)});var _f=class extends Nt{_parse(e){if(this._getType(e)!==Ie.null){let n=this._getOrReturnCtx(e);return ve(n,{code:ce.invalid_type,expected:Ie.null,received:n.parsedType}),st}return ls(e.data)}};_f.create=t=>new _f({typeName:de.ZodNull,...Tt(t)});var Xu=class extends Nt{constructor(){super(...arguments),this._any=!0}_parse(e){return ls(e.data)}};Xu.create=t=>new Xu({typeName:de.ZodAny,...Tt(t)});var Bc=class extends Nt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ls(e.data)}};Bc.create=t=>new Bc({typeName:de.ZodUnknown,...Tt(t)});var Eo=class extends Nt{_parse(e){let r=this._getOrReturnCtx(e);return ve(r,{code:ce.invalid_type,expected:Ie.never,received:r.parsedType}),st}};Eo.create=t=>new Eo({typeName:de.ZodNever,...Tt(t)});var z0=class extends Nt{_parse(e){if(this._getType(e)!==Ie.undefined){let n=this._getOrReturnCtx(e);return ve(n,{code:ce.invalid_type,expected:Ie.void,received:n.parsedType}),st}return ls(e.data)}};z0.create=t=>new z0({typeName:de.ZodVoid,...Tt(t)});var $c=class t extends Nt{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==Ie.array)return ve(r,{code:ce.invalid_type,expected:Ie.array,received:r.parsedType}),st;if(s.exactLength!==null){let o=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(o||a)&&(ve(r,{code:o?ce.too_big:ce.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(ve(r,{code:ce.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(ve(r,{code:ce.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>s.type._parseAsync(new ji(r,o,r.path,a)))).then(o=>Zn.mergeArray(n,o));let i=[...r.data].map((o,a)=>s.type._parseSync(new ji(r,o,r.path,a)));return Zn.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:Ze.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:Ze.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:Ze.toString(r)}})}nonempty(e){return this.min(1,e)}};$c.create=(t,e)=>new $c({type:t,minLength:null,maxLength:null,exactLength:null,typeName:de.ZodArray,...Tt(e)});function M0(t){if(t instanceof Gs){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Zs.create(M0(n))}return new Gs({...t._def,shape:()=>e})}else return t instanceof $c?new $c({...t._def,type:M0(t.element)}):t instanceof Zs?Zs.create(M0(t.unwrap())):t instanceof Ca?Ca.create(M0(t.unwrap())):t instanceof Ea?Ea.create(t.items.map(e=>M0(e))):t}var Gs=class t extends Nt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=Ht.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==Ie.object){let u=this._getOrReturnCtx(e);return ve(u,{code:ce.invalid_type,expected:Ie.object,received:u.parsedType}),st}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Eo&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||a.push(u);let c=[];for(let u of o){let l=i[u],d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ji(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Eo){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")a.length>0&&(ve(s,{code:ce.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ji(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Zn.mergeObjectSync(n,u)):Zn.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return Ze.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Ze.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:de.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Ht.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Ht.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return M0(this)}partial(e){let r={};for(let n of Ht.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Ht.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Zs;)i=i._def.innerType;r[n]=i}return new t({...this._def,shape:()=>r})}keyof(){return iX(Ht.objectKeys(this.shape))}};Gs.create=(t,e)=>new Gs({shape:()=>t,unknownKeys:"strip",catchall:Eo.create(),typeName:de.ZodObject,...Tt(e)});Gs.strictCreate=(t,e)=>new Gs({shape:()=>t,unknownKeys:"strict",catchall:Eo.create(),typeName:de.ZodObject,...Tt(e)});Gs.lazycreate=(t,e)=>new Gs({shape:t,unknownKeys:"strip",catchall:Eo.create(),typeName:de.ZodObject,...Tt(e)});var vf=class extends Nt{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new Ks(a.ctx.common.issues));return ve(r,{code:ce.invalid_union,unionErrors:o}),st}if(r.common.async)return Promise.all(n.map(async i=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new Ks(c));return ve(r,{code:ce.invalid_union,unionErrors:a}),st}}get options(){return this._def.options}};vf.create=(t,e)=>new vf({options:t,typeName:de.ZodUnion,...Tt(e)});var Nc=t=>t instanceof Sf?Nc(t.schema):t instanceof zi?Nc(t.innerType()):t instanceof Af?[t.value]:t instanceof Ef?t.options:t instanceof Cf?Ht.objectValues(t.enum):t instanceof kf?Nc(t._def.innerType):t instanceof bf?[void 0]:t instanceof _f?[null]:t instanceof Zs?[void 0,...Nc(t.unwrap())]:t instanceof Ca?[null,...Nc(t.unwrap())]:t instanceof f1||t instanceof If?Nc(t.unwrap()):t instanceof Tf?Nc(t._def.innerType):[],sE=class t extends Nt{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Ie.object)return ve(r,{code:ce.invalid_type,expected:Ie.object,received:r.parsedType}),st;let n=this.discriminator,s=r.data[n],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(ve(r,{code:ce.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),st)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let i of r){let o=Nc(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new t({typeName:de.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...Tt(n)})}};function K5(t,e){let r=Aa(t),n=Aa(e);if(t===e)return{valid:!0,data:t};if(r===Ie.object&&n===Ie.object){let s=Ht.objectKeys(e),i=Ht.objectKeys(t).filter(a=>s.indexOf(a)!==-1),o={...t,...e};for(let a of i){let c=K5(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===Ie.array&&n===Ie.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],a=e[i],c=K5(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===Ie.date&&n===Ie.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var wf=class extends Nt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(rE(i)||rE(o))return st;let a=K5(i.value,o.value);return a.valid?((nE(i)||nE(o))&&r.dirty(),{status:r.value,value:a.data}):(ve(n,{code:ce.invalid_intersection_types}),st)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};wf.create=(t,e,r)=>new wf({left:t,right:e,typeName:de.ZodIntersection,...Tt(r)});var Ea=class t extends Nt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ie.array)return ve(n,{code:ce.invalid_type,expected:Ie.array,received:n.parsedType}),st;if(n.data.length<this._def.items.length)return ve(n,{code:ce.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),st;!this._def.rest&&n.data.length>this._def.items.length&&(ve(n,{code:ce.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ji(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>Zn.mergeArray(r,o)):Zn.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ea.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ea({items:t,typeName:de.ZodTuple,rest:null,...Tt(e)})};var iE=class t extends Nt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ie.object)return ve(n,{code:ce.invalid_type,expected:Ie.object,received:n.parsedType}),st;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new ji(n,a,n.path,a)),value:o._parse(new ji(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Zn.mergeObjectAsync(r,s):Zn.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Nt?new t({keyType:e,valueType:r,typeName:de.ZodRecord,...Tt(n)}):new t({keyType:Wu.create(),valueType:e,typeName:de.ZodRecord,...Tt(r)})}},L0=class extends Nt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ie.map)return ve(n,{code:ce.invalid_type,expected:Ie.map,received:n.parsedType}),st;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new ji(n,a,n.path,[u,"key"])),value:i._parse(new ji(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return st;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return st;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};L0.create=(t,e,r)=>new L0({valueType:e,keyType:t,typeName:de.ZodMap,...Tt(r)});var D0=class t extends Nt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ie.set)return ve(n,{code:ce.invalid_type,expected:Ie.set,received:n.parsedType}),st;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(ve(n,{code:ce.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(ve(n,{code:ce.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return st;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>i._parse(new ji(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:Ze.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:Ze.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};D0.create=(t,e)=>new D0({valueType:t,minSize:null,maxSize:null,typeName:de.ZodSet,...Tt(e)});var oE=class t extends Nt{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Ie.function)return ve(r,{code:ce.invalid_type,expected:Ie.function,received:r.parsedType}),st;function n(a,c){return d1({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,B0(),Oc].filter(u=>!!u),issueData:{code:ce.invalid_arguments,argumentsError:c}})}function s(a,c){return d1({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,B0(),Oc].filter(u=>!!u),issueData:{code:ce.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ju){let a=this;return ls(async function(...c){let u=new Ks([]),l=await a._def.args.parseAsync(c,i).catch(p=>{throw u.addIssue(n(c,p)),u}),d=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(d,i).catch(p=>{throw u.addIssue(s(d,p)),u})})}else{let a=this;return ls(function(...c){let u=a._def.args.safeParse(c,i);if(!u.success)throw new Ks([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=a._def.returns.safeParse(l,i);if(!d.success)throw new Ks([s(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ea.create(e).rest(Bc.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Ea.create([]).rest(Bc.create()),returns:r||Bc.create(),typeName:de.ZodFunction,...Tt(n)})}},Sf=class extends Nt{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Sf.create=(t,e)=>new Sf({getter:t,typeName:de.ZodLazy,...Tt(e)});var Af=class extends Nt{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return ve(r,{received:r.data,code:ce.invalid_literal,expected:this._def.value}),st}return{status:"valid",value:e.data}}get value(){return this._def.value}};Af.create=(t,e)=>new Af({value:t,typeName:de.ZodLiteral,...Tt(e)});function iX(t,e){return new Ef({values:t,typeName:de.ZodEnum,...Tt(e)})}var Ef=class t extends Nt{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return ve(r,{expected:Ht.joinValues(n),received:r.parsedType,code:ce.invalid_type}),st}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return ve(r,{received:r.data,code:ce.invalid_enum_value,options:n}),st}return ls(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ef.create=iX;var Cf=class extends Nt{_parse(e){let r=Ht.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Ie.string&&n.parsedType!==Ie.number){let s=Ht.objectValues(r);return ve(n,{expected:Ht.joinValues(s),received:n.parsedType,code:ce.invalid_type}),st}if(this._cache||(this._cache=new Set(Ht.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=Ht.objectValues(r);return ve(n,{received:n.data,code:ce.invalid_enum_value,options:s}),st}return ls(e.data)}get enum(){return this._def.values}};Cf.create=(t,e)=>new Cf({values:t,typeName:de.ZodNativeEnum,...Tt(e)});var Ju=class extends Nt{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Ie.promise&&r.common.async===!1)return ve(r,{code:ce.invalid_type,expected:Ie.promise,received:r.parsedType}),st;let n=r.parsedType===Ie.promise?r.data:Promise.resolve(r.data);return ls(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ju.create=(t,e)=>new Ju({type:t,typeName:de.ZodPromise,...Tt(e)});var zi=class extends Nt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===de.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{ve(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return st;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?st:c.status==="dirty"?pf(c.value):r.value==="dirty"?pf(c.value):c});{if(r.value==="aborted")return st;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?st:a.status==="dirty"?pf(a.value):r.value==="dirty"?pf(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?st:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?st:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Gu(o))return st;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Gu(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:r.value,value:a})):st);Ht.assertNever(s)}};zi.create=(t,e,r)=>new zi({schema:t,typeName:de.ZodEffects,effect:e,...Tt(r)});zi.createWithPreprocess=(t,e,r)=>new zi({schema:e,effect:{type:"preprocess",transform:t},typeName:de.ZodEffects,...Tt(r)});var Zs=class extends Nt{_parse(e){return this._getType(e)===Ie.undefined?ls(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Zs.create=(t,e)=>new Zs({innerType:t,typeName:de.ZodOptional,...Tt(e)});var Ca=class extends Nt{_parse(e){return this._getType(e)===Ie.null?ls(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ca.create=(t,e)=>new Ca({innerType:t,typeName:de.ZodNullable,...Tt(e)});var kf=class extends Nt{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===Ie.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};kf.create=(t,e)=>new kf({innerType:t,typeName:de.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Tt(e)});var Tf=class extends Nt{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return $0(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ks(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ks(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Tf.create=(t,e)=>new Tf({innerType:t,typeName:de.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Tt(e)});var U0=class extends Nt{_parse(e){if(this._getType(e)!==Ie.nan){let n=this._getOrReturnCtx(e);return ve(n,{code:ce.invalid_type,expected:Ie.nan,received:n.parsedType}),st}return{status:"valid",value:e.data}}};U0.create=t=>new U0({typeName:de.ZodNaN,...Tt(t)});var Zge=Symbol("zod_brand"),f1=class extends Nt{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},h1=class t extends Nt{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?st:i.status==="dirty"?(r.dirty(),pf(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?st:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:de.ZodPipeline})}},If=class extends Nt{_parse(e){let r=this._def.innerType._parse(e),n=s=>(Gu(s)&&(s.value=Object.freeze(s.value)),s);return $0(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};If.create=(t,e)=>new If({innerType:t,typeName:de.ZodReadonly,...Tt(e)});function tX(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function oX(t,e={},r){return t?Xu.create().superRefine((n,s)=>{let i=t(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=tX(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=tX(e,n),a=o.fatal??r??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Xu.create()}var Gge={object:Gs.lazycreate},de;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(de||(de={}));var Wge=(t,e={message:`Input not instance of ${t.name}`})=>oX(r=>r instanceof t,e),aX=Wu.create,cX=mf.create,Xge=U0.create,Jge=gf.create,uX=yf.create,Yge=xf.create,Qge=j0.create,eye=bf.create,tye=_f.create,rye=Xu.create,nye=Bc.create,sye=Eo.create,iye=z0.create,oye=$c.create,Z5=Gs.create,aye=Gs.strictCreate,cye=vf.create,uye=sE.create,lye=wf.create,dye=Ea.create,fye=iE.create,hye=L0.create,pye=D0.create,mye=oE.create,gye=Sf.create,yye=Af.create,xye=Ef.create,bye=Cf.create,_ye=Ju.create,vye=zi.create,wye=Zs.create,Sye=Ca.create,Aye=zi.createWithPreprocess,Eye=h1.create,Cye=()=>aX().optional(),kye=()=>cX().optional(),Tye=()=>uX().optional(),Iye={string:(t=>Wu.create({...t,coerce:!0})),number:(t=>mf.create({...t,coerce:!0})),boolean:(t=>yf.create({...t,coerce:!0})),bigint:(t=>gf.create({...t,coerce:!0})),date:(t=>xf.create({...t,coerce:!0}))};var Pye=st;var Rye=Object.freeze({status:"aborted"});function K(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in o.prototype)l in a||Object.defineProperty(a,l,{value:o.prototype[l].bind(a)});a._zod.constr=o,a._zod.def=c}let s=r?.Parent??Object;class i extends s{}Object.defineProperty(i,"name",{value:t});function o(a){var c;let u=r?.Parent?new i:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var Mc=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},aE={};function mi(t){return t&&Object.assign(aE,t),aE}var Kt={};$a(Kt,{BIGINT_FORMAT_RANGES:()=>dX,Class:()=>W5,NUMBER_FORMAT_RANGES:()=>rR,aborted:()=>Of,allowsEval:()=>Q5,assert:()=>Mye,assertEqual:()=>Oye,assertIs:()=>Bye,assertNever:()=>$ye,assertNotEqual:()=>Nye,assignProp:()=>Y5,cached:()=>g1,captureStackTrace:()=>uE,cleanEnum:()=>Wye,cleanRegex:()=>x1,clone:()=>gi,createTransparentProxy:()=>qye,defineLazy:()=>Or,esc:()=>Rf,escapeRegex:()=>Yu,extend:()=>Vye,finalizeIssue:()=>Co,floatSafeRemainder:()=>J5,getElementAtPath:()=>jye,getEnumValues:()=>m1,getLengthableOrigin:()=>b1,getParsedType:()=>Uye,getSizableOrigin:()=>fX,isObject:()=>q0,isPlainObject:()=>H0,issue:()=>nR,joinValues:()=>cE,jsonStringifyReplacer:()=>X5,merge:()=>Kye,normalizeParams:()=>it,nullish:()=>y1,numKeys:()=>Dye,omit:()=>Fye,optionalKeys:()=>tR,partial:()=>Zye,pick:()=>Hye,prefixIssues:()=>ka,primitiveTypes:()=>lX,promiseAllObject:()=>zye,propertyKeyTypes:()=>eR,randomString:()=>Lye,required:()=>Gye,stringifyPrimitive:()=>lE,unwrapMessage:()=>p1});function Oye(t){return t}function Nye(t){return t}function Bye(t){}function $ye(t){throw new Error}function Mye(t){}function m1(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function cE(t,e="|"){return t.map(r=>lE(r)).join(e)}function X5(t,e){return typeof e=="bigint"?e.toString():e}function g1(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function y1(t){return t==null}function x1(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function J5(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}function Or(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function Y5(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function jye(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function zye(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let s={};for(let i=0;i<e.length;i++)s[e[i]]=n[i];return s})}function Lye(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Rf(t){return JSON.stringify(t)}var uE=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function q0(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Q5=g1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function H0(t){if(q0(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(q0(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Dye(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Uye=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},eR=new Set(["string","number","symbol"]),lX=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Yu(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gi(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function it(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function qye(t){let e;return new Proxy({},{get(r,n,s){return e??(e=t()),Reflect.get(e,n,s)},set(r,n,s,i){return e??(e=t()),Reflect.set(e,n,s,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,s){return e??(e=t()),Reflect.defineProperty(e,n,s)}})}function lE(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function tR(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var rR={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},dX={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Hye(t,e){let r={},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return gi(t,{...t._zod.def,shape:r,checks:[]})}function Fye(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return gi(t,{...t._zod.def,shape:r,checks:[]})}function Vye(t,e){if(!H0(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Y5(this,"shape",n),n},checks:[]};return gi(t,r)}function Kye(t,e){return gi(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Y5(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Zye(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=t?new t({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)s[i]=t?new t({type:"optional",innerType:n[i]}):n[i];return gi(e,{...e._zod.def,shape:s,checks:[]})}function Gye(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:n[i]}))}else for(let i in n)s[i]=new t({type:"nonoptional",innerType:n[i]});return gi(e,{...e._zod.def,shape:s,checks:[]})}function Of(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function ka(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function p1(t){return typeof t=="string"?t:t?.message}function Co(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=p1(t.inst?._zod.def?.error?.(t))??p1(e?.error?.(t))??p1(r.customError?.(t))??p1(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function fX(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function b1(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function nR(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Wye(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var W5=class{constructor(...e){}};var hX=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,X5,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},dE=K("$ZodError",hX),_1=K("$ZodError",hX,{Parent:Error});function sR(t,e=r=>r.message){let r={},n=[];for(let s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function iR(t,e){let r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>s({issues:a}));else if(o.code==="invalid_key")s({issues:o.issues});else if(o.code==="invalid_element")s({issues:o.issues});else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(t),n}var oR=t=>(e,r,n,s)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new Mc;if(o.issues.length){let a=new(s?.Err??t)(o.issues.map(c=>Co(c,i,mi())));throw uE(a,s?.callee),a}return o.value},aR=oR(_1),cR=t=>async(e,r,n,s)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(s?.Err??t)(o.issues.map(c=>Co(c,i,mi())));throw uE(a,s?.callee),a}return o.value},uR=cR(_1),lR=t=>(e,r,n)=>{let s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Mc;return i.issues.length?{success:!1,error:new(t??dE)(i.issues.map(o=>Co(o,s,mi())))}:{success:!0,data:i.value}},Nf=lR(_1),dR=t=>async(e,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(o=>Co(o,s,mi())))}:{success:!0,data:i.value}},Bf=dR(_1);var pX=/^[cC][^\s-]{8,}$/,mX=/^[0-9a-z]+$/,gX=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,yX=/^[0-9a-vA-V]{20}$/,xX=/^[A-Za-z0-9]{27}$/,bX=/^[a-zA-Z0-9_-]{21}$/,_X=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var vX=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fR=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var wX=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Jye="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function SX(){return new RegExp(Jye,"u")}var AX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,EX=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,CX=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,kX=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,TX=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hR=/^[A-Za-z0-9_-]*$/,IX=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var PX=/^\+(?:[0-9]){6,14}[0-9]$/,RX="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",OX=new RegExp(`^${RX}$`);function NX(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function BX(t){return new RegExp(`^${NX(t)}$`)}function $X(t){let e=NX({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${RX}T(?:${n})$`)}var MX=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var jX=/^\d+$/,zX=/^-?\d+(?:\.\d+)?/i,LX=/true|false/i,DX=/null/i;var UX=/^[^A-Z]*$/,qX=/^[^a-z]*$/;var Gn=K("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),HX={number:"number",bigint:"bigint",object:"date"},pR=K("$ZodCheckLessThan",(t,e)=>{Gn.init(t,e);let r=HX[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,i=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),mR=K("$ZodCheckGreaterThan",(t,e)=>{Gn.init(t,e);let r=HX[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,i=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),FX=K("$ZodCheckMultipleOf",(t,e)=>{Gn.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):J5(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),VX=K("$ZodCheckNumberFormat",(t,e)=>{Gn.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,i]=rR[e.format];t._zod.onattach.push(o=>{let a=o._zod.bag;a.format=e.format,a.minimum=s,a.maximum=i,r&&(a.pattern=jX)}),t._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<s&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>i&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:t})}});var KX=K("$ZodCheckMaxLength",(t,e)=>{var r;Gn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!y1(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let s=n.value;if(s.length<=e.maximum)return;let o=b1(s);n.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),ZX=K("$ZodCheckMinLength",(t,e)=>{var r;Gn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!y1(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let s=n.value;if(s.length>=e.minimum)return;let o=b1(s);n.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),GX=K("$ZodCheckLengthEquals",(t,e)=>{var r;Gn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!y1(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{let s=n.value,i=s.length;if(i===e.length)return;let o=b1(s),a=i>e.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),v1=K("$ZodCheckStringFormat",(t,e)=>{var r,n;Gn.init(t,e),t._zod.onattach.push(s=>{let i=s._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),WX=K("$ZodCheckRegex",(t,e)=>{v1.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),XX=K("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=UX),v1.init(t,e)}),JX=K("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=qX),v1.init(t,e)}),YX=K("$ZodCheckIncludes",(t,e)=>{Gn.init(t,e);let r=Yu(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{let i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),QX=K("$ZodCheckStartsWith",(t,e)=>{Gn.init(t,e);let r=new RegExp(`^${Yu(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),eJ=K("$ZodCheckEndsWith",(t,e)=>{Gn.init(t,e);let r=new RegExp(`.*${Yu(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var tJ=K("$ZodCheckOverwrite",(t,e)=>{Gn.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var hE=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
298
|
+
`).filter(o=>o),s=Math.min(...n.map(o=>o.length-o.trimStart().length)),i=n.map(o=>o.slice(s)).map(o=>" ".repeat(this.indent*2)+o);for(let o of i)this.content.push(o)}compile(){let e=Function,r=this?.args,s=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,s.join(`
|
|
299
|
+
`))}};var nJ={major:4,minor:0,patch:0};var wr=K("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=nJ;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let s of n)for(let i of s._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let s=(i,o,a)=>{let c=Of(i),u;for(let l of o){if(l._zod.def.when){if(!l._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,f=l._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new Mc;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(c||(c=Of(i,d)))});else{if(i.issues.length===d)continue;c||(c=Of(i,d))}}return u?u.then(()=>i):i};t._zod.run=(i,o)=>{let a=t._zod.parse(i,o);if(a instanceof Promise){if(o.async===!1)throw new Mc;return a.then(c=>s(c,n,o))}return s(a,n,o)}}t["~standard"]={validate:s=>{try{let i=Nf(t,s);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Bf(t,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),w1=K("$ZodString",(t,e)=>{wr.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??MX(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Nr=K("$ZodStringFormat",(t,e)=>{v1.init(t,e),w1.init(t,e)}),yR=K("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=vX),Nr.init(t,e)}),xR=K("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=fR(n))}else e.pattern??(e.pattern=fR());Nr.init(t,e)}),bR=K("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=wX),Nr.init(t,e)}),_R=K("$ZodURL",(t,e)=>{Nr.init(t,e),t._zod.check=r=>{try{let n=r.value,s=new URL(n),i=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:IX.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),vR=K("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=SX()),Nr.init(t,e)}),wR=K("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=bX),Nr.init(t,e)}),SR=K("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=pX),Nr.init(t,e)}),AR=K("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=mX),Nr.init(t,e)}),ER=K("$ZodULID",(t,e)=>{e.pattern??(e.pattern=gX),Nr.init(t,e)}),CR=K("$ZodXID",(t,e)=>{e.pattern??(e.pattern=yX),Nr.init(t,e)}),kR=K("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=xX),Nr.init(t,e)}),hJ=K("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=$X(e)),Nr.init(t,e)}),pJ=K("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=OX),Nr.init(t,e)}),mJ=K("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=BX(e)),Nr.init(t,e)}),gJ=K("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=_X),Nr.init(t,e)}),TR=K("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=AX),Nr.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),IR=K("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=EX),Nr.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),PR=K("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=CX),Nr.init(t,e)}),RR=K("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=kX),Nr.init(t,e),t._zod.check=r=>{let[n,s]=r.value.split("/");try{if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function yJ(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var OR=K("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=TX),Nr.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{yJ(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Yye(t){if(!hR.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return yJ(r)}var NR=K("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=hR),Nr.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Yye(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),BR=K("$ZodE164",(t,e)=>{e.pattern??(e.pattern=PX),Nr.init(t,e)});function Qye(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}var $R=K("$ZodJWT",(t,e)=>{Nr.init(t,e),t._zod.check=r=>{Qye(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var mE=K("$ZodNumber",(t,e)=>{wr.init(t,e),t._zod.pattern=t._zod.bag.pattern??zX,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;let i=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...i?{received:i}:{}}),r}}),MR=K("$ZodNumber",(t,e)=>{VX.init(t,e),mE.init(t,e)}),jR=K("$ZodBoolean",(t,e)=>{wr.init(t,e),t._zod.pattern=LX,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}});var zR=K("$ZodNull",(t,e)=>{wr.init(t,e),t._zod.pattern=DX,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}});var LR=K("$ZodUnknown",(t,e)=>{wr.init(t,e),t._zod.parse=r=>r}),DR=K("$ZodNever",(t,e)=>{wr.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function sJ(t,e,r){t.issues.length&&e.issues.push(...ka(r,t.issues)),e.value[r]=t.value}var UR=K("$ZodArray",(t,e)=>{wr.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);let i=[];for(let o=0;o<s.length;o++){let a=s[o],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(u=>sJ(u,r,o))):sJ(c,r,o)}return i.length?Promise.all(i).then(()=>r):r}});function pE(t,e,r){t.issues.length&&e.issues.push(...ka(r,t.issues)),e.value[r]=t.value}function iJ(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...ka(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var gE=K("$ZodObject",(t,e)=>{wr.init(t,e);let r=g1(()=>{let d=Object.keys(e.shape);for(let p of d)if(!(e.shape[p]instanceof wr))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let f=tR(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});Or(t._zod,"propValues",()=>{let d=e.shape,f={};for(let p in d){let m=d[p]._zod;if(m.values){f[p]??(f[p]=new Set);for(let y of m.values)f[p].add(y)}}return f});let n=d=>{let f=new hE(["shape","payload","ctx"]),p=r.value,m=C=>{let E=Rf(C);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};f.write("const input = payload.value;");let y=Object.create(null),_=0;for(let C of p.keys)y[C]=`key_${_++}`;f.write("const newResult = {}");for(let C of p.keys)if(p.optionalKeys.has(C)){let E=y[C];f.write(`const ${E} = ${m(C)};`);let B=Rf(C);f.write(`
|
|
300
|
+
if (${E}.issues.length) {
|
|
301
|
+
if (input[${B}] === undefined) {
|
|
302
|
+
if (${B} in input) {
|
|
303
|
+
newResult[${B}] = undefined;
|
|
132
304
|
}
|
|
133
305
|
} else {
|
|
134
306
|
payload.issues = payload.issues.concat(
|
|
135
|
-
${
|
|
307
|
+
${E}.issues.map((iss) => ({
|
|
136
308
|
...iss,
|
|
137
|
-
path: iss.path ? [${
|
|
309
|
+
path: iss.path ? [${B}, ...iss.path] : [${B}],
|
|
138
310
|
}))
|
|
139
311
|
);
|
|
140
312
|
}
|
|
141
|
-
} else if (${
|
|
142
|
-
if (${
|
|
313
|
+
} else if (${E}.value === undefined) {
|
|
314
|
+
if (${B} in input) newResult[${B}] = undefined;
|
|
143
315
|
} else {
|
|
144
|
-
newResult[${
|
|
316
|
+
newResult[${B}] = ${E}.value;
|
|
145
317
|
}
|
|
146
|
-
`)}else{let
|
|
147
|
-
if (${
|
|
318
|
+
`)}else{let E=y[C];f.write(`const ${E} = ${m(C)};`),f.write(`
|
|
319
|
+
if (${E}.issues.length) payload.issues = payload.issues.concat(${E}.issues.map(iss => ({
|
|
148
320
|
...iss,
|
|
149
|
-
path: iss.path ? [${
|
|
150
|
-
})));`),f.write(`newResult[${kr(v)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(v,x)=>w(d,v,x)},o,s=Yr,i=!ts.jitless,c=i&&ma.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let p=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),d=o(d,f);else{d.value={};let x=l.shape;for(let T of l.keys){let N=x[T],he=N._zod.run({value:m[T],issues:[]},f),He=N._zod.optin==="optional"&&N._zod.optout==="optional";he instanceof Promise?p.push(he.then(ye=>He?Pf(ye,d,T,m):cs(ye,d,T))):He?Pf(he,d,T,m):cs(he,d,T)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let h=[],g=l.keySet,w=u._zod,v=w.def.type;for(let x of Object.keys(m)){if(g.has(x))continue;if(v==="never"){h.push(x);continue}let T=w.run({value:m[x],issues:[]},f);T instanceof Promise?p.push(T.then(N=>cs(N,d,x))):cs(T,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function Of(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>it(s,n,Be())))}),e}var ds=_("$ZodUnion",(t,e)=>{ee.init(t,e),ne(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ne(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ne(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ne(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Fn(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Of(i,r,t,n)):Of(s,r,t,n)}}),nc=_("$ZodDiscriminatedUnion",(t,e)=>{ds.init(t,e);let r=t._zod.parse;ne(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=qn(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Yr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),oc=_("$ZodIntersection",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Ef(r,c,u)):Ef(r,s,i)}});function Ia(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Qr(t)&&Qr(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Ia(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Ia(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Ef(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Sr(t))return t;let n=Ia(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var sc=_("$ZodRecord",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Qr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...yt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...yt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>it(u,n,Be())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...yt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...yt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var ic=_("$ZodEnum",(t,e)=>{ee.init(t,e);let r=Ln(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>ha.has(typeof n)).map(n=>typeof n=="string"?qt(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),ac=_("$ZodLiteral",(t,e)=>{ee.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?qt(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var cc=_("$ZodTransform",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ot;return r.value=o,r}}),uc=_("$ZodOptional",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ne(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ne(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Fn(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),lc=_("$ZodNullable",(t,e)=>{ee.init(t,e),ne(t._zod,"optin",()=>e.innerType._zod.optin),ne(t._zod,"optout",()=>e.innerType._zod.optout),ne(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Fn(r.source)}|null)$`):void 0}),ne(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),dc=_("$ZodDefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",ne(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>If(s,e)):If(o,e)}});function If(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var pc=_("$ZodPrefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",ne(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),fc=_("$ZodNonOptional",(t,e)=>{ee.init(t,e),ne(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Rf(s,t)):Rf(o,t)}});function Rf(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var mc=_("$ZodCatch",(t,e)=>{ee.init(t,e),t._zod.optin="optional",ne(t._zod,"optout",()=>e.innerType._zod.optout),ne(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>it(i,n,Be()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>it(s,n,Be()))},input:r.value}),r.issues=[]),r)}});var hc=_("$ZodPipe",(t,e)=>{ee.init(t,e),ne(t._zod,"values",()=>e.in._zod.values),ne(t._zod,"optin",()=>e.in._zod.optin),ne(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>jf(s,e,n)):jf(o,e,n)}});function jf(t,e,r){return Sr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var gc=_("$ZodReadonly",(t,e)=>{ee.init(t,e),ne(t._zod,"propValues",()=>e.innerType._zod.propValues),ne(t._zod,"values",()=>e.innerType._zod.values),ne(t._zod,"optin",()=>e.innerType._zod.optin),ne(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Nf):Nf(o)}});function Nf(t){return t.value=Object.freeze(t.value),t}var yc=_("$ZodCustom",(t,e)=>{be.init(t,e),ee.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Cf(s,r,n,t));Cf(o,r,n,t)}});function Cf(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(_a(o))}}var $w=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},kw=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${$w(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${os(n.values[0])}`:`Invalid option: expected one of ${rs(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${rs(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function qf(){return{localeError:kw()}}var Xn=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function Uf(){return new Xn}var Ut=Uf();function _c(t,e){return new t({type:"string",...Z(e)})}function vc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Z(e)})}function ps(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Z(e)})}function xc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Z(e)})}function wc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Z(e)})}function bc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Z(e)})}function $c(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Z(e)})}function kc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Z(e)})}function Sc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Z(e)})}function zc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Z(e)})}function Tc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Z(e)})}function Pc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Z(e)})}function Oc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Z(e)})}function Ec(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Z(e)})}function Ic(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Z(e)})}function Rc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Z(e)})}function jc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Z(e)})}function Nc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Z(e)})}function Cc(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Z(e)})}function Zc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Z(e)})}function Ac(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Z(e)})}function Mc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Z(e)})}function Dc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Z(e)})}function Ff(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Z(e)})}function Vf(t,e){return new t({type:"string",format:"date",check:"string_format",...Z(e)})}function Hf(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Z(e)})}function Kf(t,e){return new t({type:"string",format:"duration",check:"string_format",...Z(e)})}function Lc(t,e){return new t({type:"number",checks:[],...Z(e)})}function qc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Z(e)})}function Uc(t,e){return new t({type:"boolean",...Z(e)})}function Fc(t,e){return new t({type:"null",...Z(e)})}function Vc(t){return new t({type:"unknown"})}function Hc(t,e){return new t({type:"never",...Z(e)})}function fs(t,e){return new Oa({check:"less_than",...Z(e),value:t,inclusive:!1})}function Jn(t,e){return new Oa({check:"less_than",...Z(e),value:t,inclusive:!0})}function ms(t,e){return new Ea({check:"greater_than",...Z(e),value:t,inclusive:!1})}function Gn(t,e){return new Ea({check:"greater_than",...Z(e),value:t,inclusive:!0})}function hs(t,e){return new ff({check:"multiple_of",...Z(e),value:t})}function gs(t,e){return new hf({check:"max_length",...Z(e),maximum:t})}function en(t,e){return new gf({check:"min_length",...Z(e),minimum:t})}function ys(t,e){return new yf({check:"length_equals",...Z(e),length:t})}function Kc(t,e){return new _f({check:"string_format",format:"regex",...Z(e),pattern:t})}function Bc(t){return new vf({check:"string_format",format:"lowercase",...Z(t)})}function Xc(t){return new xf({check:"string_format",format:"uppercase",...Z(t)})}function Jc(t,e){return new wf({check:"string_format",format:"includes",...Z(e),includes:t})}function Gc(t,e){return new bf({check:"string_format",format:"starts_with",...Z(e),prefix:t})}function Wc(t,e){return new $f({check:"string_format",format:"ends_with",...Z(e),suffix:t})}function Pr(t){return new kf({check:"overwrite",tx:t})}function Yc(t){return Pr(e=>e.normalize(t))}function Qc(){return Pr(t=>t.trim())}function eu(){return Pr(t=>t.toLowerCase())}function tu(){return Pr(t=>t.toUpperCase())}function Bf(t,e,r){return new t({type:"array",element:e,...Z(r)})}function ru(t,e,r){let n=Z(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function nu(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Z(r)})}var _s=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ut,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let p=m;p.type="string";let{minimum:h,maximum:g,format:w,patterns:v,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),w&&(p.format=s[w]??w,p.format===""&&delete p.format),x&&(p.contentEncoding=x),v&&v.size>0){let T=[...v];T.length===1?p.pattern=T[0].source:T.length>1&&(a.schema.allOf=[...T.map(N=>({...this.target==="draft-7"?{type:"string"}:{},pattern:N.source}))])}break}case"number":{let p=m,{minimum:h,maximum:g,format:w,multipleOf:v,exclusiveMaximum:x,exclusiveMinimum:T}=e._zod.bag;typeof w=="string"&&w.includes("int")?p.type="integer":p.type="number",typeof T=="number"&&(p.exclusiveMinimum=T),typeof h=="number"&&(p.minimum=h,typeof T=="number"&&(T>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof x=="number"&&(p.exclusiveMaximum=x),typeof g=="number"&&(p.maximum=g,typeof x=="number"&&(x<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{let p=m;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=m,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=m;p.type="object",p.properties={};let h=o.shape;for(let v in h)p.properties[v]=this.process(h[v],{...d,path:[...d.path,"properties",v]});let g=new Set(Object.keys(h)),w=new Set([...g].filter(v=>{let x=o.shape[v]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));w.size>0&&(p.required=Array.from(w)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=m;p.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=m,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),w=x=>"allOf"in x&&Object.keys(x).length===1,v=[...w(h)?h.allOf:[h],...w(g)?g.allOf:[g]];p.allOf=v;break}case"tuple":{let p=m;p.type="array";let h=o.items.map((v,x)=>this.process(v,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let v=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=v:p.additionalItems=v}o.rest&&(p.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:w}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof w=="number"&&(p.maxItems=w);break}case"record":{let p=m;p.type="object",p.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=m,h=Ln(o.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=m,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:w,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),w!==void 0&&(h.maxLength=w),v?v.length===1?(h.contentMediaType=v[0],Object.assign(p,h)):p.anyOf=v.map(x=>({...h,contentMediaType:x})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,d);m.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let p=m;p.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,d),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&_e(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let w=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=w,{defId:w,ref:`${g("__shared")}#/${d}/${w}`}}if(l[1]===o)return{ref:"#"};let m=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:m+p}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:f,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let p=d.schema;for(let h in p)delete p[h];p.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
321
|
+
path: iss.path ? [${Rf(C)}, ...iss.path] : [${Rf(C)}]
|
|
322
|
+
})));`),f.write(`newResult[${Rf(C)}] = ${E}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let S=f.compile();return(C,E)=>S(d,C,E)},s,i=q0,o=!aE.jitless,c=o&&Q5.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let m=[];if(o&&c&&f?.async===!1&&f.jitless!==!0)s||(s=n(e.shape)),d=s(d,f);else{d.value={};let E=l.shape;for(let B of l.keys){let G=E[B],se=G._zod.run({value:p[B],issues:[]},f),_e=G._zod.optin==="optional"&&G._zod.optout==="optional";se instanceof Promise?m.push(se.then(he=>_e?iJ(he,d,B,p):pE(he,d,B))):_e?iJ(se,d,B,p):pE(se,d,B)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let y=[],_=l.keySet,S=u._zod,C=S.def.type;for(let E of Object.keys(p)){if(_.has(E))continue;if(C==="never"){y.push(E);continue}let B=S.run({value:p[E],issues:[]},f);B instanceof Promise?m.push(B.then(G=>pE(G,d,E))):pE(B,d,E)}return y.length&&d.issues.push({code:"unrecognized_keys",keys:y,input:p,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function oJ(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>Co(i,n,mi())))}),e}var yE=K("$ZodUnion",(t,e)=>{wr.init(t,e),Or(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Or(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Or(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Or(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>x1(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,i=[];for(let o of e.options){let a=o._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),s=!0;else{if(a.issues.length===0)return a;i.push(a)}}return s?Promise.all(i).then(o=>oJ(o,r,t,n)):oJ(i,r,t,n)}}),qR=K("$ZodDiscriminatedUnion",(t,e)=>{yE.init(t,e);let r=t._zod.parse;Or(t._zod,"propValues",()=>{let s={};for(let i of e.options){let o=i._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,c]of Object.entries(o)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=g1(()=>{let s=e.options,i=new Map;for(let o of s){let a=o._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,o)}}return i});t._zod.parse=(s,i)=>{let o=s.value;if(!q0(o))return s.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),s;let a=n.value.get(o?.[e.discriminator]);return a?a._zod.run(s,i):e.unionFallback?r(s,i):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),s)}}),HR=K("$ZodIntersection",(t,e)=>{wr.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,i=e.left._zod.run({value:s,issues:[]},n),o=e.right._zod.run({value:s,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([c,u])=>aJ(r,c,u)):aJ(r,i,o)}});function gR(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(H0(t)&&H0(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),s={...t,...e};for(let i of n){let o=gR(t[i],e[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};s[i]=o.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let s=t[n],i=e[n],o=gR(s,i);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function aJ(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Of(t))return t;let n=gR(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var FR=K("$ZodRecord",(t,e)=>{wr.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!H0(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let i=[];if(e.keyType._zod.values){let o=e.keyType._zod.values;r.value={};for(let c of o)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:s[c],issues:[]},n);u instanceof Promise?i.push(u.then(l=>{l.issues.length&&r.issues.push(...ka(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...ka(c,u.issues)),r.value[c]=u.value)}let a;for(let c in s)o.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let o of Reflect.ownKeys(s)){if(o==="__proto__")continue;let a=e.keyType._zod.run({value:o,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>Co(u,n,mi())),input:o,path:[o],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[o],issues:[]},n);c instanceof Promise?i.push(c.then(u=>{u.issues.length&&r.issues.push(...ka(o,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...ka(o,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var VR=K("$ZodEnum",(t,e)=>{wr.init(t,e);let r=m1(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>eR.has(typeof n)).map(n=>typeof n=="string"?Yu(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:t}),n}}),KR=K("$ZodLiteral",(t,e)=>{wr.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Yu(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var ZR=K("$ZodTransform",(t,e)=>{wr.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(o=>(r.value=o,r));if(s instanceof Promise)throw new Mc;return r.value=s,r}}),GR=K("$ZodOptional",(t,e)=>{wr.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Or(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Or(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${x1(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),WR=K("$ZodNullable",(t,e)=>{wr.init(t,e),Or(t._zod,"optin",()=>e.innerType._zod.optin),Or(t._zod,"optout",()=>e.innerType._zod.optout),Or(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${x1(r.source)}|null)$`):void 0}),Or(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),XR=K("$ZodDefault",(t,e)=>{wr.init(t,e),t._zod.optin="optional",Or(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>cJ(i,e)):cJ(s,e)}});function cJ(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var JR=K("$ZodPrefault",(t,e)=>{wr.init(t,e),t._zod.optin="optional",Or(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),YR=K("$ZodNonOptional",(t,e)=>{wr.init(t,e),Or(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>uJ(i,t)):uJ(s,t)}});function uJ(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var QR=K("$ZodCatch",(t,e)=>{wr.init(t,e),t._zod.optin="optional",Or(t._zod,"optout",()=>e.innerType._zod.optout),Or(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(o=>Co(o,n,mi()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Co(i,n,mi()))},input:r.value}),r.issues=[]),r)}});var eO=K("$ZodPipe",(t,e)=>{wr.init(t,e),Or(t._zod,"values",()=>e.in._zod.values),Or(t._zod,"optin",()=>e.in._zod.optin),Or(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(i=>lJ(i,e,n)):lJ(s,e,n)}});function lJ(t,e,r){return Of(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var tO=K("$ZodReadonly",(t,e)=>{wr.init(t,e),Or(t._zod,"propValues",()=>e.innerType._zod.propValues),Or(t._zod,"values",()=>e.innerType._zod.values),Or(t._zod,"optin",()=>e.innerType._zod.optin),Or(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(dJ):dJ(s)}});function dJ(t){return t.value=Object.freeze(t.value),t}var rO=K("$ZodCustom",(t,e)=>{Gn.init(t,e),wr.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(i=>fJ(i,r,n,t));fJ(s,r,n,t)}});function fJ(t,e,r,n){if(!t){let s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(nR(s))}}var exe=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},txe=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${exe(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${lE(n.values[0])}`:`Invalid option: expected one of ${cE(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=e(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",i=e(n.origin);return i?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${cE(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function xJ(){return{localeError:txe()}}var S1=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function bJ(){return new S1}var Qu=bJ();function nO(t,e){return new t({type:"string",...it(e)})}function sO(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...it(e)})}function xE(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...it(e)})}function iO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...it(e)})}function oO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...it(e)})}function aO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...it(e)})}function cO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...it(e)})}function uO(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...it(e)})}function lO(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...it(e)})}function dO(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...it(e)})}function fO(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...it(e)})}function hO(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...it(e)})}function pO(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...it(e)})}function mO(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...it(e)})}function gO(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...it(e)})}function yO(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...it(e)})}function xO(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...it(e)})}function bO(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...it(e)})}function _O(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...it(e)})}function vO(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...it(e)})}function wO(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...it(e)})}function SO(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...it(e)})}function AO(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...it(e)})}function _J(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...it(e)})}function vJ(t,e){return new t({type:"string",format:"date",check:"string_format",...it(e)})}function wJ(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...it(e)})}function SJ(t,e){return new t({type:"string",format:"duration",check:"string_format",...it(e)})}function EO(t,e){return new t({type:"number",checks:[],...it(e)})}function CO(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...it(e)})}function kO(t,e){return new t({type:"boolean",...it(e)})}function TO(t,e){return new t({type:"null",...it(e)})}function IO(t){return new t({type:"unknown"})}function PO(t,e){return new t({type:"never",...it(e)})}function bE(t,e){return new pR({check:"less_than",...it(e),value:t,inclusive:!1})}function A1(t,e){return new pR({check:"less_than",...it(e),value:t,inclusive:!0})}function _E(t,e){return new mR({check:"greater_than",...it(e),value:t,inclusive:!1})}function E1(t,e){return new mR({check:"greater_than",...it(e),value:t,inclusive:!0})}function vE(t,e){return new FX({check:"multiple_of",...it(e),value:t})}function wE(t,e){return new KX({check:"max_length",...it(e),maximum:t})}function F0(t,e){return new ZX({check:"min_length",...it(e),minimum:t})}function SE(t,e){return new GX({check:"length_equals",...it(e),length:t})}function RO(t,e){return new WX({check:"string_format",format:"regex",...it(e),pattern:t})}function OO(t){return new XX({check:"string_format",format:"lowercase",...it(t)})}function NO(t){return new JX({check:"string_format",format:"uppercase",...it(t)})}function BO(t,e){return new YX({check:"string_format",format:"includes",...it(e),includes:t})}function $O(t,e){return new QX({check:"string_format",format:"starts_with",...it(e),prefix:t})}function MO(t,e){return new eJ({check:"string_format",format:"ends_with",...it(e),suffix:t})}function $f(t){return new tJ({check:"overwrite",tx:t})}function jO(t){return $f(e=>e.normalize(t))}function zO(){return $f(t=>t.trim())}function LO(){return $f(t=>t.toLowerCase())}function DO(){return $f(t=>t.toUpperCase())}function AJ(t,e,r){return new t({type:"array",element:e,...it(r)})}function UO(t,e,r){let n=it(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function qO(t,e,r){return new t({type:"custom",check:"custom",fn:e,...it(r)})}var AE=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Qu,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let p=a.schema;switch(s.type){case"string":{let m=p;m.type="string";let{minimum:y,maximum:_,format:S,patterns:C,contentEncoding:E}=e._zod.bag;if(typeof y=="number"&&(m.minLength=y),typeof _=="number"&&(m.maxLength=_),S&&(m.format=i[S]??S,m.format===""&&delete m.format),E&&(m.contentEncoding=E),C&&C.size>0){let B=[...C];B.length===1?m.pattern=B[0].source:B.length>1&&(a.schema.allOf=[...B.map(G=>({...this.target==="draft-7"?{type:"string"}:{},pattern:G.source}))])}break}case"number":{let m=p,{minimum:y,maximum:_,format:S,multipleOf:C,exclusiveMaximum:E,exclusiveMinimum:B}=e._zod.bag;typeof S=="string"&&S.includes("int")?m.type="integer":m.type="number",typeof B=="number"&&(m.exclusiveMinimum=B),typeof y=="number"&&(m.minimum=y,typeof B=="number"&&(B>=y?delete m.minimum:delete m.exclusiveMinimum)),typeof E=="number"&&(m.exclusiveMaximum=E),typeof _=="number"&&(m.maximum=_,typeof E=="number"&&(E<=_?delete m.maximum:delete m.exclusiveMaximum)),typeof C=="number"&&(m.multipleOf=C);break}case"boolean":{let m=p;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{p.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=p,{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(m.minItems=y),typeof _=="number"&&(m.maxItems=_),m.type="array",m.items=this.process(s.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=p;m.type="object",m.properties={};let y=s.shape;for(let C in y)m.properties[C]=this.process(y[C],{...d,path:[...d.path,"properties",C]});let _=new Set(Object.keys(y)),S=new Set([..._].filter(C=>{let E=s.shape[C]._zod;return this.io==="input"?E.optin===void 0:E.optout===void 0}));S.size>0&&(m.required=Array.from(S)),s.catchall?._zod.def.type==="never"?m.additionalProperties=!1:s.catchall?s.catchall&&(m.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=p;m.anyOf=s.options.map((y,_)=>this.process(y,{...d,path:[...d.path,"anyOf",_]}));break}case"intersection":{let m=p,y=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),_=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),S=E=>"allOf"in E&&Object.keys(E).length===1,C=[...S(y)?y.allOf:[y],...S(_)?_.allOf:[_]];m.allOf=C;break}case"tuple":{let m=p;m.type="array";let y=s.items.map((C,E)=>this.process(C,{...d,path:[...d.path,"prefixItems",E]}));if(this.target==="draft-2020-12"?m.prefixItems=y:m.items=y,s.rest){let C=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=C:m.additionalItems=C}s.rest&&(m.items=this.process(s.rest,{...d,path:[...d.path,"items"]}));let{minimum:_,maximum:S}=e._zod.bag;typeof _=="number"&&(m.minItems=_),typeof S=="number"&&(m.maxItems=S);break}case"record":{let m=p;m.type="object",m.propertyNames=this.process(s.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(s.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=p,y=m1(s.entries);y.every(_=>typeof _=="number")&&(m.type="number"),y.every(_=>typeof _=="string")&&(m.type="string"),m.enum=y;break}case"literal":{let m=p,y=[];for(let _ of s.values)if(_===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof _=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");y.push(Number(_))}else y.push(_);if(y.length!==0)if(y.length===1){let _=y[0];m.type=_===null?"null":typeof _,m.const=_}else y.every(_=>typeof _=="number")&&(m.type="number"),y.every(_=>typeof _=="string")&&(m.type="string"),y.every(_=>typeof _=="boolean")&&(m.type="string"),y.every(_=>_===null)&&(m.type="null"),m.enum=y;break}case"file":{let m=p,y={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:S,mime:C}=e._zod.bag;_!==void 0&&(y.minLength=_),S!==void 0&&(y.maxLength=S),C?C.length===1?(y.contentMediaType=C[0],Object.assign(m,y)):m.anyOf=C.map(E=>({...y,contentMediaType:E})):Object.assign(m,y);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(s.innerType,d);p.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),a.ref=s.innerType;break}case"success":{let m=p;m.type="boolean";break}case"default":{this.process(s.innerType,d),a.ref=s.innerType,p.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),a.ref=s.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),a.ref=s.innerType;let m;try{m=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=p,y=e._zod.pattern;if(!y)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=y.source;break}case"pipe":{let m=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(s.innerType,d),a.ref=s.innerType,p.readOnly=!0;break}case"promise":{this.process(s.innerType,d),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,d),a.ref=s.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,d),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&In(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let y=n.external.registry.get(l[0])?.id,_=n.external.uri??(C=>C);if(y)return{ref:_(y)};let S=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=S,{defId:S,ref:`${_("__shared")}#/${d}/${S}`}}if(l[1]===s)return{ref:"#"};let p=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:p+m}},o=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:f,defId:p}=i(l);d.def={...d.schema},p&&(d.defId=p);let m=d.schema;for(let y in m)delete m[y];m.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
151
323
|
|
|
152
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let m=n.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let f=this.seen.get(l),m=f.def??f.schema,p={...m};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(g)):(Object.assign(m,g),Object.assign(m,p))}f.isParent||this.override({zodSchema:l,jsonSchema:m,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function ou(t,e){if(t instanceof Xn){let n=new _s(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new _s(e);return r.process(t),r.emit(t,e)}function _e(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return _e(o.element,r);case"object":{for(let s in o.shape)if(_e(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(_e(s,r))return!0;return!1}case"intersection":return _e(o.left,r)||_e(o.right,r);case"tuple":{for(let s of o.items)if(_e(s,r))return!0;return!!(o.rest&&_e(o.rest,r))}case"record":return _e(o.keyType,r)||_e(o.valueType,r);case"map":return _e(o.keyType,r)||_e(o.valueType,r);case"set":return _e(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return _e(o.innerType,r);case"lazy":return _e(o.getter(),r);case"default":return _e(o.innerType,r);case"prefault":return _e(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return _e(o.in,r)||_e(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var sb=_("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ee.init(t,e),t.def=e,t.parse=(r,n)=>ba(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>zr(t,r,n),t.parseAsync=async(r,n)=>ka(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Tr(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Xe(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var ib=_("ZodMiniObject",(t,e)=>{ls.init(t,e),sb.init(t,e),K.defineLazy(t,"shape",()=>e.shape)});function su(t,e){let r={type:"object",get shape(){return K.assignProp(this,"shape",{...t}),this.shape},...K.normalizeParams(e)};return new ib(r)}function Ye(t){return!!t._zod}function Er(t){let e=Object.values(t);if(e.length===0)return su({});let r=e.every(Ye),n=e.every(o=>!Ye(o));if(r)return su(t);if(n)return ca(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ft(t,e){return Ye(t)?zr(t,e):t.safeParse(e)}async function vs(t,e){return Ye(t)?await Tr(t,e):await t.safeParseAsync(e)}function Vt(t){if(!t)return;let e;if(Ye(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function tn(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Er(t)}}if(Ye(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function xs(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Jf(t){return t.description}function Gf(t){if(Ye(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function ws(t){if(Ye(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Wn={};qo(Wn,{ZodISODate:()=>Yf,ZodISODateTime:()=>Wf,ZodISODuration:()=>em,ZodISOTime:()=>Qf,date:()=>au,datetime:()=>iu,duration:()=>uu,time:()=>cu});var Wf=_("ZodISODateTime",(t,e)=>{Zf.init(t,e),ue.init(t,e)});function iu(t){return Ff(Wf,t)}var Yf=_("ZodISODate",(t,e)=>{Af.init(t,e),ue.init(t,e)});function au(t){return Vf(Yf,t)}var Qf=_("ZodISOTime",(t,e)=>{Mf.init(t,e),ue.init(t,e)});function cu(t){return Hf(Qf,t)}var em=_("ZodISODuration",(t,e)=>{Df.init(t,e),ue.init(t,e)});function uu(t){return Kf(em,t)}var tm=(t,e)=>{ss.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>xa(t,r)},flatten:{value:r=>va(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},ER=_("ZodError",tm),Yn=_("ZodError",tm,{Parent:Error});var rm=wa(Yn),nm=$a(Yn),om=Sa(Yn),sm=za(Yn);var me=_("ZodType",(t,e)=>(ee.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Xe(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>rm(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>om(t,r,n),t.parseAsync=async(r,n)=>nm(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>sm(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(n$(r,n)),t.superRefine=r=>t.check(o$(r)),t.overwrite=r=>t.check(Pr(r)),t.optional=()=>de(t),t.nullable=()=>cm(t),t.nullish=()=>de(cm(t)),t.nonoptional=r=>Gb(t,r),t.array=()=>B(t),t.or=r=>ie([t,r]),t.and=r=>$s(t,r),t.transform=r=>du(t,mm(r)),t.default=r=>Bb(t,r),t.prefault=r=>Jb(t,r),t.catch=r=>Yb(t,r),t.pipe=r=>du(t,r),t.readonly=()=>t$(t),t.describe=r=>{let n=t.clone();return Ut.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Ut.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Ut.get(t);let n=t.clone();return Ut.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),um=_("_ZodString",(t,e)=>{Bn.init(t,e),me.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Kc(...n)),t.includes=(...n)=>t.check(Jc(...n)),t.startsWith=(...n)=>t.check(Gc(...n)),t.endsWith=(...n)=>t.check(Wc(...n)),t.min=(...n)=>t.check(en(...n)),t.max=(...n)=>t.check(gs(...n)),t.length=(...n)=>t.check(ys(...n)),t.nonempty=(...n)=>t.check(en(1,...n)),t.lowercase=n=>t.check(Bc(n)),t.uppercase=n=>t.check(Xc(n)),t.trim=()=>t.check(Qc()),t.normalize=(...n)=>t.check(Yc(...n)),t.toLowerCase=()=>t.check(eu()),t.toUpperCase=()=>t.check(tu())}),hb=_("ZodString",(t,e)=>{Bn.init(t,e),um.init(t,e),t.email=r=>t.check(vc(gb,r)),t.url=r=>t.check(kc(yb,r)),t.jwt=r=>t.check(Dc(Rb,r)),t.emoji=r=>t.check(Sc(_b,r)),t.guid=r=>t.check(ps(im,r)),t.uuid=r=>t.check(xc(bs,r)),t.uuidv4=r=>t.check(wc(bs,r)),t.uuidv6=r=>t.check(bc(bs,r)),t.uuidv7=r=>t.check($c(bs,r)),t.nanoid=r=>t.check(zc(vb,r)),t.guid=r=>t.check(ps(im,r)),t.cuid=r=>t.check(Tc(xb,r)),t.cuid2=r=>t.check(Pc(wb,r)),t.ulid=r=>t.check(Oc(bb,r)),t.base64=r=>t.check(Zc(Ob,r)),t.base64url=r=>t.check(Ac(Eb,r)),t.xid=r=>t.check(Ec($b,r)),t.ksuid=r=>t.check(Ic(kb,r)),t.ipv4=r=>t.check(Rc(Sb,r)),t.ipv6=r=>t.check(jc(zb,r)),t.cidrv4=r=>t.check(Nc(Tb,r)),t.cidrv6=r=>t.check(Cc(Pb,r)),t.e164=r=>t.check(Mc(Ib,r)),t.datetime=r=>t.check(iu(r)),t.date=r=>t.check(au(r)),t.time=r=>t.check(cu(r)),t.duration=r=>t.check(uu(r))});function y(t){return _c(hb,t)}var ue=_("ZodStringFormat",(t,e)=>{oe.init(t,e),um.init(t,e)}),gb=_("ZodEmail",(t,e)=>{Na.init(t,e),ue.init(t,e)});var im=_("ZodGUID",(t,e)=>{Ra.init(t,e),ue.init(t,e)});var bs=_("ZodUUID",(t,e)=>{ja.init(t,e),ue.init(t,e)});var yb=_("ZodURL",(t,e)=>{Ca.init(t,e),ue.init(t,e)});var _b=_("ZodEmoji",(t,e)=>{Za.init(t,e),ue.init(t,e)});var vb=_("ZodNanoID",(t,e)=>{Aa.init(t,e),ue.init(t,e)});var xb=_("ZodCUID",(t,e)=>{Ma.init(t,e),ue.init(t,e)});var wb=_("ZodCUID2",(t,e)=>{Da.init(t,e),ue.init(t,e)});var bb=_("ZodULID",(t,e)=>{La.init(t,e),ue.init(t,e)});var $b=_("ZodXID",(t,e)=>{qa.init(t,e),ue.init(t,e)});var kb=_("ZodKSUID",(t,e)=>{Ua.init(t,e),ue.init(t,e)});var Sb=_("ZodIPv4",(t,e)=>{Fa.init(t,e),ue.init(t,e)});var zb=_("ZodIPv6",(t,e)=>{Va.init(t,e),ue.init(t,e)});var Tb=_("ZodCIDRv4",(t,e)=>{Ha.init(t,e),ue.init(t,e)});var Pb=_("ZodCIDRv6",(t,e)=>{Ka.init(t,e),ue.init(t,e)});var Ob=_("ZodBase64",(t,e)=>{Ba.init(t,e),ue.init(t,e)});var Eb=_("ZodBase64URL",(t,e)=>{Xa.init(t,e),ue.init(t,e)});var Ib=_("ZodE164",(t,e)=>{Ja.init(t,e),ue.init(t,e)});var Rb=_("ZodJWT",(t,e)=>{Ga.init(t,e),ue.init(t,e)});var lm=_("ZodNumber",(t,e)=>{us.init(t,e),me.init(t,e),t.gt=(n,o)=>t.check(ms(n,o)),t.gte=(n,o)=>t.check(Gn(n,o)),t.min=(n,o)=>t.check(Gn(n,o)),t.lt=(n,o)=>t.check(fs(n,o)),t.lte=(n,o)=>t.check(Jn(n,o)),t.max=(n,o)=>t.check(Jn(n,o)),t.int=n=>t.check(am(n)),t.safe=n=>t.check(am(n)),t.positive=n=>t.check(ms(0,n)),t.nonnegative=n=>t.check(Gn(0,n)),t.negative=n=>t.check(fs(0,n)),t.nonpositive=n=>t.check(Jn(0,n)),t.multipleOf=(n,o)=>t.check(hs(n,o)),t.step=(n,o)=>t.check(hs(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function Q(t){return Lc(lm,t)}var jb=_("ZodNumberFormat",(t,e)=>{Wa.init(t,e),lm.init(t,e)});function am(t){return qc(jb,t)}var Nb=_("ZodBoolean",(t,e)=>{Ya.init(t,e),me.init(t,e)});function xe(t){return Uc(Nb,t)}var Cb=_("ZodNull",(t,e)=>{Qa.init(t,e),me.init(t,e)});function dm(t){return Fc(Cb,t)}var Zb=_("ZodUnknown",(t,e)=>{ec.init(t,e),me.init(t,e)});function le(){return Vc(Zb)}var Ab=_("ZodNever",(t,e)=>{tc.init(t,e),me.init(t,e)});function Mb(t){return Hc(Ab,t)}var Db=_("ZodArray",(t,e)=>{rc.init(t,e),me.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(en(r,n)),t.nonempty=r=>t.check(en(1,r)),t.max=(r,n)=>t.check(gs(r,n)),t.length=(r,n)=>t.check(ys(r,n)),t.unwrap=()=>t.element});function B(t,e){return Bf(Db,t,e)}var pm=_("ZodObject",(t,e)=>{ls.init(t,e),me.init(t,e),K.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Le(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:le()}),t.loose=()=>t.clone({...t._zod.def,catchall:le()}),t.strict=()=>t.clone({...t._zod.def,catchall:Mb()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>K.extend(t,r),t.merge=r=>K.merge(t,r),t.pick=r=>K.pick(t,r),t.omit=r=>K.omit(t,r),t.partial=(...r)=>K.partial(hm,t,r[0]),t.required=(...r)=>K.required(gm,t,r[0])});function P(t,e){let r={type:"object",get shape(){return K.assignProp(this,"shape",{...t}),this.shape},...K.normalizeParams(e)};return new pm(r)}function Re(t,e){return new pm({type:"object",get shape(){return K.assignProp(this,"shape",{...t}),this.shape},catchall:le(),...K.normalizeParams(e)})}var fm=_("ZodUnion",(t,e)=>{ds.init(t,e),me.init(t,e),t.options=e.options});function ie(t,e){return new fm({type:"union",options:t,...K.normalizeParams(e)})}var Lb=_("ZodDiscriminatedUnion",(t,e)=>{fm.init(t,e),nc.init(t,e)});function pu(t,e,r){return new Lb({type:"union",options:e,discriminator:t,...K.normalizeParams(r)})}var qb=_("ZodIntersection",(t,e)=>{oc.init(t,e),me.init(t,e)});function $s(t,e){return new qb({type:"intersection",left:t,right:e})}var Ub=_("ZodRecord",(t,e)=>{sc.init(t,e),me.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function se(t,e,r){return new Ub({type:"record",keyType:t,valueType:e,...K.normalizeParams(r)})}var lu=_("ZodEnum",(t,e)=>{ic.init(t,e),me.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new lu({...e,checks:[],...K.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new lu({...e,checks:[],...K.normalizeParams(o),entries:s})}});function Le(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new lu({type:"enum",entries:r,...K.normalizeParams(e)})}var Fb=_("ZodLiteral",(t,e)=>{ac.init(t,e),me.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function I(t,e){return new Fb({type:"literal",values:Array.isArray(t)?t:[t],...K.normalizeParams(e)})}var Vb=_("ZodTransform",(t,e)=>{cc.init(t,e),me.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(K.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(K.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function mm(t){return new Vb({type:"transform",transform:t})}var hm=_("ZodOptional",(t,e)=>{uc.init(t,e),me.init(t,e),t.unwrap=()=>t._zod.def.innerType});function de(t){return new hm({type:"optional",innerType:t})}var Hb=_("ZodNullable",(t,e)=>{lc.init(t,e),me.init(t,e),t.unwrap=()=>t._zod.def.innerType});function cm(t){return new Hb({type:"nullable",innerType:t})}var Kb=_("ZodDefault",(t,e)=>{dc.init(t,e),me.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Bb(t,e){return new Kb({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Xb=_("ZodPrefault",(t,e)=>{pc.init(t,e),me.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Jb(t,e){return new Xb({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var gm=_("ZodNonOptional",(t,e)=>{fc.init(t,e),me.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Gb(t,e){return new gm({type:"nonoptional",innerType:t,...K.normalizeParams(e)})}var Wb=_("ZodCatch",(t,e)=>{mc.init(t,e),me.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Yb(t,e){return new Wb({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Qb=_("ZodPipe",(t,e)=>{hc.init(t,e),me.init(t,e),t.in=e.in,t.out=e.out});function du(t,e){return new Qb({type:"pipe",in:t,out:e})}var e$=_("ZodReadonly",(t,e)=>{gc.init(t,e),me.init(t,e)});function t$(t){return new e$({type:"readonly",innerType:t})}var ym=_("ZodCustom",(t,e)=>{yc.init(t,e),me.init(t,e)});function r$(t){let e=new be({check:"custom"});return e._zod.check=t,e}function _m(t,e){return ru(ym,t??(()=>!0),e)}function n$(t,e={}){return nu(ym,t,e)}function o$(t){let e=r$(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(K.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(K.issue(o))}},t(r.value,r)));return e}function fu(t,e){return du(mm(t),e)}Be(qf());var hu="2025-11-25";var vm=[hu,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ht="io.modelcontextprotocol/related-task",Ss="2.0",ve=_m(t=>t!==null&&(typeof t=="object"||typeof t=="function")),xm=ie([y(),Q().int()]),wm=y(),VR=Re({ttl:Q().optional(),pollInterval:Q().optional()}),s$=P({ttl:Q().optional()}),i$=P({taskId:y()}),gu=Re({progressToken:xm.optional(),[Ht]:i$.optional()}),Je=P({_meta:gu.optional()}),Qn=Je.extend({task:s$.optional()}),bm=t=>Qn.safeParse(t).success,$e=P({method:y(),params:Je.loose().optional()}),Qe=P({_meta:gu.optional()}),et=P({method:y(),params:Qe.loose().optional()}),ke=Re({_meta:gu.optional()}),zs=ie([y(),Q().int()]),$m=P({jsonrpc:I(Ss),id:zs,...$e.shape}).strict(),yu=t=>$m.safeParse(t).success,km=P({jsonrpc:I(Ss),...et.shape}).strict(),Sm=t=>km.safeParse(t).success,_u=P({jsonrpc:I(Ss),id:zs,result:ke}).strict(),eo=t=>_u.safeParse(t).success;var j;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(j||(j={}));var vu=P({jsonrpc:I(Ss),id:zs.optional(),error:P({code:Q().int(),message:y(),data:le().optional()})}).strict();var zm=t=>vu.safeParse(t).success;var Tm=ie([$m,km,_u,vu]),HR=ie([_u,vu]),Ts=ke.strict(),a$=Qe.extend({requestId:zs.optional(),reason:y().optional()}),Ps=et.extend({method:I("notifications/cancelled"),params:a$}),c$=P({src:y(),mimeType:y().optional(),sizes:B(y()).optional(),theme:Le(["light","dark"]).optional()}),to=P({icons:B(c$).optional()}),rn=P({name:y(),title:y().optional()}),Pm=rn.extend({...rn.shape,...to.shape,version:y(),websiteUrl:y().optional(),description:y().optional()}),u$=$s(P({applyDefaults:xe().optional()}),se(y(),le())),l$=fu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,$s(P({form:u$.optional(),url:ve.optional()}),se(y(),le()).optional())),d$=Re({list:ve.optional(),cancel:ve.optional(),requests:Re({sampling:Re({createMessage:ve.optional()}).optional(),elicitation:Re({create:ve.optional()}).optional()}).optional()}),p$=Re({list:ve.optional(),cancel:ve.optional(),requests:Re({tools:Re({call:ve.optional()}).optional()}).optional()}),f$=P({experimental:se(y(),ve).optional(),sampling:P({context:ve.optional(),tools:ve.optional()}).optional(),elicitation:l$.optional(),roots:P({listChanged:xe().optional()}).optional(),tasks:d$.optional(),extensions:se(y(),ve).optional()}),m$=Je.extend({protocolVersion:y(),capabilities:f$,clientInfo:Pm}),xu=$e.extend({method:I("initialize"),params:m$});var h$=P({experimental:se(y(),ve).optional(),logging:ve.optional(),completions:ve.optional(),prompts:P({listChanged:xe().optional()}).optional(),resources:P({subscribe:xe().optional(),listChanged:xe().optional()}).optional(),tools:P({listChanged:xe().optional()}).optional(),tasks:p$.optional(),extensions:se(y(),ve).optional()}),g$=ke.extend({protocolVersion:y(),capabilities:h$,serverInfo:Pm,instructions:y().optional()}),wu=et.extend({method:I("notifications/initialized"),params:Qe.optional()});var Os=$e.extend({method:I("ping"),params:Je.optional()}),y$=P({progress:Q(),total:de(Q()),message:de(y())}),_$=P({...Qe.shape,...y$.shape,progressToken:xm}),Es=et.extend({method:I("notifications/progress"),params:_$}),v$=Je.extend({cursor:wm.optional()}),ro=$e.extend({params:v$.optional()}),no=ke.extend({nextCursor:wm.optional()}),x$=Le(["working","input_required","completed","failed","cancelled"]),oo=P({taskId:y(),status:x$,ttl:ie([Q(),dm()]),createdAt:y(),lastUpdatedAt:y(),pollInterval:de(Q()),statusMessage:de(y())}),nn=ke.extend({task:oo}),w$=Qe.merge(oo),so=et.extend({method:I("notifications/tasks/status"),params:w$}),Is=$e.extend({method:I("tasks/get"),params:Je.extend({taskId:y()})}),Rs=ke.merge(oo),js=$e.extend({method:I("tasks/result"),params:Je.extend({taskId:y()})}),KR=ke.loose(),Ns=ro.extend({method:I("tasks/list")}),Cs=no.extend({tasks:B(oo)}),Zs=$e.extend({method:I("tasks/cancel"),params:Je.extend({taskId:y()})}),Om=ke.merge(oo),Em=P({uri:y(),mimeType:de(y()),_meta:se(y(),le()).optional()}),Im=Em.extend({text:y()}),bu=y().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Rm=Em.extend({blob:bu}),io=Le(["user","assistant"]),on=P({audience:B(io).optional(),priority:Q().min(0).max(1).optional(),lastModified:Wn.datetime({offset:!0}).optional()}),jm=P({...rn.shape,...to.shape,uri:y(),description:de(y()),mimeType:de(y()),size:de(Q()),annotations:on.optional(),_meta:de(Re({}))}),b$=P({...rn.shape,...to.shape,uriTemplate:y(),description:de(y()),mimeType:de(y()),annotations:on.optional(),_meta:de(Re({}))}),As=ro.extend({method:I("resources/list")}),$$=no.extend({resources:B(jm)}),Ms=ro.extend({method:I("resources/templates/list")}),k$=no.extend({resourceTemplates:B(b$)}),$u=Je.extend({uri:y()}),S$=$u,Ds=$e.extend({method:I("resources/read"),params:S$}),z$=ke.extend({contents:B(ie([Im,Rm]))}),T$=et.extend({method:I("notifications/resources/list_changed"),params:Qe.optional()}),P$=$u,O$=$e.extend({method:I("resources/subscribe"),params:P$}),E$=$u,I$=$e.extend({method:I("resources/unsubscribe"),params:E$}),R$=Qe.extend({uri:y()}),j$=et.extend({method:I("notifications/resources/updated"),params:R$}),N$=P({name:y(),description:de(y()),required:de(xe())}),C$=P({...rn.shape,...to.shape,description:de(y()),arguments:de(B(N$)),_meta:de(Re({}))}),Ls=ro.extend({method:I("prompts/list")}),Z$=no.extend({prompts:B(C$)}),A$=Je.extend({name:y(),arguments:se(y(),y()).optional()}),qs=$e.extend({method:I("prompts/get"),params:A$}),ku=P({type:I("text"),text:y(),annotations:on.optional(),_meta:se(y(),le()).optional()}),Su=P({type:I("image"),data:bu,mimeType:y(),annotations:on.optional(),_meta:se(y(),le()).optional()}),zu=P({type:I("audio"),data:bu,mimeType:y(),annotations:on.optional(),_meta:se(y(),le()).optional()}),M$=P({type:I("tool_use"),name:y(),id:y(),input:se(y(),le()),_meta:se(y(),le()).optional()}),D$=P({type:I("resource"),resource:ie([Im,Rm]),annotations:on.optional(),_meta:se(y(),le()).optional()}),L$=jm.extend({type:I("resource_link")}),Tu=ie([ku,Su,zu,L$,D$]),q$=P({role:io,content:Tu}),U$=ke.extend({description:y().optional(),messages:B(q$)}),F$=et.extend({method:I("notifications/prompts/list_changed"),params:Qe.optional()}),V$=P({title:y().optional(),readOnlyHint:xe().optional(),destructiveHint:xe().optional(),idempotentHint:xe().optional(),openWorldHint:xe().optional()}),H$=P({taskSupport:Le(["required","optional","forbidden"]).optional()}),Nm=P({...rn.shape,...to.shape,description:y().optional(),inputSchema:P({type:I("object"),properties:se(y(),ve).optional(),required:B(y()).optional()}).catchall(le()),outputSchema:P({type:I("object"),properties:se(y(),ve).optional(),required:B(y()).optional()}).catchall(le()).optional(),annotations:V$.optional(),execution:H$.optional(),_meta:se(y(),le()).optional()}),Us=ro.extend({method:I("tools/list")}),K$=no.extend({tools:B(Nm)}),Fs=ke.extend({content:B(Tu).default([]),structuredContent:se(y(),le()).optional(),isError:xe().optional()}),BR=Fs.or(ke.extend({toolResult:le()})),B$=Qn.extend({name:y(),arguments:se(y(),le()).optional()}),sn=$e.extend({method:I("tools/call"),params:B$}),X$=et.extend({method:I("notifications/tools/list_changed"),params:Qe.optional()}),XR=P({autoRefresh:xe().default(!0),debounceMs:Q().int().nonnegative().default(300)}),ao=Le(["debug","info","notice","warning","error","critical","alert","emergency"]),J$=Je.extend({level:ao}),Pu=$e.extend({method:I("logging/setLevel"),params:J$}),G$=Qe.extend({level:ao,logger:y().optional(),data:le()}),W$=et.extend({method:I("notifications/message"),params:G$}),Y$=P({name:y().optional()}),Q$=P({hints:B(Y$).optional(),costPriority:Q().min(0).max(1).optional(),speedPriority:Q().min(0).max(1).optional(),intelligencePriority:Q().min(0).max(1).optional()}),e0=P({mode:Le(["auto","required","none"]).optional()}),t0=P({type:I("tool_result"),toolUseId:y().describe("The unique identifier for the corresponding tool call."),content:B(Tu).default([]),structuredContent:P({}).loose().optional(),isError:xe().optional(),_meta:se(y(),le()).optional()}),r0=pu("type",[ku,Su,zu]),ks=pu("type",[ku,Su,zu,M$,t0]),n0=P({role:io,content:ie([ks,B(ks)]),_meta:se(y(),le()).optional()}),o0=Qn.extend({messages:B(n0),modelPreferences:Q$.optional(),systemPrompt:y().optional(),includeContext:Le(["none","thisServer","allServers"]).optional(),temperature:Q().optional(),maxTokens:Q().int(),stopSequences:B(y()).optional(),metadata:ve.optional(),tools:B(Nm).optional(),toolChoice:e0.optional()}),s0=$e.extend({method:I("sampling/createMessage"),params:o0}),co=ke.extend({model:y(),stopReason:de(Le(["endTurn","stopSequence","maxTokens"]).or(y())),role:io,content:r0}),Ou=ke.extend({model:y(),stopReason:de(Le(["endTurn","stopSequence","maxTokens","toolUse"]).or(y())),role:io,content:ie([ks,B(ks)])}),i0=P({type:I("boolean"),title:y().optional(),description:y().optional(),default:xe().optional()}),a0=P({type:I("string"),title:y().optional(),description:y().optional(),minLength:Q().optional(),maxLength:Q().optional(),format:Le(["email","uri","date","date-time"]).optional(),default:y().optional()}),c0=P({type:Le(["number","integer"]),title:y().optional(),description:y().optional(),minimum:Q().optional(),maximum:Q().optional(),default:Q().optional()}),u0=P({type:I("string"),title:y().optional(),description:y().optional(),enum:B(y()),default:y().optional()}),l0=P({type:I("string"),title:y().optional(),description:y().optional(),oneOf:B(P({const:y(),title:y()})),default:y().optional()}),d0=P({type:I("string"),title:y().optional(),description:y().optional(),enum:B(y()),enumNames:B(y()).optional(),default:y().optional()}),p0=ie([u0,l0]),f0=P({type:I("array"),title:y().optional(),description:y().optional(),minItems:Q().optional(),maxItems:Q().optional(),items:P({type:I("string"),enum:B(y())}),default:B(y()).optional()}),m0=P({type:I("array"),title:y().optional(),description:y().optional(),minItems:Q().optional(),maxItems:Q().optional(),items:P({anyOf:B(P({const:y(),title:y()}))}),default:B(y()).optional()}),h0=ie([f0,m0]),g0=ie([d0,p0,h0]),y0=ie([g0,i0,a0,c0]),_0=Qn.extend({mode:I("form").optional(),message:y(),requestedSchema:P({type:I("object"),properties:se(y(),y0),required:B(y()).optional()})}),v0=Qn.extend({mode:I("url"),message:y(),elicitationId:y(),url:y().url()}),x0=ie([_0,v0]),w0=$e.extend({method:I("elicitation/create"),params:x0}),b0=Qe.extend({elicitationId:y()}),$0=et.extend({method:I("notifications/elicitation/complete"),params:b0}),an=ke.extend({action:Le(["accept","decline","cancel"]),content:fu(t=>t===null?void 0:t,se(y(),ie([y(),Q(),xe(),B(y())])).optional())}),k0=P({type:I("ref/resource"),uri:y()});var S0=P({type:I("ref/prompt"),name:y()}),z0=Je.extend({ref:ie([S0,k0]),argument:P({name:y(),value:y()}),context:P({arguments:se(y(),y()).optional()}).optional()}),Vs=$e.extend({method:I("completion/complete"),params:z0});function Cm(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Zm(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var T0=ke.extend({completion:Re({values:B(y()).max(100),total:de(Q().int()),hasMore:de(xe())})}),P0=P({uri:y().startsWith("file://"),name:y().optional(),_meta:se(y(),le()).optional()}),O0=$e.extend({method:I("roots/list"),params:Je.optional()}),Eu=ke.extend({roots:B(P0)}),E0=et.extend({method:I("notifications/roots/list_changed"),params:Qe.optional()}),JR=ie([Os,xu,Vs,Pu,qs,Ls,As,Ms,Ds,O$,I$,sn,Us,Is,js,Ns,Zs]),GR=ie([Ps,Es,wu,E0,so]),WR=ie([Ts,co,Ou,an,Eu,Rs,Cs,nn]),YR=ie([Os,s0,w0,O0,Is,js,Ns,Zs]),QR=ie([Ps,Es,W$,j$,T$,X$,F$,so,$0]),e1=ie([Ts,g$,T0,U$,Z$,$$,k$,z$,Fs,K$,Rs,Cs,nn]),E=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===j.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new mu(o.elicitations,r)}return new t(e,r,n)}},mu=class extends E{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(j.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Kt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Mm=Symbol("Let zodToJsonSchema decide on which parser to use");var Am={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Dm=t=>typeof t=="string"?{...Am,name:t}:{...Am,...t};var Lm=t=>{let e=Dm(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Iu(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function X(t,e,r,n,o){t[e]=r,Iu(t,e,n,o)}var Hs=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function pe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Hs(e,t.currentPath):e.join("/")}}function qm(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==$.ZodAny&&(r.items=A(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&X(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&X(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(X(r,"minItems",t.exactLength.value,t.exactLength.message,e),X(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Um(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?X(r,"minimum",n.value,n.message,e):X(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),X(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?X(r,"maximum",n.value,n.message,e):X(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),X(r,"maximum",n.value,n.message,e));break;case"multipleOf":X(r,"multipleOf",n.value,n.message,e);break}return r}function Fm(){return{type:"boolean"}}function Ks(t,e){return A(t.type._def,e)}var Vm=(t,e)=>A(t.innerType._def,e);function Ru(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Ru(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return I0(t,e)}}var I0=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":X(r,"minimum",n.value,n.message,e);break;case"max":X(r,"maximum",n.value,n.message,e);break}return r};function Hm(t,e){return{...A(t.innerType._def,e),default:t.defaultValue()}}function Km(t,e){return e.effectStrategy==="input"?A(t.schema._def,e):pe(e)}function Bm(t){return{type:"string",enum:Array.from(t.values)}}var R0=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Xm(t,e){let r=[A(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),A(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(R0(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function Jm(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ju,at={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ju===void 0&&(ju=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ju),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Bs(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":X(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":X(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ct(r,"email",n.message,e);break;case"format:idn-email":ct(r,"idn-email",n.message,e);break;case"pattern:zod":je(r,at.email,n.message,e);break}break;case"url":ct(r,"uri",n.message,e);break;case"uuid":ct(r,"uuid",n.message,e);break;case"regex":je(r,n.regex,n.message,e);break;case"cuid":je(r,at.cuid,n.message,e);break;case"cuid2":je(r,at.cuid2,n.message,e);break;case"startsWith":je(r,RegExp(`^${Nu(n.value,e)}`),n.message,e);break;case"endsWith":je(r,RegExp(`${Nu(n.value,e)}$`),n.message,e);break;case"datetime":ct(r,"date-time",n.message,e);break;case"date":ct(r,"date",n.message,e);break;case"time":ct(r,"time",n.message,e);break;case"duration":ct(r,"duration",n.message,e);break;case"length":X(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),X(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{je(r,RegExp(Nu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&ct(r,"ipv4",n.message,e),n.version!=="v4"&&ct(r,"ipv6",n.message,e);break}case"base64url":je(r,at.base64url,n.message,e);break;case"jwt":je(r,at.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&je(r,at.ipv4Cidr,n.message,e),n.version!=="v4"&&je(r,at.ipv6Cidr,n.message,e);break}case"emoji":je(r,at.emoji(),n.message,e);break;case"ulid":{je(r,at.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ct(r,"binary",n.message,e);break}case"contentEncoding:base64":{X(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{je(r,at.base64,n.message,e);break}}break}case"nanoid":je(r,at.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Nu(t,e){return e.patternStrategy==="escape"?N0(t):t}var j0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function N0(t){let e="";for(let r=0;r<t.length;r++)j0.has(t[r])||(e+="\\"),e+=t[r];return e}function ct(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):X(t,"format",e,r,n)}function je(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Gm(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):X(t,"pattern",Gm(e,n),r,n)}function Gm(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
153
|
-
]))`;continue}else if(n[c]==="$"){
|
|
154
|
-
]))`;continue}}if(r.s&&n[c]==="."){o
|
|
324
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){o(l);continue}if(n.external){let p=n.external.registry.get(l[0])?.id;if(e!==l[0]&&p){o(l);continue}}if(this.metadataRegistry.get(l[0])?.id){o(l);continue}if(d.cycle){o(l);continue}if(d.count>1&&n.reused==="ref"){o(l);continue}}let a=(l,d)=>{let f=this.seen.get(l),p=f.def??f.schema,m={...p};if(f.ref===null)return;let y=f.ref;if(f.ref=null,y){a(y,d);let _=this.seen.get(y).schema;_.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(_)):(Object.assign(p,_),Object.assign(p,m))}f.isParent||this.override({zodSchema:l,jsonSchema:p,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,s.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function HO(t,e){if(t instanceof S1){let n=new AE(e),s={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let i={},o={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,u]=a;i[c]=n.emit(u,{...e,external:o})}if(Object.keys(s).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[a]:s}}return{schemas:i}}let r=new AE(e);return r.process(t),r.emit(t,e)}function In(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return In(s.element,r);case"object":{for(let i in s.shape)if(In(s.shape[i],r))return!0;return!1}case"union":{for(let i of s.options)if(In(i,r))return!0;return!1}case"intersection":return In(s.left,r)||In(s.right,r);case"tuple":{for(let i of s.items)if(In(i,r))return!0;return!!(s.rest&&In(s.rest,r))}case"record":return In(s.keyType,r)||In(s.valueType,r);case"map":return In(s.keyType,r)||In(s.valueType,r);case"set":return In(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return In(s.innerType,r);case"lazy":return In(s.getter(),r);case"default":return In(s.innerType,r);case"prefault":return In(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return In(s.in,r)||In(s.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var Mxe=K("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");wr.init(t,e),t.def=e,t.parse=(r,n)=>aR(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Nf(t,r,n),t.parseAsync=async(r,n)=>uR(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Bf(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>gi(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var jxe=K("ZodMiniObject",(t,e)=>{gE.init(t,e),Mxe.init(t,e),Kt.defineLazy(t,"shape",()=>e.shape)});function FO(t,e){let r={type:"object",get shape(){return Kt.assignProp(this,"shape",{...t}),this.shape},...Kt.normalizeParams(e)};return new jxe(r)}function Li(t){return!!t._zod}function jf(t){let e=Object.values(t);if(e.length===0)return FO({});let r=e.every(Li),n=e.every(s=>!Li(s));if(r)return FO(t);if(n)return Z5(t);throw new Error("Mixed Zod versions detected in object shape.")}function el(t,e){return Li(t)?Nf(t,e):t.safeParse(e)}async function EE(t,e){return Li(t)?await Bf(t,e):await t.safeParseAsync(e)}function tl(t){if(!t)return;let e;if(Li(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function V0(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return jf(t)}}if(Li(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function CE(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function CJ(t){return t.description}function kJ(t){if(Li(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function kE(t){if(Li(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var C1={};$a(C1,{ZodISODate:()=>IJ,ZodISODateTime:()=>TJ,ZodISODuration:()=>RJ,ZodISOTime:()=>PJ,date:()=>KO,datetime:()=>VO,duration:()=>GO,time:()=>ZO});var TJ=K("ZodISODateTime",(t,e)=>{hJ.init(t,e),Gr.init(t,e)});function VO(t){return _J(TJ,t)}var IJ=K("ZodISODate",(t,e)=>{pJ.init(t,e),Gr.init(t,e)});function KO(t){return vJ(IJ,t)}var PJ=K("ZodISOTime",(t,e)=>{mJ.init(t,e),Gr.init(t,e)});function ZO(t){return wJ(PJ,t)}var RJ=K("ZodISODuration",(t,e)=>{gJ.init(t,e),Gr.init(t,e)});function GO(t){return SJ(RJ,t)}var OJ=(t,e)=>{dE.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>iR(t,r)},flatten:{value:r=>sR(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},K9e=K("ZodError",OJ),k1=K("ZodError",OJ,{Parent:Error});var NJ=oR(k1),BJ=cR(k1),$J=lR(k1),MJ=dR(k1);var tn=K("ZodType",(t,e)=>(wr.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>gi(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>NJ(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>$J(t,r,n),t.parseAsync=async(r,n)=>BJ(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>MJ(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Bbe(r,n)),t.superRefine=r=>t.check($be(r)),t.overwrite=r=>t.check($f(r)),t.optional=()=>Xr(t),t.nullable=()=>LJ(t),t.nullish=()=>Xr(LJ(t)),t.nonoptional=r=>kbe(t,r),t.array=()=>Zt(t),t.or=r=>qr([t,r]),t.and=r=>IE(t,r),t.transform=r=>XO(t,VJ(r)),t.default=r=>Abe(t,r),t.prefault=r=>Cbe(t,r),t.catch=r=>Ibe(t,r),t.pipe=r=>XO(t,r),t.readonly=()=>Obe(t),t.describe=r=>{let n=t.clone();return Qu.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Qu.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Qu.get(t);let n=t.clone();return Qu.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),DJ=K("_ZodString",(t,e)=>{w1.init(t,e),tn.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(RO(...n)),t.includes=(...n)=>t.check(BO(...n)),t.startsWith=(...n)=>t.check($O(...n)),t.endsWith=(...n)=>t.check(MO(...n)),t.min=(...n)=>t.check(F0(...n)),t.max=(...n)=>t.check(wE(...n)),t.length=(...n)=>t.check(SE(...n)),t.nonempty=(...n)=>t.check(F0(1,...n)),t.lowercase=n=>t.check(OO(n)),t.uppercase=n=>t.check(NO(n)),t.trim=()=>t.check(zO()),t.normalize=(...n)=>t.check(jO(...n)),t.toLowerCase=()=>t.check(LO()),t.toUpperCase=()=>t.check(DO())}),Kxe=K("ZodString",(t,e)=>{w1.init(t,e),DJ.init(t,e),t.email=r=>t.check(sO(Zxe,r)),t.url=r=>t.check(uO(Gxe,r)),t.jwt=r=>t.check(AO(ube,r)),t.emoji=r=>t.check(lO(Wxe,r)),t.guid=r=>t.check(xE(jJ,r)),t.uuid=r=>t.check(iO(TE,r)),t.uuidv4=r=>t.check(oO(TE,r)),t.uuidv6=r=>t.check(aO(TE,r)),t.uuidv7=r=>t.check(cO(TE,r)),t.nanoid=r=>t.check(dO(Xxe,r)),t.guid=r=>t.check(xE(jJ,r)),t.cuid=r=>t.check(fO(Jxe,r)),t.cuid2=r=>t.check(hO(Yxe,r)),t.ulid=r=>t.check(pO(Qxe,r)),t.base64=r=>t.check(vO(obe,r)),t.base64url=r=>t.check(wO(abe,r)),t.xid=r=>t.check(mO(ebe,r)),t.ksuid=r=>t.check(gO(tbe,r)),t.ipv4=r=>t.check(yO(rbe,r)),t.ipv6=r=>t.check(xO(nbe,r)),t.cidrv4=r=>t.check(bO(sbe,r)),t.cidrv6=r=>t.check(_O(ibe,r)),t.e164=r=>t.check(SO(cbe,r)),t.datetime=r=>t.check(VO(r)),t.date=r=>t.check(KO(r)),t.time=r=>t.check(ZO(r)),t.duration=r=>t.check(GO(r))});function q(t){return nO(Kxe,t)}var Gr=K("ZodStringFormat",(t,e)=>{Nr.init(t,e),DJ.init(t,e)}),Zxe=K("ZodEmail",(t,e)=>{bR.init(t,e),Gr.init(t,e)});var jJ=K("ZodGUID",(t,e)=>{yR.init(t,e),Gr.init(t,e)});var TE=K("ZodUUID",(t,e)=>{xR.init(t,e),Gr.init(t,e)});var Gxe=K("ZodURL",(t,e)=>{_R.init(t,e),Gr.init(t,e)});var Wxe=K("ZodEmoji",(t,e)=>{vR.init(t,e),Gr.init(t,e)});var Xxe=K("ZodNanoID",(t,e)=>{wR.init(t,e),Gr.init(t,e)});var Jxe=K("ZodCUID",(t,e)=>{SR.init(t,e),Gr.init(t,e)});var Yxe=K("ZodCUID2",(t,e)=>{AR.init(t,e),Gr.init(t,e)});var Qxe=K("ZodULID",(t,e)=>{ER.init(t,e),Gr.init(t,e)});var ebe=K("ZodXID",(t,e)=>{CR.init(t,e),Gr.init(t,e)});var tbe=K("ZodKSUID",(t,e)=>{kR.init(t,e),Gr.init(t,e)});var rbe=K("ZodIPv4",(t,e)=>{TR.init(t,e),Gr.init(t,e)});var nbe=K("ZodIPv6",(t,e)=>{IR.init(t,e),Gr.init(t,e)});var sbe=K("ZodCIDRv4",(t,e)=>{PR.init(t,e),Gr.init(t,e)});var ibe=K("ZodCIDRv6",(t,e)=>{RR.init(t,e),Gr.init(t,e)});var obe=K("ZodBase64",(t,e)=>{OR.init(t,e),Gr.init(t,e)});var abe=K("ZodBase64URL",(t,e)=>{NR.init(t,e),Gr.init(t,e)});var cbe=K("ZodE164",(t,e)=>{BR.init(t,e),Gr.init(t,e)});var ube=K("ZodJWT",(t,e)=>{$R.init(t,e),Gr.init(t,e)});var UJ=K("ZodNumber",(t,e)=>{mE.init(t,e),tn.init(t,e),t.gt=(n,s)=>t.check(_E(n,s)),t.gte=(n,s)=>t.check(E1(n,s)),t.min=(n,s)=>t.check(E1(n,s)),t.lt=(n,s)=>t.check(bE(n,s)),t.lte=(n,s)=>t.check(A1(n,s)),t.max=(n,s)=>t.check(A1(n,s)),t.int=n=>t.check(zJ(n)),t.safe=n=>t.check(zJ(n)),t.positive=n=>t.check(_E(0,n)),t.nonnegative=n=>t.check(E1(0,n)),t.negative=n=>t.check(bE(0,n)),t.nonpositive=n=>t.check(A1(0,n)),t.multipleOf=(n,s)=>t.check(vE(n,s)),t.step=(n,s)=>t.check(vE(n,s)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function hr(t){return EO(UJ,t)}var lbe=K("ZodNumberFormat",(t,e)=>{MR.init(t,e),UJ.init(t,e)});function zJ(t){return CO(lbe,t)}var dbe=K("ZodBoolean",(t,e)=>{jR.init(t,e),tn.init(t,e)});function Ln(t){return kO(dbe,t)}var fbe=K("ZodNull",(t,e)=>{zR.init(t,e),tn.init(t,e)});function qJ(t){return TO(fbe,t)}var hbe=K("ZodUnknown",(t,e)=>{LR.init(t,e),tn.init(t,e)});function Wr(){return IO(hbe)}var pbe=K("ZodNever",(t,e)=>{DR.init(t,e),tn.init(t,e)});function mbe(t){return PO(pbe,t)}var gbe=K("ZodArray",(t,e)=>{UR.init(t,e),tn.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(F0(r,n)),t.nonempty=r=>t.check(F0(1,r)),t.max=(r,n)=>t.check(wE(r,n)),t.length=(r,n)=>t.check(SE(r,n)),t.unwrap=()=>t.element});function Zt(t,e){return AJ(gbe,t,e)}var HJ=K("ZodObject",(t,e)=>{gE.init(t,e),tn.init(t,e),Kt.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Ws(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Wr()}),t.loose=()=>t.clone({...t._zod.def,catchall:Wr()}),t.strict=()=>t.clone({...t._zod.def,catchall:mbe()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Kt.extend(t,r),t.merge=r=>Kt.merge(t,r),t.pick=r=>Kt.pick(t,r),t.omit=r=>Kt.omit(t,r),t.partial=(...r)=>Kt.partial(KJ,t,r[0]),t.required=(...r)=>Kt.required(ZJ,t,r[0])});function Oe(t,e){let r={type:"object",get shape(){return Kt.assignProp(this,"shape",{...t}),this.shape},...Kt.normalizeParams(e)};return new HJ(r)}function Ss(t,e){return new HJ({type:"object",get shape(){return Kt.assignProp(this,"shape",{...t}),this.shape},catchall:Wr(),...Kt.normalizeParams(e)})}var FJ=K("ZodUnion",(t,e)=>{yE.init(t,e),tn.init(t,e),t.options=e.options});function qr(t,e){return new FJ({type:"union",options:t,...Kt.normalizeParams(e)})}var ybe=K("ZodDiscriminatedUnion",(t,e)=>{FJ.init(t,e),qR.init(t,e)});function JO(t,e,r){return new ybe({type:"union",options:e,discriminator:t,...Kt.normalizeParams(r)})}var xbe=K("ZodIntersection",(t,e)=>{HR.init(t,e),tn.init(t,e)});function IE(t,e){return new xbe({type:"intersection",left:t,right:e})}var bbe=K("ZodRecord",(t,e)=>{FR.init(t,e),tn.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Br(t,e,r){return new bbe({type:"record",keyType:t,valueType:e,...Kt.normalizeParams(r)})}var WO=K("ZodEnum",(t,e)=>{VR.init(t,e),tn.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let i={};for(let o of n)if(r.has(o))i[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new WO({...e,checks:[],...Kt.normalizeParams(s),entries:i})},t.exclude=(n,s)=>{let i={...e.entries};for(let o of n)if(r.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new WO({...e,checks:[],...Kt.normalizeParams(s),entries:i})}});function Ws(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new WO({type:"enum",entries:r,...Kt.normalizeParams(e)})}var _be=K("ZodLiteral",(t,e)=>{KR.init(t,e),tn.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Xe(t,e){return new _be({type:"literal",values:Array.isArray(t)?t:[t],...Kt.normalizeParams(e)})}var vbe=K("ZodTransform",(t,e)=>{ZR.init(t,e),tn.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(Kt.issue(i,r.value,e));else{let o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(Kt.issue(o))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(i=>(r.value=i,r)):(r.value=s,r)}});function VJ(t){return new vbe({type:"transform",transform:t})}var KJ=K("ZodOptional",(t,e)=>{GR.init(t,e),tn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Xr(t){return new KJ({type:"optional",innerType:t})}var wbe=K("ZodNullable",(t,e)=>{WR.init(t,e),tn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function LJ(t){return new wbe({type:"nullable",innerType:t})}var Sbe=K("ZodDefault",(t,e)=>{XR.init(t,e),tn.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Abe(t,e){return new Sbe({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Ebe=K("ZodPrefault",(t,e)=>{JR.init(t,e),tn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Cbe(t,e){return new Ebe({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var ZJ=K("ZodNonOptional",(t,e)=>{YR.init(t,e),tn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function kbe(t,e){return new ZJ({type:"nonoptional",innerType:t,...Kt.normalizeParams(e)})}var Tbe=K("ZodCatch",(t,e)=>{QR.init(t,e),tn.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Ibe(t,e){return new Tbe({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Pbe=K("ZodPipe",(t,e)=>{eO.init(t,e),tn.init(t,e),t.in=e.in,t.out=e.out});function XO(t,e){return new Pbe({type:"pipe",in:t,out:e})}var Rbe=K("ZodReadonly",(t,e)=>{tO.init(t,e),tn.init(t,e)});function Obe(t){return new Rbe({type:"readonly",innerType:t})}var GJ=K("ZodCustom",(t,e)=>{rO.init(t,e),tn.init(t,e)});function Nbe(t){let e=new Gn({check:"custom"});return e._zod.check=t,e}function WJ(t,e){return UO(GJ,t??(()=>!0),e)}function Bbe(t,e={}){return qO(GJ,t,e)}function $be(t){let e=Nbe(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Kt.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(Kt.issue(s))}},t(r.value,r)));return e}function YO(t,e){return XO(VJ(t),e)}mi(xJ());var e9="2025-11-25";var XJ=[e9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],rl="io.modelcontextprotocol/related-task",RE="2.0",Pn=WJ(t=>t!==null&&(typeof t=="object"||typeof t=="function")),JJ=qr([q(),hr().int()]),YJ=q(),oNe=Ss({ttl:hr().optional(),pollInterval:hr().optional()}),Mbe=Oe({ttl:hr().optional()}),jbe=Oe({taskId:q()}),t9=Ss({progressToken:JJ.optional(),[rl]:jbe.optional()}),yi=Oe({_meta:t9.optional()}),T1=yi.extend({task:Mbe.optional()}),QJ=t=>T1.safeParse(t).success,Wn=Oe({method:q(),params:yi.loose().optional()}),Di=Oe({_meta:t9.optional()}),Ui=Oe({method:q(),params:Di.loose().optional()}),Xn=Ss({_meta:t9.optional()}),OE=qr([q(),hr().int()]),eY=Oe({jsonrpc:Xe(RE),id:OE,...Wn.shape}).strict(),r9=t=>eY.safeParse(t).success,tY=Oe({jsonrpc:Xe(RE),...Ui.shape}).strict(),rY=t=>tY.safeParse(t).success,n9=Oe({jsonrpc:Xe(RE),id:OE,result:Xn}).strict(),I1=t=>n9.safeParse(t).success;var rt;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(rt||(rt={}));var s9=Oe({jsonrpc:Xe(RE),id:OE.optional(),error:Oe({code:hr().int(),message:q(),data:Wr().optional()})}).strict();var nY=t=>s9.safeParse(t).success;var sY=qr([eY,tY,n9,s9]),aNe=qr([n9,s9]),NE=Xn.strict(),zbe=Di.extend({requestId:OE.optional(),reason:q().optional()}),BE=Ui.extend({method:Xe("notifications/cancelled"),params:zbe}),Lbe=Oe({src:q(),mimeType:q().optional(),sizes:Zt(q()).optional(),theme:Ws(["light","dark"]).optional()}),P1=Oe({icons:Zt(Lbe).optional()}),K0=Oe({name:q(),title:q().optional()}),iY=K0.extend({...K0.shape,...P1.shape,version:q(),websiteUrl:q().optional(),description:q().optional()}),Dbe=IE(Oe({applyDefaults:Ln().optional()}),Br(q(),Wr())),Ube=YO(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,IE(Oe({form:Dbe.optional(),url:Pn.optional()}),Br(q(),Wr()).optional())),qbe=Ss({list:Pn.optional(),cancel:Pn.optional(),requests:Ss({sampling:Ss({createMessage:Pn.optional()}).optional(),elicitation:Ss({create:Pn.optional()}).optional()}).optional()}),Hbe=Ss({list:Pn.optional(),cancel:Pn.optional(),requests:Ss({tools:Ss({call:Pn.optional()}).optional()}).optional()}),Fbe=Oe({experimental:Br(q(),Pn).optional(),sampling:Oe({context:Pn.optional(),tools:Pn.optional()}).optional(),elicitation:Ube.optional(),roots:Oe({listChanged:Ln().optional()}).optional(),tasks:qbe.optional(),extensions:Br(q(),Pn).optional()}),Vbe=yi.extend({protocolVersion:q(),capabilities:Fbe,clientInfo:iY}),i9=Wn.extend({method:Xe("initialize"),params:Vbe});var Kbe=Oe({experimental:Br(q(),Pn).optional(),logging:Pn.optional(),completions:Pn.optional(),prompts:Oe({listChanged:Ln().optional()}).optional(),resources:Oe({subscribe:Ln().optional(),listChanged:Ln().optional()}).optional(),tools:Oe({listChanged:Ln().optional()}).optional(),tasks:Hbe.optional(),extensions:Br(q(),Pn).optional()}),Zbe=Xn.extend({protocolVersion:q(),capabilities:Kbe,serverInfo:iY,instructions:q().optional()}),o9=Ui.extend({method:Xe("notifications/initialized"),params:Di.optional()});var $E=Wn.extend({method:Xe("ping"),params:yi.optional()}),Gbe=Oe({progress:hr(),total:Xr(hr()),message:Xr(q())}),Wbe=Oe({...Di.shape,...Gbe.shape,progressToken:JJ}),ME=Ui.extend({method:Xe("notifications/progress"),params:Wbe}),Xbe=yi.extend({cursor:YJ.optional()}),R1=Wn.extend({params:Xbe.optional()}),O1=Xn.extend({nextCursor:YJ.optional()}),Jbe=Ws(["working","input_required","completed","failed","cancelled"]),N1=Oe({taskId:q(),status:Jbe,ttl:qr([hr(),qJ()]),createdAt:q(),lastUpdatedAt:q(),pollInterval:Xr(hr()),statusMessage:Xr(q())}),Z0=Xn.extend({task:N1}),Ybe=Di.merge(N1),B1=Ui.extend({method:Xe("notifications/tasks/status"),params:Ybe}),jE=Wn.extend({method:Xe("tasks/get"),params:yi.extend({taskId:q()})}),zE=Xn.merge(N1),LE=Wn.extend({method:Xe("tasks/result"),params:yi.extend({taskId:q()})}),cNe=Xn.loose(),DE=R1.extend({method:Xe("tasks/list")}),UE=O1.extend({tasks:Zt(N1)}),qE=Wn.extend({method:Xe("tasks/cancel"),params:yi.extend({taskId:q()})}),oY=Xn.merge(N1),aY=Oe({uri:q(),mimeType:Xr(q()),_meta:Br(q(),Wr()).optional()}),cY=aY.extend({text:q()}),a9=q().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),uY=aY.extend({blob:a9}),$1=Ws(["user","assistant"]),G0=Oe({audience:Zt($1).optional(),priority:hr().min(0).max(1).optional(),lastModified:C1.datetime({offset:!0}).optional()}),lY=Oe({...K0.shape,...P1.shape,uri:q(),description:Xr(q()),mimeType:Xr(q()),size:Xr(hr()),annotations:G0.optional(),_meta:Xr(Ss({}))}),Qbe=Oe({...K0.shape,...P1.shape,uriTemplate:q(),description:Xr(q()),mimeType:Xr(q()),annotations:G0.optional(),_meta:Xr(Ss({}))}),HE=R1.extend({method:Xe("resources/list")}),e1e=O1.extend({resources:Zt(lY)}),FE=R1.extend({method:Xe("resources/templates/list")}),t1e=O1.extend({resourceTemplates:Zt(Qbe)}),c9=yi.extend({uri:q()}),r1e=c9,VE=Wn.extend({method:Xe("resources/read"),params:r1e}),n1e=Xn.extend({contents:Zt(qr([cY,uY]))}),s1e=Ui.extend({method:Xe("notifications/resources/list_changed"),params:Di.optional()}),i1e=c9,o1e=Wn.extend({method:Xe("resources/subscribe"),params:i1e}),a1e=c9,c1e=Wn.extend({method:Xe("resources/unsubscribe"),params:a1e}),u1e=Di.extend({uri:q()}),l1e=Ui.extend({method:Xe("notifications/resources/updated"),params:u1e}),d1e=Oe({name:q(),description:Xr(q()),required:Xr(Ln())}),f1e=Oe({...K0.shape,...P1.shape,description:Xr(q()),arguments:Xr(Zt(d1e)),_meta:Xr(Ss({}))}),KE=R1.extend({method:Xe("prompts/list")}),h1e=O1.extend({prompts:Zt(f1e)}),p1e=yi.extend({name:q(),arguments:Br(q(),q()).optional()}),ZE=Wn.extend({method:Xe("prompts/get"),params:p1e}),u9=Oe({type:Xe("text"),text:q(),annotations:G0.optional(),_meta:Br(q(),Wr()).optional()}),l9=Oe({type:Xe("image"),data:a9,mimeType:q(),annotations:G0.optional(),_meta:Br(q(),Wr()).optional()}),d9=Oe({type:Xe("audio"),data:a9,mimeType:q(),annotations:G0.optional(),_meta:Br(q(),Wr()).optional()}),m1e=Oe({type:Xe("tool_use"),name:q(),id:q(),input:Br(q(),Wr()),_meta:Br(q(),Wr()).optional()}),g1e=Oe({type:Xe("resource"),resource:qr([cY,uY]),annotations:G0.optional(),_meta:Br(q(),Wr()).optional()}),y1e=lY.extend({type:Xe("resource_link")}),f9=qr([u9,l9,d9,y1e,g1e]),x1e=Oe({role:$1,content:f9}),b1e=Xn.extend({description:q().optional(),messages:Zt(x1e)}),_1e=Ui.extend({method:Xe("notifications/prompts/list_changed"),params:Di.optional()}),v1e=Oe({title:q().optional(),readOnlyHint:Ln().optional(),destructiveHint:Ln().optional(),idempotentHint:Ln().optional(),openWorldHint:Ln().optional()}),w1e=Oe({taskSupport:Ws(["required","optional","forbidden"]).optional()}),dY=Oe({...K0.shape,...P1.shape,description:q().optional(),inputSchema:Oe({type:Xe("object"),properties:Br(q(),Pn).optional(),required:Zt(q()).optional()}).catchall(Wr()),outputSchema:Oe({type:Xe("object"),properties:Br(q(),Pn).optional(),required:Zt(q()).optional()}).catchall(Wr()).optional(),annotations:v1e.optional(),execution:w1e.optional(),_meta:Br(q(),Wr()).optional()}),GE=R1.extend({method:Xe("tools/list")}),S1e=O1.extend({tools:Zt(dY)}),WE=Xn.extend({content:Zt(f9).default([]),structuredContent:Br(q(),Wr()).optional(),isError:Ln().optional()}),uNe=WE.or(Xn.extend({toolResult:Wr()})),A1e=T1.extend({name:q(),arguments:Br(q(),Wr()).optional()}),W0=Wn.extend({method:Xe("tools/call"),params:A1e}),E1e=Ui.extend({method:Xe("notifications/tools/list_changed"),params:Di.optional()}),lNe=Oe({autoRefresh:Ln().default(!0),debounceMs:hr().int().nonnegative().default(300)}),M1=Ws(["debug","info","notice","warning","error","critical","alert","emergency"]),C1e=yi.extend({level:M1}),h9=Wn.extend({method:Xe("logging/setLevel"),params:C1e}),k1e=Di.extend({level:M1,logger:q().optional(),data:Wr()}),T1e=Ui.extend({method:Xe("notifications/message"),params:k1e}),I1e=Oe({name:q().optional()}),P1e=Oe({hints:Zt(I1e).optional(),costPriority:hr().min(0).max(1).optional(),speedPriority:hr().min(0).max(1).optional(),intelligencePriority:hr().min(0).max(1).optional()}),R1e=Oe({mode:Ws(["auto","required","none"]).optional()}),O1e=Oe({type:Xe("tool_result"),toolUseId:q().describe("The unique identifier for the corresponding tool call."),content:Zt(f9).default([]),structuredContent:Oe({}).loose().optional(),isError:Ln().optional(),_meta:Br(q(),Wr()).optional()}),N1e=JO("type",[u9,l9,d9]),PE=JO("type",[u9,l9,d9,m1e,O1e]),B1e=Oe({role:$1,content:qr([PE,Zt(PE)]),_meta:Br(q(),Wr()).optional()}),$1e=T1.extend({messages:Zt(B1e),modelPreferences:P1e.optional(),systemPrompt:q().optional(),includeContext:Ws(["none","thisServer","allServers"]).optional(),temperature:hr().optional(),maxTokens:hr().int(),stopSequences:Zt(q()).optional(),metadata:Pn.optional(),tools:Zt(dY).optional(),toolChoice:R1e.optional()}),M1e=Wn.extend({method:Xe("sampling/createMessage"),params:$1e}),j1=Xn.extend({model:q(),stopReason:Xr(Ws(["endTurn","stopSequence","maxTokens"]).or(q())),role:$1,content:N1e}),p9=Xn.extend({model:q(),stopReason:Xr(Ws(["endTurn","stopSequence","maxTokens","toolUse"]).or(q())),role:$1,content:qr([PE,Zt(PE)])}),j1e=Oe({type:Xe("boolean"),title:q().optional(),description:q().optional(),default:Ln().optional()}),z1e=Oe({type:Xe("string"),title:q().optional(),description:q().optional(),minLength:hr().optional(),maxLength:hr().optional(),format:Ws(["email","uri","date","date-time"]).optional(),default:q().optional()}),L1e=Oe({type:Ws(["number","integer"]),title:q().optional(),description:q().optional(),minimum:hr().optional(),maximum:hr().optional(),default:hr().optional()}),D1e=Oe({type:Xe("string"),title:q().optional(),description:q().optional(),enum:Zt(q()),default:q().optional()}),U1e=Oe({type:Xe("string"),title:q().optional(),description:q().optional(),oneOf:Zt(Oe({const:q(),title:q()})),default:q().optional()}),q1e=Oe({type:Xe("string"),title:q().optional(),description:q().optional(),enum:Zt(q()),enumNames:Zt(q()).optional(),default:q().optional()}),H1e=qr([D1e,U1e]),F1e=Oe({type:Xe("array"),title:q().optional(),description:q().optional(),minItems:hr().optional(),maxItems:hr().optional(),items:Oe({type:Xe("string"),enum:Zt(q())}),default:Zt(q()).optional()}),V1e=Oe({type:Xe("array"),title:q().optional(),description:q().optional(),minItems:hr().optional(),maxItems:hr().optional(),items:Oe({anyOf:Zt(Oe({const:q(),title:q()}))}),default:Zt(q()).optional()}),K1e=qr([F1e,V1e]),Z1e=qr([q1e,H1e,K1e]),G1e=qr([Z1e,j1e,z1e,L1e]),W1e=T1.extend({mode:Xe("form").optional(),message:q(),requestedSchema:Oe({type:Xe("object"),properties:Br(q(),G1e),required:Zt(q()).optional()})}),X1e=T1.extend({mode:Xe("url"),message:q(),elicitationId:q(),url:q().url()}),J1e=qr([W1e,X1e]),Y1e=Wn.extend({method:Xe("elicitation/create"),params:J1e}),Q1e=Di.extend({elicitationId:q()}),e_e=Ui.extend({method:Xe("notifications/elicitation/complete"),params:Q1e}),X0=Xn.extend({action:Ws(["accept","decline","cancel"]),content:YO(t=>t===null?void 0:t,Br(q(),qr([q(),hr(),Ln(),Zt(q())])).optional())}),t_e=Oe({type:Xe("ref/resource"),uri:q()});var r_e=Oe({type:Xe("ref/prompt"),name:q()}),n_e=yi.extend({ref:qr([r_e,t_e]),argument:Oe({name:q(),value:q()}),context:Oe({arguments:Br(q(),q()).optional()}).optional()}),XE=Wn.extend({method:Xe("completion/complete"),params:n_e});function fY(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function hY(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var s_e=Xn.extend({completion:Ss({values:Zt(q()).max(100),total:Xr(hr().int()),hasMore:Xr(Ln())})}),i_e=Oe({uri:q().startsWith("file://"),name:q().optional(),_meta:Br(q(),Wr()).optional()}),o_e=Wn.extend({method:Xe("roots/list"),params:yi.optional()}),m9=Xn.extend({roots:Zt(i_e)}),a_e=Ui.extend({method:Xe("notifications/roots/list_changed"),params:Di.optional()}),dNe=qr([$E,i9,XE,h9,ZE,KE,HE,FE,VE,o1e,c1e,W0,GE,jE,LE,DE,qE]),fNe=qr([BE,ME,o9,a_e,B1]),hNe=qr([NE,j1,p9,X0,m9,zE,UE,Z0]),pNe=qr([$E,M1e,Y1e,o_e,jE,LE,DE,qE]),mNe=qr([BE,ME,T1e,l1e,s1e,E1e,_1e,B1,e_e]),gNe=qr([NE,Zbe,s_e,b1e,h1e,e1e,t1e,n1e,WE,S1e,zE,UE,Z0]),We=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===rt.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new QO(s.elicitations,r)}return new t(e,r,n)}},QO=class extends We{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(rt.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function nl(t){return t==="completed"||t==="failed"||t==="cancelled"}var mY=Symbol("Let zodToJsonSchema decide on which parser to use");var pY={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},gY=t=>typeof t=="string"?{...pY,name:t}:{...pY,...t};var yY=t=>{let e=gY(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function g9(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Gt(t,e,r,n,s){t[e]=r,g9(t,e,n,s)}var JE=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Jr(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?JE(e,t.currentPath):e.join("/")}}function xY(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==de.ZodAny&&(r.items=at(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Gt(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Gt(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Gt(r,"minItems",t.exactLength.value,t.exactLength.message,e),Gt(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function bY(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Gt(r,"minimum",n.value,n.message,e):Gt(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Gt(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Gt(r,"maximum",n.value,n.message,e):Gt(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Gt(r,"maximum",n.value,n.message,e));break;case"multipleOf":Gt(r,"multipleOf",n.value,n.message,e);break}return r}function _Y(){return{type:"boolean"}}function YE(t,e){return at(t.type._def,e)}var vY=(t,e)=>at(t.innerType._def,e);function y9(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,i)=>y9(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return c_e(t,e)}}var c_e=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Gt(r,"minimum",n.value,n.message,e);break;case"max":Gt(r,"maximum",n.value,n.message,e);break}return r};function wY(t,e){return{...at(t.innerType._def,e),default:t.defaultValue()}}function SY(t,e){return e.effectStrategy==="input"?at(t.schema._def,e):Jr(e)}function AY(t){return{type:"string",enum:Array.from(t.values)}}var u_e=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function EY(t,e){let r=[at(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),at(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(i=>{if(u_e(i))s.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let o=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;o=c}else n=void 0;s.push(o)}}),s.length?{allOf:s,...n}:void 0}function CY(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var x9,ko={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(x9===void 0&&(x9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),x9),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function QE(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Gt(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Gt(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":To(r,"email",n.message,e);break;case"format:idn-email":To(r,"idn-email",n.message,e);break;case"pattern:zod":As(r,ko.email,n.message,e);break}break;case"url":To(r,"uri",n.message,e);break;case"uuid":To(r,"uuid",n.message,e);break;case"regex":As(r,n.regex,n.message,e);break;case"cuid":As(r,ko.cuid,n.message,e);break;case"cuid2":As(r,ko.cuid2,n.message,e);break;case"startsWith":As(r,RegExp(`^${b9(n.value,e)}`),n.message,e);break;case"endsWith":As(r,RegExp(`${b9(n.value,e)}$`),n.message,e);break;case"datetime":To(r,"date-time",n.message,e);break;case"date":To(r,"date",n.message,e);break;case"time":To(r,"time",n.message,e);break;case"duration":To(r,"duration",n.message,e);break;case"length":Gt(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Gt(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{As(r,RegExp(b9(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&To(r,"ipv4",n.message,e),n.version!=="v4"&&To(r,"ipv6",n.message,e);break}case"base64url":As(r,ko.base64url,n.message,e);break;case"jwt":As(r,ko.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&As(r,ko.ipv4Cidr,n.message,e),n.version!=="v4"&&As(r,ko.ipv6Cidr,n.message,e);break}case"emoji":As(r,ko.emoji(),n.message,e);break;case"ulid":{As(r,ko.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{To(r,"binary",n.message,e);break}case"contentEncoding:base64":{Gt(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{As(r,ko.base64,n.message,e);break}}break}case"nanoid":As(r,ko.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function b9(t,e){return e.patternStrategy==="escape"?d_e(t):t}var l_e=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function d_e(t){let e="";for(let r=0;r<t.length;r++)l_e.has(t[r])||(e+="\\"),e+=t[r];return e}function To(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Gt(t,"format",e,r,n)}function As(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:kY(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Gt(t,"pattern",kY(e,n),r,n)}function kY(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,s="",i=!1,o=!1,a=!1;for(let c=0;c<n.length;c++){if(i){s+=n[c],i=!1;continue}if(r.i){if(o){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
325
|
+
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
|
326
|
+
]))`;continue}}if(r.s&&n[c]==="."){s+=o?`${n[c]}\r
|
|
155
327
|
`:`[${n[c]}\r
|
|
156
|
-
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Xs(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===$.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:A(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??pe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:A(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===$.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Bs(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===$.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===$.ZodBranded&&t.keyType._def.type._def.typeName===$.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ks(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Wm(t,e){if(e.mapStrategy==="record")return Xs(t,e);let r=A(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||pe(e),n=A(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||pe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Ym(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Qm(t){return t.target==="openAi"?void 0:{not:pe({...t,currentPath:[...t.currentPath,"not"]})}}function eh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var uo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function rh(t,e){if(e.target==="openApi3")return th(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in uo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=uo[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return th(t,e)}var th=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>A(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function nh(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:uo[t.innerType._def.typeName],nullable:!0}:{type:[uo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=A(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=A(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function oh(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Iu(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?X(r,"minimum",n.value,n.message,e):X(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),X(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?X(r,"maximum",n.value,n.message,e):X(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),X(r,"maximum",n.value,n.message,e));break;case"multipleOf":X(r,"multipleOf",n.value,n.message,e);break}return r}function sh(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=Z0(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=A(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=C0(t,e);return i!==void 0&&(n.additionalProperties=i),n}function C0(t,e){if(t.catchall._def.typeName!=="ZodNever")return A(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Z0(t){try{return t.isOptional()}catch{return!0}}var ih=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return A(t.innerType._def,e);let r=A(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:pe(e)},r]}:pe(e)};var ah=(t,e)=>{if(e.pipeStrategy==="input")return A(t.in._def,e);if(e.pipeStrategy==="output")return A(t.out._def,e);let r=A(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=A(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function ch(t,e){return A(t.type._def,e)}function uh(t,e){let n={type:"array",uniqueItems:!0,items:A(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&X(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&X(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function lh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>A(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:A(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>A(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function dh(t){return{not:pe(t)}}function ph(t){return pe(t)}var fh=(t,e)=>A(t.innerType._def,e);var mh=(t,e,r)=>{switch(e){case $.ZodString:return Bs(t,r);case $.ZodNumber:return oh(t,r);case $.ZodObject:return sh(t,r);case $.ZodBigInt:return Um(t,r);case $.ZodBoolean:return Fm();case $.ZodDate:return Ru(t,r);case $.ZodUndefined:return dh(r);case $.ZodNull:return eh(r);case $.ZodArray:return qm(t,r);case $.ZodUnion:case $.ZodDiscriminatedUnion:return rh(t,r);case $.ZodIntersection:return Xm(t,r);case $.ZodTuple:return lh(t,r);case $.ZodRecord:return Xs(t,r);case $.ZodLiteral:return Jm(t,r);case $.ZodEnum:return Bm(t);case $.ZodNativeEnum:return Ym(t);case $.ZodNullable:return nh(t,r);case $.ZodOptional:return ih(t,r);case $.ZodMap:return Wm(t,r);case $.ZodSet:return uh(t,r);case $.ZodLazy:return()=>t.getter()._def;case $.ZodPromise:return ch(t,r);case $.ZodNaN:case $.ZodNever:return Qm(r);case $.ZodEffects:return Km(t,r);case $.ZodAny:return pe(r);case $.ZodUnknown:return ph(r);case $.ZodDefault:return Hm(t,r);case $.ZodBranded:return Ks(t,r);case $.ZodReadonly:return fh(t,r);case $.ZodCatch:return Vm(t,r);case $.ZodPipeline:return ah(t,r);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(n=>{})(e)}};function A(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Mm)return a}if(n&&!r){let a=A0(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=mh(t,t.typeName,e),i=typeof s=="function"?A(s(),e):s;if(i&&M0(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var A0=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Hs(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),pe(e)):e.$refStrategy==="seen"?pe(e):void 0}},M0=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Cu=(t,e)=>{let r=Lm(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:A(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??pe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=A(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??pe(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function D0(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Zu(t,e){return Ye(t)?ou(t,{target:D0(e?.target),io:e?.pipeStrategy??"input"}):Cu(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Au(t){let r=Vt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ws(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Mu(t,e){let r=Ft(t,e);if(!r.success)throw r.error;return r.data}var L0=6e4,Js=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ps,r=>{this._oncancel(r)}),this.setNotificationHandler(Es,r=>{this._onprogress(r)}),this.setRequestHandler(Os,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Is,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(j.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(js,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,f=new E(d.error.code,d.error.message,d.error.data);l(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new E(j.InvalidParams,`Task not found: ${s}`);if(!Kt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Kt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Ht]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ns,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new E(j.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Zs,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(j.InvalidParams,`Task not found: ${r.params.taskId}`);if(Kt(o.status))throw new E(j.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new E(j.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof E?o:new E(j.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),E.fromError(j.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),eo(s)||zm(s)?this._onresponse(s):yu(s)?this._onrequest(s,i):Sm(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=E.fromError(j.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Ht]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:j.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=bm(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(i.signal.aborted)throw new E(j.ConnectionClosed,"Request was cancelled");let m={...f,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let p=m.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:j.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),eo(e))n(e);else{let i=new E(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(eo(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),eo(e))o(e);else{let i=E.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof E?i:new E(j.InternalError,String(i))}}return}let s;try{let i=await this.request(e,nn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new E(j.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Kt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new E(j.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new E(j.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof E?i:new E(j.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Ht]:c}});let p=v=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));let x=v instanceof E?v:new E(j.RequestTimeout,String(v));l(x)};this._responseHandlers.set(f,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let x=Ft(r,v.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??L0,g=()=>p(E.fromError(j.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let v=x=>{let T=this._responseHandlers.get(f);T?T(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,v),this._enqueueTaskMessage(w,{type:"request",message:m,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),l(x)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(f),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Rs,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Cs,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Om,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ht]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Ht]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ht]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Au(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Mu(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Au(e);this._notificationHandlers.set(n,o=>{let s=Mu(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&yu(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new E(j.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new E(j.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new E(j.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new E(j.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=so.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Kt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new E(j.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Kt(a.status))throw new E(j.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=so.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Kt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function hh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gh(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];hh(i)&&hh(s)?r[o]={...i,...s}:r[o]=s}return r}var a_=Vd(kd(),1),c_=Vd(i_(),1);function FO(){let t=new a_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,c_.default)(t),t}var Ei=class{constructor(e){this._ajv=e??FO()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Ii=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},co,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},an,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function u_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function l_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ri=class extends Js{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ao.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ei,this.setRequestHandler(xu,n=>this._oninitialize(n)),this.setNotificationHandler(wu,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Pu,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ao.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ii(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=gh(this._capabilities,e)}setRequestHandler(e,r){let o=Vt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ye(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Ft(sn,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new E(j.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let p=Ft(nn,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new E(j.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let m=Ft(Fs,f);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new E(j.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){l_(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&u_(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:vm.includes(r)?r:hu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ts)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ou,r):this.request({method:"sampling/createMessage",params:e},co,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},an,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},an,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new E(j.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof E?i:new E(j.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Eu,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var p_=Symbol.for("mcp.completable");function Rd(t){return!!t&&typeof t=="object"&&p_ in t}function f_(t){return t[p_]?.complete}var d_;(function(t){t.Completable="McpCompletable"})(d_||(d_={}));var VO=/^[A-Za-z0-9._-]{1,128}$/;function HO(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!VO.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function KO(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function jd(t){let e=HO(t);return KO(t,e.warnings),e.isValid}var ji=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Ni=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ri(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ji(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(tr(Us)),this.server.assertCanSetRequestHandler(tr(sn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Us,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=tn(r.inputSchema);return o?Zu(o,{strictUnions:!0,pipeStrategy:"input"}):BO})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=tn(r.outputSchema);o&&(n.outputSchema=Zu(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(sn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new E(j.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new E(j.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new E(j.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new E(j.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof E&&n.code===j.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=tn(e.inputSchema)??e.inputSchema,i=await vs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=xs(a);throw new E(j.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new E(j.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=tn(e.outputSchema),s=await vs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=xs(i);throw new E(j.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await n.taskStore.getTask(c);if(!d)throw new E(j.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(tr(Vs)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Vs,async e=>{switch(e.params.ref.type){case"ref/prompt":return Cm(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Zm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new E(j.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new E(j.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new E(j.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Lo;let s=Vt(n.argsSchema)?.[e.params.argument.name];if(!Rd(s))return Lo;let i=f_(s);if(!i)return Lo;let a=await i(e.params.argument.value,e.params.context);return h_(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Lo;throw new E(j.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Lo;let s=await o(e.params.argument.value,e.params.context);return h_(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(tr(As)),this.server.assertCanSetRequestHandler(tr(Ms)),this.server.assertCanSetRequestHandler(tr(Ds)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(As,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Ms,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ds,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new E(j.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new E(j.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(tr(Ls)),this.server.assertCanSetRequestHandler(tr(qs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ls,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?XO(r.argsSchema):void 0}))})),this.server.setRequestHandler(qs,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new E(j.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new E(j.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=tn(n.argsSchema),s=await vs(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=xs(c);throw new E(j.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Er(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Er(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Me?c._def?.innerType:c;return Rd(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){jd(e);let l={title:r,description:n,inputSchema:m_(o),outputSchema:m_(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&jd(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Er(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Er(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Nd(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Nd(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var BO={type:"object",properties:{}};function g_(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function y_(t){return"_def"in t||"_zod"in t||g_(t)}function Nd(t){return typeof t!="object"||t===null||y_(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(g_)}function m_(t){if(t){if(Nd(t))return Er(t);if(!y_(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function XO(t){let e=Vt(t);return e?Object.entries(e).map(([r,n])=>{let o=Jf(n),s=Gf(n);return{name:r,description:o,required:!s}}):[]}function tr(t){let r=Vt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ws(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function h_(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Lo={completion:{values:[],hasMore:!1}};import v_ from"node:process";var Ci=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
157
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
158
|
-
`}var
|
|
159
|
-
`).map(c=>c.trim()).filter(c=>c.startsWith("- ")),a=r.toLowerCase();for(
|
|
160
|
-
`).length>
|
|
328
|
+
]`;continue}s+=n[c],n[c]==="\\"?i=!0:o&&n[c]==="]"?o=!1:!o&&n[c]==="["&&(o=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function eC(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:at(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Jr(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:at(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=QE(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===de.ZodBranded&&t.keyType._def.type._def.typeName===de.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=YE(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function TY(t,e){if(e.mapStrategy==="record")return eC(t,e);let r=at(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Jr(e),n=at(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Jr(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function IY(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),s=Array.from(new Set(n.map(i=>typeof i)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function PY(t){return t.target==="openAi"?void 0:{not:Jr({...t,currentPath:[...t.currentPath,"not"]})}}function RY(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var z1={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function NY(t,e){if(e.target==="openApi3")return OY(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in z1&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,i)=>{let o=z1[i._def.typeName];return o&&!s.includes(o)?[...s,o]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,i)=>{let o=typeof i._def.value;switch(o){case"string":case"number":case"boolean":return[...s,o];case"bigint":return[...s,"integer"];case"object":if(i._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((i,o,a)=>a.indexOf(i)===o);return{type:s.length>1?s:s[0],enum:r.reduce((i,o)=>i.includes(o._def.value)?i:[...i,o._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(i=>!n.includes(i))],[])};return OY(t,e)}var OY=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>at(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function BY(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:z1[t.innerType._def.typeName],nullable:!0}:{type:[z1[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=at(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=at(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function $Y(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",g9(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Gt(r,"minimum",n.value,n.message,e):Gt(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Gt(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Gt(r,"maximum",n.value,n.message,e):Gt(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Gt(r,"maximum",n.value,n.message,e));break;case"multipleOf":Gt(r,"multipleOf",n.value,n.message,e);break}return r}function MY(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],i=t.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=h_e(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=at(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||s.push(a))}s.length&&(n.required=s);let o=f_e(t,e);return o!==void 0&&(n.additionalProperties=o),n}function f_e(t,e){if(t.catchall._def.typeName!=="ZodNever")return at(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function h_e(t){try{return t.isOptional()}catch{return!0}}var jY=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return at(t.innerType._def,e);let r=at(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Jr(e)},r]}:Jr(e)};var zY=(t,e)=>{if(e.pipeStrategy==="input")return at(t.in._def,e);if(e.pipeStrategy==="output")return at(t.out._def,e);let r=at(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=at(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function LY(t,e){return at(t.type._def,e)}function DY(t,e){let n={type:"array",uniqueItems:!0,items:at(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Gt(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Gt(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function UY(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>at(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:at(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>at(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function qY(t){return{not:Jr(t)}}function HY(t){return Jr(t)}var FY=(t,e)=>at(t.innerType._def,e);var VY=(t,e,r)=>{switch(e){case de.ZodString:return QE(t,r);case de.ZodNumber:return $Y(t,r);case de.ZodObject:return MY(t,r);case de.ZodBigInt:return bY(t,r);case de.ZodBoolean:return _Y();case de.ZodDate:return y9(t,r);case de.ZodUndefined:return qY(r);case de.ZodNull:return RY(r);case de.ZodArray:return xY(t,r);case de.ZodUnion:case de.ZodDiscriminatedUnion:return NY(t,r);case de.ZodIntersection:return EY(t,r);case de.ZodTuple:return UY(t,r);case de.ZodRecord:return eC(t,r);case de.ZodLiteral:return CY(t,r);case de.ZodEnum:return AY(t);case de.ZodNativeEnum:return IY(t);case de.ZodNullable:return BY(t,r);case de.ZodOptional:return jY(t,r);case de.ZodMap:return TY(t,r);case de.ZodSet:return DY(t,r);case de.ZodLazy:return()=>t.getter()._def;case de.ZodPromise:return LY(t,r);case de.ZodNaN:case de.ZodNever:return PY(r);case de.ZodEffects:return SY(t,r);case de.ZodAny:return Jr(r);case de.ZodUnknown:return HY(r);case de.ZodDefault:return wY(t,r);case de.ZodBranded:return YE(t,r);case de.ZodReadonly:return FY(t,r);case de.ZodCatch:return vY(t,r);case de.ZodPipeline:return zY(t,r);case de.ZodFunction:case de.ZodVoid:case de.ZodSymbol:return;default:return(n=>{})(e)}};function at(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==mY)return a}if(n&&!r){let a=p_e(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let i=VY(t,t.typeName,e),o=typeof i=="function"?at(i(),e):i;if(o&&m_e(t,e,o),e.postProcess){let a=e.postProcess(o,t,e);return s.jsonSchema=o,a}return s.jsonSchema=o,o}var p_e=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:JE(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Jr(e)):e.$refStrategy==="seen"?Jr(e):void 0}},m_e=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var _9=(t,e)=>{let r=yY(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:at(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Jr(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=at(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??Jr(r),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(i.title=o),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=s===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function g_e(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function v9(t,e){return Li(t)?HO(t,{target:g_e(e?.target),io:e?.pipeStrategy??"input"}):_9(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function w9(t){let r=tl(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=kE(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function S9(t,e){let r=el(t,e);if(!r.success)throw r.error;return r.data}var y_e=6e4,tC=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(BE,r=>{this._oncancel(r)}),this.setNotificationHandler(ME,r=>{this._onprogress(r)}),this.setRequestHandler($E,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(jE,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new We(rt.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(LE,async(r,n)=>{let s=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,f=new We(d.error.code,d.error.message,d.error.data);l(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(i,n.sessionId);if(!o)throw new We(rt.InvalidParams,`Task not found: ${i}`);if(!nl(o.status))return await this._waitForTaskUpdate(i,n.signal),await s();if(nl(o.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[rl]:{taskId:i}}}}return await s()};return await s()}),this.setRequestHandler(DE,async(r,n)=>{try{let{tasks:s,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:i,_meta:{}}}catch(s){throw new We(rt.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(qE,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new We(rt.InvalidParams,`Task not found: ${r.params.taskId}`);if(nl(s.status))throw new We(rt.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new We(rt.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(s){throw s instanceof We?s:new We(rt.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),We.fromError(rt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let s=this._transport?.onmessage;this._transport.onmessage=(i,o)=>{s?.(i,o),I1(i)||nY(i)?this._onresponse(i):r9(i)?this._onrequest(i,o):rY(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=We.fromError(rt.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,i=e.params?._meta?.[rl]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:rt.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},s?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):s?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let a=QJ(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:o.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(o.signal.aborted)return;let d={relatedRequestId:e.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(o.signal.aborted)throw new We(rt.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(o.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)},async l=>{if(o.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:rt.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===o&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),i=this._progressHandlers.get(s);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),o(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),I1(e))n(e);else{let o=new We(e.error.code,e.error.message,e.error.data);n(o)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(I1(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let a=o.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),I1(e))s(e);else{let o=We.fromError(e.error.code,e.error.message,e.error.data);s(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(o){yield{type:"error",error:o instanceof We?o:new We(rt.InternalError,String(o))}}return}let i;try{let o=await this.request(e,Z0,n);if(o.task)i=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new We(rt.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},nl(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new We(rt.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new We(rt.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof We?o:new We(rt.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=C=>{l(C)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(C){d(C);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[rl]:c}});let m=C=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(C)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(B=>this._onerror(new Error(`Failed to send cancellation: ${B}`)));let E=C instanceof We?C:new We(rt.RequestTimeout,String(C));l(E)};this._responseHandlers.set(f,C=>{if(!n?.signal?.aborted){if(C instanceof Error)return l(C);try{let E=el(r,C.result);E.success?u(E.data):l(E.error)}catch(E){l(E)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let y=n?.timeout??y_e,_=()=>m(We.fromError(rt.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(f,y,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let S=c?.taskId;if(S){let C=E=>{let B=this._responseHandlers.get(f);B?B(E):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,C),this._enqueueTaskMessage(S,{type:"request",message:p,timestamp:Date.now()}).catch(E=>{this._cleanupTimeout(f),l(E)})}else this._transport.send(p,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(C=>{this._cleanupTimeout(f),l(C)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},zE,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},UE,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},oY,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[rl]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[rl]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[rl]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=w9(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,i)=>{let o=S9(e,s);return Promise.resolve(r(o,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=w9(e);this._notificationHandlers.set(n,s=>{let i=S9(e,s);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&r9(s.message)){let i=s.message.id,o=this._requestResolvers.get(i);o?(o(new We(rt.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new We(rt.InvalidRequest,"Request cancelled"));return}let o=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(o),i(new We(rt.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let i=await n.getTask(s,r);if(!i)throw new We(rt.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(s,i,o)=>{await n.storeTaskResult(s,i,o,r);let a=await n.getTask(s,r);if(a){let c=B1.parse({method:"notifications/tasks/status",params:a});await this.notification(c),nl(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,i,o)=>{let a=await n.getTask(s,r);if(!a)throw new We(rt.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(nl(a.status))throw new We(rt.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,i,o,r);let c=await n.getTask(s,r);if(c){let u=B1.parse({method:"notifications/tasks/status",params:c});await this.notification(u),nl(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function KY(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ZY(t,e){let r={...t};for(let n in e){let s=n,i=e[s];if(i===void 0)continue;let o=r[s];KY(o)&&KY(i)?r[s]={...o,...i}:r[s]=i}return r}var jte=vt(cB(),1),zte=vt(Mte(),1);function _Ee(){let t=new jte.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,zte.default)(t),t}var MC=class{constructor(e){this._ajv=e??_Ee()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var jC=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],i=Array.isArray(s.content)?s.content:[s.content],o=i.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(o){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},j1,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},X0,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Lte(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Dte(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var zC=class extends tC{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(M1.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let i=this._loggingLevels.get(s);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new MC,this.setRequestHandler(i9,n=>this._oninitialize(n)),this.setNotificationHandler(o9,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(h9,async(n,s)=>{let i=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=n.params,a=M1.safeParse(o);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new jC(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ZY(this._capabilities,e)}setRequestHandler(e,r){let s=tl(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let i;if(Li(s)){let a=s;i=a._zod?.def?.value??a.value}else{let a=s;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,u)=>{let l=el(W0,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new We(rt.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let m=el(Z0,f);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new We(rt.InvalidParams,`Invalid task creation result: ${y}`)}return m.data}let p=el(WE,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new We(rt.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Dte(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Lte(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:XJ.includes(r)?r:e9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},NE)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],i=s.some(u=>u.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=o?Array.isArray(o.content)?o.content:[o.content]:[],c=a.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(s.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},p9,r):this.request({method:"sampling/createMessage",params:e},j1,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},X0,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:s},X0,r);if(i.action==="accept"&&i.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(i.content);if(!a.valid)throw new We(rt.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(o){throw o instanceof We?o:new We(rt.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return i}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},m9,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var qte=Symbol.for("mcp.completable");function gB(t){return!!t&&typeof t=="object"&&qte in t}function Hte(t){return t[qte]?.complete}var Ute;(function(t){t.Completable="McpCompletable"})(Ute||(Ute={}));var vEe=/^[A-Za-z0-9._-]{1,128}$/;function wEe(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!vEe.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,i)=>i.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function SEe(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function yB(t){let e=wEe(t);return SEe(t,e.warnings),e.isValid}var LC=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}};var DC=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new zC(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new LC(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(fl(GE)),this.server.assertCanSetRequestHandler(fl(W0)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(GE,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=V0(r.inputSchema);return s?v9(s,{strictUnions:!0,pipeStrategy:"input"}):AEe})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=V0(r.outputSchema);s&&(n.outputSchema=v9(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(W0,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new We(rt.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new We(rt.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,i=n.execution?.taskSupport,o="createTask"in n.handler;if((i==="required"||i==="optional")&&!o)throw new We(rt.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!s)throw new We(rt.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!s&&o)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof We&&n.code===rt.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let i=V0(e.inputSchema)??e.inputSchema,o=await EE(i,r);if(!o.success){let a="error"in o?o.error:"Unknown error",c=CE(a);throw new We(rt.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return o.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new We(rt.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=V0(e.outputSchema),i=await EE(s,r.structuredContent);if(!i.success){let o="error"in i?i.error:"Unknown error",a=CE(o);throw new We(rt.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let o={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,o))}else{let a=s;return await Promise.resolve(a.createTask(o))}}if(e.inputSchema){let o=s;return await Promise.resolve(o(r,n))}else{let o=s;return await Promise.resolve(o(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,o={...n,taskStore:n.taskStore},a=s?await Promise.resolve(i.createTask(s,o)):await Promise.resolve(i.createTask(o)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await n.taskStore.getTask(c);if(!d)throw new We(rt.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(fl(XE)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(XE,async e=>{switch(e.params.ref.type){case"ref/prompt":return fY(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return hY(e),this.handleResourceCompletion(e,e.params.ref);default:throw new We(rt.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new We(rt.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new We(rt.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return p_;let i=tl(n.argsSchema)?.[e.params.argument.name];if(!gB(i))return p_;let o=Hte(i);if(!o)return p_;let a=await o(e.params.argument.value,e.params.context);return Vte(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return p_;throw new We(rt.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return p_;let i=await s(e.params.argument.value,e.params.context);return Vte(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(fl(HE)),this.server.assertCanSetRequestHandler(fl(FE)),this.server.assertCanSetRequestHandler(fl(VE)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(HE,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([i,o])=>o.enabled).map(([i,o])=>({uri:i,name:o.name,...o.metadata})),s=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let o=await i.resourceTemplate.listCallback(r);for(let a of o.resources)s.push({...i.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(FE,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(VE,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new We(rt.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let o=i.resourceTemplate.uriTemplate.match(n.toString());if(o)return i.readCallback(n,o,r)}throw new We(rt.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(fl(KE)),this.server.assertCanSetRequestHandler(fl(ZE)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(KE,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?EEe(r.argsSchema):void 0}))})),this.server.setRequestHandler(ZE,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new We(rt.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new We(rt.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=V0(n.argsSchema),i=await EE(s,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=CE(c);throw new We(rt.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let o=i.data,a=n.callback;return await Promise.resolve(a(o,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,void 0,r,s,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,void 0,r,s,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,n,s,i){let o={name:e,title:r,metadata:s,readCallback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=o)),typeof a.name<"u"&&(o.name=a.name),typeof a.title<"u"&&(o.title=a.title),typeof a.metadata<"u"&&(o.metadata=a.metadata),typeof a.callback<"u"&&(o.readCallback=a.callback),typeof a.enabled<"u"&&(o.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=o,o}_createRegisteredResourceTemplate(e,r,n,s,i){let o={resourceTemplate:n,title:r,metadata:s,readCallback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=o)),typeof u.title<"u"&&(o.title=u.title),typeof u.template<"u"&&(o.resourceTemplate=u.template),typeof u.metadata<"u"&&(o.metadata=u.metadata),typeof u.callback<"u"&&(o.readCallback=u.callback),typeof u.enabled<"u"&&(o.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,r,n,s,i){let o={title:r,description:n,argsSchema:s===void 0?void 0:jf(s),callback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=o)),typeof a.title<"u"&&(o.title=a.title),typeof a.description<"u"&&(o.description=a.description),typeof a.argsSchema<"u"&&(o.argsSchema=jf(a.argsSchema)),typeof a.callback<"u"&&(o.callback=a.callback),typeof a.enabled<"u"&&(o.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,s&&Object.values(s).some(c=>{let u=c instanceof Zs?c._def?.innerType:c;return gB(u)})&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,r,n,s,i,o,a,c,u){yB(e);let l={title:r,description:n,inputSchema:Fte(s),outputSchema:Fte(i),annotations:o,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&yB(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=jf(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=jf(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,i,o;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(xB(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!xB(r[0])&&(o=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);o=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,s,i,o,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:i,inputSchema:o,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,s,i,o,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());let i=r[0],o=this._createRegisteredPrompt(e,void 0,n,s,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:i,argsSchema:o}=r,a=this._createRegisteredPrompt(e,s,i,o,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var AEe={type:"object",properties:{}};function Kte(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Zte(t){return"_def"in t||"_zod"in t||Kte(t)}function xB(t){return typeof t!="object"||t===null||Zte(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Kte)}function Fte(t){if(t){if(xB(t))return jf(t);if(!Zte(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function EEe(t){let e=tl(t);return e?Object.entries(e).map(([r,n])=>{let s=CJ(n),i=kJ(n);return{name:r,description:s,required:!i}}):[]}function fl(t){let r=tl(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=kE(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Vte(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var p_={completion:{values:[],hasMore:!1}};import Wte from"node:process";var UC=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
329
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),CEe(r)}clear(){this._buffer=void 0}};function CEe(t){return sY.parse(JSON.parse(t))}function Gte(t){return JSON.stringify(t)+`
|
|
330
|
+
`}var qC=class{constructor(e=Wte.stdin,r=Wte.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new UC,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Gte(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{promises as bB}from"node:fs";import*as mm from"node:path";var Xte=".oioxo",kEe="rules.md",Jte="memory.md",TEe=40,IEe=4e3;async function _B(t){try{return(await bB.readFile(t,"utf8")).trim()}catch{return""}}async function vB(t){let e=mm.join(t,Xte);return{rules:await _B(mm.join(e,kEe)),memory:await _B(mm.join(e,Jte))}}async function Yte(t,e){let r=e.replace(/\s+/g," ").trim();if(!r)return;let n=mm.join(t,Xte);await bB.mkdir(n,{recursive:!0});let s=mm.join(n,Jte),o=(await _B(s)).split(`
|
|
331
|
+
`).map(c=>c.trim()).filter(c=>c.startsWith("- ")),a=r.toLowerCase();for(o=o.filter(c=>c.slice(2).toLowerCase()!==a),o.push(`- ${r}`);o.length>TEe||o.join(`
|
|
332
|
+
`).length>IEe;)o.shift();await bB.writeFile(s,o.join(`
|
|
161
333
|
`)+`
|
|
162
|
-
`,"utf8")}function
|
|
334
|
+
`,"utf8")}function wB(t){let e=[];return t.rules&&e.push(`PROJECT RULES (from .oioxo/rules.md \u2014 always follow these):
|
|
163
335
|
${t.rules}`),t.memory&&e.push(`PROJECT MEMORY (facts OIOXO learned about this project, on-device):
|
|
164
336
|
${t.memory}`),e.join(`
|
|
165
337
|
|
|
166
|
-
`)}var
|
|
167
|
-
${
|
|
168
|
-
Free accounts include a monthly context allowance; OIOXO Pro is unlimited \u2192 ${
|
|
169
|
-
It resets ${new Date(t.resetsAt).toUTCString()}. OIOXO Pro is unlimited \u2192 ${
|
|
338
|
+
`)}$o();var PEe="0.1.0",REe=6e4,Na=t=>({content:[{type:"text",text:t}]});async function SB(){if(!await Uc())return{ok:!1,message:`OIOXO context engine is linked to an OIOXO account.
|
|
339
|
+
${Em}
|
|
340
|
+
Free accounts include a monthly context allowance; OIOXO Pro is unlimited \u2192 ${xl}`};let t=await ms("check");return t?t.optimize?{ok:!0,state:t}:t.tier==="anon"?{ok:!1,message:`Your OIOXO session expired. ${Em}`}:{ok:!1,message:`Your OIOXO Free monthly context allowance is used (${t.savedThisMonth.toLocaleString()} tokens saved this month).
|
|
341
|
+
It resets ${new Date(t.resetsAt).toUTCString()}. OIOXO Pro is unlimited \u2192 ${xl}`}:{ok:!1,message:"OIOXO could not verify your plan (oioxo.com unreachable). Retrieval is paused until the connection returns."}}async function Qte(t){let e=new DC({name:"oioxo",version:PEe}),r=[],n=new qc,s=0,i=null,o=async()=>{if(!(Date.now()-s<REe&&r.length))return i||(i=(async()=>{r=await Yf(t),n.build(r),s=Date.now()})().finally(()=>{i=null})),i};e.tool("get_context","ALWAYS call this FIRST, before reading or searching files yourself. Returns the minimal relevant slice of this codebase for a task: the exact code in play plus the API surface of its real dependencies \u2014 typically 10-20x fewer tokens than reading the files. Powered by OIOXO, 100% on-device.",{query:Pf.string().describe("The task or question, in natural language (include identifiers/error text when you have them).")},async({query:c})=>{let u=await SB();if(!u.ok)return Na(u.message);await o();let l=w_(c,r,n);if(!l.text)return Na("No relevant code found for that query in this workspace.");l.savedTokens>0&&ms("report",l.savedTokens);let d=wB(await vB(t)),f=`OIOXO context capsule \u2014 files: ${l.files.join(", ")} (\u2248${l.savedTokens.toLocaleString()} tokens saved vs reading full files)`;return Na([f,d,l.text].filter(Boolean).join(`
|
|
170
342
|
|
|
171
|
-
`))}),e.tool("get_skeleton","The API surface of one file \u2014 signatures, no implementation bodies. Use to learn how to CALL code without paying for its full text.",{path
|
|
343
|
+
`))}),e.tool("get_skeleton","The API surface of one file \u2014 signatures, no implementation bodies. Use to learn how to CALL code without paying for its full text.",{path:Pf.string().describe("Workspace-relative file path.")},async({path:c})=>{let u=await SB();if(!u.ok)return Na(u.message);await o();let l=r.find(p=>p.path===c.replace(/\\/g,"/"));if(!l)return Na(`File not found in the OIOXO index: ${c}`);let d=v_(l.path,l.content),f=Math.max(0,Math.round((l.content.length-d.length)/4));return f>0&&ms("report",f),Na(d)}),e.tool("get_impact","Blast radius of a file: what it imports and everything that imports IT. Call before refactoring or deleting to know what may break.",{path:Pf.string().describe("Workspace-relative file path.")},async({path:c})=>{let u=await SB();if(!u.ok)return Na(u.message);await o();let l=c.replace(/\\/g,"/"),d=__(r),f=d.deps.get(l)??[],p=d.dependents.get(l)??[];return Na(`OIOXO impact graph for ${l}
|
|
172
344
|
|
|
173
345
|
IMPORTS (its dependencies):
|
|
174
|
-
${f.map(
|
|
346
|
+
${f.map(m=>` ${m}`).join(`
|
|
175
347
|
`)||" (none in-project)"}
|
|
176
348
|
|
|
177
349
|
IMPORTED BY (changing ${l} may break these):
|
|
178
|
-
${
|
|
179
|
-
`)||" (none \u2014 no in-project callers)"}`)}),e.tool("remember","Save one durable fact about THIS project to .oioxo/memory.md (on-device, shared with the OIOXO IDEs). Use for decisions, conventions, gotchas worth keeping.",{fact
|
|
350
|
+
${p.map(m=>` ${m}`).join(`
|
|
351
|
+
`)||" (none \u2014 no in-project callers)"}`)}),e.tool("remember","Save one durable fact about THIS project to .oioxo/memory.md (on-device, shared with the OIOXO IDEs). Use for decisions, conventions, gotchas worth keeping.",{fact:Pf.string().describe("The fact, one concise sentence.")},async({fact:c})=>(await Yte(t,c),Na("Saved to .oioxo/memory.md."))),e.tool("recall","This project's rules and learned memory from .oioxo/ (same files the OIOXO IDEs maintain). Call when starting work in an unfamiliar repo.",{},async()=>{let c=wB(await vB(t));return Na(c||"No .oioxo/rules.md or memory.md in this project yet.")});let a=new qC;await e.connect(a)}$o();var AB=(()=>{try{return"0.5.0"}catch{}try{return OEe(import.meta.url)("../../package.json").version}catch{return"0.0.0"}})(),ere=`OIOXO ${AB} \u2014 context engine + terminal coding agent (https://oioxo.com)
|
|
180
352
|
|
|
181
353
|
Usage: oioxo <command> [options]
|
|
182
354
|
|
|
@@ -204,11 +376,18 @@ Agents (MCP):
|
|
|
204
376
|
mcp list Show which agents OIOXO is wired into
|
|
205
377
|
serve Run the MCP server over stdio (agents call this; you rarely will)
|
|
206
378
|
|
|
379
|
+
Devices (Compute Mesh):
|
|
380
|
+
invite Show a code; the device that has the project scans it. This
|
|
381
|
+
machine then lends its coder to that build (same account + Wi-Fi).
|
|
382
|
+
join Scan/paste the code from the device that has the project, and
|
|
383
|
+
lend this machine's compute to it.
|
|
384
|
+
stop-helping How to stop lending (Ctrl+C in the helper's terminal).
|
|
385
|
+
|
|
207
386
|
Maintenance:
|
|
208
387
|
doctor Check creds, connection, coder config, and agent wiring
|
|
209
388
|
update How to update the OIOXO CLI
|
|
210
389
|
--version, -v Print the version
|
|
211
390
|
--help, -h Show this help
|
|
212
|
-
`;async function
|
|
213
|
-
OIOXO status`),console.log(` Control plane : ${
|
|
214
|
-
`),console.log(
|
|
391
|
+
`;async function NEe(t){console.log(`
|
|
392
|
+
OIOXO status`),console.log(` Control plane : ${gn}`);let e=await Ma();if(!e||e.expiresAt<=Date.now())console.log(" Account : not connected \u2014 run `oioxo-mcp login`");else{let i=Math.max(0,Math.round((e.expiresAt-Date.now())/864e5));console.log(` Account : connected (credential valid ~${i}d)`);let o=await ms("check");o?.tier==="pro"?console.log(" Plan : OIOXO Pro \u2014 unlimited context engine"):o?.tier==="free"?console.log(` Plan : OIOXO Free \u2014 ${o.remainingTokens?.toLocaleString()??0} saved-tokens left this month (resets ${new Date(o.resetsAt).toUTCString()})`):console.log(o?` Plan : ${o.tier}`:" Plan : could not reach oioxo.com")}let r=await Yf(t),s=new qc().build(r);console.log(` Index : ${s.files} files, ${s.chunks} chunks (in-memory, on-device)`)}async function BEe(){let[t,...e]=process.argv.slice(2),r=process.cwd();switch(t){case"code":await x$(r,e);return;case"login":await b_();return;case"logout":await IB(),console.log("OIOXO credential removed from this machine.");return;case"whoami":await WW();return;case"usage":await XW(e);return;case"config":await m$(e);return;case"model":await ZW(e);return;case"mcp":await GW(e);return;case"mesh":await eE(e);return;case"invite":await eE(["invite",...e]);return;case"join":await eE(["join",...e]);return;case"stop-helping":console.log("To stop helping, press Ctrl+C in the terminal that is running `oioxo invite`/`oioxo join`.");return;case"doctor":await JW();return;case"update":YW(AB);return;case"init":{let n=e.includes("--all"),s=e.indexOf("--command"),i=s>=0?e[s+1]:void 0;await BB(r,{all:n,command:i});return}case"serve":await Qte(r);return;case"status":await NEe(r);return;case"--version":case"-v":case"version":console.log(AB);return;case"--help":case"-h":case"help":case void 0:console.log(ere);return;default:console.log(`oioxo: unknown command "${t}"
|
|
393
|
+
`),console.log(ere),process.exitCode=1}}BEe().catch(t=>{console.error(`oioxo-mcp: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
|