ball2d 0.2.3 → 0.3.2-next.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/README.md +16 -22
- package/dist/browser.js +7500 -3564
- package/dist/core.wasm +0 -0
- package/dist/licenses/native.json +6 -0
- package/dist/licenses/valibot.txt +9 -0
- package/dist/node.js +33 -33
- package/dist/stadiums/asphalt.ball2dstadium +515 -0
- package/dist/stadiums/{big_hockey.hbs → asphalt_arena.ball2dstadium} +118 -119
- package/dist/stadiums/{big.hbs → big.ball2dstadium} +16 -16
- package/dist/stadiums/{big_easy.hbs → big_easy.ball2dstadium} +16 -16
- package/dist/stadiums/{big_rounded.hbs → big_rounded.ball2dstadium} +20 -20
- package/dist/stadiums/{classic.hbs → classic.ball2dstadium} +16 -16
- package/dist/stadiums/courtyard.ball2dstadium +611 -0
- package/dist/stadiums/{easy.hbs → easy.ball2dstadium} +16 -16
- package/dist/stadiums/{huge.hbs → huge.ball2dstadium} +16 -16
- package/dist/stadiums/meadow.ball2dstadium +611 -0
- package/dist/stadiums/provenance.json +36 -20
- package/dist/stadiums/{rounded.hbs → rounded.ball2dstadium} +20 -20
- package/dist/stadiums/{small.hbs → small.ball2dstadium} +16 -16
- package/dist/stadiums/{hockey.hbs → street_five.ball2dstadium} +82 -83
- package/dist/stadiums/training_green.ball2dstadium +611 -0
- package/dist/types/browser.d.ts +10 -0
- package/dist/types/commentary.d.ts +276 -0
- package/dist/types/config.d.ts +3 -0
- package/dist/types/creation.d.ts +3 -0
- package/dist/types/match-intelligence.d.ts +128 -0
- package/dist/types/match-state.d.ts +8 -2
- package/dist/types/match-xg-runtime.d.ts +37 -0
- package/dist/types/match-xg.d.ts +88 -0
- package/dist/types/node.d.ts +6 -2
- package/dist/types/player.d.ts +2 -0
- package/dist/types/replay.d.ts +1 -1
- package/dist/types/room-geo.d.ts +6 -0
- package/dist/types/room-hooks.d.ts +48 -0
- package/dist/types/room.d.ts +29 -31
- package/package.json +2 -1
package/dist/node.js
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/promises";import{createRequire as n}from"module";import{createCipheriv as r,createDecipheriv as i,createHash as a,createHmac as o,createSign as s,randomBytes as c,randomUUID as l,timingSafeEqual as u,webcrypto as d}from"crypto";import{createSocket as f}from"dgram";import p from"node:process";import*as m from"node:os";import h from"node:os";import g from"node:tty";import*as _ from"node:net";import{connect as v,createServer as y,isIP as b,isIPv4 as x,isIPv6 as S}from"node:net";import*as C from"node:tls";import{isIPv4 as w}from"net";import*as T from"node:crypto";import{setTimeout as E}from"timers/promises";import{promises as D}from"node:dns";import*as O from"node:timers/promises";import{EventEmitter as k}from"node:events";import{performance as A}from"perf_hooks";var j=Object.create,M=Object.defineProperty,N=Object.getOwnPropertyDescriptor,P=Object.getOwnPropertyNames,F=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty,L=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},R=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),z=(e,t)=>{let n={};for(var r in e)M(n,r,{get:e[r],enumerable:!0});return t||M(n,Symbol.toStringTag,{value:`Module`}),n},B=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=P(t),a=0,o=i.length,s;a<o;a++)s=i[a],!I.call(e,s)&&s!==n&&M(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=N(t,s))||r.enumerable});return e},V=(e,t,n)=>(n=e==null?{}:j(F(e)),B(t||!e||!e.__esModule||!I.call(e,`default`)?M(n,`default`,{value:e,enumerable:!0}):n,e)),ee=e=>I.call(e,`module.exports`)?e[`module.exports`]:B(M({},`__esModule`,{value:!0}),e),te=e(import.meta.url),ne=`/api/v1`,re={rooms:`${ne}/rooms`,sdkRooms:`${ne}/sdk/rooms`,account:`${ne}/account`,accountConfig:`${ne}/account/config`,profile:`${ne}/account/profile`,notifications:`${ne}/account/notifications`,keys:`${ne}/account/keys`,signal:e=>`${ne}/rooms/${encodeURIComponent(e)}/signal`,lease:e=>`${ne}/sdk/rooms/${encodeURIComponent(e)}/lease`};function ie(e){if(!e||typeof e!=`object`)throw Error(`Invalid room authorization response`);let t=e;if(typeof t.leaseId!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t.leaseId)||typeof t.expiresAt!=`number`||!Number.isSafeInteger(t.expiresAt)||typeof t.validForMs!=`number`||!Number.isFinite(t.validForMs)||t.validForMs<=0||t.validForMs>9e4)throw Error(`Invalid room authorization response`);return t}var ae=class{origin;apiKey;roomId;expired;grant;deadline=0;expiry;renewal;abort=new AbortController;pending=Promise.resolve();stopped;failures=0;started=!1;constructor(e,t,n,r,i,a){if(this.origin=e,this.apiKey=t,this.roomId=n,this.expired=a,!/^[0-9a-f]{10}$/.test(n))throw Error(`Invalid room authorization response`);this.grant=ie(r),this.accept(this.grant,i)}accept(e,t){if(e.leaseId!==this.grant.leaseId)throw Error(`Room authorization changed unexpectedly`);let n=t+e.validForMs;if(performance.now()>=n)throw Error(`Room authorization expired during the request`);this.grant=e,this.deadline=n,clearTimeout(this.expiry),this.expiry=setTimeout(()=>this.end(`Room authorization expired.`),Math.max(0,n-performance.now()))}start(){this.started||this.abort.signal.aborted||(this.started=!0,this.pending=this.refresh())}end(e){clearTimeout(this.expiry),clearTimeout(this.renewal),this.abort.abort(),this.expired(e)}async refresh(){let e=performance.now(),t=!1;try{let n=await fetch(new URL(re.lease(this.roomId),this.origin),{method:`POST`,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify({leaseId:this.grant.leaseId}),redirect:`error`,signal:AbortSignal.any([this.abort.signal,AbortSignal.timeout(8e3)])});if(!n.ok)throw t=[400,401,403,404,409,410].includes(n.status),await n.body?.cancel(),Error(`Room authorization could not be renewed.`);let r=await n.json();t=!0;let i=ie(r.lease);if(this.abort.signal.aborted)return;if(performance.now()>=this.deadline)throw Error(`Room authorization expired.`);this.accept(i,e),this.failures=0}catch{if(this.abort.signal.aborted)return;if(t){this.end(`Room authorization ended.`);return}this.failures++}if(!this.abort.signal.aborted){let e=this.failures?Math.min(5e3*2**Math.min(this.failures-1,3),3e4):3e4;this.renewal=setTimeout(()=>{this.pending=this.refresh()},Math.max(0,Math.min(e,this.deadline-performance.now())))}}stop(){return this.stopped?this.stopped:(clearTimeout(this.expiry),clearTimeout(this.renewal),this.abort.abort(),this.stopped=(async()=>{await this.pending;try{await(await fetch(new URL(re.lease(this.roomId),this.origin),{method:`DELETE`,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify({leaseId:this.grant.leaseId}),redirect:`error`,signal:AbortSignal.timeout(3e3)})).body?.cancel()}catch{}})(),this.stopped)}};function oe(e){return e===0||e===1||e===2}function se(e,t){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=t}function ce(e){let{score:t,minutes:n,locked:r,kickRate:i}=e;return!se(t,99)||!se(n,99)||typeof r!=`boolean`||i!==void 0&&!se(i,6619135)?null:{score:t,minutes:n,locked:r,kickRate:i}}function le(e,t,n){return t!==void 0&&(e.admin||!n&&t===e)}function ue(e,t,n){return t!==void 0&&e.admin&&t!==e&&!n(t)}var de=n(`/`),fe;try{fe=de(`worker_threads`),fe.Worker,fe.isMarkedAsUntransferable}catch{}var pe=Uint8Array,me=Uint16Array,he=Int32Array,ge=new pe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),_e=new pe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ve=new pe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ye=function(e,t){for(var n=new me(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new he(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},fe=ye(ge,2),be=fe.b,xe=fe.r;be[28]=258,xe[258]=28;for(var Se=ye(_e,0),Ce=Se.b,we=Se.r,Te=new me(32768),Ee=0;Ee<32768;++Ee){var De=(Ee&43690)>>1|(Ee&21845)<<1;De=(De&52428)>>2|(De&13107)<<2,De=(De&61680)>>4|(De&3855)<<4,Te[Ee]=((De&65280)>>8|(De&255)<<8)>>1}for(var Oe=(function(e,t,n){for(var r=e.length,i=0,a=new me(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new me(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new me(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Te[d]>>c]=l}else for(s=new me(r),i=0;i<r;++i)e[i]&&(s[i]=Te[o[e[i]-1]++]>>15-e[i]);return s}),ke=new pe(288),Ee=0;Ee<144;++Ee)ke[Ee]=8;for(var Ee=144;Ee<256;++Ee)ke[Ee]=9;for(var Ee=256;Ee<280;++Ee)ke[Ee]=7;for(var Ee=280;Ee<288;++Ee)ke[Ee]=8;for(var Ae=new pe(32),Ee=0;Ee<32;++Ee)Ae[Ee]=5;var je=Oe(ke,9,0),Me=Oe(ke,9,1),Ne=Oe(Ae,5,0),Pe=Oe(Ae,5,1),Fe=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Ie=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Le=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Re=function(e){return(e+7)/8|0},ze=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new pe(e.subarray(t,n))},Be=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],Ve=function(e,t,n){var r=Error(t||Be[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Ve),!n)throw r;return r},He=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new pe(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new pe(i*3));var l=function(e){var t=n.length;if(e>t){var r=new pe(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Ie(e,d,1);var v=Ie(e,d+1,3);if(d+=3,!v){var y=Re(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&Ve(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}if(v==1)p=Me,m=Pe,h=9,g=5;else if(v==2){var S=Ie(e,d,31)+257,C=Ie(e,d+10,15)+4,w=S+Ie(e,d+5,31)+1;d+=14;for(var T=new pe(w),E=new pe(19),D=0;D<C;++D)E[ve[D]]=Ie(e,d+D*3,7);d+=C*3;for(var O=Fe(E),k=(1<<O)-1,A=Oe(E,O,1),D=0;D<w;){var j=A[Ie(e,d,k)];d+=j&15;var y=j>>4;if(y<16)T[D++]=y;else{var M=0,N=0;for(y==16?(N=3+Ie(e,d,3),d+=2,M=T[D-1]):y==17?(N=3+Ie(e,d,7),d+=3):y==18&&(N=11+Ie(e,d,127),d+=7);N--;)T[D++]=M}}var P=T.subarray(0,S),F=T.subarray(S);h=Fe(P),g=Fe(F),p=Oe(P,h,1),m=Oe(F,g,1)}else Ve(1);if(d>_){c&&Ve(0);break}}s&&l(f+131072);for(var I=(1<<h)-1,L=(1<<g)-1,R=d;;R=d){var M=p[Le(e,d)&I],z=M>>4;if(d+=M&15,d>_){c&&Ve(0);break}if(M||Ve(2),z<256)n[f++]=z;else if(z==256){R=d,p=null;break}else{var B=z-254;if(z>264){var D=z-257,V=ge[D];B=Ie(e,d,(1<<V)-1)+be[D],d+=V}var ee=m[Le(e,d)&L],te=ee>>4;ee||Ve(3),d+=ee&15;var F=Ce[te];if(te>3){var V=_e[te];F+=Le(e,d)&(1<<V)-1,d+=V}if(d>_){c&&Ve(0);break}s&&l(f+131072);var ne=f+B;if(f<F){var re=a-F,ie=Math.min(F,ne);for(re+f<0&&Ve(3);f<ie;++f)n[f]=r[re+f]}for(;f<ne;++f)n[f]=n[f-F]}}t.l=p,t.p=R,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?ze(n,0,f):n.subarray(0,f)},Ue=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},We=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},Ge=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,a=n.slice();if(!i)return{t:Qe,l:0};if(i==1){var o=new pe(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var s=n[0],c=n[1],l=0,u=1,d=2;for(n[0]={s:-1,f:s.f+c.f,l:s,r:c};u!=i-1;)s=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:s.f+c.f,l:s,r:c};for(var f=a[0].s,r=1;r<i;++r)a[r].s>f&&(f=a[r].s);var p=new me(f+1),m=Ke(n[u-1],p,0);if(m>t){var r=0,h=0,g=m-t,_=1<<g;for(a.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});r<i;++r){var v=a[r].s;if(p[v]>t)h+=_-(1<<m-p[v]),p[v]=t;else break}for(h>>=g;h>0;){var y=a[r].s;p[y]<t?h-=1<<t-p[y]++-1:++r}for(;r>=0&&h;--r){var b=a[r].s;p[b]==t&&(--p[b],++h)}m=t}return{t:new pe(p),l:m}},Ke=function(e,t,n){return e.s==-1?Math.max(Ke(e.l,t,n+1),Ke(e.r,t,n+1)):t[e.s]=n},qe=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new me(++t),r=0,i=e[0],a=1,o=function(e){n[r++]=e},s=1;s<=t;++s)if(e[s]==i&&s!=t)++a;else{if(!i&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(i),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(i);a=1,i=e[s]}return{c:n.subarray(0,r),n:t}},Je=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Ye=function(e,t,n){var r=n.length,i=Re(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},Xe=function(e,t,n,r,i,a,o,s,c,l,u){Ue(t,u++,n),++i[256];for(var d=Ge(i,15),f=d.t,p=d.l,m=Ge(a,15),h=m.t,g=m.l,_=qe(f),v=_.c,y=_.n,b=qe(h),x=b.c,S=b.n,C=new me(19),w=0;w<v.length;++w)++C[v[w]&31];for(var w=0;w<x.length;++w)++C[x[w]&31];for(var T=Ge(C,7),E=T.t,D=T.l,O=19;O>4&&!E[ve[O-1]];--O);var k=l+5<<3,A=Je(i,ke)+Je(a,Ae)+o,j=Je(i,f)+Je(a,h)+o+14+3*O+Je(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&k<=A&&k<=j)return Ye(t,u,e.subarray(c,c+l));var M,N,P,F;if(Ue(t,u,1+(j<A)),u+=2,j<A){M=Oe(f,p,0),N=f,P=Oe(h,g,0),F=h;var I=Oe(E,D,0);Ue(t,u,y-257),Ue(t,u+5,S-1),Ue(t,u+10,O-4),u+=14;for(var w=0;w<O;++w)Ue(t,u+3*w,E[ve[w]]);u+=3*O;for(var L=[v,x],R=0;R<2;++R)for(var z=L[R],w=0;w<z.length;++w){var B=z[w]&31;Ue(t,u,I[B]),u+=E[B],B>15&&(Ue(t,u,z[w]>>5&127),u+=z[w]>>12)}}else M=je,N=ke,P=Ne,F=Ae;for(var w=0;w<s;++w){var V=r[w];if(V>255){var B=V>>18&31;We(t,u,M[B+257]),u+=N[B+257],B>7&&(Ue(t,u,V>>23&31),u+=ge[B]);var ee=V&31;We(t,u,P[ee]),u+=F[ee],ee>3&&(We(t,u,V>>5&8191),u+=_e[ee])}else We(t,u,M[V]),u+=N[V]}return We(t,u,M[256]),u+N[256]},Ze=new he([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Qe=new pe(0),$e=function(e,t,n,r,i,a){var o=a.z||e.length,s=new pe(r+o+5*(1+Math.ceil(o/7e3))+i),c=s.subarray(r,s.length-i),l=a.l,u=(a.r||0)&7;if(t){u&&(c[0]=a.r>>3);for(var d=Ze[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new me(32768),g=a.h||new me(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new he(25e3),x=new me(288),S=new me(32),C=0,w=0,T=a.i||0,E=0,D=a.w||0,O=0;T+2<o;++T){var k=y(T),A=T&32767,j=g[k];if(h[A]=j,g[k]=A,D<=T){var M=o-T;if((C>7e3||E>24576)&&(M>423||!l)){u=Xe(e,c,0,b,x,S,w,E,O,T-O,u),E=C=w=0,O=T;for(var N=0;N<286;++N)x[N]=0;for(var N=0;N<30;++N)S[N]=0}var P=2,F=0,I=p,L=A-j&32767;if(M>2&&k==y(T-L))for(var R=Math.min(f,M)-1,z=Math.min(32767,T),B=Math.min(258,M);L<=z&&--I&&A!=j;){if(e[T+P]==e[T+P-L]){for(var V=0;V<B&&e[T+V]==e[T+V-L];++V);if(V>P){if(P=V,F=L,V>R)break;for(var ee=Math.min(L,V-2),te=0,N=0;N<ee;++N){var ne=T-L+N&32767,re=ne-h[ne]&32767;re>te&&(te=re,j=ne)}}}A=j,j=h[A],L+=A-j&32767}if(F){b[E++]=268435456|xe[P]<<18|we[F];var ie=xe[P]&31,ae=we[F]&31;w+=ge[ie]+_e[ae],++x[257+ie],++S[ae],D=T+P,++C}else b[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,D);T<o;++T)b[E++]=e[T],++x[e[T]];u=Xe(e,c,l,b,x,S,w,E,O,T-O,u),l||(a.r=u&7|c[u/8|0]<<3,u-=7,a.h=g,a.p=h,a.i=T,a.w=D)}else{for(var T=a.w||0;T<o+l;T+=65535){var oe=T+65535;oe>=o&&(c[u/8|0]=l,oe=o),u=Ye(c,u+1,e.subarray(T,oe))}a.i=o}return ze(s,0,r+Re(u)+i)},et=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new pe(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return $e(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,i)};function tt(e,t){return et(e,t||{},0,0)}var nt=function(){function e(e,t){typeof e==`function`&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new pe(32768),this.p=new pe(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||Ve(5),this.d&&Ve(4),!this.p.length)this.p=e;else if(e.length){var t=new pe(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=He(this.p,this.s,this.o);this.ondata(ze(n,t,this.s.b),this.d),this.o=ze(n,this.s.b-32768),this.s.b=this.o.length,this.p=ze(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),rt=typeof TextDecoder<`u`&&new TextDecoder;try{rt.decode(Qe,{stream:!0})}catch{}var it=5389,at=(e,t,n)=>Number.isInteger(e)&&e>=t&&e<=n,ot=e=>Number.isFinite(e)&&e>=1&&e<=1e5,st=class{core;enabled=!1;constructor(e){if(this.core=e,e.surface_state_capacity()!==5389)throw Error(`Unsupported surface state version`)}configure(e){if(!at(e.seed,0,4294967295)||!ot(e.halfWidth)||!ot(e.halfHeight)||!at(e.moisturePermille,0,1e3))throw Error(`Invalid surface configuration`);if(!this.core.surface_configure(e.seed,e.halfWidth,e.halfHeight,e.moisturePermille))throw Error(`Surface configuration rejected`);this.enabled=!0}disable(){this.core.surface_disable(),this.enabled=!1}setWeather(e){if(!at(e.rainMilliMmH,0,2e5)||!at(e.temperatureMilliC,-3e4,6e4)||!at(e.humidityPermille,0,1e3)||!at(e.windMilliMS,0,6e4))throw Error(`Invalid surface weather`);if(!this.core.surface_weather(e.rainMilliMmH,e.temperatureMilliC,e.humidityPermille,e.windMilliMS))throw Error(`Surface is disabled`)}sample(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw Error(`Invalid surface position`);return{traction:this.core.surface_sample(e,t,0),rollingDrag:this.core.surface_sample(e,t,1),waterMm:this.core.surface_sample(e,t,2),compaction:this.core.surface_sample(e,t,3)}}snapshot(){let e=this.core.surface_save();if(e===0)return[];if(e!==5389)throw Error(`Invalid surface checkpoint size`);return Array.from(this.buffer())}restore(e){if(!Array.isArray(e)||e.length!==0&&e.length!==5389||!e.every(e=>at(e,0,4294967295))||(e.length&&this.buffer().set(e),!this.core.surface_restore(e.length)))throw Error(`Invalid surface checkpoint`);this.enabled=e.length>0}buffer(){let e=this.core.surface_state_ptr();return new Uint32Array(this.core.memory.buffer,e,it)}},ct=131072,lt=49152,ut=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});var dt=(e,t)=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=t;function ft(e,t){if(!dt(t,65535)||!dt(e.tick,4294967295)||!Array.isArray(e.surface)||e.surface.length!==5389)throw Error(`Invalid terrain snapshot`);let n=ut.encode(JSON.stringify(e));if(n.length>ct)throw Error(`Terrain snapshot exceeds size limit`);let r=tt(n,{level:1});if(r.length>lt)throw Error(`Compressed terrain snapshot exceeds size limit`);let i=``;for(let e of r)i+=String.fromCharCode(e);return{type:`terrain-state`,epoch:t,tick:e.tick,payload:btoa(i)}}function pt(e){let t=new AbortController,n=()=>t.abort(e?.reason);e?.aborted?n():e?.addEventListener(`abort`,n,{once:!0});let r=setTimeout(()=>t.abort(new DOMException(`Room startup timed out`,`TimeoutError`)),15e3);return{signal:t.signal,async run(e){let n,r=new Promise((e,t)=>{n=t}),i=()=>n(t.signal.reason);t.signal.addEventListener(`abort`,i,{once:!0}),t.signal.aborted&&i();try{return await Promise.race([e,r])}finally{t.signal.removeEventListener(`abort`,i)}},dispose(){clearTimeout(r),e?.removeEventListener(`abort`,n)}}}async function mt(e,t){let n=`Room creation failed (${e.status})`,r=e.body?.getReader();if(!r)return Error(n);let i=()=>{r.cancel().catch(()=>{})};t.addEventListener(`abort`,i,{once:!0});try{if(t.throwIfAborted(),e.status<400||e.status>=500||e.headers.get(`content-type`)?.split(`;`)[0].trim()!==`application/json`)return Error(n);let i=new Uint8Array(2048),a=0;for(;;){let e=await r.read();if(t.throwIfAborted(),e.done)break;if(a+e.value.byteLength>i.length)return Error(n);i.set(e.value,a),a+=e.value.byteLength}let o=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(i.subarray(0,a)));if(!o||typeof o!=`object`)return Error(n);let s=o.error;return typeof s!=`string`||!s.trim()||s.length>300||/[<>]/.test(s)||[...s].some(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127)?Error(n):Error(`${s.trim()} (${e.status})`)}catch{return t.throwIfAborted(),Error(n)}finally{t.removeEventListener(`abort`,i),i(),r.releaseLock()}}var ht=class{stream;sequence=0;pending=[];lastSent=-1/0;constructor(e=crypto.randomUUID()){this.stream=e}checkpoint(){return{stream:this.stream,sequence:this.sequence}}capture(e,t){let n=(e.ballKicks??[]).map(n=>({sequence:++this.sequence,tick:e.tick,epoch:t,slot:n,x:e.data[0],y:e.data[1]}));return this.pending.push(...n),this.pending.length>8&&this.pending.splice(0,this.pending.length-8),n}drain(e){if(!this.pending.length||e-this.lastSent<50)return;this.lastSent=e;let t=this.pending;return this.pending=[],{type:`match-kicks`,stream:this.stream,events:t}}};function gt(e,t){if(t)for(let n of e.peers.values())n.control?.readyState===`open`&&n.control.bufferedAmount<16384&&e.control(n,t)}var _t=new Set([`noPlayer`,`playerName`,`roomName`,`maxPlayers`,`password`,`public`,`stadium`]);function vt(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Room configuration must be an object`);for(let t of Object.keys(e)){if(t===`token`)throw Error(`External service tokens are not supported. Ball2D join verification is configured on the room.`);if(t===`geo`)throw Error(`Geolocation overrides are not supported. Room country comes from the host connection.`);if(!_t.has(t))throw Error(`Unknown room setting: ${t}`)}let t={...e};if(typeof t.roomName!=`string`||!t.roomName.trim()||t.roomName.length>64)throw Error(`Room name must contain 1–64 characters`);for(let e of[`public`,`noPlayer`])if(t[e]!==void 0&&typeof t[e]!=`boolean`)throw Error(`Invalid ${e} setting: expected a boolean`);if(t.maxPlayers!==void 0&&(typeof t.maxPlayers!=`number`||!Number.isInteger(t.maxPlayers)||t.maxPlayers<2||t.maxPlayers>32))throw Error(`maxPlayers must be an integer between 2 and 32`);if(t.password!==void 0&&(typeof t.password!=`string`||t.password.length>64))throw Error(`Password must be a string of at most 64 characters`);if(t.stadium!==void 0&&typeof t.stadium!=`string`)throw Error(`Stadium must be an HBS source string`);if(t.noPlayer===!1&&t.playerName!==void 0&&(typeof t.playerName!=`string`||!t.playerName.trim()||t.playerName.length>24))throw Error(`Invalid host player name`);return{roomName:t.roomName,maxPlayers:t.maxPlayers??16,password:t.password??``,public:t.public??!0,noPlayer:t.noPlayer??!0,playerName:t.noPlayer===!1?(t.playerName??`Host`).trim():void 0,stadium:t.stadium}}function yt(e){return/^(?:[0-9a-f]{10}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.test(e)?e.toLowerCase():null}function bt(e){let t=yt(e);if(!t)throw Error(`Invalid room code`);return`/r/${t}`}function xt(e,t,n){if(!Number.isFinite(e)||!Number.isInteger(t)||t<0||t>16777215||!Array.isArray(n)||n.length<1||n.length>3||n.some(e=>!Number.isInteger(e)||e<0||e>16777215))throw Error(`Invalid team colors`);return{angle:(e%360+360)%360,textColor:t,colors:[...n]}}function St(e){if(e===void 0)return[null,null];if(!Array.isArray(e)||e.length!==2)throw Error(`Invalid team styles`);return e.map(e=>e===null?null:xt(e.angle,e.textColor,e.colors))}var Ct=[`normal`,`bold`,`italic`,`small`,`small-bold`,`small-italic`];function wt(e,t,n,r){if(typeof e!=`string`||e.length>1e3)throw Error(`Announcement exceeds 1000 characters`);if(t!=null&&(!Number.isInteger(t)||t<0||t>16777215))throw Error(`Invalid announcement color`);if(n!=null&&!Ct.includes(n))throw Error(`Invalid announcement style`);if(r!=null&&![0,1,2].includes(r))throw Error(`Invalid announcement sound`);return{type:`announcement`,text:e,color:t??null,style:n??`normal`,sound:r??1}}function Tt(e){return e===null||typeof e==`string`&&Array.from(e).length<=2&&!/[\p{Cc}\p{Cf}]/u.test(e)}var Et=[[`x`,0,-8192,8192],[`y`,1,-8192,8192],[`xspeed`,2,-8192,8192],[`yspeed`,3,-8192,8192],[`xgravity`,8,-8192,8192],[`ygravity`,9,-8192,8192],[`radius`,4,.5,100],[`bCoeff`,7,-1,8192],[`invMass`,5,0,8192],[`damping`,6,0,8192],[`color`,-1,-1,16777215],[`cMask`,11,-2147483648,2147483647],[`cGroup`,10,-2147483648,2147483647]];function Dt(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid disc property update`);let t=e,n={};for(let e=0;e<Et.length;e++){let[r,,i,a]=Et[e],o=t[r];if(o==null)continue;if(typeof o!=`number`||!Number.isFinite(o))throw Error(`Invalid disc property: ${r}`);let s=e<10?Math.fround(o):o|0;if(!Number.isFinite(s)||s<Math.fround(i)||s>a)throw Error(`Invalid disc property: ${r}`);n[r]=s}return n}var Ot=`5a27b77ea69c9f5e179f`,kt={Space_Separator:/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ID_Start:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\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\u0AF9\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-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\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-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\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-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\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\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},At={isSpaceSeparator(e){return typeof e==`string`&&kt.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||kt.ID_Start.test(e))},isIdContinueChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===``||e===``||kt.ID_Continue.test(e))},isDigit(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}},jt,Mt,Nt,Pt,Ft,It,Lt,Rt,zt,Bt=function(e,t){jt=String(e),Mt=`start`,Nt=[],Pt=0,Ft=1,It=0,Lt=void 0,Rt=void 0,zt=void 0;do Lt=qt(),tn[Mt]();while(Lt.type!==`eof`);return typeof t==`function`?Vt({"":zt},``,t):zt};function Vt(e,t,n){let r=e[t];if(typeof r==`object`&&r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=String(e),i=Vt(r,t,n);i===void 0?delete r[t]:Object.defineProperty(r,t,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let e in r){let t=Vt(r,e,n);t===void 0?delete r[e]:Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}}return n.call(e,t,r)}var Ht,Ut,Wt,Gt,Kt;function qt(){for(Ht=`default`,Ut=``,Wt=!1,Gt=1;;){Kt=Jt();let e=Yt[Ht]();if(e)return e}}function Jt(){if(jt[Pt])return String.fromCodePoint(jt.codePointAt(Pt))}function H(){let e=Jt();return e===`
|
|
2
|
-
`?(
|
|
3
|
-
`:case`\r`:case`\u2028`:case`\u2029`:H();return;case`/`:H(),
|
|
4
|
-
`:case`\r`:case`\u2028`:case`\u2029`:H(),
|
|
5
|
-
`:case`\r`:throw
|
|
6
|
-
`;case`r`:return H(),`\r`;case`t`:return H(),` `;case`v`:return H(),`\v`;case`0`:if(H(),
|
|
7
|
-
`:case`\u2028`:case`\u2029`:return H(),``;case`\r`:return H(),
|
|
8
|
-
`&&H(),``;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:throw
|
|
1
|
+
import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/promises";import{createRequire as n}from"module";import{createCipheriv as r,createDecipheriv as i,createHash as a,createHmac as o,createSign as s,randomBytes as c,randomUUID as l,timingSafeEqual as u,webcrypto as d}from"crypto";import{createSocket as f}from"dgram";import p from"node:process";import*as m from"node:os";import h from"node:os";import g from"node:tty";import*as _ from"node:net";import{connect as v,createServer as y,isIP as b,isIPv4 as x,isIPv6 as S}from"node:net";import*as C from"node:tls";import{isIPv4 as w}from"net";import*as T from"node:crypto";import{setTimeout as E}from"timers/promises";import{promises as D}from"node:dns";import*as O from"node:timers/promises";import{EventEmitter as k}from"node:events";import{performance as A}from"perf_hooks";var j=Object.create,M=Object.defineProperty,N=Object.getOwnPropertyDescriptor,P=Object.getOwnPropertyNames,F=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty,L=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},R=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ee=(e,t)=>{let n={};for(var r in e)M(n,r,{get:e[r],enumerable:!0});return t||M(n,Symbol.toStringTag,{value:`Module`}),n},z=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=P(t),a=0,o=i.length,s;a<o;a++)s=i[a],!I.call(e,s)&&s!==n&&M(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=N(t,s))||r.enumerable});return e},B=(e,t,n)=>(n=e==null?{}:j(F(e)),z(t||!e||!e.__esModule||!I.call(e,`default`)?M(n,`default`,{value:e,enumerable:!0}):n,e)),te=e=>I.call(e,`module.exports`)?e[`module.exports`]:z(M({},`__esModule`,{value:!0}),e),ne=e(import.meta.url),re=`/api/v1`,ie={rooms:`${re}/rooms`,sdkRooms:`${re}/sdk/rooms`,account:`${re}/account`,accountConfig:`${re}/account/config`,profile:`${re}/account/profile`,profileVisibility:`${re}/account/profile/visibility`,publicProfile:(e,t)=>`${re}/community/${e}/${encodeURIComponent(t)}`,notifications:`${re}/account/notifications`,keys:`${re}/account/keys`,signal:e=>`${re}/rooms/${encodeURIComponent(e)}/signal`,liveness:e=>`${re}/rooms/${encodeURIComponent(e)}/liveness`,lease:e=>`${re}/sdk/rooms/${encodeURIComponent(e)}/lease`},ae={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function oe(e){return e?{lang:e?.lang??void 0,message:e?.message,abortEarly:e?.abortEarly??void 0,abortPipeEarly:e?.abortPipeEarly??void 0}:ae}function se(e){let t=typeof e;return t===`string`?`"${e}"`:t===`number`||t===`bigint`||t===`boolean`?`${e}`:t===`object`||t===`function`?(e&&Object.getPrototypeOf(e)?.constructor?.name)??`null`:t}function ce(e,t,n,r,i){let a=i&&`input`in i?i.input:n.value,o=i?.expected??e.expects??null,s=i?.received??se(a),c={kind:e.kind,type:e.type,input:a,expected:o,received:s,message:`Invalid ${t}: ${o?`Expected ${o} but r`:`R`}eceived ${s}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=e.kind===`schema`,u=i?.message??e.message??(e.reference,c.lang,void 0)??(l?(c.lang,void 0):null)??r.message??(c.lang,void 0);u!==void 0&&(c.message=typeof u==`function`?u(c):u),l&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}function le(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function ue(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??`never`}function de(e){return e[`~standard`]={version:1,vendor:`valibot`,validate:t=>e[`~run`]({value:t},oe())},e}function fe(e,t){return{kind:`validation`,type:`check`,reference:fe,async:!1,expects:null,requirement:e,message:t,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&ce(this,`input`,e,t),e}}}function pe(e){return{kind:`validation`,type:`finite`,reference:pe,async:!1,expects:null,requirement:Number.isFinite,message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&ce(this,`finite`,e,t),e}}}function me(e,t){return{kind:`validation`,type:`gt_value`,reference:me,async:!1,expects:`>${e instanceof Date?e.toJSON():se(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value>this.requirement)&&ce(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():se(e.value)}),e}}}function he(e){return{kind:`validation`,type:`integer`,reference:he,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&ce(this,`integer`,e,t),e}}}function ge(e,t){return{kind:`validation`,type:`max_length`,reference:ge,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&e.value.length>this.requirement&&ce(this,`length`,e,t,{received:`${e.value.length}`}),e}}}function _e(e,t){return{kind:`validation`,type:`max_value`,reference:_e,async:!1,expects:`<=${e instanceof Date?e.toJSON():se(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value<=this.requirement)&&ce(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():se(e.value)}),e}}}function ve(e,t){return{kind:`validation`,type:`min_length`,reference:ve,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&e.value.length<this.requirement&&ce(this,`length`,e,t,{received:`${e.value.length}`}),e}}}function ye(e,t){return{kind:`validation`,type:`min_value`,reference:ye,async:!1,expects:`>=${e instanceof Date?e.toJSON():se(e)}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!(e.value>=this.requirement)&&ce(this,`value`,e,t,{received:e.value instanceof Date?e.value.toJSON():se(e.value)}),e}}}function be(e){return{kind:`transformation`,type:`raw_transform`,reference:be,async:!1,"~run"(t,n){let r=e({dataset:t,config:n,addIssue:e=>ce(this,e?.label??`input`,t,n,e),NEVER:null});return t.issues?t.typed=!1:t.value=r,t}}}function xe(e,t){return{kind:`validation`,type:`regex`,reference:xe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&ce(this,`format`,e,t),e}}}function Se(e){return{kind:`validation`,type:`safe_integer`,reference:Se,async:!1,expects:null,requirement:Number.isSafeInteger,message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&ce(this,`safe integer`,e,t),e}}}var Ce={abortEarly:!0};function we(e,t,n){return typeof e.fallback==`function`?e.fallback(t,n):e.fallback}function Te(e,t,n){return typeof e.default==`function`?e.default(t,n):e.default}function Ee(e,t){return!e[`~run`]({value:t},Ce).issues}function De(e,t){return de({kind:`schema`,type:`array`,reference:De,expects:`Array`,async:!1,item:e,message:t,"~run"(e,t){let n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<n.length;r++){let i=n[r],a=this.item[`~run`]({value:i},t);if(a.issues){let o={type:`array`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),e.value.push(a.value)}}else ce(this,`type`,e,t);return e}})}function Oe(e){return de({kind:`schema`,type:`boolean`,reference:Oe,expects:`boolean`,async:!1,message:e,"~run"(e,t){return typeof e.value==`boolean`?e.typed=!0:ce(this,`type`,e,t),e}})}function ke(e,t){return de({kind:`schema`,type:`custom`,reference:ke,expects:`unknown`,async:!1,check:e,message:t,"~run"(e,t){return this.check(e.value)?e.typed=!0:ce(this,`type`,e,t),e}})}function Ae(e,t){return de({kind:`schema`,type:`literal`,reference:Ae,expects:se(e),async:!1,literal:e,message:t,"~run"(e,t){return le(e.value,this.literal)?e.typed=!0:ce(this,`type`,e,t),e}})}function je(e,t){return de({kind:`schema`,type:`nullable`,reference:je,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(e,t){return e.value===null&&(this.default!==void 0&&(e.value=Te(this,e,t)),e.value===null)?(e.typed=!0,e):this.wrapped[`~run`](e,t)}})}function Me(e){return de({kind:`schema`,type:`number`,reference:Me,expects:`number`,async:!1,message:e,"~run"(e,t){return typeof e.value==`number`&&!isNaN(e.value)?e.typed=!0:ce(this,`type`,e,t),e}})}function Ne(e,t){return de({kind:`schema`,type:`object`,reference:Ne,expects:`Object`,async:!1,entries:e,message:t,"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=this.entries[r];if(r in n||(i.type===`exact_optional`||i.type===`optional`||i.type===`nullish`)&&i.default!==void 0){let a=r in n?n[r]:Te(i),o=i[`~run`]({value:a},t);if(o.issues){let i={type:`object`,origin:`value`,input:n,key:r,value:a};for(let t of o.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(i.fallback!==void 0)e.value[r]=we(i);else if(i.type!==`exact_optional`&&i.type!==`optional`&&i.type!==`nullish`&&(ce(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}}else ce(this,`type`,e,t);return e}})}function Pe(e,t){return de({kind:`schema`,type:`optional`,reference:Pe,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(e,t){return e.value===void 0&&(this.default!==void 0&&(e.value=Te(this,e,t)),e.value===void 0)?(e.typed=!0,e):this.wrapped[`~run`](e,t)}})}function Fe(e,t){return de({kind:`schema`,type:`picklist`,reference:Fe,expects:ue(e.map(se),`|`),async:!1,options:e,message:t,"~run"(e,t){return this.options.includes(e.value)?e.typed=!0:ce(this,`type`,e,t),e}})}function Ie(e,t){return de({kind:`schema`,type:`strict_object`,reference:Ie,expects:`Object`,async:!1,entries:e,message:t,"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=this.entries[r];if(r in n||(i.type===`exact_optional`||i.type===`optional`||i.type===`nullish`)&&i.default!==void 0){let a=r in n?n[r]:Te(i),o=i[`~run`]({value:a},t);if(o.issues){let i={type:`object`,origin:`value`,input:n,key:r,value:a};for(let t of o.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(i.fallback!==void 0)e.value[r]=we(i);else if(i.type!==`exact_optional`&&i.type!==`optional`&&i.type!==`nullish`&&(ce(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}if(!e.issues||!t.abortEarly){for(let r in n)if(!Object.prototype.hasOwnProperty.call(this.entries,r)){ce(this,`key`,e,t,{input:r,expected:`never`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]});break}}}else ce(this,`type`,e,t);return e}})}function Le(e){return de({kind:`schema`,type:`string`,reference:Le,expects:`string`,async:!1,message:e,"~run"(e,t){return typeof e.value==`string`?e.typed=!0:ce(this,`type`,e,t),e}})}function Re(e,t){return de({kind:`schema`,type:`tuple`,reference:Re,expects:`Array`,async:!1,items:e,message:t,"~run"(e,t){let n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<this.items.length;r++){let i=n[r],a=this.items[r][`~run`]({value:i},t);if(a.issues){let o={type:`array`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),e.value.push(a.value)}}else ce(this,`type`,e,t);return e}})}function ze(e){let t;if(e)for(let n of e)if(t)for(let e of n.issues)t.push(e);else t=n.issues;return t}function Be(e,t){return de({kind:`schema`,type:`union`,reference:Be,expects:ue(e.map(e=>e.expects),`|`),async:!1,options:e,message:t,"~run"(e,t){let n,r,i;for(let a of this.options){let o=a[`~run`]({value:e.value},t);if(o.typed){if(o.issues)r?r.push(o):r=[o];else{n=o;break}}else i?i.push(o):i=[o]}if(n)return n;if(r){if(r.length===1)return r[0];ce(this,`type`,e,t,{issues:ze(r)}),e.typed=!0}else if(i?.length===1)return i[0];else ce(this,`type`,e,t,{issues:ze(i)});return e}})}function Ve(){return de({kind:`schema`,type:`unknown`,reference:Ve,expects:`unknown`,async:!1,"~run"(e){return e.typed=!0,e}})}function He(e,t,n){return de({kind:`schema`,type:`variant`,reference:He,expects:`Object`,async:!1,key:e,options:t,message:n,"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){let r,i=0,a=this.key,o=[],s=(e,c)=>{for(let l of e.options){if(l.type===`variant`)s(l,new Set(c).add(l.key));else{let e=!0,s=0;for(let t of c){let r=l.entries[t];if(t in n?r[`~run`]({typed:!1,value:n[t]},Ce).issues:r.type!==`exact_optional`&&r.type!==`optional`&&r.type!==`nullish`){e=!1,a!==t&&(i<s||i===s&&t in n&&!(a in n))&&(i=s,a=t,o=[]),a===t&&o.push(l.entries[t].expects);break}s++}if(e){let e=l[`~run`]({value:n},t);(!r||!r.typed&&e.typed)&&(r=e)}}if(r&&!r.issues)break}};if(s(this,new Set([this.key])),r)return r;ce(this,`type`,e,t,{input:n[a],expected:ue(o,`|`),path:[{type:`object`,origin:`value`,input:n,key:a,value:n[a]}]})}else ce(this,`type`,e,t);return e}})}function Ue(...e){return de({...e[0],pipe:e,"~run"(t,n){for(let r of e)if(r.kind!==`metadata`){if(t.issues&&(r.kind===`schema`||r.kind===`transformation`)){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r[`~run`](t,n))}return t}})}function We(e,t,n){let r=e[`~run`]({value:t},oe(n));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}var Ge=Ue(Le(),xe(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)),Ke=Ue(Me(),Se()),qe=e=>Ue(ke(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),e),Je=e=>qe(Ie(e));(e=>qe(Ne(e)))({error:Le()}),Je({password:Ve()}),Je({password:Ve(),verifier:Ve()}),Je({verifier:Ve()}),Je({verified:Oe()});var Ye=Ne({leaseId:Ge,expiresAt:Ke,validForMs:Ue(Me(),pe(),me(0),_e(9e4))}),Xe=Ne({error:Ue(Le(),ge(300),fe(e=>e.trim()!==``),fe(e=>!/[<>]/.test(e)),fe(e=>!/[\u0000-\u001f\u007f]/.test(e)))});function Ze(e){let t=We(Ye,e);if(!t.success)throw Error(`Invalid room authorization response`);return t.output}var Qe=class{origin;apiKey;roomId;stopped;grant;constructor(e,t,n,r,i){if(this.origin=e,this.apiKey=t,this.roomId=n,!/^[0-9a-f]{10}$/.test(n))throw Error(`Invalid room authorization response`);if(this.grant=Ze(r),performance.now()>=i+this.grant.validForMs)throw Error(`Room authorization expired during the request`)}stop(){return this.stopped||=(async()=>{try{await(await fetch(new URL(ie.lease(this.roomId),this.origin),{method:`DELETE`,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify({leaseId:this.grant.leaseId}),redirect:`error`,signal:AbortSignal.timeout(3e3)})).body?.cancel()}catch{}})(),this.stopped}},$e=(e,t)=>e!==t&&(e-t+65536)%65536>32768;function et(e){return!!e&&[`lobby`,`playing`,`goal`,`finished`].includes(e.phase)&&Number.isFinite(e.elapsed)&&e.elapsed>=0&&Number.isFinite(e.timeLimit)&&e.timeLimit>=0&&Number.isSafeInteger(e.scoreLimit)&&e.scoreLimit>=0&&!!e.score&&Number.isSafeInteger(e.score.red)&&e.score.red>=0&&Number.isSafeInteger(e.score.blue)&&e.score.blue>=0}function tt(e,t){let[n,r]=e.p0,i=e.p1[0]-n,a=e.p1[1]-r,o=Math.hypot(i,a);if(![n,r,i,a,...e.pitchPoint,t.x,t.y,t.vx,t.vy].every(Number.isFinite)||o<.001||e.defendingTeam!==1&&e.defendingTeam!==2)return null;let s=((e.pitchPoint[0]-n)*a-(e.pitchPoint[1]-r)*i)/o;if(Math.abs(s)<.001)return null;let c=Math.sign(s);return{along:((t.x-n)*i+(t.y-r)*a)/o,across:c*((t.x-n)*a-(t.y-r)*i)/o,length:o,alongSpeed:(t.vx*i+t.vy*a)/o,acrossSpeed:c*(t.vx*a-t.vy*i)/o}}var nt={post:100,"near-miss":90,block:80,"directed-shot":70,pressure:60},rt=class{ticksPerSecond;streamId=null;epoch=-1;tick=-1;goals=[];shot=null;constructor(e=60){if(this.ticksPerSecond=e,!Number.isFinite(e)||e<=0)throw Error(`Invalid tick rate`)}reset(){this.streamId=null,this.epoch=this.tick=-1,this.goals=[],this.shot=null}observe(e){if(!et(e.context)||!Number.isSafeInteger(e.tick)||!Number.isSafeInteger(e.epoch)||e.tick<0||e.epoch<0||!Number.isFinite(e.ball.radius)||e.ball.radius<=0||e.goals.length>32)return[];if(this.streamId!==e.streamId||this.epoch!==e.epoch){if(this.streamId===e.streamId&&$e(e.epoch,this.epoch))return[];this.reset(),this.streamId=e.streamId,this.epoch=e.epoch}if(e.tick<=this.tick)return[];let t=this.tick>=0&&e.tick-this.tick<=this.ticksPerSecond/4;if(t||(this.goals=[],this.shot=null),this.tick=e.tick,e.context.phase!==`playing`||e.context.paused)return this.goals=[],this.shot=null,[];this.shot&&e.tick-this.shot.tick>this.ticksPerSecond*2&&(this.shot=null);let n=[],r=[],i=(t,r,i,a,o,s)=>{if(n.length>=4){let e=n.reduce((e,t,r)=>nt[t.kind]<nt[n[e].kind]?r:e,0);if(nt[t]<=nt[n[e].kind])return;n.splice(e,1)}n.push(Object.freeze({eventId:`${e.streamId}:${e.epoch}:analysis:${e.tick}:${r.id}:${t}`,streamId:e.streamId,epoch:e.epoch,tick:e.tick,kind:t,context:Object.freeze({...e.context,score:Object.freeze({...e.context.score})}),confidence:`supported`,evidence:Object.freeze(a),attackingTeam:r.defendingTeam===1?2:1,intensity:i,...o?{player:Object.freeze({...o})}:{},...s?{attackId:s}:{}}))};for(let n of e.goals){let a=tt(n,e.ball);if(!a||r.some(e=>e.id===n.id))continue;let o=`${n.p0}:${n.p1}:${n.pitchPoint}:${n.defendingTeam}`,s=this.goals.find(e=>e.id===n.id&&e.shape===o),c={id:n.id,shape:o,previous:a,pressure:s?.pressure??!1,lastReactionTick:s?.lastReactionTick??-1/0,attackId:s?.attackId??null,attackStartedTick:s?.attackStartedTick??e.tick},{along:l,across:u,length:d,acrossSpeed:f,alongSpeed:p}=a,m=f<-.001?-u/f:1/0,h=l+p*m,g=u>e.ball.radius&&m>0&&m<=1.2&&h>=e.ball.radius&&h<=d-e.ball.radius,_=g&&u<=d*2.5;!_&&(u>d*3||f>=0)&&(c.pressure=!1),(u>d*3||e.tick-c.attackStartedTick>this.ticksPerSecond*6)&&(c.attackId=null),_&&!c.attackId&&(c.attackId=`${e.streamId}:${e.epoch}:attack:${e.tick}:${n.id}`,c.attackStartedTick=e.tick);let v=e.contact;g&&v?.kind===`kick`&&v.player?.team!==n.defendingTeam&&v.player&&(this.shot={goalId:n.id,tick:e.tick,player:{...v.player}},i(`directed-shot`,n,.6,[`observed-kick`,`projected-inside-goal-mouth`],v.player,c.attackId)),_&&!c.pressure&&t&&(c.pressure=!0,i(`pressure`,n,.45,[`approaching-field-side`,`projected-inside-goal-mouth`],void 0,c.attackId));let y=e.tick-c.lastReactionTick>=this.ticksPerSecond*2;if(y&&v?.kind===`post`&&v.goalId===n.id)c.lastReactionTick=e.tick,this.shot=null,i(`post`,n,.75,[`classified-post-contact`,`explicit-goal-id`],void 0,c.attackId),c.attackId=null;else if(y&&t&&s&&s.previous.across>0&&u<=0){let t=s.previous.across/(s.previous.across-u),r=s.previous.along+t*(l-s.previous.along),a=r<0?-r:r-d;a>e.ball.radius&&a<=d*.35&&f<0&&(c.lastReactionTick=e.tick,this.shot=null,i(`near-miss`,n,.62,[`observed-line-crossing`,`outside-posts`,`within-near-miss-band`],void 0,c.attackId),c.attackId=null)}this.shot?.goalId===n.id&&t&&v?.kind===`player`&&v.player?.team===n.defendingTeam&&s?.previous.acrossSpeed!==void 0&&s.previous.acrossSpeed<0&&f>=0&&(i(`block`,n,.55,[`prior-directed-kick`,`defender-contact`,`trajectory-reversed`],v.player,c.attackId),this.shot=null,c.attackId=null),(v?.kind===`wall`||v?.kind===`net`)&&(this.shot=null,c.attackId=null),f>=0&&(c.attackId=null),r.push(c)}return this.goals=r,n.sort((e,t)=>nt[t.kind]-nt[e.kind])}},it=e=>`${e.sessionId.length}:${e.sessionId}:${e.playerId}:${e.team}`,at=e=>Object.freeze({...e}),ot=(e,t=1e9)=>Number.isFinite(e)&&Math.abs(e)<=t,st=e=>typeof e==`string`&&e.length>0&&e.length<=256,ct=e=>!!e&&st(e.sessionId)&&Number.isSafeInteger(e.playerId)&&e.playerId>=0&&e.playerId<=2147483647&&(e.team===1||e.team===2);function lt(e){if(!e||!st(e.streamId)||!Number.isSafeInteger(e.epoch)||e.epoch<0||e.epoch>65535||!Number.isSafeInteger(e.tick)||e.tick<0||!et(e.context)||!e.ball||!Array.isArray(e.players)||e.players.length>32||!Array.isArray(e.goals)||e.goals.length>32||!Array.isArray(e.contacts)||e.contacts.length>32||typeof e.contactsComplete!=`boolean`||![e.ball.x,e.ball.y,e.ball.vx,e.ball.vy,e.ball.radius].every(e=>ot(e))||e.ball.radius<.001||e.ball.radius>1e6)return!1;let t=new Set;for(let n of e.players){if(!n||!ct(n.identity)||![n.x,n.y,n.vx,n.vy,n.radius].every(e=>ot(e))||n.radius<.001||n.radius>1e6||n.role!==void 0&&n.role!==`goalkeeper`&&n.role!==`outfield`)return!1;let e=it(n.identity);if(t.has(e))return!1;t.add(e)}let n=new Set;for(let t of e.goals){if(!t||!st(t.id)||!Array.isArray(t.p0)||t.p0.length!==2||!Array.isArray(t.p1)||t.p1.length!==2||!Array.isArray(t.pitchPoint)||t.pitchPoint.length!==2||![...t.p0,...t.p1,...t.pitchPoint].every(e=>ot(e))||n.has(t.id)||!tt(t,e.ball))return!1;n.add(t.id)}let r=-1,i=new Set;for(let a of e.contacts){if(!a||!st(a.id)||i.has(a.id)||!Number.isSafeInteger(a.tick)||a.tick<0||a.tick>e.tick||a.tick<r||![`kick`,`player`,`wall`,`post`].includes(a.kind)||a.player&&(!ct(a.player)||!t.has(it(a.player)))||(a.kind===`kick`||a.kind===`player`)&&!a.player||a.goalId!==void 0&&!n.has(a.goalId))return!1;r=a.tick,i.add(a.id)}return!0}function ut(e,t){let n;for(let r of e.goals){if(r.defendingTeam===t)continue;let i=tt(r,e.ball);!i||i.across<=e.ball.radius||(!n||i.across/i.length<n.projection.across/n.projection.length)&&(n={goal:r,projection:i})}return n}function dt(e,t,n){let r=e.goals.find(e=>e.id===t),i=r&&tt(r,e.ball);if(!i||i.across<=e.ball.radius||i.acrossSpeed>=0)return!1;let a=i.across/-i.acrossSpeed,o=i.along+i.alongSpeed*a;return a<=n&&o>e.ball.radius&&o<i.length-e.ball.radius}function ft(e,t,n,r){let i=Math.hypot(e.ball.vx,e.ball.vy);if(!(i<e.ball.radius*5))return e.players.find(a=>{if(a.identity.team!==t.team||it(a.identity)===it(t))return!1;let o=a.x-e.ball.x,s=a.y-e.ball.y,c=(o*e.ball.vx+s*e.ball.vy)/i,l=Math.abs(o*e.ball.vy-s*e.ball.vx)/i;return c>=e.ball.radius*r&&c/i<=n/1e3&&l<=a.radius+e.ball.radius*2})}function pt(e,t,n){let r=e.goals.find(e=>e.id===t);if(!r)return;let i=tt(r,e.ball);if(!i)return;let a=Math.atan2(r.p0[1]-e.ball.y,r.p0[0]-e.ball.x),o=Math.atan2(r.p1[1]-e.ball.y,r.p1[0]-e.ball.x),s=Math.abs(Math.atan2(Math.sin(a-o),Math.cos(a-o))),c=(r.p0[0]+r.p1[0])/2-e.ball.x,l=(r.p0[1]+r.p1[1])/2-e.ball.y,u=c*c+l*l,d=0;for(let t of e.players){if(t.identity.team===n)continue;let r=((t.x-e.ball.x)*c+(t.y-e.ball.y)*l)/u;r>0&&r<1&&Math.hypot(t.x-e.ball.x-r*c,t.y-e.ball.y-r*l)<=t.radius+e.ball.radius&&d++}return Object.freeze({distanceGoalWidths:i.across/i.length,openingAngleRadians:s,speedBallRadiiPerSecond:Math.hypot(e.ball.vx,e.ball.vy)/e.ball.radius,defendersInLane:d})}var mt=`kick-team-goal-before-next-kick-v1`,ht=(e,t=256)=>typeof e==`string`&&e.length>0&&e.length<=t&&e.trim()===e&&!/\p{Cc}/u.test(e),gt=(e,t=1e9)=>typeof e==`number`&&Number.isFinite(e)&&Math.abs(e)<=t,_t=(e,t)=>e.sessionId===t.sessionId&&e.playerId===t.playerId&&e.team===t.team,vt=e=>!!e&&ht(e.sessionId)&&Number.isInteger(e.playerId)&&e.playerId>=0&&e.playerId<=2147483647&&(e.team===1||e.team===2);function yt(e,t,n){if(!e||!ht(e.id)||e.tick!==t.tick||e.order!==n||!Number.isInteger(e.contactIndex)||e.contactIndex<0||e.contactIndex>=t.contacts.length||!vt(e.player)||!e.ball||!Array.isArray(e.players)||e.players.length>32||e.players.length!==t.players.length)return!1;let r=t.contacts[e.contactIndex];if(r.kind!==`kick`||r.tick!==t.tick||!r.player||!_t(r.player,e.player))return!1;let i=e.ball;return!(![i.x,i.y,i.radius,i.beforeVx,i.beforeVy,i.afterVx,i.afterVy].every(e=>gt(e))||i.radius<.001||i.radius>1e6)}function bt(e,t){let n=new Set;for(let r of e.players){if(!r||!vt(r.identity)||![r.x,r.y,r.radius].every(e=>gt(e))||r.radius<.001||r.radius>1e6||!t.players.some(e=>_t(e.identity,r.identity)))return!1;let e=it(r.identity);if(n.has(e))return!1;n.add(e)}return e.players.some(t=>_t(t.identity,e.player))}function xt(e,t,n){return yt(e,t,n)&&bt(e,t)}var St=[`sessionId`,`playerId`,`team`],Ct=[`identity`,`x`,`y`,`radius`],wt=[`id`,`tick`,`order`,`contactIndex`,`player`,`ball`,`players`],Tt=[`x`,`y`,`radius`,`beforeVx`,`beforeVy`,`afterVx`,`afterVy`],Et=[`players`],Dt=[`identity`];function Ot(e,t){return!!e&&typeof e==`object`&&Object.isFrozen(e)&&t.every(t=>{let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&`value`in n})}function kt(e){return Array.isArray(e)&&Object.isFrozen(e)&&Object.getPrototypeOf(e)===Array.prototype&&!Object.hasOwn(e,Symbol.iterator)&&!Object.hasOwn(e,`some`)}function At(e){if(!Ot(e,Et)||!kt(e.players)||e.players.length<=16||e.players.length>32)return null;let t=new Set;for(let n=0;n<e.players.length;n++){let r=Object.getOwnPropertyDescriptor(e.players,n);if(!r||!(`value`in r))return null;let i=r.value;if(!Ot(i,Dt)||!Ot(i.identity,St)||!vt(i.identity))return null;t.add(it(i.identity))}return t}function jt(e,t){if(!kt(e))return null;let n=new Set;for(let r=0;r<e.length;r++){let i=Object.getOwnPropertyDescriptor(e,r);if(!i||!(`value`in i))return null;let a=i.value;if(!Ot(a,Ct)||!Ot(a.identity,St)||!vt(a.identity)||![a.x,a.y,a.radius].every(e=>gt(e))||a.radius<.001||a.radius>1e6)return null;let o=it(a.identity);if(!t.has(o)||n.has(o))return null;n.add(o)}return n}function Mt(e,t){if(!e.length)return!0;let n=At(t);if(!n)return!e.some((n,r)=>!xt(n,t,r)||r>0&&n.contactIndex<=e[r-1].contactIndex);let r=new Map;return!e.some((i,a)=>{let o;if(Ot(i,wt)&&Ot(i.player,St)&&Ot(i.ball,Tt)){if(!yt(i,t,a))return!0;let e=r.get(i.players);e===void 0&&(e=jt(i.players,n),r.set(i.players,e)),o=e?e.has(it(i.player)):bt(i,t)}else o=xt(i,t,a);return!o||a>0&&i.contactIndex<=e[a-1].contactIndex})}function Nt(e,t,n){let r={x:e.ball.x,y:e.ball.y,radius:e.ball.radius,vx:n.featureStage===`pre-kick`?e.ball.beforeVx:e.ball.afterVx,vy:n.featureStage===`pre-kick`?e.ball.beforeVy:e.ball.afterVy},i,a=1/0;for(let n of t.goals){let t=tt(n,r);if(n.defendingTeam===e.player.team||!t||t.across<0)continue;let o=Math.hypot((n.p0[0]+n.p1[0])/2-r.x,(n.p0[1]+n.p1[1])/2-r.y);(o<a||o===a&&i&&n.id<i.id)&&(i=n,a=o)}if(!i)return null;let o=e.ball.afterVx*((i.p0[0]+i.p1[0])/2-r.x)+e.ball.afterVy*((i.p0[1]+i.p1[1])/2-r.y);if(n.population===`goalward-release-v1`&&!(o>0))return null;let s=pt({ball:r,goals:t.goals,players:e.players},i.id,e.player.team);return!s||s.distanceGoalWidths>1e6||s.speedBallRadiiPerSecond>1e9||!Object.values(s).every(e=>Number.isFinite(e)&&e>=0)?null:Object.freeze({features:Object.freeze({...s,distanceGoalWidths:Math.max(0,s.distanceGoalWidths)}),player:at(e.player),goalId:i.id,ball:Object.freeze({...r})})}var Pt=`shot-quality-v1`,Ft=[1e6,Math.PI,1e9,32],It=/^[a-f0-9]{64}$/u,Lt=(e,t=512)=>typeof e==`string`&&e.length>0&&e.length<=t&&e.trim()===e&&!/\p{Cc}/u.test(e),Rt=e=>typeof e==`object`&&!!e&&!Array.isArray(e),zt=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,Bt=(e,t,n)=>zt(e,t,n)&&Number.isSafeInteger(e),Vt=e=>typeof e==`string`&&It.test(e),Ht=e=>Array.isArray(e)&&e.length===4&&[e[0],e[1],e[2],e[3]].every(e=>zt(e,-1e9,1e9)),Ut=e=>Ht(e)&&e.every((e,t)=>zt(e,0,Ft[t]))&&Number.isInteger(e[3]),Wt=e=>Object.freeze([e[0],e[1],e[2],e[3]]);function Gt(e){return Rt(e)&&Lt(e.engineId,128)&&Vt(e.geometrySha256)&&Vt(e.policySha256)&&e.featuresRevision===`shot-quality-v1`&&[`pre-kick`,`post-kick`,`end-step`].includes(e.featureStage)&&[`all-kicks-v1`,`goalward-release-v1`,`legacy-end-step-on-target-v1`].includes(e.population)&&e.featureStage===`end-step`==(e.population===`legacy-end-step-on-target-v1`)&&Lt(e.shotDefinitionRevision,128)&&Bt(e.outcomeHorizonMs,100,6e4)}function Kt(e){return Object.freeze({engineId:e.engineId,geometrySha256:e.geometrySha256,policySha256:e.policySha256,featuresRevision:e.featuresRevision,featureStage:e.featureStage,population:e.population,shotDefinitionRevision:e.shotDefinitionRevision,outcomeHorizonMs:e.outcomeHorizonMs})}function qt(e,t){return e.engineId===t.engineId&&e.geometrySha256===t.geometrySha256&&e.policySha256===t.policySha256&&e.featuresRevision===t.featuresRevision&&e.featureStage===t.featureStage&&e.population===t.population&&e.shotDefinitionRevision===t.shotDefinitionRevision&&e.outcomeHorizonMs===t.outcomeHorizonMs}function Jt(e,t){if(!Gt(t))return{ok:!1,reason:`invalid-domain`};let n=()=>({ok:!1,reason:`invalid-descriptor`});if(!Rt(e)||e.schemaVersion!==1||!Lt(e.id,128)||e.purpose!==`production`&&e.purpose!==`technical-fixture`||e.kind!==`logistic`||!Gt(e.domain)||!zt(e.intercept,-100,100)||!Ht(e.weights)||!e.weights.every(e=>Math.abs(e)<=100)||!Ht(e.means)||!Ht(e.scales)||!e.scales.every(e=>zt(e,1e-6,1e6))||!Ut(e.minimums)||!Ut(e.maximums)||!e.minimums.every((t,n)=>t<=e.maximums[n])||!e.means.every((t,n)=>zt(t,e.minimums[n],e.maximums[n]))||!Rt(e.evaluation)||!Rt(e.provenance))return n();let r=e.evaluation,i=e.provenance;return!Vt(r.trainingDatasetSha256)||!Vt(r.evaluationDatasetSha256)||r.trainingDatasetSha256===r.evaluationDatasetSha256||!Vt(r.evaluationReportSha256)||r.splitUnit!==`match`||!Bt(r.heldOutSamples,2,1e8)||!Bt(r.heldOutGoals,1,r.heldOutSamples-1)||!zt(r.brier,0,1)||!zt(r.logLoss,0,100)||!zt(r.ece,0,1)||!Bt(r.eceBins,2,100)||!Lt(i.provider)||!Lt(i.source)||!Lt(i.license)||!Lt(i.reviewedBy)||!Lt(i.reviewReference)?n():qt(e.domain,t)?{ok:!0,model:Object.freeze({schemaVersion:1,id:e.id,purpose:e.purpose,kind:`logistic`,domain:Kt(e.domain),intercept:e.intercept,weights:Wt(e.weights),means:Wt(e.means),scales:Wt(e.scales),minimums:Wt(e.minimums),maximums:Wt(e.maximums),evaluation:Object.freeze({trainingDatasetSha256:r.trainingDatasetSha256,evaluationDatasetSha256:r.evaluationDatasetSha256,evaluationReportSha256:r.evaluationReportSha256,splitUnit:`match`,heldOutSamples:r.heldOutSamples,heldOutGoals:r.heldOutGoals,brier:r.brier,logLoss:r.logLoss,ece:r.ece,eceBins:r.eceBins}),provenance:Object.freeze({provider:i.provider,source:i.source,license:i.license,reviewedBy:i.reviewedBy,reviewReference:i.reviewReference})}),evidence:`structure-only`}:{ok:!1,reason:`domain-mismatch`}}function Yt(e,t){return Object.freeze({xG:null,status:`uncalibrated`,reason:e,...t?{modelId:t}:{}})}function Xt(e,t,n={}){let r=e==null?null:Jt(e,t),i,a=Yt(`missing-model`);if(!Gt(t))a=Yt(`invalid-domain`);else if(r?.ok){i=r.model;let e=n?.trustedModels,o=JSON.stringify(i),s=Array.isArray(e)&&e.length<=16&&e.some(e=>{let n=Jt(e,t);return n.ok&&JSON.stringify(n.model)===o});a=i.purpose===`technical-fixture`?Yt(`technical-fixture`,i.id):s?void 0:Yt(`untrusted-model`,i.id)}else r&&(a=Yt(r.reason));let o=i&&!a?i:void 0,s=a??Yt(`untrusted-model`,i?.id);return Object.freeze({domain:Gt(t)?Kt(t):null,modelId:o?.id??null,status:o?`reviewed-model`:`uncalibrated`,estimate(e){if(!o)return s;let t=[e?.distanceGoalWidths,e?.openingAngleRadians,e?.speedBallRadiiPerSecond,e?.defendersInLane];if(!Ut(t))return Yt(`invalid-features`,o.id);if(t.some((e,t)=>e<o.minimums[t]||e>o.maximums[t]))return Yt(`outside-model-support`,o.id);let n=o.intercept;for(let e=0;e<4;e++)n+=o.weights[e]*(t[e]-o.means[e])/o.scales[e];let r=Math.exp(n>=0?-n:n),i=n>=0?1/(1+r):r/(1+r);return Object.freeze({xG:i,status:`reviewed-model`,reason:`trusted-offline-model`,modelId:o.id})}})}var Zt=`98c92c27828179bc4258`,V={X:0,Y:1,SPEED_X:2,SPEED_Y:3,RADIUS:4,INVERSE_MASS:5,DAMPING:6,BOUNCE:7,GRAVITY_X:8,GRAVITY_Y:9,COLLISION_GROUP:10,COLLISION_MASK:11,PLAYER_SLOT:12,TEAM:13,INPUT:14,KICK_STATE:15,SPAWN_X:16,SPAWN_Y:17,KICK_BUDGET:17},Qt=1023,$t=1024,en=2048,tn=[[`x`,0,-8192,8192],[`y`,1,-8192,8192],[`xspeed`,2,-8192,8192],[`yspeed`,3,-8192,8192],[`xgravity`,8,-8192,8192],[`ygravity`,9,-8192,8192],[`radius`,4,.5,100],[`bCoeff`,7,-1,8192],[`invMass`,5,0,8192],[`damping`,6,0,8192],[`color`,-1,-1,16777215],[`cMask`,11,-2147483648,2147483647],[`cGroup`,10,-2147483648,2147483647]];function nn(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid disc property update`);let t=e,n={};for(let e=0;e<tn.length;e++){let[r,,i,a]=tn[e],o=t[r];if(o==null)continue;if(typeof o!=`number`||!Number.isFinite(o))throw Error(`Invalid disc property: ${r}`);let s=e<10?Math.fround(o):o|0;if(!Number.isFinite(s)||s<Math.fround(i)||s>a)throw Error(`Invalid disc property: ${r}`);n[r]=s}return n}var rn=6619135;function an(e,t,n){if(![e,t,n].every(Number.isInteger))throw Error(`Invalid kick rate limit`);return Math.max(0,Math.min(255,e))|Math.max(0,Math.min(255,t))<<8|Math.max(0,Math.min(100,n))<<16}function on(e){return[e&255,e>>>8&255,e>>>16]}function sn(e=`Emerald Arena`,t=440,n=220){let r=[[-t,-n],[t,-n],[-t,n],[t,n],[-t,-70],[-t,70],[t,-70],[t,70],[-t-30,-70],[-t-30,70],[t+30,-70],[t+30,70],[0,-n-40],[0,-65],[0,65],[0,n+40]];return JSON.stringify({version:1,physicsMode:`substeps`,name:e,width:t+75,height:n+65,spawnDistance:t*.4,bg:{type:`grass`,width:t,height:n,kickOffRadius:65,color:`285B35`},vertexes:r.map(([e,t],n)=>({x:e,y:t,...n>=12?{cGroup:[`redKO`,`blueKO`],cMask:[`red`,`blue`]}:{cMask:[`ball`]}})),segments:[...[[0,1],[2,3],[0,4],[5,2],[1,6],[7,3],[4,8],[8,9],[9,5],[6,10],[10,11],[11,7]].map(([e,t],n)=>({v0:e,v1:t,cMask:[`ball`],color:n<6?`FFFFFF`:`C7D2CA`,bCoef:n<6?.8:.15})),{v0:12,v1:13,vis:!1,cGroup:[`redKO`,`blueKO`],cMask:[`red`,`blue`]},{v0:14,v1:15,vis:!1,cGroup:[`redKO`,`blueKO`],cMask:[`red`,`blue`]},{v0:14,v1:13,curve:-180,vis:!1,cGroup:[`redKO`],cMask:[`red`,`blue`]},{v0:14,v1:13,curve:180,vis:!1,cGroup:[`blueKO`],cMask:[`red`,`blue`]}],planes:[{normal:[0,1],dist:-n-40},{normal:[0,-1],dist:-n-40},{normal:[1,0],dist:-t-50},{normal:[-1,0],dist:-t-50}],goals:[{p0:[-t,-70],p1:[-t,70],team:`red`},{p0:[t,-70],p1:[t,70],team:`blue`}],discs:[...[-t,t].flatMap(e=>[-70,70].map(t=>({pos:[e,t],radius:6,invMass:0,color:`FFFFFF`,bCoef:.5})))],ballPhysics:{radius:9,damping:.991,bCoef:.6},playerPhysics:{radius:15,acceleration:.11,damping:.96,kickStrength:5.5}},null,2)}var cn={Space_Separator:/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ID_Start:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\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\u0AF9\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-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\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-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\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-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\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\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},ln={isSpaceSeparator(e){return typeof e==`string`&&cn.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||cn.ID_Start.test(e))},isIdContinueChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===``||e===``||cn.ID_Continue.test(e))},isDigit(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}},un,dn,fn,pn,mn,hn,gn,_n,vn,yn=function(e,t){un=String(e),dn=`start`,fn=[],pn=0,mn=1,hn=0,gn=void 0,_n=void 0,vn=void 0;do gn=En(),Pn[dn]();while(gn.type!==`eof`);return typeof t==`function`?bn({"":vn},``,t):vn};function bn(e,t,n){let r=e[t];if(typeof r==`object`&&r){if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=String(e),i=bn(r,t,n);i===void 0?delete r[t]:Object.defineProperty(r,t,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let e in r){let t=bn(r,e,n);t===void 0?delete r[e]:Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}}return n.call(e,t,r)}var xn,Sn,Cn,wn,Tn;function En(){for(xn=`default`,Sn=``,Cn=!1,wn=1;;){Tn=Dn();let e=On[xn]();if(e)return e}}function Dn(){if(un[pn])return String.fromCodePoint(un.codePointAt(pn))}function H(){let e=Dn();return e===`
|
|
2
|
+
`?(mn++,hn=0):e?hn+=e.length:hn++,e&&(pn+=e.length),e}var On={default(){switch(Tn){case` `:case`\v`:case`\f`:case` `:case`\xA0`:case``:case`
|
|
3
|
+
`:case`\r`:case`\u2028`:case`\u2029`:H();return;case`/`:H(),xn=`comment`;return;case void 0:return H(),kn(`eof`)}if(ln.isSpaceSeparator(Tn)){H();return}return On[dn]()},comment(){switch(Tn){case`*`:H(),xn=`multiLineComment`;return;case`/`:H(),xn=`singleLineComment`;return}throw Ln(H())},multiLineComment(){switch(Tn){case`*`:H(),xn=`multiLineCommentAsterisk`;return;case void 0:throw Ln(H())}H()},multiLineCommentAsterisk(){switch(Tn){case`*`:H();return;case`/`:H(),xn=`default`;return;case void 0:throw Ln(H())}H(),xn=`multiLineComment`},singleLineComment(){switch(Tn){case`
|
|
4
|
+
`:case`\r`:case`\u2028`:case`\u2029`:H(),xn=`default`;return;case void 0:return H(),kn(`eof`)}H()},value(){switch(Tn){case`{`:case`[`:return kn(`punctuator`,H());case`n`:return H(),An(`ull`),kn(`null`,null);case`t`:return H(),An(`rue`),kn(`boolean`,!0);case`f`:return H(),An(`alse`),kn(`boolean`,!1);case`-`:case`+`:H()===`-`&&(wn=-1),xn=`sign`;return;case`.`:Sn=H(),xn=`decimalPointLeading`;return;case`0`:Sn=H(),xn=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Sn=H(),xn=`decimalInteger`;return;case`I`:return H(),An(`nfinity`),kn(`numeric`,1/0);case`N`:return H(),An(`aN`),kn(`numeric`,NaN);case`"`:case`'`:Cn=H()===`"`,Sn=``,xn=`string`;return}throw Ln(H())},identifierNameStartEscape(){if(Tn!==`u`)throw Ln(H());H();let e=Nn();switch(e){case`$`:case`_`:break;default:if(!ln.isIdStartChar(e))throw zn()}Sn+=e,xn=`identifierName`},identifierName(){switch(Tn){case`$`:case`_`:case``:case``:Sn+=H();return;case`\\`:H(),xn=`identifierNameEscape`;return}if(ln.isIdContinueChar(Tn)){Sn+=H();return}return kn(`identifier`,Sn)},identifierNameEscape(){if(Tn!==`u`)throw Ln(H());H();let e=Nn();switch(e){case`$`:case`_`:case``:case``:break;default:if(!ln.isIdContinueChar(e))throw zn()}Sn+=e,xn=`identifierName`},sign(){switch(Tn){case`.`:Sn=H(),xn=`decimalPointLeading`;return;case`0`:Sn=H(),xn=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Sn=H(),xn=`decimalInteger`;return;case`I`:return H(),An(`nfinity`),kn(`numeric`,wn*(1/0));case`N`:return H(),An(`aN`),kn(`numeric`,NaN)}throw Ln(H())},zero(){switch(Tn){case`.`:Sn+=H(),xn=`decimalPoint`;return;case`e`:case`E`:Sn+=H(),xn=`decimalExponent`;return;case`x`:case`X`:Sn+=H(),xn=`hexadecimal`;return}return kn(`numeric`,wn*0)},decimalInteger(){switch(Tn){case`.`:Sn+=H(),xn=`decimalPoint`;return;case`e`:case`E`:Sn+=H(),xn=`decimalExponent`;return}if(ln.isDigit(Tn)){Sn+=H();return}return kn(`numeric`,wn*Number(Sn))},decimalPointLeading(){if(ln.isDigit(Tn)){Sn+=H(),xn=`decimalFraction`;return}throw Ln(H())},decimalPoint(){switch(Tn){case`e`:case`E`:Sn+=H(),xn=`decimalExponent`;return}if(ln.isDigit(Tn)){Sn+=H(),xn=`decimalFraction`;return}return kn(`numeric`,wn*Number(Sn))},decimalFraction(){switch(Tn){case`e`:case`E`:Sn+=H(),xn=`decimalExponent`;return}if(ln.isDigit(Tn)){Sn+=H();return}return kn(`numeric`,wn*Number(Sn))},decimalExponent(){switch(Tn){case`+`:case`-`:Sn+=H(),xn=`decimalExponentSign`;return}if(ln.isDigit(Tn)){Sn+=H(),xn=`decimalExponentInteger`;return}throw Ln(H())},decimalExponentSign(){if(ln.isDigit(Tn)){Sn+=H(),xn=`decimalExponentInteger`;return}throw Ln(H())},decimalExponentInteger(){if(ln.isDigit(Tn)){Sn+=H();return}return kn(`numeric`,wn*Number(Sn))},hexadecimal(){if(ln.isHexDigit(Tn)){Sn+=H(),xn=`hexadecimalInteger`;return}throw Ln(H())},hexadecimalInteger(){if(ln.isHexDigit(Tn)){Sn+=H();return}return kn(`numeric`,wn*Number(Sn))},string(){switch(Tn){case`\\`:H(),Sn+=jn();return;case`"`:if(Cn)return H(),kn(`string`,Sn);Sn+=H();return;case`'`:if(!Cn)return H(),kn(`string`,Sn);Sn+=H();return;case`
|
|
5
|
+
`:case`\r`:throw Ln(H());case`\u2028`:case`\u2029`:Bn(Tn);break;case void 0:throw Ln(H())}Sn+=H()},start(){switch(Tn){case`{`:case`[`:return kn(`punctuator`,H())}xn=`value`},beforePropertyName(){switch(Tn){case`$`:case`_`:Sn=H(),xn=`identifierName`;return;case`\\`:H(),xn=`identifierNameStartEscape`;return;case`}`:return kn(`punctuator`,H());case`"`:case`'`:Cn=H()===`"`,xn=`string`;return}if(ln.isIdStartChar(Tn)){Sn+=H(),xn=`identifierName`;return}throw Ln(H())},afterPropertyName(){if(Tn===`:`)return kn(`punctuator`,H());throw Ln(H())},beforePropertyValue(){xn=`value`},afterPropertyValue(){switch(Tn){case`,`:case`}`:return kn(`punctuator`,H())}throw Ln(H())},beforeArrayValue(){if(Tn===`]`)return kn(`punctuator`,H());xn=`value`},afterArrayValue(){switch(Tn){case`,`:case`]`:return kn(`punctuator`,H())}throw Ln(H())},end(){throw Ln(H())}};function kn(e,t){return{type:e,value:t,line:mn,column:hn}}function An(e){for(let t of e){if(Dn()!==t)throw Ln(H());H()}}function jn(){switch(Dn()){case`b`:return H(),`\b`;case`f`:return H(),`\f`;case`n`:return H(),`
|
|
6
|
+
`;case`r`:return H(),`\r`;case`t`:return H(),` `;case`v`:return H(),`\v`;case`0`:if(H(),ln.isDigit(Dn()))throw Ln(H());return`\0`;case`x`:return H(),Mn();case`u`:return H(),Nn();case`
|
|
7
|
+
`:case`\u2028`:case`\u2029`:return H(),``;case`\r`:return H(),Dn()===`
|
|
8
|
+
`&&H(),``;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:throw Ln(H());case void 0:throw Ln(H())}return H()}function Mn(){let e=``,t=Dn();if(!ln.isHexDigit(t)||(e+=H(),t=Dn(),!ln.isHexDigit(t)))throw Ln(H());return e+=H(),String.fromCodePoint(parseInt(e,16))}function Nn(){let e=``,t=4;for(;t-->0;){let t=Dn();if(!ln.isHexDigit(t))throw Ln(H());e+=H()}return String.fromCodePoint(parseInt(e,16))}var Pn={start(){if(gn.type===`eof`)throw Rn();Fn()},beforePropertyName(){switch(gn.type){case`identifier`:case`string`:_n=gn.value,dn=`afterPropertyName`;return;case`punctuator`:In();return;case`eof`:throw Rn()}},afterPropertyName(){if(gn.type===`eof`)throw Rn();dn=`beforePropertyValue`},beforePropertyValue(){if(gn.type===`eof`)throw Rn();Fn()},beforeArrayValue(){if(gn.type===`eof`)throw Rn();if(gn.type===`punctuator`&&gn.value===`]`){In();return}Fn()},afterPropertyValue(){if(gn.type===`eof`)throw Rn();switch(gn.value){case`,`:dn=`beforePropertyName`;return;case`}`:In()}},afterArrayValue(){if(gn.type===`eof`)throw Rn();switch(gn.value){case`,`:dn=`beforeArrayValue`;return;case`]`:In()}},end(){}};function Fn(){let e;switch(gn.type){case`punctuator`:switch(gn.value){case`{`:e={};break;case`[`:e=[]}break;case`null`:case`boolean`:case`numeric`:case`string`:e=gn.value}if(vn===void 0)vn=e;else{let t=fn[fn.length-1];Array.isArray(t)?t.push(e):Object.defineProperty(t,_n,{value:e,writable:!0,enumerable:!0,configurable:!0})}if(typeof e==`object`&&e)fn.push(e),dn=Array.isArray(e)?`beforeArrayValue`:`beforePropertyName`;else{let e=fn[fn.length-1];dn=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}}function In(){fn.pop();let e=fn[fn.length-1];dn=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}function Ln(e){return Hn(e===void 0?`JSON5: invalid end of input at ${mn}:${hn}`:`JSON5: invalid character '${Vn(e)}' at ${mn}:${hn}`)}function Rn(){return Hn(`JSON5: invalid end of input at ${mn}:${hn}`)}function zn(){return hn-=5,Hn(`JSON5: invalid identifier character at ${mn}:${hn}`)}function Bn(e){console.warn(`JSON5: '${Vn(e)}' in strings is not valid ECMAScript; consider escaping`)}function Vn(e){let t={"'":`\\'`,'"':`\\"`,"\\":`\\\\`,"\b":`\\b`,"\f":`\\f`,"\n":`\\n`,"\r":`\\r`," ":`\\t`,"\v":`\\v`,"\0":`\\0`,"\u2028":`\\u2028`,"\u2029":`\\u2029`};if(t[e])return t[e];if(e<` `){let t=e.charCodeAt(0).toString(16);return`\\x`+(`00`+t).substring(t.length)}return e}function Hn(e){let t=SyntaxError(e);return t.lineNumber=mn,t.columnNumber=hn,t}var Un={parse:yn,stringify:function(e,t,n){let r=[],i=``,a,o,s=``,c;if(typeof t==`object`&&t&&!Array.isArray(t)&&(n=t.space,c=t.quote,t=t.replacer),typeof t==`function`)o=t;else if(Array.isArray(t)){a=[];for(let e of t){let t;typeof e==`string`?t=e:(typeof e==`number`||e instanceof String||e instanceof Number)&&(t=String(e)),t!==void 0&&a.indexOf(t)<0&&a.push(t)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n==`number`?n>0&&(n=Math.min(10,Math.floor(n)),s=` `.substr(0,n)):typeof n==`string`&&(s=n.substr(0,10)),l(``,{"":e});function l(e,t){let n=t[e];switch(n!=null&&(typeof n.toJSON5==`function`?n=n.toJSON5(e):typeof n.toJSON==`function`&&(n=n.toJSON(e))),o&&(n=o.call(t,e,n)),n instanceof Number?n=Number(n):n instanceof String?n=String(n):n instanceof Boolean&&(n=n.valueOf()),n){case null:return`null`;case!0:return`true`;case!1:return`false`}if(typeof n==`string`)return u(n,!1);if(typeof n==`number`)return String(n);if(typeof n==`object`)return Array.isArray(n)?p(n):d(n)}function u(e){let t={"'":.1,'"':.2},n={"'":`\\'`,'"':`\\"`,"\\":`\\\\`,"\b":`\\b`,"\f":`\\f`,"\n":`\\n`,"\r":`\\r`," ":`\\t`,"\v":`\\v`,"\0":`\\0`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},r=``;for(let i=0;i<e.length;i++){let a=e[i];switch(a){case`'`:case`"`:t[a]++,r+=a;continue;case`\0`:if(ln.isDigit(e[i+1])){r+=`\\x00`;continue}}if(n[a]){r+=n[a];continue}if(a<` `){let e=a.charCodeAt(0).toString(16);r+=`\\x`+(`00`+e).substring(e.length);continue}r+=a}let i=c||Object.keys(t).reduce((e,n)=>t[e]<t[n]?e:n);return r=r.replace(new RegExp(i,`g`),n[i]),i+r+i}function d(e){if(r.indexOf(e)>=0)throw TypeError(`Converting circular structure to JSON5`);r.push(e);let t=i;i+=s;let n=a||Object.keys(e),o=[];for(let t of n){let n=l(t,e);if(n!==void 0){let e=f(t)+`:`;s!==``&&(e+=` `),e+=n,o.push(e)}}let c;if(o.length===0)c=`{}`;else{let e;if(s===``)e=o.join(`,`),c=`{`+e+`}`;else{let n=`,
|
|
9
9
|
`+i;e=o.join(n),c=`{
|
|
10
10
|
`+i+e+`,
|
|
11
|
-
`+t+`}`}}return r.pop(),i=t,c}function f(e){if(e.length===0)return u(e,!0);let t=String.fromCodePoint(e.codePointAt(0));if(!
|
|
11
|
+
`+t+`}`}}return r.pop(),i=t,c}function f(e){if(e.length===0)return u(e,!0);let t=String.fromCodePoint(e.codePointAt(0));if(!ln.isIdStartChar(t))return u(e,!0);for(let n=t.length;n<e.length;n++)if(!ln.isIdContinueChar(String.fromCodePoint(e.codePointAt(n))))return u(e,!0);return e}function p(e){if(r.indexOf(e)>=0)throw TypeError(`Converting circular structure to JSON5`);r.push(e);let t=i;i+=s;let n=[];for(let t=0;t<e.length;t++){let r=l(String(t),e);n.push(r===void 0?`null`:r)}let a;if(n.length===0)a=`[]`;else if(s===``)a=`[`+n.join(`,`)+`]`;else{let e=`,
|
|
12
12
|
`+i,r=n.join(e);a=`[
|
|
13
13
|
`+i+r+`,
|
|
14
|
-
`+t+`]`}return r.pop(),i=t,a}}},fn={ball:1,red:2,blue:4,redKO:8,blueKO:16,wall:32,kick:64,score:128,c0:268435456,c1:536870912,c2:1073741824,c3:-2147483648,all:63},pn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Expected an object`);return e},mn=(e,t,n=-4096,r=4096)=>{let i=e===void 0?t:e;if(typeof i!=`number`||!Number.isFinite(i)||i<n||i>r)throw Error(`Number must be between ${n} and ${r}`);return i},hn=(e,t=[0,0])=>{if(e===void 0)return[...t];if(!Array.isArray(e)||e.length!==2)throw Error(`Expected [x, y]`);return[mn(e[0],0),mn(e[1],0)]},gn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.length>t)throw Error(`Array limit: ${t}`);return e};function _n(e,t){return e===void 0?t:typeof e==`number`?mn(e,t,-2147483648,4294967295)|0:gn(e,16).reduce((e,t)=>{if(typeof t!=`string`||!Object.hasOwn(fn,t))throw Error(`Unknown collision flag`);return e|fn[t]},0)}function vn(e,t=`FFFFFF`){if(e===void 0)return t;if(e===`transparent`)return e;if(Array.isArray(e)&&e.length===3)return e.map(e=>Math.round(mn(e,0,0,255)).toString(16).padStart(2,`0`)).join(``);if(typeof e==`string`&&/^[0-9a-f]{6}$/i.test(e))return e;throw Error(`Invalid color`)}var yn=Object.fromEntries(Object.entries({root:`version physicsMode name width height maxViewWidth cameraFollow spawnDistance canBeStored kickOffReset bg traits vertexes segments goals discs planes joints redSpawnPoints blueSpawnPoints playerPhysics ballPhysics`,bg:`type width height kickOffRadius cornerRadius goalLine color`,vertexes:`trait x y bCoef cMask cGroup`,segments:`trait v0 v1 bCoef cMask cGroup curve curveF bias color vis`,discs:`trait pos speed gravity radius invMass damping bCoef cGroup cMask color`,planes:`trait normal dist bCoef cMask cGroup`,goals:`trait p0 p1 team`,joints:`trait d0 d1 length strength color`,playerPhysics:`trait pos speed gravity radius invMass damping bCoef cGroup cMask color acceleration kickingAcceleration kickingDamping kickStrength kickback`}).map(([e,t])=>[e,new Set(t.split(` `))])),bn=new Set([`vertexes`,`segments`,`discs`,`planes`,`goals`,`joints`,`playerPhysics`].flatMap(e=>[...yn[e]]));function xn(e){let t=[],n=(e,t)=>{let n=t.length>80?`${t.slice(0,80)}…`:t;return e+(/^[A-Za-z_$][\w$]*$/.test(n)?`.${n}`:`[${JSON.stringify(n)}]`)},r=(e,r,i)=>{if(e&&typeof e==`object`&&!Array.isArray(e))for(let a of Object.keys(e))r.has(a)||(t.length<64?t.push(`Unsupported stadium field: ${n(i,a)}`):t.length===64&&t.push(`Additional unsupported stadium fields omitted.`))};r(e,yn.root,`$`),r(e.bg,yn.bg,`$.bg`);for(let t of[`vertexes`,`segments`,`discs`,`planes`,`goals`,`joints`]){let n=e[t];Array.isArray(n)&&n.forEach((e,n)=>{r(e,yn[t],`$.${t}[${n}]`)})}if(r(e.ballPhysics,yn.discs,`$.ballPhysics`),r(e.playerPhysics,yn.playerPhysics,`$.playerPhysics`),e.traits&&typeof e.traits==`object`&&!Array.isArray(e.traits))for(let[t,i]of Object.entries(e.traits))r(i,bn,n(`$.traits`,t));return t}function Sn(e,t,n,r,i){let a=e===`hbs`?1:Math.ceil(2*Math.SQRT2*100/Math.min(10,i));if((t+32)*(n+t+32+r)*a>2e6)throw Error(`Stadium collision complexity exceeds the room budget`)}function Cn(e){if(new TextEncoder().encode(e).length>262144)throw Error(`Stadium exceeds 256 KB`);let t=pn(dn.parse(e));if(t.physicsMode!==void 0&&t.physicsMode!==`hbs`&&t.physicsMode!==`substeps`)throw Error(`Invalid physics mode`);let n=t.physicsMode===`substeps`?`substeps`:`hbs`;if(t.version!==void 0&&t.version!==1)throw Error(`Unsupported stadium version`);let r=t.traits===void 0?{}:pn(t.traits),i=e=>{let t=pn(e);if(t.trait===void 0)return t;if(typeof t.trait!=`string`||!Object.hasOwn(r,t.trait))throw Error(`Unknown trait`);return{...pn(r[t.trait]),...t}},a=(e,t=!1)=>({pos:hn(e.pos),speed:hn(e.speed),gravity:hn(e.gravity),radius:mn(e.radius,10,.5,100),invMass:mn(e.invMass,1,0,8192),damping:mn(e.damping,.99,0,8192),bCoef:mn(e.bCoef,.5,-1,8192),cGroup:_n(e.cGroup,t?193:63),cMask:_n(e.cMask,63),color:vn(e.color)}),o=gn(t.discs,63).map(e=>a(i(e)));if(t.ballPhysics!==`disc0`){let e=a(t.ballPhysics===void 0?{}:i(t.ballPhysics),!0);e.cGroup|=192,o.unshift(e)}else if(!o.length)throw Error(`disc0 needs a disc`);let s=gn(t.vertexes,1024).map(e=>i(e)),c=[],l=[],u=xn(t);for(let e of s)c.push({a:[mn(e.x,0),mn(e.y,0)],b:[mn(e.x,0),mn(e.y,0)],bCoef:mn(e.bCoef,1,-1,8192),cGroup:_n(e.cGroup,32),cMask:_n(e.cMask,63),bias:0,color:`transparent`,vis:!1});let d=[...c];for(let e of gn(t.segments,1024)){let t=i(e),n=mn(t.v0,-1,0,s.length-1),r=mn(t.v1,-1,0,s.length-1);if(!Number.isInteger(n)||!Number.isInteger(r))throw Error(`Vertex indices must be integers`);let a=[mn(s[n].x,0),mn(s[n].y,0)],o=[mn(s[r].x,0),mn(s[r].y,0)],u={bCoef:mn(t.bCoef,1,-1,8192),cGroup:_n(t.cGroup,32),cMask:_n(t.cMask,63),bias:mn(t.bias,0,-100,100),color:vn(t.color,`000000`),vis:t.vis!==!1},f=t.curveF===void 0?mn(t.curve,0,-359,359):2*Math.atan2(1,mn(t.curveF,0,-1e8,1e8))*180/Math.PI;if(Math.abs(f)<1e-4){let e={a,b:o,...u};c.push(e),(a[0]!==o[0]||a[1]!==o[1])&&d.push(e);continue}let p=f*Math.PI/180,m=o[0]-a[0],h=o[1]-a[1];if(Math.hypot(m,h)<.001)throw Error(`Arc endpoints overlap`);let g=1/(2*Math.tan(p/2)),_=[(a[0]+o[0])/2-h*g,(a[1]+o[1])/2+m*g],v=Math.hypot(a[0]-_[0],a[1]-_[1]),y=Math.atan2(a[1]-_[1],a[0]-_[0]),b=Math.ceil(Math.abs(p)/Math.max(1e-8,2*Math.acos(Math.max(-1,1-.15/v))));if(c.length+b>4096)throw Error(`Compiled geometry exceeds 4096 segments`);let x={a,b:o,...u,center:_,radius:v,start:y,sweep:p,major:t.curveF===void 0?Math.abs(f)>180:Number(t.curveF)<=0};l.push(x),d.push(x);let S=a;for(let e=1;e<=b;e++){let t=e===b?o:[_[0]+v*Math.cos(y+p*e/b),_[1]+v*Math.sin(y+p*e/b)];c.push({a:S,b:t,...u,renderOnly:!0}),S=t}}if(c.length>4096)throw Error(`Compiled geometry exceeds 4096 segments`);let f=t.playerPhysics===void 0?{}:i(t.playerPhysics),p={...a({...f,radius:f.radius??15,invMass:f.invMass??.5,damping:f.damping??.96,cGroup:f.cGroup??0}),acceleration:mn(f.acceleration,.1,-8192,8192),kickingAcceleration:mn(f.kickingAcceleration,.07,-8192,8192),kickingDamping:mn(f.kickingDamping,.96,0,8192),kickStrength:mn(f.kickStrength,5,-8192,8192),kickback:mn(f.kickback,0,-8192,8192)};Sn(n,o.length,c.length,gn(t.planes,64).length+gn(t.joints,128).length,Math.min(p.radius,...o.map(e=>e.radius)));let m=t.bg===void 0?{}:pn(t.bg);return{version:1,physicsMode:n,name:typeof t.name==`string`?t.name.slice(0,64):`Untitled stadium`,canBeStored:t.canBeStored!==!1,width:mn(t.width,520,100,2048),height:mn(t.height,300,80,2048),maxViewWidth:mn(t.maxViewWidth,0,0,4096),cameraFollow:t.cameraFollow===`player`?`player`:`ball`,bg:{type:m.type===`grass`?`grass`:m.type===`hockey`?`hockey`:`none`,cornerRadius:mn(m.cornerRadius,0,0,500),goalLine:mn(m.goalLine,0,0,2048),width:mn(m.width,0,0,2048),height:mn(m.height,0,0,2048),color:vn(m.color,`718C5A`),kickOffRadius:mn(m.kickOffRadius,0,0,500)},discs:o,segments:c,arcs:l,colliders:d,player:p,spawnDistance:mn(t.spawnDistance,200,0,1500),kickOffReset:t.kickOffReset===`full`?`full`:`partial`,redSpawnPoints:gn(t.redSpawnPoints,32).map(e=>hn(e)),blueSpawnPoints:gn(t.blueSpawnPoints,32).map(e=>hn(e)),warnings:u,planes:gn(t.planes,64).map(e=>{let t=i(e),n=hn(t.normal);if(Math.hypot(...n)<1e-6)throw Error(`Plane normal is zero`);return{normal:n,dist:mn(t.dist,0),bCoef:mn(t.bCoef,1,-1,8192),cGroup:_n(t.cGroup,32),cMask:_n(t.cMask,63)}}),goals:gn(t.goals,16).map(e=>{let t=i(e);if(t.team!==`red`&&t.team!==`blue`)throw Error(`Invalid goal team`);let n=hn(t.p0),r=hn(t.p1);if(Math.hypot(r[0]-n[0],r[1]-n[1])<1)throw Error(`Goal has zero length`);return{p0:n,p1:r,team:t.team===`red`?1:2}}),joints:gn(t.joints,128).map(e=>{let t=i(e),n=mn(t.d0,-1,0,o.length-1),r=mn(t.d1,-1,0,o.length-1);if(!Number.isInteger(n)||!Number.isInteger(r)||n===r)throw Error(`Invalid joint indices`);let a=Math.hypot(o[r].pos[0]-o[n].pos[0],o[r].pos[1]-o[n].pos[1]),s=t.length==null?[a,a]:typeof t.length==`number`?[t.length,t.length]:hn(t.length);return{d0:n,d1:r,min:mn(s[0],0,0),max:mn(s[1],0,0),strength:t.strength===void 0||t.strength===`rigid`?`rigid`:mn(t.strength,0,-8192,8192),color:vn(t.color,`000000`)}})}}function wn(e=`Emerald Arena`,t=440,n=220){let r=[[-t,-n],[t,-n],[-t,n],[t,n],[-t,-70],[-t,70],[t,-70],[t,70],[-t-30,-70],[-t-30,70],[t+30,-70],[t+30,70],[0,-n-40],[0,-65],[0,65],[0,n+40]];return JSON.stringify({version:1,physicsMode:`substeps`,name:e,width:t+75,height:n+65,spawnDistance:t*.4,bg:{type:`grass`,width:t,height:n,kickOffRadius:65,color:`285B35`},vertexes:r.map(([e,t],n)=>({x:e,y:t,...n>=12?{cGroup:[`redKO`,`blueKO`],cMask:[`red`,`blue`]}:{}})),segments:[...[[0,1],[2,3],[0,4],[5,2],[1,6],[7,3],[4,8],[8,9],[9,5],[6,10],[10,11],[11,7]].map(([e,t],n)=>({v0:e,v1:t,cMask:[`ball`],color:n<6?`72A99C`:`3D7267`,bCoef:n<6?.8:.15})),{v0:12,v1:13,vis:!1,cGroup:[`redKO`,`blueKO`],cMask:[`red`,`blue`]},{v0:14,v1:15,vis:!1,cGroup:[`redKO`,`blueKO`],cMask:[`red`,`blue`]},{v0:14,v1:13,curve:-180,vis:!1,cGroup:[`redKO`],cMask:[`red`,`blue`]},{v0:14,v1:13,curve:180,vis:!1,cGroup:[`blueKO`],cMask:[`red`,`blue`]}],planes:[{normal:[0,1],dist:-n-40},{normal:[0,-1],dist:-n-40},{normal:[1,0],dist:-t-50},{normal:[-1,0],dist:-t-50}],goals:[{p0:[-t,-70],p1:[-t,70],team:`red`},{p0:[t,-70],p1:[t,70],team:`blue`}],discs:[...[-t,t].flatMap(e=>[-70,70].map(t=>({pos:[e,t],radius:6,invMass:0,color:`DAEEE4`,bCoef:.5})))],ballPhysics:{radius:9,damping:.991,bCoef:.6},playerPhysics:{radius:15,acceleration:.11,damping:.96,kickStrength:5.5}},null,2)}var Tn=`ball2d-core/1/${Ot}`,En=32,Dn=class e{core;terrain;stadium;source=``;colors=[];tick=0;elapsed=0;ballKicks=[];red=0;blue=0;phase=`lobby`;paused=!1;resumeTicks=0;countdown=0;kickoff=1;kickoffActive=!0;scoreLimit=5;timeLimit=300;lastGoal=0;kickRate=2;setKickRateLimit(e,t,n){this.kickRate=On(e,t,n),this.core.kick_limits(this.kickRate&255,this.kickRate>>>8&255,this.kickRate>>>16)}constructor(e){this.core=e.exports,this.terrain=new st(this.core)}configureSurface(e){if(this.phase!==`lobby`&&this.phase!==`finished`)throw Error(`Stop the match before configuring its surface`);e===null?this.terrain.disable():this.terrain.configure(e)}setSurfaceWeather(e){this.terrain.setWeather(e)}sampleSurface(e,t){return this.terrain.sample(e,t)}get surfaceEnabled(){return this.terrain.enabled}static async create(t,n){let r=t??await(await fetch(`/core.wasm?v=5a27b77ea69c9f5e179f`,{signal:n})).arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest(`SHA-256`,r))).map(e=>e.toString(16).padStart(2,`0`)).join(``)!==`1229b1b4ba3892d6073fb85b3b6231282c2d81ee270808cb0acda874d49cb87e`)throw Error(`Physics build changed. Refresh the page to load a matching version.`);return new e(await WebAssembly.instantiate(await WebAssembly.compile(r)))}get data(){return new Float64Array(this.core.memory.buffer,this.core.data_ptr(),this.core.count()*18)}load(e){this.stadium=Cn(e),this.source=e,this.core.reset(),this.terrain.disable(),this.colors=[],this.core.physics_mode(+(this.stadium.physicsMode===`substeps`)),this.tick=0,this.elapsed=0,this.red=this.blue=0,this.phase=`lobby`,this.paused=!1,this.resumeTicks=0,this.countdown=0,this.kickoffActive=!0;for(let e of this.stadium.discs)this.add(e);for(let e=0;e<En;e++)this.add(this.stadium.player,e+1);for(let e of this.stadium.colliders)if(`center`in e){let t=e;this.core.arc(...t.center,t.radius,...t.a,...t.b,t.sweep,+t.major,t.bCoef,t.cGroup,t.cMask,t.bias)}else{let t=e;this.core.wall(...t.a,...t.b,t.bCoef,t.cGroup,t.cMask,t.bias)}for(let e of this.stadium.planes)this.core.plane(...e.normal,e.dist,e.bCoef,e.cGroup,e.cMask);for(let e of this.stadium.joints)this.core.joint(e.d0,e.d1,e.min,e.max,e.strength===`rigid`?1/0:e.strength);for(let e of this.stadium.goals)this.core.goal(...e.p0,...e.p1,e.team);let t=this.stadium.player;this.core.configure(t.acceleration,t.kickStrength,t.kickingAcceleration,t.kickingDamping,t.kickback,this.kickRate&255),this.setKickRateLimit(this.kickRate&255,this.kickRate>>>8&255,this.kickRate>>>16)}add(e,t=0){let n=this.core.add_disc();if(n<0)throw Error(`Disc capacity exceeded`);this.colors.push(e.color===`transparent`?-1:parseInt(e.color,16)),[...e.pos,...e.speed,e.radius,e.invMass,e.damping,e.bCoef,...e.gravity,e.cGroup,e.cMask,t,0,0,0,e.pos[0],t?0:e.pos[1]].forEach((e,t)=>{this.core.set_disc(n,t,e)})}index(e){if(!Number.isInteger(e)||e<0||e>=En)throw Error(`Invalid slot`);return this.stadium.discs.length+e}joinPlayer(e){let t=this.index(e)*18;this.data[t+15]=0,this.data[t+17]=0,this.setTeam(e,0)}setTeam(e,t){if(![0,1,2].includes(t))throw Error(`Invalid team`);let n=this.index(e),r=this.data;r[n*18+13]=t,r[n*18+10]=this.stadium.player.cGroup|(t===1?2:t===2?4:0),r[n*18+14]=0,this.spawn(n,e,t,this.phase!==`lobby`)}input(e,t){let n=this.data,r=this.index(e)*18,i=t&31;i&16?n[r+14]&16||(n[r+15]=n[r+15]|1024):n[r+15]=n[r+15]&1023,n[r+14]=i}applyDiscProperties(e,t){let n=this.data;if(this.phase===`lobby`||!Number.isInteger(e)||e<0||e>=this.colors.length||n[e*18+12]>0&&n[e*18+13]===0)return!1;let r=Dt(t),i=!1;for(let[t,a]of Et){let o=r[t];if(o===void 0)continue;let s=a===-1?this.colors[e]:n[e*18+a];Object.is(s,o)||(i=!0)}if(!i)return!1;if(r.radius!==void 0){let t=r.radius;for(let r=0;r<this.colors.length;r++)r!==e&&(t=Math.min(t,n[r*18+4]));Sn(this.stadium.physicsMode,this.stadium.discs.length,this.stadium.segments.length,this.stadium.planes.length+this.stadium.joints.length,t)}for(let[t,i]of Et){let a=r[t];a!==void 0&&(i===-1?this.colors[e]=a:n[e*18+i]=a)}return!0}restoreDiscProperties(e,t){let n=e*18,r=this.data;this.colors[e]=t.color===`transparent`?-1:parseInt(t.color,16),r[n+4]=t.radius,r[n+5]=t.invMass,r[n+6]=t.damping,r[n+7]=t.bCoef,r[n+8]=t.gravity[0],r[n+9]=t.gravity[1],r[n+10]=t.cGroup,r[n+11]=t.cMask}spawn(e,t,n,r=!1){this.restoreDiscProperties(e,this.stadium.player),this.colors[e]=n===1?16087152:n===2?7516147:16777215,this.data[e*18+10]|=n===1?2:n===2?4:0;let i=n===1?this.stadium.redSpawnPoints:this.stadium.blueSpawnPoints,a=this.data,o=0;for(let e=0;e<t;e++)a[this.index(e)*18+13]===n&&o++;let s=n===1?-1:1,c=i.length?i[r?i.length-1:Math.min(o,i.length-1)]:r?[s*this.stadium.width,0]:[s*this.stadium.spawnDistance,o?Math.ceil(o/2)*55*(o%2?1:-1):0];a[e*18]=c[0],a[e*18+1]=c[1],a[e*18+2]=a[e*18+3]=a[e*18+14]=0,a[e*18+15]&=1023,a[e*18+11]=this.stadium.player.cMask&-25}resetPositions(e=!1){this.kickoffActive=!0;let t=this.data;for(let n=0;n<this.stadium.discs.length;n++){let r=this.stadium.discs[n];(e||n===0||this.stadium.kickOffReset===`full`)&&(this.restoreDiscProperties(n,r),t[n*18]=r.pos[0],t[n*18+1]=r.pos[1],t[n*18+2]=r.speed[0],t[n*18+3]=r.speed[1])}for(let e=0;e<En;e++){let n=this.index(e);this.spawn(n,e,t[n*18+13])}}start(){(this.phase===`lobby`||this.phase===`finished`)&&(this.red=this.blue=this.elapsed=0,this.phase=`playing`,this.paused=!1,this.resumeTicks=0,this.kickoff=1,this.countdown=0,this.resetPositions(!0))}stop(){this.phase=`lobby`,this.paused=!1,this.resumeTicks=0}setPaused(e){this.phase!==`lobby`&&(e=!!e,this.paused!==e&&(this.paused=e,this.resumeTicks=e?0:119))}finish(){this.phase=`finished`,this.countdown=300}step(){if(this.ballKicks.length=0,this.tick++,this.paused||this.phase===`lobby`)return;if(this.resumeTicks>0){this.resumeTicks--;return}let e=this.data;this.core.step();for(let e=this.core.ball_kick_events()>>>0,t=0;e;e>>>=1,t++)e&1&&this.ballKicks.push(t);if(this.phase===`finished`){--this.countdown<=0&&this.stop();return}if(this.phase===`goal`){--this.countdown<=0&&(this.scoreLimit>0&&Math.max(this.red,this.blue)>=this.scoreLimit||this.timeLimit>0&&this.elapsed>=this.timeLimit*60&&this.red!==this.blue?this.finish():(this.phase=`playing`,this.resetPositions()));return}for(let t=0;t<En;t++){let n=this.index(t)*18,r=this.stadium.player.cMask;e[n+11]=r&-25|(this.kickoffActive?r&(this.kickoff===1?8:16):0)}if(this.kickoffActive){e[2]*e[2]+e[3]*e[3]>0&&(this.kickoffActive=!1);return}this.elapsed++;let t=this.core.goal_event();if(t===1||t===2){t===1?this.red++:this.blue++,this.kickoff=t===1?2:1,this.phase=`goal`,this.countdown=150,this.lastGoal=this.tick;return}this.timeLimit>0&&this.elapsed>=this.timeLimit*60&&this.red!==this.blue&&this.finish()}snapshotSurface(){return this.terrain.snapshot()}snapshot(){let e=this.snapshotSurface();return{...e.length?{surface:e}:{},tick:this.tick,elapsed:this.elapsed,red:this.red,blue:this.blue,phase:this.phase,paused:this.paused,resumeTicks:this.resumeTicks,countdown:this.countdown,kickoff:this.kickoff,kickoffActive:this.kickoffActive,scoreLimit:this.scoreLimit,timeLimit:this.timeLimit,kickRate:this.kickRate,discs:Array.from(this.data),colors:[...this.colors]}}restore(e){if(!e||typeof e!=`object`||!Array.isArray(e.discs)||e.discs.length!==this.data.length||!e.discs.every((e,t)=>typeof e==`number`&&Number.isFinite(e)&&Math.abs(e)<=(t%18==10||t%18==11?2147483648:t%18==17?25500:8192)))throw Error(`Invalid state`);if(!Array.isArray(e.colors)||e.colors.length!==e.discs.length/18||e.colors.some(e=>!Number.isInteger(e)||e<-1||e>16777215))throw Error(`Invalid disc colors`);let t=(e,t,n=0)=>Number.isInteger(e)&&e>=n&&e<=t;if(!t(e.kickRate,6619135)||!t(e.tick,4294967295)||!t(e.elapsed,4294967295)||!t(e.red,65535)||!t(e.blue,65535)||!t(e.countdown,300)||!t(e.resumeTicks,119)||(e.paused||e.phase===`lobby`)&&e.resumeTicks!==0||!t(e.scoreLimit,99)||!t(e.timeLimit,5940)||![`lobby`,`playing`,`goal`,`finished`].includes(e.phase)||typeof e.paused!=`boolean`||typeof e.kickoffActive!=`boolean`||![1,2].includes(e.kickoff))throw Error(`Invalid match metadata`);for(let n=0;n<e.discs.length;n+=18)if(e.discs[n+4]<.5||e.discs[n+4]>100||e.discs[n+5]<0||e.discs[n+5]>8192||e.discs[n+6]<0||e.discs[n+6]>8192||e.discs[n+7]<-1||e.discs[n+7]>8192||!t(e.discs[n+10],2147483647,-2147483648)||!t(e.discs[n+11],2147483647,-2147483648)||!t(e.discs[n+13],2)||!t(e.discs[n+14],31)||!t(e.discs[n+15],2047)||e.discs[n+12]>0&&(!Number.isInteger(e.discs[n+17])||e.discs[n+17]<-255||e.discs[n+17]>25500))throw Error(`Invalid disc properties`);let n=10;for(let t=4;t<e.discs.length;t+=18)n=Math.min(n,e.discs[t]);Sn(this.stadium.physicsMode,this.stadium.discs.length,this.stadium.segments.length,this.stadium.planes.length+this.stadium.joints.length,n),this.terrain.restore(e.surface===void 0?[]:e.surface),this.setKickRateLimit(e.kickRate&255,e.kickRate>>>8&255,e.kickRate>>>16),this.tick=e.tick,this.elapsed=e.elapsed,this.red=e.red,this.blue=e.blue,this.phase=e.phase,this.paused=e.paused,this.resumeTicks=e.resumeTicks,this.countdown=e.countdown,this.kickoff=e.kickoff,this.kickoffActive=e.kickoffActive,this.scoreLimit=e.scoreLimit,this.timeLimit=e.timeLimit,this.data.set(e.discs),this.colors=[...e.colors]}};function On(e,t,n){if(![e,t,n].every(Number.isInteger))throw Error(`Invalid kick rate limit`);return Math.max(0,Math.min(255,e))|Math.max(0,Math.min(255,t))<<8|Math.max(0,Math.min(100,n))<<16}function kn(e){let t=new URL(e);if(![`http:`,`https:`].includes(t.protocol)||t.username||t.password||t.pathname!==`/`||t.search||t.hash)throw Error(`Expected an HTTP(S) service origin without credentials or a path`);return t.origin}function An(e){let t=new URL(e.assets);if(![`http:`,`https:`,`ball2d:`].includes(t.protocol)||!t.host||t.username||t.password||t.pathname!==`/`||t.search||t.hash)throw Error(`Expected a root asset origin`);let n=kn(e.service),r=kn(e.public);function i(e,t){if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||[...e].some(e=>e.charCodeAt(0)<=32||e.charCodeAt(0)===127))throw Error(`Expected an absolute application path`);let n=decodeURIComponent(e.split(/[?#]/,1)[0]);if(n.includes(`\\`)||n.includes(`//`)||n.split(`/`).some(e=>e===`.`||e===`..`))throw Error(`Ambiguous application path`);let r=new URL(e,t),i=new URL(t);if(r.protocol!==i.protocol||r.host!==i.host||r.username||r.password)throw Error(`Application path escaped its runtime origin`);return r}return{serviceOrigin:n,publicOrigin:r,asset:e=>i(e,t.href),public:e=>i(e,r),api:e=>{let t=i(e,n);if(!t.pathname.startsWith(`${ne}/`)||t.hash)throw Error(`Expected a versioned application API path`);return t}}}function jn(){let e=location.origin;return An({assets:e,service:e,public:e})}function Mn(e=jn()){return{serviceOrigin:e.serviceOrigin,signalingResume:!0,createWebSocket:e=>new WebSocket(e),createPeerConnection:e=>new RTCPeerConnection(e)}}var Nn=[[`classic`,`Classic`],[`easy`,`Easy`],[`small`,`Small`],[`big`,`Big`],[`rounded`,`Rounded`],[`hockey`,`Hockey`],[`big_easy`,`Big Easy`],[`big_rounded`,`Big Rounded`],[`big_hockey`,`Big Hockey`],[`huge`,`Huge`]];function Pn(e){let t=new Map;return async n=>{let r=Nn.find(([e,t])=>e===n||t===n);if(!r)throw Error(`Unknown default stadium`);let i=t.get(r[0]);return i||(i=(async()=>{let t=await e(`/stadiums/${r[0]}.hbs`);if(!t.ok)throw Error(`Could not load stadium`);let n=await t.text();return Cn(n),n})(),t.set(r[0],i),i.catch(()=>t.delete(r[0]))),i}}function Fn(e=jn()){let t=Mn(e),n=(e,t)=>fetch(e,t);return{network:t,publicOrigin:e.publicOrigin,request:n,loadEngine:async t=>{let r=await n(e.asset(`/core.wasm?v=${Ot}`),{signal:t});if(!r.ok)throw Error(`Could not load bundled physics engine`);return Dn.create(await r.arrayBuffer(),t)},loadStadium:Pn(t=>n(e.asset(t)))}}var In={message:{burst:240,perSecond:160},action:{burst:12,perSecond:6},chat:{burst:4,perSecond:1}},Ln=class{peers=new Map;allow(e,t,n=performance.now()){let r=this.peers.get(e);r||(r={},this.peers.set(e,r));let{burst:i,perSecond:a}=In[t],o=r[t]??{tokens:i,at:n};return o.tokens=Math.min(i,o.tokens+Math.max(0,n-o.at)*a/1e3),o.at=Math.max(o.at,n),r[t]=o,o.tokens<1?!1:(o.tokens--,!0)}delete(e){this.peers.delete(e)}clear(){this.peers.clear()}},Rn=33554432,zn=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});function Bn(e){let t=2166136261;for(let n of e)t=Math.imul(t^n,16777619);return t>>>0}function Vn(e){if(e.length>33554432)throw Error(`Replay exceeds 32 MB`);let t=tt(e,{level:6}),n=new Uint8Array(16+t.length),r=new DataView(n.buffer);return n.set([66,50,68,90,1,0,0,0]),r.setUint32(8,e.length,!0),r.setUint32(12,Bn(e),!0),n.set(t,16),n}function Hn(e){if(typeof e==`string`){if(zn.encode(e).length>33554432)throw Error(`Replay exceeds 32 MB`);return zn.encode(e)}let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length>33554432)throw Error(`Replay exceeds 32 MB`);if(t[0]!==66||t[1]!==50||t[2]!==68||t[3]!==90)return t;if(t.length<17||t[4]!==1||t[5]||t[6]||t[7])throw Error(`Invalid compressed replay header`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(8,!0);if(!r||r>33554432)throw Error(`Invalid expanded replay size`);let i=new Uint8Array(r),a=0,o=!1,s=new nt((e,t)=>{if(a+e.length>r)throw Error(`Expanded replay exceeds declared size`);i.set(e,a),a+=e.length,o=t});for(let e=16;e<t.length;e+=1024)s.push(t.subarray(e,e+1024),e+1024>=t.length);if(!o||a!==r||Bn(i)!==n.getUint32(12,!0))throw Error(`Compressed replay integrity failure`);return i}var Un=[`input`,`team`,`start`,`stop`,`pause`,`scoreLimit`,`timeLimit`,`kickRate`,`join`,`disc`,`surface`],Wn=new TextEncoder,Gn=new TextDecoder(`utf-8`,{fatal:!0});function Kn(e){return Vn(qn(e))}function qn(e){let{commands:t,...n}=e,r=t.some(e=>e.kind===`surface`)||e.initial.surface!==void 0||e.checkpoints.some(e=>e.state.surface!==void 0)?4:t.some(e=>e.kind===`disc`)?3:e.checkpoints.length?2:1,i=0,a=e.checkpoints.map(e=>{let t=e.state.discs;if(!Array.isArray(t)||t.length>1728||t.some(e=>!Number.isFinite(e)))throw Error(`Invalid checkpoint discs`);i+=t.length*8;let n=e.state.surface;if(n!==void 0){if(!Array.isArray(n)||n.length!==0&&n.length!==5389||n.some(e=>!Number.isInteger(e)||e<0||e>4294967295))throw Error(`Invalid checkpoint surface`);i+=n.length*4}return{...e,state:{...e.state,discs:t.length,...n===void 0?{}:{surface:n.length}}}});if(a.length>721)throw Error(`Too many replay checkpoints`);let o=Wn.encode(JSON.stringify(r>=2?{...n,checkpoints:a}:n));if(t.length>5e5||o.length+16>33554432)throw Error(`Replay exceeds bounds`);let s=t.length*12+t.filter(e=>e.kind===`disc`).length*106,c=new Uint8Array(Math.min(Rn,s)),l=new DataView(c.buffer),u=e=>{if(d+e>c.length)throw Error(`Replay exceeds bounds`)},d=0,f=e.initial.tick,p=e=>{if(!Number.isInteger(e)||e<0||e>4294967295)throw Error(`Invalid replay integer`);do{u(1);let t=Math.floor(e/128);c[d++]=e%128|(t?128:0),e=t}while(e)};for(let e of t){let t=Un.indexOf(r<3&&e.kind===`join`?`team`:e.kind);if(e.kind===`join`&&e.value!==0||e.kind===`team`&&e.value>2)throw Error(`Invalid replay team command`);if(t<0||!Number.isInteger(e.slot)||e.slot<0||e.slot>(e.kind===`disc`?95:31))throw Error(`Invalid replay command`);if(p(e.tick-f),u(1),c[d++]=r>=3?t:t<<5|e.slot,r>=3&&p(e.slot),p(r<3&&e.kind===`join`?3:e.value),e.kind===`disc`){let t=Dt(e.properties),n=0;Et.forEach(([e],r)=>{t[e]!==void 0&&(n|=1<<r)}),p(n);for(let[e]of Et){let n=t[e];n!==void 0&&(u(8),l.setFloat64(d,n,!0),d+=8)}}f=e.tick}let m=16+o.length+i+d;if(m>33554432)throw Error(`Replay exceeds 32 MB`);let h=new Uint8Array(m),g=new DataView(h.buffer);h.set([66,50,68,80,r,0,0,0]),g.setUint32(8,o.length,!0),g.setUint32(12,t.length,!0),h.set(o,16);let _=16+o.length;for(let t of e.checkpoints){for(let e of t.state.discs)g.setFloat64(_,e,!0),_+=8;for(let e of t.state.surface??[])g.setUint32(_,e,!0),_+=4}return h.set(c.subarray(0,d),_),h}function Jn(e){let t=Hn(e);if(t[0]!==66||t[1]!==50||t[2]!==68||t[3]!==80)return JSON.parse(Gn.decode(t));if(t.length<16||![1,2,3,4].includes(t[4])||t[5]||t[6]||t[7])throw Error(`Invalid packed replay header`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(8,!0),i=n.getUint32(12,!0);if(r>t.length-16||i>5e5||i>(t.length-16-r)/3)throw Error(`Invalid packed replay bounds`);let a=JSON.parse(Gn.decode(t.subarray(16,16+r)));if(!a||!Number.isSafeInteger(a.initial?.tick)||a.initial.tick<0)throw Error(`Invalid replay initial tick`);a.commands=[];let o=16+r,s=a.initial.tick;if(t[4]>=2){if(!Array.isArray(a.checkpoints)||a.checkpoints.length>721)throw Error(`Invalid packed checkpoints`);let e=0;for(let n of a.checkpoints){let r=n?.state?.discs;if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>1728)throw Error(`Invalid checkpoint disc count`);if(e+=r*8,t[4]>=4&&n.state.surface!==void 0){let t=n.state.surface;if(t!==0&&t!==5389)throw Error(`Invalid checkpoint surface count`);e+=t*4}}if(e>t.length-o-i*3)throw Error(`Truncated checkpoint discs`);for(let e of a.checkpoints){let r=e.state.discs,i=Array(r);for(let e=0;e<r;e++){let t=n.getFloat64(o,!0);if(!Number.isFinite(t))throw Error(`Nonfinite checkpoint disc`);i[e]=t,o+=8}if(e.state.discs=i,t[4]>=4&&e.state.surface!==void 0){let t=e.state.surface,r=Array(t);for(let e=0;e<t;e++)r[e]=n.getUint32(o,!0),o+=4;e.state.surface=r}}}let c=()=>{let e=0;for(let n=0;n<=28;n+=7){if(o>=t.length)throw Error(`Truncated replay command`);let r=t[o++];if(n===28&&r>15)throw Error(`Replay integer overflow`);if(e+=(r&127)*2**n,!(r&128)){if(n&&r===0)throw Error(`Noncanonical replay integer`);return e}}throw Error(`Invalid replay integer`)};for(let e=0;e<i;e++){if(s+=c(),!Number.isSafeInteger(s)||o>=t.length)throw Error(`Invalid replay tick`);let e=t[o++],r=Un[t[4]>=3?e:e>>5];if(!r)throw Error(`Unknown replay command`);let i=t[4]>=3?c():e&31,l=c();if(r===`disc`){let e=c();if(e>8191)throw Error(`Invalid disc property mask`);let u={};Et.forEach(([r],i)=>{if(e&1<<i){if(o+8>t.length)throw Error(`Truncated disc properties`);u[r]=n.getFloat64(o,!0),o+=8}}),a.commands.push({tick:s,kind:r,slot:i,value:l,properties:Dt(u)});continue}a.commands.push(t[4]<3&&r===`team`&&l===3?{tick:s,kind:`join`,slot:i,value:0}:{tick:s,kind:r,slot:i,value:l})}if(o!==t.length)throw Error(`Trailing replay command data`);return a}function Yn(e){let t=JSON.stringify(e),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,`0`)}function Xn(e,t){switch(t.kind){case`surface`:if(t.slot!==0||t.value!==0&&t.value!==1)throw Error(`Invalid surface command`);e.configureSurface(t.value?{seed:42,halfWidth:e.stadium.bg.width||e.stadium.width,halfHeight:e.stadium.bg.height||e.stadium.height,moisturePermille:1e3}:null),t.value&&e.setSurfaceWeather({rainMilliMmH:2e5,temperatureMilliC:2e4,humidityPermille:1e3,windMilliMS:0});break;case`disc`:if(!t.properties)throw Error(`Missing replay disc properties`);e.applyDiscProperties(t.slot,t.properties);break;case`input`:e.input(t.slot,t.value);break;case`join`:e.joinPlayer(t.slot);break;case`team`:e.setTeam(t.slot,t.value);break;case`start`:e.start();break;case`stop`:e.stop();break;case`scoreLimit`:e.scoreLimit=t.value;break;case`timeLimit`:e.timeLimit=t.value;break;case`kickRate`:e.setKickRateLimit(t.value&255,t.value>>>8&255,t.value>>>16);break;case`pause`:e.setPaused(!!t.value)}}var Zn=class{replay;playerOrder=[];lastInputs=new Map;bytes=0;full=!1;canRecord(e){return!this.full&&e.tick-this.replay.initial.tick<216e3}constructor(e,t=[],n=[null,null]){let r=e.snapshot();this.playerOrder=t.map(e=>e.slot),this.replay={magic:`B2DR`,version:1,engine:Tn,stadium:e.source,initial:r,commands:[],checkpoints:[],roster:t.map(e=>({...e,tick:r.tick})),styles:[{tick:r.tick,teams:St(n)}],orders:[{tick:r.tick,slots:[...this.playerOrder]}],end:r.tick,finalHash:Yn(r)},this.bytes=new TextEncoder().encode(JSON.stringify(this.replay)).length;for(let t=0;t<32;t++)this.lastInputs.set(t,e.data[e.index(t)*18+14])}reserve(e){let t=new TextEncoder().encode(JSON.stringify(e)).length+1;return this.full||this.bytes+t>31457280?(this.full=!0,!1):(this.bytes+=t,!0)}player(e,t,n,r){let i={tick:e,slot:t,name:n,avatar:r};return this.replay.roster.length>=4096||!this.reserve(i)?(this.full=!0,!1):(this.replay.roster.push(i),n===null?this.order(e,this.playerOrder.filter(e=>e!==t)):this.playerOrder.includes(t)?!0:this.order(e,[...this.playerOrder,t]))}style(e,t){let n={tick:e,teams:St(t)},r=this.replay.styles;return r.length>=4096||!this.reserve(n)?(this.full=!0,!1):(r.push(n),!0)}order(e,t){if(t.length===this.playerOrder.length&&t.every((e,t)=>e===this.playerOrder[t]))return!0;let n={tick:e,slots:[...t]},r=this.replay.orders;return r.length>=4096||!this.reserve(n)?(this.full=!0,!1):(this.playerOrder=[...t],r.push(n),!0)}command(e){return e.kind===`input`&&this.lastInputs.get(e.slot)===e.value?!0:this.replay.commands.length>=5e5||!this.reserve(e)?(this.full=!0,!1):(e.kind===`input`&&this.lastInputs.set(e.slot,e.value),(e.kind===`team`||e.kind===`join`)&&this.lastInputs.set(e.slot,0),e.kind===`start`&&this.lastInputs.clear(),this.replay.commands.push(e.kind===`disc`?{...e,properties:Dt(e.properties)}:{...e}),!0)}step(e){for(let t=0;t<32;t++)this.lastInputs.set(t,e.data[e.index(t)*18+14]);if(e.tick%300==0){let t=e.snapshot(),n={tick:e.tick,state:t,hash:Yn(t)};this.reserve(n)&&this.replay.checkpoints.push(n)}this.replay.end=e.tick}pack(e){return this.replay.end=e.tick,this.replay.finalHash=Yn(e.snapshot()),qn(this.replay)}finish(e){return this.replay.end=e.tick,this.replay.finalHash=Yn(e.snapshot()),new Blob([Kn(this.replay)],{type:`application/x-ball2d-replay`})}};async function Qn(e){if(e.size>33554432)throw Error(`Replay exceeds 32 MB`);return $n(await e.arrayBuffer())}function $n(e){let t=Jn(e);if(t.magic!==`B2DR`||t.version!==1||t.engine!==Tn)throw Error(`Unsupported replay engine/version`);if(!Array.isArray(t.commands)||t.commands.length>5e5||!Array.isArray(t.checkpoints)||t.checkpoints.length>721||!Number.isInteger(t.end)||t.end<t.initial.tick||t.end-t.initial.tick>216e3)throw Error(`Invalid replay bounds`);let n=t.initial.tick;for(let e of t.commands){if(!Number.isInteger(e.tick)||e.tick<n||e.tick>t.end||![`input`,`team`,`start`,`stop`,`pause`,`scoreLimit`,`timeLimit`,`kickRate`,`join`,`disc`,`surface`].includes(e.kind)||e.kind===`surface`&&e.slot!==0||!Number.isInteger(e.slot)||e.slot<0||e.slot>(e.kind===`disc`?95:31)||!Number.isInteger(e.value)||e.value<0||e.value>(e.kind===`disc`||e.kind===`join`?0:e.kind===`kickRate`?6619135:e.kind===`timeLimit`?5940:e.kind===`scoreLimit`?99:e.kind===`team`?2:e.kind===`pause`||e.kind===`surface`?1:31))throw Error(`Invalid replay command`);e.kind===`disc`&&(e.properties=Dt(e.properties)),n=e.tick}if(!Array.isArray(t.roster)||t.roster.length>4096)throw Error(`Invalid replay roster`);n=t.initial.tick;for(let e of t.roster){if(!Number.isInteger(e.tick)||e.tick<n||e.tick>t.end||!Number.isInteger(e.slot)||e.slot<0||e.slot>31||e.name!==null&&(typeof e.name!=`string`||e.name.length>24)||e.avatar!==void 0&&!Tt(e.avatar))throw Error(`Invalid roster event`);n=e.tick}if(t.styles!==void 0){if(!Array.isArray(t.styles)||t.styles.length>4096)throw Error(`Invalid replay styles`);let e=t.initial.tick;for(let n of t.styles){if(!n||!Number.isInteger(n.tick)||n.tick<e||n.tick>t.end||n.teams===void 0)throw Error(`Invalid replay style`);n.teams=St(n.teams),e=n.tick}}if(t.orders!==void 0){if(!Array.isArray(t.orders)||t.orders.length>4096)throw Error(`Invalid replay orders`);let e=t.initial.tick;for(let n of t.orders){if(!n||!Number.isInteger(n.tick)||n.tick<e||n.tick>t.end||!Array.isArray(n.slots)||n.slots.length>32||n.slots.some(e=>!Number.isInteger(e)||e<0||e>31)||new Set(n.slots).size!==n.slots.length)throw Error(`Invalid replay order`);e=n.tick}}let r=t.initial.tick;for(let e of t.checkpoints){if(!Number.isInteger(e.tick)||e.tick<=r||e.tick>t.end||e.state.tick!==e.tick||typeof e.hash!=`string`)throw Error(`Invalid checkpoint`);r=e.tick}return t}var er=e=>Number.isSafeInteger(e)&&e>0&&e<=9e4,tr=class{io;state=`admitted`;currentEpoch=0;membershipDeadline;recoveryDeadline=1/0;phaseDeadline=1/0;attemptId;retry=0;timer;timerVersion=0;transport;constructor(e,t){if(this.io=e,!er(t))throw RangeError(`Invalid membership duration`);this.membershipDeadline=e.now()+t,this.arm()}get epoch(){return this.currentEpoch}get status(){return this.state}disconnected(e){e!==this.currentEpoch||this.terminal()||this.checkExpiry()||(this.state===`admitted`?(this.recoveryDeadline=Math.min(this.io.now()+3e4,this.membershipDeadline),this.attemptId=this.io.newAttemptId(),this.retry=0,this.wait()):(this.state===`connecting`||this.state===`awaiting-ack`)&&this.wait())}acknowledge(e,t){if(e!==this.currentEpoch||this.state!==`awaiting-ack`||t!==void 0&&!er(t)||this.checkExpiry()||this.checkAttemptTimeout())return!1;t!==void 0&&(this.membershipDeadline=Math.min(this.membershipDeadline,this.io.now()+t));let n=this.attemptId;if(n===void 0)return!1;let r={attemptId:n,epoch:e};return this.state=`admitted`,this.recoveryDeadline=1/0,this.phaseDeadline=1/0,this.attemptId=void 0,this.retry=0,this.arm(),this.io.onRecovered(r),!0}heartbeat(e,t){return e!==this.currentEpoch||this.state!==`admitted`||!er(t)||this.checkExpiry()?!1:(this.membershipDeadline=this.io.now()+t,this.arm(),!0)}cancel(){this.terminal()||(this.state=`cancelled`,this.clearTimer(),this.retire())}terminal(){return this.state===`expired`||this.state===`cancelled`}retire(){let e=this.transport;this.transport=void 0;try{e?.close()}catch{}}clearTimer(){this.timerVersion++,this.timer!==void 0&&this.io.clearTimer(this.timer),this.timer=void 0}checkExpiry(){if(this.terminal())return!0;let e=this.io.now(),t=e>=this.membershipDeadline;return!t&&e<this.recoveryDeadline?!1:(this.state=`expired`,this.clearTimer(),this.retire(),this.io.onExpired(t?`membership`:`recovery`),!0)}checkAttemptTimeout(){return(this.state===`connecting`||this.state===`awaiting-ack`)&&this.io.now()>=this.phaseDeadline&&(this.wait(),!0)}wait(){this.state=`waiting`,this.retire();let e=this.io.random(),t=Number.isFinite(e)?Math.max(0,Math.min(1,e)):.5,n=Math.min(4e3,250*2**Math.min(this.retry++,4));this.phaseDeadline=this.io.now()+n*(.75+t*.25),this.arm()}arm(){if(this.clearTimer(),this.terminal())return;let e=this.timerVersion,t=Math.min(this.membershipDeadline,this.recoveryDeadline,this.phaseDeadline);this.timer=this.io.setTimer(()=>{if(!(e!==this.timerVersion||this.checkExpiry())){if(this.timer=void 0,this.io.now()<this.phaseDeadline){this.arm();return}this.state===`waiting`?this.attempt():this.state===`connecting`||this.state===`awaiting-ack`?this.wait():this.arm()}},Math.max(0,t-this.io.now()))}attempt(){if(this.checkExpiry())return;let e=this.attemptId;if(e===void 0)throw Error(`Recovery attempt identity is unavailable`);this.state=`connecting`;let t=++this.currentEpoch;this.phaseDeadline=this.io.now()+5e3,this.arm();let n;try{n=this.io.createAttempt({attemptId:e,epoch:t},{opened:()=>{t!==this.currentEpoch||this.state!==`connecting`||this.checkExpiry()||this.checkAttemptTimeout()||(this.state=`awaiting-ack`)},closed:()=>this.disconnected(t)})}catch{t===this.currentEpoch&&this.disconnected(t);return}if(t===this.currentEpoch&&(this.state===`connecting`||this.state===`awaiting-ack`||this.state===`admitted`))this.transport=n;else try{n.close()}catch{}}},nr=2,rr=9e4,ir=33;function ar(e,t){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}var or=e=>typeof e==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e),sr=e=>typeof e==`string`&&/^[0-9a-f]{64}$/.test(e),cr=(e,t)=>Number.isSafeInteger(e)&&e>=t,lr=e=>cr(e,1)&&e<=rr,ur=e=>e===`host`||e===`guest`;function dr(e){return!ar(e,[`version`,`roomGeneration`,`secret`,`connectionEpoch`,`membershipValidForMs`])||e.version!==nr||!or(e.roomGeneration)||!sr(e.secret)||!cr(e.connectionEpoch,1)||!lr(e.membershipValidForMs)?null:{version:2,roomGeneration:e.roomGeneration,secret:e.secret,connectionEpoch:e.connectionEpoch,membershipValidForMs:e.membershipValidForMs}}function fr(e){if(!ar(e,[`type`,`version`,`roomGeneration`,`attemptId`,`id`,`hostId`,`role`,`connectionEpoch`,`membershipValidForMs`,`rosterRevision`,`members`,`requireVerification`,`locked`])||e.type!==`resumed`||e.version!==nr||!or(e.roomGeneration)||!or(e.attemptId)||!or(e.id)||!or(e.hostId)||!ur(e.role)||!cr(e.connectionEpoch,1)||!lr(e.membershipValidForMs)||!cr(e.rosterRevision,0)||typeof e.requireVerification!=`boolean`||typeof e.locked!=`boolean`||!Array.isArray(e.members)||e.members.length<1||e.members.length>ir)return null;let t=mr(e.members,e.hostId);return t?.some(t=>t.id===e.id&&t.role===e.role&&t.attached&&t.connectionEpoch===e.connectionEpoch)?{type:`resumed`,version:2,roomGeneration:e.roomGeneration,attemptId:e.attemptId,id:e.id,hostId:e.hostId,role:e.role,connectionEpoch:e.connectionEpoch,membershipValidForMs:e.membershipValidForMs,rosterRevision:e.rosterRevision,members:t,requireVerification:e.requireVerification,locked:e.locked}:null}function pr(e){if(!ar(e,[`type`,`id`,`hostId`,`role`,`resumeGrant`,`rosterRevision`,`members`,`requireVerification`,`locked`])||e.type!==`ready`)return null;let t=dr(e.resumeGrant);if(!t)return null;let n=fr({type:`resumed`,version:2,roomGeneration:t.roomGeneration,attemptId:t.roomGeneration,id:e.id,hostId:e.hostId,role:e.role,connectionEpoch:t.connectionEpoch,membershipValidForMs:t.membershipValidForMs,rosterRevision:e.rosterRevision,members:e.members,requireVerification:e.requireVerification,locked:e.locked});return n?{type:`ready`,id:n.id,hostId:n.hostId,role:n.role,resumeGrant:t,rosterRevision:n.rosterRevision,members:n.members,requireVerification:n.requireVerification,locked:n.locked}:null}function mr(e,t){if(!Array.isArray(e)||e.length<1||e.length>ir)return null;let n=[],r=new Set;for(let t of e){if(!ar(t,[`id`,`role`,`attached`,`connectionEpoch`])||!or(t.id)||!ur(t.role)||typeof t.attached!=`boolean`||!cr(t.connectionEpoch,1)||r.has(t.id))return null;r.add(t.id),n.push({id:t.id,role:t.role,attached:t.attached,connectionEpoch:t.connectionEpoch})}let i=n.filter(e=>e.role===`host`);return i.length===1&&i[0].id===t?n:null}function hr(e){if(!ar(e,[`type`,`roomGeneration`,`hostId`,`rosterRevision`,`members`])||e.type!==`roster`||!or(e.roomGeneration)||!or(e.hostId)||!cr(e.rosterRevision,0))return null;let t=mr(e.members,e.hostId);return t?{type:`roster`,roomGeneration:e.roomGeneration,hostId:e.hostId,rosterRevision:e.rosterRevision,members:t}:null}function gr(e){let t=[...e],n=new Set(t.filter(e=>e.type===`transport`&&e.selectedCandidatePairId).map(e=>e.selectedCandidatePairId)),r=t.filter(e=>e.type===`candidate-pair`&&e.state===`succeeded`),i=n.size?r.filter(e=>n.has(e.id)):r.filter(e=>e.nominated===!0);if(i.length!==1)return null;let a=i[0].currentRoundTripTime;return typeof a==`number`&&Number.isFinite(a)&&a>=0?a*1e3:null}var _r=524288,vr=16384,yr=12;function br(e,t){let n=JSON.stringify(e);if(n===void 0)throw Error(`Missing control message`);let r=new TextEncoder().encode(n);if(r.length>_r)throw Error(`Control message exceeds 512 KB`);if(r.length<=vr)return[n];let i=Math.ceil(r.length/vr),a=[];for(let e=0;e<i;e++){let n=r.subarray(e*vr,(e+1)*vr),o=new ArrayBuffer(yr+n.length),s=new DataView(o);s.setUint16(0,45635),s.setUint8(2,1),s.setUint32(4,t,!0),s.setUint16(8,e,!0),s.setUint16(10,i,!0),new Uint8Array(o,yr).set(n),a.push(o)}return a}var xr=class{partial;push(e,t=performance.now()){if(typeof e==`string`){if(this.partial||new TextEncoder().encode(e).length>vr)throw Error(`Invalid control message`);return JSON.parse(e)}if(e.byteLength<13||e.byteLength>16396)throw Error(`Control fragment length`);let n=new DataView(e);if(n.getUint16(0)!==45635||n.getUint8(2)!==1||n.getUint8(3)!==0)throw Error(`Control fragment version`);let r=n.getUint32(4,!0),i=n.getUint16(8,!0),a=n.getUint16(10,!0);if(a<2||a>32||i>=a)throw Error(`Control fragment bounds`);if(!this.partial){if(i!==0)throw Error(`Missing first fragment`);this.partial={id:r,count:a,next:0,bytes:0,parts:[],since:t}}let o=this.partial;if(o.id!==r||o.count!==a||o.next!==i||t-o.since>1e4)throw Error(`Control fragment sequence`);if(o.next++,o.bytes+=e.byteLength-yr,o.bytes>_r)throw Error(`Control size limit`);if(o.parts.push(new Uint8Array(e.slice(yr))),o.next!==a)return;let s=new Uint8Array(o.bytes),c=0;for(let e of o.parts)s.set(e,c),c+=e.length;return this.partial=void 0,JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(s))}},Sr=class extends Error{},Cr=1,wr=e=>typeof e==`string`&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(e),Tr=e=>Number.isSafeInteger(e)&&e>0,Er=e=>e?.match(/(?:^|\r?\n)a=ice-ufrag:([^\s]+)/)?.[1],Dr=e=>e.usernameFragment??e.candidate?.match(/(?:^| )ufrag ([^ ]+)/)?.[1],Or=class{room;credentials;hooks;runtime;ws;peers=new Map;id=``;host=!1;hostId=``;closed=!1;timer;bytesSent=0;bytesReceived=0;pollingStats=!1;resumeGrant;recovery;resumeAttempt;socketSerial=0;requestSentAt=0;rosterRevision=-1;members=new Map;lockedState=null;get locked(){return this.lockedState}heartbeatSequence=0;heartbeatRequest;heartbeatTimer;heartbeatTimerVersion=0;heartbeatDeadline=0;cancelHeartbeat(){clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0,this.heartbeatTimerVersion++,this.heartbeatRequest=void 0}armHeartbeat(e){clearTimeout(this.heartbeatTimer);let t=++this.heartbeatTimerVersion;this.heartbeatTimer=setTimeout(()=>{t===this.heartbeatTimerVersion&&(this.heartbeatTimer=void 0,this.sendHeartbeat())},e)}scheduleHeartbeat(e,t){this.cancelHeartbeat();let n=performance.now()+e;this.heartbeatDeadline=t?n:Math.min(this.heartbeatDeadline,n);let r=this.heartbeatDeadline-performance.now();r>0&&this.signalingReady&&this.armHeartbeat(Math.max(1,Math.floor(Math.min(3e4,r/3))))}sendHeartbeat(){let e=this.heartbeatDeadline-performance.now();if(!this.signalingReady||!this.resumeGrant||!this.recovery||e<=0)return;this.heartbeatRequest??={id:++this.heartbeatSequence,sentAt:performance.now(),localEpoch:this.recovery.epoch,transmissions:0,retryDelay:Math.max(1,Math.floor(Math.min(5e3,e/3)))};let t=this.heartbeatRequest;if(!(t.transmissions>=3)){t.transmissions++;try{this.signal({type:`heartbeat`,requestId:t.id,connectionEpoch:this.resumeGrant.connectionEpoch})}catch{}this.heartbeatRequest===t&&this.signalingReady&&t.transmissions<3&&t.retryDelay<e&&this.armHeartbeat(t.retryDelay)}}get signalingReady(){return!this.closed&&!!this.id&&this.ws.readyState===Cr&&this.signalingAdmitted}get signalingAdmitted(){return!this.recovery||this.recovery.status===`admitted`}verificationState=null;get requireVerification(){return this.verificationState}verificationSequence=0;verificationRequest;challenge;rejectVerification(e,t=!0){let n=this.verificationRequest;n&&(this.verificationRequest=void 0,clearTimeout(n.timer),t&&(this.verificationState=null),n.reject(Error(e)))}setRequireVerification(e){return typeof e==`boolean`?this.closed||!this.host||!this.signalingAdmitted||this.ws.readyState!==Cr?Promise.reject(Error(`An active room-owner connection is required.`)):this.verificationRequest?Promise.reject(Error(`A verification update is already pending.`)):new Promise((t,n)=>{let r=++this.verificationSequence,i=setTimeout(()=>this.rejectVerification(`Verification update was not confirmed.`),1e4);this.verificationRequest={id:r,timer:i,resolve:t,reject:n};try{this.signal({type:`setVerification`,required:e,requestId:r})}catch{this.rejectVerification(`Verification update could not be sent.`)}}):Promise.reject(Error(`Expected a boolean.`))}passwordRequestId=0;passwordRequest;rejectPasswordUpdate(e){let t=this.passwordRequest;t&&(this.passwordRequest=void 0,clearTimeout(t.timer),t.reject(Error(e)))}setPassword(e){return e!==null&&(typeof e!=`string`||e.length>64)?Promise.reject(Error(`Password must contain at most 64 characters.`)):this.closed||!this.host||!this.signalingAdmitted||this.ws.readyState!==Cr?Promise.reject(Error(`An active room-owner connection is required.`)):this.passwordRequest?Promise.reject(Error(`A password update is already pending.`)):new Promise((t,n)=>{let r=++this.passwordRequestId,i=setTimeout(()=>this.rejectPasswordUpdate(`Password update was not confirmed.`),1e4);this.passwordRequest={id:r,timer:i,resolve:t,reject:n};try{this.signal({type:`setPassword`,requestId:r,password:e??``})}catch{this.rejectPasswordUpdate(`Password update could not be sent.`)}})}banSequence=0;banRequest;rejectBan(e,t=!0){let n=this.banRequest;n&&(this.banRequest=void 0,clearTimeout(n.timer),n.reject(t?new Sr(e):Error(e)))}updateBan(e,t,n){return this.closed||!this.host||!this.signalingAdmitted||this.ws.readyState!==Cr?Promise.reject(Error(`An active room-owner connection is required.`)):this.banRequest?Promise.reject(Error(`A ban operation is already pending.`)):new Promise((r,i)=>{let a=++this.banSequence,o=setTimeout(()=>this.rejectBan(`Ban operation was not confirmed.`),1e4);this.banRequest={id:a,resolve:r,reject:i,timer:o};try{this.signal({type:e,id:t,requestId:a,...e===`ban`&&n!==void 0?{reason:n}:{}})}catch{this.rejectBan(`Ban operation could not be sent.`)}})}get rtt(){let e=[...this.peers.values()].filter(e=>e.connected&&e.lostAt===void 0).map(e=>e.rtt).filter(e=>typeof e==`number`);return e.length?Math.max(...e):null}signalQueue=Promise.resolve();lastHeartbeat=0;controlId=0;controlAssemblers=new Map;constructor(e,t,n,r=Mn()){this.room=e,this.credentials=t,this.hooks=n,this.runtime=r;let i=new URL(re.signal(e),kn(r.serviceOrigin));i.protocol=i.protocol===`https:`?`wss:`:`ws:`,this.ws=r.createWebSocket(i),this.attachSocket(this.ws,()=>{this.requestSentAt=performance.now(),this.signal({type:`hello`,...t,...r.signalingResume?{signalingVersion:2}:{}})},0),this.timer=setInterval(()=>{!this.resumeGrant&&this.signalingAdmitted&&this.ws.readyState===Cr&&performance.now()-this.lastHeartbeat>=3e4&&(this.signal({type:`heartbeat`}),this.lastHeartbeat=performance.now());for(let e of this.peers.values()){if(!e.connected&&performance.now()-e.created>2e4){n.status(`Could not connect directly to this room. Try another network or room.`,`error`),this.remove(e.id);continue}e.lostAt!==void 0&&(performance.now()-e.lostAt>2e4?(n.status(`The direct connection could not be recovered. Rejoin the room.`,`error`),this.remove(e.id)):this.host&&performance.now()-e.lastRestart>5e3&&this.restartPeer(e.id))}},5e3)}attachSocket(e,t,n){let r=++this.socketSerial,i=()=>!this.closed&&this.ws===e&&this.socketSerial===r;e.onopen=()=>{i()&&t()},e.onmessage=e=>{i()&&(this.signalQueue=this.signalQueue.then(async()=>{i()&&await this.message(JSON.parse(e.data),r)}).catch(()=>{i()&&this.hooks.status(`Connection negotiation failed. Try another room or network.`,`error`)}))},e.onclose=e=>{if(i()){if(this.socketSerial++,this.challenge?.abort(),this.cancelHeartbeat(),this.rejectVerification(`Signaling disconnected before verification confirmation.`),this.rejectBan(`Signaling disconnected before ban confirmation.`),this.rejectPasswordUpdate(`Signaling disconnected before password confirmation.`),this.recovery&&this.resumeGrant&&![1e3,1008,1009].includes(e.code)){this.recovery.disconnected(n),this.hooks.status(`Signaling interrupted. Reconnecting…`,`info`);return}if(!this.id||this.recovery||[1001,1008,1009].includes(e.code)){this.close(),this.hooks.ended?.(e.reason||`Room connection ended.`);return}this.hooks.status(e.reason||`Signaling disconnected. Established matches can continue; new joins are unavailable.`,`error`)}},e.onerror=()=>{i()&&this.hooks.status(`Room service is unavailable.`,`error`)}}startRecovery(e){let t=Math.floor(e.membershipValidForMs-(performance.now()-this.requestSentAt));if(t<=0){this.close(),this.hooks.ended?.(`Room membership expired.`);return}this.resumeGrant=e,this.recovery=new tr({now:()=>performance.now(),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),random:()=>Math.random(),newAttemptId:()=>crypto.randomUUID(),createAttempt:(e,t)=>{this.resumeAttempt=e;let n=new URL(re.signal(this.room),kn(this.runtime.serviceOrigin));n.protocol=n.protocol===`https:`?`wss:`:`ws:`;let r=this.runtime.createWebSocket(n);return this.ws=r,this.attachSocket(r,()=>{t.opened();let n=this.resumeGrant;this.recovery?.status===`awaiting-ack`&&n&&(this.requestSentAt=performance.now(),r.send(JSON.stringify({type:`resume`,version:2,roomGeneration:n.roomGeneration,peerId:this.id,secret:n.secret,attemptId:e.attemptId,expectedEpoch:n.connectionEpoch})))},e.epoch),{close:()=>{this.ws===r&&this.socketSerial++,r.onopen=null,r.onmessage=null,r.onclose=null,r.onerror=null,r.close()}}},onExpired:()=>{this.close(),this.hooks.ended?.(`Room signaling recovery expired.`)},onRecovered:()=>{}},t),this.scheduleHeartbeat(t,!0)}signal(e){!this.closed&&this.signalingAdmitted&&this.ws.readyState===Cr&&this.ws.send(JSON.stringify(e))}async message(e,t=this.socketSerial){if(this.closed||t!==this.socketSerial)return;if(e.type===`terminal`){this.close(),this.hooks.ended?.(typeof e.reason==`string`&&e.reason.length<=123?e.reason:`Room connection ended.`);return}if(e.type===`resumed`){let n=fr(e),r=this.resumeGrant,i=this.resumeAttempt;if(!n||!r||!i||!this.recovery||n.roomGeneration!==r.roomGeneration||n.attemptId!==i.attemptId||n.id!==this.id||n.hostId!==this.hostId||n.role===`host`!==this.host||n.connectionEpoch<=r.connectionEpoch||n.rosterRevision<this.rosterRevision||n.members.some(e=>e.connectionEpoch<(this.members.get(e.id)?.connectionEpoch??0)))return;let a=Math.floor(n.membershipValidForMs-(performance.now()-this.requestSentAt));if(a<=0||!this.recovery.acknowledge(i.epoch,a))return;this.resumeGrant={...r,connectionEpoch:n.connectionEpoch,membershipValidForMs:a},this.resumeAttempt=void 0,this.scheduleHeartbeat(a,!1),this.verificationState=n.requireVerification,this.lockedState=n.locked,this.reconcile(n.members,n.rosterRevision,t),this.hooks.status(`Room signaling restored.`,`info`);return}if(e.type===`heartbeat`&&this.resumeGrant&&this.recovery){let t=this.heartbeatRequest;if(!t||e.requestId!==t.id||e.connectionEpoch!==this.resumeGrant.connectionEpoch||typeof e.membershipValidForMs!=`number`||!Number.isSafeInteger(e.membershipValidForMs)||e.membershipValidForMs<1||e.membershipValidForMs>9e4)return;let n=Math.floor(e.membershipValidForMs-(performance.now()-t.sentAt));n>0&&this.recovery.heartbeat(t.localEpoch,n)&&this.scheduleHeartbeat(n,!0);return}if(this.recovery&&!this.signalingAdmitted)return;if(e.type===`roster`&&this.resumeGrant){let n=hr(e);if(!n||n.roomGeneration!==this.resumeGrant.roomGeneration||n.hostId!==this.hostId||n.rosterRevision<=this.rosterRevision)return;let r=n.members.find(e=>e.id===this.id);if(!r?.attached||r.connectionEpoch!==this.resumeGrant.connectionEpoch||r.role===`host`!==this.host){this.close(),this.hooks.ended?.(`Room membership ended.`);return}if(n.members.some(e=>e.connectionEpoch<(this.members.get(e.id)?.connectionEpoch??0)))return;this.reconcile(n.members,n.rosterRevision,t);return}if(e.type===`verificationUpdated`&&this.verificationRequest&&this.verificationRequest.id===e.requestId){if(e.ok!==!0||typeof e.required!=`boolean`)this.rejectVerification(typeof e.error==`string`?e.error:`Verification update failed.`,e.ok!==!1);else{let t=this.verificationRequest;this.verificationRequest=void 0,clearTimeout(t.timer),this.verificationState=e.required,t.resolve(e.required)}return}if(e.type===`verificationRequired`){if(this.closed||this.id||this.credentials.hostToken||this.challenge||e.roomId!==this.room||typeof e.siteKey!=`string`||!/^[A-Za-z0-9_-]{1,100}$/.test(e.siteKey))return;if(!this.hooks.verify){this.close(),this.hooks.ended?.(`This client cannot complete the room verification challenge.`);return}let t=new AbortController;this.challenge=t;try{let n=await this.hooks.verify({siteKey:e.siteKey,roomId:this.room},t.signal);if(t.signal.aborted||this.closed||this.ws.readyState!==Cr)return;if(typeof n!=`string`||n.length===0||n.length>2048)throw Error(`Invalid verification response.`);this.requestSentAt=performance.now(),this.signal({type:`hello`,...this.credentials,verificationToken:n,...this.runtime.signalingResume?{signalingVersion:2}:{}})}catch(e){this.closed||(this.close(),this.hooks.ended?.(e instanceof Error?e.message:`Room verification failed.`))}finally{this.challenge===t&&(this.challenge=void 0)}return}if(e.type===`passwordUpgradeRequired`&&this.host){this.hooks.status(`Update the room password or explicitly unlock it to allow new guests.`,`error`);return}if(e.type===`passwordUpdated`&&e.ok===!1&&this.passwordRequest?.id===e.requestId){this.rejectPasswordUpdate(typeof e.error==`string`?e.error:`Password update failed.`);return}if(e.type===`passwordUpdated`&&typeof e.locked==`boolean`&&this.passwordRequest&&this.passwordRequest.id===e.requestId){let t=this.passwordRequest;this.passwordRequest=void 0,clearTimeout(t.timer),t.resolve(e.locked);return}if(e.type===`banResult`&&this.banRequest&&this.banRequest.id===e.requestId){if(e.ok!==!0)this.rejectBan(typeof e.error==`string`?e.error:`Ban operation failed.`,!1);else{let e=this.banRequest;this.banRequest=void 0,clearTimeout(e.timer),e.resolve()}return}if(e.type===`ready`){if(this.id)return;if(this.runtime.signalingResume&&e.resumeGrant!==void 0){let t=pr(e);if(!t){this.close(),this.hooks.ended?.(`Invalid room admission.`);return}if(this.id=t.id,this.host=t.role===`host`,this.hostId=t.hostId,this.verificationState=t.requireVerification,this.lockedState=t.locked,this.startRecovery(t.resumeGrant),this.closed)return;this.members=new Map(t.members.map(e=>[e.id,e])),this.rosterRevision=t.rosterRevision}else this.id=e.id,this.host=e.role===`host`,this.hostId=e.hostId,this.verificationState=typeof e.requireVerification==`boolean`?e.requireVerification:null;this.hooks.ready(this.id,this.host),this.resumeGrant&&this.reconcile([...this.members.values()],this.rosterRevision,t);return}if(e.type===`peer`||e.type===`leave`){if(this.resumeGrant){if(!wr(e.id)||!Tr(e.connectionEpoch)||typeof e.rosterRevision!=`number`||!Number.isSafeInteger(e.rosterRevision)||e.rosterRevision<=this.rosterRevision||e.id===this.id)return;let t=this.members.get(e.id);if(t&&e.connectionEpoch<t.connectionEpoch)return;this.rosterRevision=e.rosterRevision,e.type===`peer`?this.members.set(e.id,{id:e.id,role:e.id===this.hostId?`host`:`guest`,attached:!0,connectionEpoch:e.connectionEpoch}):this.members.delete(e.id)}if(e.type===`leave`){this.remove(e.id,!1);return}this.host&&!this.peers.has(e.id)&&await this.offerPeer(e.id,t);return}if(e.type!==`signal`||this.resumeGrant&&(!wr(e.negotiationId)||e.toConnectionEpoch!==this.resumeGrant.connectionEpoch||e.fromConnectionEpoch!==this.members.get(e.from)?.connectionEpoch||!this.members.get(e.from)?.attached))return;let n=this.peers.get(e.from);if(!n){if(this.host||e.from!==this.hostId||![`offer`,`candidate`].includes(e.signal.type))return;n=this.make(e.from)}if(this.resumeGrant){if(!wr(e.negotiationId))return;if(e.signal.type===`offer`){if(this.host||!Er(e.signal.sdp))return;n.negotiationId!==e.negotiationId&&(n.candidates=[]),this.beginNegotiation(n,e.negotiationId),n.remoteIceUfrag=Er(e.signal.sdp),n.localIceUfrag=void 0}else if(e.signal.type===`candidate`&&!n.negotiationId&&!this.host)this.beginNegotiation(n,e.negotiationId);else if(n.negotiationId!==e.negotiationId)return;if(n.negotiationLocalEpoch!==e.toConnectionEpoch||n.negotiationRemoteEpoch!==e.fromConnectionEpoch)return;if(e.signal.type===`answer`){if(!Er(e.signal.sdp))return;n.remoteIceUfrag=Er(e.signal.sdp)}}let r=n,i=r.negotiationId,a=()=>this.current(r)&&t===this.socketSerial&&this.signalingAdmitted&&r.negotiationId===i&&this.negotiationCurrent(r);if(e.signal.type===`offer`){if(this.host)throw Error(`Only the host can offer`);if(await n.pc.setRemoteDescription({type:`offer`,sdp:e.signal.sdp}),!a()||(await this.flushCandidates(n,a),!a()))return;let t=await n.pc.createAnswer();if(!a()||(n.localIceUfrag=Er(t.sdp),await n.pc.setLocalDescription(t),!a()))return;this.peerSignal(n,{type:`answer`,sdp:this.localSdp(n)})}else if(e.signal.type===`answer`){if(!this.host)throw Error(`Only guests can answer`);if(await n.pc.setRemoteDescription({type:`answer`,sdp:e.signal.sdp}),!a())return;await this.flushCandidates(n,a),this.noteHealthy(n)}else if(e.signal.type===`candidate`&&e.signal.candidate){if(this.resumeGrant&&(!Dr(e.signal.candidate)||n.remoteIceUfrag&&Dr(e.signal.candidate)!==n.remoteIceUfrag))return;if(!n.pc.remoteDescription)this.queueCandidate(n,e.signal.candidate);else try{await n.pc.addIceCandidate(e.signal.candidate)}catch{a()&&this.queueCandidate(n,e.signal.candidate)}}}reconcile(e,t,n){this.members=new Map(e.map(e=>[e.id,e])),this.rosterRevision=t;for(let e of[...this.peers.keys()])this.members.has(e)||this.remove(e,!1);if(this.host)for(let t of e)t.id!==this.id&&t.attached&&!this.peers.has(t.id)&&this.offerPeer(t.id,n).catch(()=>{!this.closed&&n===this.socketSerial&&this.hooks.status(`Connection negotiation failed.`,`error`)})}negotiationCurrent(e){return!this.resumeGrant||e.negotiationLocalEpoch===this.resumeGrant.connectionEpoch&&e.negotiationRemoteEpoch===this.members.get(e.id)?.connectionEpoch&&this.members.get(e.id)?.attached===!0}beginNegotiation(e,t){e.negotiationId=t,e.negotiationLocalEpoch=this.resumeGrant?.connectionEpoch,e.negotiationRemoteEpoch=this.members.get(e.id)?.connectionEpoch}peerSignal(e,t){let n=this.resumeGrant,r=this.members.get(e.id);(!n||r?.attached&&e.negotiationId&&this.signalingAdmitted&&e.negotiationLocalEpoch===n.connectionEpoch&&e.negotiationRemoteEpoch===r.connectionEpoch)&&this.signal({type:`signal`,to:e.id,signal:t,...n&&r?{fromConnectionEpoch:n.connectionEpoch,toConnectionEpoch:r.connectionEpoch,negotiationId:e.negotiationId}:{}})}async offerPeer(e,t){let n=this.make(e);this.bind(n,n.pc.createDataChannel(`control`,{ordered:!0})),this.bind(n,n.pc.createDataChannel(`realtime`,{ordered:!1,maxRetransmits:0})),this.resumeGrant&&this.beginNegotiation(n,crypto.randomUUID());let r=n.negotiationId,i=()=>this.current(n)&&t===this.socketSerial&&this.signalingAdmitted&&n.negotiationId===r&&this.negotiationCurrent(n),a=await n.pc.createOffer();i()&&(n.localIceUfrag=Er(a.sdp),await n.pc.setLocalDescription(a),i()&&this.peerSignal(n,{type:`offer`,sdp:this.localSdp(n)}))}localSdp(e){let t=e.pc.localDescription;if(!t)throw Error(`Local peer description is unavailable`);return t.sdp}current(e){return!this.closed&&this.peers.get(e.id)===e}queueCandidate(e,t){if(this.current(e)){if(e.candidates.length>=128)throw Error(`Too many pending ICE candidates`);e.candidates.push(t)}}noteHealthy(e){if(!this.current(e)||e.pc.connectionState!==`connected`||![`connected`,`completed`].includes(e.pc.iceConnectionState))return;let t=e.lostAt!==void 0;e.lostAt=void 0,e.restarts=0,t&&this.hooks.status(`Direct connection restored.`,`info`)}async flushCandidates(e,t=()=>this.current(e)){let n=e.candidates.splice(0);for(let r of n){if(!t())return;if(!this.resumeGrant||e.remoteIceUfrag&&Dr(r)===e.remoteIceUfrag)try{await e.pc.addIceCandidate(r)}catch{}}}async restartPeer(e){let t=this.peers.get(e);if(this.closed||!this.host||!t||t.restarting||t.restarts>=2||t.pc.signalingState!==`stable`||!this.signalingAdmitted||this.ws.readyState!==Cr)return!1;let n=this.socketSerial;this.resumeGrant&&(this.beginNegotiation(t,crypto.randomUUID()),t.localIceUfrag=void 0,t.remoteIceUfrag=void 0,t.candidates=[]);let r=t.negotiationId,i=()=>this.current(t)&&n===this.socketSerial&&this.signalingAdmitted&&t.negotiationId===r&&this.negotiationCurrent(t);t.restarting=!0,t.lastRestart=performance.now(),t.lostAt??=t.lastRestart,t.restarts++;try{let e=await t.pc.createOffer({iceRestart:!0});return!i()||(t.localIceUfrag=Er(e.sdp),await t.pc.setLocalDescription(e),!i())?!1:(this.peerSignal(t,{type:`offer`,sdp:this.localSdp(t)}),!0)}catch{return!this.closed&&this.peers.get(e)===t&&this.hooks.status(`Direct connection recovery is still pending.`,`info`),!1}finally{t.restarting=!1}}make(e){let t=this.runtime.createPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}],bundlePolicy:`max-bundle`}),n={id:e,pc:t,connected:!1,created:performance.now(),candidates:[],lastRestart:0,restarts:0,restarting:!1};this.peers.set(e,n),t.onicecandidate=e=>{if(!this.current(n)||!e.candidate||!this.signalingAdmitted)return;let t=e.candidate.toJSON();(!this.resumeGrant||n.localIceUfrag&&Dr(t)===n.localIceUfrag)&&this.peerSignal(n,{type:`candidate`,candidate:t})},t.ondatachannel=e=>this.bind(n,e.channel);let r=()=>{this.closed||this.peers.get(e)!==n||(t.connectionState===`closed`?(this.hooks.status(`A peer disconnected.`,`info`),this.remove(e)):t.connectionState===`connected`&&[`connected`,`completed`].includes(t.iceConnectionState)?this.noteHealthy(n):([`failed`,`disconnected`].includes(t.connectionState)||[`failed`,`disconnected`].includes(t.iceConnectionState))&&(n.lostAt??=performance.now(),this.hooks.status(`Direct connection interrupted. Attempting recovery…`,`info`)))};return t.onconnectionstatechange=r,t.oniceconnectionstatechange=r,n}bind(e,t){if(this.closed||this.peers.get(e.id)!==e||![`control`,`realtime`].includes(t.label)){t.close();return}if(t.maxPacketLifeTime!==null||t.label===`control`&&(t.ordered!==!0||t.maxRetransmits!==null)||t.label===`realtime`&&(t.ordered!==!1||t.maxRetransmits!==0)||(t.label===`control`?e.control:e.fast)){t.close(),this.remove(e.id);return}t.binaryType=`arraybuffer`,t.label===`control`?e.control=t:e.fast=t,t.onclose=()=>{!this.closed&&this.peers.get(e.id)===e&&(this.hooks.status(`A peer closed its game channel.`,`info`),this.remove(e.id))},t.onopen=()=>{this.closed||this.peers.get(e.id)!==e||e.control?.readyState===`open`&&e.fast?.readyState===`open`&&!e.connected&&(e.connected=!0,this.host&&(e.admissionTimer=setTimeout(()=>{this.closed||this.peers.get(e.id)!==e||(this.hooks.status(`A peer did not complete room admission.`,`error`),this.remove(e.id))},1e4)),this.hooks.open(e))},t.onmessage=n=>{if(!(this.closed||this.peers.get(e.id)!==e)){this.bytesReceived+=typeof n.data==`string`?n.data.length:n.data.byteLength;try{if(t.label===`control`){let t=typeof n.data!=`string`||new TextEncoder().encode(n.data).length>4096;if(this.host&&t&&!this.hooks.allowStadiumUpload?.(e))throw Error(`Guest control size or permission`);if(typeof n.data!=`string`&&!(n.data instanceof ArrayBuffer))throw Error(`Invalid control type`);let r=this.controlAssemblers.get(e.id);r||(r=new xr,this.controlAssemblers.set(e.id,r));let i=r.push(n.data);if(i!==void 0){if(this.host&&t&&(!i||typeof i!=`object`||i.type!==`action`||i.action!==`customStadium`))throw Error(`Invalid bulk action`);this.hooks.control(e,i)}}else if(n.data instanceof ArrayBuffer&&n.data.byteLength<=1200)this.hooks.fast(e,n.data);else throw Error()}catch{this.hooks.status(`Invalid peer message rejected.`,`error`),this.remove(e.id)}}}}admit(e){clearTimeout(e.admissionTimer),e.admissionTimer=void 0}control(e,t){if(e.control?.readyState!==`open`)return;let n=br(t,this.controlId++),r=n.reduce((e,t)=>e+(typeof t==`string`?new TextEncoder().encode(t).length:t.byteLength),0);if(e.control.bufferedAmount+r>1048576){this.remove(e.id);return}for(let t of n)e.control.send(t);this.bytesSent+=r}fast(e,t){e.fast?.readyState===`open`&&e.fast.bufferedAmount<32768&&(e.fast.send(t),this.bytesSent+=t.byteLength)}broadcast(e){for(let t of this.peers.values())this.control(t,e)}async stats(){if(!(this.pollingStats||this.closed)){this.pollingStats=!0;try{await Promise.allSettled([...this.peers.values()].map(async e=>{if(!e.connected||e.lostAt!==void 0){e.rtt=null;return}try{let t=await e.pc.getStats();!this.closed&&this.peers.get(e.id)===e&&(e.rtt=gr(t.values()))}catch{e.rtt=null}}))}finally{this.pollingStats=!1}}}hostCloseTimer;remove(e,t=!0){let n=this.peers.get(e);if(n&&(clearTimeout(n.admissionTimer),this.peers.delete(e),this.controlAssemblers.delete(e),n.pc.close(),this.host&&t&&this.signal({type:`evict`,id:e}),this.hooks.leave(e),!this.host)){let e=()=>{this.close(),this.hooks.ended?.(`The host connection ended.`)};this.signalingAdmitted&&this.ws.readyState===Cr?this.hostCloseTimer=setTimeout(e,1e3):e()}}close(){if(!this.closed){clearTimeout(this.hostCloseTimer),this.hostCloseTimer=void 0,this.resumeGrant&&this.signalingAdmitted&&this.ws.readyState===Cr&&this.signal({type:`leave`,connectionEpoch:this.resumeGrant.connectionEpoch}),this.recovery?.cancel(),this.resumeGrant=void 0,this.resumeAttempt=void 0,this.cancelHeartbeat(),this.socketSerial++,this.challenge?.abort(),this.rejectVerification(`Room closed before verification confirmation.`),this.verificationState=null,this.rejectBan(`Room closed before ban confirmation.`),this.rejectPasswordUpdate(`Room closed before password confirmation.`),this.closed=!0,clearInterval(this.timer),this.ws.close(1e3,`Left room`);for(let e of this.peers.values())clearTimeout(e.admissionTimer),e.pc.close();this.peers.clear(),this.controlAssemblers.clear()}}},kr=5;function Ar(e,t){return e!==t&&e-t>>>0<2147483648}function jr(e){if(e.byteLength!==14)throw Error(`Input length`);let t=new DataView(e);if(t.getUint8(0)!==1||t.getUint8(1)!==kr||t.getUint8(6)>31||t.getUint8(7))throw Error(`Input format`);return{seq:t.getUint32(2,!0),keys:t.getUint8(6),time:t.getUint32(8,!0),epoch:t.getUint16(12,!0)}}function Mr(e,t,n=0){if(e.surface?.length)throw Error(`Terrain transport is not enabled`);let r=[];for(let t=0;t<e.discs.length/18;t++){let n=t*18,i=e.discs,a=i[n+5]>0||i[n+2]!==0||i[n+3]!==0||i[n+8]!==0||i[n+9]!==0||i[n]!==i[n+16]||i[n+1]!==i[n+17];(i[n+12]>0?i[n+13]>0:a)&&r.push(t)}let i=[`lobby`,`playing`,`goal`,`finished`],a=new ArrayBuffer(36+r.length*24),o=new DataView(a);o.setUint32(0,e.tick,!0),o.setUint32(4,e.elapsed,!0),o.setUint16(8,e.red,!0),o.setUint16(10,e.blue,!0),o.setUint8(12,i.indexOf(e.phase)),o.setUint8(13,+e.paused),o.setUint8(14,e.kickoff),o.setUint8(15,+e.kickoffActive),o.setUint16(16,e.countdown,!0),o.setUint16(18,e.scoreLimit,!0),o.setUint16(20,e.timeLimit,!0),o.setUint16(22,e.discs.length/18,!0),o.setUint32(24,t,!0),o.setUint16(28,r.length,!0),o.setUint16(30,e.resumeTicks,!0),o.setUint32(32,e.kickRate,!0),r.forEach((t,n)=>{let r=t*18,i=36+n*24;o.setUint16(i,t,!0),o.setUint8(i+2,e.discs[r+13]),o.setUint8(i+3,e.discs[r+14]|(e.discs[r+12]>0?(e.discs[r+11]&24)<<2:0));for(let t=0;t<4;t++)o.setFloat32(i+4+t*4,e.discs[r+t],!0);o.setUint16(i+20,e.discs[r+15],!0),e.discs[r+12]>0&&o.setUint16(i+22,e.discs[r+17]+255,!0)});let s=new Uint8Array(a),c=[],l=Math.ceil(s.length/1188);for(let t=0;t<l;t++){let r=s.subarray(t*1188,(t+1)*1188),i=new ArrayBuffer(12+r.length),a=new DataView(i);a.setUint8(0,2),a.setUint8(1,kr),a.setUint32(2,e.tick,!0),a.setUint8(6,t),a.setUint8(7,l),a.setUint16(8,n,!0),a.setUint16(10,r.length,!0),new Uint8Array(i,12).set(r),c.push(i)}return c}var Nr=Object.freeze({...fn}),Pr=class e{runtime;engine;network;roomId=``;roomLink=``;roomName=``;epoch=0;kickStream=new ht;stadiumSelection=0;players=[];nextPlayerId=0;bans=new Map;loop;linkNotification;last=performance.now();accumulator=0;recorder;closed=!1;closeController=new AbortController;signal=this.closeController.signal;finishingRecording=!1;lastRecording=null;onRecordingComplete;locked=!1;teamStyles=[null,null];inputs=new Map;traffic=new Ln;onRoomLink;onPlayerJoin;onPlayerTeamChange;onPlayerMuteChange;onPlayerAdminChange;onGameStart;onGameStop;onTeamVictory;onGameVictory;onGamePauseChange;onGamePause;onGameUnpause;onPlayerLeave;onPlayerKicked;onPlayerActivity;onPlayerChat;onPlayerBallKick;onTeamGoal;onPositionsReset;onStadiumChange;onTeamsLockChange;onKickRateLimitSet;onGameTick;onError;report(e){try{let t=this.onError?.(e);t instanceof Promise&&t.catch(()=>{})}catch{}}invoke(e,t,...n){if(!(this.closed&&e!==`onRecordingComplete`))try{let r=t?.apply(this,n);return r instanceof Promise&&r.catch(t=>this.report(`${e}: ${String(t)}`)),r}catch(t){this.report(`${e}: ${String(t)}`);return}}constructor(e,t){this.runtime=t,this.engine=e}static async create(t,n=Fn(),r){let i=kn(n.network.serviceOrigin),a=kn(n.publicOrigin??i);if(t=vt(t),t.noPlayer!==void 0&&typeof t.noPlayer!=`boolean`)throw Error(`Invalid noPlayer setting`);let o=t.noPlayer===!1,s=t.playerName??`Host`;if(o&&(typeof s!=`string`||!s.trim()||s.length>24))throw Error(`Invalid host player name`);let c=pt(r),l;try{c.signal.throwIfAborted();let r=await c.run(n.loadEngine(c.signal));r.load(t.stadium??wn()),l=new e(r,n);let u=l,d=await c.run(n.request(new URL(re.rooms,i),{signal:c.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t.roomName,maxPlayers:t.maxPlayers??16,password:t.password??``,private:t.public===!1,hostPlayer:o})}));if(!d.ok)throw await c.run(mt(d,c.signal));let f=await c.run(d.json());u.roomId=f.id,u.roomName=t.roomName,u.roomLink=`${a}${bt(f.id)}`;let p;try{await c.run(new Promise((e,t)=>{p=setTimeout(()=>t(Error(`Signaling timed out`)),12e3),u.network=new Or(f.id,{hostToken:f.hostToken},{ready:(n,r)=>{if(!r){t(Error(`Host authority was not granted`));return}o&&(u.players.push({id:u.nextPlayerId++,slot:0,peerId:n,name:s.trim(),team:0,admin:!0}),u.engine.joinPlayer(0)),clearTimeout(p),e()},allowStadiumUpload:e=>!!u.players.find(t=>t.peerId===e.id)?.admin&&[`lobby`,`finished`].includes(u.engine.phase)&&u.traffic.allow(e.id,`message`),open:()=>{},control:(e,t)=>u.control(e,t),fast:(e,t)=>u.fast(e,t),leave:e=>u.leave(e),status:(e,t)=>{t===`error`&&u.report(e)},ended:e=>{clearTimeout(p),t(Error(e)),u.close(),u.report(e)}},n.network)}))}catch(e){throw u.close(),e}finally{clearTimeout(p)}if(u.closed)throw Error(`Room closed during startup`);u.last=performance.now(),u.loop=setInterval(()=>u.advance(),1e3/60);let m=u.roomLink;return u.linkNotification=setTimeout(()=>{u.linkNotification=void 0,u.invoke(`onRoomLink`,u.onRoomLink,m)},0),l}catch(e){throw l?.close(),e}finally{c.dispose()}}advance(){if(this.closed)return;let e=performance.now(),t=e-this.last;this.last=e,t>500&&this.engine.phase===`playing`&&!this.engine.paused&&(this.pauseGame(!0),this.report(`Host scheduler stalled; match paused.`)),this.accumulator+=Math.max(0,Math.min(t,500));let n=0;try{for(;!this.closed&&this.accumulator>=1e3/60&&n++<32;){for(let t of this.players){let n=this.inputs.get(t.peerId);n&&e-n.received>250&&this.engine.data[this.engine.index(t.slot)*18+14]&&this.command(`input`,t.slot,0)}if(this.recorder&&!this.recorder.canRecord(this.engine)&&this.finishRecording(`Recording limit reached`),this.closed||(this.engine.phase!==`lobby`&&!this.engine.paused&&!this.engine.resumeTicks&&this.invoke(`onGameTick`,this.onGameTick),this.closed))break;let t=this.engine.red,n=this.engine.blue,r=this.engine.phase;this.engine.step(),this.kickStream.capture(this.engine,this.epoch),this.recorder?.step(this.engine),this.engine.phase!==r&&this.state();let i=r===`goal`&&this.engine.phase===`playing`,a=r===`finished`&&this.engine.phase===`lobby`,o=this.engine.red>t,s=this.engine.blue>n,c=this.engine.ballKicks.map(e=>{let t=this.players.find(t=>t.slot===e);return t?this.playerCopy(t):null}).filter(e=>!!e),l=r!==`finished`&&this.engine.phase===`finished`?this.getScores():null;a&&this.invoke(`onGameStop`,this.onGameStop,null),l&&(this.invoke(`onTeamVictory`,this.onTeamVictory,{...l}),this.invoke(`onGameVictory`,this.onGameVictory,{...l}));for(let e of c)this.invoke(`onPlayerBallKick`,this.onPlayerBallKick,e);if(o&&this.invoke(`onTeamGoal`,this.onTeamGoal,1),s&&this.invoke(`onTeamGoal`,this.onTeamGoal,2),i&&this.invoke(`onPositionsReset`,this.onPositionsReset),this.closed)break;if(this.engine.tick%2==0){let e=this.engine.snapshot();if(e.surface?.length){if(this.engine.tick%6==0){let t=ft(e,this.epoch);for(let e of this.network.peers.values())e.control?.readyState===`open`&&e.control.bufferedAmount<65536&&this.network.control(e,{...t,ack:this.inputs.get(e.id)?.seq??0})}}else for(let t of this.network.peers.values())for(let n of Mr(e,this.inputs.get(t.id)?.seq??0,this.epoch))this.network.fast(t,n)}this.accumulator-=1e3/60}this.closed||gt(this.network,this.kickStream.drain(e))}catch(e){this.closed||(this.engine.setPaused(!0),this.report(String(e)))}}allowed(e){return this.traffic.allow(e.id,`message`)?!0:(this.network.remove(e.id),!1)}control(e,t){if(!this.allowed(e)||!t||typeof t!=`object`)return;let n=t,r=this.players.find(t=>t.peerId===e.id);if(n.type===`join`&&!r){if(n.version!==1||n.engine!==Tn||typeof n.name!=`string`||!n.name.trim()||n.name.length>24){this.network.remove(e.id);return}let t=Array.from({length:32},(e,t)=>t).find(e=>!this.players.some(t=>t.slot===e));if(t===void 0){this.network.remove(e.id);return}r={id:this.nextPlayerId++,slot:t,peerId:e.id,name:n.name.trim(),team:0,admin:!1},this.players.push(r),this.network.admit(e),this.recorder?.player(this.engine.tick,r.slot,r.name),this.command(`join`,t,0),this.network.control(e,{type:`welcome`,kickStream:this.kickStream.checkpoint(),epoch:this.epoch,roomName:this.roomName,engine:Tn,slot:t,stadium:this.engine.source,state:this.engine.snapshot(),players:this.roster(),teamStyles:this.teamStyles,locked:this.locked}),this.sync(),this.invoke(`onPlayerJoin`,this.onPlayerJoin,this.playerCopy(r));return}if(r&&n.type===`action`){if(n.action===`chat`&&typeof n.text==`string`&&n.text.length<=200){if(r.muted||!n.text.trim()||!this.traffic.allow(e.id,`chat`)||(this.invoke(`onPlayerActivity`,this.onPlayerActivity,this.playerCopy(r)),this.closed||!this.players.includes(r)))return;this.invoke(`onPlayerChat`,this.onPlayerChat,this.playerCopy(r),n.text)!==!1&&!this.closed&&this.players.includes(r)&&!r.muted&&this.network.broadcast({type:`chat`,name:r.name,text:n.text})}if(n.action===`chat`||this.traffic.allow(e.id,`action`)){if(n.action===`avatar`&&Tt(n.avatar)){r.avatar=n.avatar,this.recorder?.player(this.engine.tick,r.slot,r.name,r.avatarOverride??r.avatar),this.sync();return}if(n.action===`team`&&oe(n.team)){let e=n.slot===void 0?r:this.players.find(e=>e.slot===n.slot);le(r,e,this.locked)&&this.changeTeam(e.id,n.team,r)}if(n.action===`defaultStadium`||n.action===`customStadium`){let t=t=>{!this.closed&&this.players.includes(r)&&this.network.control(e,{type:`stadiumResult`,text:t})};if(!r.admin||![`lobby`,`finished`].includes(this.engine.phase)){t(`Stadium change rejected: admin permission and a stopped match are required.`);return}if(n.action===`defaultStadium`?typeof n.name!=`string`:typeof n.source!=`string`)return;let i=++this.stadiumSelection;(n.action===`defaultStadium`?this.runtime.loadStadium(n.name):Promise.resolve(n.source)).then(e=>{if(!this.closed&&this.players.includes(r)){if(i!==this.stadiumSelection||!r.admin||![`lobby`,`finished`].includes(this.engine.phase)){t(`Stadium change cancelled: room state or permissions changed.`);return}this.changeStadium(e,this.playerCopy(r)),t(`Stadium applied.`)}}).catch(()=>t(`Stadium could not be loaded. Please try again.`));return}if(r.admin){if(n.action===`mute`&&typeof n.muted==`boolean`){let e=this.players.find(e=>e.slot===n.slot);ue(r,e,e=>e.peerId===this.network.hostId)&&this.changePlayerMuted(e.id,n.muted,this.playerCopy(r));return}if(n.action===`surface`&&typeof n.enabled==`boolean`&&[`lobby`,`finished`].includes(this.engine.phase)){this.setSurfaceEnabled(n.enabled);return}if(n.action===`ban`||n.action===`clearBans`){let t=this.players.find(e=>e.slot===n.slot);if(n.action===`ban`&&!ue(r,t,e=>e.peerId===this.network.hostId))return;let i=t=>{!this.closed&&this.network.peers.has(e.id)&&this.network.control(e,{type:`moderationResult`,text:t})};if(n.action===`clearBans`){i(`Only the room owner can clear bans.`);return}if(!t)return;this.banPlayer(t.id,`Removed by admin`,this.playerCopy(r)).then(()=>i(`Player banned.`)).catch(e=>i(e instanceof Error?e.message:`Moderation failed.`));return}if(n.action===`teamColors`&&(n.team===1||n.team===2)){let e=n.palette;this.changeTeamColors(n.team,e===null?null:xt(e.angle,e.textColor,e.colors))}if(n.action===`kickRate`&&Number.isInteger(n.value)&&Number(n.value)>=0&&Number(n.value)<=6619135){let e=Number(n.value);this.changeKickRateLimit(e&255,e>>>8&255,e>>>16,this.playerCopy(r))}if(n.action===`start`&&this.beginGame(r),n.action===`stop`&&this.endGame(r),n.action===`pause`&&(n.paused===void 0||typeof n.paused==`boolean`)&&this.changePause(n.paused===void 0?!this.engine.paused:n.paused,this.playerCopy(r)),n.action===`settings`&&[`lobby`,`finished`].includes(this.engine.phase)){let e=ce(n);if(e){if(this.setScoreLimit(e.score),this.setTimeLimit(e.minutes),this.changeTeamsLock(e.locked,this.playerCopy(r)),this.closed)return;if(e.kickRate!==void 0&&e.kickRate!==this.engine.kickRate){let t=e.kickRate;this.changeKickRateLimit(t&255,t>>>8&255,t>>>16,this.playerCopy(r))}}}if(n.action===`kick`&&typeof n.slot==`number`){let e=this.players.find(e=>e.slot===n.slot);ue(r,e,e=>e.peerId===this.network.hostId)&&this.removePlayer(e.id,`Removed by host`,this.playerCopy(r))}}}}}fast(e,t){if(!this.allowed(e))return;let n=this.players.find(t=>t.peerId===e.id);if(!n)return;let r=jr(t);if(r.epoch!==this.epoch)return;let i=this.inputs.get(e.id);(!i||Ar(r.seq,i.seq))&&(this.inputs.set(e.id,{seq:r.seq,received:performance.now(),keys:r.keys}),this.command(`input`,n.slot,r.keys),r.keys!==(i?.keys??0)&&this.invoke(`onPlayerActivity`,this.onPlayerActivity,this.playerCopy(n)))}command(e,t=0,n=0){if(this.closed)throw Error(`Room is closed`);let r={tick:this.engine.tick,kind:e,slot:t,value:n};if(this.recorder&&(!this.recorder.canRecord(this.engine)||!this.recorder.command(r))&&this.finishRecording(`Recording limit reached`),this.closed)throw Error(`Room is closed`);Xn(this.engine,r)}roster(){return this.players.map(e=>({avatar:e.avatarOverride??e.avatar??null,id:e.peerId,slot:e.slot,name:e.name,team:e.team,admin:e.admin,muted:!!e.muted}))}sync(){this.network.broadcast({type:`lobby`,players:this.roster(),teamStyles:this.teamStyles,locked:this.locked,scoreLimit:this.engine.scoreLimit,timeLimit:this.engine.timeLimit})}state(){this.network.broadcast({type:`state`,epoch:this.epoch,state:this.engine.snapshot()})}leave(e){this.traffic.delete(e);let t=this.players.find(t=>t.peerId===e);t&&(this.recorder?.player(this.engine.tick,t.slot,null),this.command(`team`,t.slot,0),this.players=this.players.filter(t=>t.peerId!==e),this.inputs.delete(e),this.sync(),this.invoke(`onPlayerLeave`,this.onPlayerLeave,this.playerCopy(t)))}playerCopy(e){let t=this.engine.index(e.slot)*18,n=!this.closed&&this.engine.phase!==`lobby`&&this.engine.data[t+13]>0,{slot:r,avatarOverride:i,...a}=e;return{...a,muted:!!e.muted,avatar:e.avatarOverride??e.avatar??null,position:n?{x:this.engine.data[t],y:this.engine.data[t+1]}:null}}getPlayerList(){return this.players.map(e=>this.playerCopy(e))}getPlayer(e){let t=this.players.find(t=>t.id===e);return t?this.playerCopy(t):null}setTeamColors(e,t,n,r){let i=xt(t,n,r);i.angle=((256*t/360|0)&255)*(360/256),this.changeTeamColors(e,i)}changeTeamColors(e,t){if(this.closed)throw Error(`Room is closed`);if(e!==1&&e!==2)throw Error(`Invalid team`);JSON.stringify(this.teamStyles[e-1])!==JSON.stringify(t)&&(this.teamStyles[e-1]=t,this.recorder?.style(this.engine.tick,this.teamStyles),this.sync())}reorderPlayers(e,t){if(this.closed)throw Error(`Room is closed`);if(!Array.isArray(e)||e.length>32||e.some(e=>!Number.isSafeInteger(e)||e<0)||typeof t!=`boolean`)throw Error(`Invalid player order`);let n=new Set(e),r=[...n].flatMap(e=>{let t=this.players.find(t=>t.id===e);return t?[t]:[]}),i=this.players.filter(e=>!n.has(e.id)),a=t?[...r,...i]:[...i,...r];a.every((e,t)=>e===this.players[t])||(this.players=a,this.recorder?.order(this.engine.tick,a.map(e=>e.slot)),this.sync())}setPlayerAvatar(e,t){if(this.closed)throw Error(`Room is closed`);if(!Tt(t))throw Error(`Avatar must be null or at most two visible characters.`);let n=this.players.find(t=>t.id===e);n&&(n.avatarOverride=t,this.recorder?.player(this.engine.tick,n.slot,n.name,t??n.avatar),this.sync())}setPlayerTeam(e,t){this.changeTeam(e,t,null)}changeTeam(e,t,n){if(this.closed)throw Error(`Room is closed`);if(![0,1,2].includes(t))throw Error(`Invalid team`);let r=this.players.find(t=>t.id===e);r&&r.team!==t&&(r.team=t,this.command(`team`,r.slot,t),this.sync(),this.invoke(`onPlayerTeamChange`,this.onPlayerTeamChange,this.playerCopy(r),n?this.playerCopy(n):null))}setPlayerAdmin(e,t){if(this.closed)throw Error(`Room is closed`);let n=this.players.find(t=>t.id===e);n&&n.admin!==!!t&&(n.admin=!!t,this.sync(),this.invoke(`onPlayerAdminChange`,this.onPlayerAdminChange,this.playerCopy(n),null))}setPlayerMuted(e,t){this.changePlayerMuted(e,t,null)}changePlayerMuted(e,t,n){if(this.closed)throw Error(`Room is closed`);if(!Number.isInteger(e)||typeof t!=`boolean`)throw Error(`Invalid player mute`);let r=this.players.find(t=>t.id===e);r&&r.peerId!==this.network.hostId&&!!r.muted!==t&&(r.muted=t,this.sync(),this.invoke(`onPlayerMuteChange`,this.onPlayerMuteChange,this.playerCopy(r),n))}setTeamsLock(e){this.changeTeamsLock(e,null)}changeTeamsLock(e,t){if(this.closed)throw Error(`Room is closed`);this.locked!==!!e&&(this.locked=!!e,this.sync(),this.invoke(`onTeamsLockChange`,this.onTeamsLockChange,this.locked,t))}kickPlayer(e,t=`Removed by host`,n=!1){if(this.closed)throw Error(`Room is closed`);if(typeof n!=`boolean`)throw Error(`Invalid ban flag`);if(n)return this.banPlayer(e,t);this.removePlayer(e,t,null)}async banPlayer(e,t,n=null){if(typeof t!=`string`)throw Error(`Invalid kick reason`);let r=this.players.find(t=>t.id===e);if(!r||r.peerId===this.network.hostId)return;let i=this.playerCopy(r),a=t.slice(0,100);if(this.bans.size>=256&&!this.bans.has(e))throw Error(`Clear existing bans before adding more.`);try{await this.network.updateBan(`ban`,r.peerId,a)}catch(t){throw t instanceof Sr&&this.bans.set(e,r.peerId),t}this.bans.set(e,r.peerId),this.network.remove(r.peerId),this.invoke(`onPlayerKicked`,this.onPlayerKicked,i,a,!0,n)}async clearBan(e){if(this.closed)throw Error(`Room is closed`);let t=this.bans.get(e);t&&(await this.network.updateBan(`clearBan`,t),this.bans.delete(e))}async clearBans(){if(this.closed)throw Error(`Room is closed`);await this.network.updateBan(`clearBans`),this.bans.clear()}removePlayer(e,t,n){if(this.closed)throw Error(`Room is closed`);if(typeof t!=`string`)throw Error(`Invalid kick reason`);let r=this.players.find(t=>t.id===e);if(r&&r.peerId!==this.network.hostId){let e=this.playerCopy(r),i=t.slice(0,100),a=this.network.peers.get(r.peerId);a&&this.network.control(a,{type:`kicked`,reason:i}),this.network.remove(r.peerId),this.players.includes(r)||this.invoke(`onPlayerKicked`,this.onPlayerKicked,e,i,!1,n)}}sendChat(e,t){if(this.closed)throw Error(`Room is closed`);if(typeof e!=`string`||e.length>200)throw Error(`Chat must contain at most 200 characters`);if(t!=null&&(!Number.isSafeInteger(t)||t<0))throw Error(`Invalid chat target`);let n=this.players.find(e=>e.peerId===this.network.hostId);if(!n)throw Error(`sendChat requires a host player; use sendAnnouncement`);if(!e.trim())return;let r={type:`chat`,name:n.name,text:e};if(t==null)this.network.broadcast(r);else{let e=this.players.find(e=>e.id===t),n=e&&this.network.peers.get(e.peerId);n&&this.network.control(n,r)}}sendAnnouncement(e,t,n,r,i){if(this.closed)throw Error(`Room is closed`);let a=wt(e,n,r,i);if(t!=null&&(!Number.isSafeInteger(t)||t<0))throw Error(`Invalid announcement target`);if(t==null)this.network.broadcast(a);else{let e=this.players.find(e=>e.id===t),n=e&&this.network.peers.get(e.peerId);n&&this.network.control(n,a)}}startGame(){this.beginGame(null)}beginGame(e){if(this.closed)throw Error(`Room is closed`);let t=this.engine.phase;(t===`lobby`||t===`finished`)&&(this.command(`start`),this.stadiumSelection++,this.state(),t!==this.engine.phase&&this.engine.phase===`playing`&&this.invoke(`onGameStart`,this.onGameStart,e?this.playerCopy(e):null))}stopGame(){this.endGame(null)}endGame(e){if(this.closed)throw Error(`Room is closed`);let t=this.engine.phase!==`lobby`;(t||this.engine.paused)&&(this.command(`stop`),this.state(),t&&this.invoke(`onGameStop`,this.onGameStop,e?this.playerCopy(e):null))}pauseGame(e){this.changePause(e,null)}changePause(e,t){if(this.closed)throw Error(`Room is closed`);this.engine.phase!==`lobby`&&(e=!!e,this.engine.paused!==e&&(this.command(`pause`,0,+e),this.state(),e?this.invoke(`onGamePause`,this.onGamePause,t):this.invoke(`onGameUnpause`,this.onGameUnpause,t),this.invoke(`onGamePauseChange`,this.onGamePauseChange,e)))}setSurfaceEnabled(e){if(this.closed)throw Error(`Room is closed`);if(typeof e!=`boolean`)throw Error(`Surface enabled must be a boolean`);if(![`lobby`,`finished`].includes(this.engine.phase))throw Error(`Stop the match before changing its surface`);!!this.engine.snapshotSurface().length!==e&&(this.command(`surface`,0,+e),this.state(),this.sync())}setKickRateLimit(e=2,t=0,n=0){this.changeKickRateLimit(e,t,n,null)}changeKickRateLimit(e,t,n,r){if(this.closed)throw Error(`Room is closed`);let i=On(e,t,n);i!==this.engine.kickRate&&(this.command(`kickRate`,0,i),this.state(),this.invoke(`onKickRateLimitSet`,this.onKickRateLimitSet,i&255,i>>>8&255,i>>>16,r))}async setPassword(e){if(this.closed)throw Error(`Room is closed`);await this.network.setPassword(e)}get requireVerification(){return this.network.requireVerification}async setRequireVerification(e){if(this.closed)throw Error(`Room is closed`);await this.network.setRequireVerification(e)}async setRequireRecaptcha(e){await this.setRequireVerification(e)}setScoreLimit(e){if(this.closed)throw Error(`Room is closed`);if([`lobby`,`finished`].includes(this.engine.phase)){if(!Number.isInteger(e)||e<0||e>99)throw Error(`Invalid limit`);e!==this.engine.scoreLimit&&(this.command(`scoreLimit`,0,e),this.sync())}}setTimeLimit(e){if(this.closed)throw Error(`Room is closed`);if([`lobby`,`finished`].includes(this.engine.phase)){if(!Number.isInteger(e)||e<0||e>99)throw Error(`Invalid time limit`);e*60!==this.engine.timeLimit&&(this.command(`timeLimit`,0,e*60),this.sync())}}async setDefaultStadium(e){if(this.closed)throw Error(`Room is closed`);if(![`lobby`,`finished`].includes(this.engine.phase))return;let t=++this.stadiumSelection,n=await this.runtime.loadStadium(e);if(this.closed)throw Error(`Room is closed`);if(t!==this.stadiumSelection)throw Error(`Stadium selection superseded`);this.setCustomStadium(n)}setCustomStadium(e){this.changeStadium(e,null)}changeStadium(e,t){if(this.closed)throw Error(`Room is closed`);if(![`lobby`,`finished`].includes(this.engine.phase))return;Cn(e);let n=++this.stadiumSelection;if(this.recorder&&this.finishRecording(`Stadium changed`),this.closed)throw Error(`Room is closed`);if([`lobby`,`finished`].includes(this.engine.phase)){if(n!==this.stadiumSelection)throw Error(`Stadium selection superseded`);this.engine.load(e);for(let e of this.players)this.engine.setTeam(e.slot,e.team);this.epoch=this.epoch+1&65535,this.inputs.clear(),this.network.broadcast({type:`stadium`,epoch:this.epoch,source:e,state:this.engine.snapshot()}),this.invoke(`onStadiumChange`,this.onStadiumChange,this.engine.stadium.name,t)}}getScores(){let e=this.engine;return this.closed||e.phase===`lobby`?null:{red:e.red,blue:e.blue,time:e.elapsed/60,scoreLimit:e.scoreLimit,timeLimit:e.timeLimit}}getBallPosition(){return this.closed||this.engine.phase===`lobby`?null:{x:this.engine.data[0],y:this.engine.data[1]}}readDisc(e){let t=this.engine.data,n=e*18;return{x:t[n],y:t[n+1],xspeed:t[n+2],yspeed:t[n+3],radius:t[n+4],invMass:t[n+5],damping:t[n+6],bCoeff:t[n+7],xgravity:t[n+8],ygravity:t[n+9],cGroup:t[n+10],cMask:t[n+11],color:this.engine.colors[e]}}get CollisionFlags(){return Nr}getDiscCount(){return this.closed||this.engine.phase===`lobby`?0:this.engine.stadium.discs.length+this.players.filter(e=>e.team!==0).length}getDiscProperties(e){if(!Number.isInteger(e)||e<0||e>=this.getDiscCount())return null;let t=this.engine.stadium.discs.length;if(e<t)return this.readDisc(e);let n=this.players.filter(e=>e.team!==0)[e-t];return this.readDisc(this.engine.index(n.slot))}setDiscProperties(e,t){if(this.closed)throw Error(`Room is closed`);if(!Number.isInteger(e)||e<0||e>=this.getDiscCount())return;let n=this.engine.stadium.discs.length,r=e<n?e:this.engine.index(this.players.filter(e=>e.team!==0)[e-n].slot);this.changeDisc(r,t)}setPlayerDiscProperties(e,t){if(this.closed)throw Error(`Room is closed`);if(this.engine.phase===`lobby`)return;let n=this.players.find(t=>t.id===e&&t.team!==0);n&&this.changeDisc(this.engine.index(n.slot),t)}changeDisc(e,t){let n=Dt(t),r=this.readDisc(e);if(Object.entries(n).every(([e,t])=>r[e]===t))return;let i={tick:this.engine.tick,kind:`disc`,slot:e,value:0,properties:n};if(this.recorder&&(!this.recorder.canRecord(this.engine)||!this.recorder.command(i))&&this.finishRecording(`Recording limit reached`),this.closed)throw Error(`Room is closed`);Xn(this.engine,i),this.state()}getPlayerDiscProperties(e){if(this.closed||this.engine.phase===`lobby`)return null;let t=this.players.find(t=>t.id===e&&t.team!==0);return t?this.readDisc(this.engine.index(t.slot)):null}getState(){return this.engine.snapshot()}startRecording(){if(this.closed)throw Error(`Room is closed`);if(this.finishingRecording)throw Error(`Recording completion is in progress`);if(this.recorder)throw Error(`Recording is already active`);this.recorder=new Zn(this.engine,this.players.map(e=>({slot:e.slot,name:e.name,avatar:e.avatarOverride??e.avatar})),this.teamStyles)}finishRecording(e){this.finishingRecording=!0;try{let t=this.stopRecording();t&&(this.lastRecording=t,this.invoke(`onRecordingComplete`,this.onRecordingComplete,t,e))}finally{this.finishingRecording=!1}}stopRecording(){let e=this.recorder?.finish(this.engine)??null;return this.recorder=void 0,e}close(){if(!this.closed){this.closed=!0,this.closeController.abort();try{this.recorder&&this.finishRecording(`Room closed`)}finally{clearInterval(this.loop),clearTimeout(this.linkNotification),this.linkNotification=void 0,this.network?.close(),this.players=[],this.traffic.clear()}}}};function Fr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Room configuration must be an object`);let t={...e},n=t.maxPlayers??12;if(typeof n!=`number`||!Number.isFinite(n)||!Number.isInteger(n))throw Error(`maxPlayers must be a finite integer`);return vt({...t,roomName:t.roomName??`Headless Room`,playerName:t.playerName??`Host`,noPlayer:t.noPlayer??!1,public:t.public??!1,maxPlayers:Math.max(2,Math.min(30,n)),password:t.password??``})}var Ir=class{onError;pending=[];active;scheduled=!1;closed=!1;constructor(e=()=>{}){this.onError=e}enqueue(e){let t=new Promise((t,n)=>{if(this.closed){n(Error(`Room is closed`));return}if(this.pending.length>=256){n(Error(`Room command queue is full`));return}this.pending.push({run:e,resolve:e=>t(e),reject:n}),this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.drain()}))});return t.catch(e=>{if(!this.closed)try{this.onError(e)}catch{}}),t}async drain(){for(;!this.closed&&this.pending.length;){let e=this.pending.shift();if(!e)break;this.active=e;try{e.resolve(await e.run())}catch(t){e.reject(t)}this.active=void 0}this.scheduled=!1}close(){if(this.closed)return;this.closed=!0;let e=Error(`Room is closed`);this.active?.reject(e);for(let t of this.pending.splice(0))t.reject(e)}},Lr=`sendChat.sendAnnouncement.setPlayerAdmin.setPlayerMuted.setPlayerTeam.kickPlayer.clearBan.clearBans.setScoreLimit.setTimeLimit.setCustomStadium.setDefaultStadium.setTeamsLock.setTeamColors.startGame.stopGame.pauseGame.setPassword.setRequireVerification.setRequireRecaptcha.reorderPlayers.setKickRateLimit.setSurfaceEnabled.setPlayerAvatar.setDiscProperties.setPlayerDiscProperties`.split(`.`);function Rr(e,t){let n=Object.create(null);t&&Object.defineProperty(n,"closed",{enumerable:!0,value:t});let r=new Ir(t=>{let n=e.onError?.(String(t));n instanceof Promise&&n.catch(()=>{})});e.signal.addEventListener(`abort`,()=>r.close(),{once:!0}),e.signal.aborted&&r.close();for(let t of Lr)Object.defineProperty(n,t,{enumerable:!0,value:(...n)=>{try{let i=structuredClone(n);return(t===`setScoreLimit`||t===`setTimeLimit`)&&typeof i[0]==`number`&&Number.isInteger(i[0])&&(i[0]=Math.max(0,Math.min(99,i[0]))),r.enqueue(()=>Reflect.apply(e[t],e,i))}catch(e){return r.enqueue(()=>{throw e})}}});for(let t of[`getPlayer`,`getPlayerList`,`getScores`,`getBallPosition`,`getDiscCount`,`getDiscProperties`,`getPlayerDiscProperties`,`getState`,`startRecording`,`stopRecording`])Object.defineProperty(n,t,{enumerable:!0,value:e[t].bind(e)});for(let t of[`roomId`,`roomLink`,`roomName`,`lastRecording`,`requireVerification`,`CollisionFlags`,`signal`])Object.defineProperty(n,t,{enumerable:!0,get:()=>e[t]});for(let t of[`onRoomLink`,`onPlayerJoin`,`onPlayerLeave`,`onPlayerChat`,`onPlayerTeamChange`,`onPlayerAdminChange`,`onPlayerMuteChange`,`onPlayerKicked`,`onPlayerActivity`,`onPlayerBallKick`,`onTeamGoal`,`onTeamVictory`,`onGameVictory`,`onGameStart`,`onGameStop`,`onGameTick`,`onGamePause`,`onGameUnpause`,`onGamePauseChange`,`onPositionsReset`,`onStadiumChange`,`onTeamsLockChange`,`onKickRateLimitSet`,`onRecordingComplete`,`onError`]){let r;Object.defineProperty(n,t,{enumerable:!0,get:()=>r,set:i=>{if(i!=null&&typeof i!=`function`)throw Error(`Callback must be a function`);r=i,Reflect.set(e,t,i==null?void 0:(...e)=>Reflect.apply(i,n,e))}})}return Object.defineProperty(n,"close",{enumerable:!0,value:()=>{r.close(),e.close()}}),Object.preventExtensions(n)}var zr=R(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Br=R(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=zr(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(` `,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){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 n.enable(n.load()),n}t.exports=n})),Vr=R(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})(),e.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`.split(`.`);function n(){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 e;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&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=Br()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Hr=z({createSupportsColor:()=>qr,default:()=>Xr});function Ur(e,t=globalThis.Deno?globalThis.Deno.args:p.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}function Wr(){if(!(`FORCE_COLOR`in Jr))return;if(Jr.FORCE_COLOR===`true`)return 1;if(Jr.FORCE_COLOR===`false`)return 0;if(Jr.FORCE_COLOR.length===0)return 1;let e=Math.min(Number.parseInt(Jr.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}function Gr(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Kr(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Wr();r!==void 0&&(Yr=r);let i=n?Yr:r;if(i===0)return 0;if(n){if(Ur(`color=16m`)||Ur(`color=full`)||Ur(`color=truecolor`))return 3;if(Ur(`color=256`))return 2}if(`TF_BUILD`in Jr&&`AGENT_NAME`in Jr)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(Jr.TERM===`dumb`)return a;if(p.platform===`win32`){let e=h.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in Jr)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in Jr)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in Jr)||Jr.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in Jr)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Jr.TEAMCITY_VERSION);if(Jr.COLORTERM===`truecolor`||Jr.TERM===`xterm-kitty`||Jr.TERM===`xterm-ghostty`||Jr.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in Jr){let e=Number.parseInt((Jr.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(Jr.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(Jr.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Jr.TERM)||`COLORTERM`in Jr?1:a}function qr(e,t={}){return Gr(Kr(e,{streamIsTTY:e&&e.isTTY,...t}))}var Jr,Yr,Xr,Zr=L((()=>{({env:Jr}=p),Ur(`no-color`)||Ur(`no-colors`)||Ur(`color=false`)||Ur(`color=never`)?Yr=0:(Ur(`color`)||Ur(`colors`)||Ur(`color=true`)||Ur(`color=always`))&&(Yr=1),Xr={stdout:qr({isTTY:g.isatty(1)}),stderr:qr({isTTY:g.isatty(2)})}})),Qr=R(((e,t)=>{var n=te(`tty`),r=te(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=(Zr(),ee(Hr));t&&(t.stderr||t).level>=2&&(e.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{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
14
|
+
`+t+`]`}return r.pop(),i=t,a}}};function Wn(e,t,n,r){let i=Math.ceil(2*Math.SQRT2*100/Math.max(.5,Math.min(10,r))),a=e+32;if(a*(2*t+a+2*n)*i*13>26e6)throw Error(`Stadium collision complexity exceeds the room budget`)}var Gn={ball:1,red:2,blue:4,redKO:8,blueKO:16,wall:32,kick:64,score:128,c0:268435456,c1:536870912,c2:1073741824,c3:-2147483648,all:63},Kn=4096;function qn(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Expected an object`);return e}function Jn(e,t,n=-4096,r=Kn){let i=e===void 0?t:e;if(typeof i!=`number`||!Number.isFinite(i)||i<n||i>r)throw Error(`Number must be between ${n} and ${r}`);return i}function Yn(e,t=[0,0]){if(e===void 0)return[...t];if(!Array.isArray(e)||e.length!==2)throw Error(`Expected [x, y]`);return[Jn(e[0],0),Jn(e[1],0)]}function Xn(e,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>t)throw Error(`Array limit: ${t}`);return e}function Zn(e,t){return e===void 0?t:typeof e==`number`?Jn(e,t,-2147483648,4294967295)|0:Xn(e,16).reduce((e,t)=>{if(typeof t!=`string`||!Object.hasOwn(Gn,t))throw Error(`Unknown collision flag`);return e|Gn[t]},0)}function Qn(e,t=`FFFFFF`){if(e===void 0)return t;if(e===`transparent`)return e;if(Array.isArray(e)&&e.length===3)return e.map(e=>Math.round(Jn(e,0,0,255)).toString(16).padStart(2,`0`)).join(``);if(typeof e==`string`&&/^[0-9a-f]{6}$/i.test(e))return e;throw Error(`Invalid color`)}var $n=4096,er=1024,tr=.15,nr=1e-4,rr=e=>[Jn(e.x,0),Jn(e.y,0)];function ir(e){return{a:rr(e),b:rr(e),bCoef:Jn(e.bCoef,1,-1,8192),cGroup:Zn(e.cGroup,32),cMask:Zn(e.cMask,63),bias:0,color:`transparent`,vis:!1}}function ar(e){return e.curveF===void 0?Jn(e.curve,0,-359,359):2*Math.atan2(1,Jn(e.curveF,0,-1e8,1e8))*180/Math.PI}function or(e,t,n,r,i,a){let o=r*Math.PI/180,s=t[0]-e[0],c=t[1]-e[1];if(Math.hypot(s,c)<.001)throw Error(`Arc endpoints overlap`);let l=1/(2*Math.tan(o/2)),u=[(e[0]+t[0])/2-c*l,(e[1]+t[1])/2+s*l],d=Math.hypot(e[0]-u[0],e[1]-u[1]),f=Math.atan2(e[1]-u[1],e[0]-u[0]),p=Math.ceil(Math.abs(o)/Math.max(1e-8,2*Math.acos(Math.max(-1,1-tr/d))));if(a.segments.length+p>$n)throw Error(`Compiled geometry exceeds 4096 segments`);let m={a:e,b:t,...n,center:u,radius:d,start:f,sweep:o,major:i.curveF===void 0?Math.abs(r)>180:Number(i.curveF)<=0};a.arcs.push(m),a.colliders.push(m);let h=e;for(let e=1;e<=p;e++){let r=e===p?t:[u[0]+d*Math.cos(f+o*e/p),u[1]+d*Math.sin(f+o*e/p)];a.segments.push({a:h,b:r,...n,renderOnly:!0}),h=r}}function sr(e,t,n){let r=e.map(ir),i={segments:r,arcs:[],colliders:[...r]};for(let a of Xn(t,er)){let t=n(a),o=Jn(t.v0,-1,0,e.length-1),s=Jn(t.v1,-1,0,e.length-1);if(!Number.isInteger(o)||!Number.isInteger(s))throw Error(`Vertex indices must be integers`);let c=rr(e[o]),l=rr(e[s]),u={bCoef:Jn(t.bCoef,1,-1,8192),cGroup:Zn(t.cGroup,32),cMask:Zn(t.cMask,63),bias:Jn(t.bias,0,-100,100),color:Qn(t.color,`000000`),vis:t.vis!==!1},d=ar(t);if(Math.abs(d)>=nr){or(c,l,u,d,t,i);continue}let f={a:c,b:l,...u};r.push(f),(c[0]!==l[0]||c[1]!==l[1])&&i.colliders.push(f)}if(r.length>$n)throw Error(`Compiled geometry exceeds 4096 segments`);return i}var cr=Object.fromEntries(Object.entries({root:`version physicsMode name width height maxViewWidth cameraFollow spawnDistance canBeStored kickOffReset bg traits vertexes segments goals discs planes joints redSpawnPoints blueSpawnPoints playerPhysics ballPhysics`,bg:`type width height kickOffRadius cornerRadius color`,vertexes:`trait x y bCoef cMask cGroup`,segments:`trait v0 v1 bCoef cMask cGroup curve curveF bias color vis`,discs:`trait pos speed gravity radius invMass damping bCoef cGroup cMask color`,planes:`trait normal dist bCoef cMask cGroup`,goals:`trait p0 p1 team`,joints:`trait d0 d1 length strength color`,playerPhysics:`trait pos speed gravity radius invMass damping bCoef cGroup cMask color acceleration kickingAcceleration kickingDamping kickStrength kickback`}).map(([e,t])=>[e,new Set(t.split(` `))])),lr=new Set([`vertexes`,`segments`,`discs`,`planes`,`goals`,`joints`,`playerPhysics`].flatMap(e=>[...cr[e]]));function ur(e){let t=[],n=(e,t)=>{let n=t.length>80?`${t.slice(0,80)}…`:t;return e+(/^[A-Za-z_$][\w$]*$/.test(n)?`.${n}`:`[${JSON.stringify(n)}]`)},r=(e,r,i)=>{if(e&&typeof e==`object`&&!Array.isArray(e))for(let a of Object.keys(e))r.has(a)||(t.length<64?t.push(`Unsupported stadium field: ${n(i,a)}`):t.length===64&&t.push(`Additional unsupported stadium fields omitted.`))};r(e,cr.root,`$`),r(e.bg,cr.bg,`$.bg`);for(let t of[`vertexes`,`segments`,`discs`,`planes`,`goals`,`joints`]){let n=e[t];Array.isArray(n)&&n.forEach((e,n)=>{r(e,cr[t],`$.${t}[${n}]`)})}if(r(e.ballPhysics,cr.discs,`$.ballPhysics`),r(e.playerPhysics,cr.playerPhysics,`$.playerPhysics`),e.traits&&typeof e.traits==`object`&&!Array.isArray(e.traits))for(let[t,i]of Object.entries(e.traits))r(i,lr,n(`$.traits`,t));return t}var dr=262144,fr=63,pr=1024,mr=64,hr=16,gr=128,_r=192,vr=[`grass`,`asphalt`,`none`];function yr(e){let t=e.traits===void 0?{}:qn(e.traits);return e=>{let n=qn(e);if(n.trait===void 0)return n;if(typeof n.trait!=`string`||!Object.hasOwn(t,n.trait))throw Error(`Unknown trait`);return{...qn(t[n.trait]),...n}}}function br(e,t=!1){return{pos:Yn(e.pos),speed:Yn(e.speed),gravity:Yn(e.gravity),radius:Jn(e.radius,10,.5,100),invMass:Jn(e.invMass,1,0,8192),damping:Jn(e.damping,.99,0,8192),bCoef:Jn(e.bCoef,.5,-1,8192),cGroup:Zn(e.cGroup,t?193:63),cMask:Zn(e.cMask,63),color:Qn(e.color)}}function xr(e,t){let n=Xn(e.discs,fr).map(e=>br(t(e)));if(e.ballPhysics!==`disc0`){let r=br(e.ballPhysics===void 0?{}:t(e.ballPhysics),!0);r.cGroup|=_r,n.unshift(r)}else if(!n.length)throw Error(`disc0 needs a disc`);return n}function Sr(e,t){let n=e.playerPhysics===void 0?{}:t(e.playerPhysics);return{...br({...n,radius:n.radius??15,invMass:n.invMass??.5,damping:n.damping??.96,cGroup:n.cGroup??0}),acceleration:Jn(n.acceleration,.1,-8192,8192),kickingAcceleration:Jn(n.kickingAcceleration,.07,-8192,8192),kickingDamping:Jn(n.kickingDamping,.96,0,8192),kickStrength:Jn(n.kickStrength,5,-8192,8192),kickback:Jn(n.kickback,0,-8192,8192)}}function Cr(e){let t=e===void 0?{}:qn(e);if(t.type!==void 0&&!vr.includes(t.type))throw Error(`Unsupported stadium background type`);return t}function wr(e){return{type:e.type===`grass`||e.type===`asphalt`?e.type:`none`,cornerRadius:Jn(e.cornerRadius,0,0,500),width:Jn(e.width,0,0,2048),height:Jn(e.height,0,0,2048),color:Qn(e.color,`718C5A`),kickOffRadius:Jn(e.kickOffRadius,0,0,500)}}function Tr(e){let t=Yn(e.normal);if(Math.hypot(...t)<1e-6)throw Error(`Plane normal is zero`);return{normal:t,dist:Jn(e.dist,0),bCoef:Jn(e.bCoef,1,-1,8192),cGroup:Zn(e.cGroup,32),cMask:Zn(e.cMask,63)}}function Er(e){if(e.team!==`red`&&e.team!==`blue`)throw Error(`Invalid goal team`);let t=Yn(e.p0),n=Yn(e.p1);if(Math.hypot(n[0]-t[0],n[1]-t[1])<1)throw Error(`Goal has zero length`);return{p0:t,p1:n,team:e.team===`red`?1:2}}function Dr(e,t){let n=Jn(e.d0,-1,0,t.length-1),r=Jn(e.d1,-1,0,t.length-1);if(!Number.isInteger(n)||!Number.isInteger(r)||n===r)throw Error(`Invalid joint indices`);let i=Math.hypot(t[r].pos[0]-t[n].pos[0],t[r].pos[1]-t[n].pos[1]),a=e.length==null?[i,i]:typeof e.length==`number`?[e.length,e.length]:Yn(e.length);return{d0:n,d1:r,min:Jn(a[0],0,0),max:Jn(a[1],0,0),strength:e.strength===void 0||e.strength===`rigid`?`rigid`:Jn(e.strength,0,-8192,8192),color:Qn(e.color,`000000`)}}function Or(e){if(new TextEncoder().encode(e).length>dr)throw Error(`Stadium exceeds 256 KB`);let t=qn(Un.parse(e));if(t.physicsMode!==void 0&&t.physicsMode!==`stadium`&&t.physicsMode!==`substeps`)throw Error(`Invalid physics mode`);if(t.version!==void 0&&t.version!==1)throw Error(`Unsupported stadium version`);let n=yr(t),r=xr(t,n),i=Xn(t.vertexes,pr).map(n),a=ur(t),{segments:o,arcs:s,colliders:c}=sr(i,t.segments,n),l=Sr(t,n),u=Xn(t.planes,mr),d=Xn(t.joints,gr);Wn(r.length,o.length,u.length+d.length,Math.min(l.radius,...r.map(e=>e.radius)));let f=Cr(t.bg);return{version:1,physicsMode:t.physicsMode===`substeps`?`substeps`:`stadium`,name:typeof t.name==`string`?t.name.slice(0,64):`Untitled stadium`,canBeStored:t.canBeStored!==!1,width:Jn(t.width,520,100,2048),height:Jn(t.height,300,80,2048),maxViewWidth:Jn(t.maxViewWidth,0,0,4096),cameraFollow:t.cameraFollow===`player`?`player`:`ball`,bg:wr(f),discs:r,segments:o,arcs:s,colliders:c,player:l,spawnDistance:Jn(t.spawnDistance,200,0,1500),kickOffReset:t.kickOffReset===`full`?`full`:`partial`,redSpawnPoints:Xn(t.redSpawnPoints,32).map(e=>Yn(e)),blueSpawnPoints:Xn(t.blueSpawnPoints,32).map(e=>Yn(e)),warnings:a,planes:u.map(e=>Tr(n(e))),goals:Xn(t.goals,hr).map(e=>Er(n(e))),joints:d.map(e=>Dr(n(e),r))}}function kr(e,t,n){if(!Number.isFinite(e)||!Number.isInteger(t)||t<0||t>16777215||!Array.isArray(n)||n.length<1||n.length>3||n.some(e=>!Number.isInteger(e)||e<0||e>16777215))throw Error(`Invalid team colors`);return{angle:(e%360+360)%360,textColor:t,colors:[...n]}}function Ar(e){if(e===void 0)return[null,null];if(!Array.isArray(e)||e.length!==2)throw Error(`Invalid team styles`);return e.map(e=>e===null?null:kr(e.angle,e.textColor,e.colors))}var jr=[15035990,5671397],Mr=e=>e.color===`transparent`?-1:Number.parseInt(e.color,16);function Nr(e,t=0){return[...e.pos,...e.speed,e.radius,e.invMass,e.damping,e.bCoef,...e.gravity,e.cGroup,e.cMask,t,0,0,0,e.pos[0],t?0:e.pos[1]]}function Pr(e,t,n){for(let n of t.colliders)if(`center`in n){let t=n;e.arc(...t.center,t.radius,...t.a,...t.b,t.sweep,+t.major,t.bCoef,t.cGroup,t.cMask,t.bias)}else{let t=n;e.wall(...t.a,...t.b,t.bCoef,t.cGroup,t.cMask,t.bias)}for(let n of t.planes)e.plane(...n.normal,n.dist,n.bCoef,n.cGroup,n.cMask);for(let n of t.joints)e.joint(n.d0,n.d1,n.min,n.max,n.strength===`rigid`?1/0:n.strength);for(let n of t.goals)e.goal(...n.p0,...n.p1,n.team);let r=t.player;e.configure(r.acceleration,r.kickStrength,r.kickingAcceleration,r.kickingDamping,r.kickback,n&255)}function Fr(e,t){Wn(e.discs.length,e.segments.length,e.planes.length+e.joints.length,t)}function Ir(e,t,n,r,i){let a=n*18;if(!tn.some(([i,o])=>{let s=r[i];return s!==void 0&&!Object.is(o===-1?t[n]:e[a+o],s)}))return!1;if(r.radius!==void 0){let a=r.radius;for(let r=0;r<t.length;r++)r!==n&&(a=Math.min(a,e[r*18+V.RADIUS]));Fr(i,a)}for(let[i,o]of tn){let s=r[i];s!==void 0&&(o===-1?t[n]=s:e[a+o]=s)}return!0}var Lr=32,Rr=11,zr=6,Br=class{snapshots=[];players=[];complete=!0;kickPool=Array.from({length:Lr},(e,t)=>({order:t,contactIndex:null,disc:0,slot:0,team:0,ball:{x:0,y:0,radius:0,beforeVx:0,beforeVy:0,afterVx:0,afterVy:0}}));playerPool=Array.from({length:Lr},()=>({disc:0,slot:0,team:0,x:0,y:0,radius:0}));kicks;roster;clear(){this.snapshots.length=this.players.length=0,this.complete=!0}read(e){let t=e.ball_kick_snapshots_count();if(this.complete=e.ball_kick_snapshots_overflow()===0,!t)return;let n=e.memory.buffer,r=e.ball_kick_snapshots_ptr();(!this.kicks||this.kicks.buffer!==n||this.kicks.byteOffset!==r)&&(this.kicks=new Float64Array(n,r,352));for(let e=0;e<t;e++){let t=e*Rr,n=this.kickPool[e];n.contactIndex=this.kicks[t]<0?null:this.kicks[t],n.disc=this.kicks[t+1],n.slot=this.kicks[t+2],n.team=this.kicks[t+3],n.ball.x=this.kicks[t+4],n.ball.y=this.kicks[t+5],n.ball.radius=this.kicks[t+6],n.ball.beforeVx=this.kicks[t+7],n.ball.beforeVy=this.kicks[t+8],n.ball.afterVx=this.kicks[t+9],n.ball.afterVy=this.kicks[t+10],this.snapshots.push(n)}let i=e.ball_kick_players_count(),a=e.ball_kick_players_ptr();(!this.roster||this.roster.buffer!==n||this.roster.byteOffset!==a)&&(this.roster=new Float64Array(n,a,192));for(let e=0;e<i;e++){let t=e*zr,n=this.playerPool[e];n.disc=this.roster[t],n.slot=this.roster[t+1],n.team=this.roster[t+2],n.x=this.roster[t+3],n.y=this.roster[t+4],n.radius=this.roster[t+5],this.players.push(n)}}},Vr=55;function Hr(e,t,n,r){let i=t===1?e.redSpawnPoints:e.blueSpawnPoints,a=t===1?-1:1;if(i.length)return i[r?i.length-1:Math.min(n,i.length-1)];if(r)return[a*e.width,0];let o=n?Math.ceil(n/2)*Vr*(n%2?1:-1):0;return[a*e.spawnDistance,o]}var Ur=8192,Wr=2147483648,Gr=25500,Kr=[`lobby`,`playing`,`goal`,`finished`],qr=(e,t,n=0)=>Number.isInteger(e)&&e>=n&&e<=t;function Jr(e){let t=e%18;return t===V.COLLISION_GROUP||t===V.COLLISION_MASK?Wr:t===V.KICK_BUDGET?Gr:Ur}function Yr(e,t){if(!e||typeof e!=`object`||!Array.isArray(e.discs)||e.discs.length!==t||!e.discs.every((e,t)=>typeof e==`number`&&Number.isFinite(e)&&Math.abs(e)<=Jr(t)))throw Error(`Invalid state`);if(!Array.isArray(e.colors)||e.colors.length!==e.discs.length/18||e.colors.some(e=>!Number.isInteger(e)||e<-1||e>16777215))throw Error(`Invalid disc colors`)}function Xr(e){if(!qr(e.kickRate,6619135)||!qr(e.tick,4294967295)||!qr(e.elapsed,4294967295)||!qr(e.red,65535)||!qr(e.blue,65535)||!qr(e.countdown,330)||!qr(e.resumeTicks,119)||(e.paused||e.phase===`lobby`)&&e.resumeTicks!==0||!qr(e.scoreLimit,99)||!qr(e.timeLimit,5940)||!Kr.includes(e.phase)||typeof e.paused!=`boolean`||typeof e.kickoffActive!=`boolean`||![1,2].includes(e.kickoff))throw Error(`Invalid match metadata`);for(let t of[e.lastTouch,e.goalTouch])if(t!=null&&(typeof t!=`object`||!qr(t.slot,31)||![1,2].includes(t.team)))throw Error(`Invalid goal attribution`)}function Zr(e){for(let t=0;t<e.length;t+=18){let n=n=>e[t+n];if(n(V.RADIUS)<.5||n(V.RADIUS)>100||n(V.INVERSE_MASS)<0||n(V.INVERSE_MASS)>Ur||n(V.DAMPING)<0||n(V.DAMPING)>Ur||n(V.BOUNCE)<-1||n(V.BOUNCE)>Ur||!qr(n(V.COLLISION_GROUP),2147483647,-2147483648)||!qr(n(V.COLLISION_MASK),2147483647,-2147483648)||!qr(n(V.TEAM),2)||!qr(n(V.INPUT),31)||!qr(n(V.KICK_STATE),4095)||n(V.PLAYER_SLOT)>0&&(!Number.isInteger(n(V.KICK_BUDGET))||n(V.KICK_BUDGET)<-255||n(V.KICK_BUDGET)>Gr))throw Error(`Invalid disc properties`)}}function Qr(e,t,n){Yr(e,t),Xr(e),Zr(e.discs);let r=10;for(let t=V.RADIUS;t<e.discs.length;t+=18)r=Math.min(r,e.discs[t]);Fr(n,r)}async function $r(e){return Array.from(new Uint8Array(await crypto.subtle.digest(`SHA-256`,e))).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function ei(e,t){let n=e??await(await fetch(`/core.wasm?v=98c92c27828179bc4258`,{signal:t})).arrayBuffer();if(await $r(n)!==`23989127182d21b3dc42055febe7b8d25cc3e9bcf7b5b738de652a48f6735871`)throw Error(`Physics build changed. Refresh the page to load a matching version.`);return WebAssembly.instantiate(await WebAssembly.compile(n))}var ti=60,ni=[0,Gn.red,Gn.blue],ri={1:Gn.redKO,2:Gn.blueKO},ii=Gn.redKO|Gn.blueKO,ai=300,oi=e=>e?{...e}:null,si=[`kick`,`disc`,`wall`],ci=class e{core;stadium;source=``;colors=[];tick=0;elapsed=0;ballKicks=[];ballContacts=[];ballContactsComplete=!0;kickSnapshots=new Br;kickSnapshotsEnabled=!1;setKickSnapshotsEnabled(e){if(typeof e!=`boolean`)throw Error(`Invalid kick snapshot setting`);this.kickSnapshotsEnabled=e,this.core.configure_kick_snapshots(+e),this.kickSnapshots.clear()}get ballKickSnapshots(){return this.kickSnapshots.snapshots}get ballKickPlayers(){return this.kickSnapshots.players}get ballKickSnapshotsComplete(){return this.kickSnapshotsEnabled&&this.kickSnapshots.complete}contactPool=Array.from({length:32},()=>({kind:`disc`,disc:-1,speed:0}));contactView;ballContact;playerContact;red=0;blue=0;phase=`lobby`;paused=!1;resumeTicks=0;countdown=0;kickoff=1;kickoffActive=!0;scoreLimit=5;timeLimit=300;lastGoal=0;lastTouch=null;goalTouch=null;kickRate=2;constructor(e){this.core=e.exports}static async create(t,n){return new e(await ei(t,n))}view;get data(){let e=this.core.memory.buffer,t=this.core.data_ptr(),n=this.core.count()*18,r=this.view;return r&&r.buffer===e&&r.byteOffset===t&&r.length===n?r:(this.view=new Float64Array(e,t,n),this.view)}setKickRateLimit(e,t,n){this.kickRate=an(e,t,n),this.core.kick_limits(...on(this.kickRate))}load(e){this.stadium=Or(e),this.source=e,this.core.reset(),this.kickSnapshotsEnabled=!1,this.kickSnapshots.clear(),this.clearEvents(),this.colors=[],this.core.physics_mode(+(this.stadium.physicsMode===`substeps`)),this.tick=0,this.elapsed=0,this.red=this.blue=0,this.lastTouch=this.goalTouch=null,this.phase=`lobby`,this.paused=!1,this.resumeTicks=0,this.countdown=0,this.kickoffActive=!0;for(let e of this.stadium.discs)this.add(e);for(let e=0;e<32;e++)this.add(this.stadium.player,e+1);Pr(this.core,this.stadium,this.kickRate),this.setKickRateLimit(...on(this.kickRate))}add(e,t=0){let n=this.core.add_disc();if(n<0)throw Error(`Disc capacity exceeded`);this.colors.push(Mr(e)),Nr(e,t).forEach((e,t)=>{this.core.set_disc(n,t,e)})}index(e){if(!Number.isInteger(e)||e<0||e>=32)throw Error(`Invalid slot`);return this.stadium.discs.length+e}joinPlayer(e){this.lastTouch?.slot===e&&(this.lastTouch=null),this.goalTouch?.slot===e&&(this.goalTouch=null);let t=this.index(e)*18;this.data[t+V.KICK_STATE]=0,this.data[t+V.KICK_BUDGET]=0,this.setTeam(e,0)}setTeam(e,t){if(![0,1,2].includes(t))throw Error(`Invalid team`);let n=this.index(e),r=n*18,i=this.data;i[r+V.TEAM]=t,i[r+V.COLLISION_GROUP]=this.stadium.player.cGroup|ni[t],i[r+V.INPUT]=0,this.spawn(n,e,t,this.phase!==`lobby`)}input(e,t){let n=this.data,r=this.index(e)*18,i=t&31;i&16?n[r+V.INPUT]&16||(n[r+V.KICK_STATE]|=$t|en):n[r+V.KICK_STATE]&2048||(n[r+V.KICK_STATE]&=Qt),n[r+V.INPUT]=i}applyDiscProperties(e,t){let n=this.data;return this.phase===`lobby`||!Number.isInteger(e)||e<0||e>=this.colors.length||n[e*18+V.PLAYER_SLOT]>0&&n[e*18+V.TEAM]===0?!1:Ir(n,this.colors,e,nn(t),this.stadium)}restoreDiscProperties(e,t){let n=e*18,r=this.data;this.colors[e]=Mr(t),r[n+V.RADIUS]=t.radius,r[n+V.INVERSE_MASS]=t.invMass,r[n+V.DAMPING]=t.damping,r[n+V.BOUNCE]=t.bCoef,r[n+V.GRAVITY_X]=t.gravity[0],r[n+V.GRAVITY_Y]=t.gravity[1],r[n+V.COLLISION_GROUP]=t.cGroup,r[n+V.COLLISION_MASK]=t.cMask}teamRank(e,t){let n=0;for(let r=0;r<e;r++)this.data[this.index(r)*18+V.TEAM]===t&&n++;return n}spawn(e,t,n,r=!1){this.restoreDiscProperties(e,this.stadium.player),this.colors[e]=n===1||n===2?jr[n-1]:16777215;let i=this.data,a=e*18;i[a+V.COLLISION_GROUP]|=ni[n]??0;let[o,s]=Hr(this.stadium,n,this.teamRank(t,n),r);i[a+V.X]=o,i[a+V.Y]=s,i[a+V.SPEED_X]=i[a+V.SPEED_Y]=i[a+V.INPUT]=0,i[a+V.KICK_STATE]&=Qt,i[a+V.COLLISION_MASK]=this.stadium.player.cMask&~ii}resetPositions(e=!1){this.kickSnapshots.clear(),this.kickoffActive=!0,this.lastTouch=null;let t=this.data;for(let n=0;n<this.stadium.discs.length;n++){let r=this.stadium.discs[n];(e||n===0||this.stadium.kickOffReset===`full`)&&(this.restoreDiscProperties(n,r),t[n*18+V.X]=r.pos[0],t[n*18+V.Y]=r.pos[1],t[n*18+V.SPEED_X]=r.speed[0],t[n*18+V.SPEED_Y]=r.speed[1])}for(let e=0;e<32;e++){let n=this.index(e);this.spawn(n,e,t[n*18+V.TEAM])}}start(){(this.phase===`lobby`||this.phase===`finished`)&&(this.red=this.blue=this.elapsed=0,this.goalTouch=null,this.phase=`playing`,this.paused=!1,this.resumeTicks=0,this.kickoff=1,this.countdown=0,this.resetPositions(!0))}stop(){this.kickSnapshots.clear(),this.lastTouch=this.goalTouch=null,this.phase=`lobby`,this.paused=!1,this.resumeTicks=0}setPaused(e){this.phase!==`lobby`&&(e=!!e,this.paused!==e&&(this.paused=e,this.resumeTicks=e?0:119))}finish(){this.phase=`finished`,this.countdown=ai}timeExpiredWithLeader(){return this.timeLimit>0&&this.elapsed>=this.timeLimit*ti&&this.red!==this.blue}step(){this.advance(),this.settleKickPresses()}settleKickPresses(){let e=this.data,t=this.stadium.discs.length;for(let n=0;n<32;n++){let r=(t+n)*18,i=e[r+V.KICK_STATE];i&3072&&(e[r+V.KICK_STATE]=i&(e[r+V.INPUT]&16?Qt|$t:Qt))}}clearEvents(){this.kickSnapshotsEnabled&&this.kickSnapshots.clear(),this.ballKicks.length=0,this.ballContacts.length=0,this.ballContactsComplete=!0,this.ballContact=void 0,this.playerContact=void 0}advance(){if(this.clearEvents(),this.tick++,this.paused||this.phase===`lobby`)return;if(this.resumeTicks>0){this.resumeTicks--;return}if(this.core.step(),this.collectBallEvents(),this.phase===`finished`){--this.countdown<=0&&this.stop();return}if(this.phase===`goal`){--this.countdown<=0&&this.afterGoalPause();return}if(this.applyKickoffBarriers(),this.kickoffActive){let e=this.data;e[V.SPEED_X]**2+e[V.SPEED_Y]**2>0&&(this.kickoffActive=!1);return}this.elapsed++;let e=this.core.goal_event();if(e===1||e===2)return this.scoreGoal(e);this.timeExpiredWithLeader()&&this.finish()}collectBallEvents(){this.kickSnapshotsEnabled&&this.kickSnapshots.read(this.core);let e=this.core.ball_contacts_count();if(this.ballContactsComplete=this.core.ball_contacts_overflow()===0,e>0){let t=this.core.memory.buffer,n=this.core.ball_contacts_ptr();(!this.contactView||this.contactView.buffer!==t||this.contactView.byteOffset!==n)&&(this.contactView=new Float64Array(t,n,96));for(let t=0;t<e;t++){let e=this.contactPool[t];e.kind=si[this.contactView[t*3]],e.disc=this.contactView[t*3+1],e.speed=this.contactView[t*3+2],this.ballContacts.push(e)}}if(this.phase===`playing`){let e=this.core.ball_touch_slot();if(e>=0&&e<32){let t=this.data[this.index(e)*18+V.TEAM];(t===1||t===2)&&(this.lastTouch={slot:e,team:t})}}let t=this.core.ball_contact_speed();t>=1&&(this.ballContact={disc:this.core.ball_contact_disc(),speed:t});let n=this.core.player_contact_speed();if(n>0){let e=this.core.player_contact_pair()>>>0;this.playerContact={a:e&255,b:e>>>8&255,speed:n}}for(let e=this.core.ball_kick_events()>>>0,t=0;e;e>>>=1,t++)e&1&&this.ballKicks.push(t)}afterGoalPause(){this.scoreLimit>0&&Math.max(this.red,this.blue)>=this.scoreLimit||this.timeExpiredWithLeader()?this.finish():(this.phase=`playing`,this.resetPositions())}applyKickoffBarriers(){let e=this.data,t=this.stadium.player.cMask,n=this.kickoffActive?t&ri[this.kickoff]:0;for(let r=0;r<32;r++)e[this.index(r)*18+V.COLLISION_MASK]=t&~ii|n}scoreGoal(e){e===1?this.red++:this.blue++,this.kickoff=e===1?2:1,this.phase=`goal`,this.countdown=330,this.goalTouch=oi(this.lastTouch),this.lastGoal=this.tick}snapshot(){return{lastTouch:oi(this.lastTouch),goalTouch:oi(this.goalTouch),tick:this.tick,elapsed:this.elapsed,red:this.red,blue:this.blue,phase:this.phase,paused:this.paused,resumeTicks:this.resumeTicks,countdown:this.countdown,kickoff:this.kickoff,kickoffActive:this.kickoffActive,scoreLimit:this.scoreLimit,timeLimit:this.timeLimit,kickRate:this.kickRate,discs:Array.from(this.data),colors:[...this.colors]}}restore(e){Qr(e,this.data.length,this.stadium),this.setKickSnapshotsEnabled(!1),this.clearEvents(),this.setKickRateLimit(...on(e.kickRate)),this.lastTouch=oi(e.lastTouch),this.goalTouch=oi(e.goalTouch),this.tick=e.tick,this.elapsed=e.elapsed,this.red=e.red,this.blue=e.blue,this.phase=e.phase,this.paused=e.paused,this.resumeTicks=e.resumeTicks,this.countdown=e.countdown,this.kickoff=e.kickoff,this.kickoffActive=e.kickoffActive,this.scoreLimit=e.scoreLimit,this.timeLimit=e.timeLimit,this.data.set(e.discs),this.colors=[...e.colors]}},li=`ball2d-core/1/${Zt}`;function ui(e){let t=e.stadium.goals;if(t.length!==2||t[0].team===t[1].team)return[];let n=e.stadium.discs[0]?.pos;if(!n)return[];let r=t.map(({p0:e,p1:t})=>[(e[0]+t[0])/2,(e[1]+t[1])/2]),i=r[1][0]-r[0][0],a=r[1][1]-r[0][1],o=i*i+a*a,s=(n[0]-r[0][0])*i+(n[1]-r[0][1])*a;return o<=0||s<=0||s>=o?[]:t.map((e,t)=>({id:`goal-${t}`,p0:[...e.p0],p1:[...e.p1],defendingTeam:e.team,pitchPoint:[...n]}))}var di=class{analyzer=new rt(ti);stadium;geometry=null;defaults=[];sampled=-1/0;reset(){this.analyzer.reset(),this.sampled=-1/0}configure(e,t){if(t!==null){if(!Array.isArray(t)||t.length>32)throw Error(`Invalid commentary geometry`);let n=new Set;for(let r of t){if(!r||typeof r.id!=`string`||!/^[a-zA-Z0-9._:-]{1,64}$/.test(r.id)||n.has(r.id)||!Array.isArray(r.p0)||!Array.isArray(r.p1)||!Array.isArray(r.pitchPoint)||r.p0.length!==2||r.p1.length!==2||r.pitchPoint.length!==2||![...r.p0,...r.p1,...r.pitchPoint].every(e=>Number.isFinite(e)&&Math.abs(e)<=1e7)||!e.stadium.goals.some(e=>e.team===r.defendingTeam&&e.p0.every((e,t)=>e===r.p0[t])&&e.p1.every((e,t)=>e===r.p1[t])))throw Error(`Commentary geometry must reference this stadium actual goals`);let t=(r.pitchPoint[0]-r.p0[0])*(r.p1[1]-r.p0[1])-(r.pitchPoint[1]-r.p0[1])*(r.p1[0]-r.p0[0]);if(Math.abs(t)<.001)throw Error(`Pitch point cannot lie on the goal line`);n.add(r.id)}}let n=this.stadium!==e.stadium,r=n?ui(e):this.defaults,i=this.geometry??this.defaults,a=t??r;return n||i.length!==a.length||i.some((e,t)=>{let n=a[t];return e.id!==n.id||e.defendingTeam!==n.defendingTeam||![`p0`,`p1`,`pitchPoint`].every(t=>e[t].every((e,r)=>e===n[t][r]))})?(this.stadium=e.stadium,this.defaults=r,this.geometry=t===null?null:structuredClone(t),this.reset(),!0):!1}getGeometry(e){return structuredClone(this.getAnalysisGeometry(e))}getAnalysisGeometry(e){return this.stadium!==e.stadium&&this.configure(e,null),this.geometry??this.defaults}observe(e,t,n,r){if(this.stadium!==e.stadium&&this.configure(e,null),e.paused||e.resumeTicks>0)return this.reset(),[];if(!e.ballKicks.length&&!e.ballContact&&e.tick-this.sampled<6&&e.tick>=this.sampled)return[];this.sampled=e.tick;let i=e.data,a=this.geometry??this.defaults,o;if(e.ballKicks.length){let t=r(e.ballKicks[e.ballKicks.length-1]);t&&(o={kind:`kick`,player:t})}else if(e.ballContact){let t=e.ballContact.disc,n=t*18,s=t>0&&i[n+V.INVERSE_MASS]===0?a.find(e=>[e.p0,e.p1].some(e=>Math.hypot(i[n]-e[0],i[n+V.Y]-e[1])<=i[n+V.RADIUS])):void 0;if(s)o={kind:`post`,goalId:s.id};else{for(let n=0;n<32;n++){if(e.index(n)!==t)continue;let i=r(n);i&&(o={kind:`player`,player:i});break}o??={kind:`wall`}}}return this.analyzer.observe({streamId:n,epoch:t,tick:e.tick,context:{phase:e.phase,elapsed:e.elapsed/ti,timeLimit:e.timeLimit,scoreLimit:e.scoreLimit,score:{red:e.red,blue:e.blue}},ball:{x:i[0],y:i[1],vx:i[2]*ti,vy:i[3]*ti,radius:i[V.RADIUS]},goals:a,...o?{contact:o}:{}})}};function fi(e,t){t.length&&e.broadcast({type:`match-analysis`,version:1,sentAtMs:performance.now(),streamId:t[0].streamId,observations:t})}var pi=e=>typeof e==`string`&&e.length>0&&e.length<=128&&e.trim()===e&&!/\p{Cc}/u.test(e),mi=e=>Number.isFinite(e)&&Math.abs(e)<=1e9;function hi(e,t,n){return!e||e.sessionId!==t||e.team!==n||n!==1&&n!==2||!Number.isSafeInteger(e.playerId)||e.playerId<0||e.playerId>2147483647?null:Object.freeze({sessionId:t,playerId:e.playerId,team:n})}var gi=class{previous=null;continuous=!1;edited=!1;revision=0;invalidate(){this.edited=!0,this.revision=Math.min(2**53-1,this.revision+1)}baseline(e,t){return this.cursor(e,t),e.setKickSnapshotsEnabled(!0),this.continuous=!0,this.read(e,t,!1)}capture(e,t){return this.advance(e,t),this.read(e,t,!0)}captureKicks(e,t){return this.previous?.streamId===t.streamId&&this.previous.epoch===t.epoch&&this.previous.tick===e.tick?null:(this.advance(e,t),e.ballKickSnapshots.length?this.read(e,t,!0):null)}advance(e,t){let n=this.previous;(!n||n.streamId!==t.streamId||n.epoch!==t.epoch||e.tick!==n.tick+1)&&(this.continuous=!1),this.cursor(e,t)}cursor(e,t){if(!pi(t.streamId)||!Number.isSafeInteger(t.epoch)||t.epoch<0||t.epoch>65535||!Number.isSafeInteger(e.tick)||e.tick<0||!Array.isArray(t.goals)||t.goals.length>32)throw Error(`Invalid explicit shot capture context`);this.previous?(this.previous.streamId=t.streamId,this.previous.epoch=t.epoch,this.previous.tick=e.tick):this.previous={streamId:t.streamId,epoch:t.epoch,tick:e.tick}}read(e,{streamId:t,epoch:n,resolve:r,goals:i},a){let o=e.data,s=this.continuous&&!this.edited;o.length!==(e.stadium.discs.length+32)*18&&(s=!1);let c=[],l=new Map,u=new Set;for(let n=0;n<32;n++){let i=e.index(n),a=i*18,d=o[a+V.TEAM];if(d===0)continue;let f=hi(r(n),t,d);if(!f||u.has(f.playerId)||o[a+V.PLAYER_SLOT]!==n+1){s=!1;continue}u.add(f.playerId),l.set(i,f),c.push(Object.freeze({identity:f,x:o[a],y:o[a+V.Y],vx:o[a+V.SPEED_X]*ti,vy:o[a+V.SPEED_Y]*ti,radius:o[a+V.RADIUS]}))}let d=!!(o[V.COLLISION_GROUP]&128);for(let e=18;e<o.length;e+=18)o[e+V.COLLISION_GROUP]&128&&(d=!1);let f=i.map(e=>Object.freeze({id:e.id,defendingTeam:e.defendingTeam,p0:Object.freeze([...e.p0]),p1:Object.freeze([...e.p1]),pitchPoint:Object.freeze([...e.pitchPoint])})),p=[],m=[];if(a){s&&=e.ballContactsComplete&&e.ballKickSnapshotsComplete;for(let[r,a]of e.ballContacts.entries()){let c=l.get(a.disc),u={id:`${t}:${n}:${e.tick}:contact:${r}`,tick:e.tick};if(a.kind===`kick`)c||(s=!1),p.push(Object.freeze({...u,kind:`kick`,...c?{player:c}:{}}));else if(c)p.push(Object.freeze({...u,kind:`player`,player:c}));else{a.disc>=e.stadium.discs.length&&(s=!1);let t=a.disc*18,n=a.kind===`disc`&&a.disc>0&&o[t+V.INVERSE_MASS]===0?i.find(e=>[e.p0,e.p1].some(e=>Math.hypot(o[t]-e[0],o[t+V.Y]-e[1])<=o[t+V.RADIUS])):void 0;p.push(Object.freeze(n?{...u,kind:`post`,goalId:n.id}:{...u,kind:`wall`}))}}let r=[],a=new Set;for(let t of e.ballKickPlayers){let n=l.get(t.disc);if(!n||n.team!==t.team||e.index(t.slot)!==t.disc||a.has(n.playerId)||![t.x,t.y,t.radius].every(mi)||t.radius<=0){s=!1;continue}a.add(n.playerId),r.push(Object.freeze({identity:n,x:t.x,y:t.y,radius:t.radius}))}e.ballKickSnapshots.length&&r.length!==c.length&&(s=!1),Object.freeze(r);for(let[i,o]of e.ballKickSnapshots.entries()){let c=l.get(o.disc),u=o.contactIndex===null?void 0:e.ballContacts[o.contactIndex];if(!c||c.team!==o.team||e.index(o.slot)!==o.disc||o.order!==i||!a.has(c.playerId)||!u||u.kind!==`kick`||u.disc!==o.disc||o.contactIndex===null||![o.ball.x,o.ball.y,o.ball.radius,o.ball.beforeVx*ti,o.ball.beforeVy*ti,o.ball.afterVx*ti,o.ball.afterVy*ti].every(mi)||o.ball.radius<=0){s=!1;continue}m.push(Object.freeze({id:`${t}:${n}:${e.tick}:kick:${i}`,tick:e.tick,order:i,contactIndex:o.contactIndex,player:c,ball:Object.freeze({x:o.ball.x,y:o.ball.y,radius:o.ball.radius,beforeVx:o.ball.beforeVx*ti,beforeVy:o.ball.beforeVy*ti,afterVx:o.ball.afterVx*ti,afterVy:o.ball.afterVy*ti}),players:r}))}m.length!==e.ballContacts.filter(e=>e.kind===`kick`).length&&(s=!1)}let h={streamId:t,epoch:n,tick:e.tick,context:Object.freeze({phase:e.phase,paused:e.paused||e.resumeTicks>0,elapsed:e.elapsed/ti,timeLimit:e.timeLimit,scoreLimit:e.scoreLimit,score:Object.freeze({red:e.red,blue:e.blue})}),ball:Object.freeze({x:o[0],y:o[1],vx:o[2]*ti,vy:o[3]*ti,radius:o[V.RADIUS]}),players:Object.freeze(c),goals:Object.freeze(f),contacts:Object.freeze(p),contactsComplete:s};return lt(h)||(s=!1),Object.freeze({frame:Object.freeze({...h,contactsComplete:s}),captures:Object.freeze(m),capturesComplete:s,physicsRevision:this.revision,primaryBallOnlyScoring:d})}},_i=mt,vi=e=>[e.pos,e.speed,e.gravity,e.radius,e.invMass,e.damping,e.bCoef,e.cGroup,e.cMask];function yi(e){let t=e.player;return{version:e.version,physicsMode:e.physicsMode,lateEntryBoundaryWidth:e.width,discs:e.discs.map(vi),player:[...vi(t),t.acceleration,t.kickingAcceleration,t.kickingDamping,t.kickStrength,t.kickback],colliders:e.colliders.map(e=>[e.a,e.b,e.bCoef,e.cGroup,e.cMask,e.bias,...`center`in e?[e.center,e.radius,e.sweep,e.major]:[]]),planes:e.planes.map(e=>[e.normal,e.dist,e.bCoef,e.cGroup,e.cMask]),joints:e.joints.map(e=>[e.d0,e.d1,e.min,e.max,e.strength]),goals:e.goals.map(e=>[e.p0,e.p1,e.team]),redSpawnPoints:e.redSpawnPoints,blueSpawnPoints:e.blueSpawnPoints,spawnDistance:e.spawnDistance,kickOffReset:e.kickOffReset}}function bi(e){return JSON.stringify(e,(e,t)=>{if(typeof t==`number`&&!Number.isFinite(t))throw Error(`Nonfinite xG domain configuration`);return t})}function xi(e,t){if(!Number.isInteger(e.kickRate)||e.kickRate<0||e.kickRate>6619135)throw Error(`Invalid xG domain kick rate`);let n=new di;n.configure(e,t);let r=n.getAnalysisGeometry(e);if(!r.length)throw Error(`xG collection requires supported oriented goal geometry`);return bi({revision:`stadium-physics-v1`,physics:yi(e.stadium),kickRate:e.kickRate,goals:r.map(e=>[e.id,e.p0,e.p1,e.defendingTeam,e.pitchPoint])})}async function Si(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(t),e=>e.toString(16).padStart(2,`0`)).join(``)}async function Ci(e,t,n=null){if(!t||![`pre-kick`,`post-kick`].includes(t.featureStage)||![`all-kicks-v1`,`goalward-release-v1`].includes(t.population)||!Number.isInteger(t.outcomeHorizonMs)||t.outcomeHorizonMs<100||t.outcomeHorizonMs>6e4)throw Error(`Invalid xG collection policy`);let r=xi(e,n),i={featureStage:t.featureStage,population:t.population,outcomeHorizonMs:t.outcomeHorizonMs},[a,o]=await Promise.all([Si(r),Si(bi({revision:_i,featuresRevision:Pt,hz:ti,maximumGapTicks:1,snapshot:`raw-before-after-impulse-before-integration-v1`,featureGoal:`nearest-opposing-center-playable-side-inclusive-v1`,populationRule:`all-supported-or-positive-post-impulse-dot-v1`,outcomeRule:`unique-primary-crossing-awarded-team-before-next-kick-v1`,horizonRounding:`ceil-to-ticks`,...i}))]);if(r!==xi(e,n))throw Error(`xG domain changed during preparation`);return Object.freeze({engineId:li,geometrySha256:a,policySha256:o,featuresRevision:Pt,shotDefinitionRevision:_i,...i})}function wi(e){let t=e.data;for(let n=0;n<e.colors.length;n++){let r=n>=e.stadium.discs.length,i=r?e.stadium.player:e.stadium.discs[n],a=n*18;if([i.radius,i.invMass,i.damping,i.bCoef,...i.gravity].some((e,n)=>e!==t[a+V.RADIUS+n]))throw Error(`Replay initial physics differs from its stadium; no mixed-domain collection`);let o=i.cGroup|(r?[0,Gn.red,Gn.blue][t[a+V.TEAM]]:0),s=r?~(Gn.redKO|Gn.blueKO):-1;if(t[a+V.COLLISION_GROUP]!==o||(t[a+V.COLLISION_MASK]&s)!==(i.cMask&s))throw Error(`Replay initial collision rules differ from its stadium`);if(n>0&&t[a+V.COLLISION_GROUP]&Gn.score)throw Error(`Offline collection currently requires the primary ball to be the sole scoring disc`)}if(!(t[V.COLLISION_GROUP]&Gn.score))throw Error(`Offline collection requires a scoring primary ball`)}function Ti(e,t){let n=e.stadium.goals,r=new Set(t.map(e=>n.findIndex(t=>t.team===e.defendingTeam&&t.p0.every((t,n)=>t===e.p0[n])&&t.p1.every((t,n)=>t===e.p1[n]))));if(t.length!==n.length||r.size!==n.length||r.has(-1))throw Error(`Offline collection geometry must cover every physical goal exactly once`)}var Ei=Object.freeze([]),Di=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.defendingTeam===r.defendingTeam&&e.p0.every((e,t)=>e===r.p0[t])&&e.p1.every((e,t)=>e===r.p1[t])&&e.pitchPoint.every((e,t)=>e===r.pitchPoint[t])}),Oi=class{trust;engine=null;stadium=null;generation=0;edited=!1;closed=!1;estimator=null;adapter=null;goals=[];kickRate=0;tick=-1;epoch=-1;streamId=``;wasPlaying=!1;status=Object.freeze({state:`disabled`,reason:`disabled`,domain:null,modelId:null,trustScope:`host-configuration`});constructor(e={}){if(!e||typeof e!=`object`||Array.isArray(e)||e.trustedModels!==void 0&&(!Array.isArray(e.trustedModels)||e.trustedModels.length>16))throw TypeError(`Invalid host-local xG trust list`);let t=(e.trustedModels??[]).flatMap(e=>{let t=Jt(e,e?.domain);return t.ok?[t.model]:[]});this.trust=Object.freeze({trustedModels:Object.freeze(t)})}get active(){return this.status.state===`ready`}getStatus(){return this.status}async configure(e,t,n=null){let r=++this.generation;if(this.disable(),this.closed)return this.setStatus(`disabled`,`closed`);if(t===null)return this.setStatus(`disabled`,`disabled`);if(this.edited)return this.setStatus(`invalidated`,`physics-edit`);this.engine=e,this.stadium=e.stadium,e.setKickSnapshotsEnabled(!1);let i=Xt(t?.model,t?.model?.domain,this.trust);if(i.status!==`reviewed-model`){let e=i.estimate({});return this.setStatus(`unavailable`,e.reason)}let a=Jt(t.model,t.model.domain);if(!a.ok)return this.setStatus(`unavailable`,a.reason);let o=a.model,s=Object.freeze({...t.policy}),c;try{let t=new di;t.configure(e,n),c=t.getGeometry(e),Ti(e,c)}catch{return this.setStatus(`unavailable`,`unsupported-geometry`)}try{wi(e)}catch{return this.invalidate(`physics-edit`),this.status}this.setStatus(`preparing`,`preparing`);try{let t=await Ci(e,s,c);if(r!==this.generation||this.closed)return this.status;if(e.stadium!==this.stadium)return this.setStatus(`unavailable`,`domain-change`);wi(e);let n=Xt(o,t,this.trust);if(n.status!==`reviewed-model`){let e=n.estimate({});return this.setStatus(`unavailable`,e.reason,t)}return this.estimator=n,this.goals=c,this.kickRate=e.kickRate,this.setStatus(`ready`,`ready`,t,n.modelId)}catch{return r!==this.generation||this.closed?this.status:this.setStatus(`unavailable`,`domain-change`)}}baseline(e,t){if(!(!this.estimator||this.edited||this.closed||this.status.state!==`ready`&&this.status.reason!==`capture-discontinuity`)&&this.matches(e,t))try{let n=new gi,r=n.baseline(e,t);if(!r.capturesComplete||!r.primaryBallOnlyScoring){e.setKickSnapshotsEnabled(!1),this.setStatus(`invalidated`,`capture-discontinuity`,this.status.domain,this.status.modelId);return}this.adapter=n,this.cursor(e,t),this.setStatus(`ready`,`ready`,this.status.domain,this.status.modelId)}catch{e.setKickSnapshotsEnabled(!1),this.setStatus(`invalidated`,`capture-discontinuity`,this.status.domain,this.status.modelId)}}capture(e,t){if(!this.active||!this.estimator||!this.adapter||!this.matches(e,t)||this.tick===e.tick&&this.epoch===t.epoch&&this.streamId===t.streamId)return Ei;if(this.tick+1!==e.tick||this.epoch!==t.epoch||this.streamId!==t.streamId)return e.setKickSnapshotsEnabled(!1),this.adapter=null,this.setStatus(`invalidated`,`capture-discontinuity`,this.status.domain,this.status.modelId),Ei;let n=this.wasPlaying;this.cursor(e,t);let r=this.adapter.captureKicks(e,t);if(!n||!r||!r.capturesComplete||!r.primaryBallOnlyScoring||!Mt(r.captures,r.frame))return Ei;let i=this.status.domain;if(!i)return Ei;let a=[];for(let e of r.captures){let n=Nt(e,r.frame,i);n&&a.push(Object.freeze({eventId:`${e.id}:estimate`,streamId:t.streamId,epoch:t.epoch,tick:e.tick,order:e.order,player:n.player,goalId:n.goalId,features:n.features,estimate:this.estimator.estimate(n.features),domain:i,trustScope:`host-configuration`}))}return a.length?Object.freeze(a):Ei}invalidate(e){++this.generation,e===`physics-edit`&&(this.edited=!0),this.disable(),this.setStatus(this.closed?`disabled`:`invalidated`,this.closed?`closed`:e)}reset(){++this.generation,this.disable(),this.setStatus(`disabled`,this.closed?`closed`:`disabled`)}resetForStadium(e){let t=e!==this.engine||e.stadium!==this.stadium;if(this.reset(),!this.closed){if(this.engine=e,this.stadium=e.stadium,t)try{wi(e),this.edited=!1}catch{this.edited=!0}this.edited&&this.setStatus(`invalidated`,`physics-edit`)}}close(){this.closed=!0,this.reset()}matches(e,t){return this.engine!==e||this.stadium!==e.stadium||this.kickRate!==e.kickRate||!Di(this.goals,t.goals)?(this.invalidate(`domain-change`),!1):!0}cursor(e,t){this.tick=e.tick,this.epoch=t.epoch,this.streamId=t.streamId,this.wasPlaying=e.phase===`playing`&&!e.paused&&e.resumeTicks===0}disable(){this.engine?.setKickSnapshotsEnabled(!1),this.estimator=null,this.adapter=null,this.tick=-1,this.wasPlaying=!1}setStatus(e,t,n=null,r=null){return this.status=Object.freeze({state:e,reason:t,domain:n,modelId:r,trustScope:`host-configuration`}),this.status}},ki=n(`/`),Ai;try{Ai=ki(`worker_threads`),Ai.Worker,Ai.isMarkedAsUntransferable}catch{}var ji=Uint8Array,Mi=Uint16Array,Ni=Int32Array,Pi=new ji([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Fi=new ji([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ii=new ji([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Li=function(e,t){for(var n=new Mi(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Ni(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Ai=Li(Pi,2),Ri=Ai.b,zi=Ai.r;Ri[28]=258,zi[258]=28;for(var Bi=Li(Fi,0),Vi=Bi.b,Hi=Bi.r,Ui=new Mi(32768),Wi=0;Wi<32768;++Wi){var Gi=(Wi&43690)>>1|(Wi&21845)<<1;Gi=(Gi&52428)>>2|(Gi&13107)<<2,Gi=(Gi&61680)>>4|(Gi&3855)<<4,Ui[Wi]=((Gi&65280)>>8|(Gi&255)<<8)>>1}for(var Ki=(function(e,t,n){for(var r=e.length,i=0,a=new Mi(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Mi(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Mi(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Ui[d]>>c]=l}else for(s=new Mi(r),i=0;i<r;++i)e[i]&&(s[i]=Ui[o[e[i]-1]++]>>15-e[i]);return s}),qi=new ji(288),Wi=0;Wi<144;++Wi)qi[Wi]=8;for(var Wi=144;Wi<256;++Wi)qi[Wi]=9;for(var Wi=256;Wi<280;++Wi)qi[Wi]=7;for(var Wi=280;Wi<288;++Wi)qi[Wi]=8;for(var Ji=new ji(32),Wi=0;Wi<32;++Wi)Ji[Wi]=5;var Yi=Ki(qi,9,0),Xi=Ki(qi,9,1),Zi=Ki(Ji,5,0),Qi=Ki(Ji,5,1),$i=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ea=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},ta=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},na=function(e){return(e+7)/8|0},ra=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new ji(e.subarray(t,n))},ia=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],aa=function(e,t,n){var r=Error(t||ia[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,aa),!n)throw r;return r},oa=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new ji(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new ji(i*3));var l=function(e){var t=n.length;if(e>t){var r=new ji(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=ea(e,d,1);var v=ea(e,d+1,3);if(d+=3,!v){var y=na(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&aa(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}if(v==1)p=Xi,m=Qi,h=9,g=5;else if(v==2){var S=ea(e,d,31)+257,C=ea(e,d+10,15)+4,w=S+ea(e,d+5,31)+1;d+=14;for(var T=new ji(w),E=new ji(19),D=0;D<C;++D)E[Ii[D]]=ea(e,d+D*3,7);d+=C*3;for(var O=$i(E),k=(1<<O)-1,A=Ki(E,O,1),D=0;D<w;){var j=A[ea(e,d,k)];d+=j&15;var y=j>>4;if(y<16)T[D++]=y;else{var M=0,N=0;for(y==16?(N=3+ea(e,d,3),d+=2,M=T[D-1]):y==17?(N=3+ea(e,d,7),d+=3):y==18&&(N=11+ea(e,d,127),d+=7);N--;)T[D++]=M}}var P=T.subarray(0,S),F=T.subarray(S);h=$i(P),g=$i(F),p=Ki(P,h,1),m=Ki(F,g,1)}else aa(1);if(d>_){c&&aa(0);break}}s&&l(f+131072);for(var I=(1<<h)-1,L=(1<<g)-1,R=d;;R=d){var M=p[ta(e,d)&I],ee=M>>4;if(d+=M&15,d>_){c&&aa(0);break}if(M||aa(2),ee<256)n[f++]=ee;else if(ee==256){R=d,p=null;break}else{var z=ee-254;if(ee>264){var D=ee-257,B=Pi[D];z=ea(e,d,(1<<B)-1)+Ri[D],d+=B}var te=m[ta(e,d)&L],ne=te>>4;te||aa(3),d+=te&15;var F=Vi[ne];if(ne>3){var B=Fi[ne];F+=ta(e,d)&(1<<B)-1,d+=B}if(d>_){c&&aa(0);break}s&&l(f+131072);var re=f+z;if(f<F){var ie=a-F,ae=Math.min(F,re);for(ie+f<0&&aa(3);f<ae;++f)n[f]=r[ie+f]}for(;f<re;++f)n[f]=n[f-F]}}t.l=p,t.p=R,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?ra(n,0,f):n.subarray(0,f)},sa=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},ca=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},la=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,a=n.slice();if(!i)return{t:ga,l:0};if(i==1){var o=new ji(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var s=n[0],c=n[1],l=0,u=1,d=2;for(n[0]={s:-1,f:s.f+c.f,l:s,r:c};u!=i-1;)s=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:s.f+c.f,l:s,r:c};for(var f=a[0].s,r=1;r<i;++r)a[r].s>f&&(f=a[r].s);var p=new Mi(f+1),m=ua(n[u-1],p,0);if(m>t){var r=0,h=0,g=m-t,_=1<<g;for(a.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});r<i;++r){var v=a[r].s;if(p[v]>t)h+=_-(1<<m-p[v]),p[v]=t;else break}for(h>>=g;h>0;){var y=a[r].s;p[y]<t?h-=1<<t-p[y]++-1:++r}for(;r>=0&&h;--r){var b=a[r].s;p[b]==t&&(--p[b],++h)}m=t}return{t:new ji(p),l:m}},ua=function(e,t,n){return e.s==-1?Math.max(ua(e.l,t,n+1),ua(e.r,t,n+1)):t[e.s]=n},da=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Mi(++t),r=0,i=e[0],a=1,o=function(e){n[r++]=e},s=1;s<=t;++s)if(e[s]==i&&s!=t)++a;else{if(!i&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(i),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(i);a=1,i=e[s]}return{c:n.subarray(0,r),n:t}},fa=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},pa=function(e,t,n){var r=n.length,i=na(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},ma=function(e,t,n,r,i,a,o,s,c,l,u){sa(t,u++,n),++i[256];for(var d=la(i,15),f=d.t,p=d.l,m=la(a,15),h=m.t,g=m.l,_=da(f),v=_.c,y=_.n,b=da(h),x=b.c,S=b.n,C=new Mi(19),w=0;w<v.length;++w)++C[v[w]&31];for(var w=0;w<x.length;++w)++C[x[w]&31];for(var T=la(C,7),E=T.t,D=T.l,O=19;O>4&&!E[Ii[O-1]];--O);var k=l+5<<3,A=fa(i,qi)+fa(a,Ji)+o,j=fa(i,f)+fa(a,h)+o+14+3*O+fa(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&k<=A&&k<=j)return pa(t,u,e.subarray(c,c+l));var M,N,P,F;if(sa(t,u,1+(j<A)),u+=2,j<A){M=Ki(f,p,0),N=f,P=Ki(h,g,0),F=h;var I=Ki(E,D,0);sa(t,u,y-257),sa(t,u+5,S-1),sa(t,u+10,O-4),u+=14;for(var w=0;w<O;++w)sa(t,u+3*w,E[Ii[w]]);u+=3*O;for(var L=[v,x],R=0;R<2;++R)for(var ee=L[R],w=0;w<ee.length;++w){var z=ee[w]&31;sa(t,u,I[z]),u+=E[z],z>15&&(sa(t,u,ee[w]>>5&127),u+=ee[w]>>12)}}else M=Yi,N=qi,P=Zi,F=Ji;for(var w=0;w<s;++w){var B=r[w];if(B>255){var z=B>>18&31;ca(t,u,M[z+257]),u+=N[z+257],z>7&&(sa(t,u,B>>23&31),u+=Pi[z]);var te=B&31;ca(t,u,P[te]),u+=F[te],te>3&&(ca(t,u,B>>5&8191),u+=Fi[te])}else ca(t,u,M[B]),u+=N[B]}return ca(t,u,M[256]),u+N[256]},ha=new Ni([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ga=new ji(0),_a=function(e,t,n,r,i,a){var o=a.z||e.length,s=new ji(r+o+5*(1+Math.ceil(o/7e3))+i),c=s.subarray(r,s.length-i),l=a.l,u=(a.r||0)&7;if(t){u&&(c[0]=a.r>>3);for(var d=ha[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new Mi(32768),g=a.h||new Mi(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new Ni(25e3),x=new Mi(288),S=new Mi(32),C=0,w=0,T=a.i||0,E=0,D=a.w||0,O=0;T+2<o;++T){var k=y(T),A=T&32767,j=g[k];if(h[A]=j,g[k]=A,D<=T){var M=o-T;if((C>7e3||E>24576)&&(M>423||!l)){u=ma(e,c,0,b,x,S,w,E,O,T-O,u),E=C=w=0,O=T;for(var N=0;N<286;++N)x[N]=0;for(var N=0;N<30;++N)S[N]=0}var P=2,F=0,I=p,L=A-j&32767;if(M>2&&k==y(T-L))for(var R=Math.min(f,M)-1,ee=Math.min(32767,T),z=Math.min(258,M);L<=ee&&--I&&A!=j;){if(e[T+P]==e[T+P-L]){for(var B=0;B<z&&e[T+B]==e[T+B-L];++B);if(B>P){if(P=B,F=L,B>R)break;for(var te=Math.min(L,B-2),ne=0,N=0;N<te;++N){var re=T-L+N&32767,ie=re-h[re]&32767;ie>ne&&(ne=ie,j=re)}}}A=j,j=h[A],L+=A-j&32767}if(F){b[E++]=268435456|zi[P]<<18|Hi[F];var ae=zi[P]&31,oe=Hi[F]&31;w+=Pi[ae]+Fi[oe],++x[257+ae],++S[oe],D=T+P,++C}else b[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,D);T<o;++T)b[E++]=e[T],++x[e[T]];u=ma(e,c,l,b,x,S,w,E,O,T-O,u),l||(a.r=u&7|c[u/8|0]<<3,u-=7,a.h=g,a.p=h,a.i=T,a.w=D)}else{for(var T=a.w||0;T<o+l;T+=65535){var se=T+65535;se>=o&&(c[u/8|0]=l,se=o),u=pa(c,u+1,e.subarray(T,se))}a.i=o}return ra(s,0,r+na(u)+i)},va=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new ji(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return _a(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,i)};function ya(e,t){return va(e,t||{},0,0)}var ba=function(){function e(e,t){typeof e==`function`&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new ji(32768),this.p=new ji(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||aa(5),this.d&&aa(4),!this.p.length)this.p=e;else if(e.length){var t=new ji(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=oa(this.p,this.s,this.o);this.ondata(ra(n,t,this.s.b),this.d),this.o=ra(n,this.s.b-32768),this.s.b=this.o.length,this.p=ra(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),xa=typeof TextDecoder<`u`&&new TextDecoder;try{xa.decode(ga,{stream:!0})}catch{}var Sa=33554432;function Ca(e){let t=2166136261;for(let n of e)t=Math.imul(t^n,16777619);return t>>>0}function wa(e){if(e.length>33554432)throw Error(`Replay exceeds 32 MB`);let t=ya(e,{level:6}),n=new Uint8Array(16+t.length),r=new DataView(n.buffer);return n.set([66,50,68,90,1,0,0,0]),r.setUint32(8,e.length,!0),r.setUint32(12,Ca(e),!0),n.set(t,16),n}function Ta(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length>33554432)throw Error(`Replay exceeds 32 MB`);if(t.length<17||t[0]!==66||t[1]!==50||t[2]!==68||t[3]!==90||t[4]!==1||t[5]||t[6]||t[7])throw Error(`Invalid compressed replay header`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(8,!0);if(!r||r>33554432)throw Error(`Invalid expanded replay size`);let i=new Uint8Array(r),a=0,o=!1,s=new ba((e,t)=>{if(a+e.length>r)throw Error(`Expanded replay exceeds declared size`);i.set(e,a),a+=e.length,o=t});for(let e=16;e<t.length;e+=1024)s.push(t.subarray(e,e+1024),e+1024>=t.length);if(!o||a!==r||Ca(i)!==n.getUint32(12,!0))throw Error(`Compressed replay integrity failure`);return i}function Ea(e){let t=new URL(e);if(![`http:`,`https:`].includes(t.protocol)||t.username||t.password||t.pathname!==`/`||t.search||t.hash)throw Error(`Expected an HTTP(S) service origin without credentials or a path`);return t.origin}function Da(e){let t=new URL(e.assets);if(![`http:`,`https:`,`ball2d:`].includes(t.protocol)||!t.host||t.username||t.password||t.pathname!==`/`||t.search||t.hash)throw Error(`Expected a root asset origin`);let n=Ea(e.service),r=Ea(e.public);function i(e,t){if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||[...e].some(e=>e.charCodeAt(0)<=32||e.charCodeAt(0)===127))throw Error(`Expected an absolute application path`);let n=decodeURIComponent(e.split(/[?#]/,1)[0]);if(n.includes(`\\`)||n.includes(`//`)||n.split(`/`).some(e=>e===`.`||e===`..`))throw Error(`Ambiguous application path`);let r=new URL(e,t),i=new URL(t);if(r.protocol!==i.protocol||r.host!==i.host||r.username||r.password)throw Error(`Application path escaped its runtime origin`);return r}return{serviceOrigin:n,publicOrigin:r,asset:e=>i(e,t.href),public:e=>i(e,r),api:e=>{let t=i(e,n);if(!t.pathname.startsWith(`${re}/`)||t.hash)throw Error(`Expected a versioned application API path`);return t}}}function Oa(){let e=location.origin;return Da({assets:e,service:e,public:e})}function ka(e,t){let n={get label(){return e.label},get readyState(){return e.readyState},get ordered(){return e.ordered},get maxRetransmits(){return e.maxRetransmits??null},get maxPacketLifeTime(){return e.maxPacketLifeTime??null},get bufferedAmount(){return e.bufferedAmount},onopen:null,onclose:null,onmessage:null,send(n){e.send(t.encode(n))},close(){e.close()}};return t.prepare?.(e),e.onopen=()=>n.onopen?.(),e.onclose=()=>n.onclose?.(),e.onmessage=({data:e})=>n.onmessage?.({data:t.decode(e)}),n}function Aa(e,t,n){let r={get connectionState(){return e.connectionState},get iceConnectionState(){return e.iceConnectionState},get signalingState(){return e.signalingState},get localDescription(){return e.localDescription??null},get remoteDescription(){return e.remoteDescription??null},onicecandidate:null,ondatachannel:null,onconnectionstatechange:null,oniceconnectionstatechange:null,createDataChannel:(n,r)=>ka(e.createDataChannel(n,r),t),createOffer:t=>e.createOffer(t),createAnswer:()=>e.createAnswer(),setLocalDescription:t=>e.setLocalDescription(t),setRemoteDescription:async t=>{await e.setRemoteDescription(t)},addIceCandidate:async t=>{await e.addIceCandidate(t)},getStats:()=>e.getStats(),close:n};return e.onicecandidate=({candidate:e})=>r.onicecandidate?.({candidate:e??null}),e.ondatachannel=({channel:e})=>r.ondatachannel?.({channel:ka(e,t)}),e.onconnectionstatechange=()=>r.onconnectionstatechange?.(),e.oniceconnectionstatechange=()=>r.oniceconnectionstatechange?.(),r}var ja=null,Ma=null;function Na(e){if(Object.keys(e).length!==2||e.bundlePolicy!==`max-bundle`)return!1;let t=e.iceServers;if(t?.length!==1)return!1;let n=t[0];return Object.keys(n).length===1&&n.urls===`stun:stun.l.google.com:19302`}function Pa(){Ma?.removeEventListener(`pagehide`,Fa),Ma=null}function Fa(){let e=ja;ja=null,Pa(),e?.close()}var Ia={prepare(e){e.binaryType=`arraybuffer`},encode:e=>e,decode:e=>e};function La(e){let t;return ja&&Na(e)?(t=ja,ja=null,Pa(),t.signalingState===`closed`&&(t=new RTCPeerConnection(e))):t=new RTCPeerConnection(e),Aa(t,Ia,()=>t.close())}function Ra(e=Oa()){return{serviceOrigin:e.serviceOrigin,createWebSocket:(e,t)=>new WebSocket(e,t),createPeerConnection:La}}var za=[[`classic`,`Classic`],[`easy`,`Easy`],[`small`,`Small`],[`big`,`Big`],[`rounded`,`Rounded`],[`big_easy`,`Big Easy`],[`big_rounded`,`Big Rounded`],[`huge`,`Huge`],[`asphalt`,`Asphalt`],[`meadow`,`Meadow`],[`training_green`,`Training Green`],[`courtyard`,`Courtyard`],[`street_five`,`Street Five`],[`asphalt_arena`,`Asphalt Arena`]];function Ba(e){let t=new Map;return async n=>{let r=za.find(([e,t])=>e===n||t===n);if(!r)throw Error(`Unknown default stadium`);let i=t.get(r[0]);return i||(i=(async()=>{let t=await e(`/stadiums/${r[0]}.ball2dstadium`);if(!t.ok)throw Error(`Could not load stadium`);let n=await t.text();return Or(n),n})(),t.set(r[0],i),i.catch(()=>t.delete(r[0]))),i}}async function Va(e){let t=new Uint8Array(await crypto.subtle.digest(`SHA-256`,e));return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function Ha(e=Oa()){let t=Ra(e),n=(e,t)=>fetch(e,t);return{network:t,publicOrigin:e.publicOrigin,request:n,loadEngine:async t=>{let r=async t=>{let r=await n(e.asset(`/core.wasm?v=${Zt}`),t);if(!r.ok)throw Error(`Could not load bundled physics engine`);return r.arrayBuffer()},i=await r({signal:t});return await Va(i)!==`23989127182d21b3dc42055febe7b8d25cc3e9bcf7b5b738de652a48f6735871`&&(i=await r({signal:t,cache:`reload`})),ci.create(i,t)},loadStadium:Ba(t=>n(e.asset(t)))}}function Ua(e,t){let n=e.engine.stadium.discs.length;return t<n?t:e.engine.index(e.players.fielded()[t-n].slot)}function Wa(e,t){let n=e.engine.data,r=t*18;return{x:n[r],y:n[r+V.Y],xspeed:n[r+V.SPEED_X],yspeed:n[r+V.SPEED_Y],radius:n[r+V.RADIUS],invMass:n[r+V.INVERSE_MASS],damping:n[r+V.DAMPING],bCoeff:n[r+V.BOUNCE],xgravity:n[r+V.GRAVITY_X],ygravity:n[r+V.GRAVITY_Y],cGroup:n[r+V.COLLISION_GROUP],cMask:n[r+V.COLLISION_MASK],color:e.engine.colors[t]}}function Ga(e,t,n){let r=nn(n),i=Wa(e,t);Object.entries(r).every(([e,t])=>i[e]===t)||(e.match.command(`disc`,t,0,r),t===0&&e.commentaryAnalysis.reset(),Object.keys(r).some(e=>e!==`color`)&&(e.intelligence.invalidate(),e.xg.invalidate(`physics-edit`)),e.broadcastState())}function Ka(e){return e.closed||e.engine.phase===`lobby`?0:e.engine.stadium.discs.length+e.players.fielded().length}var qa=(e,t)=>Number.isInteger(t)&&t>=0&&t<Ka(e);function Ja(e,t){return qa(e,t)?Wa(e,Ua(e,t)):null}function Ya(e,t,n){e.assertOpen(),qa(e,t)&&Ga(e,Ua(e,t),n)}var Xa=(e,t)=>{let n=e.players.byId(t);return n&&n.team!==0?n:void 0};function Za(e,t){if(e.closed||e.engine.phase===`lobby`)return null;let n=Xa(e,t);return n?Wa(e,e.engine.index(n.slot)):null}function Qa(e,t,n){if(e.assertOpen(),e.engine.phase===`lobby`)return;let r=Xa(e,t);r&&Ga(e,e.engine.index(r.slot),n)}function $a(e){return e.closed||e.engine.phase===`lobby`?null:{x:e.engine.data[0],y:e.engine.data[1]}}function eo(e,t){e.assertOpen();let n=e.engine.phase;if(n!==`lobby`&&n!==`finished`)return;let r=e.command(`start`),i=n!==e.engine.phase&&e.engine.phase===`playing`;e.stadiumSelection++,r.length||e.broadcastState(),e.notifyCommentary(r),i&&e.invoke(`onGameStart`,e.hooks.onGameStart,e.publicOrNull(t))}function to(e,t){e.assertOpen();let n=e.engine.phase!==`lobby`;if(!n&&!e.engine.paused)return;let r=e.command(`stop`);r.length||e.broadcastState(),e.notifyCommentary(r),n&&e.invoke(`onGameStop`,e.hooks.onGameStop,e.publicOrNull(t))}function no(e,t,n){if(e.assertOpen(),e.engine.phase===`lobby`||(t=!!t,e.engine.paused===t))return;let r=e.command(`pause`,0,+t);r.length||e.broadcastState(),e.notifyCommentary(r),t?e.invoke(`onGamePause`,e.hooks.onGamePause,n):e.invoke(`onGameUnpause`,e.hooks.onGameUnpause,n),e.invoke(`onGamePauseChange`,e.hooks.onGamePauseChange,t)}function ro(e,t,n,r,i){e.assertOpen();let a=an(t,n,r);a!==e.engine.kickRate&&(e.command(`kickRate`,0,a),e.broadcastState(),e.invoke(`onKickRateLimitSet`,e.hooks.onKickRateLimitSet,...on(a),i))}function io(e,t){if(e.assertOpen(),e.stopped()){if(!Number.isInteger(t)||t<0||t>99)throw Error(`Invalid limit`);t!==e.engine.scoreLimit&&(e.command(`scoreLimit`,0,t),e.syncLobby())}}function ao(e,t){if(e.assertOpen(),e.stopped()){if(!Number.isInteger(t)||t<0||t>99)throw Error(`Invalid time limit`);t*60!==e.engine.timeLimit&&(e.command(`timeLimit`,0,t*60),e.syncLobby())}}function oo(e){let t=e.engine;return e.closed||t.phase===`lobby`?null:{red:t.red,blue:t.blue,time:t.elapsed/ti,scoreLimit:t.scoreLimit,timeLimit:t.timeLimit}}var so=[`normal`,`bold`,`italic`,`small`,`small-bold`,`small-italic`];function co(e,t,n,r){if(typeof e!=`string`||e.length>1e3)throw Error(`Announcement exceeds 1000 characters`);if(t!=null&&(!Number.isInteger(t)||t<0||t>16777215))throw Error(`Invalid announcement color`);if(n!=null&&!so.includes(n))throw Error(`Invalid announcement style`);if(r!=null&&![0,1,2].includes(r))throw Error(`Invalid announcement sound`);return{type:`announcement`,text:e,color:t??null,style:n??`normal`,sound:r??1}}function lo(e){return e==null||Number.isSafeInteger(e)&&e>=0}function uo(e,t,n){if(n==null){e.network.broadcast(t);return}let r=e.players.byId(n),i=r&&e.network.peers.get(r.peerId);i&&e.network.control(i,t)}function fo(e,t,n){if(e.assertOpen(),typeof t!=`string`||t.length>200)throw Error(`Chat must contain at most 200 characters`);if(!lo(n))throw Error(`Invalid chat target`);let r=e.players.byPeer(e.network.hostId);if(!r)throw Error(`sendChat requires a host player; use sendAnnouncement`);t.trim()&&uo(e,{type:`chat`,name:r.name,text:t,...n==null?{playerId:r.peerId}:{}},n)}function po(e,t,n,r,i,a){e.assertOpen();let o=co(t,r,i,a);if(!lo(n))throw Error(`Invalid announcement target`);uo(e,o,n)}var mo=524288,ho=16384,go=12,_o=45635,vo=1,yo=32,bo=1e4,xo={MAGIC:0,VERSION:2,RESERVED:3,ID:4,INDEX:8,COUNT:10};function So(e,t){let n=JSON.stringify(e);if(n===void 0)throw Error(`Missing control message`);let r=new TextEncoder().encode(n);if(r.length>mo)throw Error(`Control message exceeds 512 KB`);if(r.length<=ho)return[n];let i=Math.ceil(r.length/ho),a=[];for(let e=0;e<i;e++){let n=r.subarray(e*ho,(e+1)*ho),o=new ArrayBuffer(go+n.length),s=new DataView(o);s.setUint16(xo.MAGIC,_o),s.setUint8(xo.VERSION,vo),s.setUint32(xo.ID,t,!0),s.setUint16(xo.INDEX,e,!0),s.setUint16(xo.COUNT,i,!0),new Uint8Array(o,go).set(n),a.push(o)}return a}var Co=class{partial;push(e,t=performance.now()){if(typeof e==`string`){if(this.partial||new TextEncoder().encode(e).length>ho)throw Error(`Invalid control message`);return JSON.parse(e)}if(e.byteLength<13||e.byteLength>16396)throw Error(`Control fragment length`);let n=new DataView(e);if(n.getUint16(xo.MAGIC)!==_o||n.getUint8(xo.VERSION)!==vo||n.getUint8(xo.RESERVED)!==0)throw Error(`Control fragment version`);let r=n.getUint32(xo.ID,!0),i=n.getUint16(xo.INDEX,!0),a=n.getUint16(xo.COUNT,!0);if(a<2||a>yo||i>=a)throw Error(`Control fragment bounds`);if(!this.partial){if(i!==0)throw Error(`Missing first fragment`);this.partial={id:r,count:a,next:0,bytes:0,parts:[],since:t}}let o=this.partial;if(o.id!==r||o.count!==a||o.next!==i||t-o.since>bo)throw Error(`Control fragment sequence`);if(o.next++,o.bytes+=e.byteLength-go,o.bytes>mo)throw Error(`Control size limit`);if(o.parts.push(new Uint8Array(e.slice(go))),o.next!==a)return;let s=new Uint8Array(o.bytes),c=0;for(let e of o.parts)s.set(e,c),c+=e.length;return this.partial=void 0,JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(s))}},wo={INPUT:1,STATE:2},To={KIND:0,PROTOCOL:1,SEQUENCE:2,EPOCH:6,KEYS:8},Eo={KIND:0,PROTOCOL:1,TICK:2,INDEX:6,COUNT:7,EPOCH:8,SIZE:10},Do=1188,Oo={TICK:0,ELAPSED:4,RED:8,BLUE:10,PHASE:12,PAUSED:13,KICKOFF:14,KICKOFF_ACTIVE:15,COUNTDOWN:16,SCORE_LIMIT:18,TIME_LIMIT:20,DISC_COUNT:22,ACKNOWLEDGED:24,BODY_COUNT:28,RESUME_TICKS:30,KICK_RATE:32,LAST_TOUCH:36,GOAL_TOUCH:38},ko=[`lobby`,`playing`,`goal`,`finished`],Ao={INDEX:0,TEAM:2,PACKED_INPUT:3,MOTION:4,KICK_STATE:36,KICK_BUDGET:38},jo=31;function Mo(e,t){if(e.byteLength!==12)throw Error(`Input length`);let n=new Uint8Array(e);if(n[To.KIND]!==wo.INPUT||n[To.PROTOCOL]!==3)throw Error(`Input format`);for(let e=0;e<4;e++){let r=n[To.KEYS+e];if(r>jo)throw Error(`Input format`);t.history[e]=r}return t.seq=(n[To.SEQUENCE]|n[To.SEQUENCE+1]<<8|n[To.SEQUENCE+2]<<16|n[To.SEQUENCE+3]<<24)>>>0,t.epoch=n[To.EPOCH]|n[To.EPOCH+1]<<8,t.keys=t.history[0],t}function No(e,t){return e!==t&&e-t>>>0<2147483648}function Po(e){let t=[];for(let n=0;n<e.length/18;n++){let r=n*18,i=e[r+V.INVERSE_MASS]>0||e[r+V.SPEED_X]!==0||e[r+V.SPEED_Y]!==0||e[r+V.GRAVITY_X]!==0||e[r+V.GRAVITY_Y]!==0||e[r+V.X]!==e[r+V.SPAWN_X]||e[r+V.Y]!==e[r+V.SPAWN_Y];(e[r+V.PLAYER_SLOT]>0?e[r+V.TEAM]>0:i)&&t.push(n)}return t}function Fo(e,t,n,r){e.setUint32(Oo.TICK,t.tick,!0),e.setUint32(Oo.ELAPSED,t.elapsed,!0),e.setUint16(Oo.RED,t.red,!0),e.setUint16(Oo.BLUE,t.blue,!0),e.setUint8(Oo.PHASE,ko.indexOf(t.phase)),e.setUint8(Oo.PAUSED,+t.paused),e.setUint8(Oo.KICKOFF,t.kickoff),e.setUint8(Oo.KICKOFF_ACTIVE,+t.kickoffActive),e.setUint16(Oo.COUNTDOWN,t.countdown,!0),e.setUint16(Oo.SCORE_LIMIT,t.scoreLimit,!0),e.setUint16(Oo.TIME_LIMIT,t.timeLimit,!0),e.setUint16(Oo.DISC_COUNT,t.discs.length/18,!0),e.setUint32(Oo.ACKNOWLEDGED,n,!0),e.setUint16(Oo.BODY_COUNT,r,!0),e.setUint16(Oo.RESUME_TICKS,t.resumeTicks,!0),e.setUint32(Oo.KICK_RATE,t.kickRate,!0),e.setUint8(Oo.LAST_TOUCH,t.lastTouch?.slot??255),e.setUint8(Oo.LAST_TOUCH+1,t.lastTouch?.team??0),e.setUint8(Oo.GOAL_TOUCH,t.goalTouch?.slot??255),e.setUint8(Oo.GOAL_TOUCH+1,t.goalTouch?.team??0)}function Io(e,t,n,r){let i=r*18,a=n[i+V.PLAYER_SLOT]>0;e.setUint16(t+Ao.INDEX,r,!0),e.setUint8(t+Ao.TEAM,n[i+V.TEAM]),e.setUint8(t+Ao.PACKED_INPUT,n[i+V.INPUT]|(a?(n[i+V.COLLISION_MASK]&24)<<2:0));for(let r=0;r<4;r++)e.setFloat64(t+Ao.MOTION+r*8,n[i+r],!0);e.setUint16(t+Ao.KICK_STATE,n[i+V.KICK_STATE],!0),a&&e.setUint16(t+Ao.KICK_BUDGET,n[i+V.KICK_BUDGET]+255,!0)}function Lo(e,t,n=0){let r=Po(e.discs),i=new ArrayBuffer(40+r.length*40),a=new DataView(i);Fo(a,e,t,r.length);for(let[t,n]of r.entries())Io(a,40+t*40,e.discs,n);let o=new Uint8Array(i),s=[],c=Math.ceil(o.length/Do);for(let t=0;t<c;t++){let r=o.subarray(t*Do,(t+1)*Do),i=new ArrayBuffer(12+r.length),a=new DataView(i);a.setUint8(Eo.KIND,wo.STATE),a.setUint8(Eo.PROTOCOL,3),a.setUint32(Eo.TICK,e.tick,!0),a.setUint8(Eo.INDEX,t),a.setUint8(Eo.COUNT,c),a.setUint16(Eo.EPOCH,n,!0),a.setUint16(Eo.SIZE,r.length,!0),new Uint8Array(i,12).set(r),s.push(i)}return s}function Ro(e,t,n=0){if(!t.length)return[];let r=Lo(e,t[0],n),i=[r];for(let e=1;e<t.length;e++){let n=r.map(e=>e.slice(0));new DataView(n[0]).setUint32(12+Oo.ACKNOWLEDGED,t[e],!0),i.push(n)}return i}function zo(e){let t=[...e],n=new Set(t.filter(e=>e.type===`transport`&&e.selectedCandidatePairId).map(e=>e.selectedCandidatePairId)),r=t.filter(e=>e.type===`candidate-pair`&&e.state===`succeeded`),i=n.size?r.filter(e=>n.has(e.id)):r.filter(e=>e.nominated===!0);if(i.length!==1)return null;let a=i[0].currentRoundTripTime;return typeof a==`number`&&Number.isFinite(a)&&a>=0?a*1e3:null}var Bo=e=>e?.match(/(?:^|\r?\n)a=ice-ufrag:([^\s]+)/)?.[1],Vo=e=>e.usernameFragment??e.candidate?.match(/(?:^| )ufrag ([^ ]+)/)?.[1];function Ho(e){let t=e.pc.localDescription;if(!t?.sdp)throw Error(`Local peer description is unavailable`);return t.sdp}function Uo(e,t,n){if(n()){if(e.candidates.length>=128)throw Error(`Too many pending ICE candidates`);e.candidates.push(t)}}async function Wo(e,t){let n=e.candidates.splice(0);for(let r of n){if(!t.current())return;if(!t.versioned||e.remoteIceUfrag&&Vo(r)===e.remoteIceUfrag)try{await e.pc.addIceCandidate(r)}catch{}}}async function Go(e,t,n){let r=await e.pc.createOffer(n);return!t.current()||(e.localIceUfrag=Bo(r.sdp),await e.pc.setLocalDescription(r),!t.current())?!1:(t.publish({type:`offer`,sdp:Ho(e)}),!0)}async function Ko(e,t,n){if(await e.pc.setRemoteDescription({type:`offer`,sdp:t}),!n.current()||(await Wo(e,n),!n.current()))return;let r=await e.pc.createAnswer();n.current()&&(e.localIceUfrag=Bo(r.sdp),await e.pc.setLocalDescription(r),n.current()&&n.publish({type:`answer`,sdp:Ho(e)}))}async function qo(e,t,n){return await e.pc.setRemoteDescription({type:`answer`,sdp:t}),n.current()?(await Wo(e,n),!0):!1}async function Jo(e,t,n){if(!(n.versioned&&(!Vo(t)||e.remoteIceUfrag&&Vo(t)!==e.remoteIceUfrag))){if(!e.pc.remoteDescription)Uo(e,t,n.current);else try{await e.pc.addIceCandidate(t)}catch{Uo(e,t,n.current)}}}var Yo=class{admission;assembler;constructor(e){this.admission=e}clear(){this.assembler=void 0}read(e){if(typeof e!=`string`&&!(e instanceof ArrayBuffer))throw Error(`Invalid control type`);let t=typeof e!=`string`||new TextEncoder().encode(e).length>4096,n=this.admission.fromGuest();if(n&&t&&!this.admission.canUploadStadium())throw Error(`Guest control size or permission`);this.assembler??=new Co;let r=this.assembler.push(e);if(r!==void 0&&n&&t&&(!r||typeof r!=`object`||!(`type`in r)||r.type!==`action`||!(`action`in r)||r.action!==`customStadium`))throw Error(`Invalid bulk action`);return r}},Xo=1e4,Zo=1200,Qo=e=>e.connectionState===`connected`&&[`connected`,`completed`].includes(e.iceConnectionState),$o=e=>[`failed`,`disconnected`].includes(e.connectionState)||[`failed`,`disconnected`].includes(e.iceConnectionState);function es(e,t,n){let r={id:t,pc:e,connected:!1,created:performance.now(),candidates:[],lastRestart:0,restarts:0,restarting:!1};e.onicecandidate=e=>{n.current(r)&&e.candidate&&n.signalingOpen()&&n.sendSignal(r,{type:`candidate`,candidate:e.candidate.toJSON()})},e.ondatachannel=e=>rs(r,e.channel,n);let i=()=>{n.current(r)&&(e.connectionState===`closed`?(n.hooks.status(`A peer disconnected.`,`info`),n.remove(t)):Qo(e)?n.noteHealthy(r):$o(e)&&(r.lostAt??=performance.now(),n.hooks.status(`Direct connection interrupted. Attempting recovery…`,`info`)))};return e.onconnectionstatechange=i,e.oniceconnectionstatechange=i,r}function ts(e,t){return t.maxPacketLifeTime===null?t.label===`control`?t.ordered===!0&&t.maxRetransmits===null&&!e.control:t.ordered===!1&&t.maxRetransmits===0&&!e.fast:!1}function ns(e){return typeof e==`string`?e.length:e instanceof ArrayBuffer?e.byteLength:0}function rs(e,t,n){if(!n.current(e)||![`control`,`realtime`].includes(t.label)){t.close();return}if(!ts(e,t)){t.close(),n.remove(e.id);return}t.label===`control`?(e.control=t,e.controlReader=new Yo({fromGuest:()=>n.isHost(),canUploadStadium:()=>n.hooks.allowStadiumUpload?.(e)??!1})):e.fast=t,t.onclose=()=>{n.current(e)&&(n.hooks.status(`A peer closed its game channel.`,`info`),n.remove(e.id))},t.onopen=()=>{n.current(e)&&(e.control?.readyState!==`open`||e.fast?.readyState!==`open`||e.connected||(e.connected=!0,n.isHost()&&(e.admissionTimer=setTimeout(()=>{n.current(e)&&(n.hooks.status(`A peer did not complete room admission.`,`error`),n.remove(e.id))},Xo)),n.hooks.open(e)))},t.onmessage=r=>{if(n.current(e)){n.countReceived(ns(r.data));try{if(t.label===`control`){let t=e.controlReader?.read(r.data);t!==void 0&&n.hooks.control(e,t)}else if(r.data instanceof ArrayBuffer&&r.data.byteLength<=Zo)n.hooks.fast(e,r.data);else throw Error(`Invalid realtime packet`)}catch{n.hooks.status(`Invalid peer message rejected.`,`error`),n.remove(e.id)}}}}var is=Ue(Ne({id:Ue(Le(),ve(1)),hostId:Ue(Le(),ve(1)),role:Fe([`host`,`guest`]),generation:Pe(Ge),requireVerification:Pe(Ve()),locked:Pe(Ve())}),fe(e=>e.role===`host`==(e.id===e.hostId))),as=Ne({roomId:Le(),siteKey:Ue(Le(),xe(/^[A-Za-z0-9_-]{1,100}$/))}),os=6e4,ss=class{roomId;hostToken;runtime;socket;retry;handshake;stopped=!1;admitted=!1;lastAcknowledgedAt;lastPulseAt;constructor(e,t,n){this.roomId=e,this.hostToken=t,this.runtime=n,this.connect()}acknowledged(){this.stopped||(this.lastAcknowledgedAt=performance.now(),this.admitted&&this.socket?.readyState===1&&this.pulse(this.socket))}pulse(e){let t=performance.now();this.lastPulseAt!==void 0&&t-this.lastPulseAt<os||(e.send(`hb`),this.lastPulseAt=t)}connect(){if(this.stopped)return;let e=new URL(ie.liveness(this.roomId),Ea(this.runtime.serviceOrigin));e.protocol=e.protocol===`https:`?`wss:`:`ws:`;let t;try{t=this.runtime.createWebSocket(e)}catch{this.retry=setTimeout(()=>this.connect(),5e3);return}this.socket=t,this.admitted=!1,this.lastPulseAt=void 0,this.handshake=setTimeout(()=>t.close(),1e4),t.onopen=()=>{!this.stopped&&t===this.socket&&t.send(JSON.stringify({type:`hello`,hostToken:this.hostToken}))},t.onmessage=({data:e})=>{this.stopped||t!==this.socket||(e===`ready`&&!this.admitted?(this.admitted=!0,clearTimeout(this.handshake),this.lastAcknowledgedAt!==void 0&&performance.now()-this.lastAcknowledgedAt<1e4&&this.pulse(t)):e!==`ok`&&t.close())},t.onclose=()=>{clearTimeout(this.handshake),t===this.socket&&(this.socket=void 0,this.admitted=!1,this.stopped||(this.retry=setTimeout(()=>this.connect(),5e3)))},t.onerror=()=>t.close()}close(){this.stopped||(this.stopped=!0,clearTimeout(this.retry),clearTimeout(this.handshake),this.socket?.close(1e3,`Host left`),this.socket=void 0)}},cs=class extends Error{},ls=class{messages;unconfirmed;sequence=0;pending;constructor(e,t=e=>Error(e)){this.messages=e,this.unconfirmed=t}matches(e){return!!this.pending&&this.pending.id===e}start(e){return this.pending?Promise.reject(Error(this.messages.pending)):new Promise((t,n)=>{let r=++this.sequence,i=setTimeout(()=>this.fail(this.messages.timeout),1e4);this.pending={id:r,resolve:t,reject:n,timer:i};try{e(r)}catch{this.fail(this.messages.send)}})}resolve(e){this.take()?.resolve(e)}fail(e,t=!1){let n=this.take();n&&n.reject(t?Error(e):this.unconfirmed(e))}take(){let e=this.pending;return this.pending=void 0,e&&clearTimeout(e.timer),e}},us=class{available;send;verification=null;verificationRequest=new ls({pending:`A verification update is already pending.`,timeout:`Verification update was not confirmed.`,send:`Verification update could not be sent.`},e=>(this.verification=null,Error(e)));passwordRequest=new ls({pending:`A password update is already pending.`,timeout:`Password update was not confirmed.`,send:`Password update could not be sent.`});banRequest=new ls({pending:`A ban operation is already pending.`,timeout:`Ban operation was not confirmed.`,send:`Ban operation could not be sent.`},e=>new cs(e));constructor(e,t){this.available=e,this.send=t}setRequireVerification(e){return typeof e==`boolean`?this.available()?this.verificationRequest.start(t=>this.send({type:`setVerification`,required:e,requestId:t})):Promise.reject(Error(`An active room-owner connection is required.`)):Promise.reject(Error(`Expected a boolean.`))}setPassword(e){return e!==null&&(typeof e!=`string`||e.length>64)?Promise.reject(Error(`Password must contain at most 64 characters.`)):this.available()?this.passwordRequest.start(t=>this.send({type:`setPassword`,requestId:t,password:e??``})):Promise.reject(Error(`An active room-owner connection is required.`))}updateBan(e,t,n){return this.available()?this.banRequest.start(r=>this.send({type:e,id:t,requestId:r,...e===`ban`&&n!==void 0?{reason:n}:{}})):Promise.reject(Error(`An active room-owner connection is required.`))}accept(e){if(e.type===`verificationUpdated`&&this.verificationRequest.matches(e.requestId))return e.ok!==!0||typeof e.required!=`boolean`?this.verificationRequest.fail(typeof e.error==`string`?e.error:`Verification update failed.`,e.ok===!1):(this.verification=e.required,this.verificationRequest.resolve(e.required)),!0;if(e.type===`passwordUpdated`&&this.passwordRequest.matches(e.requestId)){if(e.ok===!1)return this.passwordRequest.fail(typeof e.error==`string`?e.error:`Password update failed.`),!0;if(typeof e.locked==`boolean`)return this.passwordRequest.resolve(e.locked),!0}return e.type===`banResult`&&this.banRequest.matches(e.requestId)?(e.ok===!0?this.banRequest.resolve():this.banRequest.fail(typeof e.error==`string`?e.error:`Ban operation failed.`,!0),!0):!1}cancel(e){let t=e===`closed`?`Room closed`:`Signaling disconnected`;this.verificationRequest.fail(`${t} before verification confirmation.`),this.banRequest.fail(`${t} before ban confirmation.`),this.passwordRequest.fail(`${t} before password confirmation.`),e===`closed`&&(this.verification=null)}},ds=1,fs=2048,ps=[1001,1008,1009,1011,1013],ms=e=>typeof e==`string`&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(e),hs=e=>typeof e==`string`&&e.length<=123?e:`Room connection ended.`,gs={"Host left":`The host left. Return to Rooms and join again.`,"Host connection ended":`Host connection ended. Return to Rooms and join again.`};function _s(e){return Object.hasOwn(gs,e.reason)?gs[e.reason]:ps.includes(e.code)&&e.reason?e.reason:`Room connection ended. Return to Rooms and join again.`}function vs(e){if(e.matchEntry&&(e.hostToken||!/^[a-f0-9]{64}$/.test(e.matchEntry.token)||!ms(e.matchEntry.generation)))throw Error(`Invalid match entry credentials.`);return{hostToken:e.hostToken,password:e.password,...e.matchEntry?{matchEntry:{...e.matchEntry}}:{}}}var ys=class{room;hooks;events;runtime;ws;id=``;host=!1;hostId=``;closed=!1;generation=null;locked=null;serial=0;ownerRequests=new us(()=>this.host&&this.ready,e=>this.send(e));credentials;challenge;queue=Promise.resolve();hostMonitor;constructor(e,t,n,r,i){this.room=e,this.hooks=n,this.events=r,this.runtime=i,this.credentials=vs(t);let a=new URL(ie.signal(e),Ea(i.serviceOrigin));a.protocol=a.protocol===`https:`?`wss:`:`ws:`,this.ws=i.createWebSocket(a),this.attach(this.ws)}get socketOpen(){return this.ws.readyState===ds}get ready(){return!this.closed&&!!this.id&&this.socketOpen}isCurrent(e){return e===this.serial}send(e){!this.closed&&this.socketOpen&&this.ws.send(JSON.stringify(e))}sendPeerSignal(e,t){this.send({type:`signal`,to:e,signal:t})}attach(e){let t=++this.serial,n=()=>!this.closed&&this.ws===e&&this.serial===t;e.onopen=()=>{n()&&this.send({type:`hello`,...this.helloCredentials()})},e.onmessage=e=>{n()&&(this.queue=this.queue.then(async()=>{n()&&await this.receive(JSON.parse(e.data),t)}).catch(()=>{n()&&this.hooks.status(`Connection negotiation failed. Try another room or network.`,`error`)}))},e.onclose=e=>{n()&&(this.serial++,this.challenge?.abort(),this.ownerRequests.cancel(`disconnected`),this.events.ended(_s(e)))},e.onerror=()=>{n()&&this.hooks.status(`Room service is unavailable.`,`error`)}}async receive(e,t){if(!(this.closed||t!==this.serial)){if(e.type===`terminal`)return this.events.ended(hs(e.reason));if(!this.ownerRequests.accept(e))switch(e.type){case`heartbeat`:this.host&&this.hostMonitor?.acknowledged();return;case`verificationRequired`:return this.answerVerification(e);case`ready`:return this.admit(e);case`peer`:case`leave`:return this.events.peer(e,t);case`signal`:return this.events.negotiate(e,t)}}}async answerVerification(e){if(this.closed||this.id||this.credentials.hostToken||this.challenge||!Ee(as,e)||e.roomId!==this.room)return;if(!this.hooks.verify){this.events.ended(`This client cannot complete the room verification challenge.`);return}let t=new AbortController;this.challenge=t;try{let n=await this.hooks.verify({siteKey:e.siteKey,roomId:this.room},t.signal);if(t.signal.aborted||this.closed||!this.socketOpen)return;if(typeof n!=`string`||n.length===0||n.length>fs)throw Error(`Invalid verification response.`);this.send({type:`hello`,...this.helloCredentials(),verificationToken:n})}catch(e){this.closed||this.events.ended(e instanceof Error?e.message:`Room verification failed.`)}finally{this.challenge===t&&(this.challenge=void 0)}}admit(e){if(this.id)return;let t=this.credentials.matchEntry;if(!Ee(is,e)||t&&(e.role!==`guest`||!ms(e.id)||!ms(e.hostId)||e.generation!==t.generation)){this.events.ended(`Invalid room admission.`);return}this.id=e.id,this.host=e.role===`host`,this.host&&this.credentials.hostToken&&(this.hostMonitor=new ss(this.room,this.credentials.hostToken,this.runtime),this.hostMonitor.acknowledged()),this.hostId=e.hostId,this.generation=e.generation??null,delete this.credentials.matchEntry,this.ownerRequests.verification=typeof e.requireVerification==`boolean`?e.requireVerification:null,this.locked=typeof e.locked==`boolean`?e.locked:null,this.events.admitted(this.id,this.host)}helloCredentials(){return{hostToken:this.credentials.hostToken,password:this.credentials.password,...this.credentials.matchEntry?{matchEntryToken:this.credentials.matchEntry.token}:{}}}close(){this.closed||(this.serial++,this.challenge?.abort(),this.ownerRequests.cancel(`closed`),this.closed=!0,this.hostMonitor?.close(),this.hostMonitor=void 0,this.credentials={},this.ws.close(1e3,`Left room`))}},bs=2e4,xs=5e3,Ss=2,Cs=3e4,ws=5e3,Ts=1048576,Es=32768,Ds=1e3,Os=[{urls:`stun:stun.l.google.com:19302`}],ks=e=>typeof e==`string`?new TextEncoder().encode(e).length:e.byteLength,As=class{hooks;runtime;peers=new Map;timer;bytesSent=0;bytesReceived=0;signaling;link;pollingStats=!1;lastHeartbeat=0;controlId=0;hostCloseTimer;constructor(e,t,n,r=Ra()){this.hooks=n,this.runtime=r,this.link={isHost:()=>this.host,hooks:n,current:e=>this.current(e),signalingOpen:()=>this.signaling.socketOpen,sendSignal:(e,t)=>this.signaling.sendPeerSignal(e.id,t),noteHealthy:e=>this.noteHealthy(e),remove:e=>this.remove(e),countReceived:e=>{this.bytesReceived+=e}},this.signaling=new ys(e,t,n,{admitted:(e,t)=>n.ready(e,t),peer:(e,t)=>this.peerChanged(e,t),negotiate:(e,t)=>this.negotiate(e,t),ended:e=>this.end(e)},r),this.timer=setInterval(()=>this.maintain(),ws)}get ws(){return this.signaling.ws}get id(){return this.signaling.id}get host(){return this.signaling.host}get hostId(){return this.signaling.hostId}get closed(){return this.signaling.closed}get locked(){return this.signaling.locked}get signalingReady(){return this.signaling.ready}get roomGeneration(){return this.signaling.generation}get requireVerification(){return this.signaling.ownerRequests.verification}setRequireVerification(e){return this.signaling.ownerRequests.setRequireVerification(e)}setPassword(e){return this.signaling.ownerRequests.setPassword(e)}updateBan(e,t,n){return this.signaling.ownerRequests.updateBan(e,t,n)}get rtt(){let e=[...this.peers.values()].filter(e=>e.connected&&e.lostAt===void 0).map(e=>e.rtt).filter(e=>typeof e==`number`);return e.length?Math.max(...e):null}signal(e){this.signaling.send(e)}maintain(){let e=performance.now();this.host&&this.signalingReady&&e-this.lastHeartbeat>=Cs&&(this.signal({type:`heartbeat`}),this.lastHeartbeat=e);for(let t of this.peers.values())!t.connected&&e-t.created>bs?(this.hooks.status(`Could not connect directly to this room. Try another network or room.`,`error`),this.remove(t.id)):t.lostAt!==void 0&&e-t.lostAt>bs?(this.hooks.status(`The direct connection could not be recovered. Rejoin the room.`,`error`),this.remove(t.id)):t.lostAt!==void 0&&this.host&&e-t.lastRestart>xs&&this.restartPeer(t.id)}async peerChanged(e,t){typeof e.id==`string`&&e.id&&e.id!==this.id&&(e.type===`leave`?this.remove(e.id,!1):this.host&&!this.peers.has(e.id)&&await this.offerPeer(e.id,t))}async negotiate(e,t){if(typeof e.from!=`string`||!e.from)return;let{signal:n}=e,r=this.peers.get(e.from);if(!r){if(this.host||e.from!==this.hostId||![`offer`,`candidate`].includes(n.type))return;r=this.make(e.from)}let i=this.negotiationScope(r,t);if(n.type===`offer`){if(this.host)throw Error(`Only the host can offer`);await Ko(r,n.sdp,i)}else if(n.type===`answer`){if(!this.host)throw Error(`Only guests can answer`);await qo(r,n.sdp,i)&&this.noteHealthy(r)}else n.type===`candidate`&&n.candidate&&await Jo(r,n.candidate,i)}async offerPeer(e,t){let n=this.make(e);this.bind(n,n.pc.createDataChannel(`control`,{ordered:!0})),this.bind(n,n.pc.createDataChannel(`realtime`,{ordered:!1,maxRetransmits:0})),await Go(n,this.negotiationScope(n,t))}negotiationScope(e,t){return{current:()=>this.current(e)&&this.signaling.isCurrent(t)&&this.signaling.socketOpen,versioned:!1,publish:t=>this.signaling.sendPeerSignal(e.id,t)}}current(e){return!this.closed&&this.peers.get(e.id)===e}noteHealthy(e){if(!this.current(e)||e.pc.connectionState!==`connected`||![`connected`,`completed`].includes(e.pc.iceConnectionState))return;let t=e.lostAt!==void 0;e.lostAt=void 0,e.restarts=0,t&&this.hooks.status(`Direct connection restored.`,`info`)}async restartPeer(e){let t=this.peers.get(e);if(this.closed||!this.host||!t||t.restarting||t.restarts>=Ss||t.pc.signalingState!==`stable`||!this.signaling.socketOpen)return!1;let n=this.signaling.serial;t.restarting=!0,t.lastRestart=performance.now(),t.lostAt??=t.lastRestart,t.restarts++;try{return await Go(t,this.negotiationScope(t,n),{iceRestart:!0})}catch{return this.current(t)&&this.hooks.status(`Direct connection recovery is still pending.`,`info`),!1}finally{t.restarting=!1}}make(e){let t=es(this.runtime.createPeerConnection({iceServers:Os,bundlePolicy:`max-bundle`}),e,this.link);return this.peers.set(e,t),t}bind(e,t){rs(e,t,this.link)}admit(e){clearTimeout(e.admissionTimer),e.admissionTimer=void 0}control(e,t){let n=e.control;if(n?.readyState!==`open`)return;let r=So(t,this.controlId++),i=r.reduce((e,t)=>e+ks(t),0);if(n.bufferedAmount+i>Ts){this.remove(e.id);return}for(let e of r)n.send(e);this.bytesSent+=i}fast(e,t){e.fast?.readyState===`open`&&e.fast.bufferedAmount<Es&&(e.fast.send(t),this.bytesSent+=t.byteLength)}broadcast(e){for(let t of this.peers.values())this.control(t,e)}async stats(){if(!(this.pollingStats||this.closed)){this.pollingStats=!0;try{await Promise.allSettled([...this.peers.values()].map(async e=>{if(!e.connected||e.lostAt!==void 0){e.rtt=null;return}try{let t=await e.pc.getStats();this.current(e)&&(e.rtt=zo(t.values()))}catch{e.rtt=null}}))}finally{this.pollingStats=!1}}}end(e){this.closed||(this.close(),this.hooks.ended?.(e))}remove(e,t=!0){if(this.closed)return;let n=this.peers.get(e);if(!n)return;if(clearTimeout(n.admissionTimer),this.peers.delete(e),n.controlReader?.clear(),n.pc.close(),this.host&&t)try{this.signal({type:`evict`,id:e})}catch{}if(this.hooks.leave(e),this.host)return;let r=this.signalingReady,i=()=>this.end(r?`The host connection ended. Return to Rooms and join again.`:`Room connection ended. Return to Rooms and join again.`);r?this.hostCloseTimer=setTimeout(i,Ds):i()}close(){if(!this.closed){clearTimeout(this.hostCloseTimer),this.hostCloseTimer=void 0,this.signaling.close(),clearInterval(this.timer);for(let e of this.peers.values())clearTimeout(e.admissionTimer),e.controlReader?.clear(),e.pc.close();this.peers.clear()}}},js=256,Ms=e=>e.slice(0,100);function Ns(e,t,n,r){if(e.assertOpen(),typeof n!=`string`)throw Error(`Invalid kick reason`);let i=e.players.byId(t);if(!i||e.isHost(i))return;let a=e.publicPlayer(i),o=Ms(n),s=e.network.peers.get(i.peerId);s&&e.network.control(s,{type:`kicked`,reason:o}),e.network.remove(i.peerId),e.players.has(i)||e.invoke(`onPlayerKicked`,e.hooks.onPlayerKicked,a,o,!1,r)}async function Ps(e,t,n,r=null){if(typeof n!=`string`)throw Error(`Invalid kick reason`);let i=e.players.byId(t);if(!i||e.isHost(i))return;let a=e.publicPlayer(i),o=Ms(n);if(e.bans.size>=js&&!e.bans.has(t))throw Error(`Clear existing bans before adding more.`);try{await e.network.updateBan(`ban`,i.peerId,o)}catch(n){throw n instanceof cs&&e.bans.set(t,i.peerId),n}e.bans.set(t,i.peerId),e.network.remove(i.peerId),e.invoke(`onPlayerKicked`,e.hooks.onPlayerKicked,a,o,!0,r)}async function Fs(e,t){e.assertOpen();let n=e.bans.get(t);n&&(await e.network.updateBan(`clearBan`,n),e.bans.delete(t))}async function Is(e){e.assertOpen(),await e.network.updateBan(`clearBans`),e.bans.clear()}function Ls(e){return e===null||typeof e==`string`&&Array.from(e).length<=2&&!/[\p{Cc}\p{Cf}]/u.test(e)}var Rs=e=>Ue(Me(),he(),ye(0),_e(e)),zs=Rs(31),Bs=Fe([1,2]),Vs=Ue(Le(),ge(200),fe(e=>!!e.trim())),Hs=Ne({score:Rs(99),minutes:Rs(99),locked:Oe(),kickRate:Pe(Rs(rn))}),Us=Ue(Ne({angle:Me(),textColor:Me(),colors:De(Me())}),be(({dataset:e,addIssue:t,NEVER:n})=>{try{let{angle:t,textColor:n,colors:r}=e.value;return kr(t,n,r)}catch{return t({message:`Invalid team colors`}),n}})),Ws=e=>Ne({action:Ae(e)}),Gs=He(`action`,[Ne({action:Ae(`typing`),active:Oe()}),Ne({action:Ae(`chat`),text:Vs}),Ne({action:Ae(`directChat`),recipientId:Ue(Le(),ve(1),ge(128)),text:Vs}),Ne({action:Ae(`avatar`),avatar:ke(Ls)}),Ws(`autoTeams`),Ws(`clearBans`),Ws(`start`),Ws(`stop`),Ne({action:Ae(`teamsLock`),locked:Oe()}),Ne({action:Ae(`resetTeams`),team:Pe(Bs)}),Ne({action:Ae(`team`),team:Fe([0,1,2]),slot:Pe(zs)}),Ne({action:Ae(`defaultStadium`),name:Le()}),Ne({action:Ae(`customStadium`),source:Le()}),Ne({action:Ae(`ban`),slot:zs}),Ne({action:Ae(`kick`),slot:zs}),Ne({action:Ae(`admin`),slot:zs}),Ne({action:Ae(`mute`),slot:zs,muted:Oe()}),Ne({action:Ae(`teamColors`),team:Bs,palette:je(Us)}),Ne({action:Ae(`pause`),paused:Pe(Oe())}),Ne({action:Ae(`kickRate`),value:Rs(rn)}),Ne({action:Ae(`settings`),...Hs.entries})]);function Ks(e,t){let n=We(Gs,{...t,action:e});return n.success?n.output:null}var qs=0xe8d4a51000,Js=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=qs;function Ys(e,t,n=performance.now()){if(Js(e)&&Js(n))return{version:1,requestAtMs:e,hostNowMs:n,streamId:t}}var Xs=new WeakMap;function Zs(e,t,n,r=performance.now()){if(r-(Xs.get(e)??-1/0)<1e4)return;let i=Ys(t,n,r);return i&&Xs.set(e,r),i}function Qs(e,t,n,r){let i=e.find(e=>e.id===t),a=e.find(e=>e.id===n);return!i||i.muted||!a||a.bot||t===n||!r.trim()||r.length>200?null:{type:`directChat`,fromId:i.id,fromName:i.name,toId:a.id,toName:a.name,text:r}}function $s(e,t,n){return t!==void 0&&(e.admin||!n&&t===e)}function ec(e,t,n){return t!==void 0&&e.admin&&t!==e&&!n(t)}function tc(e,t,n){let r=e.indexOf(t);return r<0||t.team===n?!1:(t.team=n,e.splice(r,1),e.push(t),!0)}function nc(e,t){let n=e.filter(e=>e.team===0),r=e.filter(e=>e.team===1).length,i=e.filter(e=>e.team===2).length;if(!n.length||r===i&&n.length<2)return[];let a=()=>n.splice(t?Math.floor(t()*n.length):0,1)[0];return r<i?[{player:a(),team:1}]:i<r?[{player:a(),team:2}]:[{player:a(),team:1},{player:a(),team:2}]}function rc(e,t){return(t?[t]:[2,1]).flatMap(t=>e.filter(e=>e.team===t))}function ic(e,t,n){switch(t.action){case`team`:{let r=t.slot===void 0?e:n.players().find(e=>e.slot===t.slot);return $s(e,r,n.locked())&&n.move(r,t.team),!0}case`teamsLock`:return e.admin&&n.lock(t.locked),!0;case`autoTeams`:case`resetTeams`:{if(!e.admin)return!0;let r=t.action===`resetTeams`?rc(n.players(),t.team).map(e=>({player:e,team:0})):nc(n.players());for(let{player:i,team:a}of r){if(!n.current()||!n.players().includes(e)||!e.admin||t.action===`resetTeams`&&!n.stopped())break;n.players().includes(i)&&((t.action===`autoTeams`?i.team!==0:i.team===0)||n.move(i,a))}return!0}default:return!1}}function ac(e,t,n,r){if(e.assertOpen(),![0,1,2].includes(n))throw Error(`Invalid team`);let i=e.players.byId(t);if(!i)return;let a=i.team;if(!e.players.assignTeam(i,n))return;e.intelligence.removePlayer(i.id),e.commentary.removePlayer(i.id)&&e.network.broadcast({type:`commentary-config`,config:e.commentary.snapshot()}),e.command(`team`,i.slot,n),e.match.recordOrder(e.players.all.map(e=>e.slot)),e.syncLobby();let o=e.publicPlayer(i),s=e.publicOrNull(r);e.publishPlayerRetirement(i,a,`player-changed-team`),e.invoke(`onPlayerTeamChange`,e.hooks.onPlayerTeamChange,o,s)}function oc(e,t,n){e.assertOpen();let r=e.players.byId(t);r&&r.admin!==!!n&&(r.admin=!!n,e.syncLobby(),e.invoke(`onPlayerAdminChange`,e.hooks.onPlayerAdminChange,e.publicPlayer(r),null))}function sc(e,t,n,r){if(e.assertOpen(),!Number.isInteger(t)||typeof n!=`boolean`)throw Error(`Invalid player mute`);let i=e.players.byId(t);i&&!e.isHost(i)&&!!i.muted!==n&&(i.muted=n,e.syncLobby(),e.invoke(`onPlayerMuteChange`,e.hooks.onPlayerMuteChange,e.publicPlayer(i),r))}function cc(e,t,n){e.assertOpen(),e.locked!==!!t&&(e.locked=!!t,e.syncLobby(),e.invoke(`onTeamsLockChange`,e.hooks.onTeamsLockChange,e.locked,n))}function lc(e,t,n){if(e.assertOpen(),t!==1&&t!==2)throw Error(`Invalid team`);JSON.stringify(e.teamStyles[t-1])!==JSON.stringify(n)&&(e.teamStyles[t-1]=n,e.match.recordStyles(e.teamStyles),e.syncLobby())}function uc(e,t,n,r,i){let a=kr(n,r,i);a.angle=((256*n/360|0)&255)*(360/256),lc(e,t,a)}function dc(e,t,n){if(e.assertOpen(),!Array.isArray(t)||t.length>32||t.some(e=>!Number.isSafeInteger(e)||e<0)||typeof n!=`boolean`)throw Error(`Invalid player order`);let r=new Set(t),i=[...r].flatMap(t=>{let n=e.players.byId(t);return n?[n]:[]}),a=e.players.all.filter(e=>!r.has(e.id)),o=n?[...i,...a]:[...a,...i];e.players.reorder(o)&&(e.match.recordOrder(o.map(e=>e.slot)),e.syncLobby())}function fc(e,t,n){if(e.assertOpen(),!Ls(n))throw Error(`Avatar must be null or at most two visible characters.`);let r=e.players.byId(t);r&&(r.avatarOverride=n,e.match.recordPlayer(r.slot,r.name,n??r.avatar),e.syncLobby())}function pc(e,t,n){if(e.assertOpen(),!e.stopped())return;Or(t);let r=++e.stadiumSelection;if(e.match.finishRecording(`Stadium changed`),e.assertOpen(),e.stopped()){if(r!==e.stadiumSelection)throw Error(`Stadium selection superseded`);e.engine.load(t),e.commentaryAnalysis.configure(e.engine,null),e.xg.resetForStadium(e.engine);for(let t of e.players.all)e.engine.setTeam(t.slot,t.team);e.epoch=e.epoch+1&65535,e.factStream.rebase(e.engine,e.epoch),e.intelligence.reset(),e.inputs.reset(),e.network.broadcast({type:`stadium`,epoch:e.epoch,source:t,state:e.engine.snapshot()}),e.invoke(`onStadiumChange`,e.hooks.onStadiumChange,e.engine.stadium.name,n)}}async function mc(e,t){if(e.assertOpen(),!e.stopped())return;let n=++e.stadiumSelection,r=await e.runtime.loadStadium(t);if(e.assertOpen(),n!==e.stadiumSelection)throw Error(`Stadium selection superseded`);pc(e,r,null)}var hc=`You are muted in this room.`,gc=`Message not sent. Please wait a moment before sending again.`;function _c({room:e,peer:t,actor:n},r,i){return!n.muted&&e.traffic.allow(t.id,`chat`)?!1:(e.traffic.allow(t.id,`feedback`)&&e.network.control(t,{type:`chatError`,rejectedText:r,recipientId:i,text:n.muted?hc:gc}),!0)}var vc=({room:e,actor:t})=>!e.closed&&e.players.has(t);function yc(e,t){let{room:n,peer:r,actor:i}=e;n.traffic.allow(r.id,`typing`)&&n.network.broadcast({type:`typing`,playerId:i.peerId,active:t.active&&!i.muted})}function bc(e,t){let{room:n,peer:r,actor:i}=e;if(_c(e,t.text,t.recipientId))return;let a=Qs(n.players.all.map(e=>({...e,id:e.peerId})),r.id,t.recipientId,t.text);if(!a){n.network.control(r,{type:`directChatError`,recipientId:t.recipientId,text:`This player is no longer available.`});return}let o=n.players.byPeer(a.toId);if(!o)return;let s=!1,c=n.invoke(`onPlayerDirectChat`,()=>{let e=n.hooks.onPlayerDirectChat?.(n.publicPlayer(i),n.publicPlayer(o),a.text);return s=!0,e});if(!(!s||c instanceof Promise||c===!1||!vc(e)||i.muted||!n.players.has(o)))for(let e of[a.fromId,a.toId]){let t=n.network.peers.get(e);t&&n.network.control(t,a)}}function xc(e,t){let{room:n,actor:r}=e;_c(e,t.text,``)||(n.invoke(`onPlayerActivity`,n.hooks.onPlayerActivity,n.publicPlayer(r)),vc(e)&&n.invoke(`onPlayerChat`,n.hooks.onPlayerChat,n.publicPlayer(r),t.text)!==!1&&vc(e)&&!r.muted&&n.network.broadcast({type:`chat`,playerId:r.peerId,name:r.name,text:t.text}))}function Sc({room:e,actor:t},n){t.avatar=n.avatar,e.match.recordPlayer(t.slot,t.name,t.avatarOverride??t.avatar),e.syncLobby()}function Cc(e,t){let{room:n,peer:r,actor:i}=e,a=t=>{vc(e)&&n.network.control(r,{type:`stadiumResult`,text:t})};if(!i.admin||!n.stopped()){a(`Stadium change rejected: admin permission and a stopped match are required.`);return}let o=++n.stadiumSelection;(t.action===`defaultStadium`?n.runtime.loadStadium(t.name):Promise.resolve(t.source)).then(t=>{if(vc(e)){if(o!==n.stadiumSelection||!i.admin||!n.stopped()){a(`Stadium change cancelled: room state or permissions changed.`);return}pc(n,t,n.publicPlayer(i)),a(`Stadium applied.`)}}).catch(()=>a(`Stadium could not be loaded. Please try again.`))}function wc({room:e,actor:t},n){let r=e.players.bySlot(n);return ec(t,r,t=>e.isHost(t))?r:void 0}function Tc({room:e,peer:t},n){!e.closed&&e.network.peers.has(t.id)&&e.network.control(t,{type:`moderationResult`,text:n})}function Ec(e,t){let{room:n,actor:r}=e,i=wc(e,t);i&&Ps(n,i.id,`Removed by admin`,n.publicPlayer(r)).then(()=>Tc(e,`Player banned.`)).catch(t=>Tc(e,t instanceof Error?t.message:`Moderation failed.`))}function Dc(e,t,n){ro(e,...on(t),e.publicPlayer(n))}function Oc({room:e,actor:t},n){e.stopped()&&(io(e,n.score),ao(e,n.minutes),cc(e,n.locked,e.publicPlayer(t)),!e.closed&&n.kickRate!==void 0&&n.kickRate!==e.engine.kickRate&&Dc(e,n.kickRate,t))}function kc(e,t){let{room:n,actor:r}=e;switch(t.action){case`mute`:{let i=wc(e,t.slot);i&&sc(n,i.id,t.muted,n.publicPlayer(r));return}case`ban`:return Ec(e,t.slot);case`clearBans`:return Tc(e,`Only the room owner can clear bans.`);case`teamColors`:return lc(n,t.team,t.palette);case`kickRate`:return Dc(n,t.value,r);case`start`:return eo(n,r);case`stop`:return to(n,r);case`pause`:return no(n,t.paused===void 0?!n.engine.paused:t.paused,n.publicPlayer(r));case`settings`:return Oc(e,t);case`kick`:{let i=wc(e,t.slot);i&&Ns(n,i.id,`Removed by host`,n.publicPlayer(r));return}}}function Ac(e,t,n,r){let i={room:e,peer:t,actor:n};switch(r.action){case`typing`:return yc(i,r);case`directChat`:return bc(i,r);case`chat`:return xc(i,r);case`avatar`:return Sc(i,r);case`defaultStadium`:case`customStadium`:return Cc(i,r)}!ic(n,r,{players:()=>e.players.all,current:()=>!e.closed,stopped:()=>e.stopped(),locked:()=>e.locked,move:(t,r)=>ac(e,t.id,r,n),lock:t=>cc(e,t,e.publicPlayer(n))})&&n.admin&&kc(i,r)}var jc=new Set([`chat`,`directChat`,`typing`]);function Mc(e,t){return e.traffic.allow(t.id,`message`)?!0:(e.network.remove(t.id),!1)}function Nc(e){return e.version===1&&e.engine===li&&typeof e.name==`string`&&!!e.name.trim()&&e.name.length<=24}function Pc(e,t,n){let r=Nc(n)?e.players.freeSlot():void 0;if(!Nc(n)||r===void 0){e.network.remove(t.id);return}let i=e.players.add({slot:r,peerId:t.id,name:n.name.trim(),team:0,admin:!1});e.network.admit(t),e.match.recordPlayer(i.slot,i.name),e.command(`join`,r,0),e.turfState.capture(e.engine),e.network.control(t,{type:`welcome`,features:[`directChat`,`playerConversation`],...n.turfVersion===1?{turf:e.turfState.checkpoint()}:{},soundStream:e.soundStream.checkpoint(),commentaryStream:e.factStream.checkpoint(),commentaryClock:Ys(n.commentaryClock,e.factStream.streamId),commentary:e.commentary.snapshot(),epoch:e.epoch,roomName:e.roomName,engine:li,slot:r,stadium:e.engine.source,state:e.engine.snapshot(),players:e.players.roster(),teamStyles:e.teamStyles,locked:e.locked}),e.network.control(t,{type:`commentary-config`,config:e.commentary.snapshot(Date.now(),!0)}),e.syncLobby(),e.invoke(`onPlayerJoin`,e.hooks.onPlayerJoin,e.publicPlayer(i))}function Fc(e){return{control(t,n){if(!Mc(e,t)||!n||typeof n!=`object`)return;let r=n,i=e.players.byPeer(t.id);if(r.type===`join`&&!i)return Pc(e,t,r);if(i&&r.type===`commentary-clock`){let n=Zs(t,r.requestAtMs,e.factStream.streamId);n&&e.network.control(t,{type:`commentary-clock`,clock:n});return}if(!i||r.type!==`action`||!(typeof r.action==`string`&&jc.has(r.action))&&!e.traffic.allow(t.id,`action`))return;let a=Ks(r.action,r);a&&Ac(e,t,i,a)},fast(t,n){if(!Mc(e,t))return;let r=e.players.byPeer(t.id);if(!r)return;let i=e.inputs.accept(t.id,r.slot,n,e.epoch,t=>e.invoke(`onPlayerInput`,e.hooks.onPlayerInput,e.publicPlayer(r),t));i!==void 0&&i&&e.invoke(`onPlayerActivity`,e.hooks.onPlayerActivity,e.publicPlayer(r))},leave(t){e.traffic.delete(t);let n=e.players.byPeer(t);if(!n)return;e.match.recordPlayer(n.slot,null),e.command(`team`,n.slot,0),e.players.removePeer(t),e.intelligence.removePlayer(n.id,n.team!==0),e.commentary.removePlayer(n.id)&&e.network.broadcast({type:`commentary-config`,config:e.commentary.snapshot()}),e.inputs.remove(t),e.syncLobby();let r=e.publicPlayer(n);e.publishPlayerRetirement(n,n.team,`player-left-room`),e.invoke(`onPlayerLeave`,e.hooks.onPlayerLeave,r)},allowStadiumUpload(t){return!!e.players.byPeer(t.id)?.admin&&e.stopped()&&e.traffic.allow(t.id,`message`)}}}var Ic=class{match;now;peers=new Map;closed=!1;input={seq:0,keys:0,epoch:0,history:[]};constructor(e,t=()=>performance.now()){this.match=e,this.now=t}accept(e,t,n,r,i){if(this.closed)return;let a=Mo(n,this.input);if(a.epoch!==r)return;let o=this.peers.get(e);if(o&&!No(a.seq,o.seq))return;let s=o?Math.min(a.history.length,a.seq-o.seq>>>0):1,c=o?.keys??0,l=!1;o?(o.seq=a.seq,o.received=this.now(),o.keys=a.keys):this.peers.set(e,{seq:a.seq,received:this.now(),keys:a.keys});let u=this.match.engine,d=u.index(t)*18+V.INPUT;for(let e=s-1;e>=0;e--){let n=a.history[e],r=n!==c;if(l||=r,c=n,this.closed)return;if(r&&!i){this.match.command(`input`,t,n);continue}let o=u.data[d];o!==n&&(this.match.command(`input`,t,n),i?.(o))}if(!this.closed)return l}expire(e,t,n=this.now()){if(this.closed)return;let r=this.peers.get(e),i=this.match.engine;r&&n-r.received>250&&i.data[i.index(t)*18+V.INPUT]!==0&&this.match.command(`input`,t,0)}acknowledgment(e){return this.peers.get(e)?.seq??0}remove(e){this.peers.delete(e)}reset(){this.peers.clear()}close(){this.closed=!0,this.reset()}},Lc={input:{slot:31,value:31},team:{slot:31,value:2},start:{slot:31,value:31},stop:{slot:31,value:31},pause:{slot:31,value:1},scoreLimit:{slot:31,value:99},timeLimit:{slot:31,value:5940},kickRate:{slot:31,value:rn},join:{slot:31,value:0},disc:{slot:95,value:0}};function Rc(e,t){switch(t.kind){case`disc`:if(!t.properties)throw Error(`Missing replay disc properties`);e.applyDiscProperties(t.slot,t.properties);break;case`input`:e.input(t.slot,t.value);break;case`join`:e.joinPlayer(t.slot);break;case`team`:e.setTeam(t.slot,t.value);break;case`start`:e.start();break;case`stop`:e.stop();break;case`scoreLimit`:e.scoreLimit=t.value;break;case`timeLimit`:e.timeLimit=t.value;break;case`kickRate`:e.setKickRateLimit(...on(t.value));break;case`pause`:e.setPaused(!!t.value)}}function zc(e){let t=JSON.stringify(e),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,`0`)}var Bc=[`input`,`team`,`start`,`stop`,`pause`,`scoreLimit`,`timeLimit`,`kickRate`,`join`,`disc`],Vc=new TextEncoder,Hc=new TextDecoder(`utf-8`,{fatal:!0});function Uc(e){return wa(Wc(e))}function Wc(e){let{commands:t,...n}=e,r=0,i=e.checkpoints.map(e=>{let t=e.state.discs;if(!Array.isArray(t)||t.length>1728||t.some(e=>!Number.isFinite(e)))throw Error(`Invalid checkpoint discs`);return r+=t.length*8,{...e,state:{...e.state,discs:t.length}}});if(i.length>721)throw Error(`Too many replay checkpoints`);let a=Vc.encode(JSON.stringify({...n,checkpoints:i}));if(t.length>5e5||a.length+16>33554432)throw Error(`Replay exceeds bounds`);let o=t.length*12+t.filter(e=>e.kind===`disc`).length*106,s=new Uint8Array(Math.min(Sa,o)),c=new DataView(s.buffer),l=e=>{if(u+e>s.length)throw Error(`Replay exceeds bounds`)},u=0,d=e.initial.tick,f=e=>{if(!Number.isInteger(e)||e<0||e>4294967295)throw Error(`Invalid replay integer`);do{l(1);let t=Math.floor(e/128);s[u++]=e%128|(t?128:0),e=t}while(e)};for(let e of t){let t=Bc.indexOf(e.kind);if(e.kind===`join`&&e.value!==0||e.kind===`team`&&e.value>2)throw Error(`Invalid replay team command`);if(t<0||!Number.isInteger(e.slot)||e.slot<0||e.slot>(e.kind===`disc`?95:31))throw Error(`Invalid replay command`);if(f(e.tick-d),l(1),s[u++]=t,f(e.slot),f(e.value),e.kind===`disc`){let t=nn(e.properties),n=0;tn.forEach(([e],r)=>{t[e]!==void 0&&(n|=1<<r)}),f(n);for(let[e]of tn){let n=t[e];n!==void 0&&(l(8),c.setFloat64(u,n,!0),u+=8)}}d=e.tick}let p=16+a.length+r+u;if(p>33554432)throw Error(`Replay exceeds 32 MB`);let m=new Uint8Array(p),h=new DataView(m.buffer);m.set([66,50,68,49,1,0,0,0]),h.setUint32(8,a.length,!0),h.setUint32(12,t.length,!0),m.set(a,16);let g=16+a.length;for(let t of e.checkpoints)for(let e of t.state.discs)h.setFloat64(g,e,!0),g+=8;return m.set(s.subarray(0,u),g),m}function Gc(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=t[0]===66&&t[1]===50&&t[2]===68&&t[3]===49;if(n&&t.length>33554432)throw Error(`Replay exceeds 32 MB`);return Kc(n?t:Ta(t))}function Kc(e){if(e.length<16||e[0]!==66||e[1]!==50||e[2]!==68||e[3]!==49||e[4]!==1||e[5]||e[6]||e[7])throw Error(`Invalid packed replay header`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(8,!0),r=t.getUint32(12,!0);if(n>e.length-16||r>5e5||r>(e.length-16-n)/3)throw Error(`Invalid packed replay bounds`);let i=JSON.parse(Hc.decode(e.subarray(16,16+n)));if(!i||!Number.isSafeInteger(i.initial?.tick)||i.initial.tick<0)throw Error(`Invalid replay initial tick`);i.commands=[];let a=16+n,o=i.initial.tick;if(!Array.isArray(i.checkpoints)||i.checkpoints.length>721)throw Error(`Invalid packed checkpoints`);let s=i.checkpoints.map(e=>{let t=e?.state?.discs;if(typeof t!=`number`||!Number.isInteger(t)||t<0||t>1728)throw Error(`Invalid checkpoint disc count`);return t});if(s.reduce((e,t)=>e+t*8,0)>e.length-a-r*3)throw Error(`Truncated checkpoint discs`);for(let[e,n]of i.checkpoints.entries()){let r=s[e],i=Array(r);for(let e=0;e<r;e++){let n=t.getFloat64(a,!0);if(!Number.isFinite(n))throw Error(`Nonfinite checkpoint disc`);i[e]=n,a+=8}n.state.discs=i}let c=()=>{let t=0;for(let n=0;n<=28;n+=7){if(a>=e.length)throw Error(`Truncated replay command`);let r=e[a++];if(n===28&&r>15)throw Error(`Replay integer overflow`);if(t+=(r&127)*2**n,!(r&128)){if(n&&r===0)throw Error(`Noncanonical replay integer`);return t}}throw Error(`Invalid replay integer`)};for(let n=0;n<r;n++){if(o+=c(),!Number.isSafeInteger(o)||a>=e.length)throw Error(`Invalid replay tick`);let n=Bc[e[a++]];if(!n)throw Error(`Unknown replay command`);let r=c(),s=c();if(n===`disc`){let l=c();if(l>8191)throw Error(`Invalid disc property mask`);let u={};tn.forEach(([n],r)=>{if(l&1<<r){if(a+8>e.length)throw Error(`Truncated disc properties`);u[n]=t.getFloat64(a,!0),a+=8}}),i.commands.push({tick:o,kind:n,slot:r,value:s,properties:nn(u)});continue}i.commands.push({tick:o,kind:n,slot:r,value:s})}if(a!==e.length)throw Error(`Trailing replay command data`);return i}var qc=31457280,Jc=5e5,Yc=4096,Xc=ti*5,Zc=class{replay;playerOrder=[];lastInputs=new Map;bytes=0;full=!1;canRecord(e){return!this.full&&e.tick-this.replay.initial.tick<ti*3600}constructor(e,t=[],n=[null,null]){let r=e.snapshot();this.playerOrder=t.map(e=>e.slot),this.replay={magic:`B2DR`,version:1,engine:li,stadium:e.source,initial:r,commands:[],checkpoints:[],roster:t.map(e=>({...e,tick:r.tick})),styles:[{tick:r.tick,teams:Ar(n)}],orders:[{tick:r.tick,slots:[...this.playerOrder]}],end:r.tick,finalHash:zc(r)},this.bytes=new TextEncoder().encode(JSON.stringify(this.replay)).length;for(let t=0;t<32;t++)this.lastInputs.set(t,e.data[e.index(t)*18+V.INPUT])}reserve(e){let t=new TextEncoder().encode(JSON.stringify(e)).length+1;return this.full||this.bytes+t>qc?(this.full=!0,!1):(this.bytes+=t,!0)}player(e,t,n,r){let i={tick:e,slot:t,name:n,avatar:r};return this.replay.roster.length>=Yc||!this.reserve(i)?(this.full=!0,!1):(this.replay.roster.push(i),n===null?this.order(e,this.playerOrder.filter(e=>e!==t)):this.playerOrder.includes(t)?!0:this.order(e,[...this.playerOrder,t]))}style(e,t){let n={tick:e,teams:Ar(t)},r=this.replay.styles;return r.length>=Yc||!this.reserve(n)?(this.full=!0,!1):(r.push(n),!0)}order(e,t){if(t.length===this.playerOrder.length&&t.every((e,t)=>e===this.playerOrder[t]))return!0;let n={tick:e,slots:[...t]},r=this.replay.orders;return r.length>=Yc||!this.reserve(n)?(this.full=!0,!1):(this.playerOrder=[...t],r.push(n),!0)}command(e){return e.kind===`input`&&this.lastInputs.get(e.slot)===e.value?!0:this.replay.commands.length>=Jc||!this.reserve(e)?(this.full=!0,!1):(e.kind===`input`&&this.lastInputs.set(e.slot,e.value),(e.kind===`team`||e.kind===`join`)&&this.lastInputs.set(e.slot,0),e.kind===`start`&&this.lastInputs.clear(),this.replay.commands.push(e.kind===`disc`?{...e,properties:nn(e.properties)}:{...e}),!0)}step(e){for(let t=0;t<32;t++)this.lastInputs.set(t,e.data[e.index(t)*18+V.INPUT]);if(e.tick%Xc===0){let t=e.snapshot(),n={tick:e.tick,state:t,hash:zc(t)};this.reserve(n)&&this.replay.checkpoints.push(n)}this.replay.end=e.tick}pack(e){return this.replay.end=e.tick,this.replay.finalHash=zc(e.snapshot()),Wc(this.replay)}finish(e){return this.replay.end=e.tick,this.replay.finalHash=zc(e.snapshot()),new Blob([Uc(this.replay)],{type:`application/x-ball2d-replay`})}},Qc=5e5,$c=721,el=4096,tl=ti*3600,nl=(e,t,n)=>Number.isInteger(e)&&e>=t&&e<=n;function rl(e){if(e.magic!==`B2DR`||e.version!==1||e.engine!==li)throw Error(`Unsupported replay engine/version`);if(!Array.isArray(e.commands)||e.commands.length>Qc||!Array.isArray(e.checkpoints)||e.checkpoints.length>$c||!Number.isInteger(e.end)||e.end<e.initial.tick||e.end-e.initial.tick>tl)throw Error(`Invalid replay bounds`)}function il(e){let t=e.initial.tick;for(let n of e.commands){let r=Object.hasOwn(Lc,n.kind)?Lc[n.kind]:void 0;if(!r||!nl(n.tick,t,e.end)||!nl(n.slot,0,r.slot)||!nl(n.value,0,r.value))throw Error(`Invalid replay command`);n.kind===`disc`&&(n.properties=nn(n.properties)),t=n.tick}}function al(e){if(!Array.isArray(e.roster)||e.roster.length>el)throw Error(`Invalid replay roster`);let t=e.initial.tick;for(let n of e.roster){if(!nl(n.tick,t,e.end)||!nl(n.slot,0,31)||n.name!==null&&(typeof n.name!=`string`||n.name.length>24)||n.avatar!==void 0&&!Ls(n.avatar))throw Error(`Invalid roster event`);t=n.tick}}function ol(e){if(e.styles===void 0)return;if(!Array.isArray(e.styles)||e.styles.length>el)throw Error(`Invalid replay styles`);let t=e.initial.tick;for(let n of e.styles){if(!n||!nl(n.tick,t,e.end)||n.teams===void 0)throw Error(`Invalid replay style`);n.teams=Ar(n.teams),t=n.tick}}function sl(e){if(e.orders===void 0)return;if(!Array.isArray(e.orders)||e.orders.length>el)throw Error(`Invalid replay orders`);let t=e.initial.tick;for(let n of e.orders){if(!n||!nl(n.tick,t,e.end)||!Array.isArray(n.slots)||n.slots.length>32||n.slots.some(e=>!nl(e,0,31))||new Set(n.slots).size!==n.slots.length)throw Error(`Invalid replay order`);t=n.tick}}function cl(e){let t=e.initial.tick;for(let n of e.checkpoints){if(!nl(n.tick,t+1,e.end)||n.state.tick!==n.tick||typeof n.hash!=`string`)throw Error(`Invalid checkpoint`);t=n.tick}}function ll(e){let t=Gc(e);return rl(t),il(t),al(t),ol(t),sl(t),cl(t),t}async function ul(e){if(e.size>33554432)throw Error(`Replay exceeds 32 MB`);return ll(await e.arrayBuffer())}var dl=class{engine;onRecordingComplete;recorder;closed=!1;completing=!1;constructor(e,t){this.engine=e,this.onRecordingComplete=t}assertOpen(){if(this.closed)throw Error(`Room is closed`)}get recording(){return!!this.recorder}command(e,t=0,n=0,r){this.assertOpen();let i={tick:this.engine.tick,kind:e,slot:t,value:n};r&&(i.properties=r),this.recorder&&(!this.recorder.canRecord(this.engine)||!this.recorder.command(i))&&this.finishRecording(`Recording limit reached`),this.assertOpen(),Rc(this.engine,i)}checkRecordingLimit(){this.recorder&&!this.recorder.canRecord(this.engine)&&this.finishRecording(`Recording limit reached`)}step(){this.assertOpen(),this.engine.step(),this.recorder?.step(this.engine)}recordPlayer(e,t,n){this.recorder?.player(this.engine.tick,e,t,n)}recordStyles(e){this.recorder?.style(this.engine.tick,e)}recordOrder(e){this.recorder?.order(this.engine.tick,e)}startRecording(e,t){if(this.assertOpen(),this.completing)throw Error(`Recording completion is in progress`);if(this.recorder)throw Error(`Recording is already active`);this.recorder=new Zc(this.engine,e,t)}stopRecording(){if(!this.recorder)return null;let e=this.recorder.pack(this.engine);return this.recorder=void 0,e}finishRecording(e){let t=this.stopRecording();if(t){this.completing=!0;try{this.onRecordingComplete(t,e)}finally{this.completing=!1}}}discardRecording(){this.recorder=void 0}close(e=`Room closed`){this.closed||(this.closed=!0,this.finishRecording(e))}},fl=new Set([`start`,`goal`,`end`]),pl=e=>Math.max(0,Math.min(1,e));function ml({p0:e,p1:t},n,r){let i=t[0]-e[0],a=t[1]-e[1],o=Math.hypot(i,a)||1,s=((n-e[0])*i+(r-e[1])*a)/o,c=((n-e[0])*a-(r-e[1])*i)/o;return{along:s,across:(-e[0]*a+e[1]*i)/o<0?-c:c,length:o}}function hl(e,t){let n=e.data,[r,i,a]=[n[0],n[1],n[V.RADIUS]],o=t*18;return t>0&&n[o+V.INVERSE_MASS]!==0?`touch`:t>0&&e.stadium.goals.some(({p0:e,p1:t})=>[e,t].some(([e,t])=>Math.hypot(n[o]-e,n[o+V.Y]-t)<=n[o+V.RADIUS]))?`post`:e.stadium.goals.some(e=>{let{along:t,across:n,length:o}=ml(e,r,i);return t>-a&&t<o+a&&n<0})?`net`:`wall`}var gl=class{stream;sequence=0;pending=[];lastSent=-1/0;phase=`lobby`;lastContactTick=-1/0;lastBumpTick=-1/0;constructor(e=crypto.randomUUID()){this.stream=e}checkpoint(){return{stream:this.stream,sequence:this.sequence}}capture(e,t,n=this.phase){let r=e.data,i=(n,i,a=r[0],o=r[1])=>({kind:n,intensity:Math.round(Math.max(0,Math.min(1,i))*100)/100,sequence:++this.sequence,tick:e.tick,epoch:t,slot:0,x:a,y:o}),a=.3+.7*pl((Math.hypot(r[2],r[3])-4)/5),o=(e.ballKicks??[]).map(e=>({...i(`kick`,a),slot:e})),s=e.phase===`playing`||e.phase===`goal`,c=e.ballContact;c&&!o.length&&s&&(e.tick<this.lastContactTick||e.tick-this.lastContactTick>=6)&&(o.push(i(hl(e,c.disc),(c.speed-1)/10)),this.lastContactTick=e.tick);let l=e.playerContact;if(l&&s){let t=l.speed>=.6,n=e.tick-this.lastBumpTick;if(l.speed>=.06&&(n<0||n>=(t?6:15))){let n=l.a*18,a=l.b*18;o.push(i(`bump`,t?.15+.85*pl(l.speed/5):l.speed/4,(r[n]+r[a])/2,(r[n+V.Y]+r[a+V.Y])/2)),this.lastBumpTick=e.tick}}if(e.phase!==n){let t=e.phase===`goal`?`goal`:e.phase===`playing`?`start`:e.phase===`finished`||e.phase===`lobby`&&n!==`finished`?`end`:void 0;t&&o.push(i(t,1,0,0))}for(this.phase=e.phase,this.pending.push(...o);this.pending.length>8;){let e=this.pending.findIndex(e=>e.kind===`bump`),t=this.pending.findIndex(e=>!fl.has(e.kind));this.pending.splice(Math.max(0,e>=0?e:t),1)}return o}drain(e){if(!this.pending.length||e-this.lastSent<50)return;this.lastSent=e;let t=this.pending;return this.pending=[],{type:`match-sounds`,stream:this.stream,events:t}}};function _l(e,t){if(t)for(let n of e.peers.values())n.control?.readyState===`open`&&n.control.bufferedAmount<16384&&e.control(n,t)}var vl=e=>({phase:e.phase,red:e.red,blue:e.blue,paused:e.paused,tick:e.tick}),yl=class{streamId;sequence=0;epoch=0;touch=null;touchPlayer=null;previous={phase:`lobby`,red:0,blue:0,paused:!1,tick:0};constructor(e=crypto.randomUUID()){this.streamId=e}checkpoint(){return{streamId:this.streamId,sequence:this.sequence,epoch:this.epoch}}rebase(e,t){this.previous=vl(e),this.epoch=t,this.touch=e.lastTouch,this.touchPlayer=null}capture(e,t,n=()=>null,r){if(t!==this.epoch||e.tick<this.previous.tick)return this.rebase(e,t),[];let i=this.previous;if(this.previous=vl(e),e.lastTouch!==this.touch){this.touch=e.lastTouch;let t=this.touch?n(this.touch.slot):null;this.touchPlayer=t&&this.touch?{...t,team:this.touch.team}:null}let a=[],o=(n,r={})=>{let i=++this.sequence,o={eventId:`${this.streamId}:${i}`,streamId:this.streamId,sequence:i,tick:e.tick,epoch:t,kind:n,context:{phase:e.phase,elapsed:e.elapsed/ti,timeLimit:e.timeLimit,scoreLimit:e.scoreLimit,score:{red:e.red,blue:e.blue},paused:e.paused},...r};a.push(o)};if(e.phase===`goal`&&i.phase!==`goal`){let t=e.red>i.red?1:e.blue>i.blue?2:null;if(t){let n=e.goalTouch,r=n&&this.touch?.slot===n.slot&&this.touch.team===n.team?this.touchPlayer:null;o(`goal`,{goal:{team:t,scorer:r&&n?{...r,team:n.team}:null,ownGoal:!!n&&n.team!==t}})}}return e.phase!==i.phase&&(e.phase===`playing`?o(i.phase===`goal`?`restart`:`kickoff`):e.phase===`finished`?o(`end`,{endReason:e.scoreLimit>0&&Math.max(e.red,e.blue)>=e.scoreLimit?`score-limit`:e.timeLimit>0&&e.elapsed/ti>=e.timeLimit?`time-limit`:e.red===e.blue?`draw`:`script`}):e.phase===`lobby`&&(i.phase!==`finished`||r===`stop`)&&o(`stop`)),e.phase!==`lobby`&&e.phase===i.phase&&e.paused!==i.paused&&o(e.paused?`pause`:`resume`),a}};function bl(e,t){t.length&&e.broadcast({type:`match-facts`,version:1,sentAtMs:performance.now(),streamId:t[0].streamId,facts:t})}var xl=Object.freeze({locale:`en`,dose:`balanced`,reactionIntensity:.7,maxDurationMs:2800,minGapMs:3500,semanticCooldownMs:3e4,historySize:64,traceSize:128,seed:1,families:Object.freeze({}),contextFactsEnabled:!1,channels:Object.freeze({audio:!0,caption:!0,chat:!0})}),Sl=(e,t,n,r)=>Number.isFinite(e)?Math.max(n,Math.min(r,e)):t;function Cl(e={},t=xl){let n={...t.families};for(let[t,r]of Object.entries(e.families??{}))wl.includes(t)&&r&&(n[t]=Object.freeze({...n[t],...typeof r.enabled==`boolean`?{enabled:r.enabled}:{},...r.cooldownMs===void 0?{}:{cooldownMs:Sl(r.cooldownMs,0,0,3e5)},...r.priority===void 0?{}:{priority:Sl(r.priority,50,0,100)},...r.ttlMs===void 0?{}:{ttlMs:Sl(r.ttlMs,1500,100,1e4)}}));return Object.freeze({locale:e.locale===`tr`||e.locale===`en`?e.locale:t.locale,dose:[`off`,`minimal`,`balanced`,`rich`].includes(e.dose??``)?e.dose??t.dose:t.dose,reactionIntensity:Sl(e.reactionIntensity??t.reactionIntensity,.7,0,1),maxDurationMs:Sl(e.maxDurationMs??t.maxDurationMs,2800,250,6e3),minGapMs:Sl(e.minGapMs??t.minGapMs,3500,0,6e4),semanticCooldownMs:Sl(e.semanticCooldownMs??t.semanticCooldownMs,3e4,0,3e5),historySize:Math.floor(Sl(e.historySize??t.historySize,64,1,256)),traceSize:Math.floor(Sl(e.traceSize??t.traceSize,128,0,512)),seed:Math.floor(Sl(e.seed??t.seed,1,0,4294967295)),families:Object.freeze(n),contextFactsEnabled:typeof e.contextFactsEnabled==`boolean`?e.contextFactsEnabled:t.contextFactsEnabled,channels:Object.freeze({audio:typeof e.channels?.audio==`boolean`?e.channels.audio:t.channels?.audio??!0,caption:typeof e.channels?.caption==`boolean`?e.channels.caption:t.channels?.caption??!0,chat:typeof e.channels?.chat==`boolean`?e.channels.chat:t.channels?.chat??!0})})}var wl=Object.freeze(`kickoff,restart,goal.neutral,goal.first,goal.equalizer,goal.lead,goal.late-winner,goal.consolation,goal.own-goal,post,near-miss,pressure,pass,pass-chain,turnover,assist,save,shot,block,counterattack,attack-progress,sustained-pressure,tactical-summary,match-end.win,match-end.draw,match-stop,pause,resume,context.fact`.split(`,`)),Tl=e=>typeof e==`string`&&/^[a-f0-9]{64}$/u.test(e),El=e=>!!e&&typeof e==`object`&&!Array.isArray(e),Dl=(e,t)=>Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t)),Ol=e=>typeof e==`string`&&e.trim().length>0&&e.length<=512;function kl(e,t){if(!El(e)||!Dl(e,[`schemaVersion`,`audioSha256`,`textSha256`,`durationMs`,`words`,`annotation`])||e.schemaVersion!==1||!Tl(e.audioSha256)||e.audioSha256!==t.audio?.sha256||!Tl(e.textSha256)||!Number.isFinite(t.durationMs)||t.durationMs<=0||e.durationMs!==t.durationMs||!Ol(t.text)||!Array.isArray(e.words)||e.words.length<1||e.words.length>128||!El(e.annotation)||!Dl(e.annotation,[`source`,`reviewer`,`reference`])||![e.annotation.source,e.annotation.reviewer,e.annotation.reference].every(Ol))throw Error(`Invalid commentary word timing binding`);let n=[...t.text.matchAll(/\S+/gu)];if(n.length!==e.words.length)throw Error(`Word timing requires complete token coverage`);let r=0,i=e.words.map((e,i)=>{let a=n[i];if(!El(e)||!Dl(e,[`startChar`,`endChar`,`startMs`,`endMs`])||e.startChar!==a.index||e.endChar!==a.index+a[0].length||typeof e.startMs!=`number`||typeof e.endMs!=`number`||!Number.isFinite(e.startMs)||!Number.isFinite(e.endMs)||e.startMs<r||e.endMs<=e.startMs||e.endMs>t.durationMs)throw Error(`Invalid commentary word timing order, token or clip bounds`);return r=e.endMs,Object.freeze({startChar:a.index,endChar:a.index+a[0].length,startMs:e.startMs,endMs:e.endMs})});return Object.freeze({schemaVersion:1,audioSha256:e.audioSha256,textSha256:e.textSha256,durationMs:t.durationMs,words:Object.freeze(i),annotation:Object.freeze({source:e.annotation.source,reviewer:e.annotation.reviewer,reference:e.annotation.reference})})}var Al=e=>Ue(Le(),ve(1),ge(e)),jl=Ue(Al(96),xe(/^[a-zA-Z0-9._:-]+$/)),Ml=(e,t)=>Ue(Me(),pe(),ye(e),_e(t)),Nl=Ue(Re([Ml(0,1),Ml(0,1)]),fe(e=>e[0]<=e[1])),Pl=Ne({source:Al(200),license:Al(200),status:Fe([`draft`,`approved`])}),Fl=Ne({url:Ue(Al(1024),fe(e=>{if((!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`))&&!e.startsWith(`https://`))return!1;try{let t=new URL(e,`https://ball2d.invalid`);return t.protocol===`https:`&&!t.username&&!t.password}catch{return!1}})),sha256:Ue(Le(),xe(/^[a-f0-9]{64}$/))}),Il=Ne({id:jl,locale:Fe([`tr`,`en`]),role:Fe([`play-by-play`,`analyst`]),family:Fe(wl),semanticKey:Al(96),openingKey:Al(96),text:Al(300),intensity:Nl,durationMs:Ml(1,12e3),onsetMs:Ml(0,11999),interruptibleAtMs:Ue(De(Ml(0,12e3)),ge(16)),cooldownMs:Ml(0,3e5),audio:je(Fl),wordTiming:Pe(Ve()),provenance:Pl,fallbackId:Pe(jl),contextFactKey:Pe(jl),contextFactValue:Pe(Be([Ue(Le(),ge(80)),Ue(Me(),pe())]))}),Ll=Ne({id:jl,kind:Fe([`bed`,`tension`,`goal`,`disappointment`,`chant`,`post`,`near-miss`,`release`]),team:Be([Ae(`neutral`),Ae(1),Ae(2)]),intensity:Nl,durationMs:Ml(100,6e4),loop:je(Ne({startMs:Ml(0,6e4),endMs:Ml(1,6e4)})),audio:Fl,provenance:Pl}),Rl=e=>{if(new TextEncoder().encode(JSON.stringify(e)).length>262144)throw Error(`Commentary assets exceed 256 KiB control budget`)};function zl(e){if(e===null)return null;let t=We(Ue(De(Il),ge(4096)),e);if(!t.success)throw Error(`Invalid commentary catalog`);let n=t.output.map(({wordTiming:e,...t})=>({...t,...e===void 0?{}:{wordTiming:kl(e,t)}}));Rl(n);let r=new Map(n.map(e=>[e.id,e]));if(r.size!==n.length)throw Error(`Duplicate commentary cue`);let i=new Set;for(let e of n){if(e.onsetMs>=e.durationMs||e.interruptibleAtMs.some((t,n)=>t>=e.durationMs||n>0&&t<=e.interruptibleAtMs[n-1])||e.provenance.status===`approved`&&!e.audio||e.family===`context.fact`&&(!e.contextFactKey||e.contextFactValue===void 0))throw Error(`Invalid commentary cue timing or context`);let t=e,n=new Set;for(;t.fallbackId&&!i.has(t.id);){if(n.has(t.id))throw Error(`Cyclic commentary fallback`);n.add(t.id);let e=r.get(t.fallbackId);if(!e||e.locale!==t.locale||e.role!==t.role||!(e.family===t.family||t.family.startsWith(`goal.`)&&e.family===`goal.neutral`)||t.family===`context.fact`&&(e.contextFactKey!==t.contextFactKey||e.contextFactValue!==t.contextFactValue))throw Error(`Missing or incompatible commentary fallback`);t=e}for(let e of n)i.add(e)}return n}function Bl(e){if(e===null)return null;let t=We(Ne({id:jl,version:Al(32),cues:Ue(De(Ll),ge(64))}),e);if(!t.success)throw Error(`Invalid atmosphere pack`);let n=t.output,r=new Set;for(let e of n.cues){if(r.has(e.id)||e.provenance.status!==`approved`||e.loop&&(e.loop.endMs-e.loop.startMs<100||e.loop.endMs>e.durationMs||![`bed`,`tension`,`chant`].includes(e.kind)))throw Error(`Invalid atmosphere cue identity, loop or approval`);r.add(e.id)}return Rl(n),n}var Vl=Object.freeze({enabled:!0,bedIntensity:1,reactionIntensity:1,chantIntensity:.5,chantCooldownMs:45e3,preferredTeam:`neutral`}),Hl=Ne({enabled:Oe(),bedIntensity:Ml(0,1),reactionIntensity:Ml(0,1),chantIntensity:Ml(0,1),chantCooldownMs:Ml(5e3,3e5),preferredTeam:Be([Ae(`neutral`),Ae(1),Ae(2)])});function Ul(e,t=Vl){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid atmosphere policy`);let n=We(Hl,{...t,...e});if(!n.success)throw Error(`Invalid atmosphere policy`);return n.output}var Wl=class{policy=Cl();context=new Map;catalog=null;atmosphere=Vl;atmospherePack=null;setCatalog(e){this.catalog=zl(e)}getCatalog(){return structuredClone(this.catalog)}setAtmosphere(e){this.atmosphere=Ul(e,this.atmosphere)}getAtmosphere(){return structuredClone(this.atmosphere)}setAtmospherePack(e){this.atmospherePack=Bl(e)}getAtmospherePack(){return structuredClone(this.atmospherePack)}configure(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid commentary policy`);this.policy=Cl(e,this.policy)}getPolicy(){return structuredClone(this.policy)}setPlayer(e,t,n=Date.now()){if(t===null){this.context.delete(e.playerId);return}if(!Array.isArray(t)||t.length>4)throw Error(`At most four commentary facts per player`);let r=new Set,i=t.map(t=>{if(!t||typeof t!=`object`||typeof t.id!=`string`||!/^[a-zA-Z0-9._:-]{1,64}$/.test(t.id)||r.has(t.id)||typeof t.key!=`string`||!/^[a-zA-Z0-9._:-]{1,64}$/.test(t.key)||typeof t.source!=`string`||!t.source.trim()||t.source.length>120||!(typeof t.value==`string`&&t.value.length<=80||typeof t.value==`number`&&Number.isFinite(t.value))||!Number.isFinite(t.issuedAtMs)||!Number.isFinite(t.expiresAtMs)||t.issuedAtMs>n+5e3||t.expiresAtMs<=n||t.expiresAtMs<=t.issuedAtMs||t.expiresAtMs-t.issuedAtMs>36e5)throw Error(`Invalid or expired commentary player fact`);return r.add(t.id),{id:t.id,key:t.key,source:t.source,value:t.value,issuedAtMs:t.issuedAtMs,expiresAtMs:t.expiresAtMs,player:{...e},trusted:!0}});this.context.set(e.playerId,i)}getPlayer(e,t=Date.now()){let n=(this.context.get(e)??[]).filter(e=>e.expiresAtMs>t);return n.length?this.context.set(e,n):this.context.delete(e),structuredClone(n)}removePlayer(e){return this.context.delete(e)}snapshot(e=Date.now(),t=!1){let n=[...this.context.keys()].flatMap(t=>this.getPlayer(t,e));return{version:1,policy:this.getPolicy(),playerFacts:n,hostNowMs:e,sentAtMs:performance.now(),atmosphere:this.getAtmosphere(),...t===!0||t===`catalog`?{catalog:this.getCatalog()}:{},...t===!0||t===`atmospherePack`?{atmospherePack:this.getAtmospherePack()}:{}}}},Gl={enabled:!0,maxGapMs:250,controlHoldMs:120,controlExtraRadii:1.25,controlRelativeSpeedRadii:12,passWindowMs:3e3,passMinTravelRadii:4,chainWindowMs:1e4,assistWindowMs:8e3,shotWindowMs:2e3,shotMinSpeedRadii:18,shotHorizonMs:2e3,saveAreaGoalWidths:1.5,progressGoalWidths:.75,counterWindowMs:4e3,pressureHoldMs:1800,pressureAreaGoalWidths:1.5,summaryWindowMs:15e3},Kl={maxGapMs:[16,1e3],controlHoldMs:[50,1e3],controlExtraRadii:[0,4],controlRelativeSpeedRadii:[1,40],passWindowMs:[300,6e3],passMinTravelRadii:[2,30],chainWindowMs:[1e3,2e4],assistWindowMs:[500,12e3],shotWindowMs:[200,4e3],shotMinSpeedRadii:[5,100],shotHorizonMs:[200,3e3],saveAreaGoalWidths:[.25,3],progressGoalWidths:[.25,3],counterWindowMs:[1e3,8e3],pressureHoldMs:[500,6e3],pressureAreaGoalWidths:[.5,4],summaryWindowMs:[5e3,6e4]};function ql(e={},t=Gl){let n=e&&typeof e==`object`?e:{},r={...Gl,...t};r.enabled=typeof n.enabled==`boolean`?n.enabled:typeof t.enabled==`boolean`?t.enabled:Gl.enabled;for(let e of Object.keys(Kl)){let i=n[e],a=Number.isFinite(t[e])?t[e]:Gl[e],[o,s]=Kl[e];r[e]=Math.max(o,Math.min(s,typeof i==`number`&&Number.isFinite(i)?i:a))}return Object.freeze(r)}var Jl=()=>({controlledMs:0,completedPasses:0,failedPasses:0,turnoversWon:0,directedShots:0,blocks:0,saves:0,confirmedAssists:0}),Yl=(e,t=1)=>Math.min(2**53-1,e+t),Xl={"player-retired":120,"control-ended":110,"assist-confirmed":100,"goalkeeper-save":95,block:90,"directed-shot":85,counterattack:80,"pass-chain":75,"attack-progress":70,"pass-completed":65,turnover:60,"pass-failed":55,"sustained-pressure":50,"control-established":30,"tactical-summary":10},Zl=(e,t)=>e.identity.playerId===t.identity.playerId&&e.identity.sessionId===t.identity.sessionId&&e.identity.team===t.identity.team&&e.role===t.role,Ql=(e,t)=>e.length===t.length&&e.every((e,n)=>Zl(e,t[n])||t.some(t=>Zl(e,t))),$l=(e,t)=>e.id===t.id&&e.defendingTeam===t.defendingTeam&&e.p0[0]===t.p0[0]&&e.p0[1]===t.p0[1]&&e.p1[0]===t.p1[0]&&e.p1[1]===t.p1[1]&&e.pitchPoint[0]===t.pitchPoint[0]&&e.pitchPoint[1]===t.pitchPoint[1],eu=(e,t)=>e.length===t.length&&e.every((e,n)=>$l(e,t[n])||t.some(t=>$l(e,t))),tu=class{ticksPerSecond;policy;streamId=null;epoch=-1;tick=-1;confirmedSequence=0;sequence=0;status=`uninitialized`;unknown=[];geometryBaseline=null;rosterBaseline=null;controller=null;candidate=null;lastController=null;pass=null;lastPass=null;shot=null;chain={team:null,completed:0,tick:-1};attack=null;contacts=new Set;red=Jl();blue=Jl();observedMs=0;uncontrolledMs=0;summarySince=-1;summaryBase={red:0,blue:0,observed:0,redPasses:0,bluePasses:0};emitted=0;dropped=0;completeAtTick=!1;constructor(e={},t=60){if(this.ticksPerSecond=t,!Number.isFinite(t)||t<1||t>1e3)throw Error(`Invalid intelligence tick rate`);this.policy=ql(e)}getPolicy(){return this.policy}invalidate(e=`discontinuity`){this.clearContinuity(),this.completeAtTick=!1,this.unknown=[typeof e==`string`&&e.length?e.slice(0,96):`discontinuity`],this.status=this.policy.enabled?`unknown`:`disabled`}configure(e){return this.policy=ql(e,this.policy),this.reset(),this.policy}reset(){this.clearContinuity(),this.streamId=null,this.epoch=this.tick=-1,this.confirmedSequence=this.sequence=0,this.geometryBaseline=this.rosterBaseline=null,this.contacts.clear(),this.red=Jl(),this.blue=Jl(),this.observedMs=this.uncontrolledMs=this.emitted=this.dropped=0,this.summarySince=-1,this.summaryBase={red:0,blue:0,observed:0,redPasses:0,bluePasses:0},this.status=this.policy.enabled?`uninitialized`:`disabled`,this.unknown=[],this.completeAtTick=!1}clearContinuity(){this.controller=this.candidate=this.lastController=null,this.pass=this.lastPass=this.shot=null,this.chain={team:null,completed:0,tick:-1},this.attack=null,this.summarySince=-1}team(e){return e===1?this.red:this.blue}ms(e){return e*1e3/this.ticksPerSecond}emit(e,t,n,r,i,a={}){let o=Object.freeze({eventId:`${t.streamId}:intelligence:${t.epoch}:${t.tick}:${++this.sequence}`,streamId:t.streamId,epoch:t.epoch,tick:t.tick,kind:n,team:r,context:Object.freeze({...t.context,score:Object.freeze({...t.context.score})}),confidence:a.confidence??`supported`,evidence:Object.freeze(i),metrics:Object.freeze({...a.metrics??{}}),...a.player?{player:at(a.player)}:{},...a.otherPlayer?{otherPlayer:at(a.otherPlayer)}:{},...a.goalId?{goalId:a.goalId}:{},...a.shotQuality?{shotQuality:a.shotQuality}:{},...this.attack?.team===r?{attackId:this.attack.id}:{}});e.length<40?e.push(o):this.dropped++}finish(e){return e.sort((e,t)=>Xl[t.kind]-Xl[e.kind]),e.length>8&&(this.dropped+=e.length-8,e.length=8),this.emitted=Yl(this.emitted,e.length),Object.freeze(e)}observe(e){if(!this.policy.enabled)return this.status=`disabled`,[];if(!lt(e))return this.clearContinuity(),this.completeAtTick=!1,this.status=`unknown`,this.unknown=[`invalid-or-overflow-frame`],[];if(this.streamId&&e.streamId!==this.streamId||this.epoch>=0&&$e(e.epoch,this.epoch)||e.epoch===this.epoch&&e.tick<=this.tick)return[];this.epoch>=0&&(e.epoch!==this.epoch||!this.rosterBaseline||!this.geometryBaseline||!Ql(e.players,this.rosterBaseline)||!eu(e.goals,this.geometryBaseline))&&this.reset();let t=this.tick,n=t>=0?this.ms(e.tick-t):0;this.streamId=e.streamId,this.epoch=e.epoch,this.tick=e.tick,this.rosterBaseline||=e.players.map(e=>({identity:at(e.identity),role:e.role})),this.geometryBaseline||=e.goals.map(e=>({...e,p0:[...e.p0],p1:[...e.p1],pitchPoint:[...e.pitchPoint]})),this.unknown=[],n>this.policy.maxGapMs&&(this.clearContinuity(),this.unknown.push(`sampling-gap`));let r=t<0?e.tick-1:t,i=e.contacts.filter(e=>e.tick>r&&!this.contacts.has(e.id));for(let e of i){this.contacts.add(e.id);let t=this.contacts.values().next().value;this.contacts.size>128&&t!==void 0&&this.contacts.delete(t)}let a=!1,o=-1,s=``;for(let e of i){let t=e.player?it(e.player):e.kind;if(e.tick!==o)o=e.tick,s=t;else if(t!==s){a=!0;break}}let c=e.contactsComplete&&!a&&n<=this.policy.maxGapMs;this.completeAtTick=c,c||(this.pass=this.lastPass=this.shot=null,this.chain={team:null,completed:0,tick:-1},this.unknown.push(a?`ambiguous-contact-order`:e.contactsComplete?`sampling-gap`:`incomplete-contact-coverage`));for(let e of i)e.player&&this.lastPass&&it(e.player)!==it(this.lastPass.to)&&(this.lastPass=null);if(e.context.paused||e.context.phase!==`playing`)return(e.context.paused||e.context.phase===`lobby`)&&this.clearContinuity(),this.controller=this.candidate=null,this.summarySince=-1,this.status=`paused`,[];e.goals.length||this.unknown.push(`goal-geometry-unavailable`);let l=[];if(this.pass&&this.ms(e.tick-this.pass.tick)>this.policy.passWindowMs&&(this.pass=null),this.lastPass&&this.ms(e.tick-this.lastPass.tick)>this.policy.assistWindowMs&&(this.lastPass=null),this.shot&&this.ms(e.tick-this.shot.tick)>this.policy.shotWindowMs&&(this.shot=null),this.chain.team&&this.ms(e.tick-this.chain.tick)>this.policy.chainWindowMs&&(this.chain={team:null,completed:0,tick:-1}),this.lastController&&this.ms(e.tick-this.lastController.tick)>this.policy.chainWindowMs&&(this.attack=null,this.lastController=null),c)for(let t of i){let n=t.player;if(n&&this.pass&&n.team!==this.pass.player.team){let t=this.pass;this.team(t.player.team).failedPasses++,this.emit(l,e,`pass-failed`,t.player.team,[`verified-kick`,`opponent-contact-before-reception`],{player:t.player,otherPlayer:n,metrics:{flightMs:this.ms(e.tick-t.tick)}}),this.pass=null,this.chain={team:null,completed:0,tick:-1}}if(n&&this.shot&&n.team!==this.shot.player.team&&(t.tick===e.tick?this.defend(e,n,l):this.shot=null),t.kind===`kick`&&n){if(this.pass=null,t.tick!==e.tick)continue;let r=e.goals.find(t=>t.defendingTeam!==n.team&&dt(e,t.id,this.policy.shotHorizonMs/1e3)),i=Math.hypot(e.ball.vx,e.ball.vy)/e.ball.radius;r&&i>=this.policy.shotMinSpeedRadii?(this.shot={player:at(n),goalId:r.id,tick:e.tick,threatTick:e.tick},this.team(n.team).directedShots++,this.emit(l,e,`directed-shot`,n.team,[`verified-kick`,`trajectory-crosses-goal-mouth`,`finite-flight-horizon`],{player:n,goalId:r.id,shotQuality:pt(e,r.id,n.team)})):(this.shot=null,ft(e,n,this.policy.passWindowMs,this.policy.passMinTravelRadii)&&(this.pass={player:at(n),tick:e.tick,x:e.ball.x,y:e.ball.y,radius:e.ball.radius}))}}this.shot&&(dt(e,this.shot.goalId,this.policy.shotHorizonMs/1e3)?this.shot.threatTick=e.tick:this.shot=null);let u=this.controller,d=i.some(e=>e.kind===`kick`),f=e.players.filter(t=>Math.hypot(t.x-e.ball.x,t.y-e.ball.y)<=t.radius+e.ball.radius*(1+this.policy.controlExtraRadii)),p=f.length===1&&!d&&Math.hypot(f[0].vx-e.ball.vx,f[0].vy-e.ball.vy)<=e.ball.radius*this.policy.controlRelativeSpeedRadii?f[0]:void 0;return p?((!this.candidate||it(this.candidate.player)!==it(p.identity))&&(this.candidate={player:at(p.identity),began:e.tick}),this.ms(e.tick-this.candidate.began)>=this.policy.controlHoldMs?(this.controller=this.candidate.player,(!u||it(u)!==it(this.controller))&&this.establish(e,l)):this.controller=null):(this.controller=this.candidate=null,f.length>1&&this.unknown.push(`contested-control`)),c&&u&&!this.controller&&this.endReleasedControl(e,u,i,l),n>0&&n<=this.policy.maxGapMs&&(this.observedMs=Yl(this.observedMs,n),this.controller&&u&&it(this.controller)===it(u)?this.team(this.controller.team).controlledMs=Yl(this.team(this.controller.team).controlledMs,n):this.uncontrolledMs=Yl(this.uncontrolledMs,n)),this.controller?(this.lastController={player:this.controller,tick:e.tick},this.advanceAttack(e,l)):this.attack&&(this.attack.pressureSince=null),this.summarize(e,l),this.status=this.unknown.length?`unknown`:`tracking`,this.finish(l)}endReleasedControl(e,t,n,r){let i=it(t);if(!n.some(t=>t.kind===`kick`&&t.tick===e.tick&&t.player&&it(t.player)===i))return;let a=e.players.find(e=>it(e.identity)===i);if(!a||!this.attack||this.attack.team!==t.team)return;let o=Math.hypot(a.x-e.ball.x,a.y-e.ball.y)/e.ball.radius,s=a.radius/e.ball.radius+1+this.policy.controlExtraRadii,c=Math.hypot(a.vx-e.ball.vx,a.vy-e.ball.vy)/e.ball.radius;o<=s&&c<=this.policy.controlRelativeSpeedRadii||this.emit(r,e,`control-ended`,t.team,[`previous-observed-control`,`verified-controller-kick`,`measured-control-separation`],{player:t,metrics:{distanceBallRadii:o,controlReachBallRadii:s,relativeSpeedBallRadiiPerSecond:c,controlRelativeSpeedRadii:this.policy.controlRelativeSpeedRadii}})}defend(e,t,n){let r=this.shot;if(!r)return;this.shot=null;let i=e.goals.find(e=>e.id===r.goalId),a=i&&tt(i,e.ball);if(!a||a.across<=e.ball.radius||this.ms(e.tick-r.threatTick)>this.policy.maxGapMs||dt(e,r.goalId,this.policy.shotHorizonMs/1e3))return;let o=e.players.find(e=>it(e.identity)===it(t))?.role===`goalkeeper`&&a.across/a.length<=this.policy.saveAreaGoalWidths,s=o?`goalkeeper-save`:`block`;this.team(t.team)[o?`saves`:`blocks`]++,this.emit(n,e,s,t.team,[`prior-directed-shot`,`recent-goal-bound-trajectory`,`verified-opponent-ball-contact`,`trajectory-no-longer-goal-bound`,...o?[`explicit-goalkeeper-role`,`inside-configured-save-area`]:[]],{player:t,otherPlayer:r.player,goalId:r.goalId,metrics:{shotAgeMs:this.ms(e.tick-r.tick)}})}establish(e,t){let n=this.controller,r=this.candidate;if(!n||!r)return;let i=this.lastController,a=!!i&&i.player.team!==n.team&&this.ms(e.tick-i.tick)<=this.policy.passWindowMs;if(this.emit(t,e,`control-established`,n.team,[`unique-nearby-player`,`matched-relative-velocity`,`sustained-control-window`],{player:n,metrics:{heldMs:this.ms(e.tick-r.began)}}),a&&i&&(this.team(n.team).turnoversWon++,this.emit(t,e,`turnover`,n.team,[`previous-observed-opponent-control`,`new-sustained-control`],{player:n,otherPlayer:i.player}),this.chain={team:null,completed:0,tick:-1}),this.pass&&it(this.pass.player)!==it(n)){let r=this.pass,i=Math.hypot(e.ball.x-r.x,e.ball.y-r.y)/r.radius;r.player.team===n.team&&i>=this.policy.passMinTravelRadii?(this.team(n.team).completedPasses++,this.lastPass={from:r.player,to:at(n),tick:e.tick},this.chain={team:n.team,completed:Math.min(32,this.chain.team===n.team?this.chain.completed+1:1),tick:e.tick},this.emit(t,e,`pass-completed`,n.team,[`verified-kick`,`distinct-teammate-sustained-control`,`uninterrupted-contact-coverage`,`minimum-ball-travel`],{player:r.player,otherPlayer:n,metrics:{travelBallRadii:i,flightMs:this.ms(e.tick-r.tick),chainLength:this.chain.completed}}),this.chain.completed>=3&&this.emit(t,e,`pass-chain`,n.team,[`consecutive-confirmed-passes`],{player:n,metrics:{completed:this.chain.completed}})):r.player.team!==n.team&&(this.team(r.player.team).failedPasses++,this.emit(t,e,`pass-failed`,r.player.team,[`verified-kick`,`opponent-sustained-control-before-reception`],{player:r.player,otherPlayer:n})),this.pass=null}else this.pass&&this.ms(e.tick-this.pass.tick)>this.policy.controlHoldMs&&(this.pass=null);if(!this.attack||this.attack.team!==n.team){let t=ut(e,n.team);t&&(this.attack={id:`${e.streamId}:attack:${e.epoch}:${e.tick}:${n.team}`,team:n.team,goalId:t.goal.id,began:e.tick,startDistance:t.projection.across/t.projection.length,lastProgress:0,turnover:a,counterCalled:!1,pressureSince:null,pressureCalled:!1})}}advanceAttack(e,t){let n=this.attack,r=this.controller;if(!n||!r||n.team!==r.team)return;let i=e.goals.find(e=>e.id===n.goalId),a=i&&tt(i,e.ball);if(!a||a.across<=e.ball.radius)return;let o=a.across/a.length,s=n.startDistance-o,c=this.ms(e.tick-n.began);s-n.lastProgress>=this.policy.progressGoalWidths&&(n.lastProgress=s,this.emit(t,e,`attack-progress`,n.team,[`same-team-controlled-attack`,`measured-goalward-progression`],{player:r,goalId:n.goalId,metrics:{progressGoalWidths:s,elapsedMs:c}}),n.turnover&&!n.counterCalled&&n.startDistance>=2&&c<=this.policy.counterWindowMs&&(n.counterCalled=!0,this.emit(t,e,`counterattack`,n.team,[`observed-control-turnover`,`started-away-from-opponent-goal`,`rapid-goalward-controlled-progression`],{player:r,goalId:n.goalId,metrics:{progressGoalWidths:s,elapsedMs:c}})));let l=a.along>=-a.length/2&&a.along<=a.length*1.5;if(o<=this.policy.pressureAreaGoalWidths&&l){n.pressureSince===null&&(n.pressureSince=e.tick);let i=this.ms(e.tick-n.pressureSince);!n.pressureCalled&&i>=this.policy.pressureHoldMs&&(n.pressureCalled=!0,this.emit(t,e,`sustained-pressure`,n.team,[`sustained-observed-control-near-opponent-goal`,`goal-relative-area`],{player:r,goalId:n.goalId,metrics:{durationMs:i,distanceGoalWidths:o}}))}else n.pressureSince=null}summarize(e,t){if(this.summarySince<0){this.beginSummary(e.tick);return}if(this.ms(e.tick-this.summarySince)<this.policy.summaryWindowMs)return;let n=this.observedMs-this.summaryBase.observed,r=this.red.controlledMs-this.summaryBase.red,i=this.blue.controlledMs-this.summaryBase.blue,a=n>0?(r+i)/n:0;if(n>=this.policy.summaryWindowMs*.8&&a>=.5){let o=r>=i?1:2;this.emit(t,e,`tactical-summary`,o,[`bounded-observation-window`,`observed-control-coverage-at-least-half`],{metrics:{windowMs:n,controlCoverage:a,redControlledMs:r,blueControlledMs:i,redCompletedPasses:this.red.completedPasses-this.summaryBase.redPasses,blueCompletedPasses:this.blue.completedPasses-this.summaryBase.bluePasses}})}this.beginSummary(e.tick)}beginSummary(e){this.summarySince=e,this.summaryBase={red:this.red.controlledMs,blue:this.blue.controlledMs,observed:this.observedMs,redPasses:this.red.completedPasses,bluePasses:this.blue.completedPasses}}confirm(e){if(!this.policy.enabled||!e||!et(e.context)||e.streamId!==this.streamId||e.epoch!==this.epoch||!Number.isSafeInteger(e.sequence)||e.sequence<=this.confirmedSequence||!Number.isSafeInteger(e.tick)||e.tick<this.tick||e.kind===`goal`&&e.tick!==this.tick)return[];this.confirmedSequence=e.sequence;let t=[];if(e.kind===`goal`){let n=this.lastPass,r=e.goal?.scorer;e.tick===this.tick&&this.completeAtTick&&e.context.phase!==`lobby`&&e.goal&&!e.goal.ownGoal&&r&&n&&it(n.to)===it(r)&&r.team===e.goal.team&&n.from.team===e.goal.team&&this.ms(e.tick-n.tick)<=this.policy.assistWindowMs&&(this.team(r.team).confirmedAssists++,this.emit(t,e,`assist-confirmed`,r.team,[`authoritative-goal`,`confirmed-last-completed-pass-to-scorer`,`no-intervening-other-player-contact`,`assist-window`],{player:n.from,otherPlayer:r,confidence:`authoritative`,metrics:{sincePassMs:this.ms(e.tick-n.tick)}})),this.clearContinuity()}else if(e.kind===`kickoff`){let{streamId:t,epoch:n,tick:r}=e;this.reset(),this.streamId=t,this.epoch=n,this.tick=r,this.confirmedSequence=e.sequence}else(e.kind===`pause`||e.kind===`stop`||e.kind===`end`||e.kind===`restart`)&&this.clearContinuity();return this.finish(t)}snapshot(){return Object.freeze({streamId:this.streamId,epoch:this.epoch<0?null:this.epoch,tick:this.tick<0?null:this.tick,status:this.status,unknownReasons:Object.freeze([...new Set(this.unknown)].slice(0,8)),controller:this.controller?at(this.controller):null,passChain:Object.freeze({team:this.chain.team,completed:this.chain.completed}),attack:this.attack?Object.freeze({id:this.attack.id,team:this.attack.team,goalId:this.attack.goalId}):null,observedMs:this.observedMs,uncontrolledMs:this.uncontrolledMs,teams:Object.freeze({red:Object.freeze({...this.red}),blue:Object.freeze({...this.blue})}),emittedEvents:this.emitted,droppedEvents:this.dropped})}};function nu(e,t){for(let n=0;n<t.length;n+=8){let r=t.slice(n,n+8);e.broadcast({type:`match-intelligence`,version:1,streamId:r[0].streamId,sentAtMs:performance.now(),events:r})}}var ru=(e,t)=>e.sessionId===t.sessionId&&e.playerId===t.playerId&&e.team===t.team,iu=class{intelligence;roles=[];sampled;discontinuous=!1;constructor(e={}){this.intelligence=new tu(e,ti)}configure(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid match intelligence policy`);let t=this.intelligence.getPolicy(),n=ql(e,t);Object.keys(t).every(e=>n[e]===t[e])||this.intelligence.configure(n)}getPolicy(){return structuredClone(this.intelligence.getPolicy())}getSnapshot(){return structuredClone(this.intelligence.snapshot())}reset(){this.intelligence.reset(),this.sampled=void 0,this.discontinuous=!1}invalidate(){this.breakContinuity(`scripted-motion-or-geometry`)}breakContinuity(e){this.intelligence.invalidate(e),this.discontinuous=!0}setRoles(e,t){if(!Array.isArray(e)||e.length>32)throw Error(`At most 32 match intelligence role assignments`);let n=new Set,r=e.map(e=>{if(!e||!Number.isSafeInteger(e.playerId)||e.playerId<0||n.has(e.playerId)||![`goalkeeper`,`outfield`].includes(e.role))throw Error(`Invalid match intelligence role assignment`);let r=t(e.playerId);if(!r||r.playerId!==e.playerId||r.team!==1&&r.team!==2)throw Error(`Match intelligence role requires a current field player`);return n.add(e.playerId),{player:{...r},role:e.role}}),i=r.length!==this.roles.length||r.some(e=>!this.roles.some(t=>ru(t.player,e.player)&&t.role===e.role));this.roles=r,i&&this.sampled&&this.breakContinuity(`role-change`)}getRoles(){return structuredClone(this.roles)}removePlayer(e,t=!0){this.roles=this.roles.filter(t=>t.player.playerId!==e),t&&this.sampled&&this.breakContinuity(`roster-change`)}confirm(e){return e.flatMap(e=>this.intelligence.confirm(e))}observePlayers(e,t,n,r,i,a){if(!this.intelligence.getPolicy().enabled)return[];let o=Array(32);for(let e of r)Number.isInteger(e.slot)&&e.slot>=0&&e.slot<32&&(o[e.slot]??=e);return this.observe(e,t,n,e=>{let t=o[e];return t?i(t):null},a)}observe(e,t,n,r,i){if(!this.intelligence.getPolicy().enabled)return[];let a=e.data,o=[],s=this.sampled?.streamId===n&&this.sampled.epoch===t&&this.sampled.tick===e.tick,c=!s&&e.ballContacts.length?new Map:void 0;for(let t=0;t<32;t++){let n=r(t);if(!n)continue;let i=e.index(t),s=i*18,l=this.roles.find(e=>ru(e.player,n))?.role;c?.set(i,n),o.push({identity:{...n},x:a[s],y:a[s+V.Y],vx:a[s+V.SPEED_X]*ti,vy:a[s+V.SPEED_Y]*ti,radius:a[s+V.RADIUS],...l?{role:l}:{}})}this.roles.some(e=>!o.some(({identity:t})=>ru(e.player,t)))&&(this.roles=this.roles.filter(e=>o.some(({identity:t})=>ru(e.player,t))));let l=!this.sampled||s||this.sampled.streamId===n&&this.sampled.epoch===t&&e.tick===this.sampled.tick+1;this.sampled={streamId:n,epoch:t,tick:e.tick};let u=[];if(!s)for(let[r,o]of e.ballContacts.entries()){let s=c?.get(o.disc),l={id:`${n}:${t}:${e.tick}:contact:${r}`,tick:e.tick};if(o.kind===`kick`)s?u.push({...l,kind:`kick`,player:{...s}}):u.push({...l,kind:`wall`});else if(s)u.push({...l,kind:`player`,player:{...s}});else{let e=o.disc*18,t=o.kind===`disc`&&o.disc>0&&a[e+V.INVERSE_MASS]===0?i.find(t=>[t.p0,t.p1].some(t=>Math.hypot(a[e]-t[0],a[e+V.Y]-t[1])<=a[e+V.RADIUS])):void 0;u.push(t?{...l,kind:`post`,goalId:t.id}:{...l,kind:`wall`})}}let d=!this.discontinuous&&l&&(s||e.ballContactsComplete);return s||(this.discontinuous=!1),this.intelligence.observe({streamId:n,epoch:t,tick:e.tick,context:{phase:e.phase,paused:e.paused||e.resumeTicks>0,elapsed:e.elapsed/ti,timeLimit:e.timeLimit,scoreLimit:e.scoreLimit,score:{red:e.red,blue:e.blue}},ball:{x:a[0],y:a[1],vx:a[2]*ti,vy:a[3]*ti,radius:a[V.RADIUS]},goals:i,players:o,contacts:u,contactsComplete:d})}},au=class{sequence=0;capture(e,t,n,r){return Object.freeze({eventId:`${n.sessionId}:retirement:${t}:${e.tick}:${++this.sequence}`,streamId:n.sessionId,epoch:t,tick:e.tick,kind:`player-retired`,team:n.team,player:Object.freeze({...n}),confidence:`authoritative`,context:Object.freeze({phase:e.phase,paused:e.paused||e.resumeTicks>0,elapsed:e.elapsed/ti,timeLimit:e.timeLimit,scoreLimit:e.scoreLimit,score:Object.freeze({red:e.red,blue:e.blue})}),evidence:Object.freeze([`authoritative-roster-change`,r]),metrics:Object.freeze({})})}},ou={message:{burst:240,perSecond:160},action:{burst:12,perSecond:6},chat:{burst:4,perSecond:1},typing:{burst:6,perSecond:3},feedback:{burst:1,perSecond:.5}},su=class{peers=new Map;allow(e,t,n=performance.now()){let r=this.peers.get(e);r||(r={},this.peers.set(e,r));let{burst:i,perSecond:a}=ou[t],o=r[t]??{tokens:i,at:n};return o.tokens=Math.min(i,o.tokens+Math.max(0,n-o.at)*a/1e3),o.at=Math.max(o.at,n),r[t]=o,o.tokens<1?!1:(o.tokens--,!0)}delete(e){this.peers.delete(e)}clear(){this.peers.clear()}},cu=32768,lu=62258,uu=4,du=32,fu=(e,t)=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=t,pu=e=>Math.max(-32768,Math.min(32767,Math.round(e*uu)));function mu(e){return fu(e.halfWidthQ,65535)&&fu(e.halfHeightQ,65535)&&e.halfWidthQ!==0&&e.halfHeightQ!==0&&fu(e.grassWidthQ,e.halfWidthQ)&&fu(e.grassHeightQ,e.halfHeightQ)&&fu(e.cornerQ,Math.min(e.grassWidthQ,e.grassHeightQ))}function hu(e){let{bg:t}=e,n={halfWidthQ:Math.round((Math.max(e.width,t.width)+du)*uu),halfHeightQ:Math.round((Math.max(e.height,t.height)+du)*uu),grassWidthQ:Math.round(t.width*uu),grassHeightQ:Math.round(t.height*uu),cornerQ:Math.round(Math.min(t.cornerRadius??0,t.width,t.height)*uu)};if(!mu(n))throw Error(`Invalid turf field`);return n}var gu=(e,t)=>e.halfWidthQ===t.halfWidthQ&&e.halfHeightQ===t.halfHeightQ&&e.grassWidthQ===t.grassWidthQ&&e.grassHeightQ===t.grassHeightQ&&e.cornerQ===t.cornerQ,_u=e=>[e.halfWidthQ/uu,e.halfHeightQ/uu];function vu(e,t,{grassWidthQ:n,grassHeightQ:r,cornerQ:i}){let a=Math.abs(e),o=Math.abs(t);return a>n||o>r?!1:!(i>0&&a>n-i&&o>r-i&&(a-n+i)**2+(o-r+i)**2>i**2)}function yu(e,[t,n,r,i],a,o,s){let{halfWidthQ:c,halfHeightQ:l}=s,u=Math.max(0,Math.floor((Math.min(t,r)-a+c)*256/(2*c))),d=Math.min(255,Math.ceil((Math.max(t,r)+a+c)*256/(2*c))),f=Math.max(0,Math.floor((Math.min(n,i)-a+l)*128/(2*l))),p=Math.min(127,Math.ceil((Math.max(n,i)+a+l)*128/(2*l)));if(d<u||p<f)return!1;let m=r-t,h=i-n,g=m*m+h*h;if(!g)return!1;let _=Math.sqrt(g),v=a*a,y=!1;for(let r=f;r<=p;r++){let i=(2*r+1-128)*l/128;for(let a=u;a<=d;a++){let l=(2*a+1-256)*c/256;if(!vu(l,i,s))continue;let u=Math.max(0,Math.min(1,((l-t)*m+(i-n)*h)/g)),d=l-t-m*u,f=i-n-h*u,p=d*d+f*f;if(p>=v)continue;let b=r*256+a,x=Math.round(_*o*(1-p/v)*(1-e[b]/65535)/32);if(!x)continue;let S=Math.min(lu,e[b]+x);S!==e[b]&&(e[b]=S,y=!0)}}return y}var bu=cu*3,xu=102400,Su=1,Cu=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,wu=(e,t)=>Math.imul(e^t,16777619);function Tu(e){let t=2166136261;for(let n of e)t=wu(t,n);return t>>>0}function Eu(e){let t=2166136261;for(let n of e)t=wu(wu(t,n&255),n>>>8);return t>>>0}function Du(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return btoa(t)}function Ou(e,t,n){if(typeof e!=`string`||e.length>Math.ceil(t/3)*4||!Cu.test(e))throw Error(n);return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function ku(e){let t=Ou(e,cu*2,`Invalid turf payload`);if(t.length!==65536)throw Error(`Invalid turf atlas length`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new Uint16Array(cu);for(let e=0;e<cu;e++)if(r[e]=n.getUint16(e*2,!0),r[e]>62258)throw Error(`Invalid turf wear`);return r}function Au(e){let t=Ou(e,xu,`Invalid turf surface payload`);if(!t.length||t.length>xu)throw Error(`Invalid turf surface length`);let n=new Uint8Array(bu),r=0,i=!1,a=new ba((e,t)=>{if(r+e.length>bu)throw Error(`Expanded turf surface exceeds size limit`);n.set(e,r),r+=e.length,i=t});for(let e=0;e<t.length;e+=256)a.push(t.subarray(e,e+256),e+256>=t.length);if(!i||r!==bu)throw Error(`Invalid turf surface length`);return n}function ju(e){let t=new Uint8Array(cu*2),n=new DataView(t.buffer);for(let t=0;t<cu;t++)n.setUint16(t*2,e.atlas[t],!0);let r={type:`turf-checkpoint`,version:Su,generation:e.generation,...e.field,digest:e.digest,atlas:Du(t)};if(e.surfaceRgb){let t=ya(e.surfaceRgb,{level:1});if(t.length>xu)throw Error(`Compressed turf surface exceeds size limit`);r.surface=Du(t),r.surfaceDigest=Tu(e.surfaceRgb)}return r}function Mu(e){if(!e||typeof e!=`object`)throw Error(`Invalid turf checkpoint`);let t=e,n={halfWidthQ:t.halfWidthQ,halfHeightQ:t.halfHeightQ,grassWidthQ:t.grassWidthQ,grassHeightQ:t.grassHeightQ,cornerQ:t.cornerQ};if(t.type!==`turf-checkpoint`||t.version!==Su||!fu(t.generation,4294967295)||!mu(n)||!fu(t.digest,4294967295))throw Error(`Invalid turf checkpoint`);let r=ku(t.atlas);if(Eu(r)!==t.digest)throw Error(`Turf checksum mismatch`);if(t.surface===void 0!=(t.surfaceDigest===void 0))throw Error(`Invalid turf surface envelope`);let i;if(t.surface!==void 0){if(!fu(t.surfaceDigest,4294967295))throw Error(`Invalid turf surface checksum`);if(i=Au(t.surface),Tu(i)!==t.surfaceDigest)throw Error(`Turf surface checksum mismatch`)}return{field:n,generation:t.generation,digest:t.digest,atlas:r,surfaceRgb:i}}var Nu=6,Pu=33,Fu=31,Iu=255,Lu={halfWidthQ:0,halfHeightQ:0,grassWidthQ:0,grassHeightQ:0,cornerQ:0},Ru=e=>Math.min(lu,Math.round(e*65535/255)),zu=class{atlas=new Uint16Array(cu);image=new Uint8Array(cu);surfaceRgb;surfaceImage=new Uint8Array(cu*4);surfaceDirty=!0;imageDirty=!0;digestDirty=!0;digestValue=0;previous=new Map;stadium;lastTick=-1;lastElapsed=-1;lastPhase=`lobby`;bounds=Lu;generation=0;revision=0;field=[0,0];get digest(){return this.digestDirty&&=(this.digestValue=Eu(this.atlas),!1),this.digestValue}get hasPressure(){let e=this.surfaceRgb;if(!e)return!1;for(let t=0;t<bu;t+=3)if(e[t]!==0)return!0;return!1}pixels(){if(this.imageDirty){for(let e=0;e<cu;e++)this.image[e]=Math.round(this.atlas[e]*255/65535);this.imageDirty=!1}return this.image}surfacePixels(){if(this.surfaceDirty||this.imageDirty){let e=this.pixels(),t=this.surfaceRgb;for(let n=0;n<cu;n++){let r=n*4,i=n*3;this.surfaceImage[r]=t?t[i]:0,this.surfaceImage[r+1]=t?t[i+1]:128,this.surfaceImage[r+2]=t?t[i+2]:128,this.surfaceImage[r+3]=e[n]}this.surfaceDirty=!1}return this.surfaceImage}changed(){this.imageDirty=!0,this.surfaceDirty=!0,this.digestDirty=!0,this.revision++}reset(e){this.atlas.fill(0),this.surfaceRgb=void 0,this.previous.clear(),this.generation=this.generation+1>>>0,this.bounds=e,this.field=_u(e),this.changed()}startsOver(e,t){return this.stadium!==e.stadium||this.lastTick>e.tick||this.lastElapsed>0&&e.elapsed<this.lastElapsed||e.phase===`lobby`&&this.lastPhase!==`lobby`||!gu(this.bounds,t)}capture(e){let t=e.stadium,n=hu(t);if(this.startsOver(e,n)&&this.reset(n),this.stadium=t,this.lastTick=e.tick,this.lastElapsed=e.elapsed,this.lastPhase=e.phase,e.phase!==`playing`||e.paused||e.resumeTicks||t.bg.type!==`grass`){this.previous.clear();return}e.tick%Nu===0&&this.sampleBodies(e.data)}sampleBodies(e){let t=new Set,n=0;for(let r=0;r<e.length/18;r++){let i=r*18;if(r!==0&&(!e[i+V.PLAYER_SLOT]||e[i+V.TEAM]===0))continue;let a=e[i+V.X],o=e[i+V.Y],s=e[i+V.RADIUS];if(!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(s))continue;t.add(r);let c=this.previous.get(r);if(c&&n<Pu){let e=Math.hypot(a-c[0],o-c[1]);if(e>.1&&e<60){n++;let e=[pu(c[0]),pu(c[1]),pu(a),pu(o)],t=Math.max(1,Math.min(96,Math.round(Math.max(3.5,s*.78)*4))),i=r===0?Fu:Iu;yu(this.atlas,e,t,i,this.bounds)&&this.changed()}}this.previous.set(r,[a,o])}for(let e of this.previous.keys())t.has(e)||this.previous.delete(e)}seed(e){if(!(e instanceof Uint8Array)||e.length!==32768)throw Error(`Invalid turf seed`);for(let t=0;t<cu;t++)this.atlas[t]=Ru(e[t]);this.surfaceRgb=void 0,this.changed()}seedSurface(e){if(!(e instanceof Uint8Array)||e.length!==131072)throw Error(`Invalid turf surface seed`);let t=new Uint8Array(bu);for(let n=0;n<cu;n++){let r=n*4,i=n*3;t[i]=e[r],t[i+1]=e[r+1],t[i+2]=e[r+2],this.atlas[n]=Ru(e[r+3])}this.surfaceRgb=t,this.changed()}checkpoint(){if(!this.bounds.halfWidthQ||!this.bounds.halfHeightQ)throw Error(`Turf field is not initialized`);return ju({field:this.bounds,generation:this.generation,digest:this.digest,atlas:this.atlas,surfaceRgb:this.surfaceRgb})}restore(e){let t=Mu(e);this.generation>t.generation&&this.generation-t.generation<2147483648||(this.atlas=t.atlas,this.surfaceRgb=t.surfaceRgb,this.generation=t.generation,this.bounds=t.field,this.field=_u(t.field),this.previous.clear(),this.changed(),this.digestValue=t.digest,this.digestDirty=!1)}},Bu=class{players=[];nextId=0;get all(){return this.players}get size(){return this.players.length}byId(e){return this.players.find(t=>t.id===e)}byPeer(e){return this.players.find(t=>t.peerId===e)}bySlot(e){return this.players.find(t=>t.slot===e)}has(e){return this.players.includes(e)}fielded(){return this.players.filter(e=>e.team!==0)}freeSlot(){return Array.from({length:32},(e,t)=>t).find(e=>!this.players.some(t=>t.slot===e))}add(e){let t={...e,id:this.nextId++};return this.players.push(t),t}assignTeam(e,t){return tc(this.players,e,t)}removePeer(e){this.players=this.players.filter(t=>t.peerId!==e)}reorder(e){return!e.every((e,t)=>e===this.players[t])&&(this.players=e,!0)}clear(){this.players=[]}roster(){return this.players.map(e=>({avatar:e.avatarOverride??e.avatar??null,id:e.peerId,slot:e.slot,name:e.name,team:e.team,admin:e.admin,muted:!!e.muted}))}},Vu=Object.freeze([]),Hu=class{engine;runtime;hooks;xg;players=new Bu;match;inputs;traffic=new su;soundStream=new gl;factStream=new yl;commentary=new Wl;commentaryAnalysis=new di;intelligence=new iu;kickEstimates=Vu;intelligenceEvents=[];playerRetirements=new au;turfState=new zu;bans=new Map;network;roomId=``;roomName=``;roomLink=``;epoch=0;locked=!1;teamStyles=[null,null];closed=!1;stadiumSelection=0;constructor(e,t,n,r,i=new Oi){this.engine=e,this.runtime=t,this.hooks=n,this.xg=i,this.match=new dl(e,r),this.inputs=new Ic(this.match),this.xg.resetForStadium(e)}report(e){try{let t=this.hooks.onError?.(e);t instanceof Promise&&t.catch(()=>{})}catch{}}invoke(e,t,...n){if(!(this.closed&&e!==`onRecordingComplete`))try{let r=t?.apply(this.hooks,n);return r instanceof Promise&&r.catch(t=>this.report(`${e}: ${String(t)}`)),r}catch(t){this.report(`${e}: ${String(t)}`);return}}assertOpen(){if(this.closed)throw Error(`Room is closed`)}stopped(){return this.engine.phase===`lobby`||this.engine.phase===`finished`}isHost(e){return e.peerId===this.network.hostId}command(e,t=0,n=0){this.assertOpen();let r=this.engine.kickRate;if(this.match.command(e,t,n),e===`kickRate`&&this.engine.kickRate!==r&&this.xg.invalidate(`domain-change`),[`start`,`stop`,`pause`,`team`,`join`].includes(e)&&this.baselineXg(),(e===`start`||e===`stop`)&&this.turfState.capture(this.engine),e===`start`||e===`stop`||e===`pause`){let t=this.captureCommentary(e===`stop`?`stop`:void 0);return this.captureIntelligence(t),t}return[]}captureCommentary(e){let t=this.factStream.capture(this.engine,this.epoch,e=>{let t=this.players.bySlot(e);return t&&t.team!==0?{sessionId:this.factStream.streamId,playerId:t.id,team:t.team,name:t.name}:null},e);return t.length&&(this.broadcastState(),bl(this.network,t)),t}notifyCommentary(e){let t=this.intelligenceEvents,n=this.kickEstimates;this.intelligenceEvents=[],this.kickEstimates=Vu;for(let t of e)this.invoke(`onMatchFact`,this.hooks.onMatchFact,structuredClone(t));for(let e of n)this.invoke(`onMatchKickEstimate`,this.hooks.onMatchKickEstimate,structuredClone(e));for(let e of t)this.invoke(`onMatchIntelligenceEvent`,this.hooks.onMatchIntelligenceEvent,structuredClone(e))}publishPlayerRetirement(e,t,n){if(t!==1&&t!==2)return;let r=this.playerRetirements.capture(this.engine,this.epoch,{sessionId:this.factStream.streamId,playerId:e.id,team:t,name:e.name},n);nu(this.network,[r]),this.invoke(`onMatchIntelligenceEvent`,this.hooks.onMatchIntelligenceEvent,structuredClone(r))}xgContext(){return{streamId:this.factStream.streamId,epoch:this.epoch,goals:this.commentaryAnalysis.getAnalysisGeometry(this.engine),resolve:e=>{let t=this.players.bySlot(e);return t&&t.team!==0?{sessionId:this.factStream.streamId,playerId:t.id,team:t.team}:null}}}baselineXg(){this.xg.baseline(this.engine,this.xgContext())}captureXg(){this.kickEstimates=this.xg.active?this.xg.capture(this.engine,this.xgContext()):Vu}captureIntelligence(e){let t=[...this.intelligence.observePlayers(this.engine,this.epoch,this.factStream.streamId,this.players.all,e=>e.team===0?null:{sessionId:this.factStream.streamId,playerId:e.id,team:e.team,name:e.name},this.commentaryAnalysis.getAnalysisGeometry(this.engine)),...this.intelligence.confirm(e)];nu(this.network,t),this.intelligenceEvents=t}captureAnalysis(){let e=this.commentaryAnalysis.observe(this.engine,this.epoch,this.factStream.streamId,e=>{let t=this.players.bySlot(e);return t&&t.team!==0?{sessionId:this.factStream.streamId,playerId:t.id,team:t.team,name:t.name}:null});return fi(this.network,e),e}syncLobby(){this.network.broadcast({type:`lobby`,players:this.players.roster(),teamStyles:this.teamStyles,locked:this.locked,scoreLimit:this.engine.scoreLimit,timeLimit:this.engine.timeLimit})}broadcastState(){this.network.broadcast({type:`state`,epoch:this.epoch,state:this.engine.snapshot()})}publicPlayer(e){let t=this.engine.index(e.slot)*18,n=!this.closed&&this.engine.phase!==`lobby`&&this.engine.data[t+V.TEAM]>0,{slot:r,avatarOverride:i,...a}=e;return{...a,muted:!!e.muted,avatar:e.avatarOverride??e.avatar??null,position:n?{x:this.engine.data[t],y:this.engine.data[t+V.Y]}:null,input:this.engine.data[t+V.INPUT]}}publicOrNull(e){return e?this.publicPlayer(e):null}};function Uu(e){return/^(?:[0-9a-f]{10}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.test(e)?e.toLowerCase():null}function Wu(e){let t=Uu(e);if(!t)throw Error(`Invalid room code`);return`/r/${t}`}async function Gu(e,t,n){let r=e.getReader(),i=()=>{r.cancel().catch(()=>{})};n?.addEventListener(`abort`,i,{once:!0});let a=[],o=0;try{for(;;){if(n?.aborted)return{ok:!1,reason:`aborted`};let e=await r.read();if(e.done)break;if(o+=e.value.byteLength,o>t)return{ok:!1,reason:`too-large`};a.push(e.value)}}catch(e){if(n?.aborted)return{ok:!1,reason:`aborted`};throw e}finally{n?.removeEventListener(`abort`,i),i();try{r.releaseLock()}catch{}}if(n?.aborted)return{ok:!1,reason:`aborted`};let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.byteLength;return{ok:!0,bytes:s}}var Ku=2048,qu=class extends Error{status;retryAfterSeconds;constructor(e,t,n=null){super(e),this.status=t,this.retryAfterSeconds=n,this.name=`RoomAdmissionError`}};async function Ju(e,t){let n=`Room creation failed (${e.status})`,r=e.status===429?e.headers.get(`Retry-After`):null,i=r&&/^\d+$/.test(r)&&Number.isSafeInteger(Number(r))?Number(r):null,a=t=>new qu(t,e.status,i),o=e.body;if(!o)return a(n);try{if(t.throwIfAborted(),e.status<400||e.status>=500||e.headers.get(`content-type`)?.split(`;`)[0].trim()!==`application/json`)return a(n);let r=await Gu(o,Ku,t);if(!r.ok)return t.throwIfAborted(),a(n);let i=We(Xe,JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(r.bytes)));return i.success?a(`${i.output.error.trim()} (${e.status})`):a(n)}catch{return t.throwIfAborted(),a(n)}finally{o.cancel().catch(()=>{})}}function Yu(e){if(e===void 0)return;if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Geolocation must contain a country code, latitude and longitude.`);let{code:t,lat:n,lon:r}=e;if(typeof t!=`string`||!/^[a-z]{2}$/i.test(t)||typeof n!=`number`||!Number.isFinite(n)||n<-90||n>90||typeof r!=`number`||!Number.isFinite(r)||r<-180||r>180)throw TypeError(`Geolocation must contain a country code, latitude and longitude.`);return{code:t.toUpperCase(),lat:n===0?0:n,lon:r===0?0:r}}var Xu=(e,t)=>Ue(Le(t),fe(t=>!!t.trim()&&t.length<=e,t)),Zu=e=>Pe(Oe(`Invalid ${e} setting: expected a boolean`)),Qu=`maxPlayers must be an integer between 2 and 32`,$u=Ue(Ne({roomName:Xu(64,`Room name must contain 1–64 characters`),public:Zu(`public`),noPlayer:Zu(`noPlayer`),maxPlayers:Pe(Ue(Me(Qu),he(Qu),ye(2,Qu),_e(32,Qu))),password:Pe(Ue(Le(`Password must be a string of at most 64 characters`),ge(64,`Password must be a string of at most 64 characters`))),stadium:Pe(Le(`Stadium must be a Ball2D stadium source string`)),playerName:Pe(Ve()),geo:Pe(Ve())}),fe(e=>e.noPlayer!==!1||e.playerName===void 0||Ee(Xu(24,``),e.playerName),`Invalid host player name`)),ed=new Set(Object.keys($u.pipe[0].entries));function td(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Room configuration must be an object`);for(let t of Object.keys(e)){if(t===`token`)throw Error(`External service tokens are not supported. Ball2D join verification is configured on the room.`);if(!ed.has(t))throw Error(`Unknown room setting: ${t}`)}let t=We($u,e,{abortEarly:!0});if(!t.success)throw Error(t.issues[0].message);let n=t.output;return{roomName:n.roomName,maxPlayers:n.maxPlayers??16,password:n.password??``,public:n.public??!0,noPlayer:n.noPlayer??!0,playerName:n.noPlayer===!1?(n.playerName??`Host`).trim():void 0,stadium:n.stadium,...n.geo===void 0?{}:{geo:Yu(n.geo)}}}function nd(e){let t=new AbortController,n=()=>t.abort(e?.reason);e?.aborted?n():e?.addEventListener(`abort`,n,{once:!0});let r=setTimeout(()=>t.abort(new DOMException(`Room startup timed out`,`TimeoutError`)),15e3);return{signal:t.signal,async run(e){let n,r=new Promise((e,t)=>{n=t}),i=()=>n(t.signal.reason);t.signal.addEventListener(`abort`,i,{once:!0}),t.signal.aborted&&i();try{return await Promise.race([e,r])}finally{t.signal.removeEventListener(`abort`,i)}},dispose(){clearTimeout(r),e?.removeEventListener(`abort`,n)}}}var rd=12e3;function id(e){if(e.noPlayer!==void 0&&typeof e.noPlayer!=`boolean`)throw Error(`Invalid noPlayer setting`);if(e.noPlayer!==!1)return null;let t=e.playerName??`Host`;if(typeof t!=`string`||!t.trim()||t.length>24)throw Error(`Invalid host player name`);return t.trim()}function ad(e,t,n,r,i,a){let o;return{ready:new Promise((s,c)=>{o=setTimeout(()=>c(Error(`Signaling timed out`)),rd),e.network=new As(n.id,{hostToken:n.hostToken},{ready:(t,n)=>{if(!n){c(Error(`Host authority was not granted`));return}r!==null&&(e.players.add({slot:0,peerId:t,name:r,team:0,admin:!0}),e.engine.joinPlayer(0)),clearTimeout(o),s()},allowStadiumUpload:e=>t.allowStadiumUpload(e),open:()=>{},control:(e,n)=>t.control(e,n),fast:(e,n)=>t.fast(e,n),leave:e=>t.leave(e),status:(t,n)=>{n===`error`&&e.report(t)},ended:t=>{clearTimeout(o),c(Error(t)),a(),e.report(t)}},i.network)}),cancel:()=>clearTimeout(o)}}async function od(e,t,n,r){let i=Ea(t.network.serviceOrigin),a=Ea(t.publicOrigin??i),o=td(e),s=id(o),c=nd(n),l;try{c.signal.throwIfAborted();let e=await c.run(t.loadEngine(c.signal));e.load(o.stadium??sn());let n=r.construct(e);l=n;let u=r.core(n),d=await c.run(t.request(new URL(ie.rooms,i),{signal:c.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:o.roomName,maxPlayers:o.maxPlayers??16,password:o.password??``,private:o.public===!1,hostPlayer:s!==null,...o.geo?{geo:o.geo}:{}})}));if(!d.ok)throw await c.run(Ju(d,c.signal));let f=await c.run(d.json());u.roomId=f.id,u.roomName=o.roomName,u.roomLink=`${a}${Wu(f.id)}`;let p=ad(u,r.gateway(n),f,s,t,()=>r.close(n));try{await c.run(p.ready)}catch(e){throw r.close(n),e}finally{p.cancel()}if(u.closed)throw Error(`Room closed during startup`);return r.start(n),n}catch(e){throw l&&r.close(l),e}finally{c.dispose()}}var sd=32768;function cd(e,t,n,r){let i=[...e.peers.values()].filter(e=>e.fast?.readyState===`open`&&e.fast.bufferedAmount<sd);if(!i.length)return;let a=Ro(t,i.map(e=>r.acknowledgment(e.id)),n);for(let t=0;t<i.length;t++){let n=i[t],r=a[t],o=r.reduce((e,t)=>e+t.byteLength,0);if(!(n.fast?.readyState!==`open`||n.fast.bufferedAmount+o>sd))for(let t of r)e.fast(n,t)}}var ld=1e3/ti,ud=500,dd=32,fd=ti/30;function pd(e){let{engine:t}=e,n=t.red,r=t.blue,i=t.phase;e.match.step(),e.turfState.capture(t),e.soundStream.capture(t,e.epoch);let a={kickers:t.ballKicks.map(t=>{let n=e.players.bySlot(t);return n?e.publicPlayer(n):null}).filter(e=>!!e),redGoal:t.red>n,blueGoal:t.blue>r,positionsReset:i===`goal`&&t.phase===`playing`,stopped:i===`finished`&&t.phase===`lobby`,victory:i!==`finished`&&t.phase===`finished`?oo(e):null},o=e.captureCommentary();t.phase!==i&&!o.length&&e.broadcastState();let s=e.captureAnalysis();e.captureIntelligence(o),e.captureXg(),e.notifyCommentary(o);for(let t of s)e.invoke(`onMatchObservation`,e.hooks.onMatchObservation,structuredClone(t));return a}var md=class{room;accumulator=0;last=performance.now();constructor(e){this.room=e}restart(){this.last=performance.now(),this.accumulator=0}advance(){let{room:e}=this;if(e.closed)return;let t=performance.now(),n=t-this.last;this.last=t,n>ud&&e.engine.phase===`playing`&&!e.engine.paused&&(no(e,!0,null),e.report(`Host scheduler stalled; match paused.`)),this.accumulator+=Math.max(0,Math.min(n,ud));let r=0;try{for(;!e.closed&&this.accumulator>=ld&&r++<dd&&(this.tick(t),!e.closed);)this.accumulator-=ld;e.closed||_l(e.network,e.soundStream.drain(t))}catch(t){e.closed||(e.engine.setPaused(!0),e.report(String(t)))}}tick(e){let{room:t}=this,{engine:n,hooks:r}=t;for(let n of t.players.all)t.inputs.expire(n.peerId,n.slot,e);if(t.match.checkRecordingLimit(),t.closed||(n.phase!==`lobby`&&!n.paused&&!n.resumeTicks&&t.invoke(`onGameTick`,r.onGameTick),t.closed))return;let i=pd(t);i.stopped&&t.invoke(`onGameStop`,r.onGameStop,null),i.victory&&(t.invoke(`onTeamVictory`,r.onTeamVictory,{...i.victory}),t.invoke(`onGameVictory`,r.onGameVictory,{...i.victory}));for(let e of i.kickers)t.invoke(`onPlayerBallKick`,r.onPlayerBallKick,e);i.redGoal&&t.invoke(`onTeamGoal`,r.onTeamGoal,1),i.blueGoal&&t.invoke(`onTeamGoal`,r.onTeamGoal,2),i.positionsReset&&t.invoke(`onPositionsReset`,r.onPositionsReset),!t.closed&&n.tick%fd===0&&cd(t.network,n.snapshot(),t.epoch,t.inputs)}},hd=Object.freeze({...Gn}),gd=e=>new Blob([wa(e)],{type:`application/x-ball2d-replay`}),_d=class e{engine;core;loop;timer;linkNotification;closeController=new AbortController;signal=this.closeController.signal;gateway;lastRecording=null;constructor(e,t,n){this.engine=e,this.core=new Hu(e,t,this,(e,t)=>{let n=gd(e);this.lastRecording=n,this.core.invoke(`onRecordingComplete`,this.onRecordingComplete,n,t)},n),this.loop=new md(this.core),this.gateway=Fc(this.core)}static async create(t,n=Ha(),r,i={}){let a=new Oi(i);return od(t,n,r,{construct:t=>new e(t,n,a),core:e=>e.core,gateway:e=>e.gateway,start:e=>e.start(),close:e=>e.close()})}start(){this.loop.restart(),this.timer=setInterval(()=>this.loop.advance(),1e3/ti);let e=this.core.roomLink;this.linkNotification=setTimeout(()=>{this.linkNotification=void 0,this.core.invoke(`onRoomLink`,this.onRoomLink,e)},0)}advance(){this.loop.advance()}get network(){return this.core.network}get roomId(){return this.core.roomId}get roomLink(){return this.core.roomLink}get roomName(){return this.core.roomName}get teamsLocked(){return this.core.locked}get requireVerification(){return this.core.network.requireVerification}get CollisionFlags(){return hd}getPlayerList(){return this.core.players.all.map(e=>this.core.publicPlayer(e))}getPlayer(e){return this.core.publicOrNull(this.core.players.byId(e)??null)}getScores(){return oo(this.core)}getBallPosition(){return $a(this.core)}getDiscCount(){return Ka(this.core)}getDiscProperties(e){return Ja(this.core,e)}getPlayerDiscProperties(e){return Za(this.core,e)}getState(){return this.engine.snapshot()}async setMatchXgConfig(e){this.core.assertOpen(),await this.core.xg.configure(this.engine,e,this.core.commentaryAnalysis.getAnalysisGeometry(this.engine)),this.core.assertOpen(),this.core.baselineXg()}getMatchXgStatus(){return structuredClone(this.core.xg.getStatus())}setCommentaryPolicy(e){this.core.assertOpen(),this.core.commentary.configure(e),this.core.network.broadcast({type:`commentary-config`,config:this.core.commentary.snapshot()})}getCommentaryPolicy(){return this.core.commentary.getPolicy()}setMatchIntelligencePolicy(e){this.core.assertOpen(),this.core.intelligence.configure(e)}getMatchIntelligencePolicy(){return this.core.intelligence.getPolicy()}setMatchIntelligenceRoles(e){this.core.assertOpen(),this.core.intelligence.setRoles(e,e=>{let t=this.core.players.byId(e);return t&&t.team!==0?{sessionId:this.core.factStream.streamId,playerId:e,team:t.team,name:t.name}:null})}getMatchIntelligenceRoles(){return this.core.intelligence.getRoles()}getMatchIntelligenceSnapshot(){return this.core.intelligence.getSnapshot()}setCommentaryCatalog(e){this.core.assertOpen(),this.core.commentary.setCatalog(e),this.broadcastCommentaryAssets(`catalog`)}getCommentaryCatalog(){return this.core.commentary.getCatalog()}setAtmospherePolicy(e){this.core.assertOpen(),this.core.commentary.setAtmosphere(e),this.core.network.broadcast({type:`commentary-config`,config:this.core.commentary.snapshot()})}getAtmospherePolicy(){return this.core.commentary.getAtmosphere()}setAtmospherePack(e){this.core.assertOpen(),this.core.commentary.setAtmospherePack(e),this.broadcastCommentaryAssets(`atmospherePack`)}getAtmospherePack(){return this.core.commentary.getAtmospherePack()}broadcastCommentaryAssets(e){this.core.network.broadcast({type:`commentary-config`,config:this.core.commentary.snapshot(Date.now(),e)})}setPlayerCommentaryContext(e,t){this.core.assertOpen();let n=this.core.players.byId(e);if(!n||n.team===0)throw Error(`Commentary context requires a current field player`);this.core.commentary.setPlayer({sessionId:this.core.factStream.streamId,playerId:e,team:n.team,name:n.name},t),this.core.network.broadcast({type:`commentary-config`,config:this.core.commentary.snapshot()})}getPlayerCommentaryContext(e){return this.core.players.byId(e)?this.core.commentary.getPlayer(e):[]}setCommentaryGeometry(e){this.core.assertOpen(),this.core.commentaryAnalysis.getAnalysisGeometry(this.engine),this.core.commentaryAnalysis.configure(this.engine,e)&&(this.core.intelligence.invalidate(),this.core.xg.invalidate(`domain-change`))}getCommentaryGeometry(){return this.core.commentaryAnalysis.getGeometry(this.engine)}setTeamColors(e,t,n,r){uc(this.core,e,t,n,r)}reorderPlayers(e,t){dc(this.core,e,t)}setPlayerAvatar(e,t){fc(this.core,e,t)}setPlayerTeam(e,t){ac(this.core,e,t,null)}setPlayerAdmin(e,t){oc(this.core,e,t)}setPlayerMuted(e,t){sc(this.core,e,t,null)}setTeamsLock(e){cc(this.core,e,null)}kickPlayer(e,t=`Removed by host`,n=!1){if(this.core.assertOpen(),typeof n!=`boolean`)throw Error(`Invalid ban flag`);if(n)return Ps(this.core,e,t);Ns(this.core,e,t,null)}clearBan(e){return Fs(this.core,e)}clearBans(){return Is(this.core)}sendChat(e,t){fo(this.core,e,t)}sendAnnouncement(e,t,n,r,i){po(this.core,e,t,n,r,i)}startGame(){eo(this.core,null)}stopGame(){to(this.core,null)}pauseGame(e){no(this.core,e,null)}setKickRateLimit(e=2,t=0,n=0){ro(this.core,e,t,n,null)}setScoreLimit(e){io(this.core,e)}setTimeLimit(e){ao(this.core,e)}async setPassword(e){this.core.assertOpen(),await this.core.network.setPassword(e)}async setRequireVerification(e){this.core.assertOpen(),await this.core.network.setRequireVerification(e)}setDefaultStadium(e){return mc(this.core,e)}setCustomStadium(e){pc(this.core,e,null)}setDiscProperties(e,t){Ya(this.core,e,t)}setPlayerDiscProperties(e,t){Qa(this.core,e,t)}startRecording(){this.core.assertOpen(),this.core.match.startRecording(this.core.players.all.map(e=>({slot:e.slot,name:e.name,avatar:e.avatarOverride??e.avatar})),this.core.teamStyles)}stopRecording(){let e=this.core.match.stopRecording();return e?gd(e):null}close(){let{core:e}=this;if(!e.closed){e.closed=!0,e.xg.close(),e.inputs.close(),this.closeController.abort();try{e.match.close()}finally{clearInterval(this.timer),clearTimeout(this.linkNotification),this.linkNotification=void 0,e.network?.close(),e.players.clear(),e.intelligence.reset(),e.intelligence.setRoles([],()=>null),e.traffic.clear()}}}};function vd(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Room configuration must be an object`);let t={...e},n=t.maxPlayers??12;if(typeof n!=`number`||!Number.isFinite(n)||!Number.isInteger(n))throw Error(`maxPlayers must be a finite integer`);return td({...t,roomName:t.roomName??`Headless Room`,playerName:t.playerName??`Host`,noPlayer:t.noPlayer??!1,public:t.public??!1,maxPlayers:Math.max(2,Math.min(30,n)),password:t.password??``})}var yd=R(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),bd=R(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=yd(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(` `,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){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 n.enable(n.load()),n}t.exports=n})),xd=R(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})(),e.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`.split(`.`);function n(){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 e;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&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=bd()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Sd=ee({createSupportsColor:()=>Dd,default:()=>Ad});function Cd(e,t=globalThis.Deno?globalThis.Deno.args:p.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}function wd(){if(!(`FORCE_COLOR`in Od))return;if(Od.FORCE_COLOR===`true`)return 1;if(Od.FORCE_COLOR===`false`)return 0;if(Od.FORCE_COLOR.length===0)return 1;let e=Math.min(Number.parseInt(Od.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}function Td(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Ed(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=wd();r!==void 0&&(kd=r);let i=n?kd:r;if(i===0)return 0;if(n){if(Cd(`color=16m`)||Cd(`color=full`)||Cd(`color=truecolor`))return 3;if(Cd(`color=256`))return 2}if(`TF_BUILD`in Od&&`AGENT_NAME`in Od)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(Od.TERM===`dumb`)return a;if(p.platform===`win32`){let e=h.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in Od)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in Od)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in Od)||Od.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in Od)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Od.TEAMCITY_VERSION);if(Od.COLORTERM===`truecolor`||Od.TERM===`xterm-kitty`||Od.TERM===`xterm-ghostty`||Od.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in Od){let e=Number.parseInt((Od.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(Od.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(Od.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Od.TERM)||`COLORTERM`in Od?1:a}function Dd(e,t={}){return Td(Ed(e,{streamIsTTY:e&&e.isTTY,...t}))}var Od,kd,Ad,jd=L((()=>{({env:Od}=p),Cd(`no-color`)||Cd(`no-colors`)||Cd(`color=false`)||Cd(`color=never`)?kd=0:(Cd(`color`)||Cd(`colors`)||Cd(`color=true`)||Cd(`color=always`))&&(kd=1),Ad={stdout:Dd({isTTY:g.isatty(1)}),stderr:Dd({isTTY:g.isatty(2)})}})),Md=R(((e,t)=>{var n=ne(`tty`),r=ne(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=(jd(),te(Sd));t&&(t.stderr||t).level>=2&&(e.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{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
15
15
|
`).join(`
|
|
16
16
|
`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
|
|
17
|
-
`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=
|
|
18
|
-
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})),$r=R(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?Vr():Qr()})),ei=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`net`);function n(e){switch(t.isIP(e)){case 4:return Buffer.from(e.split(`.`).map(e=>parseInt(e,10)));case 6:let t=e.split(`:`),n=Buffer.alloc(16),r=0;t[t.length-1]===``&&(t[t.length-1]=`0`);for(let e=0;e<t.length;e++){if(t[e]===``){e+1<t.length&&t[e+1]!==``&&(r=16-(t.length-e-1)*2);continue}n.writeUInt16BE(parseInt(t[e],16),r),r+=2}return n;default:return null}}e.bytesFromIP=n;function r(e){switch(e.length){case 4:return[e[0],e[1],e[2],e[3]].join(`.`);case 16:let t=[],n=-1,r=0,i=-1,a=0;for(let o=0;o<e.length;o+=2){let s=e[o]<<8|e[o+1];s===0?(r++,n===-1&&(n=t.length),r>a&&(a=r,i=n)):(n=-1,r=0),t.push(s.toString(16))}if(a>0){let e=``,n=t.slice(i+a);t.length=i,t.length===0&&(e+=`:`),n.length===0&&(e+=`:`),t.push(e,...n)}return t.join(`:`);default:return``}}e.bytesToIP=r;var i=Object.create(null),a=/^[0-9.]+$/;function o(e){return a.test(e)&&i[e]!==``?e:i[e]==null?``:i[e]}e.getOID=o;function s(e){return!a.test(e)&&i[e]!==``||i[e]==null?e:i[e]}e.getOIDName=s;function c(e,t){i[e]=t,i[t]=e}c(`1.2.840.113549.1.1.1`,`rsaEncryption`),c(`1.2.840.113549.1.1.4`,`md5WithRsaEncryption`),c(`1.2.840.113549.1.1.5`,`sha1WithRsaEncryption`),c(`1.2.840.113549.1.1.8`,`mgf1`),c(`1.2.840.113549.1.1.10`,`RSASSA-PSS`),c(`1.2.840.113549.1.1.11`,`sha256WithRsaEncryption`),c(`1.2.840.113549.1.1.12`,`sha384WithRsaEncryption`),c(`1.2.840.113549.1.1.13`,`sha512WithRsaEncryption`),c(`1.2.840.10045.2.1`,`ecEncryption`),c(`1.2.840.10045.4.1`,`ecdsaWithSha1`),c(`1.2.840.10045.4.3.2`,`ecdsaWithSha256`),c(`1.2.840.10045.4.3.3`,`ecdsaWithSha384`),c(`1.2.840.10045.4.3.4`,`ecdsaWithSha512`),c(`1.2.840.10040.4.3`,`dsaWithSha1`),c(`2.16.840.1.101.3.4.3.2`,`dsaWithSha256`),c(`1.3.14.3.2.7`,`desCBC`),c(`1.3.14.3.2.26`,`sha1`),c(`2.16.840.1.101.3.4.2.1`,`sha256`),c(`2.16.840.1.101.3.4.2.2`,`sha384`),c(`2.16.840.1.101.3.4.2.3`,`sha512`),c(`1.2.840.113549.2.5`,`md5`),c(`1.3.101.110`,`X25519`),c(`1.3.101.111`,`X448`),c(`1.3.101.112`,`Ed25519`),c(`1.3.101.113`,`Ed448`),c(`1.2.840.113549.1.7.1`,`data`),c(`1.2.840.113549.1.7.2`,`signedData`),c(`1.2.840.113549.1.7.3`,`envelopedData`),c(`1.2.840.113549.1.7.4`,`signedAndEnvelopedData`),c(`1.2.840.113549.1.7.5`,`digestedData`),c(`1.2.840.113549.1.7.6`,`encryptedData`),c(`1.2.840.113549.1.9.1`,`emailAddress`),c(`1.2.840.113549.1.9.2`,`unstructuredName`),c(`1.2.840.113549.1.9.3`,`contentType`),c(`1.2.840.113549.1.9.4`,`messageDigest`),c(`1.2.840.113549.1.9.5`,`signingTime`),c(`1.2.840.113549.1.9.6`,`counterSignature`),c(`1.2.840.113549.1.9.7`,`challengePassword`),c(`1.2.840.113549.1.9.8`,`unstructuredAddress`),c(`1.2.840.113549.1.9.14`,`extensionRequest`),c(`1.2.840.113549.1.9.20`,`friendlyName`),c(`1.2.840.113549.1.9.21`,`localKeyId`),c(`1.2.840.113549.1.9.22.1`,`x509Certificate`),c(`1.2.840.113549.1.12.10.1.1`,`keyBag`),c(`1.2.840.113549.1.12.10.1.2`,`pkcs8ShroudedKeyBag`),c(`1.2.840.113549.1.12.10.1.3`,`certBag`),c(`1.2.840.113549.1.12.10.1.4`,`crlBag`),c(`1.2.840.113549.1.12.10.1.5`,`secretBag`),c(`1.2.840.113549.1.12.10.1.6`,`safeContentsBag`),c(`1.2.840.113549.1.5.13`,`pkcs5PBES2`),c(`1.2.840.113549.1.5.12`,`pkcs5PBKDF2`),c(`1.2.840.113549.2.7`,`hmacWithSha1`),c(`1.2.840.113549.2.9`,`hmacWithSha256`),c(`1.2.840.113549.2.10`,`hmacWithSha384`),c(`1.2.840.113549.2.11`,`hmacWithSha512`),c(`1.2.840.113549.3.7`,`3desCBC`),c(`2.16.840.1.101.3.4.1.2`,`aesCBC128`),c(`2.16.840.1.101.3.4.1.42`,`aesCBC256`),c(`2.5.4.3`,`commonName`),c(`2.5.4.5`,`serialName`),c(`2.5.4.6`,`countryName`),c(`2.5.4.7`,`localityName`),c(`2.5.4.8`,`stateOrProvinceName`),c(`2.5.4.10`,`organizationName`),c(`2.5.4.11`,`organizationalUnitName`),c(`2.5.4.15`,`businessCategory`),c(`2.16.840.1.113730.1.1`,`nsCertType`),c(`2.5.29.2`,`keyAttributes`),c(`2.5.29.4`,`keyUsageRestriction`),c(`2.5.29.6`,`subtreesConstraint`),c(`2.5.29.9`,`subjectDirectoryAttributes`),c(`2.5.29.14`,`subjectKeyIdentifier`),c(`2.5.29.15`,`keyUsage`),c(`2.5.29.16`,`privateKeyUsagePeriod`),c(`2.5.29.17`,`subjectAltName`),c(`2.5.29.18`,`issuerAltName`),c(`2.5.29.19`,`basicConstraints`),c(`2.5.29.20`,`cRLNumber`),c(`2.5.29.21`,`cRLReason`),c(`2.5.29.22`,`expirationDate`),c(`2.5.29.23`,`instructionCode`),c(`2.5.29.24`,`invalidityDate`),c(`2.5.29.27`,`deltaCRLIndicator`),c(`2.5.29.28`,`issuingDistributionPoint`),c(`2.5.29.29`,`certificateIssuer`),c(`2.5.29.30`,`nameConstraints`),c(`2.5.29.31`,`cRLDistributionPoints`),c(`2.5.29.32`,`certificatePolicies`),c(`2.5.29.33`,`policyMappings`),c(`2.5.29.35`,`authorityKeyIdentifier`),c(`2.5.29.36`,`policyConstraints`),c(`2.5.29.37`,`extKeyUsage`),c(`2.5.29.46`,`freshestCRL`),c(`2.5.29.54`,`inhibitAnyPolicy`),c(`1.3.6.1.4.1.311.60.2.1.2`,`jurisdictionST`),c(`1.3.6.1.4.1.311.60.2.1.3`,`jurisdictionC`),c(`1.3.6.1.4.1.11129.2.4.2`,`timestampList`),c(`1.3.6.1.5.5.7.1.1`,`authorityInfoAccess`),c(`1.3.6.1.5.5.7.3.1`,`serverAuth`),c(`1.3.6.1.5.5.7.3.2`,`clientAuth`),c(`1.3.6.1.5.5.7.3.3`,`codeSigning`),c(`1.3.6.1.5.5.7.3.4`,`emailProtection`),c(`1.3.6.1.5.5.7.3.8`,`timeStamping`),c(`1.3.6.1.5.5.7.48.1`,`authorityInfoAccessOcsp`),c(`1.3.6.1.5.5.7.48.2`,`authorityInfoAccessIssuers`)})),ti=R(((e,t)=>{(function(e){var t=function(e){var t,n=new Float64Array(16);if(e)for(t=0;t<e.length;t++)n[t]=e[t];return n},n=function(){throw Error(`no PRNG`)},r=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var a=t(),o=t([1]),s=t([56129,1]),c=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),l=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),u=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),d=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function p(e,t,n,r){e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255,e[t+4]=r>>24&255,e[t+5]=r>>16&255,e[t+6]=r>>8&255,e[t+7]=r&255}function m(e,t,n,r,i){var a,o=0;for(a=0;a<i;a++)o|=e[t+a]^n[r+a];return(1&o-1>>>8)-1}function h(e,t,n,r){return m(e,t,n,r,16)}function g(e,t,n,r){return m(e,t,n,r,32)}function _(e,t,n,r){for(var i=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,a=n[0]&255|(n[1]&255)<<8|(n[2]&255)<<16|(n[3]&255)<<24,o=n[4]&255|(n[5]&255)<<8|(n[6]&255)<<16|(n[7]&255)<<24,s=n[8]&255|(n[9]&255)<<8|(n[10]&255)<<16|(n[11]&255)<<24,c=n[12]&255|(n[13]&255)<<8|(n[14]&255)<<16|(n[15]&255)<<24,l=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,u=t[0]&255|(t[1]&255)<<8|(t[2]&255)<<16|(t[3]&255)<<24,d=t[4]&255|(t[5]&255)<<8|(t[6]&255)<<16|(t[7]&255)<<24,f=t[8]&255|(t[9]&255)<<8|(t[10]&255)<<16|(t[11]&255)<<24,p=t[12]&255|(t[13]&255)<<8|(t[14]&255)<<16|(t[15]&255)<<24,m=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,h=n[16]&255|(n[17]&255)<<8|(n[18]&255)<<16|(n[19]&255)<<24,g=n[20]&255|(n[21]&255)<<8|(n[22]&255)<<16|(n[23]&255)<<24,_=n[24]&255|(n[25]&255)<<8|(n[26]&255)<<16|(n[27]&255)<<24,v=n[28]&255|(n[29]&255)<<8|(n[30]&255)<<16|(n[31]&255)<<24,y=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24,b=i,x=a,S=o,C=s,w=c,T=l,E=u,D=d,O=f,k=p,A=m,j=h,M=g,N=_,P=v,F=y,I,L=0;L<20;L+=2)I=b+M|0,w^=I<<7|I>>>25,I=w+b|0,O^=I<<9|I>>>23,I=O+w|0,M^=I<<13|I>>>19,I=M+O|0,b^=I<<18|I>>>14,I=T+x|0,k^=I<<7|I>>>25,I=k+T|0,N^=I<<9|I>>>23,I=N+k|0,x^=I<<13|I>>>19,I=x+N|0,T^=I<<18|I>>>14,I=A+E|0,P^=I<<7|I>>>25,I=P+A|0,S^=I<<9|I>>>23,I=S+P|0,E^=I<<13|I>>>19,I=E+S|0,A^=I<<18|I>>>14,I=F+j|0,C^=I<<7|I>>>25,I=C+F|0,D^=I<<9|I>>>23,I=D+C|0,j^=I<<13|I>>>19,I=j+D|0,F^=I<<18|I>>>14,I=b+C|0,x^=I<<7|I>>>25,I=x+b|0,S^=I<<9|I>>>23,I=S+x|0,C^=I<<13|I>>>19,I=C+S|0,b^=I<<18|I>>>14,I=T+w|0,E^=I<<7|I>>>25,I=E+T|0,D^=I<<9|I>>>23,I=D+E|0,w^=I<<13|I>>>19,I=w+D|0,T^=I<<18|I>>>14,I=A+k|0,j^=I<<7|I>>>25,I=j+A|0,O^=I<<9|I>>>23,I=O+j|0,k^=I<<13|I>>>19,I=k+O|0,A^=I<<18|I>>>14,I=F+P|0,M^=I<<7|I>>>25,I=M+F|0,N^=I<<9|I>>>23,I=N+M|0,P^=I<<13|I>>>19,I=P+N|0,F^=I<<18|I>>>14;b=b+i|0,x=x+a|0,S=S+o|0,C=C+s|0,w=w+c|0,T=T+l|0,E=E+u|0,D=D+d|0,O=O+f|0,k=k+p|0,A=A+m|0,j=j+h|0,M=M+g|0,N=N+_|0,P=P+v|0,F=F+y|0,e[0]=b>>>0&255,e[1]=b>>>8&255,e[2]=b>>>16&255,e[3]=b>>>24&255,e[4]=x>>>0&255,e[5]=x>>>8&255,e[6]=x>>>16&255,e[7]=x>>>24&255,e[8]=S>>>0&255,e[9]=S>>>8&255,e[10]=S>>>16&255,e[11]=S>>>24&255,e[12]=C>>>0&255,e[13]=C>>>8&255,e[14]=C>>>16&255,e[15]=C>>>24&255,e[16]=w>>>0&255,e[17]=w>>>8&255,e[18]=w>>>16&255,e[19]=w>>>24&255,e[20]=T>>>0&255,e[21]=T>>>8&255,e[22]=T>>>16&255,e[23]=T>>>24&255,e[24]=E>>>0&255,e[25]=E>>>8&255,e[26]=E>>>16&255,e[27]=E>>>24&255,e[28]=D>>>0&255,e[29]=D>>>8&255,e[30]=D>>>16&255,e[31]=D>>>24&255,e[32]=O>>>0&255,e[33]=O>>>8&255,e[34]=O>>>16&255,e[35]=O>>>24&255,e[36]=k>>>0&255,e[37]=k>>>8&255,e[38]=k>>>16&255,e[39]=k>>>24&255,e[40]=A>>>0&255,e[41]=A>>>8&255,e[42]=A>>>16&255,e[43]=A>>>24&255,e[44]=j>>>0&255,e[45]=j>>>8&255,e[46]=j>>>16&255,e[47]=j>>>24&255,e[48]=M>>>0&255,e[49]=M>>>8&255,e[50]=M>>>16&255,e[51]=M>>>24&255,e[52]=N>>>0&255,e[53]=N>>>8&255,e[54]=N>>>16&255,e[55]=N>>>24&255,e[56]=P>>>0&255,e[57]=P>>>8&255,e[58]=P>>>16&255,e[59]=P>>>24&255,e[60]=F>>>0&255,e[61]=F>>>8&255,e[62]=F>>>16&255,e[63]=F>>>24&255}function v(e,t,n,r){for(var i=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,a=n[0]&255|(n[1]&255)<<8|(n[2]&255)<<16|(n[3]&255)<<24,o=n[4]&255|(n[5]&255)<<8|(n[6]&255)<<16|(n[7]&255)<<24,s=n[8]&255|(n[9]&255)<<8|(n[10]&255)<<16|(n[11]&255)<<24,c=n[12]&255|(n[13]&255)<<8|(n[14]&255)<<16|(n[15]&255)<<24,l=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,u=t[0]&255|(t[1]&255)<<8|(t[2]&255)<<16|(t[3]&255)<<24,d=t[4]&255|(t[5]&255)<<8|(t[6]&255)<<16|(t[7]&255)<<24,f=t[8]&255|(t[9]&255)<<8|(t[10]&255)<<16|(t[11]&255)<<24,p=t[12]&255|(t[13]&255)<<8|(t[14]&255)<<16|(t[15]&255)<<24,m=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,h=n[16]&255|(n[17]&255)<<8|(n[18]&255)<<16|(n[19]&255)<<24,g=n[20]&255|(n[21]&255)<<8|(n[22]&255)<<16|(n[23]&255)<<24,_=n[24]&255|(n[25]&255)<<8|(n[26]&255)<<16|(n[27]&255)<<24,v=n[28]&255|(n[29]&255)<<8|(n[30]&255)<<16|(n[31]&255)<<24,y=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24,b=i,x=a,S=o,C=s,w=c,T=l,E=u,D=d,O=f,k=p,A=m,j=h,M=g,N=_,P=v,F=y,I,L=0;L<20;L+=2)I=b+M|0,w^=I<<7|I>>>25,I=w+b|0,O^=I<<9|I>>>23,I=O+w|0,M^=I<<13|I>>>19,I=M+O|0,b^=I<<18|I>>>14,I=T+x|0,k^=I<<7|I>>>25,I=k+T|0,N^=I<<9|I>>>23,I=N+k|0,x^=I<<13|I>>>19,I=x+N|0,T^=I<<18|I>>>14,I=A+E|0,P^=I<<7|I>>>25,I=P+A|0,S^=I<<9|I>>>23,I=S+P|0,E^=I<<13|I>>>19,I=E+S|0,A^=I<<18|I>>>14,I=F+j|0,C^=I<<7|I>>>25,I=C+F|0,D^=I<<9|I>>>23,I=D+C|0,j^=I<<13|I>>>19,I=j+D|0,F^=I<<18|I>>>14,I=b+C|0,x^=I<<7|I>>>25,I=x+b|0,S^=I<<9|I>>>23,I=S+x|0,C^=I<<13|I>>>19,I=C+S|0,b^=I<<18|I>>>14,I=T+w|0,E^=I<<7|I>>>25,I=E+T|0,D^=I<<9|I>>>23,I=D+E|0,w^=I<<13|I>>>19,I=w+D|0,T^=I<<18|I>>>14,I=A+k|0,j^=I<<7|I>>>25,I=j+A|0,O^=I<<9|I>>>23,I=O+j|0,k^=I<<13|I>>>19,I=k+O|0,A^=I<<18|I>>>14,I=F+P|0,M^=I<<7|I>>>25,I=M+F|0,N^=I<<9|I>>>23,I=N+M|0,P^=I<<13|I>>>19,I=P+N|0,F^=I<<18|I>>>14;e[0]=b>>>0&255,e[1]=b>>>8&255,e[2]=b>>>16&255,e[3]=b>>>24&255,e[4]=T>>>0&255,e[5]=T>>>8&255,e[6]=T>>>16&255,e[7]=T>>>24&255,e[8]=A>>>0&255,e[9]=A>>>8&255,e[10]=A>>>16&255,e[11]=A>>>24&255,e[12]=F>>>0&255,e[13]=F>>>8&255,e[14]=F>>>16&255,e[15]=F>>>24&255,e[16]=E>>>0&255,e[17]=E>>>8&255,e[18]=E>>>16&255,e[19]=E>>>24&255,e[20]=D>>>0&255,e[21]=D>>>8&255,e[22]=D>>>16&255,e[23]=D>>>24&255,e[24]=O>>>0&255,e[25]=O>>>8&255,e[26]=O>>>16&255,e[27]=O>>>24&255,e[28]=k>>>0&255,e[29]=k>>>8&255,e[30]=k>>>16&255,e[31]=k>>>24&255}function y(e,t,n,r){_(e,t,n,r)}function b(e,t,n,r){v(e,t,n,r)}var x=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(e,t,n,r,i,a,o){for(var s=new Uint8Array(16),c=new Uint8Array(64),l,u=0;u<16;u++)s[u]=0;for(u=0;u<8;u++)s[u]=a[u];for(;i>=64;){for(y(c,s,o,x),u=0;u<64;u++)e[t+u]=n[r+u]^c[u];for(l=1,u=8;u<16;u++)l=l+(s[u]&255)|0,s[u]=l&255,l>>>=8;i-=64,t+=64,r+=64}if(i>0)for(y(c,s,o,x),u=0;u<i;u++)e[t+u]=n[r+u]^c[u];return 0}function C(e,t,n,r,i){for(var a=new Uint8Array(16),o=new Uint8Array(64),s,c=0;c<16;c++)a[c]=0;for(c=0;c<8;c++)a[c]=r[c];for(;n>=64;){for(y(o,a,i,x),c=0;c<64;c++)e[t+c]=o[c];for(s=1,c=8;c<16;c++)s=s+(a[c]&255)|0,a[c]=s&255,s>>>=8;n-=64,t+=64}if(n>0)for(y(o,a,i,x),c=0;c<n;c++)e[t+c]=o[c];return 0}function w(e,t,n,r,i){var a=new Uint8Array(32);b(a,r,i,x);for(var o=new Uint8Array(8),s=0;s<8;s++)o[s]=r[s+16];return C(e,t,n,o,a)}function T(e,t,n,r,i,a,o){var s=new Uint8Array(32);b(s,a,o,x);for(var c=new Uint8Array(8),l=0;l<8;l++)c[l]=a[l+16];return S(e,t,n,r,i,c,s)}var E=function(e){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 t=e[0]&255|(e[1]&255)<<8,n,r,i,a,o,s,c;this.r[0]=t&8191,n=e[2]&255|(e[3]&255)<<8,this.r[1]=(t>>>13|n<<3)&8191,r=e[4]&255|(e[5]&255)<<8,this.r[2]=(n>>>10|r<<6)&7939,i=e[6]&255|(e[7]&255)<<8,this.r[3]=(r>>>7|i<<9)&8191,a=e[8]&255|(e[9]&255)<<8,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,o=e[10]&255|(e[11]&255)<<8,this.r[6]=(a>>>14|o<<2)&8191,s=e[12]&255|(e[13]&255)<<8,this.r[7]=(o>>>11|s<<5)&8065,c=e[14]&255|(e[15]&255)<<8,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127,this.pad[0]=e[16]&255|(e[17]&255)<<8,this.pad[1]=e[18]&255|(e[19]&255)<<8,this.pad[2]=e[20]&255|(e[21]&255)<<8,this.pad[3]=e[22]&255|(e[23]&255)<<8,this.pad[4]=e[24]&255|(e[25]&255)<<8,this.pad[5]=e[26]&255|(e[27]&255)<<8,this.pad[6]=e[28]&255|(e[29]&255)<<8,this.pad[7]=e[30]&255|(e[31]&255)<<8};E.prototype.blocks=function(e,t,n){for(var r=this.fin?0:2048,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C=this.h[0],w=this.h[1],T=this.h[2],E=this.h[3],D=this.h[4],O=this.h[5],k=this.h[6],A=this.h[7],j=this.h[8],M=this.h[9],N=this.r[0],P=this.r[1],F=this.r[2],I=this.r[3],L=this.r[4],R=this.r[5],z=this.r[6],B=this.r[7],V=this.r[8],ee=this.r[9];n>=16;)i=e[t+0]&255|(e[t+1]&255)<<8,C+=i&8191,a=e[t+2]&255|(e[t+3]&255)<<8,w+=(i>>>13|a<<3)&8191,o=e[t+4]&255|(e[t+5]&255)<<8,T+=(a>>>10|o<<6)&8191,s=e[t+6]&255|(e[t+7]&255)<<8,E+=(o>>>7|s<<9)&8191,c=e[t+8]&255|(e[t+9]&255)<<8,D+=(s>>>4|c<<12)&8191,O+=c>>>1&8191,l=e[t+10]&255|(e[t+11]&255)<<8,k+=(c>>>14|l<<2)&8191,u=e[t+12]&255|(e[t+13]&255)<<8,A+=(l>>>11|u<<5)&8191,d=e[t+14]&255|(e[t+15]&255)<<8,j+=(u>>>8|d<<8)&8191,M+=d>>>5|r,f=0,p=f,p+=C*N,p+=5*ee*w,p+=5*V*T,p+=5*B*E,p+=5*z*D,f=p>>>13,p&=8191,p+=5*R*O,p+=5*L*k,p+=5*I*A,p+=5*F*j,p+=5*P*M,f+=p>>>13,p&=8191,m=f,m+=C*P,m+=w*N,m+=5*ee*T,m+=5*V*E,m+=5*B*D,f=m>>>13,m&=8191,m+=5*z*O,m+=5*R*k,m+=5*L*A,m+=5*I*j,m+=5*F*M,f+=m>>>13,m&=8191,h=f,h+=C*F,h+=w*P,h+=T*N,h+=5*ee*E,h+=5*V*D,f=h>>>13,h&=8191,h+=5*B*O,h+=5*z*k,h+=5*R*A,h+=5*L*j,h+=5*I*M,f+=h>>>13,h&=8191,g=f,g+=C*I,g+=w*F,g+=T*P,g+=E*N,g+=5*ee*D,f=g>>>13,g&=8191,g+=5*V*O,g+=5*B*k,g+=5*z*A,g+=5*R*j,g+=5*L*M,f+=g>>>13,g&=8191,_=f,_+=C*L,_+=w*I,_+=T*F,_+=E*P,_+=D*N,f=_>>>13,_&=8191,_+=5*ee*O,_+=5*V*k,_+=5*B*A,_+=5*z*j,_+=5*R*M,f+=_>>>13,_&=8191,v=f,v+=C*R,v+=w*L,v+=T*I,v+=E*F,v+=D*P,f=v>>>13,v&=8191,v+=O*N,v+=5*ee*k,v+=5*V*A,v+=5*B*j,v+=5*z*M,f+=v>>>13,v&=8191,y=f,y+=C*z,y+=w*R,y+=T*L,y+=E*I,y+=D*F,f=y>>>13,y&=8191,y+=O*P,y+=k*N,y+=5*ee*A,y+=5*V*j,y+=5*B*M,f+=y>>>13,y&=8191,b=f,b+=C*B,b+=w*z,b+=T*R,b+=E*L,b+=D*I,f=b>>>13,b&=8191,b+=O*F,b+=k*P,b+=A*N,b+=5*ee*j,b+=5*V*M,f+=b>>>13,b&=8191,x=f,x+=C*V,x+=w*B,x+=T*z,x+=E*R,x+=D*L,f=x>>>13,x&=8191,x+=O*I,x+=k*F,x+=A*P,x+=j*N,x+=5*ee*M,f+=x>>>13,x&=8191,S=f,S+=C*ee,S+=w*V,S+=T*B,S+=E*z,S+=D*R,f=S>>>13,S&=8191,S+=O*L,S+=k*I,S+=A*F,S+=j*P,S+=M*N,f+=S>>>13,S&=8191,f=(f<<2)+f|0,f=f+p|0,p=f&8191,f>>>=13,m+=f,C=p,w=m,T=h,E=g,D=_,O=v,k=y,A=b,j=x,M=S,t+=16,n-=16;this.h[0]=C,this.h[1]=w,this.h[2]=T,this.h[3]=E,this.h[4]=D,this.h[5]=O,this.h[6]=k,this.h[7]=A,this.h[8]=j,this.h[9]=M},E.prototype.finish=function(e,t){var n=new Uint16Array(10),r,i,a,o;if(this.leftover){for(o=this.leftover,this.buffer[o++]=1;o<16;o++)this.buffer[o]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,o=2;o<10;o++)this.h[o]+=r,r=this.h[o]>>>13,this.h[o]&=8191;for(this.h[0]+=r*5,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,n[0]=this.h[0]+5,r=n[0]>>>13,n[0]&=8191,o=1;o<10;o++)n[o]=this.h[o]+r,r=n[o]>>>13,n[o]&=8191;for(n[9]-=8192,i=(r^1)-1,o=0;o<10;o++)n[o]&=i;for(i=~i,o=0;o<10;o++)this.h[o]=this.h[o]&i|n[o];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,a=this.h[0]+this.pad[0],this.h[0]=a&65535,o=1;o<8;o++)a=(this.h[o]+this.pad[o]|0)+(a>>>16)|0,this.h[o]=a&65535;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},E.prototype.update=function(e,t,n){var r,i;if(this.leftover){for(i=16-this.leftover,i>n&&(i=n),r=0;r<i;r++)this.buffer[this.leftover+r]=e[t+r];if(n-=i,t+=i,this.leftover+=i,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(n>=16&&(i=n-n%16,this.blocks(e,t,i),t+=i,n-=i),n){for(r=0;r<n;r++)this.buffer[this.leftover+r]=e[t+r];this.leftover+=n}};function D(e,t,n,r,i,a){var o=new E(a);return o.update(n,r,i),o.finish(e,t),0}function O(e,t,n,r,i,a){var o=new Uint8Array(16);return D(o,0,n,r,i,a),h(e,t,o,0)}function k(e,t,n,r,i){var a;if(n<32)return-1;for(T(e,0,t,0,n,r,i),D(e,16,e,32,n-32,e),a=0;a<16;a++)e[a]=0;return 0}function A(e,t,n,r,i){var a,o=new Uint8Array(32);if(n<32||(w(o,0,32,r,i),O(t,16,t,32,n-32,o)!==0))return-1;for(T(e,0,t,0,n,r,i),a=0;a<32;a++)e[a]=0;return 0}function j(e,t){for(var n=0;n<16;n++)e[n]=t[n]|0}function M(e){var t,n,r=1;for(t=0;t<16;t++)n=e[t]+r+65535,r=Math.floor(n/65536),e[t]=n-r*65536;e[0]+=r-1+37*(r-1)}function N(e,t,n){for(var r,i=~(n-1),a=0;a<16;a++)r=i&(e[a]^t[a]),e[a]^=r,t[a]^=r}function P(e,n){var r,i,a,o=t(),s=t();for(r=0;r<16;r++)s[r]=n[r];for(M(s),M(s),M(s),i=0;i<2;i++){for(o[0]=s[0]-65517,r=1;r<15;r++)o[r]=s[r]-65535-(o[r-1]>>16&1),o[r-1]&=65535;o[15]=s[15]-32767-(o[14]>>16&1),a=o[15]>>16&1,o[14]&=65535,N(s,o,1-a)}for(r=0;r<16;r++)e[2*r]=s[r]&255,e[2*r+1]=s[r]>>8}function F(e,t){var n=new Uint8Array(32),r=new Uint8Array(32);return P(n,e),P(r,t),g(n,0,r,0)}function I(e){var t=new Uint8Array(32);return P(t,e),t[0]&1}function L(e,t){for(var n=0;n<16;n++)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function R(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]+n[r]}function z(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]-n[r]}function B(e,t,n){var r,i,a=0,o=0,s=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0,S=0,C=0,w=0,T=0,E=0,D=0,O=0,k=0,A=0,j=0,M=0,N=0,P=0,F=0,I=n[0],L=n[1],R=n[2],z=n[3],B=n[4],V=n[5],ee=n[6],te=n[7],ne=n[8],re=n[9],ie=n[10],ae=n[11],oe=n[12],se=n[13],ce=n[14],le=n[15];r=t[0],a+=r*I,o+=r*L,s+=r*R,c+=r*z,l+=r*B,u+=r*V,d+=r*ee,f+=r*te,p+=r*ne,m+=r*re,h+=r*ie,g+=r*ae,_+=r*oe,v+=r*se,y+=r*ce,b+=r*le,r=t[1],o+=r*I,s+=r*L,c+=r*R,l+=r*z,u+=r*B,d+=r*V,f+=r*ee,p+=r*te,m+=r*ne,h+=r*re,g+=r*ie,_+=r*ae,v+=r*oe,y+=r*se,b+=r*ce,x+=r*le,r=t[2],s+=r*I,c+=r*L,l+=r*R,u+=r*z,d+=r*B,f+=r*V,p+=r*ee,m+=r*te,h+=r*ne,g+=r*re,_+=r*ie,v+=r*ae,y+=r*oe,b+=r*se,x+=r*ce,S+=r*le,r=t[3],c+=r*I,l+=r*L,u+=r*R,d+=r*z,f+=r*B,p+=r*V,m+=r*ee,h+=r*te,g+=r*ne,_+=r*re,v+=r*ie,y+=r*ae,b+=r*oe,x+=r*se,S+=r*ce,C+=r*le,r=t[4],l+=r*I,u+=r*L,d+=r*R,f+=r*z,p+=r*B,m+=r*V,h+=r*ee,g+=r*te,_+=r*ne,v+=r*re,y+=r*ie,b+=r*ae,x+=r*oe,S+=r*se,C+=r*ce,w+=r*le,r=t[5],u+=r*I,d+=r*L,f+=r*R,p+=r*z,m+=r*B,h+=r*V,g+=r*ee,_+=r*te,v+=r*ne,y+=r*re,b+=r*ie,x+=r*ae,S+=r*oe,C+=r*se,w+=r*ce,T+=r*le,r=t[6],d+=r*I,f+=r*L,p+=r*R,m+=r*z,h+=r*B,g+=r*V,_+=r*ee,v+=r*te,y+=r*ne,b+=r*re,x+=r*ie,S+=r*ae,C+=r*oe,w+=r*se,T+=r*ce,E+=r*le,r=t[7],f+=r*I,p+=r*L,m+=r*R,h+=r*z,g+=r*B,_+=r*V,v+=r*ee,y+=r*te,b+=r*ne,x+=r*re,S+=r*ie,C+=r*ae,w+=r*oe,T+=r*se,E+=r*ce,D+=r*le,r=t[8],p+=r*I,m+=r*L,h+=r*R,g+=r*z,_+=r*B,v+=r*V,y+=r*ee,b+=r*te,x+=r*ne,S+=r*re,C+=r*ie,w+=r*ae,T+=r*oe,E+=r*se,D+=r*ce,O+=r*le,r=t[9],m+=r*I,h+=r*L,g+=r*R,_+=r*z,v+=r*B,y+=r*V,b+=r*ee,x+=r*te,S+=r*ne,C+=r*re,w+=r*ie,T+=r*ae,E+=r*oe,D+=r*se,O+=r*ce,k+=r*le,r=t[10],h+=r*I,g+=r*L,_+=r*R,v+=r*z,y+=r*B,b+=r*V,x+=r*ee,S+=r*te,C+=r*ne,w+=r*re,T+=r*ie,E+=r*ae,D+=r*oe,O+=r*se,k+=r*ce,A+=r*le,r=t[11],g+=r*I,_+=r*L,v+=r*R,y+=r*z,b+=r*B,x+=r*V,S+=r*ee,C+=r*te,w+=r*ne,T+=r*re,E+=r*ie,D+=r*ae,O+=r*oe,k+=r*se,A+=r*ce,j+=r*le,r=t[12],_+=r*I,v+=r*L,y+=r*R,b+=r*z,x+=r*B,S+=r*V,C+=r*ee,w+=r*te,T+=r*ne,E+=r*re,D+=r*ie,O+=r*ae,k+=r*oe,A+=r*se,j+=r*ce,M+=r*le,r=t[13],v+=r*I,y+=r*L,b+=r*R,x+=r*z,S+=r*B,C+=r*V,w+=r*ee,T+=r*te,E+=r*ne,D+=r*re,O+=r*ie,k+=r*ae,A+=r*oe,j+=r*se,M+=r*ce,N+=r*le,r=t[14],y+=r*I,b+=r*L,x+=r*R,S+=r*z,C+=r*B,w+=r*V,T+=r*ee,E+=r*te,D+=r*ne,O+=r*re,k+=r*ie,A+=r*ae,j+=r*oe,M+=r*se,N+=r*ce,P+=r*le,r=t[15],b+=r*I,x+=r*L,S+=r*R,C+=r*z,w+=r*B,T+=r*V,E+=r*ee,D+=r*te,O+=r*ne,k+=r*re,A+=r*ie,j+=r*ae,M+=r*oe,N+=r*se,P+=r*ce,F+=r*le,a+=38*x,o+=38*S,s+=38*C,c+=38*w,l+=38*T,u+=38*E,d+=38*D,f+=38*O,p+=38*k,m+=38*A,h+=38*j,g+=38*M,_+=38*N,v+=38*P,y+=38*F,i=1,r=a+i+65535,i=Math.floor(r/65536),a=r-i*65536,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=m+i+65535,i=Math.floor(r/65536),m=r-i*65536,r=h+i+65535,i=Math.floor(r/65536),h=r-i*65536,r=g+i+65535,i=Math.floor(r/65536),g=r-i*65536,r=_+i+65535,i=Math.floor(r/65536),_=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=y+i+65535,i=Math.floor(r/65536),y=r-i*65536,r=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,a+=i-1+37*(i-1),i=1,r=a+i+65535,i=Math.floor(r/65536),a=r-i*65536,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=m+i+65535,i=Math.floor(r/65536),m=r-i*65536,r=h+i+65535,i=Math.floor(r/65536),h=r-i*65536,r=g+i+65535,i=Math.floor(r/65536),g=r-i*65536,r=_+i+65535,i=Math.floor(r/65536),_=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=y+i+65535,i=Math.floor(r/65536),y=r-i*65536,r=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,a+=i-1+37*(i-1),e[0]=a,e[1]=o,e[2]=s,e[3]=c,e[4]=l,e[5]=u,e[6]=d,e[7]=f,e[8]=p,e[9]=m,e[10]=h,e[11]=g,e[12]=_,e[13]=v,e[14]=y,e[15]=b}function V(e,t){B(e,t,t)}function ee(e,n){for(var r=t(),i=0;i<16;i++)r[i]=n[i];for(i=253;i>=0;i--)V(r,r),i!==2&&i!==4&&B(r,r,n);for(i=0;i<16;i++)e[i]=r[i]}function ne(e,n){for(var r=t(),i=0;i<16;i++)r[i]=n[i];for(i=250;i>=0;i--)V(r,r),i!==1&&B(r,r,n);for(i=0;i<16;i++)e[i]=r[i]}function re(e,n,r){var i=new Uint8Array(32),a=new Float64Array(80),o,c,l=t(),u=t(),d=t(),f=t(),p=t(),m=t();for(c=0;c<31;c++)i[c]=n[c];for(i[31]=n[31]&127|64,i[0]&=248,L(a,r),c=0;c<16;c++)u[c]=a[c],f[c]=l[c]=d[c]=0;for(l[0]=f[0]=1,c=254;c>=0;--c)o=i[c>>>3]>>>(c&7)&1,N(l,u,o),N(d,f,o),R(p,l,d),z(l,l,d),R(d,u,f),z(u,u,f),V(f,p),V(m,l),B(l,d,l),B(d,u,p),R(p,l,d),z(l,l,d),V(u,l),z(d,f,m),B(l,d,s),R(l,l,f),B(d,d,l),B(l,f,m),B(f,u,a),V(u,p),N(l,u,o),N(d,f,o);for(c=0;c<16;c++)a[c+16]=l[c],a[c+32]=d[c],a[c+48]=u[c],a[c+64]=f[c];var h=a.subarray(32),g=a.subarray(16);return ee(h,h),B(g,g,h),P(e,g),0}function ie(e,t){return re(e,t,i)}function ae(e,t){return n(t,32),ie(e,t)}function oe(e,t,n){var i=new Uint8Array(32);return re(i,n,t),b(e,r,i,x)}var se=k,ce=A;function le(e,t,n,r,i,a){var o=new Uint8Array(32);return oe(o,i,a),se(e,t,n,r,o)}function ue(e,t,n,r,i,a){var o=new Uint8Array(32);return oe(o,i,a),ce(e,t,n,r,o)}var de=[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 fe(e,t,n,r){for(var i=new Int32Array(16),a=new Int32Array(16),o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M=e[0],N=e[1],P=e[2],F=e[3],I=e[4],L=e[5],R=e[6],z=e[7],B=t[0],V=t[1],ee=t[2],te=t[3],ne=t[4],re=t[5],ie=t[6],ae=t[7],oe=0;r>=128;){for(w=0;w<16;w++)T=8*w+oe,i[w]=n[T+0]<<24|n[T+1]<<16|n[T+2]<<8|n[T+3],a[w]=n[T+4]<<24|n[T+5]<<16|n[T+6]<<8|n[T+7];for(w=0;w<80;w++)if(o=M,s=N,c=P,l=F,u=I,d=L,f=R,p=z,m=B,h=V,g=ee,_=te,v=ne,y=re,b=ie,x=ae,E=z,D=ae,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=(I>>>14|ne<<18)^(I>>>18|ne<<14)^(ne>>>9|I<<23),D=(ne>>>14|I<<18)^(ne>>>18|I<<14)^(I>>>9|ne<<23),O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,E=I&L^~I&R,D=ne&re^~ne&ie,O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,E=de[w*2],D=de[w*2+1],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,E=i[w%16],D=a[w%16],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,S=A&65535|j<<16,C=O&65535|k<<16,E=S,D=C,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=(M>>>28|B<<4)^(B>>>2|M<<30)^(B>>>7|M<<25),D=(B>>>28|M<<4)^(M>>>2|B<<30)^(M>>>7|B<<25),O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,E=M&N^M&P^N&P,D=B&V^B&ee^V&ee,O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,p=A&65535|j<<16,x=O&65535|k<<16,E=l,D=_,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=S,D=C,O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,l=A&65535|j<<16,_=O&65535|k<<16,N=o,P=s,F=c,I=l,L=u,R=d,z=f,M=p,V=m,ee=h,te=g,ne=_,re=v,ie=y,ae=b,B=x,w%16==15)for(T=0;T<16;T++)E=i[T],D=a[T],O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=i[(T+9)%16],D=a[(T+9)%16],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,S=i[(T+1)%16],C=a[(T+1)%16],E=(S>>>1|C<<31)^(S>>>8|C<<24)^S>>>7,D=(C>>>1|S<<31)^(C>>>8|S<<24)^(C>>>7|S<<25),O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,S=i[(T+14)%16],C=a[(T+14)%16],E=(S>>>19|C<<13)^(C>>>29|S<<3)^S>>>6,D=(C>>>19|S<<13)^(S>>>29|C<<3)^(C>>>6|S<<26),O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,i[T]=A&65535|j<<16,a[T]=O&65535|k<<16;E=M,D=B,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[0],D=t[0],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[0]=M=A&65535|j<<16,t[0]=B=O&65535|k<<16,E=N,D=V,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[1],D=t[1],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[1]=N=A&65535|j<<16,t[1]=V=O&65535|k<<16,E=P,D=ee,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[2],D=t[2],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[2]=P=A&65535|j<<16,t[2]=ee=O&65535|k<<16,E=F,D=te,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[3],D=t[3],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[3]=F=A&65535|j<<16,t[3]=te=O&65535|k<<16,E=I,D=ne,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[4],D=t[4],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[4]=I=A&65535|j<<16,t[4]=ne=O&65535|k<<16,E=L,D=re,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[5],D=t[5],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[5]=L=A&65535|j<<16,t[5]=re=O&65535|k<<16,E=R,D=ie,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[6],D=t[6],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[6]=R=A&65535|j<<16,t[6]=ie=O&65535|k<<16,E=z,D=ae,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[7],D=t[7],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[7]=z=A&65535|j<<16,t[7]=ae=O&65535|k<<16,oe+=128,r-=128}return r}function pe(e,t,n){var r=new Int32Array(8),i=new Int32Array(8),a=new Uint8Array(256),o,s=n;for(r[0]=1779033703,r[1]=3144134277,r[2]=1013904242,r[3]=2773480762,r[4]=1359893119,r[5]=2600822924,r[6]=528734635,r[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,fe(r,i,t,n),n%=128,o=0;o<n;o++)a[o]=t[s-n+o];for(a[n]=128,n=256-128*(n<112),a[n-9]=0,p(a,n-8,s/536870912|0,s<<3),fe(r,i,a,n),o=0;o<8;o++)p(e,8*o,r[o],i[o]);return 0}function me(e,n){var r=t(),i=t(),a=t(),o=t(),s=t(),c=t(),u=t(),d=t(),f=t();z(r,e[1],e[0]),z(f,n[1],n[0]),B(r,r,f),R(i,e[0],e[1]),R(f,n[0],n[1]),B(i,i,f),B(a,e[3],n[3]),B(a,a,l),B(o,e[2],n[2]),R(o,o,o),z(s,i,r),z(c,o,a),R(u,o,a),R(d,i,r),B(e[0],s,c),B(e[1],d,u),B(e[2],u,c),B(e[3],s,d)}function he(e,t,n){for(var r=0;r<4;r++)N(e[r],t[r],n)}function ge(e,n){var r=t(),i=t(),a=t();ee(a,n[2]),B(r,n[0],a),B(i,n[1],a),P(e,i),e[31]^=I(r)<<7}function _e(e,t,n){var r,i;for(j(e[0],a),j(e[1],o),j(e[2],o),j(e[3],a),i=255;i>=0;--i)r=n[i/8|0]>>(i&7)&1,he(e,t,r),me(t,e),me(e,e),he(e,t,r)}function ve(e,n){var r=[t(),t(),t(),t()];j(r[0],u),j(r[1],d),j(r[2],o),B(r[3],u,d),_e(e,r,n)}function ye(e,r,i){var a=new Uint8Array(64),o=[t(),t(),t(),t()],s;for(i||n(r,32),pe(a,r,32),a[0]&=248,a[31]&=127,a[31]|=64,ve(o,a),ge(e,o),s=0;s<32;s++)r[s+32]=e[s];return 0}var be=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 xe(e,t){for(var n,r=63,i,a;r>=32;--r){for(n=0,i=r-32,a=r-12;i<a;++i)t[i]+=n-16*t[r]*be[i-(r-32)],n=Math.floor((t[i]+128)/256),t[i]-=n*256;t[i]+=n,t[r]=0}for(n=0,i=0;i<32;i++)t[i]+=n-(t[31]>>4)*be[i],n=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=n*be[i];for(r=0;r<32;r++)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function Se(e){for(var t=new Float64Array(64),n=0;n<64;n++)t[n]=e[n];for(n=0;n<64;n++)e[n]=0;xe(e,t)}function Ce(e,n,r,i){var a=new Uint8Array(64),o=new Uint8Array(64),s=new Uint8Array(64),c,l,u=new Float64Array(64),d=[t(),t(),t(),t()];pe(a,i,32),a[0]&=248,a[31]&=127,a[31]|=64;var f=r+64;for(c=0;c<r;c++)e[64+c]=n[c];for(c=0;c<32;c++)e[32+c]=a[32+c];for(pe(s,e.subarray(32),r+32),Se(s),ve(d,s),ge(e,d),c=32;c<64;c++)e[c]=i[c];for(pe(o,e,r+64),Se(o),c=0;c<64;c++)u[c]=0;for(c=0;c<32;c++)u[c]=s[c];for(c=0;c<32;c++)for(l=0;l<32;l++)u[c+l]+=o[c]*a[l];return xe(e.subarray(32),u),f}function we(e,n){var r=t(),i=t(),s=t(),l=t(),u=t(),d=t(),p=t();return j(e[2],o),L(e[1],n),V(s,e[1]),B(l,s,c),z(s,s,e[2]),R(l,e[2],l),V(u,l),V(d,u),B(p,d,u),B(r,p,s),B(r,r,l),ne(r,r),B(r,r,s),B(r,r,l),B(r,r,l),B(e[0],r,l),V(i,e[0]),B(i,i,l),F(i,s)&&B(e[0],e[0],f),V(i,e[0]),B(i,i,l),F(i,s)?-1:(I(e[0])===n[31]>>7&&z(e[0],a,e[0]),B(e[3],e[0],e[1]),0)}function Te(e,n,r,i){var a,o=new Uint8Array(32),s=new Uint8Array(64),c=[t(),t(),t(),t()],l=[t(),t(),t(),t()];if(r<64||we(l,i))return-1;for(a=0;a<r;a++)e[a]=n[a];for(a=0;a<32;a++)e[a+32]=i[a];if(pe(s,e,r),Se(s),_e(c,l,s),ve(l,n.subarray(32)),me(c,l),ge(o,c),r-=64,g(n,0,o,0)){for(a=0;a<r;a++)e[a]=0;return-1}for(a=0;a<r;a++)e[a]=n[a+64];return r}var Ee=32,De=24,Oe=32,ke=16,Ae=32,je=32,Me=32,Ne=32,Pe=32,Fe=De,Ie=Oe,Le=ke,Re=64,ze=32,Be=64,Ve=32,He=64;e.lowlevel={crypto_core_hsalsa20:b,crypto_stream_xor:T,crypto_stream:w,crypto_stream_salsa20_xor:S,crypto_stream_salsa20:C,crypto_onetimeauth:D,crypto_onetimeauth_verify:O,crypto_verify_16:h,crypto_verify_32:g,crypto_secretbox:k,crypto_secretbox_open:A,crypto_scalarmult:re,crypto_scalarmult_base:ie,crypto_box_beforenm:oe,crypto_box_afternm:se,crypto_box:le,crypto_box_open:ue,crypto_box_keypair:ae,crypto_hash:pe,crypto_sign:Ce,crypto_sign_keypair:ye,crypto_sign_open:Te,crypto_secretbox_KEYBYTES:Ee,crypto_secretbox_NONCEBYTES:De,crypto_secretbox_ZEROBYTES:Oe,crypto_secretbox_BOXZEROBYTES:ke,crypto_scalarmult_BYTES:Ae,crypto_scalarmult_SCALARBYTES:je,crypto_box_PUBLICKEYBYTES:Me,crypto_box_SECRETKEYBYTES:Ne,crypto_box_BEFORENMBYTES:Pe,crypto_box_NONCEBYTES:Fe,crypto_box_ZEROBYTES:Ie,crypto_box_BOXZEROBYTES:Le,crypto_sign_BYTES:Re,crypto_sign_PUBLICKEYBYTES:ze,crypto_sign_SECRETKEYBYTES:Be,crypto_sign_SEEDBYTES:Ve,crypto_hash_BYTES:He,gf:t,D:c,L:be,pack25519:P,unpack25519:L,M:B,A:R,S:V,Z:z,pow2523:ne,add:me,set25519:j,modL:xe,scalarmult:_e,scalarbase:ve};function Ue(e,t){if(e.length!==Ee)throw Error(`bad key size`);if(t.length!==De)throw Error(`bad nonce size`)}function We(e,t){if(e.length!==Me)throw Error(`bad public key size`);if(t.length!==Ne)throw Error(`bad secret key size`)}function Ge(){for(var e=0;e<arguments.length;e++)if(!(arguments[e]instanceof Uint8Array))throw TypeError(`unexpected type, use Uint8Array`)}function Ke(e){for(var t=0;t<e.length;t++)e[t]=0}e.randomBytes=function(e){var t=new Uint8Array(e);return n(t,e),t},e.secretbox=function(e,t,n){Ge(e,t,n),Ue(n,t);for(var r=new Uint8Array(Oe+e.length),i=new Uint8Array(r.length),a=0;a<e.length;a++)r[a+Oe]=e[a];return k(i,r,r.length,t,n),i.subarray(ke)},e.secretbox.open=function(e,t,n){Ge(e,t,n),Ue(n,t);for(var r=new Uint8Array(ke+e.length),i=new Uint8Array(r.length),a=0;a<e.length;a++)r[a+ke]=e[a];return r.length<32||A(i,r,r.length,t,n)!==0?null:i.subarray(Oe)},e.secretbox.keyLength=Ee,e.secretbox.nonceLength=De,e.secretbox.overheadLength=ke,e.scalarMult=function(e,t){if(Ge(e,t),e.length!==je)throw Error(`bad n size`);if(t.length!==Ae)throw Error(`bad p size`);var n=new Uint8Array(Ae);return re(n,e,t),n},e.scalarMult.base=function(e){if(Ge(e),e.length!==je)throw Error(`bad n size`);var t=new Uint8Array(Ae);return ie(t,e),t},e.scalarMult.scalarLength=je,e.scalarMult.groupElementLength=Ae,e.box=function(t,n,r,i){var a=e.box.before(r,i);return e.secretbox(t,n,a)},e.box.before=function(e,t){Ge(e,t),We(e,t);var n=new Uint8Array(Pe);return oe(n,e,t),n},e.box.after=e.secretbox,e.box.open=function(t,n,r,i){var a=e.box.before(r,i);return e.secretbox.open(t,n,a)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var e=new Uint8Array(Me),t=new Uint8Array(Ne);return ae(e,t),{publicKey:e,secretKey:t}},e.box.keyPair.fromSecretKey=function(e){if(Ge(e),e.length!==Ne)throw Error(`bad secret key size`);var t=new Uint8Array(Me);return ie(t,e),{publicKey:t,secretKey:new Uint8Array(e)}},e.box.publicKeyLength=Me,e.box.secretKeyLength=Ne,e.box.sharedKeyLength=Pe,e.box.nonceLength=Fe,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(e,t){if(Ge(e,t),t.length!==Be)throw Error(`bad secret key size`);var n=new Uint8Array(Re+e.length);return Ce(n,e,e.length,t),n},e.sign.open=function(e,t){if(Ge(e,t),t.length!==ze)throw Error(`bad public key size`);var n=new Uint8Array(e.length),r=Te(n,e,e.length,t);if(r<0)return null;for(var i=new Uint8Array(r),a=0;a<i.length;a++)i[a]=n[a];return i},e.sign.detached=function(t,n){for(var r=e.sign(t,n),i=new Uint8Array(Re),a=0;a<i.length;a++)i[a]=r[a];return i},e.sign.detached.verify=function(e,t,n){if(Ge(e,t,n),t.length!==Re)throw Error(`bad signature size`);if(n.length!==ze)throw Error(`bad public key size`);for(var r=new Uint8Array(Re+e.length),i=new Uint8Array(Re+e.length),a=0;a<Re;a++)r[a]=t[a];for(a=0;a<e.length;a++)r[a+Re]=e[a];return Te(i,r,r.length,n)>=0},e.sign.keyPair=function(){var e=new Uint8Array(ze),t=new Uint8Array(Be);return ye(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(Ge(e),e.length!==Be)throw Error(`bad secret key size`);for(var t=new Uint8Array(ze),n=0;n<t.length;n++)t[n]=e[32+n];return{publicKey:t,secretKey:new Uint8Array(e)}},e.sign.keyPair.fromSeed=function(e){if(Ge(e),e.length!==Ve)throw Error(`bad seed size`);for(var t=new Uint8Array(ze),n=new Uint8Array(Be),r=0;r<32;r++)n[r]=e[r];return ye(t,n,!0),{publicKey:t,secretKey:n}},e.sign.publicKeyLength=ze,e.sign.secretKeyLength=Be,e.sign.seedLength=Ve,e.sign.signatureLength=Re,e.hash=function(e){Ge(e);var t=new Uint8Array(He);return pe(t,e,e.length),t},e.hash.hashLength=He,e.verify=function(e,t){return Ge(e,t),e.length===0||t.length===0||e.length!==t.length?!1:m(e,0,t,0,e.length)===0},e.setPRNG=function(e){n=e},(function(){var t=typeof self<`u`?self.crypto||self.msCrypto:null;if(t&&t.getRandomValues){var n=65536;e.setPRNG(function(e,r){var i,a=new Uint8Array(r);for(i=0;i<r;i+=n)t.getRandomValues(a.subarray(i,i+Math.min(r-i,n)));for(i=0;i<r;i++)e[i]=a[i];Ke(a)})}else te!==void 0&&(t=te(`crypto`),t&&t.randomBytes&&e.setPRNG(function(e,n){var r,i=t.randomBytes(n);for(r=0;r<n;r++)e[r]=i[r];Ke(i)}))})()})(t!==void 0&&t.exports?t.exports:self.nacl=self.nacl||{})})),ni=R((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferVisitor=class{constructor(e,t=0,n=0){this.start=t,this.end=n>t?n:t,this.buf=e}get length(){return this.buf.length}reset(e=0,t=0){return this.start=e,t>=this.start?this.end=t:this.end<this.start&&(this.end=this.start),this}walk(e){return this.start=this.end,this.end+=e,this}mustHas(e,t=`Too few bytes to parse.`){let n=this.end+e;if(n>this.buf.length){let e=Error(t);throw e.available=this.buf.length,e.requested=n,e}return this.walk(0),this}mustWalk(e,t){return this.mustHas(e,t),this.walk(e),this}}})),ri=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=64,r=`-----BEGIN `,i=`-----END `,a=`-----`,o=`Proc-Type`,s=class{static parse(e){let t=[],n=e.toString(`utf8`).split(`
|
|
17
|
+
`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=bd()(e);var{formatters:d}=t.exports;d.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split(`
|
|
18
|
+
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})),Nd=R(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?xd():Md()})),Pd=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ne(`net`);function n(e){switch(t.isIP(e)){case 4:return Buffer.from(e.split(`.`).map(e=>parseInt(e,10)));case 6:let t=e.split(`:`),n=Buffer.alloc(16),r=0;t[t.length-1]===``&&(t[t.length-1]=`0`);for(let e=0;e<t.length;e++){if(t[e]===``){e+1<t.length&&t[e+1]!==``&&(r=16-(t.length-e-1)*2);continue}n.writeUInt16BE(parseInt(t[e],16),r),r+=2}return n;default:return null}}e.bytesFromIP=n;function r(e){switch(e.length){case 4:return[e[0],e[1],e[2],e[3]].join(`.`);case 16:let t=[],n=-1,r=0,i=-1,a=0;for(let o=0;o<e.length;o+=2){let s=e[o]<<8|e[o+1];s===0?(r++,n===-1&&(n=t.length),r>a&&(a=r,i=n)):(n=-1,r=0),t.push(s.toString(16))}if(a>0){let e=``,n=t.slice(i+a);t.length=i,t.length===0&&(e+=`:`),n.length===0&&(e+=`:`),t.push(e,...n)}return t.join(`:`);default:return``}}e.bytesToIP=r;var i=Object.create(null),a=/^[0-9.]+$/;function o(e){return a.test(e)&&i[e]!==``?e:i[e]==null?``:i[e]}e.getOID=o;function s(e){return!a.test(e)&&i[e]!==``||i[e]==null?e:i[e]}e.getOIDName=s;function c(e,t){i[e]=t,i[t]=e}c(`1.2.840.113549.1.1.1`,`rsaEncryption`),c(`1.2.840.113549.1.1.4`,`md5WithRsaEncryption`),c(`1.2.840.113549.1.1.5`,`sha1WithRsaEncryption`),c(`1.2.840.113549.1.1.8`,`mgf1`),c(`1.2.840.113549.1.1.10`,`RSASSA-PSS`),c(`1.2.840.113549.1.1.11`,`sha256WithRsaEncryption`),c(`1.2.840.113549.1.1.12`,`sha384WithRsaEncryption`),c(`1.2.840.113549.1.1.13`,`sha512WithRsaEncryption`),c(`1.2.840.10045.2.1`,`ecEncryption`),c(`1.2.840.10045.4.1`,`ecdsaWithSha1`),c(`1.2.840.10045.4.3.2`,`ecdsaWithSha256`),c(`1.2.840.10045.4.3.3`,`ecdsaWithSha384`),c(`1.2.840.10045.4.3.4`,`ecdsaWithSha512`),c(`1.2.840.10040.4.3`,`dsaWithSha1`),c(`2.16.840.1.101.3.4.3.2`,`dsaWithSha256`),c(`1.3.14.3.2.7`,`desCBC`),c(`1.3.14.3.2.26`,`sha1`),c(`2.16.840.1.101.3.4.2.1`,`sha256`),c(`2.16.840.1.101.3.4.2.2`,`sha384`),c(`2.16.840.1.101.3.4.2.3`,`sha512`),c(`1.2.840.113549.2.5`,`md5`),c(`1.3.101.110`,`X25519`),c(`1.3.101.111`,`X448`),c(`1.3.101.112`,`Ed25519`),c(`1.3.101.113`,`Ed448`),c(`1.2.840.113549.1.7.1`,`data`),c(`1.2.840.113549.1.7.2`,`signedData`),c(`1.2.840.113549.1.7.3`,`envelopedData`),c(`1.2.840.113549.1.7.4`,`signedAndEnvelopedData`),c(`1.2.840.113549.1.7.5`,`digestedData`),c(`1.2.840.113549.1.7.6`,`encryptedData`),c(`1.2.840.113549.1.9.1`,`emailAddress`),c(`1.2.840.113549.1.9.2`,`unstructuredName`),c(`1.2.840.113549.1.9.3`,`contentType`),c(`1.2.840.113549.1.9.4`,`messageDigest`),c(`1.2.840.113549.1.9.5`,`signingTime`),c(`1.2.840.113549.1.9.6`,`counterSignature`),c(`1.2.840.113549.1.9.7`,`challengePassword`),c(`1.2.840.113549.1.9.8`,`unstructuredAddress`),c(`1.2.840.113549.1.9.14`,`extensionRequest`),c(`1.2.840.113549.1.9.20`,`friendlyName`),c(`1.2.840.113549.1.9.21`,`localKeyId`),c(`1.2.840.113549.1.9.22.1`,`x509Certificate`),c(`1.2.840.113549.1.12.10.1.1`,`keyBag`),c(`1.2.840.113549.1.12.10.1.2`,`pkcs8ShroudedKeyBag`),c(`1.2.840.113549.1.12.10.1.3`,`certBag`),c(`1.2.840.113549.1.12.10.1.4`,`crlBag`),c(`1.2.840.113549.1.12.10.1.5`,`secretBag`),c(`1.2.840.113549.1.12.10.1.6`,`safeContentsBag`),c(`1.2.840.113549.1.5.13`,`pkcs5PBES2`),c(`1.2.840.113549.1.5.12`,`pkcs5PBKDF2`),c(`1.2.840.113549.2.7`,`hmacWithSha1`),c(`1.2.840.113549.2.9`,`hmacWithSha256`),c(`1.2.840.113549.2.10`,`hmacWithSha384`),c(`1.2.840.113549.2.11`,`hmacWithSha512`),c(`1.2.840.113549.3.7`,`3desCBC`),c(`2.16.840.1.101.3.4.1.2`,`aesCBC128`),c(`2.16.840.1.101.3.4.1.42`,`aesCBC256`),c(`2.5.4.3`,`commonName`),c(`2.5.4.5`,`serialName`),c(`2.5.4.6`,`countryName`),c(`2.5.4.7`,`localityName`),c(`2.5.4.8`,`stateOrProvinceName`),c(`2.5.4.10`,`organizationName`),c(`2.5.4.11`,`organizationalUnitName`),c(`2.5.4.15`,`businessCategory`),c(`2.16.840.1.113730.1.1`,`nsCertType`),c(`2.5.29.2`,`keyAttributes`),c(`2.5.29.4`,`keyUsageRestriction`),c(`2.5.29.6`,`subtreesConstraint`),c(`2.5.29.9`,`subjectDirectoryAttributes`),c(`2.5.29.14`,`subjectKeyIdentifier`),c(`2.5.29.15`,`keyUsage`),c(`2.5.29.16`,`privateKeyUsagePeriod`),c(`2.5.29.17`,`subjectAltName`),c(`2.5.29.18`,`issuerAltName`),c(`2.5.29.19`,`basicConstraints`),c(`2.5.29.20`,`cRLNumber`),c(`2.5.29.21`,`cRLReason`),c(`2.5.29.22`,`expirationDate`),c(`2.5.29.23`,`instructionCode`),c(`2.5.29.24`,`invalidityDate`),c(`2.5.29.27`,`deltaCRLIndicator`),c(`2.5.29.28`,`issuingDistributionPoint`),c(`2.5.29.29`,`certificateIssuer`),c(`2.5.29.30`,`nameConstraints`),c(`2.5.29.31`,`cRLDistributionPoints`),c(`2.5.29.32`,`certificatePolicies`),c(`2.5.29.33`,`policyMappings`),c(`2.5.29.35`,`authorityKeyIdentifier`),c(`2.5.29.36`,`policyConstraints`),c(`2.5.29.37`,`extKeyUsage`),c(`2.5.29.46`,`freshestCRL`),c(`2.5.29.54`,`inhibitAnyPolicy`),c(`1.3.6.1.4.1.311.60.2.1.2`,`jurisdictionST`),c(`1.3.6.1.4.1.311.60.2.1.3`,`jurisdictionC`),c(`1.3.6.1.4.1.11129.2.4.2`,`timestampList`),c(`1.3.6.1.5.5.7.1.1`,`authorityInfoAccess`),c(`1.3.6.1.5.5.7.3.1`,`serverAuth`),c(`1.3.6.1.5.5.7.3.2`,`clientAuth`),c(`1.3.6.1.5.5.7.3.3`,`codeSigning`),c(`1.3.6.1.5.5.7.3.4`,`emailProtection`),c(`1.3.6.1.5.5.7.3.8`,`timeStamping`),c(`1.3.6.1.5.5.7.48.1`,`authorityInfoAccessOcsp`),c(`1.3.6.1.5.5.7.48.2`,`authorityInfoAccessIssuers`)})),Fd=R(((e,t)=>{(function(e){var t=function(e){var t,n=new Float64Array(16);if(e)for(t=0;t<e.length;t++)n[t]=e[t];return n},n=function(){throw Error(`no PRNG`)},r=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var a=t(),o=t([1]),s=t([56129,1]),c=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),l=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),u=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),d=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function p(e,t,n,r){e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255,e[t+4]=r>>24&255,e[t+5]=r>>16&255,e[t+6]=r>>8&255,e[t+7]=r&255}function m(e,t,n,r,i){var a,o=0;for(a=0;a<i;a++)o|=e[t+a]^n[r+a];return(1&o-1>>>8)-1}function h(e,t,n,r){return m(e,t,n,r,16)}function g(e,t,n,r){return m(e,t,n,r,32)}function _(e,t,n,r){for(var i=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,a=n[0]&255|(n[1]&255)<<8|(n[2]&255)<<16|(n[3]&255)<<24,o=n[4]&255|(n[5]&255)<<8|(n[6]&255)<<16|(n[7]&255)<<24,s=n[8]&255|(n[9]&255)<<8|(n[10]&255)<<16|(n[11]&255)<<24,c=n[12]&255|(n[13]&255)<<8|(n[14]&255)<<16|(n[15]&255)<<24,l=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,u=t[0]&255|(t[1]&255)<<8|(t[2]&255)<<16|(t[3]&255)<<24,d=t[4]&255|(t[5]&255)<<8|(t[6]&255)<<16|(t[7]&255)<<24,f=t[8]&255|(t[9]&255)<<8|(t[10]&255)<<16|(t[11]&255)<<24,p=t[12]&255|(t[13]&255)<<8|(t[14]&255)<<16|(t[15]&255)<<24,m=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,h=n[16]&255|(n[17]&255)<<8|(n[18]&255)<<16|(n[19]&255)<<24,g=n[20]&255|(n[21]&255)<<8|(n[22]&255)<<16|(n[23]&255)<<24,_=n[24]&255|(n[25]&255)<<8|(n[26]&255)<<16|(n[27]&255)<<24,v=n[28]&255|(n[29]&255)<<8|(n[30]&255)<<16|(n[31]&255)<<24,y=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24,b=i,x=a,S=o,C=s,w=c,T=l,E=u,D=d,O=f,k=p,A=m,j=h,M=g,N=_,P=v,F=y,I,L=0;L<20;L+=2)I=b+M|0,w^=I<<7|I>>>25,I=w+b|0,O^=I<<9|I>>>23,I=O+w|0,M^=I<<13|I>>>19,I=M+O|0,b^=I<<18|I>>>14,I=T+x|0,k^=I<<7|I>>>25,I=k+T|0,N^=I<<9|I>>>23,I=N+k|0,x^=I<<13|I>>>19,I=x+N|0,T^=I<<18|I>>>14,I=A+E|0,P^=I<<7|I>>>25,I=P+A|0,S^=I<<9|I>>>23,I=S+P|0,E^=I<<13|I>>>19,I=E+S|0,A^=I<<18|I>>>14,I=F+j|0,C^=I<<7|I>>>25,I=C+F|0,D^=I<<9|I>>>23,I=D+C|0,j^=I<<13|I>>>19,I=j+D|0,F^=I<<18|I>>>14,I=b+C|0,x^=I<<7|I>>>25,I=x+b|0,S^=I<<9|I>>>23,I=S+x|0,C^=I<<13|I>>>19,I=C+S|0,b^=I<<18|I>>>14,I=T+w|0,E^=I<<7|I>>>25,I=E+T|0,D^=I<<9|I>>>23,I=D+E|0,w^=I<<13|I>>>19,I=w+D|0,T^=I<<18|I>>>14,I=A+k|0,j^=I<<7|I>>>25,I=j+A|0,O^=I<<9|I>>>23,I=O+j|0,k^=I<<13|I>>>19,I=k+O|0,A^=I<<18|I>>>14,I=F+P|0,M^=I<<7|I>>>25,I=M+F|0,N^=I<<9|I>>>23,I=N+M|0,P^=I<<13|I>>>19,I=P+N|0,F^=I<<18|I>>>14;b=b+i|0,x=x+a|0,S=S+o|0,C=C+s|0,w=w+c|0,T=T+l|0,E=E+u|0,D=D+d|0,O=O+f|0,k=k+p|0,A=A+m|0,j=j+h|0,M=M+g|0,N=N+_|0,P=P+v|0,F=F+y|0,e[0]=b>>>0&255,e[1]=b>>>8&255,e[2]=b>>>16&255,e[3]=b>>>24&255,e[4]=x>>>0&255,e[5]=x>>>8&255,e[6]=x>>>16&255,e[7]=x>>>24&255,e[8]=S>>>0&255,e[9]=S>>>8&255,e[10]=S>>>16&255,e[11]=S>>>24&255,e[12]=C>>>0&255,e[13]=C>>>8&255,e[14]=C>>>16&255,e[15]=C>>>24&255,e[16]=w>>>0&255,e[17]=w>>>8&255,e[18]=w>>>16&255,e[19]=w>>>24&255,e[20]=T>>>0&255,e[21]=T>>>8&255,e[22]=T>>>16&255,e[23]=T>>>24&255,e[24]=E>>>0&255,e[25]=E>>>8&255,e[26]=E>>>16&255,e[27]=E>>>24&255,e[28]=D>>>0&255,e[29]=D>>>8&255,e[30]=D>>>16&255,e[31]=D>>>24&255,e[32]=O>>>0&255,e[33]=O>>>8&255,e[34]=O>>>16&255,e[35]=O>>>24&255,e[36]=k>>>0&255,e[37]=k>>>8&255,e[38]=k>>>16&255,e[39]=k>>>24&255,e[40]=A>>>0&255,e[41]=A>>>8&255,e[42]=A>>>16&255,e[43]=A>>>24&255,e[44]=j>>>0&255,e[45]=j>>>8&255,e[46]=j>>>16&255,e[47]=j>>>24&255,e[48]=M>>>0&255,e[49]=M>>>8&255,e[50]=M>>>16&255,e[51]=M>>>24&255,e[52]=N>>>0&255,e[53]=N>>>8&255,e[54]=N>>>16&255,e[55]=N>>>24&255,e[56]=P>>>0&255,e[57]=P>>>8&255,e[58]=P>>>16&255,e[59]=P>>>24&255,e[60]=F>>>0&255,e[61]=F>>>8&255,e[62]=F>>>16&255,e[63]=F>>>24&255}function v(e,t,n,r){for(var i=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,a=n[0]&255|(n[1]&255)<<8|(n[2]&255)<<16|(n[3]&255)<<24,o=n[4]&255|(n[5]&255)<<8|(n[6]&255)<<16|(n[7]&255)<<24,s=n[8]&255|(n[9]&255)<<8|(n[10]&255)<<16|(n[11]&255)<<24,c=n[12]&255|(n[13]&255)<<8|(n[14]&255)<<16|(n[15]&255)<<24,l=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,u=t[0]&255|(t[1]&255)<<8|(t[2]&255)<<16|(t[3]&255)<<24,d=t[4]&255|(t[5]&255)<<8|(t[6]&255)<<16|(t[7]&255)<<24,f=t[8]&255|(t[9]&255)<<8|(t[10]&255)<<16|(t[11]&255)<<24,p=t[12]&255|(t[13]&255)<<8|(t[14]&255)<<16|(t[15]&255)<<24,m=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,h=n[16]&255|(n[17]&255)<<8|(n[18]&255)<<16|(n[19]&255)<<24,g=n[20]&255|(n[21]&255)<<8|(n[22]&255)<<16|(n[23]&255)<<24,_=n[24]&255|(n[25]&255)<<8|(n[26]&255)<<16|(n[27]&255)<<24,v=n[28]&255|(n[29]&255)<<8|(n[30]&255)<<16|(n[31]&255)<<24,y=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24,b=i,x=a,S=o,C=s,w=c,T=l,E=u,D=d,O=f,k=p,A=m,j=h,M=g,N=_,P=v,F=y,I,L=0;L<20;L+=2)I=b+M|0,w^=I<<7|I>>>25,I=w+b|0,O^=I<<9|I>>>23,I=O+w|0,M^=I<<13|I>>>19,I=M+O|0,b^=I<<18|I>>>14,I=T+x|0,k^=I<<7|I>>>25,I=k+T|0,N^=I<<9|I>>>23,I=N+k|0,x^=I<<13|I>>>19,I=x+N|0,T^=I<<18|I>>>14,I=A+E|0,P^=I<<7|I>>>25,I=P+A|0,S^=I<<9|I>>>23,I=S+P|0,E^=I<<13|I>>>19,I=E+S|0,A^=I<<18|I>>>14,I=F+j|0,C^=I<<7|I>>>25,I=C+F|0,D^=I<<9|I>>>23,I=D+C|0,j^=I<<13|I>>>19,I=j+D|0,F^=I<<18|I>>>14,I=b+C|0,x^=I<<7|I>>>25,I=x+b|0,S^=I<<9|I>>>23,I=S+x|0,C^=I<<13|I>>>19,I=C+S|0,b^=I<<18|I>>>14,I=T+w|0,E^=I<<7|I>>>25,I=E+T|0,D^=I<<9|I>>>23,I=D+E|0,w^=I<<13|I>>>19,I=w+D|0,T^=I<<18|I>>>14,I=A+k|0,j^=I<<7|I>>>25,I=j+A|0,O^=I<<9|I>>>23,I=O+j|0,k^=I<<13|I>>>19,I=k+O|0,A^=I<<18|I>>>14,I=F+P|0,M^=I<<7|I>>>25,I=M+F|0,N^=I<<9|I>>>23,I=N+M|0,P^=I<<13|I>>>19,I=P+N|0,F^=I<<18|I>>>14;e[0]=b>>>0&255,e[1]=b>>>8&255,e[2]=b>>>16&255,e[3]=b>>>24&255,e[4]=T>>>0&255,e[5]=T>>>8&255,e[6]=T>>>16&255,e[7]=T>>>24&255,e[8]=A>>>0&255,e[9]=A>>>8&255,e[10]=A>>>16&255,e[11]=A>>>24&255,e[12]=F>>>0&255,e[13]=F>>>8&255,e[14]=F>>>16&255,e[15]=F>>>24&255,e[16]=E>>>0&255,e[17]=E>>>8&255,e[18]=E>>>16&255,e[19]=E>>>24&255,e[20]=D>>>0&255,e[21]=D>>>8&255,e[22]=D>>>16&255,e[23]=D>>>24&255,e[24]=O>>>0&255,e[25]=O>>>8&255,e[26]=O>>>16&255,e[27]=O>>>24&255,e[28]=k>>>0&255,e[29]=k>>>8&255,e[30]=k>>>16&255,e[31]=k>>>24&255}function y(e,t,n,r){_(e,t,n,r)}function b(e,t,n,r){v(e,t,n,r)}var x=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(e,t,n,r,i,a,o){for(var s=new Uint8Array(16),c=new Uint8Array(64),l,u=0;u<16;u++)s[u]=0;for(u=0;u<8;u++)s[u]=a[u];for(;i>=64;){for(y(c,s,o,x),u=0;u<64;u++)e[t+u]=n[r+u]^c[u];for(l=1,u=8;u<16;u++)l=l+(s[u]&255)|0,s[u]=l&255,l>>>=8;i-=64,t+=64,r+=64}if(i>0)for(y(c,s,o,x),u=0;u<i;u++)e[t+u]=n[r+u]^c[u];return 0}function C(e,t,n,r,i){for(var a=new Uint8Array(16),o=new Uint8Array(64),s,c=0;c<16;c++)a[c]=0;for(c=0;c<8;c++)a[c]=r[c];for(;n>=64;){for(y(o,a,i,x),c=0;c<64;c++)e[t+c]=o[c];for(s=1,c=8;c<16;c++)s=s+(a[c]&255)|0,a[c]=s&255,s>>>=8;n-=64,t+=64}if(n>0)for(y(o,a,i,x),c=0;c<n;c++)e[t+c]=o[c];return 0}function w(e,t,n,r,i){var a=new Uint8Array(32);b(a,r,i,x);for(var o=new Uint8Array(8),s=0;s<8;s++)o[s]=r[s+16];return C(e,t,n,o,a)}function T(e,t,n,r,i,a,o){var s=new Uint8Array(32);b(s,a,o,x);for(var c=new Uint8Array(8),l=0;l<8;l++)c[l]=a[l+16];return S(e,t,n,r,i,c,s)}var E=function(e){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 t=e[0]&255|(e[1]&255)<<8,n,r,i,a,o,s,c;this.r[0]=t&8191,n=e[2]&255|(e[3]&255)<<8,this.r[1]=(t>>>13|n<<3)&8191,r=e[4]&255|(e[5]&255)<<8,this.r[2]=(n>>>10|r<<6)&7939,i=e[6]&255|(e[7]&255)<<8,this.r[3]=(r>>>7|i<<9)&8191,a=e[8]&255|(e[9]&255)<<8,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,o=e[10]&255|(e[11]&255)<<8,this.r[6]=(a>>>14|o<<2)&8191,s=e[12]&255|(e[13]&255)<<8,this.r[7]=(o>>>11|s<<5)&8065,c=e[14]&255|(e[15]&255)<<8,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127,this.pad[0]=e[16]&255|(e[17]&255)<<8,this.pad[1]=e[18]&255|(e[19]&255)<<8,this.pad[2]=e[20]&255|(e[21]&255)<<8,this.pad[3]=e[22]&255|(e[23]&255)<<8,this.pad[4]=e[24]&255|(e[25]&255)<<8,this.pad[5]=e[26]&255|(e[27]&255)<<8,this.pad[6]=e[28]&255|(e[29]&255)<<8,this.pad[7]=e[30]&255|(e[31]&255)<<8};E.prototype.blocks=function(e,t,n){for(var r=this.fin?0:2048,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C=this.h[0],w=this.h[1],T=this.h[2],E=this.h[3],D=this.h[4],O=this.h[5],k=this.h[6],A=this.h[7],j=this.h[8],M=this.h[9],N=this.r[0],P=this.r[1],F=this.r[2],I=this.r[3],L=this.r[4],R=this.r[5],ee=this.r[6],z=this.r[7],B=this.r[8],te=this.r[9];n>=16;)i=e[t+0]&255|(e[t+1]&255)<<8,C+=i&8191,a=e[t+2]&255|(e[t+3]&255)<<8,w+=(i>>>13|a<<3)&8191,o=e[t+4]&255|(e[t+5]&255)<<8,T+=(a>>>10|o<<6)&8191,s=e[t+6]&255|(e[t+7]&255)<<8,E+=(o>>>7|s<<9)&8191,c=e[t+8]&255|(e[t+9]&255)<<8,D+=(s>>>4|c<<12)&8191,O+=c>>>1&8191,l=e[t+10]&255|(e[t+11]&255)<<8,k+=(c>>>14|l<<2)&8191,u=e[t+12]&255|(e[t+13]&255)<<8,A+=(l>>>11|u<<5)&8191,d=e[t+14]&255|(e[t+15]&255)<<8,j+=(u>>>8|d<<8)&8191,M+=d>>>5|r,f=0,p=f,p+=C*N,p+=5*te*w,p+=5*B*T,p+=5*z*E,p+=5*ee*D,f=p>>>13,p&=8191,p+=5*R*O,p+=5*L*k,p+=5*I*A,p+=5*F*j,p+=5*P*M,f+=p>>>13,p&=8191,m=f,m+=C*P,m+=w*N,m+=5*te*T,m+=5*B*E,m+=5*z*D,f=m>>>13,m&=8191,m+=5*ee*O,m+=5*R*k,m+=5*L*A,m+=5*I*j,m+=5*F*M,f+=m>>>13,m&=8191,h=f,h+=C*F,h+=w*P,h+=T*N,h+=5*te*E,h+=5*B*D,f=h>>>13,h&=8191,h+=5*z*O,h+=5*ee*k,h+=5*R*A,h+=5*L*j,h+=5*I*M,f+=h>>>13,h&=8191,g=f,g+=C*I,g+=w*F,g+=T*P,g+=E*N,g+=5*te*D,f=g>>>13,g&=8191,g+=5*B*O,g+=5*z*k,g+=5*ee*A,g+=5*R*j,g+=5*L*M,f+=g>>>13,g&=8191,_=f,_+=C*L,_+=w*I,_+=T*F,_+=E*P,_+=D*N,f=_>>>13,_&=8191,_+=5*te*O,_+=5*B*k,_+=5*z*A,_+=5*ee*j,_+=5*R*M,f+=_>>>13,_&=8191,v=f,v+=C*R,v+=w*L,v+=T*I,v+=E*F,v+=D*P,f=v>>>13,v&=8191,v+=O*N,v+=5*te*k,v+=5*B*A,v+=5*z*j,v+=5*ee*M,f+=v>>>13,v&=8191,y=f,y+=C*ee,y+=w*R,y+=T*L,y+=E*I,y+=D*F,f=y>>>13,y&=8191,y+=O*P,y+=k*N,y+=5*te*A,y+=5*B*j,y+=5*z*M,f+=y>>>13,y&=8191,b=f,b+=C*z,b+=w*ee,b+=T*R,b+=E*L,b+=D*I,f=b>>>13,b&=8191,b+=O*F,b+=k*P,b+=A*N,b+=5*te*j,b+=5*B*M,f+=b>>>13,b&=8191,x=f,x+=C*B,x+=w*z,x+=T*ee,x+=E*R,x+=D*L,f=x>>>13,x&=8191,x+=O*I,x+=k*F,x+=A*P,x+=j*N,x+=5*te*M,f+=x>>>13,x&=8191,S=f,S+=C*te,S+=w*B,S+=T*z,S+=E*ee,S+=D*R,f=S>>>13,S&=8191,S+=O*L,S+=k*I,S+=A*F,S+=j*P,S+=M*N,f+=S>>>13,S&=8191,f=(f<<2)+f|0,f=f+p|0,p=f&8191,f>>>=13,m+=f,C=p,w=m,T=h,E=g,D=_,O=v,k=y,A=b,j=x,M=S,t+=16,n-=16;this.h[0]=C,this.h[1]=w,this.h[2]=T,this.h[3]=E,this.h[4]=D,this.h[5]=O,this.h[6]=k,this.h[7]=A,this.h[8]=j,this.h[9]=M},E.prototype.finish=function(e,t){var n=new Uint16Array(10),r,i,a,o;if(this.leftover){for(o=this.leftover,this.buffer[o++]=1;o<16;o++)this.buffer[o]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,o=2;o<10;o++)this.h[o]+=r,r=this.h[o]>>>13,this.h[o]&=8191;for(this.h[0]+=r*5,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,n[0]=this.h[0]+5,r=n[0]>>>13,n[0]&=8191,o=1;o<10;o++)n[o]=this.h[o]+r,r=n[o]>>>13,n[o]&=8191;for(n[9]-=8192,i=(r^1)-1,o=0;o<10;o++)n[o]&=i;for(i=~i,o=0;o<10;o++)this.h[o]=this.h[o]&i|n[o];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,a=this.h[0]+this.pad[0],this.h[0]=a&65535,o=1;o<8;o++)a=(this.h[o]+this.pad[o]|0)+(a>>>16)|0,this.h[o]=a&65535;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},E.prototype.update=function(e,t,n){var r,i;if(this.leftover){for(i=16-this.leftover,i>n&&(i=n),r=0;r<i;r++)this.buffer[this.leftover+r]=e[t+r];if(n-=i,t+=i,this.leftover+=i,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(n>=16&&(i=n-n%16,this.blocks(e,t,i),t+=i,n-=i),n){for(r=0;r<n;r++)this.buffer[this.leftover+r]=e[t+r];this.leftover+=n}};function D(e,t,n,r,i,a){var o=new E(a);return o.update(n,r,i),o.finish(e,t),0}function O(e,t,n,r,i,a){var o=new Uint8Array(16);return D(o,0,n,r,i,a),h(e,t,o,0)}function k(e,t,n,r,i){var a;if(n<32)return-1;for(T(e,0,t,0,n,r,i),D(e,16,e,32,n-32,e),a=0;a<16;a++)e[a]=0;return 0}function A(e,t,n,r,i){var a,o=new Uint8Array(32);if(n<32||(w(o,0,32,r,i),O(t,16,t,32,n-32,o)!==0))return-1;for(T(e,0,t,0,n,r,i),a=0;a<32;a++)e[a]=0;return 0}function j(e,t){for(var n=0;n<16;n++)e[n]=t[n]|0}function M(e){var t,n,r=1;for(t=0;t<16;t++)n=e[t]+r+65535,r=Math.floor(n/65536),e[t]=n-r*65536;e[0]+=r-1+37*(r-1)}function N(e,t,n){for(var r,i=~(n-1),a=0;a<16;a++)r=i&(e[a]^t[a]),e[a]^=r,t[a]^=r}function P(e,n){var r,i,a,o=t(),s=t();for(r=0;r<16;r++)s[r]=n[r];for(M(s),M(s),M(s),i=0;i<2;i++){for(o[0]=s[0]-65517,r=1;r<15;r++)o[r]=s[r]-65535-(o[r-1]>>16&1),o[r-1]&=65535;o[15]=s[15]-32767-(o[14]>>16&1),a=o[15]>>16&1,o[14]&=65535,N(s,o,1-a)}for(r=0;r<16;r++)e[2*r]=s[r]&255,e[2*r+1]=s[r]>>8}function F(e,t){var n=new Uint8Array(32),r=new Uint8Array(32);return P(n,e),P(r,t),g(n,0,r,0)}function I(e){var t=new Uint8Array(32);return P(t,e),t[0]&1}function L(e,t){for(var n=0;n<16;n++)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function R(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]+n[r]}function ee(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]-n[r]}function z(e,t,n){var r,i,a=0,o=0,s=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0,S=0,C=0,w=0,T=0,E=0,D=0,O=0,k=0,A=0,j=0,M=0,N=0,P=0,F=0,I=n[0],L=n[1],R=n[2],ee=n[3],z=n[4],B=n[5],te=n[6],ne=n[7],re=n[8],ie=n[9],ae=n[10],oe=n[11],se=n[12],ce=n[13],le=n[14],ue=n[15];r=t[0],a+=r*I,o+=r*L,s+=r*R,c+=r*ee,l+=r*z,u+=r*B,d+=r*te,f+=r*ne,p+=r*re,m+=r*ie,h+=r*ae,g+=r*oe,_+=r*se,v+=r*ce,y+=r*le,b+=r*ue,r=t[1],o+=r*I,s+=r*L,c+=r*R,l+=r*ee,u+=r*z,d+=r*B,f+=r*te,p+=r*ne,m+=r*re,h+=r*ie,g+=r*ae,_+=r*oe,v+=r*se,y+=r*ce,b+=r*le,x+=r*ue,r=t[2],s+=r*I,c+=r*L,l+=r*R,u+=r*ee,d+=r*z,f+=r*B,p+=r*te,m+=r*ne,h+=r*re,g+=r*ie,_+=r*ae,v+=r*oe,y+=r*se,b+=r*ce,x+=r*le,S+=r*ue,r=t[3],c+=r*I,l+=r*L,u+=r*R,d+=r*ee,f+=r*z,p+=r*B,m+=r*te,h+=r*ne,g+=r*re,_+=r*ie,v+=r*ae,y+=r*oe,b+=r*se,x+=r*ce,S+=r*le,C+=r*ue,r=t[4],l+=r*I,u+=r*L,d+=r*R,f+=r*ee,p+=r*z,m+=r*B,h+=r*te,g+=r*ne,_+=r*re,v+=r*ie,y+=r*ae,b+=r*oe,x+=r*se,S+=r*ce,C+=r*le,w+=r*ue,r=t[5],u+=r*I,d+=r*L,f+=r*R,p+=r*ee,m+=r*z,h+=r*B,g+=r*te,_+=r*ne,v+=r*re,y+=r*ie,b+=r*ae,x+=r*oe,S+=r*se,C+=r*ce,w+=r*le,T+=r*ue,r=t[6],d+=r*I,f+=r*L,p+=r*R,m+=r*ee,h+=r*z,g+=r*B,_+=r*te,v+=r*ne,y+=r*re,b+=r*ie,x+=r*ae,S+=r*oe,C+=r*se,w+=r*ce,T+=r*le,E+=r*ue,r=t[7],f+=r*I,p+=r*L,m+=r*R,h+=r*ee,g+=r*z,_+=r*B,v+=r*te,y+=r*ne,b+=r*re,x+=r*ie,S+=r*ae,C+=r*oe,w+=r*se,T+=r*ce,E+=r*le,D+=r*ue,r=t[8],p+=r*I,m+=r*L,h+=r*R,g+=r*ee,_+=r*z,v+=r*B,y+=r*te,b+=r*ne,x+=r*re,S+=r*ie,C+=r*ae,w+=r*oe,T+=r*se,E+=r*ce,D+=r*le,O+=r*ue,r=t[9],m+=r*I,h+=r*L,g+=r*R,_+=r*ee,v+=r*z,y+=r*B,b+=r*te,x+=r*ne,S+=r*re,C+=r*ie,w+=r*ae,T+=r*oe,E+=r*se,D+=r*ce,O+=r*le,k+=r*ue,r=t[10],h+=r*I,g+=r*L,_+=r*R,v+=r*ee,y+=r*z,b+=r*B,x+=r*te,S+=r*ne,C+=r*re,w+=r*ie,T+=r*ae,E+=r*oe,D+=r*se,O+=r*ce,k+=r*le,A+=r*ue,r=t[11],g+=r*I,_+=r*L,v+=r*R,y+=r*ee,b+=r*z,x+=r*B,S+=r*te,C+=r*ne,w+=r*re,T+=r*ie,E+=r*ae,D+=r*oe,O+=r*se,k+=r*ce,A+=r*le,j+=r*ue,r=t[12],_+=r*I,v+=r*L,y+=r*R,b+=r*ee,x+=r*z,S+=r*B,C+=r*te,w+=r*ne,T+=r*re,E+=r*ie,D+=r*ae,O+=r*oe,k+=r*se,A+=r*ce,j+=r*le,M+=r*ue,r=t[13],v+=r*I,y+=r*L,b+=r*R,x+=r*ee,S+=r*z,C+=r*B,w+=r*te,T+=r*ne,E+=r*re,D+=r*ie,O+=r*ae,k+=r*oe,A+=r*se,j+=r*ce,M+=r*le,N+=r*ue,r=t[14],y+=r*I,b+=r*L,x+=r*R,S+=r*ee,C+=r*z,w+=r*B,T+=r*te,E+=r*ne,D+=r*re,O+=r*ie,k+=r*ae,A+=r*oe,j+=r*se,M+=r*ce,N+=r*le,P+=r*ue,r=t[15],b+=r*I,x+=r*L,S+=r*R,C+=r*ee,w+=r*z,T+=r*B,E+=r*te,D+=r*ne,O+=r*re,k+=r*ie,A+=r*ae,j+=r*oe,M+=r*se,N+=r*ce,P+=r*le,F+=r*ue,a+=38*x,o+=38*S,s+=38*C,c+=38*w,l+=38*T,u+=38*E,d+=38*D,f+=38*O,p+=38*k,m+=38*A,h+=38*j,g+=38*M,_+=38*N,v+=38*P,y+=38*F,i=1,r=a+i+65535,i=Math.floor(r/65536),a=r-i*65536,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=m+i+65535,i=Math.floor(r/65536),m=r-i*65536,r=h+i+65535,i=Math.floor(r/65536),h=r-i*65536,r=g+i+65535,i=Math.floor(r/65536),g=r-i*65536,r=_+i+65535,i=Math.floor(r/65536),_=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=y+i+65535,i=Math.floor(r/65536),y=r-i*65536,r=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,a+=i-1+37*(i-1),i=1,r=a+i+65535,i=Math.floor(r/65536),a=r-i*65536,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=m+i+65535,i=Math.floor(r/65536),m=r-i*65536,r=h+i+65535,i=Math.floor(r/65536),h=r-i*65536,r=g+i+65535,i=Math.floor(r/65536),g=r-i*65536,r=_+i+65535,i=Math.floor(r/65536),_=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=y+i+65535,i=Math.floor(r/65536),y=r-i*65536,r=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,a+=i-1+37*(i-1),e[0]=a,e[1]=o,e[2]=s,e[3]=c,e[4]=l,e[5]=u,e[6]=d,e[7]=f,e[8]=p,e[9]=m,e[10]=h,e[11]=g,e[12]=_,e[13]=v,e[14]=y,e[15]=b}function B(e,t){z(e,t,t)}function te(e,n){for(var r=t(),i=0;i<16;i++)r[i]=n[i];for(i=253;i>=0;i--)B(r,r),i!==2&&i!==4&&z(r,r,n);for(i=0;i<16;i++)e[i]=r[i]}function re(e,n){for(var r=t(),i=0;i<16;i++)r[i]=n[i];for(i=250;i>=0;i--)B(r,r),i!==1&&z(r,r,n);for(i=0;i<16;i++)e[i]=r[i]}function ie(e,n,r){var i=new Uint8Array(32),a=new Float64Array(80),o,c,l=t(),u=t(),d=t(),f=t(),p=t(),m=t();for(c=0;c<31;c++)i[c]=n[c];for(i[31]=n[31]&127|64,i[0]&=248,L(a,r),c=0;c<16;c++)u[c]=a[c],f[c]=l[c]=d[c]=0;for(l[0]=f[0]=1,c=254;c>=0;--c)o=i[c>>>3]>>>(c&7)&1,N(l,u,o),N(d,f,o),R(p,l,d),ee(l,l,d),R(d,u,f),ee(u,u,f),B(f,p),B(m,l),z(l,d,l),z(d,u,p),R(p,l,d),ee(l,l,d),B(u,l),ee(d,f,m),z(l,d,s),R(l,l,f),z(d,d,l),z(l,f,m),z(f,u,a),B(u,p),N(l,u,o),N(d,f,o);for(c=0;c<16;c++)a[c+16]=l[c],a[c+32]=d[c],a[c+48]=u[c],a[c+64]=f[c];var h=a.subarray(32),g=a.subarray(16);return te(h,h),z(g,g,h),P(e,g),0}function ae(e,t){return ie(e,t,i)}function oe(e,t){return n(t,32),ae(e,t)}function se(e,t,n){var i=new Uint8Array(32);return ie(i,n,t),b(e,r,i,x)}var ce=k,le=A;function ue(e,t,n,r,i,a){var o=new Uint8Array(32);return se(o,i,a),ce(e,t,n,r,o)}function de(e,t,n,r,i,a){var o=new Uint8Array(32);return se(o,i,a),le(e,t,n,r,o)}var fe=[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 pe(e,t,n,r){for(var i=new Int32Array(16),a=new Int32Array(16),o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M=e[0],N=e[1],P=e[2],F=e[3],I=e[4],L=e[5],R=e[6],ee=e[7],z=t[0],B=t[1],te=t[2],ne=t[3],re=t[4],ie=t[5],ae=t[6],oe=t[7],se=0;r>=128;){for(w=0;w<16;w++)T=8*w+se,i[w]=n[T+0]<<24|n[T+1]<<16|n[T+2]<<8|n[T+3],a[w]=n[T+4]<<24|n[T+5]<<16|n[T+6]<<8|n[T+7];for(w=0;w<80;w++)if(o=M,s=N,c=P,l=F,u=I,d=L,f=R,p=ee,m=z,h=B,g=te,_=ne,v=re,y=ie,b=ae,x=oe,E=ee,D=oe,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=(I>>>14|re<<18)^(I>>>18|re<<14)^(re>>>9|I<<23),D=(re>>>14|I<<18)^(re>>>18|I<<14)^(I>>>9|re<<23),O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,E=I&L^~I&R,D=re&ie^~re&ae,O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,E=fe[w*2],D=fe[w*2+1],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,E=i[w%16],D=a[w%16],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,S=A&65535|j<<16,C=O&65535|k<<16,E=S,D=C,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=(M>>>28|z<<4)^(z>>>2|M<<30)^(z>>>7|M<<25),D=(z>>>28|M<<4)^(M>>>2|z<<30)^(M>>>7|z<<25),O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,E=M&N^M&P^N&P,D=z&B^z&te^B&te,O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,p=A&65535|j<<16,x=O&65535|k<<16,E=l,D=_,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=S,D=C,O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,l=A&65535|j<<16,_=O&65535|k<<16,N=o,P=s,F=c,I=l,L=u,R=d,ee=f,M=p,B=m,te=h,ne=g,re=_,ie=v,ae=y,oe=b,z=x,w%16==15)for(T=0;T<16;T++)E=i[T],D=a[T],O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=i[(T+9)%16],D=a[(T+9)%16],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,S=i[(T+1)%16],C=a[(T+1)%16],E=(S>>>1|C<<31)^(S>>>8|C<<24)^S>>>7,D=(C>>>1|S<<31)^(C>>>8|S<<24)^(C>>>7|S<<25),O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,S=i[(T+14)%16],C=a[(T+14)%16],E=(S>>>19|C<<13)^(C>>>29|S<<3)^S>>>6,D=(C>>>19|S<<13)^(S>>>29|C<<3)^(C>>>6|S<<26),O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,i[T]=A&65535|j<<16,a[T]=O&65535|k<<16;E=M,D=z,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[0],D=t[0],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[0]=M=A&65535|j<<16,t[0]=z=O&65535|k<<16,E=N,D=B,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[1],D=t[1],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[1]=N=A&65535|j<<16,t[1]=B=O&65535|k<<16,E=P,D=te,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[2],D=t[2],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[2]=P=A&65535|j<<16,t[2]=te=O&65535|k<<16,E=F,D=ne,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[3],D=t[3],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[3]=F=A&65535|j<<16,t[3]=ne=O&65535|k<<16,E=I,D=re,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[4],D=t[4],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[4]=I=A&65535|j<<16,t[4]=re=O&65535|k<<16,E=L,D=ie,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[5],D=t[5],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[5]=L=A&65535|j<<16,t[5]=ie=O&65535|k<<16,E=R,D=ae,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[6],D=t[6],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[6]=R=A&65535|j<<16,t[6]=ae=O&65535|k<<16,E=ee,D=oe,O=D&65535,k=D>>>16,A=E&65535,j=E>>>16,E=e[7],D=t[7],O+=D&65535,k+=D>>>16,A+=E&65535,j+=E>>>16,k+=O>>>16,A+=k>>>16,j+=A>>>16,e[7]=ee=A&65535|j<<16,t[7]=oe=O&65535|k<<16,se+=128,r-=128}return r}function me(e,t,n){var r=new Int32Array(8),i=new Int32Array(8),a=new Uint8Array(256),o,s=n;for(r[0]=1779033703,r[1]=3144134277,r[2]=1013904242,r[3]=2773480762,r[4]=1359893119,r[5]=2600822924,r[6]=528734635,r[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,pe(r,i,t,n),n%=128,o=0;o<n;o++)a[o]=t[s-n+o];for(a[n]=128,n=256-128*(n<112),a[n-9]=0,p(a,n-8,s/536870912|0,s<<3),pe(r,i,a,n),o=0;o<8;o++)p(e,8*o,r[o],i[o]);return 0}function he(e,n){var r=t(),i=t(),a=t(),o=t(),s=t(),c=t(),u=t(),d=t(),f=t();ee(r,e[1],e[0]),ee(f,n[1],n[0]),z(r,r,f),R(i,e[0],e[1]),R(f,n[0],n[1]),z(i,i,f),z(a,e[3],n[3]),z(a,a,l),z(o,e[2],n[2]),R(o,o,o),ee(s,i,r),ee(c,o,a),R(u,o,a),R(d,i,r),z(e[0],s,c),z(e[1],d,u),z(e[2],u,c),z(e[3],s,d)}function ge(e,t,n){for(var r=0;r<4;r++)N(e[r],t[r],n)}function _e(e,n){var r=t(),i=t(),a=t();te(a,n[2]),z(r,n[0],a),z(i,n[1],a),P(e,i),e[31]^=I(r)<<7}function ve(e,t,n){var r,i;for(j(e[0],a),j(e[1],o),j(e[2],o),j(e[3],a),i=255;i>=0;--i)r=n[i/8|0]>>(i&7)&1,ge(e,t,r),he(t,e),he(e,e),ge(e,t,r)}function ye(e,n){var r=[t(),t(),t(),t()];j(r[0],u),j(r[1],d),j(r[2],o),z(r[3],u,d),ve(e,r,n)}function be(e,r,i){var a=new Uint8Array(64),o=[t(),t(),t(),t()],s;for(i||n(r,32),me(a,r,32),a[0]&=248,a[31]&=127,a[31]|=64,ye(o,a),_e(e,o),s=0;s<32;s++)r[s+32]=e[s];return 0}var xe=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 Se(e,t){for(var n,r=63,i,a;r>=32;--r){for(n=0,i=r-32,a=r-12;i<a;++i)t[i]+=n-16*t[r]*xe[i-(r-32)],n=Math.floor((t[i]+128)/256),t[i]-=n*256;t[i]+=n,t[r]=0}for(n=0,i=0;i<32;i++)t[i]+=n-(t[31]>>4)*xe[i],n=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=n*xe[i];for(r=0;r<32;r++)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function Ce(e){for(var t=new Float64Array(64),n=0;n<64;n++)t[n]=e[n];for(n=0;n<64;n++)e[n]=0;Se(e,t)}function we(e,n,r,i){var a=new Uint8Array(64),o=new Uint8Array(64),s=new Uint8Array(64),c,l,u=new Float64Array(64),d=[t(),t(),t(),t()];me(a,i,32),a[0]&=248,a[31]&=127,a[31]|=64;var f=r+64;for(c=0;c<r;c++)e[64+c]=n[c];for(c=0;c<32;c++)e[32+c]=a[32+c];for(me(s,e.subarray(32),r+32),Ce(s),ye(d,s),_e(e,d),c=32;c<64;c++)e[c]=i[c];for(me(o,e,r+64),Ce(o),c=0;c<64;c++)u[c]=0;for(c=0;c<32;c++)u[c]=s[c];for(c=0;c<32;c++)for(l=0;l<32;l++)u[c+l]+=o[c]*a[l];return Se(e.subarray(32),u),f}function Te(e,n){var r=t(),i=t(),s=t(),l=t(),u=t(),d=t(),p=t();return j(e[2],o),L(e[1],n),B(s,e[1]),z(l,s,c),ee(s,s,e[2]),R(l,e[2],l),B(u,l),B(d,u),z(p,d,u),z(r,p,s),z(r,r,l),re(r,r),z(r,r,s),z(r,r,l),z(r,r,l),z(e[0],r,l),B(i,e[0]),z(i,i,l),F(i,s)&&z(e[0],e[0],f),B(i,e[0]),z(i,i,l),F(i,s)?-1:(I(e[0])===n[31]>>7&&ee(e[0],a,e[0]),z(e[3],e[0],e[1]),0)}function Ee(e,n,r,i){var a,o=new Uint8Array(32),s=new Uint8Array(64),c=[t(),t(),t(),t()],l=[t(),t(),t(),t()];if(r<64||Te(l,i))return-1;for(a=0;a<r;a++)e[a]=n[a];for(a=0;a<32;a++)e[a+32]=i[a];if(me(s,e,r),Ce(s),ve(c,l,s),ye(l,n.subarray(32)),he(c,l),_e(o,c),r-=64,g(n,0,o,0)){for(a=0;a<r;a++)e[a]=0;return-1}for(a=0;a<r;a++)e[a]=n[a+64];return r}var De=32,Oe=24,ke=32,Ae=16,je=32,Me=32,Ne=32,Pe=32,Fe=32,Ie=Oe,Le=ke,Re=Ae,ze=64,Be=32,Ve=64,He=32,Ue=64;e.lowlevel={crypto_core_hsalsa20:b,crypto_stream_xor:T,crypto_stream:w,crypto_stream_salsa20_xor:S,crypto_stream_salsa20:C,crypto_onetimeauth:D,crypto_onetimeauth_verify:O,crypto_verify_16:h,crypto_verify_32:g,crypto_secretbox:k,crypto_secretbox_open:A,crypto_scalarmult:ie,crypto_scalarmult_base:ae,crypto_box_beforenm:se,crypto_box_afternm:ce,crypto_box:ue,crypto_box_open:de,crypto_box_keypair:oe,crypto_hash:me,crypto_sign:we,crypto_sign_keypair:be,crypto_sign_open:Ee,crypto_secretbox_KEYBYTES:De,crypto_secretbox_NONCEBYTES:Oe,crypto_secretbox_ZEROBYTES:ke,crypto_secretbox_BOXZEROBYTES:Ae,crypto_scalarmult_BYTES:je,crypto_scalarmult_SCALARBYTES:Me,crypto_box_PUBLICKEYBYTES:Ne,crypto_box_SECRETKEYBYTES:Pe,crypto_box_BEFORENMBYTES:Fe,crypto_box_NONCEBYTES:Ie,crypto_box_ZEROBYTES:Le,crypto_box_BOXZEROBYTES:Re,crypto_sign_BYTES:ze,crypto_sign_PUBLICKEYBYTES:Be,crypto_sign_SECRETKEYBYTES:Ve,crypto_sign_SEEDBYTES:He,crypto_hash_BYTES:Ue,gf:t,D:c,L:xe,pack25519:P,unpack25519:L,M:z,A:R,S:B,Z:ee,pow2523:re,add:he,set25519:j,modL:Se,scalarmult:ve,scalarbase:ye};function We(e,t){if(e.length!==De)throw Error(`bad key size`);if(t.length!==Oe)throw Error(`bad nonce size`)}function Ge(e,t){if(e.length!==Ne)throw Error(`bad public key size`);if(t.length!==Pe)throw Error(`bad secret key size`)}function Ke(){for(var e=0;e<arguments.length;e++)if(!(arguments[e]instanceof Uint8Array))throw TypeError(`unexpected type, use Uint8Array`)}function qe(e){for(var t=0;t<e.length;t++)e[t]=0}e.randomBytes=function(e){var t=new Uint8Array(e);return n(t,e),t},e.secretbox=function(e,t,n){Ke(e,t,n),We(n,t);for(var r=new Uint8Array(ke+e.length),i=new Uint8Array(r.length),a=0;a<e.length;a++)r[a+ke]=e[a];return k(i,r,r.length,t,n),i.subarray(Ae)},e.secretbox.open=function(e,t,n){Ke(e,t,n),We(n,t);for(var r=new Uint8Array(Ae+e.length),i=new Uint8Array(r.length),a=0;a<e.length;a++)r[a+Ae]=e[a];return r.length<32||A(i,r,r.length,t,n)!==0?null:i.subarray(ke)},e.secretbox.keyLength=De,e.secretbox.nonceLength=Oe,e.secretbox.overheadLength=Ae,e.scalarMult=function(e,t){if(Ke(e,t),e.length!==Me)throw Error(`bad n size`);if(t.length!==je)throw Error(`bad p size`);var n=new Uint8Array(je);return ie(n,e,t),n},e.scalarMult.base=function(e){if(Ke(e),e.length!==Me)throw Error(`bad n size`);var t=new Uint8Array(je);return ae(t,e),t},e.scalarMult.scalarLength=Me,e.scalarMult.groupElementLength=je,e.box=function(t,n,r,i){var a=e.box.before(r,i);return e.secretbox(t,n,a)},e.box.before=function(e,t){Ke(e,t),Ge(e,t);var n=new Uint8Array(Fe);return se(n,e,t),n},e.box.after=e.secretbox,e.box.open=function(t,n,r,i){var a=e.box.before(r,i);return e.secretbox.open(t,n,a)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var e=new Uint8Array(Ne),t=new Uint8Array(Pe);return oe(e,t),{publicKey:e,secretKey:t}},e.box.keyPair.fromSecretKey=function(e){if(Ke(e),e.length!==Pe)throw Error(`bad secret key size`);var t=new Uint8Array(Ne);return ae(t,e),{publicKey:t,secretKey:new Uint8Array(e)}},e.box.publicKeyLength=Ne,e.box.secretKeyLength=Pe,e.box.sharedKeyLength=Fe,e.box.nonceLength=Ie,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(e,t){if(Ke(e,t),t.length!==Ve)throw Error(`bad secret key size`);var n=new Uint8Array(ze+e.length);return we(n,e,e.length,t),n},e.sign.open=function(e,t){if(Ke(e,t),t.length!==Be)throw Error(`bad public key size`);var n=new Uint8Array(e.length),r=Ee(n,e,e.length,t);if(r<0)return null;for(var i=new Uint8Array(r),a=0;a<i.length;a++)i[a]=n[a];return i},e.sign.detached=function(t,n){for(var r=e.sign(t,n),i=new Uint8Array(ze),a=0;a<i.length;a++)i[a]=r[a];return i},e.sign.detached.verify=function(e,t,n){if(Ke(e,t,n),t.length!==ze)throw Error(`bad signature size`);if(n.length!==Be)throw Error(`bad public key size`);for(var r=new Uint8Array(ze+e.length),i=new Uint8Array(ze+e.length),a=0;a<ze;a++)r[a]=t[a];for(a=0;a<e.length;a++)r[a+ze]=e[a];return Ee(i,r,r.length,n)>=0},e.sign.keyPair=function(){var e=new Uint8Array(Be),t=new Uint8Array(Ve);return be(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(Ke(e),e.length!==Ve)throw Error(`bad secret key size`);for(var t=new Uint8Array(Be),n=0;n<t.length;n++)t[n]=e[32+n];return{publicKey:t,secretKey:new Uint8Array(e)}},e.sign.keyPair.fromSeed=function(e){if(Ke(e),e.length!==He)throw Error(`bad seed size`);for(var t=new Uint8Array(Be),n=new Uint8Array(Ve),r=0;r<32;r++)n[r]=e[r];return be(t,n,!0),{publicKey:t,secretKey:n}},e.sign.publicKeyLength=Be,e.sign.secretKeyLength=Ve,e.sign.seedLength=He,e.sign.signatureLength=ze,e.hash=function(e){Ke(e);var t=new Uint8Array(Ue);return me(t,e,e.length),t},e.hash.hashLength=Ue,e.verify=function(e,t){return Ke(e,t),e.length===0||t.length===0||e.length!==t.length?!1:m(e,0,t,0,e.length)===0},e.setPRNG=function(e){n=e},(function(){var t=typeof self<`u`?self.crypto||self.msCrypto:null;if(t&&t.getRandomValues){var n=65536;e.setPRNG(function(e,r){var i,a=new Uint8Array(r);for(i=0;i<r;i+=n)t.getRandomValues(a.subarray(i,i+Math.min(r-i,n)));for(i=0;i<r;i++)e[i]=a[i];qe(a)})}else ne!==void 0&&(t=ne(`crypto`),t&&t.randomBytes&&e.setPRNG(function(e,n){var r,i=t.randomBytes(n);for(r=0;r<n;r++)e[r]=i[r];qe(i)}))})()})(t!==void 0&&t.exports?t.exports:self.nacl=self.nacl||{})})),Id=R((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferVisitor=class{constructor(e,t=0,n=0){this.start=t,this.end=n>t?n:t,this.buf=e}get length(){return this.buf.length}reset(e=0,t=0){return this.start=e,t>=this.start?this.end=t:this.end<this.start&&(this.end=this.start),this}walk(e){return this.start=this.end,this.end+=e,this}mustHas(e,t=`Too few bytes to parse.`){let n=this.end+e;if(n>this.buf.length){let e=Error(t);throw e.available=this.buf.length,e.requested=n,e}return this.walk(0),this}mustWalk(e,t){return this.mustHas(e,t),this.walk(e),this}}})),Ld=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ne(`util`),n=64,r=`-----BEGIN `,i=`-----END `,a=`-----`,o=`Proc-Type`,s=class{static parse(e){let t=[],n=e.toString(`utf8`).split(`
|
|
19
19
|
`).map(e=>e.trim()).filter(e=>e!==``&&!e.startsWith(`#`));for(;n.length>0;)t.push(c(n));if(t.length===0)throw Error(`PEM: no block`);return t}constructor(e,t){this.type=e,this.body=t,this.headers=Object.create(null)}get procType(){return this.getHeader(o)}getHeader(e){return this.headers[e]??``}setHeader(e,t){if(e.includes(`:`))throw Error(`pem: cannot encode a header key that contains a colon`);if(e===``||t===``)throw Error(`pem: invalid header key or value`);this.headers[e]=t}toString(){let e=r+this.type+`-----
|
|
20
20
|
`,t=Object.keys(this.headers);if(t.length>0){let n=this.procType;n!==``&&(e+=`${o}: ${n}\n`),t.sort();for(let n of t)n!==o&&(e+=`${n}: ${this.headers[n]}\n`);e+=`
|
|
21
21
|
`}let a=this.body.toString(`base64`),s=0;for(;s<a.length;)e+=a.slice(s,s+n)+`
|
|
22
22
|
`,s+=n;return e+=i+this.type+`-----
|
|
23
|
-
`,e}toBuffer(){return Buffer.from(this.toString(),`utf8`)}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};e.PEM=s;function c(e){let t=e.shift();if(t==null||!t.startsWith(r)||!t.endsWith(a))throw Error(`pem: invalid BEGIN line`);let n=t.slice(11,t.length-5);if(n===``)throw Error(`pem: invalid type`);let o=[];for(t=e.shift();t!=null&&t.includes(`: `);){let n=t.split(`: `);if(n.length!==2||n[0]===``||n[1]===``)throw Error(`pem: invalid Header line`);o.push(n),t=e.shift()}let c=``;for(;t!=null&&!t.startsWith(i);)c+=t,t=e.shift();if(t==null||t!==`${i}${n}${a}`)throw Error(`pem: invalid END line`);let l=new s(n,Buffer.from(c,`base64`));if(c===``||l.body.toString(`base64`)!==c)throw Error(`pem: invalid base64 body`);for(let e of o)l.setHeader(e[0],e[1]);return l}})),ii=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=ni(),r;(function(e){e[e.UNIVERSAL=0]=`UNIVERSAL`,e[e.APPLICATION=64]=`APPLICATION`,e[e.CONTEXT_SPECIFIC=128]=`CONTEXT_SPECIFIC`,e[e.PRIVATE=192]=`PRIVATE`})(r=e.Class||={});var i;(function(e){e[e.NONE=0]=`NONE`,e[e.BOOLEAN=1]=`BOOLEAN`,e[e.INTEGER=2]=`INTEGER`,e[e.BITSTRING=3]=`BITSTRING`,e[e.OCTETSTRING=4]=`OCTETSTRING`,e[e.NULL=5]=`NULL`,e[e.OID=6]=`OID`,e[e.ENUMERATED=10]=`ENUMERATED`,e[e.UTF8=12]=`UTF8`,e[e.SEQUENCE=16]=`SEQUENCE`,e[e.SET=17]=`SET`,e[e.NUMERICSTRING=18]=`NUMERICSTRING`,e[e.PRINTABLESTRING=19]=`PRINTABLESTRING`,e[e.T61STRING=20]=`T61STRING`,e[e.IA5STRING=22]=`IA5STRING`,e[e.UTCTIME=23]=`UTCTIME`,e[e.GENERALIZEDTIME=24]=`GENERALIZEDTIME`,e[e.GENERALSTRING=27]=`GENERALSTRING`})(i=e.Tag||={});var a=class{constructor(e,t){this.buf=e,this.bitLen=t}at(e){if(e<0||e>=this.bitLen||!Number.isInteger(e))return 0;let t=Math.floor(e/8),n=7-e%8;return this.buf[t]>>n&1}rightAlign(){let e=8-this.bitLen%8;if(e===8||this.buf.length===0)return this.buf;let t=Buffer.alloc(this.buf.length);t[0]=this.buf[0]>>e;for(let n=1;n<this.buf.length;n++)t[n]=this.buf[n-1]<<8-e,t[n]|=this.buf[n]>>e;return t}};e.BitString=a,e.ASN1=class e{static Bool(t){let n=new e(r.UNIVERSAL,i.BOOLEAN,Buffer.from([t?255:0]));return n._value=t,n}static parseBool(e){if(!(e instanceof Buffer)||e.length!==1)throw Error(`ASN1 syntax error: invalid boolean`);switch(e[0]){case 0:return!1;case 255:return!0;default:throw Error(`ASN1 syntax error: invalid boolean`)}}static Integer(t){if(t instanceof Buffer){let n=new e(r.UNIVERSAL,i.INTEGER,t);return n._value=t.toString(`hex`),n}if(!Number.isSafeInteger(t))throw Error(`ASN1 syntax error: invalid integer`);let n;if(t>=-128&&t<128)n=Buffer.alloc(1),n.writeInt8(t,0);else if(t>=-32768&&t<32768)n=Buffer.alloc(2),n.writeIntBE(t,0,2);else if(t>=-8388608&&t<8388608)n=Buffer.alloc(3),n.writeIntBE(t,0,3);else if(t>=-2147483648&&t<2147483648)n=Buffer.alloc(4),n.writeIntBE(t,0,4);else if(t>=-549755813888&&t<549755813888)n=Buffer.alloc(5),n.writeIntBE(t,0,5);else if(t>=-0x800000000000&&t<0x800000000000)n=Buffer.alloc(6),n.writeIntBE(t,0,6);else throw Error(`ASN1 syntax error: invalid Integer`);let a=new e(r.UNIVERSAL,i.INTEGER,n);return a._value=t,a}static parseInteger(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid Integer`);return e.length>6?e.toString(`hex`):e.readIntBE(0,e.length)}static parseIntegerNum(t){let n=e.parseInteger(t);if(typeof n!=`number`)throw Error(`ASN1 syntax error: invalid Integer number`);return n}static parseIntegerStr(t){let n=e.parseInteger(t);return typeof n==`number`?n.toString(16):n}static BitString(t){t instanceof Buffer&&(t=new a(t,t.length*8));let n=t.buf.length*8-t.bitLen,o=Buffer.alloc(t.buf.length+1);return o.writeInt8(n,0),t.buf.copy(o,1),new e(r.UNIVERSAL,i.BITSTRING,o)}static parseBitString(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid BitString`);let t=e[0];if(t>7||e.length===1&&t>0||e[e.length-1]&(1<<e[0])-1)throw Error(`ASN1 syntax error: invalid padding bits in BIT STRING`);return new a(e.slice(1),(e.length-1)*8-t)}static Null(){let t=new e(r.UNIVERSAL,i.NULL,Buffer.alloc(0));return t._value=null,t}static parseNull(e){if(!(e instanceof Buffer)||e.length!==0)throw Error(`ASN1 syntax error: invalid null`);return null}static OID(t){let n=t.split(`.`);if(n.length===0)throw Error(`ASN1 syntax error: invalid Object Identifier`);let a=[];a.push(40*u(n[0])+u(n[1]));let o=[];for(let e=2;e<n.length;++e){let t=u(n[e]);for(o.length=0,o.push(t&127);t>127;)t>>>=7,o.unshift(t&127|128);a.push(...o)}let s=new e(r.UNIVERSAL,i.OID,Buffer.from(a));return s._value=t,s}static parseOID(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid OID`);let t=Math.floor(e[0]/40)+`.`+e[0]%40,n=0;for(let r=1;r<e.length;r++)e[r]>=128?(n+=e[r]&127,n<<=7):(t+=`.`+(n+e[r]),n=0);return t}static UTF8(t){let n=new e(r.UNIVERSAL,i.UTF8,Buffer.from(t,`utf8`));return n._value=t,n}static parseUTF8(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static NumericString(t){if(!c(t))throw Error(`ASN1 syntax error: invalid NumericString`);let n=new e(r.UNIVERSAL,i.NUMERICSTRING,Buffer.from(t,`utf8`));return n._value=t,n}static parseNumericString(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);let t=e.toString(`utf8`);if(!c(t))throw Error(`ASN1 syntax error: invalid NumericString`);return t}static PrintableString(t){let n=new e(r.UNIVERSAL,i.PRINTABLESTRING,Buffer.from(t,`utf8`));return n._value=t,n}static parsePrintableString(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static IA5String(t){if(!l(t))throw Error(`ASN1 syntax error: invalid IA5String`);let n=new e(r.UNIVERSAL,i.IA5STRING,Buffer.from(t,`utf8`));return n._value=t,n}static parseIA5String(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);let t=e.toString(`utf8`);if(!l(t))throw Error(`ASN1 syntax error: invalid IA5String`);return t}static T61String(t){let n=new e(r.UNIVERSAL,i.T61STRING,Buffer.from(t,`utf8`));return n._value=t,n}static parseT61String(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static GeneralString(t){let n=new e(r.UNIVERSAL,i.GENERALSTRING,Buffer.from(t,`utf8`));return n._value=t,n}static parseGeneralString(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static UTCTime(t){let n=``,a=[];a.push((``+t.getUTCFullYear()).substr(2)),a.push(``+(t.getUTCMonth()+1)),a.push(``+t.getUTCDate()),a.push(``+t.getUTCHours()),a.push(``+t.getUTCMinutes()),a.push(``+t.getUTCSeconds());for(let e of a)e.length<2&&(n+=`0`),n+=e;n+=`Z`;let o=new e(r.UNIVERSAL,i.UTCTIME,Buffer.from(n,`utf8`));return o._value=t,o}static parseUTCTime(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid UTC Time`);let t=e.toString(`utf8`),n=new Date,r=u(t.substr(0,2));r=r>=50?1900+r:2e3+r;let i=u(t.substr(2,2))-1,a=u(t.substr(4,2)),o=u(t.substr(6,2)),s=u(t.substr(8,2)),c=0,l=0,d=``;if(t.length>11&&(l=10,d=t.charAt(l),d!==`+`&&d!==`-`&&(c=u(t.substr(10,2)),l+=2)),n.setUTCFullYear(r,i,a),n.setUTCHours(o,s,c,0),l>0&&(d=t.charAt(l),d===`+`||d===`-`)){let e=u(t.substr(l+1,2)),r=u(t.substr(l+4,2)),i=e*60+r;i*=6e4,d===`+`?n.setTime(+n-i):n.setTime(+n+i)}return n}static GeneralizedTime(t){let n=``,a=[];a.push(``+t.getUTCFullYear()),a.push(``+(t.getUTCMonth()+1)),a.push(``+t.getUTCDate()),a.push(``+t.getUTCHours()),a.push(``+t.getUTCMinutes()),a.push(``+t.getUTCSeconds());for(let e of a)e.length<2&&(n+=`0`),n+=e;n+=`Z`;let o=new e(r.UNIVERSAL,i.GENERALIZEDTIME,Buffer.from(n,`utf8`));return o._value=t,o}static parseGeneralizedTime(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid Generalized Time`);let t=e.toString(`utf8`),n=new Date,r=u(t.substr(0,4)),i=u(t.substr(4,2))-1,a=u(t.substr(6,2)),o=u(t.substr(8,2)),s=u(t.substr(10,2)),c=u(t.substr(12,2)),l=0,d=0,f=!1;t.charAt(t.length-1)===`Z`&&(f=!0);let p=t.length-5,m=t.charAt(p);if(m===`+`||m===`-`){let e=u(t.substr(p+1,2)),n=u(t.substr(p+4,2));d=e*60+n,d*=6e4,m===`+`&&(d*=-1),f=!0}return t.charAt(14)===`.`&&(l=parseFloat(t.substr(14))*1e3),f?(n.setUTCFullYear(r,i,a),n.setUTCHours(o,s,c,l),n.setTime(+n+d)):(n.setFullYear(r,i,a),n.setHours(o,s,c,l)),n}static parseTime(t,n){switch(t){case i.UTCTIME:return e.parseUTCTime(n);case i.GENERALIZEDTIME:return e.parseGeneralizedTime(n);default:throw Error(`Invalid ASN1 time tag`)}}static Set(t){let n=new e(r.UNIVERSAL,i.SET,Buffer.concat(t.map(e=>e.toDER())));return n._value=t,n}static Seq(t){let n=new e(r.UNIVERSAL,i.SEQUENCE,Buffer.concat(t.map(e=>e.toDER())));return n._value=t,n}static Spec(t,n,i=!0){let a=Array.isArray(n)?Buffer.concat(n.map(e=>e.toDER())):n.toDER();Array.isArray(n)&&(i=!0);let o=new e(r.CONTEXT_SPECIFIC,t,a,i);return o._value=n,o}static fromDER(t,r=!1){return e._fromDER(new n.BufferVisitor(t),r)}static parseDER(t,r,i){let a=e._fromDER(new n.BufferVisitor(t),!1);if(a.class!==r&&a.tag!==i)throw Error(`invalid ASN.1 DER for class ${r} and tag ${i}`);return a}static parseDERWithTemplate(t,r){let i=e._fromDER(new n.BufferVisitor(t),!0),a={},o=i.validate(r,a);if(o!=null)throw o.data=i,o;return a}static _parseCompound(t,r){let i=[],a=t.length,o=new n.BufferVisitor(t),s=0;for(;s<a;){let t=o.end;i.push(e._fromDER(o,r)),s+=o.end-t}return i}static _fromDER(t,n){if(!(t.buf instanceof Buffer)||t.length===0)throw Error(`ASN1 syntax error: invalid Generalized Time`);t.mustWalk(1,`Too few bytes to read ASN.1 tag.`);let r=t.start,a=t.buf[r],s=a&192,c=a&31,l=o(t);if(t.mustHas(l),l!==0&&c===i.NULL)throw Error(`invalid value length or NULL tag.`);t.mustWalk(l);let u=(a&32)==32,d=new e(s,c,t.buf.slice(t.start,t.end),u);return u&&n&&(d._value=e._parseCompound(d.bytes,n)),d._der=t.buf.slice(r,t.end),d}constructor(e,t,n,r=!1){this.class=e,this.tag=t,this.bytes=n,this.isCompound=r||t===i.SEQUENCE||t===i.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??=this.toDER(),this._der}mustCompound(e=`asn1 object value is not compound`){if(!this.isCompound||!Array.isArray(this.value)){let t=Error(e);throw t.data=this.toJSON(),t}return this.value}equals(t){return!(!(t instanceof e)||this.class!==t.class||this.tag!==t.tag||this.isCompound!==t.isCompound||!this.bytes.equals(t.bytes))}toDER(){let e=this.class|this.tag;this.isCompound&&(e|=32);let t=s(this.bytes.length),n=Buffer.allocUnsafe(2+t+this.bytes.length);return n.writeInt8(e,0),t===0?(n.writeUInt8(this.bytes.length,1),this.bytes.copy(n,2)):(n.writeUInt8(t|128,1),n.writeUIntBE(this.bytes.length,2,t),this.bytes.copy(n,2+t)),n}valueOf(){if(this.isCompound)return e._parseCompound(this.bytes,!1);if(this.class!==r.UNIVERSAL)return this.bytes;switch(this.tag){case i.BOOLEAN:return e.parseBool(this.bytes);case i.INTEGER:return e.parseInteger(this.bytes);case i.BITSTRING:return e.parseBitString(this.bytes);case i.NULL:return e.parseNull(this.bytes);case i.OID:return e.parseOID(this.bytes);case i.UTF8:return e.parseUTF8(this.bytes);case i.NUMERICSTRING:return e.parseNumericString(this.bytes);case i.PRINTABLESTRING:return e.parsePrintableString(this.bytes);case i.T61STRING:return e.parseT61String(this.bytes);case i.IA5STRING:return e.parseIA5String(this.bytes);case i.GENERALSTRING:return e.parseGeneralString(this.bytes);case i.UTCTIME:return e.parseUTCTime(this.bytes);case i.GENERALIZEDTIME:return e.parseGeneralizedTime(this.bytes);default:return this.bytes}}validate(t,n={}){if(this.class!==t.class)return Error(`ASN.1 object validate failure for ${t.name} : error class ${r[this.class]}`);if(!(Array.isArray(t.tag)?t.tag:[t.tag]).includes(this.tag))return Error(`ASN.1 object validate failure for ${t.name}: error tag ${i[this.tag]}`);if(t.capture!=null&&(n[t.capture]=this),Array.isArray(t.value)){let e=this.mustCompound(`${t.name} need compound ASN1 value`);for(let r=0,i=0;r<t.value.length;r++)if(e[i]!=null){let a=e[i].validate(t.value[r],n);if(a==null)i++;else if(t.value[r].optional!==!0)return a}else if(t.value[r].optional!==!0)return Error(`ASN.1 object validate failure for ${t.value[r].name}: not exists`)}else if(t.value!=null){let r=this.tag===i.BITSTRING?this.bytes.slice(1):this.bytes;return e.fromDER(r).validate(t.value,n)}return null}toJSON(){let e=this.value;return Array.isArray(e)&&(e=e.map(e=>e.toJSON())),{class:r[this.class],tag:this.class===r.UNIVERSAL?i[this.tag]:this.tag,value:e}}[t.inspect.custom](e,n){return n.depth<=2&&(n.depth=10),`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};function o(e){e.mustWalk(1,`Too few bytes to read ASN.1 value length.`);let t=e.buf[e.start];if(!(t&128))return t;let n=t&127;return e.mustWalk(n,`Too few bytes to read ASN.1 value length.`),e.buf.readUIntBE(e.start,n)}function s(e){if(e<=127)return 0;if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;if(e<=0xffffffffff)return 5;if(e<=0xffffffffffff)return 6;throw Error(`invalid value length`)}function c(e){for(let t of e){let e=t.charCodeAt(0);if(e!==32&&(e<48||e>57))return!1}return!0}function l(e){for(let t of e)if(t.charCodeAt(0)>=128)return!1;return!0}function u(e,t=10){let n=parseInt(e,t);if(Number.isNaN(n))throw Error(`Invalid numeric string "${e}" in radix ${t}.`);return n}})),ai=R((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferVisitor=ni().BufferVisitor,e.PEM=ri().PEM;var t=ii();e.ASN1=t.ASN1,e.Class=t.Class,e.Tag=t.Tag,e.BitString=t.BitString})),oi=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=te(`crypto`),r=ti(),i=ai(),a=ei();e.publicKeyValidator={name:`PublicKeyInfo`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,capture:`publicKeyInfo`,value:[{name:`PublicKeyInfo.AlgorithmIdentifier`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`PublicKeyAlgorithmIdentifier.algorithm`,class:i.Class.UNIVERSAL,tag:i.Tag.OID,capture:`publicKeyOID`}]},{name:`PublicKeyInfo.PublicKey`,class:i.Class.UNIVERSAL,tag:i.Tag.BITSTRING,capture:`publicKey`}]},e.privateKeyValidator={name:`PrivateKeyInfo`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,capture:`privateKeyInfo`,value:[{name:`PrivateKeyInfo.Version`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyVersion`},{name:`PrivateKeyInfo.AlgorithmIdentifier`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`PrivateKeyAlgorithmIdentifier.algorithm`,class:i.Class.UNIVERSAL,tag:i.Tag.OID,capture:`privateKeyOID`}]},{name:`PrivateKeyInfo.PrivateKey`,class:i.Class.UNIVERSAL,tag:i.Tag.OCTETSTRING,capture:`privateKey`}]};var o={name:`RSAPublicKey`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`RSAPublicKey.modulus`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`publicKeyModulus`},{name:`RSAPublicKey.exponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`publicKeyExponent`}]},s={name:`RSAPrivateKey`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`RSAPrivateKey.version`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyVersion`},{name:`RSAPrivateKey.modulus`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyModulus`},{name:`RSAPrivateKey.publicExponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPublicExponent`},{name:`RSAPrivateKey.privateExponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrivateExponent`},{name:`RSAPrivateKey.prime1`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrime1`},{name:`RSAPrivateKey.prime2`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrime2`},{name:`RSAPrivateKey.exponent1`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyExponent1`},{name:`RSAPrivateKey.exponent2`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyExponent2`},{name:`RSAPrivateKey.coefficient`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyCoefficient`}]},c=[a.getOID(`X25519`),a.getOID(`X448`),a.getOID(`Ed25519`),a.getOID(`Ed448`)],l=class r{constructor(t){let n={},r=t.validate(e.publicKeyValidator,n);if(r!=null)throw Error(`Cannot read X.509 public key: `+r.message);this.oid=i.ASN1.parseOID(n.publicKeyOID.bytes),this.algo=a.getOIDName(this.oid),this._pkcs8=t,this._keyRaw=i.ASN1.parseBitString(n.publicKey.bytes).buf,this._finalKey=this._keyRaw,this._finalPEM=``}static fromPEM(e){let t=i.PEM.parse(e)[0];if(t.procType.includes(`ENCRYPTED`))throw Error(`Could not convert public key from PEM, PEM is encrypted.`);let n=i.ASN1.fromDER(t.body,!0);switch(t.type){case`PUBLIC KEY`:return new r(n);case`RSA PUBLIC KEY`:let e=i.ASN1.Seq([i.ASN1.Seq([i.ASN1.OID(a.getOID(`rsaEncryption`)),i.ASN1.Null()]),i.ASN1.BitString(n.DER)]);return new r(e);default:throw Error(`Could not convert public key from PEM, recommend PKCS#8 PEM`)}}static addVerifier(e,t){if(e=a.getOID(e),e===``)throw Error(`Invalid object identifier: ${e}`);if(r._verifiers[e]!=null)throw Error(`Verifier ${e} exists`);r._verifiers[e]=t}get keyRaw(){return this._finalKey}verify(e,t,i){let a=r._verifiers[this.oid];if(a!=null){let r=n.createHash(i).update(e).digest();return a.call(this,r,t)}let o=n.createVerify(i);return o.update(e),o.verify(this.toPEM(),t)}getFingerprint(e,t=`PublicKey`){let r;switch(t){case`PublicKeyInfo`:r=this._pkcs8.DER;break;case`PublicKey`:r=this._keyRaw;break;default:throw Error(`Unknown fingerprint type "${t}".`)}let i=n.createHash(e);return i.update(r),i.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===``&&(this._finalPEM=new i.PEM(`PUBLIC KEY`,this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{oid:this.oid,algo:this.algo,publicKey:this._keyRaw}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};l._verifiers=Object.create(null),e.PublicKey=l;var u=class o{constructor(t){let n=Object.create(null),o=t.validate(e.privateKeyValidator,n);if(o!=null)throw Error(`Cannot read X.509 private key: `+o.message);if(this.version=i.ASN1.parseIntegerNum(n.privateKeyVersion.bytes)+1,this.oid=i.ASN1.parseOID(n.privateKeyOID.bytes),this.algo=a.getOIDName(this.oid),this._pkcs8=t,this._keyRaw=n.privateKey.bytes,this._publicKeyRaw=null,this._finalKey=this._keyRaw,this._finalPEM=``,c.includes(this.oid)){if(this._finalKey=this._keyRaw=i.ASN1.parseDER(this._keyRaw,i.Class.UNIVERSAL,i.Tag.OCTETSTRING).bytes,this.oid===`1.3.101.112`){let e=r.sign.keyPair.fromSeed(this._keyRaw);this._publicKeyRaw=Buffer.from(e.publicKey),this._finalKey=Buffer.from(e.secretKey)}else if(this.version===2)for(let e of t.mustCompound())e.class===i.Class.CONTEXT_SPECIFIC&&e.tag===1&&(this._publicKeyRaw=i.ASN1.parseBitString(e.bytes).buf,this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw]))}}static fromPEM(e){let t=i.PEM.parse(e)[0];if(t.procType.includes(`ENCRYPTED`))throw Error(`Could not convert private key from PEM, PEM is encrypted.`);let n=i.ASN1.fromDER(t.body,!0);switch(t.type){case`PRIVATE KEY`:return new o(n);case`RSA PRIVATE KEY`:return n=i.ASN1.Seq([n.value[0],i.ASN1.Seq([i.ASN1.OID(a.getOID(`rsaEncryption`)),i.ASN1.Null()]),new i.ASN1(i.Class.UNIVERSAL,i.Tag.OCTETSTRING,n.DER)]),new o(n);default:throw Error(`Could not convert private key from PEM, recommend PKCS#8 PEM`)}}static addSigner(e,t){if(e=a.getOID(e),e===``)throw Error(`Invalid object identifier: ${e}`);if(o._signers[e]!=null)throw Error(`Signer ${e} exists`);o._signers[e]=t}get keyRaw(){return this._finalKey}get publicKeyRaw(){return this._publicKeyRaw}sign(e,t){let r=o._signers[this.oid];if(r!=null){let i=n.createHash(t).update(e).digest();return r.call(this,i)}let i=n.createSign(t);return i.update(e),i.sign(this.toPEM())}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===``&&(this._finalPEM=new i.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}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};u._signers=Object.create(null),e.PrivateKey=u,e.RSAPublicKey=class e extends l{static fromPublicKey(t){return new e(t.toASN1())}constructor(e){if(super(e),a.getOID(this.oid)!==a.getOID(`rsaEncryption`))throw Error(`Invalid RSA public key, unknown OID: ${this.oid}`);let t=Object.create(null);this._pkcs1=i.ASN1.fromDER(this._keyRaw,!0);let n=this._pkcs1.validate(o,t);if(n!=null)throw Error(`Cannot read RSA public key: `+n.message);this.modulus=i.ASN1.parseIntegerStr(t.publicKeyModulus.bytes),this.exponent=i.ASN1.parseIntegerNum(t.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===``&&(this._finalPEM=new i.PEM(`RSA PUBLIC KEY`,this._keyRaw).toString()),this._finalPEM}toPublicKeyPEM(){return new i.PEM(`PUBLIC KEY`,this._pkcs8.DER).toString()}toJSON(){return{oid:this.oid,algo:this.algo,modulus:d(this.modulus),exponent:this.exponent}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}},e.RSAPrivateKey=class e extends u{static fromPrivateKey(t){return new e(t.toASN1())}constructor(e){if(super(e),a.getOID(this.oid)!==a.getOID(`rsaEncryption`))throw Error(`Invalid RSA private key, unknown OID: ${this.oid}`);let t=Object.create(null);this._pkcs1=i.ASN1.fromDER(this._keyRaw,!0);let n=this._pkcs1.validate(s,t);if(n!=null)throw Error(`Cannot read RSA private key: `+n.message);this.publicExponent=i.ASN1.parseIntegerNum(t.privateKeyPublicExponent.bytes),this.privateExponent=i.ASN1.parseIntegerStr(t.privateKeyPrivateExponent.bytes),this.modulus=i.ASN1.parseIntegerStr(t.privateKeyModulus.bytes),this.prime1=i.ASN1.parseIntegerStr(t.privateKeyPrime1.bytes),this.prime2=i.ASN1.parseIntegerStr(t.privateKeyPrime2.bytes),this.exponent1=i.ASN1.parseIntegerStr(t.privateKeyExponent1.bytes),this.exponent2=i.ASN1.parseIntegerStr(t.privateKeyExponent2.bytes),this.coefficient=i.ASN1.parseIntegerStr(t.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===``&&(this._finalPEM=new i.PEM(`RSA PRIVATE KEY`,this._keyRaw).toString()),this._finalPEM}toPrivateKeyPEM(){return new i.PEM(`PRIVATE KEY`,this._pkcs8.DER).toString()}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,publicExponent:this.publicExponent,privateExponent:d(this.privateExponent),modulus:d(this.modulus),prime1:d(this.prime1),prime2:d(this.prime2),exponent1:d(this.exponent1),exponent2:d(this.exponent2),coefficient:d(this.coefficient)}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};function d(e){return e.length%8!=0&&e.startsWith(`00`)?e.slice(2):e}l.addVerifier(a.getOID(`Ed25519`),function(e,t){return r.sign.detached.verify(e,t,this.keyRaw)}),u.addSigner(a.getOID(`Ed25519`),function(e){let t=this.keyRaw;if(t.length!==64)throw Error(`Invalid signing key.`);return Buffer.from(r.sign.detached(e,t))})})),si=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=te(`crypto`),r=ai(),i=ei(),a=oi(),o=Object.create(null);o.CN=i.getOID(`commonName`),o.commonName=`CN`,o.C=i.getOID(`countryName`),o.countryName=`C`,o.L=i.getOID(`localityName`),o.localityName=`L`,o.ST=i.getOID(`stateOrProvinceName`),o.stateOrProvinceName=`ST`,o.O=i.getOID(`organizationName`),o.organizationName=`O`,o.OU=i.getOID(`organizationalUnitName`),o.organizationalUnitName=`OU`,o.E=i.getOID(`emailAddress`),o.emailAddress=`E`;function s(e){return o[e]==null?``:o[e]}var c={name:`Certificate`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`tbsCertificate`,value:[{name:`Certificate.TBSCertificate.version`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.NONE,optional:!0,value:[{name:`Certificate.TBSCertificate.version.integer`,class:r.Class.UNIVERSAL,tag:r.Tag.INTEGER,capture:`certVersion`}]},{name:`Certificate.TBSCertificate.serialNumber`,class:r.Class.UNIVERSAL,tag:r.Tag.INTEGER,capture:`certSerialNumber`},{name:`Certificate.TBSCertificate.signature`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate.signature.algorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.OID,capture:`certinfoSignatureOID`},{name:`Certificate.TBSCertificate.signature.parameters`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,optional:!0,capture:`certinfoSignatureParams`}]},{name:`Certificate.TBSCertificate.issuer`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`certIssuer`},{name:`Certificate.TBSCertificate.validity`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate.validity.notBefore`,class:r.Class.UNIVERSAL,tag:[r.Tag.UTCTIME,r.Tag.GENERALIZEDTIME],capture:`certValidityNotBefore`},{name:`Certificate.TBSCertificate.validity.notAfter`,class:r.Class.UNIVERSAL,tag:[r.Tag.UTCTIME,r.Tag.GENERALIZEDTIME],capture:`certValidityNotAfter`}]},{name:`Certificate.TBSCertificate.subject`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`certSubject`},a.publicKeyValidator,{name:`Certificate.TBSCertificate.issuerUniqueID`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.BOOLEAN,optional:!0,value:[{name:`Certificate.TBSCertificate.issuerUniqueID.id`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certIssuerUniqueId`}]},{name:`Certificate.TBSCertificate.subjectUniqueID`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.INTEGER,optional:!0,value:[{name:`Certificate.TBSCertificate.subjectUniqueID.id`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certSubjectUniqueId`}]},{name:`Certificate.TBSCertificate.extensions`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.BITSTRING,capture:`certExtensions`,optional:!0}]},{name:`Certificate.signatureAlgorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.signatureAlgorithm.algorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.OID,capture:`certSignatureOID`},{name:`Certificate.TBSCertificate.signature.parameters`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,optional:!0,capture:`certSignatureParams`}]},{name:`Certificate.signatureValue`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certSignature`}]},l=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=n.createHash(`sha1`);for(let t of this.attributes)e.update(t.oid),e.update(t.value);return e.digest()}getField(e){for(let t of this.attributes)if(e===t.oid||e===t.name||e===t.shortName)return t;return null}addField(e){C([e]),this.attributes.push(e)}setAttrs(e){C(e),this.attributes=e}toJSON(){let e={};for(let t of this.attributes){let n=t.shortName;typeof n==`string`&&n!==``&&(e[n]=t.value)}return e.uniqueId=this.uniqueId,e.attributes=this.attributes,e}getFieldValue(e){let t=this.getField(e);return t==null?``:t.value}};e.DistinguishedName=l,e.Certificate=class e{static fromPEMs(t){let n=[],i=r.PEM.parse(t);for(let t of i){if(t.type!==`CERTIFICATE`&&t.type!==`X509 CERTIFICATE`&&t.type!==`TRUSTED CERTIFICATE`)throw Error(`Could not convert certificate from PEM: invalid type`);if(t.procType.includes(`ENCRYPTED`))throw Error(`Could not convert certificate from PEM: PEM is encrypted.`);let i=r.ASN1.fromDER(t.body);n.push(new e(i))}if(n.length===0)throw Error(`No Certificate`);return n}static fromPEM(t){return e.fromPEMs(t)[0]}constructor(e){let t=Object.create(null),n=e.validate(c,t);if(n!=null)throw Error(`Cannot read X.509 certificate: `+n.message);if(this.raw=e.DER,this.version=t.certVersion==null?0:r.ASN1.parseIntegerNum(t.certVersion.bytes)+1,this.serialNumber=r.ASN1.parseIntegerStr(t.certSerialNumber.bytes),this.signatureOID=r.ASN1.parseOID(t.certSignatureOID.bytes),this.signatureAlgorithm=i.getOIDName(this.signatureOID),this.infoSignatureOID=r.ASN1.parseOID(t.certinfoSignatureOID.bytes),this.signature=r.ASN1.parseBitString(t.certSignature.bytes).buf,this.validFrom=r.ASN1.parseTime(t.certValidityNotBefore.tag,t.certValidityNotBefore.bytes),this.validTo=r.ASN1.parseTime(t.certValidityNotAfter.tag,t.certValidityNotAfter.bytes),this.issuer=new l,this.issuer.setAttrs(T(t.certIssuer)),t.certIssuerUniqueId!=null&&(this.issuer.uniqueId=r.ASN1.parseBitString(t.certIssuerUniqueId.bytes)),this.subject=new l,this.subject.setAttrs(T(t.certSubject)),t.certSubjectUniqueId!=null&&(this.subject.uniqueId=r.ASN1.parseBitString(t.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=[],t.certExtensions!=null){this.extensions=u(t.certExtensions);for(let e of this.extensions)if(typeof e.subjectKeyIdentifier==`string`&&(this.subjectKeyIdentifier=e.subjectKeyIdentifier),typeof e.authorityKeyIdentifier==`string`&&(this.authorityKeyIdentifier=e.authorityKeyIdentifier),typeof e.authorityInfoAccessOcsp==`string`&&(this.ocspServer=e.authorityInfoAccessOcsp),typeof e.authorityInfoAccessIssuers==`string`&&(this.issuingCertificateURL=e.authorityInfoAccessIssuers),typeof e.basicConstraintsValid==`boolean`&&(this.isCA=e.isCA,this.maxPathLen=e.maxPathLen,this.basicConstraintsValid=e.basicConstraintsValid),typeof e.keyUsage==`number`&&(this.keyUsage=e.keyUsage),Array.isArray(e.altNames))for(let t of e.altNames)t.dnsName!=null&&this.dnsNames.push(t.dnsName),t.email!=null&&this.emailAddresses.push(t.email),t.ip!=null&&this.ipAddresses.push(t.ip),t.uri!=null&&this.uris.push(t.uri)}this.publicKey=new a.PublicKey(t.publicKeyInfo),this.publicKeyRaw=this.publicKey.toDER(),this.tbsCertificate=t.tbsCertificate}getExtension(e,t=``){for(let n of this.extensions)if(e===n.oid||e===n.name)return t===``?n:n[t];return null}checkSignature(e){if(this.version===3&&!this.basicConstraintsValid||this.basicConstraintsValid&&!this.isCA||this.getExtension(`keyUsage`,`keyCertSign`)!==!0)return Error(`The parent constraint violation error`);if(!e.isIssuer(this))return Error(`The parent certificate did not issue the given child certificate`);let t=w(e.signatureOID);return t===``?Error(`Unknown child signature OID.`):this.publicKey.verify(e.tbsCertificate.DER,e.signature,t)===!1?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 t of Object.keys(this))e[t]=E(this[t]);return delete e.tbsCertificate,e}[t.inspect.custom](e,n){return n.depth<=2&&(n.depth=10),`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};function u(e){let t=[];for(let n of e.mustCompound())for(let e of n.mustCompound())t.push(d(e));return t}function d(e){let t={};switch(t.oid=r.ASN1.parseOID(e.value[0].bytes),t.critical=!1,e.value[1].tag===r.Tag.BOOLEAN?(t.critical=r.ASN1.parseBool(e.value[1].bytes),t.value=e.value[2].bytes):t.value=e.value[1].bytes,t.name=i.getOIDName(t.oid),t.name){case`keyUsage`:f(t);break;case`basicConstraints`:p(t);break;case`extKeyUsage`:m(t);break;case`nsCertType`:h(t);break;case`subjectAltName`:g(t);break;case`issuerAltName`:g(t);break;case`subjectKeyIdentifier`:v(t);break;case`authorityKeyIdentifier`:b(t);break;case`authorityInfoAccess`:S(t)}return t}function f(e){let t=r.ASN1.parseBitString(r.ASN1.fromDER(e.value).bytes),n=0,i=0;e.keyUsage=0;for(let n=0;n<9;n++)t.at(n)!==0&&(e.keyUsage|=1<<n);t.buf.length>0&&(n=t.buf[0],i=t.buf.length>1?t.buf[1]:0),e.digitalSignature=(n&128)==128,e.nonRepudiation=(n&64)==64,e.keyEncipherment=(n&32)==32,e.dataEncipherment=(n&16)==16,e.keyAgreement=(n&8)==8,e.keyCertSign=(n&4)==4,e.cRLSign=(n&2)==2,e.encipherOnly=(n&1)==1,e.decipherOnly=(i&128)==128}function p(e){let t=r.ASN1.fromDER(e.value).mustCompound();e.isCA=t.length>0&&t[0].tag===r.Tag.BOOLEAN&&r.ASN1.parseBool(t[0].bytes);let n=null;t.length>0&&t[0].tag===r.Tag.INTEGER?n=t[0].bytes:t.length>1&&(n=t[1].bytes),e.maxPathLen=n===null?-1:r.ASN1.parseInteger(n),e.basicConstraintsValid=!0}function m(e){let t=r.ASN1.fromDER(e.value).mustCompound();for(let n of t)e[i.getOIDName(r.ASN1.parseOID(n.bytes))]=!0}function h(e){let t=r.ASN1.parseBitString(r.ASN1.fromDER(e.value).bytes),n=0;t.buf.length>0&&(n=t.buf[0]),e.client=(n&128)==128,e.server=(n&64)==64,e.email=(n&32)==32,e.objsign=(n&16)==16,e.reserved=(n&8)==8,e.sslCA=(n&4)==4,e.emailCA=(n&2)==2,e.objCA=(n&1)==1}function g(e){e.altNames=[];let t=r.ASN1.fromDER(e.value).mustCompound();for(let n of t){let t={tag:n.tag,value:n.bytes};switch(e.altNames.push(t),n.tag){case 1:t.email=n.bytes.toString();break;case 2:t.dnsName=n.bytes.toString();break;case 6:t.uri=n.bytes.toString();break;case 7:t.ip=i.bytesToIP(n.bytes);break;case 8:t.oid=r.ASN1.parseOID(n.bytes)}}}var _={name:`subjectKeyIdentifier`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,capture:`subjectKeyIdentifier`};function v(e){e.subjectKeyIdentifier=r.ASN1.parseDERWithTemplate(e.value,_).subjectKeyIdentifier.bytes.toString(`hex`)}var y={name:`authorityKeyIdentifier`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`authorityKeyIdentifier.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.NONE,capture:`authorityKeyIdentifier`}]};function b(e){e.authorityKeyIdentifier=r.ASN1.parseDERWithTemplate(e.value,y).authorityKeyIdentifier.bytes.toString(`hex`)}var x={name:`authorityInfoAccess`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`authorityInfoAccess.authorityInfoAccessOcsp`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,optional:!0,value:[{name:`authorityInfoAccess.authorityInfoAccessOcsp.oid`,class:r.Class.UNIVERSAL,tag:r.Tag.OID},{name:`authorityInfoAccess.authorityInfoAccessOcsp.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.OID,capture:`authorityInfoAccessOcsp`}]},{name:`authorityInfoAccess.authorityInfoAccessIssuers`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,optional:!0,value:[{name:`authorityInfoAccess.authorityInfoAccessIssuers.oid`,class:r.Class.UNIVERSAL,tag:r.Tag.OID},{name:`authorityInfoAccess.authorityInfoAccessIssuers.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.OID,capture:`authorityInfoAccessIssuers`}]}]};function S(e){let t=r.ASN1.parseDERWithTemplate(e.value,x);t.authorityInfoAccessOcsp!=null&&(e.authorityInfoAccessOcsp=t.authorityInfoAccessOcsp.bytes.toString()),t.authorityInfoAccessIssuers!=null&&(e.authorityInfoAccessIssuers=t.authorityInfoAccessIssuers.bytes.toString())}function C(e){for(let t of e){if((t.name==null||t.name===``)&&(t.oid!=null&&(t.name=i.getOIDName(t.oid)),t.name===``&&t.shortName!=null&&(t.name=i.getOIDName(o[t.shortName]))),t.oid==null||t.oid===``){if(t.name!==``)t.oid=i.getOID(t.name);else throw Error(`Attribute oid not specified.`)}if((t.shortName==null||t.shortName===``)&&(t.shortName=o[t.name]==null?``:o[t.name]),t.value==null)throw Error(`Attribute value not specified.`)}}function w(e){switch(i.getOIDName(e)){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 T(e){let t=[];for(let n of e.mustCompound())for(let e of n.mustCompound()){let n=e.mustCompound(),a={};a.oid=r.ASN1.parseOID(n[0].bytes),a.value=n[1].value,a.valueTag=n[1].tag,a.name=i.getOIDName(a.oid),a.shortName=s(a.name),t.push(a)}return t}function E(e){return e!=null&&!(e instanceof Buffer)&&typeof e.toJSON==`function`?e.toJSON():e}})),ci=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ei();e.bytesFromIP=t.bytesFromIP,e.bytesToIP=t.bytesToIP,e.getOID=t.getOID,e.getOIDName=t.getOIDName;var n=oi();e.PublicKey=n.PublicKey,e.PrivateKey=n.PrivateKey,e.RSAPublicKey=n.RSAPublicKey,e.RSAPrivateKey=n.RSAPrivateKey;var r=si();e.Certificate=r.Certificate,e.DistinguishedName=r.DistinguishedName})),li=R((()=>{var e;(function(e){(function(t){var n=typeof globalThis==`object`?globalThis:typeof global==`object`?global:typeof self==`object`?self:typeof this==`object`?this:s(),r=i(e);n.Reflect!==void 0&&(r=i(n.Reflect,r)),t(r,n),n.Reflect===void 0&&(n.Reflect=e);function i(e,t){return function(n,r){Object.defineProperty(e,n,{configurable:!0,writable:!0,value:r}),t&&t(n,r)}}function a(){try{return Function(`return this;`)()}catch{}}function o(){try{return(0,eval)(`(function() { return this; })()`)}catch{}}function s(){return a()||o()}})(function(e,t){var n=Object.prototype.hasOwnProperty,r=typeof Symbol==`function`,i=r&&Symbol.toPrimitive!==void 0?Symbol.toPrimitive:`@@toPrimitive`,a=r&&Symbol.iterator!==void 0?Symbol.iterator:`@@iterator`,o=typeof Object.create==`function`,s={__proto__:[]}instanceof Array,c=!o&&!s,l={create:o?function(){return Ce(Object.create(null))}:s?function(){return Ce({__proto__:null})}:function(){return Ce({})},has:c?function(e,t){return n.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return n.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),d=typeof Map==`function`&&typeof Map.prototype.entries==`function`?Map:be(),f=typeof Set==`function`&&typeof Set.prototype.entries==`function`?Set:xe(),p=typeof WeakMap==`function`?WeakMap:Se(),m=r?Symbol.for(`@reflect-metadata:registry`):void 0,h=ge(),g=_e(h);function _(e,t,n,r){if(L(n)){if(!ie(e)||!oe(t))throw TypeError();return D(e,t)}if(!ie(e)||!B(t)||!B(r)&&!L(r)&&!R(r))throw TypeError();return R(r)&&(r=void 0),n=re(n),O(e,t,n,r)}e(`decorate`,_);function v(e,t){function n(n,r){if(!B(n)||!L(r)&&!se(r))throw TypeError();N(e,t,n,r)}return n}e(`metadata`,v);function y(e,t,n,r){if(!B(n))throw TypeError();return L(r)||(r=re(r)),N(e,t,n,r)}e(`defineMetadata`,y);function b(e,t,n){if(!B(t))throw TypeError();return L(n)||(n=re(n)),k(e,t,n)}e(`hasMetadata`,b);function x(e,t,n){if(!B(t))throw TypeError();return L(n)||(n=re(n)),A(e,t,n)}e(`hasOwnMetadata`,x);function S(e,t,n){if(!B(t))throw TypeError();return L(n)||(n=re(n)),j(e,t,n)}e(`getMetadata`,S);function C(e,t,n){if(!B(t))throw TypeError();return L(n)||(n=re(n)),M(e,t,n)}e(`getOwnMetadata`,C);function w(e,t){if(!B(e))throw TypeError();return L(t)||(t=re(t)),P(e,t)}e(`getMetadataKeys`,w);function T(e,t){if(!B(e))throw TypeError();return L(t)||(t=re(t)),F(e,t)}e(`getOwnMetadataKeys`,T);function E(e,t,n){if(!B(t)||(L(n)||(n=re(n)),!B(t)))throw TypeError();L(n)||(n=re(n));var r=ye(t,n,!1);return!L(r)&&r.OrdinaryDeleteMetadata(e,t,n)}e(`deleteMetadata`,E);function D(e,t){for(var n=e.length-1;n>=0;--n){var r=e[n],i=r(t);if(!L(i)&&!R(i)){if(!oe(i))throw TypeError();t=i}}return t}function O(e,t,n,r){for(var i=e.length-1;i>=0;--i){var a=e[i],o=a(t,n,r);if(!L(o)&&!R(o)){if(!B(o))throw TypeError();r=o}}return r}function k(e,t,n){if(A(e,t,n))return!0;var r=me(t);return!R(r)&&k(e,r,n)}function A(e,t,n){var r=ye(t,n,!1);return!L(r)&&te(r.OrdinaryHasOwnMetadata(e,t,n))}function j(e,t,n){if(A(e,t,n))return M(e,t,n);var r=me(t);if(!R(r))return j(e,r,n)}function M(e,t,n){var r=ye(t,n,!1);if(!L(r))return r.OrdinaryGetOwnMetadata(e,t,n)}function N(e,t,n,r){ye(n,r,!0).OrdinaryDefineOwnMetadata(e,t,n,r)}function P(e,t){var n=F(e,t),r=me(e);if(r===null)return n;var i=P(r,t);if(i.length<=0)return n;if(n.length<=0)return i;for(var a=new f,o=[],s=0,c=n;s<c.length;s++){var l=c[s],u=a.has(l);u||(a.add(l),o.push(l))}for(var d=0,p=i;d<p.length;d++){var l=p[d],u=a.has(l);u||(a.add(l),o.push(l))}return o}function F(e,t){var n=ye(e,t,!1);return n?n.OrdinaryOwnMetadataKeys(e,t):[]}function I(e){if(e===null)return 1;switch(typeof e){case`undefined`:return 0;case`boolean`:return 2;case`string`:return 3;case`symbol`:return 4;case`number`:return 5;case`object`:return e===null?1:6;default:return 6}}function L(e){return e===void 0}function R(e){return e===null}function z(e){return typeof e==`symbol`}function B(e){return typeof e==`object`?e!==null:typeof e==`function`}function V(e,t){switch(I(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var n=t===3?`string`:t===5?`number`:`default`,r=le(e,i);if(r!==void 0){var a=r.call(e,n);if(B(a))throw TypeError();return a}return ee(e,n==="default"?`number`:n)}function ee(e,t){if(t===`string`){var n=e.toString;if(ae(n)){var r=n.call(e);if(!B(r))return r}var i=e.valueOf;if(ae(i)){var r=i.call(e);if(!B(r))return r}}else{var i=e.valueOf;if(ae(i)){var r=i.call(e);if(!B(r))return r}var a=e.toString;if(ae(a)){var r=a.call(e);if(!B(r))return r}}throw TypeError()}function te(e){return!!e}function ne(e){return``+e}function re(e){var t=V(e,3);return z(t)?t:ne(t)}function ie(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)===`[object Array]`}function ae(e){return typeof e==`function`}function oe(e){return typeof e==`function`}function se(e){switch(I(e)){case 3:return!0;case 4:return!0;default:return!1}}function ce(e,t){return e===t||e!==e&&t!==t}function le(e,t){var n=e[t];if(n!=null){if(!ae(n))throw TypeError();return n}}function ue(e){var t=le(e,a);if(!ae(t))throw TypeError();var n=t.call(e);if(!B(n))throw TypeError();return n}function de(e){return e.value}function fe(e){var t=e.next();return!t.done&&t}function pe(e){var t=e.return;t&&t.call(e)}function me(e){var t=Object.getPrototypeOf(e);if(typeof e!=`function`||e===u||t!==u)return t;var n=e.prototype,r=n&&Object.getPrototypeOf(n);if(r==null||r===Object.prototype)return t;var i=r.constructor;return typeof i!=`function`||i===e?t:i}function he(){var e;!L(m)&&t.Reflect!==void 0&&!(m in t.Reflect)&&typeof t.Reflect.defineMetadata==`function`&&(e=ve(t.Reflect));var n,r,i,a=new p,o={registerProvider:s,getProvider:l,setProvider:h};return o;function s(t){if(!Object.isExtensible(o))throw Error(`Cannot add provider to a frozen registry.`);switch(!0){case e===t:break;case L(n):n=t;break;case n===t:break;case L(r):r=t;break;case r===t:break;default:i===void 0&&(i=new f),i.add(t)}}function c(t,a){if(!L(n)){if(n.isProviderFor(t,a))return n;if(!L(r)){if(r.isProviderFor(t,a))return n;if(!L(i))for(var o=ue(i);;){var s=fe(o);if(!s)return;var c=de(s);if(c.isProviderFor(t,a))return pe(o),c}}}if(!L(e)&&e.isProviderFor(t,a))return e}function l(e,t){var n=a.get(e),r;return L(n)||(r=n.get(t)),L(r)?(r=c(e,t),L(r)||(L(n)&&(n=new d,a.set(e,n)),n.set(t,r)),r):r}function u(e){if(L(e))throw TypeError();return n===e||r===e||!L(i)&&i.has(e)}function h(e,t,n){if(!u(n))throw Error(`Metadata provider not registered.`);var r=l(e,t);if(r!==n){if(!L(r))return!1;var i=a.get(e);L(i)&&(i=new d,a.set(e,i)),i.set(t,n)}return!0}}function ge(){var e;return!L(m)&&B(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[m]),L(e)&&(e=he()),!L(m)&&B(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,m,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function _e(e){var t=new p,n={isProviderFor:function(e,n){var r=t.get(e);return!L(r)&&r.has(n)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:a,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:c};return h.registerProvider(n),n;function r(r,i,a){var o=t.get(r),s=!1;if(L(o)){if(!a)return;o=new d,t.set(r,o),s=!0}var c=o.get(i);if(L(c)){if(!a)return;if(c=new d,o.set(i,c),!e.setProvider(r,i,n))throw o.delete(i),s&&t.delete(r),Error(`Wrong provider for target.`)}return c}function i(e,t,n){var i=r(t,n,!1);return!L(i)&&te(i.has(e))}function a(e,t,n){var i=r(t,n,!1);if(!L(i))return i.get(e)}function o(e,t,n,i){r(n,i,!0).set(e,t)}function s(e,t){var n=[],i=r(e,t,!1);if(L(i))return n;for(var a=ue(i.keys()),o=0;;){var s=fe(a);if(!s)return n.length=o,n;var c=de(s);try{n[o]=c}catch(e){try{pe(a)}finally{throw e}}o++}}function c(e,n,i){var a=r(n,i,!1);if(L(a)||!a.delete(e))return!1;if(a.size===0){var o=t.get(n);L(o)||(o.delete(i),o.size===0&&t.delete(o))}return!0}}function ve(e){var t=e.defineMetadata,n=e.hasOwnMetadata,r=e.getOwnMetadata,i=e.getOwnMetadataKeys,a=e.deleteMetadata,o=new p;return{isProviderFor:function(e,t){var n=o.get(e);return!L(n)&&n.has(t)?!0:i(e,t).length?(L(n)&&(n=new f,o.set(e,n)),n.add(t),!0):!1},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:n,OrdinaryGetOwnMetadata:r,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:a}}function ye(e,t,n){var r=h.getProvider(e,t);if(!L(r))return r;if(n){if(h.setProvider(e,t,g))return g;throw Error(`Illegal state.`)}}function be(){var e={},t=[],n=function(){function e(e,t,n){this._index=0,this._keys=e,this._values=t,this._selector=n}return e.prototype[`@@iterator`]=function(){return this},e.prototype[a]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var n=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:n,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}();return function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var n=this._find(e,!0);return this._values[n]=t,this},t.prototype.delete=function(t){var n=this._find(t,!1);if(n>=0){for(var r=this._keys.length,i=n+1;i<r;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,ce(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new n(this._keys,this._values,r)},t.prototype.values=function(){return new n(this._keys,this._values,i)},t.prototype.entries=function(){return new n(this._keys,this._values,o)},t.prototype[`@@iterator`]=function(){return this.entries()},t.prototype[a]=function(){return this.entries()},t.prototype._find=function(e,t){if(!ce(this._cacheKey,e)){this._cacheIndex=-1;for(var n=0;n<this._keys.length;n++)if(ce(this._keys[n],e)){this._cacheIndex=n;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();function r(e,t){return e}function i(e,t){return t}function o(e,t){return[e,t]}}function xe(){return function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype[`@@iterator`]=function(){return this.keys()},e.prototype[a]=function(){return this.keys()},e}()}function Se(){var e=l.create(),t=r();return function(){function e(){this._key=r()}return e.prototype.has=function(e){var t=i(e,!1);return t!==void 0&&l.has(t,this._key)},e.prototype.get=function(e){var t=i(e,!1);return t===void 0?void 0:l.get(t,this._key)},e.prototype.set=function(e,t){var n=i(e,!0);return n[this._key]=t,this},e.prototype.delete=function(e){var t=i(e,!1);return t!==void 0&&delete t[this._key]},e.prototype.clear=function(){this._key=r()},e}();function r(){var t;do t=`@@WeakMap@@`+s();while(l.has(e,t));return e[t]=!0,t}function i(e,r){if(!n.call(e,t)){if(!r)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function a(e,t){for(var n=0;n<t;++n)e[n]=Math.random()*255|0;return e}function o(e){if(typeof Uint8Array==`function`){var t=new Uint8Array(e);return typeof crypto<`u`?crypto.getRandomValues(t):typeof msCrypto<`u`?msCrypto.getRandomValues(t):a(t,e),t}return a(Array(e),e)}function s(){var e=o(16);e[6]=e[6]&79|64,e[8]=e[8]&191|128;for(var t=``,n=0;n<16;++n){var r=e[n];(n===4||n===6||n===8)&&(t+=`-`),r<16&&(t+=`0`),t+=r.toString(16).toLowerCase()}return t}}function Ce(e){return e.__=void 0,delete e.__,e}})})(e||={})})),ui=V($r(),1),di=ci();li();var fi=`[object ArrayBuffer]`,U=class e{static isArrayBuffer(e){return Object.prototype.toString.call(e)===fi}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,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw 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(t,n){let r=e.toUint8Array(t),i=e.toUint8Array(n);if(r.length!==i.byteLength)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1;return!0}static concat(...e){let t;t=Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e;let n=0;for(let e of t)n+=e.byteLength;let r=new Uint8Array(n),i=0;for(let e of t){let t=this.toUint8Array(e);r.set(t,i),i+=t.length}return e[e.length-1]instanceof Function?this.toView(r,e[e.length-1]):r.buffer}},pi=`string`,mi=/^[0-9a-f\s]+$/i,hi=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,gi=/^[a-zA-Z0-9-_]+$/,_i=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}static toString(e){let t=U.toUint8Array(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return decodeURIComponent(escape(n))}},vi=class{static toString(e,t=!1){let n=U.toArrayBuffer(e),r=new DataView(n),i=``;for(let e=0;e<n.byteLength;e+=2){let n=r.getUint16(e,t);i+=String.fromCharCode(n)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),r=new DataView(n);for(let n=0;n<e.length;n++)r.setUint16(n*2,e.charCodeAt(n),t);return n}},yi=class e{static isHex(e){return typeof e===pi&&mi.test(e)}static isBase64(e){return typeof e===pi&&hi.test(e)}static isBase64Url(e){return typeof e===pi&&gi.test(e)}static ToString(e,t=`utf8`){let n=U.toUint8Array(e);switch(t.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 vi.toString(n,!0);case`utf16`:case`utf16be`:return vi.toString(n);default:throw Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t=`utf8`){if(!e)return new ArrayBuffer(0);switch(t.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 vi.fromString(e,!0);case`utf16`:case`utf16be`:return vi.fromString(e);default:throw Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=U.toUint8Array(e);if(typeof btoa<`u`){let e=this.ToString(t,`binary`);return btoa(e)}return Buffer.from(t).toString(`base64`)}static FromBase64(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!e.isBase64(n))throw TypeError(`Argument 'base64Text' is not Base64 encoded`);return typeof atob<`u`?this.FromBinary(atob(n)):new Uint8Array(Buffer.from(n,`base64`)).buffer}static FromBase64Url(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!e.isBase64Url(n))throw TypeError(`Argument 'base64url' is not Base64Url encoded`);return this.FromBase64(this.Base64Padding(n.replace(/\-/g,`+`).replace(/\_/g,`/`)))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/\=/g,``)}static FromUtf8String(t,n=e.DEFAULT_UTF8_ENCODING){switch(n){case`ascii`:return this.FromBinary(t);case`utf8`:return _i.fromString(t);case`utf16`:case`utf16be`:return vi.fromString(t);case`utf16le`:case`usc2`:return vi.fromString(t,!0);default:throw Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(t,n=e.DEFAULT_UTF8_ENCODING){switch(n){case`ascii`:return this.ToBinary(t);case`utf8`:return _i.toString(t);case`utf16`:case`utf16be`:return vi.toString(t);case`utf16le`:case`usc2`:return vi.toString(t,!0);default:throw Error(`Unknown type of encoding '${n}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return n.buffer}static ToBinary(e){let t=U.toUint8Array(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return n}static ToHex(e){let t=U.toUint8Array(e),n=``,r=t.length;for(let e=0;e<r;e++){let r=t[e];r<16&&(n+=`0`),n+=r.toString(16)}return n}static FromHex(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!e.isHex(n))throw TypeError(`Argument 'hexString' is not HEX encoded`);n.length%2&&(n=`0${n}`);let r=new Uint8Array(n.length/2);for(let e=0;e<n.length;e+=2){let t=n.slice(e,e+2);r[e/2]=parseInt(t,16)}return r.buffer}static ToUtf16String(e,t=!1){return vi.toString(e,t)}static FromUtf16String(e,t=!1){return vi.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+=`=`;return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,``)||``}};yi.DEFAULT_UTF8_ENCODING=`utf8`;function bi(...e){let t=e.map(e=>e.byteLength).reduce((e,t)=>e+t),n=new Uint8Array(t),r=0;return e.map(e=>new Uint8Array(e)).forEach(e=>{for(let t of e)n[r++]=t}),n.buffer}function xi(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;let n=new Uint8Array(e),r=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(n[t]!==r[t])return!1;return!0}function Si(e,t){let n=0;if(e.length===1)return e[0];for(let r=e.length-1;r>=0;r--)n+=e[e.length-1-r]*2**(t*r);return n}function Ci(e,t,n=-1){let r=n,i=e,a=0,o=2**t;for(let n=1;n<8;n++){if(e<o){let e;if(r<0)e=new ArrayBuffer(n),a=n;else{if(r<n)return new ArrayBuffer(0);e=new ArrayBuffer(r),a=r}let o=new Uint8Array(e);for(let e=n-1;e>=0;e--){let n=2**(e*t);o[a-e-1]=Math.floor(i/n),i-=o[a-e-1]*n}return e}o*=2**t}return new ArrayBuffer(0)}function wi(...e){let t=0,n=0;for(let n of e)t+=n.length;let r=new ArrayBuffer(t),i=new Uint8Array(r);for(let t of e)i.set(t,n),n+=t.length;return i}function Ti(){let e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let t=e[0]===255&&e[1]&128,n=e[0]===0&&!(e[1]&128);(t||n)&&this.warnings.push(`Needlessly long format`)}let t=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)n[e]=0;n[0]=e[0]&128;let r=Si(n,8),i=new ArrayBuffer(this.valueHex.byteLength),a=new Uint8Array(i);for(let t=0;t<this.valueHex.byteLength;t++)a[t]=e[t];return a[0]&=127,Si(a,8)-r}function Ei(e){let t=e<0?e*-1:e,n=128;for(let r=1;r<8;r++){if(t<=n){if(e<0){let e=Ci(n-t,8,r),i=new Uint8Array(e);return i[0]|=128,e}let i=Ci(t,8,r),a=new Uint8Array(i);if(a[0]&128){let e=i.slice(0),t=new Uint8Array(e);i=new ArrayBuffer(i.byteLength+1),a=new Uint8Array(i);for(let n=0;n<e.byteLength;n++)a[n+1]=t[n];a[0]=0}return i}n*=256}return new ArrayBuffer(0)}function Di(e,t){if(e.byteLength!==t.byteLength)return!1;let n=new Uint8Array(e),r=new Uint8Array(t);for(let e=0;e<n.length;e++)if(n[e]!==r[e])return!1;return!0}function Oi(e,t){let n=e.toString(10);if(t<n.length)return``;let r=t-n.length,i=Array.from({length:r});for(let e=0;e<r;e++)i[e]=`0`;return i.join(``).concat(n)}var ki=z({Any:()=>Qo,BaseBlock:()=>ra,BaseStringBlock:()=>aa,BitString:()=>za,BmpString:()=>go,Boolean:()=>Na,CharacterString:()=>Lo,Choice:()=>$o,Constructed:()=>Ta,DATE:()=>Uo,DEFAULT_MAX_CONTENT_LENGTH:()=>ua,DEFAULT_MAX_DEPTH:()=>100,DEFAULT_MAX_NODES:()=>la,DateTime:()=>qo,Duration:()=>Yo,EndOfContent:()=>Oa,Enumerated:()=>Ja,GeneralString:()=>Fo,GeneralizedTime:()=>Vo,GraphicString:()=>jo,HexBlock:()=>Qi,IA5String:()=>ko,Integer:()=>Ka,Null:()=>Aa,NumericString:()=>xo,ObjectIdentifier:()=>Qa,OctetString:()=>Ia,Primitive:()=>ca,PrintableString:()=>Co,RawData:()=>ts,RelativeObjectIdentifier:()=>no,Repeated:()=>es,Sequence:()=>io,Set:()=>oo,TIME:()=>Zo,TeletexString:()=>To,TimeOfDay:()=>Go,UTCTime:()=>zo,UniversalString:()=>yo,Utf8String:()=>po,ValueBlock:()=>ea,VideotexString:()=>Do,ViewWriter:()=>Ni,VisibleString:()=>No,compareSchema:()=>ns,fromBER:()=>xa,verifySchema:()=>rs});function Ai(){if(typeof BigInt>`u`)throw Error(`BigInt is not defined. Your environment doesn't implement BigInt.`)}function ji(e){let t=0,n=0;for(let n=0;n<e.length;n++){let r=e[n];t+=r.byteLength}let r=new Uint8Array(t);for(let t=0;t<e.length;t++){let i=e[t];r.set(new Uint8Array(i),n),n+=i.byteLength}return r.buffer}function Mi(e,t,n,r){return t instanceof Uint8Array?t.byteLength?n<0?(e.error=`Wrong parameter: inputOffset less than zero`,!1):r<0?(e.error=`Wrong parameter: inputLength less than zero`,!1):t.byteLength-n-r<0?(e.error=`End of input reached before message was fully decoded (inconsistent offset and length values)`,!1):!0:(e.error=`Wrong parameter: inputBuffer has zero length`,!1):(e.error=`Wrong parameter: inputBuffer must be 'Uint8Array'`,!1)}var Ni=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return ji(this.items)}},Pi=[new Uint8Array([1])],Fi=`0123456789`,Ii=`name`,Li=`valueHexView`,Ri=`isHexOnly`,zi=`idBlock`,Bi=`tagClass`,Vi=`tagNumber`,Hi=`isConstructed`,Ui=`fromBER`,Wi=`toBER`,Gi=`local`,Ki=``,qi=new ArrayBuffer(0),Ji=new Uint8Array,Yi=`EndOfContent`,Xi=`OCTET STRING`,Zi=`BIT STRING`;function Qi(e){var t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){super(...e);let t=e[0]||{};this.isHexOnly=t.isHexOnly??!1,this.valueHexView=t.valueHex?U.toUint8Array(t.valueHex):Ji}fromBER(e,t,n,r){let i=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Mi(this,i,t,n))return-1;let a=t+n;return this.valueHexView=i.subarray(t,a),this.valueHexView.length?(this.blockLength=n,a):(this.warnings.push(`Zero buffer length`),t)}toBER(e=!1){return this.isHexOnly?e?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`,qi)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:yi.ToHex(this.valueHexView)}}};return t.NAME=`hexBlock`,t}var $i=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:t=Ki,warnings:n=[],valueBeforeDecode:r=Ji}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=U.toUint8Array(r)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:yi.ToHex(this.valueBeforeDecodeView)}}};$i.NAME=`baseBlock`;var ea=class extends $i{fromBER(e,t,n,r){throw TypeError(`User need to make a specific function in a class which extends 'ValueBlock'`)}toBER(e,t){throw TypeError(`User need to make a specific function in a class which extends 'ValueBlock'`)}};ea.NAME=`valueBlock`;var ta=class extends Qi($i){constructor({idBlock:e={}}={}){super(),e?(this.isHexOnly=e.isHexOnly??!1,this.valueHexView=e.valueHex?U.toUint8Array(e.valueHex):Ji,this.tagClass=e.tagClass??-1,this.tagNumber=e.tagNumber??-1,this.isConstructed=e.isConstructed??!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error=`Unknown tag class`,qi}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let n=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,n[0]=t}return n.buffer}if(!this.isHexOnly){let n=Ci(this.tagNumber,7),r=new Uint8Array(n),i=n.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let e=0;e<i-1;e++)a[e+1]=r[e]|128;a[i]=r[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let e=this.valueHexView;for(let t=0;t<e.length-1;t++)n[t+1]=e[t]|128;n[this.valueHexView.byteLength]=e[e.length-1]}return n.buffer}fromBER(e,t,n){let r=U.toUint8Array(e);if(!Mi(this,r,t,n))return-1;let i=r.subarray(t,t+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 e=0;for(;;){let t=e+1;if(t>=i.length)return this.error=`End of input reached before message was fully decoded`,-1;if(e++,!(i[t]&128))break}this.blockLength=e+1;let t=this.valueHexView=new Uint8Array(e);for(let n=0;n<e;n++)t[n]=i[n+1]&127;this.blockLength<=9?this.tagNumber=Si(t,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 t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ta.NAME=`identificationBlock`;var na=class extends $i{constructor({lenBlock:e={}}={}){super(),this.isIndefiniteForm=e.isIndefiniteForm??!1,this.longFormUsed=e.longFormUsed??!1,this.length=e.length??0}fromBER(e,t,n){let r=U.toUint8Array(e);if(!Mi(this,r,t,n))return-1;let i=r.subarray(t,t+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,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let a=i[0]&127;if(a>8)return this.error=`Too big integer`,-1;if(a+1>i.length)return this.error=`End of input reached before message was fully decoded`,-1;let o=t+1,s=r.subarray(o,o+a);return s[a-1]===0&&this.warnings.push(`Needlessly long encoded length`),this.length=Si(s,8),this.longFormUsed&&this.length<=127&&this.warnings.push(`Unnecessary usage of long length form`),this.blockLength=a+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let r=Ci(this.length,8);if(r.byteLength>127)return this.error=`Too big length`,qi;if(t=new ArrayBuffer(r.byteLength+1),e)return t;let i=new Uint8Array(r);n=new Uint8Array(t),n[0]=r.byteLength|128;for(let e=0;e<r.byteLength;e++)n[e+1]=i[e];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};na.NAME=`lengthBlock`;var W={},ra=class extends $i{constructor({name:e=Ki,optional:t=!1,primitiveSchema:n,...r}={},i){super(r),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ta(r),this.lenBlock=new na(r),this.valueBlock=i?new i(r):new ea(r)}fromBER(e,t,n,r){let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,r);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,t){let n=t||new Ni;t||ia(this);let r=this.idBlock.toBER(e);if(n.write(r),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;let r=this.lenBlock.toBER(e);n.write(r),n.write(t)}return t?qi: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():yi.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${yi.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&Di(this.toBER(),e.toBER())}};ra.NAME=`BaseBlock`;function ia(e){if(e instanceof W.Constructed)for(let t of e.valueBlock.value)ia(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock?.isIndefiniteForm}var aa=class extends ra{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Ki,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(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),r)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};aa.NAME=`BaseStringBlock`;var oa=class extends Qi(ea){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};oa.NAME=`PrimitiveValueBlock`;var sa,ca=class extends ra{constructor(e={}){super(e,oa),this.idBlock.isConstructed=!1}};sa=ca,W.Primitive=sa,ca.NAME=`PRIMITIVE`;var la=1e4,ua=16777216,da=`Maximum ASN.1 nesting depth exceeded`,fa=`Maximum ASN.1 node count exceeded`,pa=`Maximum ASN.1 content length exceeded`;function ma(e={}){return{depth:0,maxDepth:e.maxDepth??100,nodesCount:0,maxNodes:e.maxNodes??la,maxContentLength:e.maxContentLength??ua}}function ha(e){let t=new ra({},ea);return t.error=e,{offset:-1,result:t}}function ga(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return fa}function _a(e,t){if(e>t.maxContentLength)return pa}function va(e,t,n,r){let i=r.depth+1;if(i>r.maxDepth)return ha(da);r.depth=i;try{return ba(e,t,n,r)}finally{--r.depth}}function ya(e,t){if(e instanceof t)return e;let n=new t;return n.idBlock=e.idBlock,n.lenBlock=e.lenBlock,n.warnings=e.warnings,n.valueBeforeDecodeView=e.valueBeforeDecodeView,n}function ba(e,t=0,n=e.length,r=ma()){let i=t,a=new ra({},ea),o=new $i;if(!Mi(o,e,t,n))return a.error=o.error,{offset:-1,result:a};if(!e.subarray(t,t+n).length)return a.error=`Zero buffer length`,{offset:-1,result:a};let s=ga(r);if(s)return a.error=s,{offset:-1,result:a};let c=a.idBlock.fromBER(e,t,n);if(a.idBlock.warnings.length&&a.warnings.concat(a.idBlock.warnings),c===-1)return a.error=a.idBlock.error,{offset:-1,result:a};if(t=c,n-=a.idBlock.blockLength,c=a.lenBlock.fromBER(e,t,n),a.lenBlock.warnings.length&&a.warnings.concat(a.lenBlock.warnings),c===-1)return a.error=a.lenBlock.error,{offset:-1,result:a};t=c,n-=a.lenBlock.blockLength;let l=a.lenBlock.isIndefiniteForm?n:a.lenBlock.length,u=_a(l,r);if(u)return a.error=u,{offset:-1,result:a};if(!a.idBlock.isConstructed&&a.lenBlock.isIndefiniteForm)return a.error=`Indefinite length form used for primitive encoding form`,{offset:-1,result:a};let d=ra;switch(a.idBlock.tagClass){case 1:if(a.idBlock.tagNumber>=37&&a.idBlock.isHexOnly===!1)return a.error=`UNIVERSAL 37 and upper tags are reserved by ASN.1 standard`,{offset:-1,result:a};switch(a.idBlock.tagNumber){case 0:if(a.idBlock.isConstructed&&a.lenBlock.length>0)return a.error=`Type [UNIVERSAL 0] is reserved`,{offset:-1,result:a};d=W.EndOfContent;break;case 1:d=W.Boolean;break;case 2:d=W.Integer;break;case 3:d=W.BitString;break;case 4:d=W.OctetString;break;case 5:d=W.Null;break;case 6:d=W.ObjectIdentifier;break;case 10:d=W.Enumerated;break;case 12:d=W.Utf8String;break;case 13:d=W.RelativeObjectIdentifier;break;case 14:d=W.TIME;break;case 15:return a.error=`[UNIVERSAL 15] is reserved by ASN.1 standard`,{offset:-1,result:a};case 16:d=W.Sequence;break;case 17:d=W.Set;break;case 18:d=W.NumericString;break;case 19:d=W.PrintableString;break;case 20:d=W.TeletexString;break;case 21:d=W.VideotexString;break;case 22:d=W.IA5String;break;case 23:d=W.UTCTime;break;case 24:d=W.GeneralizedTime;break;case 25:d=W.GraphicString;break;case 26:d=W.VisibleString;break;case 27:d=W.GeneralString;break;case 28:d=W.UniversalString;break;case 29:d=W.CharacterString;break;case 30:d=W.BmpString;break;case 31:d=W.DATE;break;case 32:d=W.TimeOfDay;break;case 33:d=W.DateTime;break;case 34:d=W.Duration;break;default:{let e=a.idBlock.isConstructed?new W.Constructed:new W.Primitive;e.idBlock=a.idBlock,e.lenBlock=a.lenBlock,e.warnings=a.warnings,a=e}}break;default:d=a.idBlock.isConstructed?W.Constructed:W.Primitive}return a=ya(a,d),c=a.fromBER(e,t,l,r),a.valueBeforeDecodeView=e.subarray(i,i+a.blockLength),{offset:c,result:a}}function xa(e,t={}){if(!e.byteLength){let e=new ra({},ea);return e.error=`Input buffer has zero length`,{offset:-1,result:e}}return ba(U.toUint8Array(e).slice(),0,e.byteLength,ma(t))}function Sa(e,t){return e?1:t}var Ca=class extends ea{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,r){let i=U.toUint8Array(e),a=r??ma();if(!Mi(this,i,t,n))return-1;if(this.valueBeforeDecodeView=i.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push(`Zero buffer length`),t;let o=t;for(;Sa(this.isIndefiniteForm,n)>0;){let e=va(i,o,n,a);if(e.offset===-1)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(o=e.offset,this.blockLength+=e.result.blockLength,n-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===Yi)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Yi?this.value.pop():this.warnings.push(`No EndOfContent block encoded`)),o}toBER(e,t){let n=t||new Ni;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,n);return t?qi:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};Ca.NAME=`ConstructedValueBlock`;var wa,Ta=class extends ra{constructor(e={}){super(e,Ca),this.idBlock.isConstructed=!0}fromBER(e,t,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,r);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 t of this.valueBlock.value)e.push(t.toString(`ascii`).split(`
|
|
23
|
+
`,e}toBuffer(){return Buffer.from(this.toString(),`utf8`)}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};e.PEM=s;function c(e){let t=e.shift();if(t==null||!t.startsWith(r)||!t.endsWith(a))throw Error(`pem: invalid BEGIN line`);let n=t.slice(11,t.length-5);if(n===``)throw Error(`pem: invalid type`);let o=[];for(t=e.shift();t!=null&&t.includes(`: `);){let n=t.split(`: `);if(n.length!==2||n[0]===``||n[1]===``)throw Error(`pem: invalid Header line`);o.push(n),t=e.shift()}let c=``;for(;t!=null&&!t.startsWith(i);)c+=t,t=e.shift();if(t==null||t!==`${i}${n}${a}`)throw Error(`pem: invalid END line`);let l=new s(n,Buffer.from(c,`base64`));if(c===``||l.body.toString(`base64`)!==c)throw Error(`pem: invalid base64 body`);for(let e of o)l.setHeader(e[0],e[1]);return l}})),Rd=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ne(`util`),n=Id(),r;(function(e){e[e.UNIVERSAL=0]=`UNIVERSAL`,e[e.APPLICATION=64]=`APPLICATION`,e[e.CONTEXT_SPECIFIC=128]=`CONTEXT_SPECIFIC`,e[e.PRIVATE=192]=`PRIVATE`})(r=e.Class||={});var i;(function(e){e[e.NONE=0]=`NONE`,e[e.BOOLEAN=1]=`BOOLEAN`,e[e.INTEGER=2]=`INTEGER`,e[e.BITSTRING=3]=`BITSTRING`,e[e.OCTETSTRING=4]=`OCTETSTRING`,e[e.NULL=5]=`NULL`,e[e.OID=6]=`OID`,e[e.ENUMERATED=10]=`ENUMERATED`,e[e.UTF8=12]=`UTF8`,e[e.SEQUENCE=16]=`SEQUENCE`,e[e.SET=17]=`SET`,e[e.NUMERICSTRING=18]=`NUMERICSTRING`,e[e.PRINTABLESTRING=19]=`PRINTABLESTRING`,e[e.T61STRING=20]=`T61STRING`,e[e.IA5STRING=22]=`IA5STRING`,e[e.UTCTIME=23]=`UTCTIME`,e[e.GENERALIZEDTIME=24]=`GENERALIZEDTIME`,e[e.GENERALSTRING=27]=`GENERALSTRING`})(i=e.Tag||={});var a=class{constructor(e,t){this.buf=e,this.bitLen=t}at(e){if(e<0||e>=this.bitLen||!Number.isInteger(e))return 0;let t=Math.floor(e/8),n=7-e%8;return this.buf[t]>>n&1}rightAlign(){let e=8-this.bitLen%8;if(e===8||this.buf.length===0)return this.buf;let t=Buffer.alloc(this.buf.length);t[0]=this.buf[0]>>e;for(let n=1;n<this.buf.length;n++)t[n]=this.buf[n-1]<<8-e,t[n]|=this.buf[n]>>e;return t}};e.BitString=a,e.ASN1=class e{static Bool(t){let n=new e(r.UNIVERSAL,i.BOOLEAN,Buffer.from([t?255:0]));return n._value=t,n}static parseBool(e){if(!(e instanceof Buffer)||e.length!==1)throw Error(`ASN1 syntax error: invalid boolean`);switch(e[0]){case 0:return!1;case 255:return!0;default:throw Error(`ASN1 syntax error: invalid boolean`)}}static Integer(t){if(t instanceof Buffer){let n=new e(r.UNIVERSAL,i.INTEGER,t);return n._value=t.toString(`hex`),n}if(!Number.isSafeInteger(t))throw Error(`ASN1 syntax error: invalid integer`);let n;if(t>=-128&&t<128)n=Buffer.alloc(1),n.writeInt8(t,0);else if(t>=-32768&&t<32768)n=Buffer.alloc(2),n.writeIntBE(t,0,2);else if(t>=-8388608&&t<8388608)n=Buffer.alloc(3),n.writeIntBE(t,0,3);else if(t>=-2147483648&&t<2147483648)n=Buffer.alloc(4),n.writeIntBE(t,0,4);else if(t>=-549755813888&&t<549755813888)n=Buffer.alloc(5),n.writeIntBE(t,0,5);else if(t>=-0x800000000000&&t<0x800000000000)n=Buffer.alloc(6),n.writeIntBE(t,0,6);else throw Error(`ASN1 syntax error: invalid Integer`);let a=new e(r.UNIVERSAL,i.INTEGER,n);return a._value=t,a}static parseInteger(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid Integer`);return e.length>6?e.toString(`hex`):e.readIntBE(0,e.length)}static parseIntegerNum(t){let n=e.parseInteger(t);if(typeof n!=`number`)throw Error(`ASN1 syntax error: invalid Integer number`);return n}static parseIntegerStr(t){let n=e.parseInteger(t);return typeof n==`number`?n.toString(16):n}static BitString(t){t instanceof Buffer&&(t=new a(t,t.length*8));let n=t.buf.length*8-t.bitLen,o=Buffer.alloc(t.buf.length+1);return o.writeInt8(n,0),t.buf.copy(o,1),new e(r.UNIVERSAL,i.BITSTRING,o)}static parseBitString(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid BitString`);let t=e[0];if(t>7||e.length===1&&t>0||e[e.length-1]&(1<<e[0])-1)throw Error(`ASN1 syntax error: invalid padding bits in BIT STRING`);return new a(e.slice(1),(e.length-1)*8-t)}static Null(){let t=new e(r.UNIVERSAL,i.NULL,Buffer.alloc(0));return t._value=null,t}static parseNull(e){if(!(e instanceof Buffer)||e.length!==0)throw Error(`ASN1 syntax error: invalid null`);return null}static OID(t){let n=t.split(`.`);if(n.length===0)throw Error(`ASN1 syntax error: invalid Object Identifier`);let a=[];a.push(40*u(n[0])+u(n[1]));let o=[];for(let e=2;e<n.length;++e){let t=u(n[e]);for(o.length=0,o.push(t&127);t>127;)t>>>=7,o.unshift(t&127|128);a.push(...o)}let s=new e(r.UNIVERSAL,i.OID,Buffer.from(a));return s._value=t,s}static parseOID(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid OID`);let t=Math.floor(e[0]/40)+`.`+e[0]%40,n=0;for(let r=1;r<e.length;r++)e[r]>=128?(n+=e[r]&127,n<<=7):(t+=`.`+(n+e[r]),n=0);return t}static UTF8(t){let n=new e(r.UNIVERSAL,i.UTF8,Buffer.from(t,`utf8`));return n._value=t,n}static parseUTF8(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static NumericString(t){if(!c(t))throw Error(`ASN1 syntax error: invalid NumericString`);let n=new e(r.UNIVERSAL,i.NUMERICSTRING,Buffer.from(t,`utf8`));return n._value=t,n}static parseNumericString(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);let t=e.toString(`utf8`);if(!c(t))throw Error(`ASN1 syntax error: invalid NumericString`);return t}static PrintableString(t){let n=new e(r.UNIVERSAL,i.PRINTABLESTRING,Buffer.from(t,`utf8`));return n._value=t,n}static parsePrintableString(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static IA5String(t){if(!l(t))throw Error(`ASN1 syntax error: invalid IA5String`);let n=new e(r.UNIVERSAL,i.IA5STRING,Buffer.from(t,`utf8`));return n._value=t,n}static parseIA5String(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);let t=e.toString(`utf8`);if(!l(t))throw Error(`ASN1 syntax error: invalid IA5String`);return t}static T61String(t){let n=new e(r.UNIVERSAL,i.T61STRING,Buffer.from(t,`utf8`));return n._value=t,n}static parseT61String(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static GeneralString(t){let n=new e(r.UNIVERSAL,i.GENERALSTRING,Buffer.from(t,`utf8`));return n._value=t,n}static parseGeneralString(e){if(!(e instanceof Buffer))throw Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static UTCTime(t){let n=``,a=[];a.push((``+t.getUTCFullYear()).substr(2)),a.push(``+(t.getUTCMonth()+1)),a.push(``+t.getUTCDate()),a.push(``+t.getUTCHours()),a.push(``+t.getUTCMinutes()),a.push(``+t.getUTCSeconds());for(let e of a)e.length<2&&(n+=`0`),n+=e;n+=`Z`;let o=new e(r.UNIVERSAL,i.UTCTIME,Buffer.from(n,`utf8`));return o._value=t,o}static parseUTCTime(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid UTC Time`);let t=e.toString(`utf8`),n=new Date,r=u(t.substr(0,2));r=r>=50?1900+r:2e3+r;let i=u(t.substr(2,2))-1,a=u(t.substr(4,2)),o=u(t.substr(6,2)),s=u(t.substr(8,2)),c=0,l=0,d=``;if(t.length>11&&(l=10,d=t.charAt(l),d!==`+`&&d!==`-`&&(c=u(t.substr(10,2)),l+=2)),n.setUTCFullYear(r,i,a),n.setUTCHours(o,s,c,0),l>0&&(d=t.charAt(l),d===`+`||d===`-`)){let e=u(t.substr(l+1,2)),r=u(t.substr(l+4,2)),i=e*60+r;i*=6e4,d===`+`?n.setTime(+n-i):n.setTime(+n+i)}return n}static GeneralizedTime(t){let n=``,a=[];a.push(``+t.getUTCFullYear()),a.push(``+(t.getUTCMonth()+1)),a.push(``+t.getUTCDate()),a.push(``+t.getUTCHours()),a.push(``+t.getUTCMinutes()),a.push(``+t.getUTCSeconds());for(let e of a)e.length<2&&(n+=`0`),n+=e;n+=`Z`;let o=new e(r.UNIVERSAL,i.GENERALIZEDTIME,Buffer.from(n,`utf8`));return o._value=t,o}static parseGeneralizedTime(e){if(!(e instanceof Buffer)||e.length===0)throw Error(`ASN1 syntax error: invalid Generalized Time`);let t=e.toString(`utf8`),n=new Date,r=u(t.substr(0,4)),i=u(t.substr(4,2))-1,a=u(t.substr(6,2)),o=u(t.substr(8,2)),s=u(t.substr(10,2)),c=u(t.substr(12,2)),l=0,d=0,f=!1;t.charAt(t.length-1)===`Z`&&(f=!0);let p=t.length-5,m=t.charAt(p);if(m===`+`||m===`-`){let e=u(t.substr(p+1,2)),n=u(t.substr(p+4,2));d=e*60+n,d*=6e4,m===`+`&&(d*=-1),f=!0}return t.charAt(14)===`.`&&(l=parseFloat(t.substr(14))*1e3),f?(n.setUTCFullYear(r,i,a),n.setUTCHours(o,s,c,l),n.setTime(+n+d)):(n.setFullYear(r,i,a),n.setHours(o,s,c,l)),n}static parseTime(t,n){switch(t){case i.UTCTIME:return e.parseUTCTime(n);case i.GENERALIZEDTIME:return e.parseGeneralizedTime(n);default:throw Error(`Invalid ASN1 time tag`)}}static Set(t){let n=new e(r.UNIVERSAL,i.SET,Buffer.concat(t.map(e=>e.toDER())));return n._value=t,n}static Seq(t){let n=new e(r.UNIVERSAL,i.SEQUENCE,Buffer.concat(t.map(e=>e.toDER())));return n._value=t,n}static Spec(t,n,i=!0){let a=Array.isArray(n)?Buffer.concat(n.map(e=>e.toDER())):n.toDER();Array.isArray(n)&&(i=!0);let o=new e(r.CONTEXT_SPECIFIC,t,a,i);return o._value=n,o}static fromDER(t,r=!1){return e._fromDER(new n.BufferVisitor(t),r)}static parseDER(t,r,i){let a=e._fromDER(new n.BufferVisitor(t),!1);if(a.class!==r&&a.tag!==i)throw Error(`invalid ASN.1 DER for class ${r} and tag ${i}`);return a}static parseDERWithTemplate(t,r){let i=e._fromDER(new n.BufferVisitor(t),!0),a={},o=i.validate(r,a);if(o!=null)throw o.data=i,o;return a}static _parseCompound(t,r){let i=[],a=t.length,o=new n.BufferVisitor(t),s=0;for(;s<a;){let t=o.end;i.push(e._fromDER(o,r)),s+=o.end-t}return i}static _fromDER(t,n){if(!(t.buf instanceof Buffer)||t.length===0)throw Error(`ASN1 syntax error: invalid Generalized Time`);t.mustWalk(1,`Too few bytes to read ASN.1 tag.`);let r=t.start,a=t.buf[r],s=a&192,c=a&31,l=o(t);if(t.mustHas(l),l!==0&&c===i.NULL)throw Error(`invalid value length or NULL tag.`);t.mustWalk(l);let u=(a&32)==32,d=new e(s,c,t.buf.slice(t.start,t.end),u);return u&&n&&(d._value=e._parseCompound(d.bytes,n)),d._der=t.buf.slice(r,t.end),d}constructor(e,t,n,r=!1){this.class=e,this.tag=t,this.bytes=n,this.isCompound=r||t===i.SEQUENCE||t===i.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??=this.toDER(),this._der}mustCompound(e=`asn1 object value is not compound`){if(!this.isCompound||!Array.isArray(this.value)){let t=Error(e);throw t.data=this.toJSON(),t}return this.value}equals(t){return!(!(t instanceof e)||this.class!==t.class||this.tag!==t.tag||this.isCompound!==t.isCompound||!this.bytes.equals(t.bytes))}toDER(){let e=this.class|this.tag;this.isCompound&&(e|=32);let t=s(this.bytes.length),n=Buffer.allocUnsafe(2+t+this.bytes.length);return n.writeInt8(e,0),t===0?(n.writeUInt8(this.bytes.length,1),this.bytes.copy(n,2)):(n.writeUInt8(t|128,1),n.writeUIntBE(this.bytes.length,2,t),this.bytes.copy(n,2+t)),n}valueOf(){if(this.isCompound)return e._parseCompound(this.bytes,!1);if(this.class!==r.UNIVERSAL)return this.bytes;switch(this.tag){case i.BOOLEAN:return e.parseBool(this.bytes);case i.INTEGER:return e.parseInteger(this.bytes);case i.BITSTRING:return e.parseBitString(this.bytes);case i.NULL:return e.parseNull(this.bytes);case i.OID:return e.parseOID(this.bytes);case i.UTF8:return e.parseUTF8(this.bytes);case i.NUMERICSTRING:return e.parseNumericString(this.bytes);case i.PRINTABLESTRING:return e.parsePrintableString(this.bytes);case i.T61STRING:return e.parseT61String(this.bytes);case i.IA5STRING:return e.parseIA5String(this.bytes);case i.GENERALSTRING:return e.parseGeneralString(this.bytes);case i.UTCTIME:return e.parseUTCTime(this.bytes);case i.GENERALIZEDTIME:return e.parseGeneralizedTime(this.bytes);default:return this.bytes}}validate(t,n={}){if(this.class!==t.class)return Error(`ASN.1 object validate failure for ${t.name} : error class ${r[this.class]}`);if(!(Array.isArray(t.tag)?t.tag:[t.tag]).includes(this.tag))return Error(`ASN.1 object validate failure for ${t.name}: error tag ${i[this.tag]}`);if(t.capture!=null&&(n[t.capture]=this),Array.isArray(t.value)){let e=this.mustCompound(`${t.name} need compound ASN1 value`);for(let r=0,i=0;r<t.value.length;r++)if(e[i]!=null){let a=e[i].validate(t.value[r],n);if(a==null)i++;else if(t.value[r].optional!==!0)return a}else if(t.value[r].optional!==!0)return Error(`ASN.1 object validate failure for ${t.value[r].name}: not exists`)}else if(t.value!=null){let r=this.tag===i.BITSTRING?this.bytes.slice(1):this.bytes;return e.fromDER(r).validate(t.value,n)}return null}toJSON(){let e=this.value;return Array.isArray(e)&&(e=e.map(e=>e.toJSON())),{class:r[this.class],tag:this.class===r.UNIVERSAL?i[this.tag]:this.tag,value:e}}[t.inspect.custom](e,n){return n.depth<=2&&(n.depth=10),`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};function o(e){e.mustWalk(1,`Too few bytes to read ASN.1 value length.`);let t=e.buf[e.start];if(!(t&128))return t;let n=t&127;return e.mustWalk(n,`Too few bytes to read ASN.1 value length.`),e.buf.readUIntBE(e.start,n)}function s(e){if(e<=127)return 0;if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;if(e<=0xffffffffff)return 5;if(e<=0xffffffffffff)return 6;throw Error(`invalid value length`)}function c(e){for(let t of e){let e=t.charCodeAt(0);if(e!==32&&(e<48||e>57))return!1}return!0}function l(e){for(let t of e)if(t.charCodeAt(0)>=128)return!1;return!0}function u(e,t=10){let n=parseInt(e,t);if(Number.isNaN(n))throw Error(`Invalid numeric string "${e}" in radix ${t}.`);return n}})),zd=R((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferVisitor=Id().BufferVisitor,e.PEM=Ld().PEM;var t=Rd();e.ASN1=t.ASN1,e.Class=t.Class,e.Tag=t.Tag,e.BitString=t.BitString})),Bd=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ne(`util`),n=ne(`crypto`),r=Fd(),i=zd(),a=Pd();e.publicKeyValidator={name:`PublicKeyInfo`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,capture:`publicKeyInfo`,value:[{name:`PublicKeyInfo.AlgorithmIdentifier`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`PublicKeyAlgorithmIdentifier.algorithm`,class:i.Class.UNIVERSAL,tag:i.Tag.OID,capture:`publicKeyOID`}]},{name:`PublicKeyInfo.PublicKey`,class:i.Class.UNIVERSAL,tag:i.Tag.BITSTRING,capture:`publicKey`}]},e.privateKeyValidator={name:`PrivateKeyInfo`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,capture:`privateKeyInfo`,value:[{name:`PrivateKeyInfo.Version`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyVersion`},{name:`PrivateKeyInfo.AlgorithmIdentifier`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`PrivateKeyAlgorithmIdentifier.algorithm`,class:i.Class.UNIVERSAL,tag:i.Tag.OID,capture:`privateKeyOID`}]},{name:`PrivateKeyInfo.PrivateKey`,class:i.Class.UNIVERSAL,tag:i.Tag.OCTETSTRING,capture:`privateKey`}]};var o={name:`RSAPublicKey`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`RSAPublicKey.modulus`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`publicKeyModulus`},{name:`RSAPublicKey.exponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`publicKeyExponent`}]},s={name:`RSAPrivateKey`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`RSAPrivateKey.version`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyVersion`},{name:`RSAPrivateKey.modulus`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyModulus`},{name:`RSAPrivateKey.publicExponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPublicExponent`},{name:`RSAPrivateKey.privateExponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrivateExponent`},{name:`RSAPrivateKey.prime1`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrime1`},{name:`RSAPrivateKey.prime2`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrime2`},{name:`RSAPrivateKey.exponent1`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyExponent1`},{name:`RSAPrivateKey.exponent2`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyExponent2`},{name:`RSAPrivateKey.coefficient`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyCoefficient`}]},c=[a.getOID(`X25519`),a.getOID(`X448`),a.getOID(`Ed25519`),a.getOID(`Ed448`)],l=class r{constructor(t){let n={},r=t.validate(e.publicKeyValidator,n);if(r!=null)throw Error(`Cannot read X.509 public key: `+r.message);this.oid=i.ASN1.parseOID(n.publicKeyOID.bytes),this.algo=a.getOIDName(this.oid),this._pkcs8=t,this._keyRaw=i.ASN1.parseBitString(n.publicKey.bytes).buf,this._finalKey=this._keyRaw,this._finalPEM=``}static fromPEM(e){let t=i.PEM.parse(e)[0];if(t.procType.includes(`ENCRYPTED`))throw Error(`Could not convert public key from PEM, PEM is encrypted.`);let n=i.ASN1.fromDER(t.body,!0);switch(t.type){case`PUBLIC KEY`:return new r(n);case`RSA PUBLIC KEY`:let e=i.ASN1.Seq([i.ASN1.Seq([i.ASN1.OID(a.getOID(`rsaEncryption`)),i.ASN1.Null()]),i.ASN1.BitString(n.DER)]);return new r(e);default:throw Error(`Could not convert public key from PEM, recommend PKCS#8 PEM`)}}static addVerifier(e,t){if(e=a.getOID(e),e===``)throw Error(`Invalid object identifier: ${e}`);if(r._verifiers[e]!=null)throw Error(`Verifier ${e} exists`);r._verifiers[e]=t}get keyRaw(){return this._finalKey}verify(e,t,i){let a=r._verifiers[this.oid];if(a!=null){let r=n.createHash(i).update(e).digest();return a.call(this,r,t)}let o=n.createVerify(i);return o.update(e),o.verify(this.toPEM(),t)}getFingerprint(e,t=`PublicKey`){let r;switch(t){case`PublicKeyInfo`:r=this._pkcs8.DER;break;case`PublicKey`:r=this._keyRaw;break;default:throw Error(`Unknown fingerprint type "${t}".`)}let i=n.createHash(e);return i.update(r),i.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===``&&(this._finalPEM=new i.PEM(`PUBLIC KEY`,this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{oid:this.oid,algo:this.algo,publicKey:this._keyRaw}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};l._verifiers=Object.create(null),e.PublicKey=l;var u=class o{constructor(t){let n=Object.create(null),o=t.validate(e.privateKeyValidator,n);if(o!=null)throw Error(`Cannot read X.509 private key: `+o.message);if(this.version=i.ASN1.parseIntegerNum(n.privateKeyVersion.bytes)+1,this.oid=i.ASN1.parseOID(n.privateKeyOID.bytes),this.algo=a.getOIDName(this.oid),this._pkcs8=t,this._keyRaw=n.privateKey.bytes,this._publicKeyRaw=null,this._finalKey=this._keyRaw,this._finalPEM=``,c.includes(this.oid)){if(this._finalKey=this._keyRaw=i.ASN1.parseDER(this._keyRaw,i.Class.UNIVERSAL,i.Tag.OCTETSTRING).bytes,this.oid===`1.3.101.112`){let e=r.sign.keyPair.fromSeed(this._keyRaw);this._publicKeyRaw=Buffer.from(e.publicKey),this._finalKey=Buffer.from(e.secretKey)}else if(this.version===2)for(let e of t.mustCompound())e.class===i.Class.CONTEXT_SPECIFIC&&e.tag===1&&(this._publicKeyRaw=i.ASN1.parseBitString(e.bytes).buf,this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw]))}}static fromPEM(e){let t=i.PEM.parse(e)[0];if(t.procType.includes(`ENCRYPTED`))throw Error(`Could not convert private key from PEM, PEM is encrypted.`);let n=i.ASN1.fromDER(t.body,!0);switch(t.type){case`PRIVATE KEY`:return new o(n);case`RSA PRIVATE KEY`:return n=i.ASN1.Seq([n.value[0],i.ASN1.Seq([i.ASN1.OID(a.getOID(`rsaEncryption`)),i.ASN1.Null()]),new i.ASN1(i.Class.UNIVERSAL,i.Tag.OCTETSTRING,n.DER)]),new o(n);default:throw Error(`Could not convert private key from PEM, recommend PKCS#8 PEM`)}}static addSigner(e,t){if(e=a.getOID(e),e===``)throw Error(`Invalid object identifier: ${e}`);if(o._signers[e]!=null)throw Error(`Signer ${e} exists`);o._signers[e]=t}get keyRaw(){return this._finalKey}get publicKeyRaw(){return this._publicKeyRaw}sign(e,t){let r=o._signers[this.oid];if(r!=null){let i=n.createHash(t).update(e).digest();return r.call(this,i)}let i=n.createSign(t);return i.update(e),i.sign(this.toPEM())}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===``&&(this._finalPEM=new i.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}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};u._signers=Object.create(null),e.PrivateKey=u,e.RSAPublicKey=class e extends l{static fromPublicKey(t){return new e(t.toASN1())}constructor(e){if(super(e),a.getOID(this.oid)!==a.getOID(`rsaEncryption`))throw Error(`Invalid RSA public key, unknown OID: ${this.oid}`);let t=Object.create(null);this._pkcs1=i.ASN1.fromDER(this._keyRaw,!0);let n=this._pkcs1.validate(o,t);if(n!=null)throw Error(`Cannot read RSA public key: `+n.message);this.modulus=i.ASN1.parseIntegerStr(t.publicKeyModulus.bytes),this.exponent=i.ASN1.parseIntegerNum(t.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===``&&(this._finalPEM=new i.PEM(`RSA PUBLIC KEY`,this._keyRaw).toString()),this._finalPEM}toPublicKeyPEM(){return new i.PEM(`PUBLIC KEY`,this._pkcs8.DER).toString()}toJSON(){return{oid:this.oid,algo:this.algo,modulus:d(this.modulus),exponent:this.exponent}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}},e.RSAPrivateKey=class e extends u{static fromPrivateKey(t){return new e(t.toASN1())}constructor(e){if(super(e),a.getOID(this.oid)!==a.getOID(`rsaEncryption`))throw Error(`Invalid RSA private key, unknown OID: ${this.oid}`);let t=Object.create(null);this._pkcs1=i.ASN1.fromDER(this._keyRaw,!0);let n=this._pkcs1.validate(s,t);if(n!=null)throw Error(`Cannot read RSA private key: `+n.message);this.publicExponent=i.ASN1.parseIntegerNum(t.privateKeyPublicExponent.bytes),this.privateExponent=i.ASN1.parseIntegerStr(t.privateKeyPrivateExponent.bytes),this.modulus=i.ASN1.parseIntegerStr(t.privateKeyModulus.bytes),this.prime1=i.ASN1.parseIntegerStr(t.privateKeyPrime1.bytes),this.prime2=i.ASN1.parseIntegerStr(t.privateKeyPrime2.bytes),this.exponent1=i.ASN1.parseIntegerStr(t.privateKeyExponent1.bytes),this.exponent2=i.ASN1.parseIntegerStr(t.privateKeyExponent2.bytes),this.coefficient=i.ASN1.parseIntegerStr(t.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===``&&(this._finalPEM=new i.PEM(`RSA PRIVATE KEY`,this._keyRaw).toString()),this._finalPEM}toPrivateKeyPEM(){return new i.PEM(`PRIVATE KEY`,this._pkcs8.DER).toString()}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,publicExponent:this.publicExponent,privateExponent:d(this.privateExponent),modulus:d(this.modulus),prime1:d(this.prime1),prime2:d(this.prime2),exponent1:d(this.exponent1),exponent2:d(this.exponent2),coefficient:d(this.coefficient)}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};function d(e){return e.length%8!=0&&e.startsWith(`00`)?e.slice(2):e}l.addVerifier(a.getOID(`Ed25519`),function(e,t){return r.sign.detached.verify(e,t,this.keyRaw)}),u.addSigner(a.getOID(`Ed25519`),function(e){let t=this.keyRaw;if(t.length!==64)throw Error(`Invalid signing key.`);return Buffer.from(r.sign.detached(e,t))})})),Vd=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ne(`util`),n=ne(`crypto`),r=zd(),i=Pd(),a=Bd(),o=Object.create(null);o.CN=i.getOID(`commonName`),o.commonName=`CN`,o.C=i.getOID(`countryName`),o.countryName=`C`,o.L=i.getOID(`localityName`),o.localityName=`L`,o.ST=i.getOID(`stateOrProvinceName`),o.stateOrProvinceName=`ST`,o.O=i.getOID(`organizationName`),o.organizationName=`O`,o.OU=i.getOID(`organizationalUnitName`),o.organizationalUnitName=`OU`,o.E=i.getOID(`emailAddress`),o.emailAddress=`E`;function s(e){return o[e]==null?``:o[e]}var c={name:`Certificate`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`tbsCertificate`,value:[{name:`Certificate.TBSCertificate.version`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.NONE,optional:!0,value:[{name:`Certificate.TBSCertificate.version.integer`,class:r.Class.UNIVERSAL,tag:r.Tag.INTEGER,capture:`certVersion`}]},{name:`Certificate.TBSCertificate.serialNumber`,class:r.Class.UNIVERSAL,tag:r.Tag.INTEGER,capture:`certSerialNumber`},{name:`Certificate.TBSCertificate.signature`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate.signature.algorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.OID,capture:`certinfoSignatureOID`},{name:`Certificate.TBSCertificate.signature.parameters`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,optional:!0,capture:`certinfoSignatureParams`}]},{name:`Certificate.TBSCertificate.issuer`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`certIssuer`},{name:`Certificate.TBSCertificate.validity`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate.validity.notBefore`,class:r.Class.UNIVERSAL,tag:[r.Tag.UTCTIME,r.Tag.GENERALIZEDTIME],capture:`certValidityNotBefore`},{name:`Certificate.TBSCertificate.validity.notAfter`,class:r.Class.UNIVERSAL,tag:[r.Tag.UTCTIME,r.Tag.GENERALIZEDTIME],capture:`certValidityNotAfter`}]},{name:`Certificate.TBSCertificate.subject`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`certSubject`},a.publicKeyValidator,{name:`Certificate.TBSCertificate.issuerUniqueID`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.BOOLEAN,optional:!0,value:[{name:`Certificate.TBSCertificate.issuerUniqueID.id`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certIssuerUniqueId`}]},{name:`Certificate.TBSCertificate.subjectUniqueID`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.INTEGER,optional:!0,value:[{name:`Certificate.TBSCertificate.subjectUniqueID.id`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certSubjectUniqueId`}]},{name:`Certificate.TBSCertificate.extensions`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.BITSTRING,capture:`certExtensions`,optional:!0}]},{name:`Certificate.signatureAlgorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.signatureAlgorithm.algorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.OID,capture:`certSignatureOID`},{name:`Certificate.TBSCertificate.signature.parameters`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,optional:!0,capture:`certSignatureParams`}]},{name:`Certificate.signatureValue`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certSignature`}]},l=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=n.createHash(`sha1`);for(let t of this.attributes)e.update(t.oid),e.update(t.value);return e.digest()}getField(e){for(let t of this.attributes)if(e===t.oid||e===t.name||e===t.shortName)return t;return null}addField(e){C([e]),this.attributes.push(e)}setAttrs(e){C(e),this.attributes=e}toJSON(){let e={};for(let t of this.attributes){let n=t.shortName;typeof n==`string`&&n!==``&&(e[n]=t.value)}return e.uniqueId=this.uniqueId,e.attributes=this.attributes,e}getFieldValue(e){let t=this.getField(e);return t==null?``:t.value}};e.DistinguishedName=l,e.Certificate=class e{static fromPEMs(t){let n=[],i=r.PEM.parse(t);for(let t of i){if(t.type!==`CERTIFICATE`&&t.type!==`X509 CERTIFICATE`&&t.type!==`TRUSTED CERTIFICATE`)throw Error(`Could not convert certificate from PEM: invalid type`);if(t.procType.includes(`ENCRYPTED`))throw Error(`Could not convert certificate from PEM: PEM is encrypted.`);let i=r.ASN1.fromDER(t.body);n.push(new e(i))}if(n.length===0)throw Error(`No Certificate`);return n}static fromPEM(t){return e.fromPEMs(t)[0]}constructor(e){let t=Object.create(null),n=e.validate(c,t);if(n!=null)throw Error(`Cannot read X.509 certificate: `+n.message);if(this.raw=e.DER,this.version=t.certVersion==null?0:r.ASN1.parseIntegerNum(t.certVersion.bytes)+1,this.serialNumber=r.ASN1.parseIntegerStr(t.certSerialNumber.bytes),this.signatureOID=r.ASN1.parseOID(t.certSignatureOID.bytes),this.signatureAlgorithm=i.getOIDName(this.signatureOID),this.infoSignatureOID=r.ASN1.parseOID(t.certinfoSignatureOID.bytes),this.signature=r.ASN1.parseBitString(t.certSignature.bytes).buf,this.validFrom=r.ASN1.parseTime(t.certValidityNotBefore.tag,t.certValidityNotBefore.bytes),this.validTo=r.ASN1.parseTime(t.certValidityNotAfter.tag,t.certValidityNotAfter.bytes),this.issuer=new l,this.issuer.setAttrs(T(t.certIssuer)),t.certIssuerUniqueId!=null&&(this.issuer.uniqueId=r.ASN1.parseBitString(t.certIssuerUniqueId.bytes)),this.subject=new l,this.subject.setAttrs(T(t.certSubject)),t.certSubjectUniqueId!=null&&(this.subject.uniqueId=r.ASN1.parseBitString(t.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=[],t.certExtensions!=null){this.extensions=u(t.certExtensions);for(let e of this.extensions)if(typeof e.subjectKeyIdentifier==`string`&&(this.subjectKeyIdentifier=e.subjectKeyIdentifier),typeof e.authorityKeyIdentifier==`string`&&(this.authorityKeyIdentifier=e.authorityKeyIdentifier),typeof e.authorityInfoAccessOcsp==`string`&&(this.ocspServer=e.authorityInfoAccessOcsp),typeof e.authorityInfoAccessIssuers==`string`&&(this.issuingCertificateURL=e.authorityInfoAccessIssuers),typeof e.basicConstraintsValid==`boolean`&&(this.isCA=e.isCA,this.maxPathLen=e.maxPathLen,this.basicConstraintsValid=e.basicConstraintsValid),typeof e.keyUsage==`number`&&(this.keyUsage=e.keyUsage),Array.isArray(e.altNames))for(let t of e.altNames)t.dnsName!=null&&this.dnsNames.push(t.dnsName),t.email!=null&&this.emailAddresses.push(t.email),t.ip!=null&&this.ipAddresses.push(t.ip),t.uri!=null&&this.uris.push(t.uri)}this.publicKey=new a.PublicKey(t.publicKeyInfo),this.publicKeyRaw=this.publicKey.toDER(),this.tbsCertificate=t.tbsCertificate}getExtension(e,t=``){for(let n of this.extensions)if(e===n.oid||e===n.name)return t===``?n:n[t];return null}checkSignature(e){if(this.version===3&&!this.basicConstraintsValid||this.basicConstraintsValid&&!this.isCA||this.getExtension(`keyUsage`,`keyCertSign`)!==!0)return Error(`The parent constraint violation error`);if(!e.isIssuer(this))return Error(`The parent certificate did not issue the given child certificate`);let t=w(e.signatureOID);return t===``?Error(`Unknown child signature OID.`):this.publicKey.verify(e.tbsCertificate.DER,e.signature,t)===!1?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 t of Object.keys(this))e[t]=E(this[t]);return delete e.tbsCertificate,e}[t.inspect.custom](e,n){return n.depth<=2&&(n.depth=10),`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};function u(e){let t=[];for(let n of e.mustCompound())for(let e of n.mustCompound())t.push(d(e));return t}function d(e){let t={};switch(t.oid=r.ASN1.parseOID(e.value[0].bytes),t.critical=!1,e.value[1].tag===r.Tag.BOOLEAN?(t.critical=r.ASN1.parseBool(e.value[1].bytes),t.value=e.value[2].bytes):t.value=e.value[1].bytes,t.name=i.getOIDName(t.oid),t.name){case`keyUsage`:f(t);break;case`basicConstraints`:p(t);break;case`extKeyUsage`:m(t);break;case`nsCertType`:h(t);break;case`subjectAltName`:g(t);break;case`issuerAltName`:g(t);break;case`subjectKeyIdentifier`:v(t);break;case`authorityKeyIdentifier`:b(t);break;case`authorityInfoAccess`:S(t)}return t}function f(e){let t=r.ASN1.parseBitString(r.ASN1.fromDER(e.value).bytes),n=0,i=0;e.keyUsage=0;for(let n=0;n<9;n++)t.at(n)!==0&&(e.keyUsage|=1<<n);t.buf.length>0&&(n=t.buf[0],i=t.buf.length>1?t.buf[1]:0),e.digitalSignature=(n&128)==128,e.nonRepudiation=(n&64)==64,e.keyEncipherment=(n&32)==32,e.dataEncipherment=(n&16)==16,e.keyAgreement=(n&8)==8,e.keyCertSign=(n&4)==4,e.cRLSign=(n&2)==2,e.encipherOnly=(n&1)==1,e.decipherOnly=(i&128)==128}function p(e){let t=r.ASN1.fromDER(e.value).mustCompound();e.isCA=t.length>0&&t[0].tag===r.Tag.BOOLEAN&&r.ASN1.parseBool(t[0].bytes);let n=null;t.length>0&&t[0].tag===r.Tag.INTEGER?n=t[0].bytes:t.length>1&&(n=t[1].bytes),e.maxPathLen=n===null?-1:r.ASN1.parseInteger(n),e.basicConstraintsValid=!0}function m(e){let t=r.ASN1.fromDER(e.value).mustCompound();for(let n of t)e[i.getOIDName(r.ASN1.parseOID(n.bytes))]=!0}function h(e){let t=r.ASN1.parseBitString(r.ASN1.fromDER(e.value).bytes),n=0;t.buf.length>0&&(n=t.buf[0]),e.client=(n&128)==128,e.server=(n&64)==64,e.email=(n&32)==32,e.objsign=(n&16)==16,e.reserved=(n&8)==8,e.sslCA=(n&4)==4,e.emailCA=(n&2)==2,e.objCA=(n&1)==1}function g(e){e.altNames=[];let t=r.ASN1.fromDER(e.value).mustCompound();for(let n of t){let t={tag:n.tag,value:n.bytes};switch(e.altNames.push(t),n.tag){case 1:t.email=n.bytes.toString();break;case 2:t.dnsName=n.bytes.toString();break;case 6:t.uri=n.bytes.toString();break;case 7:t.ip=i.bytesToIP(n.bytes);break;case 8:t.oid=r.ASN1.parseOID(n.bytes)}}}var _={name:`subjectKeyIdentifier`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,capture:`subjectKeyIdentifier`};function v(e){e.subjectKeyIdentifier=r.ASN1.parseDERWithTemplate(e.value,_).subjectKeyIdentifier.bytes.toString(`hex`)}var y={name:`authorityKeyIdentifier`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`authorityKeyIdentifier.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.NONE,capture:`authorityKeyIdentifier`}]};function b(e){e.authorityKeyIdentifier=r.ASN1.parseDERWithTemplate(e.value,y).authorityKeyIdentifier.bytes.toString(`hex`)}var x={name:`authorityInfoAccess`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`authorityInfoAccess.authorityInfoAccessOcsp`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,optional:!0,value:[{name:`authorityInfoAccess.authorityInfoAccessOcsp.oid`,class:r.Class.UNIVERSAL,tag:r.Tag.OID},{name:`authorityInfoAccess.authorityInfoAccessOcsp.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.OID,capture:`authorityInfoAccessOcsp`}]},{name:`authorityInfoAccess.authorityInfoAccessIssuers`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,optional:!0,value:[{name:`authorityInfoAccess.authorityInfoAccessIssuers.oid`,class:r.Class.UNIVERSAL,tag:r.Tag.OID},{name:`authorityInfoAccess.authorityInfoAccessIssuers.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.OID,capture:`authorityInfoAccessIssuers`}]}]};function S(e){let t=r.ASN1.parseDERWithTemplate(e.value,x);t.authorityInfoAccessOcsp!=null&&(e.authorityInfoAccessOcsp=t.authorityInfoAccessOcsp.bytes.toString()),t.authorityInfoAccessIssuers!=null&&(e.authorityInfoAccessIssuers=t.authorityInfoAccessIssuers.bytes.toString())}function C(e){for(let t of e){if((t.name==null||t.name===``)&&(t.oid!=null&&(t.name=i.getOIDName(t.oid)),t.name===``&&t.shortName!=null&&(t.name=i.getOIDName(o[t.shortName]))),t.oid==null||t.oid===``){if(t.name!==``)t.oid=i.getOID(t.name);else throw Error(`Attribute oid not specified.`)}if((t.shortName==null||t.shortName===``)&&(t.shortName=o[t.name]==null?``:o[t.name]),t.value==null)throw Error(`Attribute value not specified.`)}}function w(e){switch(i.getOIDName(e)){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 T(e){let t=[];for(let n of e.mustCompound())for(let e of n.mustCompound()){let n=e.mustCompound(),a={};a.oid=r.ASN1.parseOID(n[0].bytes),a.value=n[1].value,a.valueTag=n[1].tag,a.name=i.getOIDName(a.oid),a.shortName=s(a.name),t.push(a)}return t}function E(e){return e!=null&&!(e instanceof Buffer)&&typeof e.toJSON==`function`?e.toJSON():e}})),Hd=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Pd();e.bytesFromIP=t.bytesFromIP,e.bytesToIP=t.bytesToIP,e.getOID=t.getOID,e.getOIDName=t.getOIDName;var n=Bd();e.PublicKey=n.PublicKey,e.PrivateKey=n.PrivateKey,e.RSAPublicKey=n.RSAPublicKey,e.RSAPrivateKey=n.RSAPrivateKey;var r=Vd();e.Certificate=r.Certificate,e.DistinguishedName=r.DistinguishedName})),Ud=R((()=>{var e;(function(e){(function(t){var n=typeof globalThis==`object`?globalThis:typeof global==`object`?global:typeof self==`object`?self:typeof this==`object`?this:s(),r=i(e);n.Reflect!==void 0&&(r=i(n.Reflect,r)),t(r,n),n.Reflect===void 0&&(n.Reflect=e);function i(e,t){return function(n,r){Object.defineProperty(e,n,{configurable:!0,writable:!0,value:r}),t&&t(n,r)}}function a(){try{return Function(`return this;`)()}catch{}}function o(){try{return(0,eval)(`(function() { return this; })()`)}catch{}}function s(){return a()||o()}})(function(e,t){var n=Object.prototype.hasOwnProperty,r=typeof Symbol==`function`,i=r&&Symbol.toPrimitive!==void 0?Symbol.toPrimitive:`@@toPrimitive`,a=r&&Symbol.iterator!==void 0?Symbol.iterator:`@@iterator`,o=typeof Object.create==`function`,s={__proto__:[]}instanceof Array,c=!o&&!s,l={create:o?function(){return we(Object.create(null))}:s?function(){return we({__proto__:null})}:function(){return we({})},has:c?function(e,t){return n.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return n.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),d=typeof Map==`function`&&typeof Map.prototype.entries==`function`?Map:xe(),f=typeof Set==`function`&&typeof Set.prototype.entries==`function`?Set:Se(),p=typeof WeakMap==`function`?WeakMap:Ce(),m=r?Symbol.for(`@reflect-metadata:registry`):void 0,h=_e(),g=ve(h);function _(e,t,n,r){if(L(n)){if(!ae(e)||!se(t))throw TypeError();return D(e,t)}if(!ae(e)||!z(t)||!z(r)&&!L(r)&&!R(r))throw TypeError();return R(r)&&(r=void 0),n=ie(n),O(e,t,n,r)}e(`decorate`,_);function v(e,t){function n(n,r){if(!z(n)||!L(r)&&!ce(r))throw TypeError();N(e,t,n,r)}return n}e(`metadata`,v);function y(e,t,n,r){if(!z(n))throw TypeError();return L(r)||(r=ie(r)),N(e,t,n,r)}e(`defineMetadata`,y);function b(e,t,n){if(!z(t))throw TypeError();return L(n)||(n=ie(n)),k(e,t,n)}e(`hasMetadata`,b);function x(e,t,n){if(!z(t))throw TypeError();return L(n)||(n=ie(n)),A(e,t,n)}e(`hasOwnMetadata`,x);function S(e,t,n){if(!z(t))throw TypeError();return L(n)||(n=ie(n)),j(e,t,n)}e(`getMetadata`,S);function C(e,t,n){if(!z(t))throw TypeError();return L(n)||(n=ie(n)),M(e,t,n)}e(`getOwnMetadata`,C);function w(e,t){if(!z(e))throw TypeError();return L(t)||(t=ie(t)),P(e,t)}e(`getMetadataKeys`,w);function T(e,t){if(!z(e))throw TypeError();return L(t)||(t=ie(t)),F(e,t)}e(`getOwnMetadataKeys`,T);function E(e,t,n){if(!z(t)||(L(n)||(n=ie(n)),!z(t)))throw TypeError();L(n)||(n=ie(n));var r=be(t,n,!1);return!L(r)&&r.OrdinaryDeleteMetadata(e,t,n)}e(`deleteMetadata`,E);function D(e,t){for(var n=e.length-1;n>=0;--n){var r=e[n],i=r(t);if(!L(i)&&!R(i)){if(!se(i))throw TypeError();t=i}}return t}function O(e,t,n,r){for(var i=e.length-1;i>=0;--i){var a=e[i],o=a(t,n,r);if(!L(o)&&!R(o)){if(!z(o))throw TypeError();r=o}}return r}function k(e,t,n){if(A(e,t,n))return!0;var r=he(t);return!R(r)&&k(e,r,n)}function A(e,t,n){var r=be(t,n,!1);return!L(r)&&ne(r.OrdinaryHasOwnMetadata(e,t,n))}function j(e,t,n){if(A(e,t,n))return M(e,t,n);var r=he(t);if(!R(r))return j(e,r,n)}function M(e,t,n){var r=be(t,n,!1);if(!L(r))return r.OrdinaryGetOwnMetadata(e,t,n)}function N(e,t,n,r){be(n,r,!0).OrdinaryDefineOwnMetadata(e,t,n,r)}function P(e,t){var n=F(e,t),r=he(e);if(r===null)return n;var i=P(r,t);if(i.length<=0)return n;if(n.length<=0)return i;for(var a=new f,o=[],s=0,c=n;s<c.length;s++){var l=c[s],u=a.has(l);u||(a.add(l),o.push(l))}for(var d=0,p=i;d<p.length;d++){var l=p[d],u=a.has(l);u||(a.add(l),o.push(l))}return o}function F(e,t){var n=be(e,t,!1);return n?n.OrdinaryOwnMetadataKeys(e,t):[]}function I(e){if(e===null)return 1;switch(typeof e){case`undefined`:return 0;case`boolean`:return 2;case`string`:return 3;case`symbol`:return 4;case`number`:return 5;case`object`:return e===null?1:6;default:return 6}}function L(e){return e===void 0}function R(e){return e===null}function ee(e){return typeof e==`symbol`}function z(e){return typeof e==`object`?e!==null:typeof e==`function`}function B(e,t){switch(I(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var n=t===3?`string`:t===5?`number`:`default`,r=ue(e,i);if(r!==void 0){var a=r.call(e,n);if(z(a))throw TypeError();return a}return te(e,n==="default"?`number`:n)}function te(e,t){if(t===`string`){var n=e.toString;if(oe(n)){var r=n.call(e);if(!z(r))return r}var i=e.valueOf;if(oe(i)){var r=i.call(e);if(!z(r))return r}}else{var i=e.valueOf;if(oe(i)){var r=i.call(e);if(!z(r))return r}var a=e.toString;if(oe(a)){var r=a.call(e);if(!z(r))return r}}throw TypeError()}function ne(e){return!!e}function re(e){return``+e}function ie(e){var t=B(e,3);return ee(t)?t:re(t)}function ae(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)===`[object Array]`}function oe(e){return typeof e==`function`}function se(e){return typeof e==`function`}function ce(e){switch(I(e)){case 3:return!0;case 4:return!0;default:return!1}}function le(e,t){return e===t||e!==e&&t!==t}function ue(e,t){var n=e[t];if(n!=null){if(!oe(n))throw TypeError();return n}}function de(e){var t=ue(e,a);if(!oe(t))throw TypeError();var n=t.call(e);if(!z(n))throw TypeError();return n}function fe(e){return e.value}function pe(e){var t=e.next();return!t.done&&t}function me(e){var t=e.return;t&&t.call(e)}function he(e){var t=Object.getPrototypeOf(e);if(typeof e!=`function`||e===u||t!==u)return t;var n=e.prototype,r=n&&Object.getPrototypeOf(n);if(r==null||r===Object.prototype)return t;var i=r.constructor;return typeof i!=`function`||i===e?t:i}function ge(){var e;!L(m)&&t.Reflect!==void 0&&!(m in t.Reflect)&&typeof t.Reflect.defineMetadata==`function`&&(e=ye(t.Reflect));var n,r,i,a=new p,o={registerProvider:s,getProvider:l,setProvider:h};return o;function s(t){if(!Object.isExtensible(o))throw Error(`Cannot add provider to a frozen registry.`);switch(!0){case e===t:break;case L(n):n=t;break;case n===t:break;case L(r):r=t;break;case r===t:break;default:i===void 0&&(i=new f),i.add(t)}}function c(t,a){if(!L(n)){if(n.isProviderFor(t,a))return n;if(!L(r)){if(r.isProviderFor(t,a))return n;if(!L(i))for(var o=de(i);;){var s=pe(o);if(!s)return;var c=fe(s);if(c.isProviderFor(t,a))return me(o),c}}}if(!L(e)&&e.isProviderFor(t,a))return e}function l(e,t){var n=a.get(e),r;return L(n)||(r=n.get(t)),L(r)?(r=c(e,t),L(r)||(L(n)&&(n=new d,a.set(e,n)),n.set(t,r)),r):r}function u(e){if(L(e))throw TypeError();return n===e||r===e||!L(i)&&i.has(e)}function h(e,t,n){if(!u(n))throw Error(`Metadata provider not registered.`);var r=l(e,t);if(r!==n){if(!L(r))return!1;var i=a.get(e);L(i)&&(i=new d,a.set(e,i)),i.set(t,n)}return!0}}function _e(){var e;return!L(m)&&z(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[m]),L(e)&&(e=ge()),!L(m)&&z(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,m,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function ve(e){var t=new p,n={isProviderFor:function(e,n){var r=t.get(e);return!L(r)&&r.has(n)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:a,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:c};return h.registerProvider(n),n;function r(r,i,a){var o=t.get(r),s=!1;if(L(o)){if(!a)return;o=new d,t.set(r,o),s=!0}var c=o.get(i);if(L(c)){if(!a)return;if(c=new d,o.set(i,c),!e.setProvider(r,i,n))throw o.delete(i),s&&t.delete(r),Error(`Wrong provider for target.`)}return c}function i(e,t,n){var i=r(t,n,!1);return!L(i)&&ne(i.has(e))}function a(e,t,n){var i=r(t,n,!1);if(!L(i))return i.get(e)}function o(e,t,n,i){r(n,i,!0).set(e,t)}function s(e,t){var n=[],i=r(e,t,!1);if(L(i))return n;for(var a=de(i.keys()),o=0;;){var s=pe(a);if(!s)return n.length=o,n;var c=fe(s);try{n[o]=c}catch(e){try{me(a)}finally{throw e}}o++}}function c(e,n,i){var a=r(n,i,!1);if(L(a)||!a.delete(e))return!1;if(a.size===0){var o=t.get(n);L(o)||(o.delete(i),o.size===0&&t.delete(o))}return!0}}function ye(e){var t=e.defineMetadata,n=e.hasOwnMetadata,r=e.getOwnMetadata,i=e.getOwnMetadataKeys,a=e.deleteMetadata,o=new p;return{isProviderFor:function(e,t){var n=o.get(e);return!L(n)&&n.has(t)?!0:i(e,t).length?(L(n)&&(n=new f,o.set(e,n)),n.add(t),!0):!1},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:n,OrdinaryGetOwnMetadata:r,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:a}}function be(e,t,n){var r=h.getProvider(e,t);if(!L(r))return r;if(n){if(h.setProvider(e,t,g))return g;throw Error(`Illegal state.`)}}function xe(){var e={},t=[],n=function(){function e(e,t,n){this._index=0,this._keys=e,this._values=t,this._selector=n}return e.prototype[`@@iterator`]=function(){return this},e.prototype[a]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var n=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:n,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}();return function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var n=this._find(e,!0);return this._values[n]=t,this},t.prototype.delete=function(t){var n=this._find(t,!1);if(n>=0){for(var r=this._keys.length,i=n+1;i<r;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,le(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new n(this._keys,this._values,r)},t.prototype.values=function(){return new n(this._keys,this._values,i)},t.prototype.entries=function(){return new n(this._keys,this._values,o)},t.prototype[`@@iterator`]=function(){return this.entries()},t.prototype[a]=function(){return this.entries()},t.prototype._find=function(e,t){if(!le(this._cacheKey,e)){this._cacheIndex=-1;for(var n=0;n<this._keys.length;n++)if(le(this._keys[n],e)){this._cacheIndex=n;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();function r(e,t){return e}function i(e,t){return t}function o(e,t){return[e,t]}}function Se(){return function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype[`@@iterator`]=function(){return this.keys()},e.prototype[a]=function(){return this.keys()},e}()}function Ce(){var e=l.create(),t=r();return function(){function e(){this._key=r()}return e.prototype.has=function(e){var t=i(e,!1);return t!==void 0&&l.has(t,this._key)},e.prototype.get=function(e){var t=i(e,!1);return t===void 0?void 0:l.get(t,this._key)},e.prototype.set=function(e,t){var n=i(e,!0);return n[this._key]=t,this},e.prototype.delete=function(e){var t=i(e,!1);return t!==void 0&&delete t[this._key]},e.prototype.clear=function(){this._key=r()},e}();function r(){var t;do t=`@@WeakMap@@`+s();while(l.has(e,t));return e[t]=!0,t}function i(e,r){if(!n.call(e,t)){if(!r)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function a(e,t){for(var n=0;n<t;++n)e[n]=Math.random()*255|0;return e}function o(e){if(typeof Uint8Array==`function`){var t=new Uint8Array(e);return typeof crypto<`u`?crypto.getRandomValues(t):typeof msCrypto<`u`?msCrypto.getRandomValues(t):a(t,e),t}return a(Array(e),e)}function s(){var e=o(16);e[6]=e[6]&79|64,e[8]=e[8]&191|128;for(var t=``,n=0;n<16;++n){var r=e[n];(n===4||n===6||n===8)&&(t+=`-`),r<16&&(t+=`0`),t+=r.toString(16).toLowerCase()}return t}}function we(e){return e.__=void 0,delete e.__,e}})})(e||={})})),Wd=B(Nd(),1),Gd=Hd();Ud();var Kd=`[object ArrayBuffer]`,U=class e{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Kd}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,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw 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(t,n){let r=e.toUint8Array(t),i=e.toUint8Array(n);if(r.length!==i.byteLength)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1;return!0}static concat(...e){let t;t=Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e;let n=0;for(let e of t)n+=e.byteLength;let r=new Uint8Array(n),i=0;for(let e of t){let t=this.toUint8Array(e);r.set(t,i),i+=t.length}return e[e.length-1]instanceof Function?this.toView(r,e[e.length-1]):r.buffer}},qd=`string`,Jd=/^[0-9a-f\s]+$/i,Yd=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Xd=/^[a-zA-Z0-9-_]+$/,Zd=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}static toString(e){let t=U.toUint8Array(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return decodeURIComponent(escape(n))}},Qd=class{static toString(e,t=!1){let n=U.toArrayBuffer(e),r=new DataView(n),i=``;for(let e=0;e<n.byteLength;e+=2){let n=r.getUint16(e,t);i+=String.fromCharCode(n)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),r=new DataView(n);for(let n=0;n<e.length;n++)r.setUint16(n*2,e.charCodeAt(n),t);return n}},$d=class e{static isHex(e){return typeof e===qd&&Jd.test(e)}static isBase64(e){return typeof e===qd&&Yd.test(e)}static isBase64Url(e){return typeof e===qd&&Xd.test(e)}static ToString(e,t=`utf8`){let n=U.toUint8Array(e);switch(t.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 Qd.toString(n,!0);case`utf16`:case`utf16be`:return Qd.toString(n);default:throw Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t=`utf8`){if(!e)return new ArrayBuffer(0);switch(t.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 Qd.fromString(e,!0);case`utf16`:case`utf16be`:return Qd.fromString(e);default:throw Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=U.toUint8Array(e);if(typeof btoa<`u`){let e=this.ToString(t,`binary`);return btoa(e)}return Buffer.from(t).toString(`base64`)}static FromBase64(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!e.isBase64(n))throw TypeError(`Argument 'base64Text' is not Base64 encoded`);return typeof atob<`u`?this.FromBinary(atob(n)):new Uint8Array(Buffer.from(n,`base64`)).buffer}static FromBase64Url(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!e.isBase64Url(n))throw TypeError(`Argument 'base64url' is not Base64Url encoded`);return this.FromBase64(this.Base64Padding(n.replace(/\-/g,`+`).replace(/\_/g,`/`)))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/\=/g,``)}static FromUtf8String(t,n=e.DEFAULT_UTF8_ENCODING){switch(n){case`ascii`:return this.FromBinary(t);case`utf8`:return Zd.fromString(t);case`utf16`:case`utf16be`:return Qd.fromString(t);case`utf16le`:case`usc2`:return Qd.fromString(t,!0);default:throw Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(t,n=e.DEFAULT_UTF8_ENCODING){switch(n){case`ascii`:return this.ToBinary(t);case`utf8`:return Zd.toString(t);case`utf16`:case`utf16be`:return Qd.toString(t);case`utf16le`:case`usc2`:return Qd.toString(t,!0);default:throw Error(`Unknown type of encoding '${n}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return n.buffer}static ToBinary(e){let t=U.toUint8Array(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return n}static ToHex(e){let t=U.toUint8Array(e),n=``,r=t.length;for(let e=0;e<r;e++){let r=t[e];r<16&&(n+=`0`),n+=r.toString(16)}return n}static FromHex(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!e.isHex(n))throw TypeError(`Argument 'hexString' is not HEX encoded`);n.length%2&&(n=`0${n}`);let r=new Uint8Array(n.length/2);for(let e=0;e<n.length;e+=2){let t=n.slice(e,e+2);r[e/2]=parseInt(t,16)}return r.buffer}static ToUtf16String(e,t=!1){return Qd.toString(e,t)}static FromUtf16String(e,t=!1){return Qd.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+=`=`;return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,``)||``}};$d.DEFAULT_UTF8_ENCODING=`utf8`;function ef(...e){let t=e.map(e=>e.byteLength).reduce((e,t)=>e+t),n=new Uint8Array(t),r=0;return e.map(e=>new Uint8Array(e)).forEach(e=>{for(let t of e)n[r++]=t}),n.buffer}function tf(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;let n=new Uint8Array(e),r=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(n[t]!==r[t])return!1;return!0}function nf(e,t){let n=0;if(e.length===1)return e[0];for(let r=e.length-1;r>=0;r--)n+=e[e.length-1-r]*2**(t*r);return n}function rf(e,t,n=-1){let r=n,i=e,a=0,o=2**t;for(let n=1;n<8;n++){if(e<o){let e;if(r<0)e=new ArrayBuffer(n),a=n;else{if(r<n)return new ArrayBuffer(0);e=new ArrayBuffer(r),a=r}let o=new Uint8Array(e);for(let e=n-1;e>=0;e--){let n=2**(e*t);o[a-e-1]=Math.floor(i/n),i-=o[a-e-1]*n}return e}o*=2**t}return new ArrayBuffer(0)}function af(...e){let t=0,n=0;for(let n of e)t+=n.length;let r=new ArrayBuffer(t),i=new Uint8Array(r);for(let t of e)i.set(t,n),n+=t.length;return i}function of(){let e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let t=e[0]===255&&e[1]&128,n=e[0]===0&&!(e[1]&128);(t||n)&&this.warnings.push(`Needlessly long format`)}let t=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)n[e]=0;n[0]=e[0]&128;let r=nf(n,8),i=new ArrayBuffer(this.valueHex.byteLength),a=new Uint8Array(i);for(let t=0;t<this.valueHex.byteLength;t++)a[t]=e[t];return a[0]&=127,nf(a,8)-r}function sf(e){let t=e<0?e*-1:e,n=128;for(let r=1;r<8;r++){if(t<=n){if(e<0){let e=rf(n-t,8,r),i=new Uint8Array(e);return i[0]|=128,e}let i=rf(t,8,r),a=new Uint8Array(i);if(a[0]&128){let e=i.slice(0),t=new Uint8Array(e);i=new ArrayBuffer(i.byteLength+1),a=new Uint8Array(i);for(let n=0;n<e.byteLength;n++)a[n+1]=t[n];a[0]=0}return i}n*=256}return new ArrayBuffer(0)}function cf(e,t){if(e.byteLength!==t.byteLength)return!1;let n=new Uint8Array(e),r=new Uint8Array(t);for(let e=0;e<n.length;e++)if(n[e]!==r[e])return!1;return!0}function lf(e,t){let n=e.toString(10);if(t<n.length)return``;let r=t-n.length,i=Array.from({length:r});for(let e=0;e<r;e++)i[e]=`0`;return i.join(``).concat(n)}var uf=ee({Any:()=>Mm,BaseBlock:()=>Rf,BaseStringBlock:()=>Bf,BitString:()=>bp,BmpString:()=>Xp,Boolean:()=>mp,CharacterString:()=>_m,Choice:()=>Nm,Constructed:()=>op,DATE:()=>Cm,DEFAULT_MAX_CONTENT_LENGTH:()=>Gf,DEFAULT_MAX_DEPTH:()=>100,DEFAULT_MAX_NODES:()=>Wf,DateTime:()=>Dm,Duration:()=>km,EndOfContent:()=>lp,Enumerated:()=>kp,GeneralString:()=>hm,GeneralizedTime:()=>xm,GraphicString:()=>dm,HexBlock:()=>Nf,IA5String:()=>lm,Integer:()=>Dp,Null:()=>dp,NumericString:()=>tm,ObjectIdentifier:()=>Np,OctetString:()=>_p,Primitive:()=>Uf,PrintableString:()=>rm,RawData:()=>Fm,RelativeObjectIdentifier:()=>Lp,Repeated:()=>Pm,Sequence:()=>zp,Set:()=>Vp,TIME:()=>jm,TeletexString:()=>am,TimeOfDay:()=>Tm,UTCTime:()=>ym,UniversalString:()=>$p,Utf8String:()=>qp,ValueBlock:()=>Ff,VideotexString:()=>sm,ViewWriter:()=>mf,VisibleString:()=>pm,compareSchema:()=>Im,fromBER:()=>np,verifySchema:()=>Lm});function df(){if(typeof BigInt>`u`)throw Error(`BigInt is not defined. Your environment doesn't implement BigInt.`)}function ff(e){let t=0,n=0;for(let n=0;n<e.length;n++){let r=e[n];t+=r.byteLength}let r=new Uint8Array(t);for(let t=0;t<e.length;t++){let i=e[t];r.set(new Uint8Array(i),n),n+=i.byteLength}return r.buffer}function pf(e,t,n,r){return t instanceof Uint8Array?t.byteLength?n<0?(e.error=`Wrong parameter: inputOffset less than zero`,!1):r<0?(e.error=`Wrong parameter: inputLength less than zero`,!1):t.byteLength-n-r<0?(e.error=`End of input reached before message was fully decoded (inconsistent offset and length values)`,!1):!0:(e.error=`Wrong parameter: inputBuffer has zero length`,!1):(e.error=`Wrong parameter: inputBuffer must be 'Uint8Array'`,!1)}var mf=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return ff(this.items)}},hf=[new Uint8Array([1])],gf=`0123456789`,_f=`name`,vf=`valueHexView`,yf=`isHexOnly`,bf=`idBlock`,xf=`tagClass`,Sf=`tagNumber`,Cf=`isConstructed`,wf=`fromBER`,Tf=`toBER`,Ef=`local`,Df=``,Of=new ArrayBuffer(0),kf=new Uint8Array,Af=`EndOfContent`,jf=`OCTET STRING`,Mf=`BIT STRING`;function Nf(e){var t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){super(...e);let t=e[0]||{};this.isHexOnly=t.isHexOnly??!1,this.valueHexView=t.valueHex?U.toUint8Array(t.valueHex):kf}fromBER(e,t,n,r){let i=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!pf(this,i,t,n))return-1;let a=t+n;return this.valueHexView=i.subarray(t,a),this.valueHexView.length?(this.blockLength=n,a):(this.warnings.push(`Zero buffer length`),t)}toBER(e=!1){return this.isHexOnly?e?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`,Of)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:$d.ToHex(this.valueHexView)}}};return t.NAME=`hexBlock`,t}var Pf=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:t=Df,warnings:n=[],valueBeforeDecode:r=kf}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=U.toUint8Array(r)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:$d.ToHex(this.valueBeforeDecodeView)}}};Pf.NAME=`baseBlock`;var Ff=class extends Pf{fromBER(e,t,n,r){throw TypeError(`User need to make a specific function in a class which extends 'ValueBlock'`)}toBER(e,t){throw TypeError(`User need to make a specific function in a class which extends 'ValueBlock'`)}};Ff.NAME=`valueBlock`;var If=class extends Nf(Pf){constructor({idBlock:e={}}={}){super(),e?(this.isHexOnly=e.isHexOnly??!1,this.valueHexView=e.valueHex?U.toUint8Array(e.valueHex):kf,this.tagClass=e.tagClass??-1,this.tagNumber=e.tagNumber??-1,this.isConstructed=e.isConstructed??!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error=`Unknown tag class`,Of}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let n=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,n[0]=t}return n.buffer}if(!this.isHexOnly){let n=rf(this.tagNumber,7),r=new Uint8Array(n),i=n.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let e=0;e<i-1;e++)a[e+1]=r[e]|128;a[i]=r[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let e=this.valueHexView;for(let t=0;t<e.length-1;t++)n[t+1]=e[t]|128;n[this.valueHexView.byteLength]=e[e.length-1]}return n.buffer}fromBER(e,t,n){let r=U.toUint8Array(e);if(!pf(this,r,t,n))return-1;let i=r.subarray(t,t+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 e=0;for(;;){let t=e+1;if(t>=i.length)return this.error=`End of input reached before message was fully decoded`,-1;if(e++,!(i[t]&128))break}this.blockLength=e+1;let t=this.valueHexView=new Uint8Array(e);for(let n=0;n<e;n++)t[n]=i[n+1]&127;this.blockLength<=9?this.tagNumber=nf(t,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 t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};If.NAME=`identificationBlock`;var Lf=class extends Pf{constructor({lenBlock:e={}}={}){super(),this.isIndefiniteForm=e.isIndefiniteForm??!1,this.longFormUsed=e.longFormUsed??!1,this.length=e.length??0}fromBER(e,t,n){let r=U.toUint8Array(e);if(!pf(this,r,t,n))return-1;let i=r.subarray(t,t+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,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let a=i[0]&127;if(a>8)return this.error=`Too big integer`,-1;if(a+1>i.length)return this.error=`End of input reached before message was fully decoded`,-1;let o=t+1,s=r.subarray(o,o+a);return s[a-1]===0&&this.warnings.push(`Needlessly long encoded length`),this.length=nf(s,8),this.longFormUsed&&this.length<=127&&this.warnings.push(`Unnecessary usage of long length form`),this.blockLength=a+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let r=rf(this.length,8);if(r.byteLength>127)return this.error=`Too big length`,Of;if(t=new ArrayBuffer(r.byteLength+1),e)return t;let i=new Uint8Array(r);n=new Uint8Array(t),n[0]=r.byteLength|128;for(let e=0;e<r.byteLength;e++)n[e+1]=i[e];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Lf.NAME=`lengthBlock`;var W={},Rf=class extends Pf{constructor({name:e=Df,optional:t=!1,primitiveSchema:n,...r}={},i){super(r),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new If(r),this.lenBlock=new Lf(r),this.valueBlock=i?new i(r):new Ff(r)}fromBER(e,t,n,r){let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,r);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,t){let n=t||new mf;t||zf(this);let r=this.idBlock.toBER(e);if(n.write(r),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;let r=this.lenBlock.toBER(e);n.write(r),n.write(t)}return t?Of: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():$d.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${$d.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&cf(this.toBER(),e.toBER())}};Rf.NAME=`BaseBlock`;function zf(e){if(e instanceof W.Constructed)for(let t of e.valueBlock.value)zf(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock?.isIndefiniteForm}var Bf=class extends Rf{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Df,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(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),r)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Bf.NAME=`BaseStringBlock`;var Vf=class extends Nf(Ff){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Vf.NAME=`PrimitiveValueBlock`;var Hf,Uf=class extends Rf{constructor(e={}){super(e,Vf),this.idBlock.isConstructed=!1}};Hf=Uf,W.Primitive=Hf,Uf.NAME=`PRIMITIVE`;var Wf=1e4,Gf=16777216,Kf=`Maximum ASN.1 nesting depth exceeded`,qf=`Maximum ASN.1 node count exceeded`,Jf=`Maximum ASN.1 content length exceeded`;function Yf(e={}){return{depth:0,maxDepth:e.maxDepth??100,nodesCount:0,maxNodes:e.maxNodes??Wf,maxContentLength:e.maxContentLength??Gf}}function Xf(e){let t=new Rf({},Ff);return t.error=e,{offset:-1,result:t}}function Zf(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return qf}function Qf(e,t){if(e>t.maxContentLength)return Jf}function $f(e,t,n,r){let i=r.depth+1;if(i>r.maxDepth)return Xf(Kf);r.depth=i;try{return tp(e,t,n,r)}finally{--r.depth}}function ep(e,t){if(e instanceof t)return e;let n=new t;return n.idBlock=e.idBlock,n.lenBlock=e.lenBlock,n.warnings=e.warnings,n.valueBeforeDecodeView=e.valueBeforeDecodeView,n}function tp(e,t=0,n=e.length,r=Yf()){let i=t,a=new Rf({},Ff),o=new Pf;if(!pf(o,e,t,n))return a.error=o.error,{offset:-1,result:a};if(!e.subarray(t,t+n).length)return a.error=`Zero buffer length`,{offset:-1,result:a};let s=Zf(r);if(s)return a.error=s,{offset:-1,result:a};let c=a.idBlock.fromBER(e,t,n);if(a.idBlock.warnings.length&&a.warnings.concat(a.idBlock.warnings),c===-1)return a.error=a.idBlock.error,{offset:-1,result:a};if(t=c,n-=a.idBlock.blockLength,c=a.lenBlock.fromBER(e,t,n),a.lenBlock.warnings.length&&a.warnings.concat(a.lenBlock.warnings),c===-1)return a.error=a.lenBlock.error,{offset:-1,result:a};t=c,n-=a.lenBlock.blockLength;let l=a.lenBlock.isIndefiniteForm?n:a.lenBlock.length,u=Qf(l,r);if(u)return a.error=u,{offset:-1,result:a};if(!a.idBlock.isConstructed&&a.lenBlock.isIndefiniteForm)return a.error=`Indefinite length form used for primitive encoding form`,{offset:-1,result:a};let d=Rf;switch(a.idBlock.tagClass){case 1:if(a.idBlock.tagNumber>=37&&a.idBlock.isHexOnly===!1)return a.error=`UNIVERSAL 37 and upper tags are reserved by ASN.1 standard`,{offset:-1,result:a};switch(a.idBlock.tagNumber){case 0:if(a.idBlock.isConstructed&&a.lenBlock.length>0)return a.error=`Type [UNIVERSAL 0] is reserved`,{offset:-1,result:a};d=W.EndOfContent;break;case 1:d=W.Boolean;break;case 2:d=W.Integer;break;case 3:d=W.BitString;break;case 4:d=W.OctetString;break;case 5:d=W.Null;break;case 6:d=W.ObjectIdentifier;break;case 10:d=W.Enumerated;break;case 12:d=W.Utf8String;break;case 13:d=W.RelativeObjectIdentifier;break;case 14:d=W.TIME;break;case 15:return a.error=`[UNIVERSAL 15] is reserved by ASN.1 standard`,{offset:-1,result:a};case 16:d=W.Sequence;break;case 17:d=W.Set;break;case 18:d=W.NumericString;break;case 19:d=W.PrintableString;break;case 20:d=W.TeletexString;break;case 21:d=W.VideotexString;break;case 22:d=W.IA5String;break;case 23:d=W.UTCTime;break;case 24:d=W.GeneralizedTime;break;case 25:d=W.GraphicString;break;case 26:d=W.VisibleString;break;case 27:d=W.GeneralString;break;case 28:d=W.UniversalString;break;case 29:d=W.CharacterString;break;case 30:d=W.BmpString;break;case 31:d=W.DATE;break;case 32:d=W.TimeOfDay;break;case 33:d=W.DateTime;break;case 34:d=W.Duration;break;default:{let e=a.idBlock.isConstructed?new W.Constructed:new W.Primitive;e.idBlock=a.idBlock,e.lenBlock=a.lenBlock,e.warnings=a.warnings,a=e}}break;default:d=a.idBlock.isConstructed?W.Constructed:W.Primitive}return a=ep(a,d),c=a.fromBER(e,t,l,r),a.valueBeforeDecodeView=e.subarray(i,i+a.blockLength),{offset:c,result:a}}function np(e,t={}){if(!e.byteLength){let e=new Rf({},Ff);return e.error=`Input buffer has zero length`,{offset:-1,result:e}}return tp(U.toUint8Array(e).slice(),0,e.byteLength,Yf(t))}function rp(e,t){return e?1:t}var ip=class extends Ff{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,r){let i=U.toUint8Array(e),a=r??Yf();if(!pf(this,i,t,n))return-1;if(this.valueBeforeDecodeView=i.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push(`Zero buffer length`),t;let o=t;for(;rp(this.isIndefiniteForm,n)>0;){let e=$f(i,o,n,a);if(e.offset===-1)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(o=e.offset,this.blockLength+=e.result.blockLength,n-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===Af)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Af?this.value.pop():this.warnings.push(`No EndOfContent block encoded`)),o}toBER(e,t){let n=t||new mf;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,n);return t?Of:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};ip.NAME=`ConstructedValueBlock`;var ap,op=class extends Rf{constructor(e={}){super(e,ip),this.idBlock.isConstructed=!0}fromBER(e,t,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,r);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 t of this.valueBlock.value)e.push(t.toString(`ascii`).split(`
|
|
24
24
|
`).map(e=>` ${e}`).join(`
|
|
25
25
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join(`
|
|
26
|
-
`)}`:`${t} :`}};wa=Ta,W.Constructed=wa,Ta.NAME=`CONSTRUCTED`;var Ea=class extends ea{fromBER(e,t,n){return t}toBER(e){return qi}};Ea.override=`EndOfContentValueBlock`;var Da,Oa=class extends ra{constructor(e={}){super(e,Ea),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Da=Oa,W.EndOfContent=Da,Oa.NAME=Yi;var ka,Aa=class extends ra{constructor(e={}){super(e,ea),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,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,t+n>e.byteLength?(this.error=`End of input reached before message was fully decoded (inconsistent offset and length values)`,-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let e=new Uint8Array(n);e[0]=5,e[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};ka=Aa,W.Null=ka,Aa.NAME=`NULL`;var ja=class extends Qi(ea){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,...t}={}){super(t),this.valueHexView=t.valueHex?U.toUint8Array(t.valueHex):new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let r=U.toUint8Array(e);return Mi(this,r,t,n)?(this.valueHexView=r.subarray(t,t+n),n>1&&this.warnings.push(`Boolean value encoded in more then 1 octet`),this.isHexOnly=!0,Ti.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ja.NAME=`BooleanValueBlock`;var Ma,Na=class extends ra{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,ja),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Ma=Na,W.Boolean=Ma,Na.NAME=`BOOLEAN`;var Pa=class extends Qi(Ca){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n,r){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=Ca.prototype.fromBER.call(this,e,t,n,r),i===-1)return i;for(let e=0;e<this.value.length;e++){let t=this.value[e].constructor.NAME;if(t===Yi){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only`,-1}if(t!==Xi)return this.error=`OCTET STRING may consists of OCTET STRINGs only`,-1}}else this.isHexOnly=!0,i=super.fromBER(e,t,n),this.blockLength=n;return i}toBER(e,t){return this.isConstructed?Ca.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Pa.NAME=`OctetStringValueBlock`;var Fa,Ia=class extends ra{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Pa),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n,r){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),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let e=r??ma(),t=va(i,0,i.byteLength,e);t.offset!==-1&&t.offset===n&&(this.valueBlock.value=[t.result])}}catch{}}return super.fromBER(e,t,n,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Ta.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${yi.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof Fa&&e.push(t.valueBlock.valueHexView);return U.concat(e)}};Fa=Ia,W.OctetString=Fa,Ia.NAME=Xi;var La=class extends Qi(Ca){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n,r){if(!n)return t;let i=-1;if(this.isConstructed){if(i=Ca.prototype.fromBER.call(this,e,t,n,r),i===-1)return i;for(let e of this.value){let t=e.constructor.NAME;if(t===Yi){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only`,-1}if(t!==Zi)return this.error=`BIT STRING may consists of BIT STRINGs only`,-1;let n=e.valueBlock;if(this.unusedBits>0&&n.unusedBits>0)return this.error=`Using of "unused bits" inside constructive BIT STRING allowed for least one only`,-1;this.unusedBits=n.unusedBits}return i}let a=U.toUint8Array(e);if(!Mi(this,a,t,n))return-1;let o=a.subarray(t,t+n);if(this.unusedBits=o[0],this.unusedBits>7)return this.error=`Unused bits for BitString must be in range 0-7`,-1;if(!this.unusedBits){let e=o.subarray(1);try{if(e.byteLength){let t=r??ma(),i=va(e,0,e.byteLength,t);i.offset!==-1&&i.offset===n-1&&(this.value=[i.result])}}catch{}}return this.valueHexView=o.subarray(1),this.blockLength=o.length,t+n}toBER(e,t){if(this.isConstructed)return Ca.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let e=new Uint8Array(1);return e[0]=0,e.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}}};La.NAME=`BitStringValueBlock`;var Ra,za=class extends ra{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},La),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ta.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let n of t)e.push(n.toString(2).padStart(8,`0`));let n=e.join(``);return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Ra=za,W.BitString=Ra,za.NAME=Zi;var Ba;function Va(e,t){let n=new Uint8Array([0]),r=new Uint8Array(e),i=new Uint8Array(t),a=r.slice(0),o=a.length-1,s=i.slice(0),c=s.length-1,l=0,u=c<o?o:c,d=0;for(let e=u;e>=0;e--,d++){switch(!0){case d<s.length:l=a[o-d]+s[c-d]+n[0];break;default:l=a[o-d]+n[0]}switch(n[0]=l/10,!0){case d>=a.length:a=wi(new Uint8Array([l%10]),a);break;default:a[o-d]=l%10}}return n[0]>0&&(a=wi(n,a)),a}function Ha(e){if(e>=Pi.length)for(let t=Pi.length;t<=e;t++){let e=new Uint8Array([0]),n=Pi[t-1].slice(0);for(let t=n.length-1;t>=0;t--){let r=new Uint8Array([(n[t]<<1)+e[0]]);e[0]=r[0]/10,n[t]=r[0]%10}e[0]>0&&(n=wi(e,n)),Pi.push(n)}return Pi[e]}function Ua(e,t){let n=0,r=new Uint8Array(e),i=new Uint8Array(t),a=r.slice(0),o=a.length-1,s=i.slice(0),c=s.length-1,l,u=0;for(let e=c;e>=0;e--,u++)switch(l=a[o-u]-s[c-u]-n,!0){case l<0:n=1,a[o-u]=l+10;break;default:n=0,a[o-u]=l}if(n>0)for(let e=o-c+1;e>=0;e--,u++)if(l=a[o-u]-n,l<0)n=1,a[o-u]=l+10;else{n=0,a[o-u]=l;break}return a.slice()}var Wa=class extends Qi(ea){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=Ti.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ei(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,r=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let a=this.valueHexView;return a[0]===0&&a[1]&128?this.valueHexView=a.subarray(1):r!==0&&a.length<r&&(r-a.length>1&&(r=a.length+1),this.valueHexView=a.subarray(r-a.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case!!(t[0]&128):{let e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case t[0]===0&&!(t[1]&128):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,n){let r=super.fromBER(e,t,n);return r===-1||this.setValueHex(),r}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,t=new Uint8Array(this.valueHexView.length*8/3),n=0,r,i=this.valueHexView,a=``,o=!1;for(let o=i.byteLength-1;o>=0;o--){r=i[o];for(let i=0;i<8;i++){if((r&1)==1)switch(n){case e:t=Ua(Ha(n),t),a=`-`;break;default:t=Va(t,Ha(n))}n++,r>>=1}}for(let e=0;e<t.length;e++)t[e]&&(o=!0),o&&(a+=Fi.charAt(t[e]));return o===!1&&(a+=Fi.charAt(0)),a}};Ba=Wa,Wa.NAME=`IntegerValueBlock`,Object.defineProperty(Ba.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Ga,Ka=class extends ra{constructor(e={}){super(e,Wa),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Ai(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Ai();let t=BigInt(e),n=new Ni,r=t.toString(16).replace(/^-/,``),i=new Uint8Array(yi.FromHex(r));if(t<0){let e=new Uint8Array(i.length+(i[0]&128?1:0));e[0]|=128;let r=BigInt(`0x${yi.ToHex(e)}`)+t,a=U.toUint8Array(yi.FromHex(r.toString(16)));a[0]|=128,n.write(a)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new Ga({valueHex:n.final()})}convertToDER(){let e=new Ga({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Ga({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Ga=Ka,W.Integer=Ga,Ka.NAME=`INTEGER`;var qa,Ja=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};qa=Ja,W.Enumerated=qa,Ja.NAME=`ENUMERATED`;var Ya=class extends Qi(ea){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let r=U.toUint8Array(e);if(!Mi(this,r,t,n))return-1;let i=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let e=0;e<n&&(this.valueHexView[e]=i[e]&127,this.blockLength++,i[e]&128);e++);let a=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)a[e]=this.valueHexView[e];return this.valueHexView=a,i[this.blockLength-1]&128?(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=Si(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}set valueBigInt(e){Ai();let t=BigInt(e).toString(2);for(;t.length%7;)t=`0`+t;let n=new Uint8Array(t.length/7);for(let e=0;e<n.length;e++)n[e]=parseInt(t.slice(e*7,e*7+7),2)+(e+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 t=this.valueHexView,n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)n[e]=t[e]|128;return n[this.blockLength-1]=t[this.blockLength-1],n.buffer}let t=Ci(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,qi;let n=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)n[t]=e[t]|128;n[r]=e[r]}return n}toString(){let e=``;if(this.isHexOnly)e=yi.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e=`0.`:this.valueDec<=79?(e=`1.`,t-=40):(e=`2.`,t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Ya.NAME=`sidBlock`;var Xa=class extends ea{constructor({value:e=Ki,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new Ya;if(r=t.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=t.error,r;this.value.length===0&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,n-=t.blockLength,this.value.push(t)}return r}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let r=this.value[n].toBER(e);if(r.byteLength===0)return this.error=this.value[n].error,qi;t.push(r)}return ji(t)}fromString(e){this.value=[];let t=0,n=0,r=``,i=!1;do if(n=e.indexOf(`.`,t),r=n===-1?e.substring(t):e.substring(t,n),t=n+1,i){let e=this.value[0],t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:this.value=[];return}let n=parseInt(r,10);if(isNaN(n))return;e.valueDec=n+t,i=!1}else{let e=new Ya;if(r>2**53-1)Ai(),e.valueBigInt=BigInt(r);else if(e.valueDec=parseInt(r,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}while(n!==-1)}toString(){let e=``,t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t?(r=`{${r}}`,this.value[n].isFirstSid?e=`2.{${r} - 80}`:e+=r):e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Xa.NAME=`ObjectIdentifierValueBlock`;var Za,Qa=class extends ra{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Xa),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Za=Qa,W.ObjectIdentifier=Za,Qa.NAME=`OBJECT IDENTIFIER`;var $a=class extends Qi($i){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let r=U.toUint8Array(e);if(!Mi(this,r,t,n))return-1;let i=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let e=0;e<n&&(this.valueHexView[e]=i[e]&127,this.blockLength++,i[e]&128);e++);let a=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)a[e]=this.valueHexView[e];return this.valueHexView=a,i[this.blockLength-1]&128?(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=Si(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let t=this.valueHexView,n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)n[e]=t[e]|128;return n[this.blockLength-1]=t[this.blockLength-1],n.buffer}let t=Ci(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,qi;let n=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)n[t]=e[t]|128;n[r]=e[r]}return n.buffer}toString(){let e=``;return e=this.isHexOnly?yi.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};$a.NAME=`relativeSidBlock`;var eo=class extends ea{constructor({value:e=Ki,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new $a;if(r=t.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=t.error,r;this.blockLength+=t.blockLength,n-=t.blockLength,this.value.push(t)}return r}toBER(e,t){let n=[];for(let t=0;t<this.value.length;t++){let r=this.value[t].toBER(e);if(r.byteLength===0)return this.error=this.value[t].error,qi;n.push(r)}return ji(n)}fromString(e){this.value=[];let t=0,n=0,r=``;do{n=e.indexOf(`.`,t),r=n===-1?e.substring(t):e.substring(t,n),t=n+1;let i=new $a;if(i.valueDec=parseInt(r,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e=``,t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(r=`{${r}}`),e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};eo.NAME=`RelativeObjectIdentifierValueBlock`;var to,no=class extends ra{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,eo),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};to=no,W.RelativeObjectIdentifier=to,no.NAME=`RelativeObjectIdentifier`;var ro,io=class extends Ta{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};ro=io,W.Sequence=ro,io.NAME=`SEQUENCE`;var ao,oo=class extends Ta{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};ao=oo,W.Set=ao,oo.NAME=`SET`;var so=class extends Qi(ea){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ki}toJSON(){return{...super.toJSON(),value:this.value}}};so.NAME=`StringValueBlock`;var co=class extends so{};co.NAME=`SimpleStringValueBlock`;var lo=class extends aa{constructor({...e}={}){super(e,co)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,U.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);this.valueBlock.value=e}};lo.NAME=`SIMPLE STRING`;var uo=class extends lo{fromBuffer(e){this.valueBlock.valueHexView=U.toUint8Array(e);try{this.valueBlock.value=yi.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=yi.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(yi.FromUtf8String(e)),this.valueBlock.value=e}};uo.NAME=`Utf8StringValueBlock`;var fo,po=class extends uo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};fo=po,W.Utf8String=fo,po.NAME=`UTF8String`;var mo=class extends lo{fromBuffer(e){this.valueBlock.value=yi.ToUtf16String(e),this.valueBlock.valueHexView=U.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(yi.FromUtf16String(e))}};mo.NAME=`BmpStringValueBlock`;var ho,go=class extends mo{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};ho=go,W.BmpString=ho,go.NAME=`BMPString`;var _o=class extends lo{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let e=0;e<n.length;e+=4)n[e]=n[e+3],n[e+1]=n[e+2],n[e+2]=0,n[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let r=0;r<t;r++){let t=Ci(e.charCodeAt(r),8),i=new Uint8Array(t);if(i.length>4)continue;let a=4-i.length;for(let e=i.length-1;e>=0;e--)n[r*4+e+a]=i[e]}this.valueBlock.value=e}};_o.NAME=`UniversalStringValueBlock`;var vo,yo=class extends _o{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};vo=yo,W.UniversalString=vo,yo.NAME=`UniversalString`;var bo,xo=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};bo=xo,W.NumericString=bo,xo.NAME=`NumericString`;var So,Co=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};So=Co,W.PrintableString=So,Co.NAME=`PrintableString`;var wo,To=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};wo=To,W.TeletexString=wo,To.NAME=`TeletexString`;var Eo,Do=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Eo=Do,W.VideotexString=Eo,Do.NAME=`VideotexString`;var Oo,ko=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Oo=ko,W.IA5String=Oo,ko.NAME=`IA5String`;var Ao,jo=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ao=jo,W.GraphicString=Ao,jo.NAME=`GraphicString`;var Mo,No=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Mo=No,W.VisibleString=Mo,No.NAME=`VisibleString`;var Po,Fo=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Po=Fo,W.GeneralString=Po,Fo.NAME=`GeneralString`;var Io,Lo=class extends lo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Io=Lo,W.CharacterString=Io,Lo.NAME=`CharacterString`;var Ro,zo=class extends No{constructor({value:e,valueDate:t,...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 t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,U.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return t}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 t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(t===null){this.error=`Wrong input string for conversion`;return}let n=parseInt(t[1],10);this.year=n>=50?1900+n:2e3+n,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e=`iso`){if(e===`iso`){let e=Array(7);return e[0]=Oi(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Oi(this.month,2),e[2]=Oi(this.day,2),e[3]=Oi(this.hour,2),e[4]=Oi(this.minute,2),e[5]=Oi(this.second,2),e[6]=`Z`,e.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}}};Ro=zo,W.UTCTime=Ro,zo.NAME=`UTCTime`;var Bo,Vo=class extends zo{constructor(e={}){super(e),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 t=!1,n=``,r=``,i=0,a,o=0,s=0;if(e[e.length-1]===`Z`)n=e.substring(0,e.length-1),t=!0;else{let t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw Error(`Wrong input string for conversion`);n=e}if(t){if(n.indexOf(`+`)!==-1||n.indexOf(`-`)!==-1)throw Error(`Wrong input string for conversion`)}else{let e=1,t=n.indexOf(`+`),r=``;if(t===-1&&(t=n.indexOf(`-`),e=-1),t!==-1){if(r=n.substring(t+1),n=n.substring(0,t),r.length!==2&&r.length!==4)throw Error(`Wrong input string for conversion`);let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw Error(`Wrong input string for conversion`);if(o=e*i,r.length===4){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw Error(`Wrong input string for conversion`);s=e*i}}}let c=n.indexOf(`.`);if(c===-1&&(c=n.indexOf(`,`)),c!==-1){let e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw Error(`Wrong input string for conversion`);i=e.valueOf(),r=n.substring(0,c)}else r=n;switch(!0){case r.length===8:if(a=/(\d{4})(\d{2})(\d{2})/gi,c!==-1)throw Error(`Wrong input string for conversion`);break;case r.length===10:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=60*i;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case r.length===12:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=60*i;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case r.length===14:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=1e3*i;this.millisecond=Math.floor(e)}break;default:throw Error(`Wrong input string for conversion`)}let l=a.exec(r);if(l===null)throw Error(`Wrong input string for conversion`);for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+o;break;case 5:this.minute=parseInt(l[e],10)+s;break;case 6:this.second=parseInt(l[e],10);break;default:throw Error(`Wrong input string for conversion`)}if(t===!1){let e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e=`iso`){if(e===`iso`){let e=[];return e.push(Oi(this.year,4)),e.push(Oi(this.month,2)),e.push(Oi(this.day,2)),e.push(Oi(this.hour,2)),e.push(Oi(this.minute,2)),e.push(Oi(this.second,2)),this.millisecond!==0&&(e.push(`.`),e.push(Oi(this.millisecond,3))),e.push(`Z`),e.join(``)}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Bo=Vo,W.GeneralizedTime=Bo,Vo.NAME=`GeneralizedTime`;var Ho,Uo=class extends po{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Ho=Uo,W.DATE=Ho,Uo.NAME=`DATE`;var Wo,Go=class extends po{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Wo=Go,W.TimeOfDay=Wo,Go.NAME=`TimeOfDay`;var Ko,qo=class extends po{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Ko=qo,W.DateTime=Ko,qo.NAME=`DateTime`;var Jo,Yo=class extends po{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Jo=Yo,W.Duration=Jo,Yo.NAME=`Duration`;var Xo,Zo=class extends po{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Xo=Zo,W.TIME=Xo,Zo.NAME=`TIME`;var Qo=class{constructor({name:e=Ki,optional:t=!1}={}){this.name=e,this.optional=t}},$o=class extends Qo{constructor({value:e=[],...t}={}){super(t),this.value=e}},es=class extends Qo{constructor({value:e=new Qo,local:t=!1,...n}={}){super(n),this.value=e,this.local=t}},ts=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=U.toUint8Array(e)}constructor({data:e=Ji}={}){this.dataView=U.toUint8Array(e)}fromBER(e,t,n){let r=t+n;return this.dataView=U.toUint8Array(e).subarray(t,r),r}toBER(e){return this.dataView.slice().buffer}};function ns(e,t,n){if(n instanceof $o){for(let r of n.value)if(ns(e,t,r).verified)return{verified:!0,result:e};{let e={verified:!1,result:{error:`Wrong values for Choice type`}};return n.hasOwnProperty(Ii)&&(e.name=n.name),e}}if(n instanceof Qo)return n.hasOwnProperty(Ii)&&(e[n.name]=t),{verified:!0,result:e};if(!(e instanceof Object))return{verified:!1,result:{error:`Wrong root object`}};if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 data`}};if(!(n instanceof Object)||!(zi in n)||!(Ui in n.idBlock)||!(Wi in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};let r=n.idBlock.toBER(!1);if(r.byteLength===0)return{verified:!1,result:{error:`Error encoding idBlock for ASN.1 schema`}};if(n.idBlock.fromBER(r,0,r.byteLength)===-1)return{verified:!1,result:{error:`Error decoding idBlock for ASN.1 schema`}};if(n.idBlock.hasOwnProperty(Bi)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(n.idBlock.hasOwnProperty(Vi)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(n.idBlock.hasOwnProperty(Hi)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(Ri in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(n.idBlock.isHexOnly){if(!(Li in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};let r=n.idBlock.valueHexView,i=t.idBlock.valueHexView;if(r.length!==i.length)return{verified:!1,result:e};for(let t=0;t<r.length;t++)if(r[t]!==i[1])return{verified:!1,result:e}}if(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Ki),n.name&&(e[n.name]=t)),n instanceof W.Constructed){let r=0,i={verified:!1,result:{error:`Unknown error`}},a=n.valueBlock.value.length;if(a>0&&n.valueBlock.value[0]instanceof es&&(a=t.valueBlock.value.length),a===0)return{verified:!0,result:e};if(t.valueBlock.value.length===0&&n.valueBlock.value.length!==0){let t=!0;for(let e=0;e<n.valueBlock.value.length;e++)t&&=n.valueBlock.value[e].optional||!1;return t?{verified:!0,result:e}:(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Ki),n.name&&delete e[n.name]),e.error=`Inconsistent object length`,{verified:!1,result:e})}for(let o=0;o<a;o++)if(o-r>=t.valueBlock.value.length){if(n.valueBlock.value[o].optional===!1){let t={verified:!1,result:e};return e.error=`Inconsistent length between ASN.1 data and schema`,n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Ki),n.name&&(delete e[n.name],t.name=n.name)),t}}else if(n.valueBlock.value[0]instanceof es){if(i=ns(e,t.valueBlock.value[o],n.valueBlock.value[0].value),i.verified===!1){if(n.valueBlock.value[0].optional)r++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Ki),n.name&&delete e[n.name]),i}if(Ii in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let r={};r=Gi in n.valueBlock.value[0]&&n.valueBlock.value[0].local?t:e,r[n.valueBlock.value[0].name]===void 0&&(r[n.valueBlock.value[0].name]=[]),r[n.valueBlock.value[0].name].push(t.valueBlock.value[o])}}else if(i=ns(e,t.valueBlock.value[o-r],n.valueBlock.value[o]),i.verified===!1){if(n.valueBlock.value[o].optional)r++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Ki),n.name&&delete e[n.name]),i}if(i.verified===!1){let t={verified:!1,result:e};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Ki),n.name&&(delete e[n.name],t.name=n.name)),t}return{verified:!0,result:e}}if(n.primitiveSchema&&Li in t.valueBlock){let r=ba(t.valueBlock.valueHexView);if(r.offset===-1){let t={verified:!1,result:r.result};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Ki),n.name&&(delete e[n.name],t.name=n.name)),t}return ns(e,r.result,n.primitiveSchema)}return{verified:!0,result:e}}function rs(e,t){if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 schema type`}};let n=ba(U.toUint8Array(e));return n.offset===-1?{verified:!1,result:n.result}:ns(n.result,n.result,t)}var is=`[object ArrayBuffer]`,as=`[object SharedArrayBuffer]`;function os(e){return Object.prototype.toString.call(e)}function ss(e){if(ArrayBuffer.isView(e))return!0;if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.byteOffset==`number`&&typeof t.byteLength==`number`&&us(t.buffer)}function cs(e){return os(e)===is}function ls(e){return typeof SharedArrayBuffer<`u`&&os(e)===as}function us(e){return cs(e)||ls(e)}function ds(e){return ss(e)}function fs(e){return us(e)||ds(e)}function ps(e){if(!fs(e))throw TypeError(`Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView`)}function ms(e){return ps(e),us(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function hs(e){if(ps(e),cs(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(ms(e)),t}function gs(e,t,n={}){let r=ms(e),i=ms(t);if(!n.constantTime&&r.byteLength!==i.byteLength)return!1;let a=Math.max(r.byteLength,i.byteLength),o=r.byteLength^i.byteLength;for(let e=0;e<a;e++)o|=(r[e]??0)^(i[e]??0);return o===0}function _s(e){let t=ms(e),n=``;for(let e of t)n+=String.fromCharCode(e);return n}function vs(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function ys(e){return typeof e==`string`}var bs=/^[0-9a-f]$/i,xs=[` `,` `,`
|
|
27
|
-
`,`\r`,`:`,`-`,`.`];function
|
|
26
|
+
`)}`:`${t} :`}};ap=op,W.Constructed=ap,op.NAME=`CONSTRUCTED`;var sp=class extends Ff{fromBER(e,t,n){return t}toBER(e){return Of}};sp.override=`EndOfContentValueBlock`;var cp,lp=class extends Rf{constructor(e={}){super(e,sp),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};cp=lp,W.EndOfContent=cp,lp.NAME=Af;var up,dp=class extends Rf{constructor(e={}){super(e,Ff),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,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,t+n>e.byteLength?(this.error=`End of input reached before message was fully decoded (inconsistent offset and length values)`,-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let e=new Uint8Array(n);e[0]=5,e[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};up=dp,W.Null=up,dp.NAME=`NULL`;var fp=class extends Nf(Ff){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,...t}={}){super(t),this.valueHexView=t.valueHex?U.toUint8Array(t.valueHex):new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let r=U.toUint8Array(e);return pf(this,r,t,n)?(this.valueHexView=r.subarray(t,t+n),n>1&&this.warnings.push(`Boolean value encoded in more then 1 octet`),this.isHexOnly=!0,of.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};fp.NAME=`BooleanValueBlock`;var pp,mp=class extends Rf{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,fp),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};pp=mp,W.Boolean=pp,mp.NAME=`BOOLEAN`;var hp=class extends Nf(ip){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n,r){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=ip.prototype.fromBER.call(this,e,t,n,r),i===-1)return i;for(let e=0;e<this.value.length;e++){let t=this.value[e].constructor.NAME;if(t===Af){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only`,-1}if(t!==jf)return this.error=`OCTET STRING may consists of OCTET STRINGs only`,-1}}else this.isHexOnly=!0,i=super.fromBER(e,t,n),this.blockLength=n;return i}toBER(e,t){return this.isConstructed?ip.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};hp.NAME=`OctetStringValueBlock`;var gp,_p=class extends Rf{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},hp),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n,r){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),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let e=r??Yf(),t=$f(i,0,i.byteLength,e);t.offset!==-1&&t.offset===n&&(this.valueBlock.value=[t.result])}}catch{}}return super.fromBER(e,t,n,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?op.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${$d.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof gp&&e.push(t.valueBlock.valueHexView);return U.concat(e)}};gp=_p,W.OctetString=gp,_p.NAME=jf;var vp=class extends Nf(ip){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n,r){if(!n)return t;let i=-1;if(this.isConstructed){if(i=ip.prototype.fromBER.call(this,e,t,n,r),i===-1)return i;for(let e of this.value){let t=e.constructor.NAME;if(t===Af){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only`,-1}if(t!==Mf)return this.error=`BIT STRING may consists of BIT STRINGs only`,-1;let n=e.valueBlock;if(this.unusedBits>0&&n.unusedBits>0)return this.error=`Using of "unused bits" inside constructive BIT STRING allowed for least one only`,-1;this.unusedBits=n.unusedBits}return i}let a=U.toUint8Array(e);if(!pf(this,a,t,n))return-1;let o=a.subarray(t,t+n);if(this.unusedBits=o[0],this.unusedBits>7)return this.error=`Unused bits for BitString must be in range 0-7`,-1;if(!this.unusedBits){let e=o.subarray(1);try{if(e.byteLength){let t=r??Yf(),i=$f(e,0,e.byteLength,t);i.offset!==-1&&i.offset===n-1&&(this.value=[i.result])}}catch{}}return this.valueHexView=o.subarray(1),this.blockLength=o.length,t+n}toBER(e,t){if(this.isConstructed)return ip.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let e=new Uint8Array(1);return e[0]=0,e.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}}};vp.NAME=`BitStringValueBlock`;var yp,bp=class extends Rf{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},vp),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return op.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let n of t)e.push(n.toString(2).padStart(8,`0`));let n=e.join(``);return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};yp=bp,W.BitString=yp,bp.NAME=Mf;var xp;function Sp(e,t){let n=new Uint8Array([0]),r=new Uint8Array(e),i=new Uint8Array(t),a=r.slice(0),o=a.length-1,s=i.slice(0),c=s.length-1,l=0,u=c<o?o:c,d=0;for(let e=u;e>=0;e--,d++){switch(!0){case d<s.length:l=a[o-d]+s[c-d]+n[0];break;default:l=a[o-d]+n[0]}switch(n[0]=l/10,!0){case d>=a.length:a=af(new Uint8Array([l%10]),a);break;default:a[o-d]=l%10}}return n[0]>0&&(a=af(n,a)),a}function Cp(e){if(e>=hf.length)for(let t=hf.length;t<=e;t++){let e=new Uint8Array([0]),n=hf[t-1].slice(0);for(let t=n.length-1;t>=0;t--){let r=new Uint8Array([(n[t]<<1)+e[0]]);e[0]=r[0]/10,n[t]=r[0]%10}e[0]>0&&(n=af(e,n)),hf.push(n)}return hf[e]}function wp(e,t){let n=0,r=new Uint8Array(e),i=new Uint8Array(t),a=r.slice(0),o=a.length-1,s=i.slice(0),c=s.length-1,l,u=0;for(let e=c;e>=0;e--,u++)switch(l=a[o-u]-s[c-u]-n,!0){case l<0:n=1,a[o-u]=l+10;break;default:n=0,a[o-u]=l}if(n>0)for(let e=o-c+1;e>=0;e--,u++)if(l=a[o-u]-n,l<0)n=1,a[o-u]=l+10;else{n=0,a[o-u]=l;break}return a.slice()}var Tp=class extends Nf(Ff){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=of.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(sf(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,r=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let a=this.valueHexView;return a[0]===0&&a[1]&128?this.valueHexView=a.subarray(1):r!==0&&a.length<r&&(r-a.length>1&&(r=a.length+1),this.valueHexView=a.subarray(r-a.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case!!(t[0]&128):{let e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case t[0]===0&&!(t[1]&128):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,n){let r=super.fromBER(e,t,n);return r===-1||this.setValueHex(),r}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,t=new Uint8Array(this.valueHexView.length*8/3),n=0,r,i=this.valueHexView,a=``,o=!1;for(let o=i.byteLength-1;o>=0;o--){r=i[o];for(let i=0;i<8;i++){if((r&1)==1)switch(n){case e:t=wp(Cp(n),t),a=`-`;break;default:t=Sp(t,Cp(n))}n++,r>>=1}}for(let e=0;e<t.length;e++)t[e]&&(o=!0),o&&(a+=gf.charAt(t[e]));return o===!1&&(a+=gf.charAt(0)),a}};xp=Tp,Tp.NAME=`IntegerValueBlock`,Object.defineProperty(xp.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Ep,Dp=class extends Rf{constructor(e={}){super(e,Tp),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return df(),BigInt(this.valueBlock.toString())}static fromBigInt(e){df();let t=BigInt(e),n=new mf,r=t.toString(16).replace(/^-/,``),i=new Uint8Array($d.FromHex(r));if(t<0){let e=new Uint8Array(i.length+(i[0]&128?1:0));e[0]|=128;let r=BigInt(`0x${$d.ToHex(e)}`)+t,a=U.toUint8Array($d.FromHex(r.toString(16)));a[0]|=128,n.write(a)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new Ep({valueHex:n.final()})}convertToDER(){let e=new Ep({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Ep({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Ep=Dp,W.Integer=Ep,Dp.NAME=`INTEGER`;var Op,kp=class extends Dp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Op=kp,W.Enumerated=Op,kp.NAME=`ENUMERATED`;var Ap=class extends Nf(Ff){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let r=U.toUint8Array(e);if(!pf(this,r,t,n))return-1;let i=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let e=0;e<n&&(this.valueHexView[e]=i[e]&127,this.blockLength++,i[e]&128);e++);let a=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)a[e]=this.valueHexView[e];return this.valueHexView=a,i[this.blockLength-1]&128?(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=nf(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}set valueBigInt(e){df();let t=BigInt(e).toString(2);for(;t.length%7;)t=`0`+t;let n=new Uint8Array(t.length/7);for(let e=0;e<n.length;e++)n[e]=parseInt(t.slice(e*7,e*7+7),2)+(e+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 t=this.valueHexView,n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)n[e]=t[e]|128;return n[this.blockLength-1]=t[this.blockLength-1],n.buffer}let t=rf(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,Of;let n=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)n[t]=e[t]|128;n[r]=e[r]}return n}toString(){let e=``;if(this.isHexOnly)e=$d.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e=`0.`:this.valueDec<=79?(e=`1.`,t-=40):(e=`2.`,t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Ap.NAME=`sidBlock`;var jp=class extends Ff{constructor({value:e=Df,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new Ap;if(r=t.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=t.error,r;this.value.length===0&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,n-=t.blockLength,this.value.push(t)}return r}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let r=this.value[n].toBER(e);if(r.byteLength===0)return this.error=this.value[n].error,Of;t.push(r)}return ff(t)}fromString(e){this.value=[];let t=0,n=0,r=``,i=!1;do if(n=e.indexOf(`.`,t),r=n===-1?e.substring(t):e.substring(t,n),t=n+1,i){let e=this.value[0],t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:this.value=[];return}let n=parseInt(r,10);if(isNaN(n))return;e.valueDec=n+t,i=!1}else{let e=new Ap;if(r>2**53-1)df(),e.valueBigInt=BigInt(r);else if(e.valueDec=parseInt(r,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}while(n!==-1)}toString(){let e=``,t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t?(r=`{${r}}`,this.value[n].isFirstSid?e=`2.{${r} - 80}`:e+=r):e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};jp.NAME=`ObjectIdentifierValueBlock`;var Mp,Np=class extends Rf{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,jp),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Mp=Np,W.ObjectIdentifier=Mp,Np.NAME=`OBJECT IDENTIFIER`;var Pp=class extends Nf(Pf){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let r=U.toUint8Array(e);if(!pf(this,r,t,n))return-1;let i=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let e=0;e<n&&(this.valueHexView[e]=i[e]&127,this.blockLength++,i[e]&128);e++);let a=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)a[e]=this.valueHexView[e];return this.valueHexView=a,i[this.blockLength-1]&128?(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=nf(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let t=this.valueHexView,n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)n[e]=t[e]|128;return n[this.blockLength-1]=t[this.blockLength-1],n.buffer}let t=rf(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,Of;let n=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)n[t]=e[t]|128;n[r]=e[r]}return n.buffer}toString(){let e=``;return e=this.isHexOnly?$d.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Pp.NAME=`relativeSidBlock`;var Fp=class extends Ff{constructor({value:e=Df,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new Pp;if(r=t.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=t.error,r;this.blockLength+=t.blockLength,n-=t.blockLength,this.value.push(t)}return r}toBER(e,t){let n=[];for(let t=0;t<this.value.length;t++){let r=this.value[t].toBER(e);if(r.byteLength===0)return this.error=this.value[t].error,Of;n.push(r)}return ff(n)}fromString(e){this.value=[];let t=0,n=0,r=``;do{n=e.indexOf(`.`,t),r=n===-1?e.substring(t):e.substring(t,n),t=n+1;let i=new Pp;if(i.valueDec=parseInt(r,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e=``,t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(r=`{${r}}`),e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Fp.NAME=`RelativeObjectIdentifierValueBlock`;var Ip,Lp=class extends Rf{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Fp),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Ip=Lp,W.RelativeObjectIdentifier=Ip,Lp.NAME=`RelativeObjectIdentifier`;var Rp,zp=class extends op{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Rp=zp,W.Sequence=Rp,zp.NAME=`SEQUENCE`;var Bp,Vp=class extends op{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Bp=Vp,W.Set=Bp,Vp.NAME=`SET`;var Hp=class extends Nf(Ff){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Df}toJSON(){return{...super.toJSON(),value:this.value}}};Hp.NAME=`StringValueBlock`;var Up=class extends Hp{};Up.NAME=`SimpleStringValueBlock`;var Wp=class extends Bf{constructor({...e}={}){super(e,Up)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,U.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);this.valueBlock.value=e}};Wp.NAME=`SIMPLE STRING`;var Gp=class extends Wp{fromBuffer(e){this.valueBlock.valueHexView=U.toUint8Array(e);try{this.valueBlock.value=$d.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=$d.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array($d.FromUtf8String(e)),this.valueBlock.value=e}};Gp.NAME=`Utf8StringValueBlock`;var Kp,qp=class extends Gp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Kp=qp,W.Utf8String=Kp,qp.NAME=`UTF8String`;var Jp=class extends Wp{fromBuffer(e){this.valueBlock.value=$d.ToUtf16String(e),this.valueBlock.valueHexView=U.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array($d.FromUtf16String(e))}};Jp.NAME=`BmpStringValueBlock`;var Yp,Xp=class extends Jp{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Yp=Xp,W.BmpString=Yp,Xp.NAME=`BMPString`;var Zp=class extends Wp{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let e=0;e<n.length;e+=4)n[e]=n[e+3],n[e+1]=n[e+2],n[e+2]=0,n[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let r=0;r<t;r++){let t=rf(e.charCodeAt(r),8),i=new Uint8Array(t);if(i.length>4)continue;let a=4-i.length;for(let e=i.length-1;e>=0;e--)n[r*4+e+a]=i[e]}this.valueBlock.value=e}};Zp.NAME=`UniversalStringValueBlock`;var Qp,$p=class extends Zp{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Qp=$p,W.UniversalString=Qp,$p.NAME=`UniversalString`;var em,tm=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};em=tm,W.NumericString=em,tm.NAME=`NumericString`;var nm,rm=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};nm=rm,W.PrintableString=nm,rm.NAME=`PrintableString`;var im,am=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};im=am,W.TeletexString=im,am.NAME=`TeletexString`;var om,sm=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};om=sm,W.VideotexString=om,sm.NAME=`VideotexString`;var cm,lm=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};cm=lm,W.IA5String=cm,lm.NAME=`IA5String`;var um,dm=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};um=dm,W.GraphicString=um,dm.NAME=`GraphicString`;var fm,pm=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};fm=pm,W.VisibleString=fm,pm.NAME=`VisibleString`;var mm,hm=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};mm=hm,W.GeneralString=mm,hm.NAME=`GeneralString`;var gm,_m=class extends Wp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};gm=_m,W.CharacterString=gm,_m.NAME=`CharacterString`;var vm,ym=class extends pm{constructor({value:e,valueDate:t,...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 t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,U.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return t}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 t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(t===null){this.error=`Wrong input string for conversion`;return}let n=parseInt(t[1],10);this.year=n>=50?1900+n:2e3+n,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e=`iso`){if(e===`iso`){let e=Array(7);return e[0]=lf(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=lf(this.month,2),e[2]=lf(this.day,2),e[3]=lf(this.hour,2),e[4]=lf(this.minute,2),e[5]=lf(this.second,2),e[6]=`Z`,e.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}}};vm=ym,W.UTCTime=vm,ym.NAME=`UTCTime`;var bm,xm=class extends ym{constructor(e={}){super(e),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 t=!1,n=``,r=``,i=0,a,o=0,s=0;if(e[e.length-1]===`Z`)n=e.substring(0,e.length-1),t=!0;else{let t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw Error(`Wrong input string for conversion`);n=e}if(t){if(n.indexOf(`+`)!==-1||n.indexOf(`-`)!==-1)throw Error(`Wrong input string for conversion`)}else{let e=1,t=n.indexOf(`+`),r=``;if(t===-1&&(t=n.indexOf(`-`),e=-1),t!==-1){if(r=n.substring(t+1),n=n.substring(0,t),r.length!==2&&r.length!==4)throw Error(`Wrong input string for conversion`);let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw Error(`Wrong input string for conversion`);if(o=e*i,r.length===4){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw Error(`Wrong input string for conversion`);s=e*i}}}let c=n.indexOf(`.`);if(c===-1&&(c=n.indexOf(`,`)),c!==-1){let e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw Error(`Wrong input string for conversion`);i=e.valueOf(),r=n.substring(0,c)}else r=n;switch(!0){case r.length===8:if(a=/(\d{4})(\d{2})(\d{2})/gi,c!==-1)throw Error(`Wrong input string for conversion`);break;case r.length===10:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=60*i;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case r.length===12:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=60*i;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case r.length===14:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=1e3*i;this.millisecond=Math.floor(e)}break;default:throw Error(`Wrong input string for conversion`)}let l=a.exec(r);if(l===null)throw Error(`Wrong input string for conversion`);for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+o;break;case 5:this.minute=parseInt(l[e],10)+s;break;case 6:this.second=parseInt(l[e],10);break;default:throw Error(`Wrong input string for conversion`)}if(t===!1){let e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e=`iso`){if(e===`iso`){let e=[];return e.push(lf(this.year,4)),e.push(lf(this.month,2)),e.push(lf(this.day,2)),e.push(lf(this.hour,2)),e.push(lf(this.minute,2)),e.push(lf(this.second,2)),this.millisecond!==0&&(e.push(`.`),e.push(lf(this.millisecond,3))),e.push(`Z`),e.join(``)}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};bm=xm,W.GeneralizedTime=bm,xm.NAME=`GeneralizedTime`;var Sm,Cm=class extends qp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Sm=Cm,W.DATE=Sm,Cm.NAME=`DATE`;var wm,Tm=class extends qp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};wm=Tm,W.TimeOfDay=wm,Tm.NAME=`TimeOfDay`;var Em,Dm=class extends qp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Em=Dm,W.DateTime=Em,Dm.NAME=`DateTime`;var Om,km=class extends qp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Om=km,W.Duration=Om,km.NAME=`Duration`;var Am,jm=class extends qp{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Am=jm,W.TIME=Am,jm.NAME=`TIME`;var Mm=class{constructor({name:e=Df,optional:t=!1}={}){this.name=e,this.optional=t}},Nm=class extends Mm{constructor({value:e=[],...t}={}){super(t),this.value=e}},Pm=class extends Mm{constructor({value:e=new Mm,local:t=!1,...n}={}){super(n),this.value=e,this.local=t}},Fm=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=U.toUint8Array(e)}constructor({data:e=kf}={}){this.dataView=U.toUint8Array(e)}fromBER(e,t,n){let r=t+n;return this.dataView=U.toUint8Array(e).subarray(t,r),r}toBER(e){return this.dataView.slice().buffer}};function Im(e,t,n){if(n instanceof Nm){for(let r of n.value)if(Im(e,t,r).verified)return{verified:!0,result:e};{let e={verified:!1,result:{error:`Wrong values for Choice type`}};return n.hasOwnProperty(_f)&&(e.name=n.name),e}}if(n instanceof Mm)return n.hasOwnProperty(_f)&&(e[n.name]=t),{verified:!0,result:e};if(!(e instanceof Object))return{verified:!1,result:{error:`Wrong root object`}};if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 data`}};if(!(n instanceof Object)||!(bf in n)||!(wf in n.idBlock)||!(Tf in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};let r=n.idBlock.toBER(!1);if(r.byteLength===0)return{verified:!1,result:{error:`Error encoding idBlock for ASN.1 schema`}};if(n.idBlock.fromBER(r,0,r.byteLength)===-1)return{verified:!1,result:{error:`Error decoding idBlock for ASN.1 schema`}};if(n.idBlock.hasOwnProperty(xf)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(n.idBlock.hasOwnProperty(Sf)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(n.idBlock.hasOwnProperty(Cf)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(yf in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(n.idBlock.isHexOnly){if(!(vf in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};let r=n.idBlock.valueHexView,i=t.idBlock.valueHexView;if(r.length!==i.length)return{verified:!1,result:e};for(let t=0;t<r.length;t++)if(r[t]!==i[1])return{verified:!1,result:e}}if(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Df),n.name&&(e[n.name]=t)),n instanceof W.Constructed){let r=0,i={verified:!1,result:{error:`Unknown error`}},a=n.valueBlock.value.length;if(a>0&&n.valueBlock.value[0]instanceof Pm&&(a=t.valueBlock.value.length),a===0)return{verified:!0,result:e};if(t.valueBlock.value.length===0&&n.valueBlock.value.length!==0){let t=!0;for(let e=0;e<n.valueBlock.value.length;e++)t&&=n.valueBlock.value[e].optional||!1;return t?{verified:!0,result:e}:(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Df),n.name&&delete e[n.name]),e.error=`Inconsistent object length`,{verified:!1,result:e})}for(let o=0;o<a;o++)if(o-r>=t.valueBlock.value.length){if(n.valueBlock.value[o].optional===!1){let t={verified:!1,result:e};return e.error=`Inconsistent length between ASN.1 data and schema`,n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Df),n.name&&(delete e[n.name],t.name=n.name)),t}}else if(n.valueBlock.value[0]instanceof Pm){if(i=Im(e,t.valueBlock.value[o],n.valueBlock.value[0].value),i.verified===!1){if(n.valueBlock.value[0].optional)r++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Df),n.name&&delete e[n.name]),i}if(_f in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let r={};r=Ef in n.valueBlock.value[0]&&n.valueBlock.value[0].local?t:e,r[n.valueBlock.value[0].name]===void 0&&(r[n.valueBlock.value[0].name]=[]),r[n.valueBlock.value[0].name].push(t.valueBlock.value[o])}}else if(i=Im(e,t.valueBlock.value[o-r],n.valueBlock.value[o]),i.verified===!1){if(n.valueBlock.value[o].optional)r++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Df),n.name&&delete e[n.name]),i}if(i.verified===!1){let t={verified:!1,result:e};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Df),n.name&&(delete e[n.name],t.name=n.name)),t}return{verified:!0,result:e}}if(n.primitiveSchema&&vf in t.valueBlock){let r=tp(t.valueBlock.valueHexView);if(r.offset===-1){let t={verified:!1,result:r.result};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,Df),n.name&&(delete e[n.name],t.name=n.name)),t}return Im(e,r.result,n.primitiveSchema)}return{verified:!0,result:e}}function Lm(e,t){if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 schema type`}};let n=tp(U.toUint8Array(e));return n.offset===-1?{verified:!1,result:n.result}:Im(n.result,n.result,t)}var Rm=`[object ArrayBuffer]`,zm=`[object SharedArrayBuffer]`;function Bm(e){return Object.prototype.toString.call(e)}function Vm(e){if(ArrayBuffer.isView(e))return!0;if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.byteOffset==`number`&&typeof t.byteLength==`number`&&Wm(t.buffer)}function Hm(e){return Bm(e)===Rm}function Um(e){return typeof SharedArrayBuffer<`u`&&Bm(e)===zm}function Wm(e){return Hm(e)||Um(e)}function Gm(e){return Vm(e)}function Km(e){return Wm(e)||Gm(e)}function qm(e){if(!Km(e))throw TypeError(`Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView`)}function Jm(e){return qm(e),Wm(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Ym(e){if(qm(e),Hm(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(Jm(e)),t}function Xm(e,t,n={}){let r=Jm(e),i=Jm(t);if(!n.constantTime&&r.byteLength!==i.byteLength)return!1;let a=Math.max(r.byteLength,i.byteLength),o=r.byteLength^i.byteLength;for(let e=0;e<a;e++)o|=(r[e]??0)^(i[e]??0);return o===0}function Zm(e){let t=Jm(e),n=``;for(let e of t)n+=String.fromCharCode(e);return n}function Qm(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function $m(e){return typeof e==`string`}var eh=/^[0-9a-f]$/i,th=[` `,` `,`
|
|
27
|
+
`,`\r`,`:`,`-`,`.`];function nh(e){return e.separators===`none`?[]:!e.separators||e.separators===`common`?th:e.separators}function rh(e){if(!e)throw TypeError(`Hex separators must be non-empty strings`)}function ih(e,t,n){for(let r of n)if(e.startsWith(r,t))return r}function ah(e){let t=/[A-F]/.test(e),n=/[a-f]/.test(e);return t&&!n?`upper`:`lower`}function oh(e){let t=/\r\n|\n/.exec(e);if(t)return t[0]===`\r
|
|
28
28
|
`?`\r
|
|
29
29
|
`:`
|
|
30
|
-
`}function
|
|
31
|
-
`,r=[];for(let n=0;n<i.length;n+=e)r.push(
|
|
30
|
+
`}function sh(e){return e.replace(/[^0-9a-f]/gi,``)}function ch(e){let t=e.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(t.length<3)return;let n=t.filter((e,t)=>t%2==0),r=t.filter((e,t)=>t%2==1),i=r[0];if(!i||r.some(e=>e!==i)||n.some(e=>e.length===0||e.length%2!=0))return;let a=n[0]?.length??0;if(a&&!n.slice(0,-1).some(e=>e.length!==a)&&!((n[n.length-1]?.length??0)>a))return{size:a/2,separator:i}}function lh(e){let t=e.trim(),n=/^0x/i.test(t)?`0x`:``,r=n?t.slice(2):t,i=oh(r),a=r.split(/\r\n|\n/).filter(e=>e.length>0),o=ch(a[0]?.trim()??``),s={case:ah(t),prefix:n};if(o&&(s.group=o),i&&a.length>1){let e=sh(a[0]??``).length/2;e>0&&a.slice(0,-1).every(t=>sh(t).length/2===e)&&(s.line={bytesPerLine:e,separator:i})}return s}function uh(e,t){let n=t.allowPrefix??!0,r=[...nh(t)].sort((e,t)=>t.length-e.length);for(let e of r)rh(e);let i=e.trim();if(/^0x/i.test(i)){if(!n)throw TypeError(`Hexadecimal text must not include a 0x prefix`);i=i.slice(2)}let a=``,o=!1;for(let e=0;e<i.length;){let n=i[e]??``;if(eh.test(n)){a+=n,o=!1,e+=1;continue}let s=ih(i,e,r);if(!s)throw TypeError(`Input is not valid hexadecimal text`);if(t.strict&&(o||a.length===0))throw TypeError(`Hexadecimal text contains misplaced separators`);o=!0,e+=s.length}if(t.strict&&o&&a.length>0)throw TypeError(`Hexadecimal text must not end with a separator`);if(a.length%2!=0){if(!t.allowOddLength)throw TypeError(`Hexadecimal text must contain an even number of characters`);a=`0${a}`}return a.toLowerCase()}function dh(e,t){if(!t)return e.join(``);if(!Number.isInteger(t.size)||t.size<1)throw RangeError(`Hex group size must be a positive integer`);let n=[];for(let r=0;r<e.length;r+=t.size)n.push(e.slice(r,r+t.size).join(``));return n.join(t.separator)}function fh(e,t={}){return uh(e,t)}function ph(e,t={}){if(typeof e!=`string`)return!1;try{return fh(e,t),!0}catch{return!1}}function mh(e,t={}){let n=Jm(e),r=t.case??`lower`,i=Array.from(n,e=>{let t=e.toString(16).padStart(2,`0`);return r===`upper`?t.toUpperCase():t}),a=``;if(t.line){let e=t.line.bytesPerLine;if(!Number.isInteger(e)||e<1)throw RangeError(`Hex bytesPerLine must be a positive integer`);let n=t.line.separator??`
|
|
31
|
+
`,r=[];for(let n=0;n<i.length;n+=e)r.push(dh(i.slice(n,n+e),t.group));a=r.join(n)}else a=dh(i,t.group);return`${t.prefix??``}${a}`}function hh(e,t={}){let n=fh(e,t),r=new Uint8Array(n.length/2);for(let e=0;e<n.length;e+=2)r[e/2]=Number.parseInt(n.slice(e,e+2),16);return r}function gh(e,t={}){let n=fh(e,t);return{bytes:hh(n),format:lh(e),normalized:n}}function _h(e,t){return mh(e,t)}Object.freeze({}),Object.freeze({case:`upper`}),Object.freeze({group:{size:1,separator:`:`}}),Object.freeze({case:`upper`,group:{size:1,separator:`:`}}),Object.freeze({group:{size:4,separator:` `}}),Object.freeze({prefix:`0x`});function vh(e){return new TextEncoder().encode(e)}function yh(e){return new TextDecoder(`utf-8`,{fatal:!1}).decode(Jm(e))}function bh(e,t={}){let n=new ArrayBuffer(e.length*2),r=new DataView(n);for(let n=0;n<e.length;n++)r.setUint16(n*2,e.charCodeAt(n),t.littleEndian??!1);return new Uint8Array(n)}function xh(e,t={}){let n=Ym(e),r=new DataView(n),i=``;for(let e=0;e<n.byteLength;e+=2)i+=String.fromCharCode(r.getUint16(e,t.littleEndian??!1));return i}var Sh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Ch(){return globalThis.Buffer}function wh(e){return e.replace(/[\n\r\t ]/g,``)}function Th(e){let t=e.length%4;return t?e+`=`.repeat(4-t):e}function Eh(e){if(typeof e!=`string`)return!1;let t=wh(e);return t===``||Sh.test(t)}function Dh(e,t){let n=Jm(e),r=Ch();return r?r.from(n).toString(`base64`):btoa(Zm(n))}function Oh(e,t){let n=wh(e);if(!Eh(n))throw TypeError(`Input is not valid Base64 text`);let r=Ch();return r?new Uint8Array(r.from(n,`base64`)):Qm(atob(n))}var kh={encode:Dh,decode:Oh,is:Eh,normalize:wh,pad:Th},Ah=/^[A-Za-z0-9_-]*$/;function jh(e){return e.replace(/[\n\r\t ]/g,``)}function Mh(e){return typeof e==`string`&&Ah.test(jh(e))}function Nh(e,t){return kh.encode(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}function Ph(e,t){let n=jh(e);if(!Mh(n))throw TypeError(`Input is not valid Base64Url text`);return kh.decode(kh.pad(n.replace(/-/g,`+`).replace(/_/g,`/`)))}var Fh=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,Ih=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function Lh(e){if(!Fh.test(e))throw TypeError(`Invalid PEM label '${e}'`)}function Rh(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function zh(e){let t=e.trim().replace(/\r\n/g,`
|
|
32
32
|
`).split(`
|
|
33
|
-
`).map(e=>e.trim()).filter(Boolean),n={},r=0;for(;r<t.length;r++){let e=t[r],i=e.indexOf(`:`);if(i<=0)break;n[e.slice(0,i).trim()]=e.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:t.slice(r),base64Text:t.slice(r).join(``)}}function
|
|
33
|
+
`).map(e=>e.trim()).filter(Boolean),n={},r=0;for(;r<t.length;r++){let e=t[r],i=e.indexOf(`:`);if(i<=0)break;n[e.slice(0,i).trim()]=e.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:t.slice(r),base64Text:t.slice(r).join(``)}}function Bh(e){return/\r\n/.test(e)?`\r
|
|
34
34
|
`:`
|
|
35
|
-
`}function
|
|
36
|
-
`,a=[`-----BEGIN ${e}-----`];if(n.headers){for(let[e,t]of Object.entries(n.headers))a.push(`${e}: ${t}`);a.push(``)}return a.push(...ic(Ys.encode(t),r)),a.push(`-----END ${e}-----`),`${a.join(i)}${i}`}function lc(e,t={}){return sc(e,t).map(({lineLength:e,newline:t,...n})=>n)}function uc(e,t){let[n]=lc(e,{label:t,strict:!0});return n.data}function dc(e,t={}){let[n]=sc(e,{...t,strict:!0}),r={label:n.label,headers:n.headers,lineLength:n.lineLength,newline:n.newline};return{bytes:n.data,format:r,normalized:cc(n.label,n.data,r)}}function fc(e,t){return cc(t.label,e,t)}var pc={name:`pem`,encode:(e,t)=>{if(!t?.label)throw TypeError(`PEM label is required`);return cc(t.label,e,t)},decode:(e,t)=>uc(e,t?.label),format:fc,is:e=>typeof e==`string`&&/-----BEGIN [^-]+-----/.test(e),parse:dc};function mc(e){return e.trim().toLowerCase()}function hc(e){return e instanceof Error?e:Error(String(e))}function gc(e,t,n){for(let t of[n.name,...n.aliases??[]])e.delete(mc(t));t.delete(mc(n.name))}function _c(e,t,n){let r=e[n];if(typeof r!=`function`)throw Error(`Converter '${t}' does not support ${n}()`);return r}function vc(e,t,n){let r=mc(n.name||e),i=t.trim();if(!i)return 0;let a=!1;n.is&&(a=n.is(t));let o=!1;try{n.decode(t),o=!0}catch{o=!1}if(!a&&!o)return 0;switch(r){case`pem`:return+!!/-----BEGIN [^-]+-----/.test(t);case`hex`:{let e=i.replace(/^0x/i,``).replace(/[\s:.-]/g,``);return!e||/[^0-9a-f]/i.test(e)||e.length%2!=0?0:/^0x/i.test(i)||/[:\s.-]/.test(i)?.95:/[a-f]/.test(i)||/[A-F]/.test(i)?.8:.45}case`base64url`:return/[-_]/.test(i)?.95:/=/.test(i)?.1:.6;case`base64`:return/[+/=]/.test(i)?.9:.55;case`binary`:case`utf8`:case`utf16be`:case`utf16le`:return 0;default:return a&&o?.75:.5}}function yc(e=[]){let t=new Map,n=new Set,r={register(e,r={}){if(!e.name||!mc(e.name))throw TypeError(`Converter name is required`);let i=[...new Set([e.name,...e.aliases??[]].map(mc))],a=new Set;for(let e of i){let n=t.get(e);if(n){if(!r.override)throw Error(`Converter '${e}' is already registered`);a.add(n)}}for(let e of a)gc(t,n,e);for(let n of i)t.set(n,e);return n.add(mc(e.name)),this},unregister(e){let r=t.get(mc(e));return r?(gc(t,n,r),!0):!1},has(e){return t.has(mc(e))},get(e){let n=t.get(mc(e));if(!n)throw Error(`Converter '${e}' is not registered`);return n},list(){return[...n].map(e=>this.get(e))},encode(e,t,n){return this.get(e).encode(t,n)},decode(e,t,n){return this.get(e).decode(t,n)},tryDecode(e,t,n){try{return{ok:!0,bytes:this.decode(e,t,n)}}catch(e){return{ok:!1,error:hc(e)}}},normalize(e,t,n){let r=this.get(e);return _c(r,e,`normalize`).call(r,t,n)},parse(e,t,n){let r=this.get(e);return _c(r,e,`parse`).call(r,t,n)},format(e,t,n){let r=this.get(e);return _c(r,e,`format`).call(r,t,n)},transcode(e,t){let n=this.decode(t.from,e,t.fromOptions);return this.encode(t.to,n,t.toOptions)},detect(e,t={}){let n=t.formats?.length?t.formats.map(e=>String(e)):this.list().map(e=>e.name).filter(e=>![`binary`,`utf8`,`utf16be`,`utf16le`].includes(mc(e))),r=new Map;for(let t of n){let n=this.get(t),i=vc(t,e,n);if(i<=0)continue;let a=n.name,o=r.get(a);(!o||i>o.confidence)&&r.set(a,{format:a,confidence:i})}return[...r.values()].sort((e,t)=>t.confidence-e.confidence)}};for(let t of e)r.register(t);return r}yc([{name:`binary`,aliases:[`latin1`],encode:_s,decode:vs,is:ys},{name:`hex`,encode:Ps,decode:Fs,format:Ls,is:Ns,normalize:Ms,parse:Is},{name:`base64`,aliases:[`b64`],encode:qs,decode:Js,is:Ks,normalize:Ws},{name:`base64url`,aliases:[`base64-url`,`b64url`],encode:$s,decode:ec,is:Qs,normalize:Zs},{name:`utf8`,aliases:[`utf-8`],encode:e=>zs(e),decode:e=>Rs(e),is:e=>typeof e==`string`},{name:`utf16be`,aliases:[`utf16`,`utf-16`,`utf-16be`],encode:e=>Vs(e),decode:e=>Bs(e),is:e=>typeof e==`string`},{name:`utf16le`,aliases:[`utf-16le`,`ucs2`,`usc2`],encode:e=>Vs(e,{littleEndian:!0}),decode:e=>Bs(e,{littleEndian:!0}),is:e=>typeof e==`string`},pc]);var G;(function(e){e[e.Sequence=0]=`Sequence`,e[e.Set=1]=`Set`,e[e.Choice=2]=`Choice`})(G||={});var K;(function(e){e[e.Any=1]=`Any`,e[e.Boolean=2]=`Boolean`,e[e.OctetString=3]=`OctetString`,e[e.BitString=4]=`BitString`,e[e.Integer=5]=`Integer`,e[e.Enumerated=6]=`Enumerated`,e[e.ObjectIdentifier=7]=`ObjectIdentifier`,e[e.Utf8String=8]=`Utf8String`,e[e.BmpString=9]=`BmpString`,e[e.UniversalString=10]=`UniversalString`,e[e.NumericString=11]=`NumericString`,e[e.PrintableString=12]=`PrintableString`,e[e.TeletexString=13]=`TeletexString`,e[e.VideotexString=14]=`VideotexString`,e[e.IA5String=15]=`IA5String`,e[e.GraphicString=16]=`GraphicString`,e[e.VisibleString=17]=`VisibleString`,e[e.GeneralString=18]=`GeneralString`,e[e.CharacterString=19]=`CharacterString`,e[e.UTCTime=20]=`UTCTime`,e[e.GeneralizedTime=21]=`GeneralizedTime`,e[e.DATE=22]=`DATE`,e[e.TimeOfDay=23]=`TimeOfDay`,e[e.DateTime=24]=`DateTime`,e[e.Duration=25]=`Duration`,e[e.TIME=26]=`TIME`,e[e.Null=27]=`Null`,e[e.RelativeObjectIdentifier=28]=`RelativeObjectIdentifier`})(K||={});var bc=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e){if(typeof e==`number`)this.fromNumber(e);else if(fs(e))this.unusedBits=t,this.value=hs(e);else throw TypeError(`Unsupported type of 'params' argument for BitString`)}}fromASN(e){if(!(e instanceof za))throw TypeError(`Argument 'asn' is not instance of ASN.1 BitString`);return this.unusedBits=e.valueBlock.unusedBits,this.value=hs(e.valueBlock.valueHex),this}toASN(){return new za({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new za({name:e})}toNumber(){let e=``,t=new Uint8Array(this.value);for(let n of t)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 t=e.toString(2),n=t.length+7>>3;this.unusedBits=(n<<3)-t.length;let r=new Uint8Array(n);t=t.padStart(n<<3,`0`).split(``).reverse().join(``);let i=0;for(;i<n;)r[i]=parseInt(t.slice(i<<3,(i<<3)+8),2),i++;this.value=r.buffer}},xc=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){this.buffer=typeof e==`number`?new ArrayBuffer(e):fs(e)?hs(e):Array.isArray(e)?new Uint8Array(e).buffer:new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Ia))throw TypeError(`Argument 'asn' is not instance of ASN.1 OctetString`);return this.buffer=hs(e.valueBlock.valueHex),this}toASN(){return new Ia({valueHex:this.buffer})}toSchema(e){return new Ia({name:e})}},Sc={fromASN:e=>e instanceof Aa?null:hs(e.valueBeforeDecodeView),toASN:e=>{if(e===null)return new Aa;let t=xa(e);if(t.result.error)throw Error(t.result.error);return t.result}},Cc={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Ka({value:+e})},wc={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new Ja({value:e})},Tc={fromASN:e=>hs(e.valueBlock.valueHexView),toASN:e=>new Ka({valueHex:e})},Ec={fromASN:e=>hs(e.valueBlock.valueHexView),toASN:e=>new za({valueHex:e})},Dc={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Qa({value:e})},Oc={fromASN:e=>e.valueBlock.toString(),toASN:e=>new no({value:e})},kc={fromASN:e=>e.valueBlock.value,toASN:e=>new Na({value:e})},Ac={fromASN:e=>hs(e.valueBlock.valueHexView),toASN:e=>new Ia({valueHex:e})},jc={fromASN:e=>new xc(e.getValue()),toASN:e=>e.toASN()};function Mc(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var Nc=Mc(po),Pc=Mc(go),Fc=Mc(yo),Ic=Mc(xo),Lc=Mc(Co),Rc=Mc(To),zc=Mc(Do),Bc=Mc(ko),Vc=Mc(jo),Hc=Mc(No),Uc=Mc(Fo),Wc=Mc(Lo),Gc={fromASN:e=>e.toDate(),toASN:e=>new zo({valueDate:e})},Kc={fromASN:e=>e.toDate(),toASN:e=>new Vo({valueDate:e})},qc={fromASN:()=>null,toASN:()=>new Aa};function Jc(e){switch(e){case K.Any:return Sc;case K.BitString:return Ec;case K.BmpString:return Pc;case K.Boolean:return kc;case K.CharacterString:return Wc;case K.Enumerated:return wc;case K.GeneralString:return Uc;case K.GeneralizedTime:return Kc;case K.GraphicString:return Vc;case K.IA5String:return Bc;case K.Integer:return Cc;case K.Null:return qc;case K.NumericString:return Ic;case K.ObjectIdentifier:return Dc;case K.RelativeObjectIdentifier:return Oc;case K.OctetString:return Ac;case K.PrintableString:return Lc;case K.TeletexString:return Rc;case K.UTCTime:return Gc;case K.UniversalString:return Fc;case K.Utf8String:return Nc;case K.VideotexString:return zc;case K.VisibleString:return Hc;default:return null}}function Yc(e){return typeof e==`function`&&e.prototype?e.prototype.toASN&&e.prototype.fromASN?!0:Yc(e.prototype):!!(e&&typeof e==`object`&&`toASN`in e&&`fromASN`in e)}function Xc(e){if(e){let t=Object.getPrototypeOf(e);return t?.prototype?.constructor===Array||Xc(t)}return!1}function Zc(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;let n=new Uint8Array(e),r=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(n[t]!==r[t])return!1;return!0}var Qc=new class{items=new WeakMap;has(e){return this.items.has(e)}get(e,t=!1){let n=this.items.get(e);if(!n)throw Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!n.schema)throw Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){let t=this.get(e);t.schema||=this.create(e,!0)}createDefault(e){let t={type:G.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(t,n),t.items=Object.assign({},t.items,n.items)),t}create(e,t){let n=this.items.get(e)||this.createDefault(e),r=[];for(let e in n.items){let i=n.items[e],a=t?e:``,o;if(typeof i.type==`number`){let e=K[i.type],t=ki[e];if(!t)throw Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:a})}else Yc(i.type)?o=new i.type().toSchema(a):i.optional?this.get(i.type).type===G.Choice?o=new Qo({name:a}):(o=this.create(i.type,!1),o.name=a):o=new Qo({name:a});let s=!!i.optional||i.defaultValue!==void 0;if(i.repeated&&(o.name=``,o=new(i.repeated===`set`?oo:io)({name:``,value:[new es({name:a,value:o})]})),i.context!==null&&i.context!==void 0){if(i.implicit){if(typeof i.type==`number`||Yc(i.type)){let e=i.repeated?Ta:ca;r.push(new e({name:a,optional:s,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);let e=!!i.repeated,t=e?o:this.get(i.type,!0).schema;t=`valueBlock`in t?t.valueBlock.value:t.value,r.push(new Ta({name:e?``:a,optional:s,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}}else r.push(new Ta({optional:s,idBlock:{tagClass:3,tagNumber:i.context},value:[o]}))}else o.optional=s,r.push(o)}switch(n.type){case G.Sequence:return new io({value:r,name:``});case G.Set:return new oo({value:r,name:``});case G.Choice:return new $o({value:r,name:``});default:throw Error(`Unsupported ASN1 type in use`)}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){let t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}},q=e=>t=>{let n;Qc.has(t)?n=Qc.get(t):(n=Qc.createDefault(t),Qc.set(t,n)),Object.assign(n,e)},J=e=>(t,n)=>{let r;Qc.has(t.constructor)?r=Qc.get(t.constructor):(r=Qc.createDefault(t.constructor),Qc.set(t.constructor,r));let i=Object.assign({},e);if(typeof i.type==`number`&&!i.converter){let r=Jc(e.type);if(!r)throw Error(`Cannot get default converter for property '${n}' of ${t.constructor.name}`);i.converter=r}i.raw=e.raw,r.items[n]=i},$c=class extends Error{schemas=[]},el=class{static parse(e,t,n){let r=xa(hs(e),n?.berOptions);if(r.result.error)throw Error(r.result.error);return this.fromASN(r.result,t,n)}static fromASN(e,t,n){try{if(Yc(t))return new t().fromASN(e);let r=Qc.get(t);Qc.cache(t);let i=r.schema,a=this.handleChoiceTypes(e,r,t,i,n);if(a?.result)return a.result;a?.targetSchema&&(i=a.targetSchema);let o=this.handleSequenceTypes(e,r,t,i),s=new t;return Xc(t)?this.handleArrayTypes(e,r,t,n):(this.processSchemaItems(r,o,s,n),s)}catch(e){throw e instanceof $c&&e.schemas.push(t.name),e}}static handleChoiceTypes(e,t,n,r,i){if(e.constructor===Ta&&t.type===G.Choice&&e.idBlock.tagClass===3)for(let r in t.items){let a=t.items[r];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type==`function`&&Qc.has(a.type)){let t=Qc.get(a.type);if(t&&t.type===G.Sequence){let t=new io;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock){t.valueBlock.value=e.valueBlock.value;let o=this.fromASN(t,a.type,i),s=new n;return s[r]=o,{result:s}}}}}else if(e.constructor===Ta&&t.type!==G.Choice){let n=new Ta({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:t.schema.valueBlock.value});for(let n in t.items)delete e[n];return{targetSchema:n}}return null}static handleSequenceTypes(e,t,n,r){if(t.type===G.Sequence){let t=ns({},e,r);if(!t.verified)throw new $c(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}{let t=ns({},e,r);if(!t.verified)throw new $c(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}}static processRepeatedField(e,t,n){let r=e.slice(t);if(r.length===1&&r[0].constructor.name===`Sequence`){let e=r[0];e.valueBlock&&e.valueBlock.value&&Array.isArray(e.valueBlock.value)&&(r=e.valueBlock.value)}if(typeof n.type==`number`){let e=Jc(n.type);if(!e)throw Error(`No converter for ASN.1 type ${n.type}`);return r.filter(e=>e&&e.valueBlock).map(t=>{try{return e.fromASN(t)}catch{return}}).filter(e=>e!==void 0)}return r.filter(e=>e&&e.valueBlock).map(e=>{try{return this.fromASN(e,n.type)}catch{return}}).filter(e=>e!==void 0)}static processPrimitiveField(e,t){let n=Jc(t.type);if(!n)throw Error(`No converter for ASN.1 type ${t.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type==`function`&&Qc.has(e.type)&&Qc.get(e.type).type===G.Choice}static processOptionalChoiceField(e,t){try{return{processed:!0,value:this.fromASN(e,t.type)}}catch(e){if(e instanceof $c&&/Wrong values for Choice type/.test(e.message))return{processed:!1};throw e}}static handleArrayTypes(e,t,n,r){if(!(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);let i=t.itemType;if(typeof i==`number`){let t=Jc(i);if(!t)throw Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,e=>t.fromASN(e))}return n.from(e.valueBlock.value,e=>this.fromASN(e,i,r))}static processSchemaItems(e,t,n,r){for(let i in e.items){let a=t.result[i];if(!a)continue;let o=e.items[i],s=o.type,c;c=typeof s==`number`||Yc(s)?this.processPrimitiveSchemaItem(a,o,s,r):this.processComplexSchemaItem(a,o,s,r),c&&typeof c==`object`&&`value`in c&&`raw`in c?(n[i]=c.value,n[`${i}Raw`]=c.raw):n[i]=c}}static processPrimitiveSchemaItem(e,t,n,r){let i=t.converter??(Yc(n)?new n:null);if(!i)throw Error(`Converter is empty`);return t.repeated?this.processRepeatedPrimitiveItem(e,t,i,r):this.processSinglePrimitiveItem(e,t,n,i,r)}static processRepeatedPrimitiveItem(e,t,n,r){if(t.implicit){let i=new(t.repeated===`sequence`?io:oo);i.valueBlock=e.valueBlock;let a=xa(i.toBER(!1),r?.berOptions);if(a.offset===-1)throw Error(`Cannot parse the child item. ${a.result.error}`);if(!(`value`in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);let o=a.result.valueBlock.value;return Array.from(o,e=>n.fromASN(e))}return Array.from(e,e=>n.fromASN(e))}static processSinglePrimitiveItem(e,t,n,r,i){let a=e;if(t.implicit){let e;if(Yc(n))e=new n().toSchema(``);else{let t=K[n],r=ki[t];if(!r)throw Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=a.valueBlock,a=xa(e.toBER(!1),i?.berOptions).result}return r.fromASN(a)}static processComplexSchemaItem(e,t,n,r){if(t.repeated){if(!Array.isArray(e))throw Error(`Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.`);return Array.from(e,e=>this.fromASN(e,n,r))}{let i=this.handleImplicitTagging(e,t,n);if(this.isOptionalChoiceField(t))try{return this.fromASN(i,n,r)}catch(e){if(e instanceof $c&&/Wrong values for Choice type/.test(e.message))return;throw e}{let a=this.fromASN(i,n,r);return t.raw?{value:a,raw:e.valueBeforeDecodeView}:a}}}static handleImplicitTagging(e,t,n){if(t.implicit&&typeof t.context==`number`){let t=Qc.get(n);if(t.type===G.Sequence){let t=new io;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}else if(t.type===G.Set){let t=new oo;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}}return e}},tl=class e{static serialize(e){return e instanceof ra?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&typeof t==`object`&&Yc(t))return t.toASN();if(!(t&&typeof t==`object`))throw TypeError(`Parameter 1 should be type of Object.`);let n=t.constructor,r=Qc.get(n);Qc.cache(n);let i=[];if(r.itemType){if(!Array.isArray(t))throw TypeError(`Parameter 1 should be type of Array.`);if(typeof r.itemType==`number`){let e=Jc(r.itemType);if(!e)throw Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);i=t.map(t=>e.toASN(t))}else i=t.map(e=>this.toAsnItem({type:r.itemType},`[]`,n,e))}else for(let a in r.items){let o=r.items[a],s=t[a];if(s===void 0||o.defaultValue===s||typeof o.defaultValue==`object`&&typeof s==`object`&&Zc(this.serialize(o.defaultValue),this.serialize(s)))continue;let c=e.toAsnItem(o,a,n,s);if(typeof o.context==`number`){if(o.implicit){if(!o.repeated&&(typeof o.type==`number`||Yc(o.type))){let e={};e.valueHex=c instanceof Aa?hs(c.valueBeforeDecodeView):c.valueBlock.toBER(),i.push(new ca({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},...e}))}else i.push(new Ta({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:c.valueBlock.value}))}else i.push(new Ta({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:[c]}))}else o.repeated?i=i.concat(c):i.push(c)}let a;switch(r.type){case G.Sequence:a=new io({value:i});break;case G.Set:a=new oo({value:i});break;case G.Choice:if(!i[0])throw Error(`Schema '${n.name}' has wrong data. Choice cannot be empty.`);a=i[0]}return a}static toAsnItem(e,t,n,r){let i;if(typeof e.type==`number`){let a=e.converter;if(!a)throw Error(`Property '${t}' doesn't have converter for type ${K[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(r))throw TypeError(`Parameter 'objProp' should be type of Array.`);let t=Array.from(r,e=>a.toASN(e));i=new(e.repeated===`sequence`?io:oo)({value:t})}else i=a.toASN(r)}else if(e.repeated){if(!Array.isArray(r))throw TypeError(`Parameter 'objProp' should be type of Array.`);let t=Array.from(r,e=>this.toASN(e));i=new(e.repeated===`sequence`?io:oo)({value:t})}else i=this.toASN(r);return i}},nl=class extends Array{constructor(e=[]){if(typeof e==`number`)super(e);else{super();for(let t of e)this.push(t)}}},Y=class e{static serialize(e){return tl.serialize(e)}static parse(e,t,n){return el.parse(e,t,n)}static toString(t,n){let r=xa(fs(t)?hs(t):e.serialize(t),n?.berOptions);if(r.offset===-1)throw Error(`Cannot decode ASN.1 data. ${r.result.error}`);return r.result.toString()}};function X(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function rl(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function il(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}var al=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let t=e.split(`.`);if(t.length!==4)throw Error(`Invalid IPv4 address`);return t.map(e=>{let t=parseInt(e,10);if(isNaN(t)||t<0||t>255)throw Error(`Invalid IPv4 address part`);return t})}static parseIPv6(e){let t=this.expandIPv6(e).split(`:`);if(t.length!==8)throw Error(`Invalid IPv6 address`);return t.reduce((e,t)=>{let n=parseInt(t,16);if(isNaN(n)||n<0||n>65535)throw Error(`Invalid IPv6 address part`);return e.push(n>>8&255),e.push(n&255),e},[])}static expandIPv6(e){if(!e.includes(`::`))return e;let t=e.split(`::`);if(t.length>2)throw Error(`Invalid IPv6 address`);let n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-(n.length+r.length);if(i<0)throw Error(`Invalid IPv6 address`);return[...n,...Array(i).fill(`0`),...r].join(`:`)}static formatIPv6(e){let t=[];for(let n=0;n<16;n+=2)t.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(t.join(`:`))}static compressIPv6(e){let t=e.split(`:`),n=-1,r=0,i=-1,a=0;for(let e=0;e<t.length;e++)t[e]===`0`?(i===-1&&(i=e),a++):(a>r&&(n=i,r=a),i=-1,a=0);return a>r&&(n=i,r=a),r>1?`${t.slice(0,n).join(`:`)}::${t.slice(n+r).join(`:`)}`:e}static parseCIDR(e){let[t,n]=e.split(`/`),r=parseInt(n,10);if(this.isIPv4(t)){if(r<0||r>32)throw Error(`Invalid IPv4 prefix length`);return[this.parseIPv4(t),r]}if(r<0||r>128)throw Error(`Invalid IPv6 prefix length`);return[this.parseIPv6(t),r]}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return`::/0`;if(e.length!==16)return e;let t=parseInt(e.slice(8),16).toString(2).split(``).reduce((e,t)=>e+ +t,0),n=e.slice(0,8).replace(/(.{2})/g,e=>`${parseInt(e,16)}.`);return n=n.slice(0,-1),`${n}/${t}`}static toString(e){let t=new Uint8Array(e);if(t.length===4)return Array.from(t).join(`.`);if(t.length===16)return this.formatIPv6(t);if(t.length===8||t.length===32){let e=t.length/2,n=t.slice(0,e),r=t.slice(e);if(t.every(e=>e===0))return t.length===8?`0.0.0.0/0`:`::/0`;let i=r.reduce((e,t)=>e+(t.toString(2).match(/1/g)||[]).length,0);return t.length===8?`${Array.from(n).join(`.`)}/${i}`:`${this.formatIPv6(n)}/${i}`}return this.decodeIP(Ps(e))}static fromString(e){if(e.includes(`/`)){let[t,n]=this.parseCIDR(e),r=new Uint8Array(t.length),i=n;for(let e=0;e<r.length;e++)i>=8?(r[e]=255,i-=8):i>0&&(r[e]=255<<8-i,i=0);let a=new Uint8Array(t.length*2);return a.set(t,0),a.set(r,t.length),a.buffer}let t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}},ol,sl,cl,ll=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||``}};X([J({type:K.TeletexString})],ll.prototype,`teletexString`,void 0),X([J({type:K.PrintableString})],ll.prototype,`printableString`,void 0),X([J({type:K.UniversalString})],ll.prototype,`universalString`,void 0),X([J({type:K.Utf8String})],ll.prototype,`utf8String`,void 0),X([J({type:K.BmpString})],ll.prototype,`bmpString`,void 0),ll=X([q({type:G.Choice})],ll);var ul=class extends ll{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Ps(this.anyValue):super.toString())}};X([J({type:K.IA5String})],ul.prototype,`ia5String`,void 0),X([J({type:K.Any})],ul.prototype,`anyValue`,void 0),ul=X([q({type:G.Choice})],ul);var dl=class{type=``;value=new ul;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],dl.prototype,`type`,void 0),X([J({type:ul})],dl.prototype,`value`,void 0);var fl=ol=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,ol.prototype)}};fl=ol=X([q({type:G.Set,itemType:dl})],fl);var pl=sl=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,sl.prototype)}};pl=sl=X([q({type:G.Sequence,itemType:fl})],pl);var ml=cl=class extends pl{constructor(e){super(e),Object.setPrototypeOf(this,cl.prototype)}};ml=cl=X([q({type:G.Sequence})],ml);var hl={fromASN:e=>al.toString(Ac.fromASN(e)),toASN:e=>Ac.toASN(al.fromString(e))},gl=class{typeId=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],gl.prototype,`typeId`,void 0),X([J({type:K.Any,context:0})],gl.prototype,`value`,void 0);var _l=class{nameAssigner;partyName=new ll;constructor(e={}){Object.assign(this,e)}};X([J({type:ll,optional:!0,context:0,implicit:!0})],_l.prototype,`nameAssigner`,void 0),X([J({type:ll,context:1,implicit:!0})],_l.prototype,`partyName`,void 0);var vl=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};X([J({type:gl,context:0,implicit:!0})],vl.prototype,`otherName`,void 0),X([J({type:K.IA5String,context:1,implicit:!0})],vl.prototype,`rfc822Name`,void 0),X([J({type:K.IA5String,context:2,implicit:!0})],vl.prototype,`dNSName`,void 0),X([J({type:K.Any,context:3,implicit:!0})],vl.prototype,`x400Address`,void 0),X([J({type:ml,context:4,implicit:!1})],vl.prototype,`directoryName`,void 0),X([J({type:_l,context:5})],vl.prototype,`ediPartyName`,void 0),X([J({type:K.IA5String,context:6,implicit:!0})],vl.prototype,`uniformResourceIdentifier`,void 0),X([J({type:K.OctetString,context:7,implicit:!0,converter:hl})],vl.prototype,`iPAddress`,void 0),X([J({type:K.ObjectIdentifier,context:8,implicit:!0})],vl.prototype,`registeredID`,void 0),vl=X([q({type:G.Choice})],vl);var yl=`1.3.6.1.5.5.7`,bl=`${yl}.1`,xl=`${yl}.2`,Sl=`${yl}.3`,Cl=`${yl}.48`;`${xl}`,`${xl}`;var wl=`${Cl}.1`,Tl=`${Cl}.2`,El=`${Cl}.3`,Dl=`${Cl}.5`,Ol=`2.5.29`,kl,Al=`${bl}.1`,jl=class{accessMethod=``;accessLocation=new vl;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],jl.prototype,`accessMethod`,void 0),X([J({type:vl})],jl.prototype,`accessLocation`,void 0);var Ml=kl=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,kl.prototype)}};Ml=kl=X([q({type:G.Sequence,itemType:jl})],Ml);var Nl=`${Ol}.35`,Pl=class extends xc{},Fl=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};X([J({type:Pl,context:0,optional:!0,implicit:!0})],Fl.prototype,`keyIdentifier`,void 0),X([J({type:vl,context:1,optional:!0,implicit:!0,repeated:`sequence`})],Fl.prototype,`authorityCertIssuer`,void 0),X([J({type:K.Integer,context:2,optional:!0,implicit:!0,converter:Tc})],Fl.prototype,`authorityCertSerialNumber`,void 0);var Il=`${Ol}.19`,Ll=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Boolean,defaultValue:!1})],Ll.prototype,`cA`,void 0),X([J({type:K.Integer,optional:!0})],Ll.prototype,`pathLenConstraint`,void 0);var Rl,zl=Rl=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Rl.prototype)}};zl=Rl=X([q({type:G.Sequence,itemType:vl})],zl);var Bl;`${Ol}`;var Vl=Bl=class extends zl{constructor(e){super(e),Object.setPrototypeOf(this,Bl.prototype)}};Vl=Bl=X([q({type:G.Sequence})],Vl);var Hl,Ul=`${Ol}.32`;`${Ul}`;var Wl=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||``}};X([J({type:K.IA5String})],Wl.prototype,`ia5String`,void 0),X([J({type:K.VisibleString})],Wl.prototype,`visibleString`,void 0),X([J({type:K.BmpString})],Wl.prototype,`bmpString`,void 0),X([J({type:K.Utf8String})],Wl.prototype,`utf8String`,void 0),Wl=X([q({type:G.Choice})],Wl);var Gl=class{organization=new Wl;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};X([J({type:Wl})],Gl.prototype,`organization`,void 0),X([J({type:K.Integer,repeated:`sequence`})],Gl.prototype,`noticeNumbers`,void 0);var Kl=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};X([J({type:Gl,optional:!0})],Kl.prototype,`noticeRef`,void 0),X([J({type:Wl,optional:!0})],Kl.prototype,`explicitText`,void 0);var ql=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};X([J({type:K.IA5String})],ql.prototype,`cPSuri`,void 0),X([J({type:Kl})],ql.prototype,`userNotice`,void 0),ql=X([q({type:G.Choice})],ql);var Jl=class{policyQualifierId=``;qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Jl.prototype,`policyQualifierId`,void 0),X([J({type:K.Any})],Jl.prototype,`qualifier`,void 0);var Yl=class{policyIdentifier=``;policyQualifiers;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Yl.prototype,`policyIdentifier`,void 0),X([J({type:Jl,repeated:`sequence`,optional:!0})],Yl.prototype,`policyQualifiers`,void 0);var Xl=Hl=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Hl.prototype)}};Xl=Hl=X([q({type:G.Sequence,itemType:Yl})],Xl),`${Ol}`;var Zl=class{value;constructor(e=0){this.value=e}};X([J({type:K.Integer})],Zl.prototype,`value`,void 0),Zl=X([q({type:G.Choice})],Zl),`${Ol}`;var Ql=class extends Zl{};Ql=X([q({type:G.Choice})],Ql);var $l,eu=`${Ol}.31`,tu;(function(e){e[e.unused=1]=`unused`,e[e.keyCompromise=2]=`keyCompromise`,e[e.cACompromise=4]=`cACompromise`,e[e.affiliationChanged=8]=`affiliationChanged`,e[e.superseded=16]=`superseded`,e[e.cessationOfOperation=32]=`cessationOfOperation`,e[e.certificateHold=64]=`certificateHold`,e[e.privilegeWithdrawn=128]=`privilegeWithdrawn`,e[e.aACompromise=256]=`aACompromise`})(tu||={});var nu=class extends bc{toJSON(){let e=[],t=this.toNumber();return t&tu.aACompromise&&e.push(`aACompromise`),t&tu.affiliationChanged&&e.push(`affiliationChanged`),t&tu.cACompromise&&e.push(`cACompromise`),t&tu.certificateHold&&e.push(`certificateHold`),t&tu.cessationOfOperation&&e.push(`cessationOfOperation`),t&tu.keyCompromise&&e.push(`keyCompromise`),t&tu.privilegeWithdrawn&&e.push(`privilegeWithdrawn`),t&tu.superseded&&e.push(`superseded`),t&tu.unused&&e.push(`unused`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},ru=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:vl,context:0,repeated:`sequence`,implicit:!0})],ru.prototype,`fullName`,void 0),X([J({type:fl,context:1,implicit:!0})],ru.prototype,`nameRelativeToCRLIssuer`,void 0),ru=X([q({type:G.Choice})],ru);var iu=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:ru,context:0,optional:!0})],iu.prototype,`distributionPoint`,void 0),X([J({type:nu,context:1,optional:!0,implicit:!0})],iu.prototype,`reasons`,void 0),X([J({type:vl,context:2,optional:!0,repeated:`sequence`,implicit:!0})],iu.prototype,`cRLIssuer`,void 0);var au=$l=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,$l.prototype)}};au=$l=X([q({type:G.Sequence,itemType:iu})],au);var ou;`${Ol}`;var su=ou=class extends au{constructor(e){super(e),Object.setPrototypeOf(this,ou.prototype)}};su=ou=X([q({type:G.Sequence,itemType:iu})],su),`${Ol}`;var cu=class e{static ONLY=!1;distributionPoint;onlyContainsUserCerts=e.ONLY;onlyContainsCACerts=e.ONLY;onlySomeReasons;indirectCRL=e.ONLY;onlyContainsAttributeCerts=e.ONLY;constructor(e={}){Object.assign(this,e)}};X([J({type:ru,context:0,optional:!0})],cu.prototype,`distributionPoint`,void 0),X([J({type:K.Boolean,context:1,defaultValue:cu.ONLY,implicit:!0})],cu.prototype,`onlyContainsUserCerts`,void 0),X([J({type:K.Boolean,context:2,defaultValue:cu.ONLY,implicit:!0})],cu.prototype,`onlyContainsCACerts`,void 0),X([J({type:nu,context:3,optional:!0,implicit:!0})],cu.prototype,`onlySomeReasons`,void 0),X([J({type:K.Boolean,context:4,defaultValue:cu.ONLY,implicit:!0})],cu.prototype,`indirectCRL`,void 0),X([J({type:K.Boolean,context:5,defaultValue:cu.ONLY,implicit:!0})],cu.prototype,`onlyContainsAttributeCerts`,void 0),`${Ol}`;var lu;(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(lu||={});var uu=class{reason=lu.unspecified;constructor(e=lu.unspecified){this.reason=e}toJSON(){return lu[this.reason]}toString(){return this.toJSON()}};X([J({type:K.Enumerated})],uu.prototype,`reason`,void 0),uu=X([q({type:G.Choice})],uu);var du,fu=`${Ol}.37`,pu=du=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,du.prototype)}};pu=du=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],pu),`${fu}`;var mu=`${Sl}.1`,hu=`${Sl}.2`,gu=`${Sl}.3`,_u=`${Sl}.4`,vu=`${Sl}.8`,yu=`${Sl}.9`;`${Ol}`;var bu=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};X([J({type:K.Integer,converter:Tc})],bu.prototype,`value`,void 0),bu=X([q({type:G.Choice})],bu),`${Ol}`;var xu=class{value=new Date;constructor(e){e&&(this.value=e)}};X([J({type:K.GeneralizedTime})],xu.prototype,`value`,void 0),xu=X([q({type:G.Choice})],xu);var Su,Cu=`${Ol}.18`,wu=Su=class extends zl{constructor(e){super(e),Object.setPrototypeOf(this,Su.prototype)}};wu=Su=X([q({type:G.Sequence})],wu);var Tu=`${Ol}.15`,Eu;(function(e){e[e.digitalSignature=1]=`digitalSignature`,e[e.nonRepudiation=2]=`nonRepudiation`,e[e.keyEncipherment=4]=`keyEncipherment`,e[e.dataEncipherment=8]=`dataEncipherment`,e[e.keyAgreement=16]=`keyAgreement`,e[e.keyCertSign=32]=`keyCertSign`,e[e.cRLSign=64]=`cRLSign`,e[e.encipherOnly=128]=`encipherOnly`,e[e.decipherOnly=256]=`decipherOnly`})(Eu||={});var Du=class extends bc{toJSON(){let e=this.toNumber(),t=[];return e&Eu.cRLSign&&t.push(`crlSign`),e&Eu.dataEncipherment&&t.push(`dataEncipherment`),e&Eu.decipherOnly&&t.push(`decipherOnly`),e&Eu.digitalSignature&&t.push(`digitalSignature`),e&Eu.encipherOnly&&t.push(`encipherOnly`),e&Eu.keyAgreement&&t.push(`keyAgreement`),e&Eu.keyCertSign&&t.push(`keyCertSign`),e&Eu.keyEncipherment&&t.push(`keyEncipherment`),e&Eu.nonRepudiation&&t.push(`nonRepudiation`),t}toString(){return`[${this.toJSON().join(`, `)}]`}},Ou;`${Ol}`;var ku=class{base=new vl;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};X([J({type:vl})],ku.prototype,`base`,void 0),X([J({type:K.Integer,context:0,defaultValue:0,implicit:!0})],ku.prototype,`minimum`,void 0),X([J({type:K.Integer,context:1,optional:!0,implicit:!0})],ku.prototype,`maximum`,void 0);var Au=Ou=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Ou.prototype)}};Au=Ou=X([q({type:G.Sequence,itemType:ku})],Au);var ju=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};X([J({type:Au,context:0,optional:!0,implicit:!0})],ju.prototype,`permittedSubtrees`,void 0),X([J({type:Au,context:1,optional:!0,implicit:!0})],ju.prototype,`excludedSubtrees`,void 0),`${Ol}`;var Mu=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,implicit:!0,optional:!0,converter:Tc})],Mu.prototype,`requireExplicitPolicy`,void 0),X([J({type:K.Integer,context:1,implicit:!0,optional:!0,converter:Tc})],Mu.prototype,`inhibitPolicyMapping`,void 0);var Nu;`${Ol}`;var Pu=class{issuerDomainPolicy=``;subjectDomainPolicy=``;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Pu.prototype,`issuerDomainPolicy`,void 0),X([J({type:K.ObjectIdentifier})],Pu.prototype,`subjectDomainPolicy`,void 0);var Fu=Nu=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Nu.prototype)}};Fu=Nu=X([q({type:G.Sequence,itemType:Pu})],Fu);var Iu,Lu=`${Ol}.17`,Ru=Iu=class extends zl{constructor(e){super(e),Object.setPrototypeOf(this,Iu.prototype)}};Ru=Iu=X([q({type:G.Sequence})],Ru);var zu=class{type=``;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],zu.prototype,`type`,void 0),X([J({type:K.Any,repeated:`set`})],zu.prototype,`values`,void 0);var Bu;`${Ol}`;var Vu=Bu=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Bu.prototype)}};Vu=Bu=X([q({type:G.Sequence,itemType:zu})],Vu);var Hu=`${Ol}.14`,Uu=class extends Pl{};`${Ol}`;var Wu=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime,context:0,implicit:!0,optional:!0})],Wu.prototype,`notBefore`,void 0),X([J({type:K.GeneralizedTime,context:1,implicit:!0,optional:!0})],Wu.prototype,`notAfter`,void 0);var Gu;(function(e){e[e.keyUpdateAllowed=1]=`keyUpdateAllowed`,e[e.newExtensions=2]=`newExtensions`,e[e.pKIXCertificate=4]=`pKIXCertificate`})(Gu||={});var Ku=class extends bc{toJSON(){let e=[],t=this.toNumber();return t&Gu.pKIXCertificate&&e.push(`pKIXCertificate`),t&Gu.newExtensions&&e.push(`newExtensions`),t&Gu.keyUpdateAllowed&&e.push(`keyUpdateAllowed`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},qu=class{entrustVers=``;entrustInfoFlags=new Ku;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralString})],qu.prototype,`entrustVers`,void 0),X([J({type:Ku})],qu.prototype,`entrustInfoFlags`,void 0);var Ju;`${bl}`;var Yu=Ju=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Ju.prototype)}};Yu=Ju=X([q({type:G.Sequence,itemType:jl})],Yu);var Z=class e{algorithm=``;parameters;constructor(e={}){Object.assign(this,e)}isEqual(t){return t instanceof e&&t.algorithm==this.algorithm&&(t.parameters&&this.parameters&&gs(t.parameters,this.parameters)||t.parameters===this.parameters)}};X([J({type:K.ObjectIdentifier})],Z.prototype,`algorithm`,void 0),X([J({type:K.Any,optional:!0})],Z.prototype,`parameters`,void 0);var Xu=class{algorithm=new Z;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Xu.prototype,`algorithm`,void 0),X([J({type:K.BitString})],Xu.prototype,`subjectPublicKey`,void 0);var Zu=class{utcTime;generalTime;constructor(e){if(e){if(typeof e==`string`||typeof e==`number`||e instanceof Date){let t=new Date(e);t.setMilliseconds(0),t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw Error(`Cannot get time from CHOICE object`);return e}};X([J({type:K.UTCTime})],Zu.prototype,`utcTime`,void 0),X([J({type:K.GeneralizedTime})],Zu.prototype,`generalTime`,void 0),Zu=X([q({type:G.Choice})],Zu);var Qu=class{notBefore=new Zu(new Date);notAfter=new Zu(new Date);constructor(e){e&&(this.notBefore=new Zu(e.notBefore),this.notAfter=new Zu(e.notAfter))}};X([J({type:Zu})],Qu.prototype,`notBefore`,void 0),X([J({type:Zu})],Qu.prototype,`notAfter`,void 0);var $u,ed=class e{static CRITICAL=!1;extnID=``;critical=e.CRITICAL;extnValue=new xc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ed.prototype,`extnID`,void 0),X([J({type:K.Boolean,defaultValue:ed.CRITICAL})],ed.prototype,`critical`,void 0),X([J({type:xc})],ed.prototype,`extnValue`,void 0);var td=$u=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,$u.prototype)}};td=$u=X([q({type:G.Sequence,itemType:ed})],td);var nd;(function(e){e[e.v1=0]=`v1`,e[e.v2=1]=`v2`,e[e.v3=2]=`v3`})(nd||={});var rd=class{version=nd.v1;serialNumber=new ArrayBuffer(0);signature=new Z;issuer=new ml;validity=new Qu;subject=new ml;subjectPublicKeyInfo=new Xu;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,defaultValue:nd.v1})],rd.prototype,`version`,void 0),X([J({type:K.Integer,converter:Tc})],rd.prototype,`serialNumber`,void 0),X([J({type:Z})],rd.prototype,`signature`,void 0),X([J({type:ml})],rd.prototype,`issuer`,void 0),X([J({type:Qu})],rd.prototype,`validity`,void 0),X([J({type:ml})],rd.prototype,`subject`,void 0),X([J({type:Xu})],rd.prototype,`subjectPublicKeyInfo`,void 0),X([J({type:K.BitString,context:1,implicit:!0,optional:!0})],rd.prototype,`issuerUniqueID`,void 0),X([J({type:K.BitString,context:2,implicit:!0,optional:!0})],rd.prototype,`subjectUniqueID`,void 0),X([J({type:td,context:3,optional:!0})],rd.prototype,`extensions`,void 0);var id=class{tbsCertificate=new rd;tbsCertificateRaw;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:rd,raw:!0})],id.prototype,`tbsCertificate`,void 0),X([J({type:Z})],id.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],id.prototype,`signatureValue`,void 0);var ad=class{userCertificate=new ArrayBuffer(0);revocationDate=new Zu;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:Tc})],ad.prototype,`userCertificate`,void 0),X([J({type:Zu})],ad.prototype,`revocationDate`,void 0),X([J({type:ed,optional:!0,repeated:`sequence`})],ad.prototype,`crlEntryExtensions`,void 0);var od=class{version;signature=new Z;issuer=new ml;thisUpdate=new Zu;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],od.prototype,`version`,void 0),X([J({type:Z})],od.prototype,`signature`,void 0),X([J({type:ml})],od.prototype,`issuer`,void 0),X([J({type:Zu})],od.prototype,`thisUpdate`,void 0),X([J({type:Zu,optional:!0})],od.prototype,`nextUpdate`,void 0),X([J({type:ad,repeated:`sequence`,optional:!0})],od.prototype,`revokedCertificates`,void 0),X([J({type:ed,optional:!0,context:0,repeated:`sequence`})],od.prototype,`crlExtensions`,void 0);var sd=class{tbsCertList=new od;tbsCertListRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:od,raw:!0})],sd.prototype,`tbsCertList`,void 0),X([J({type:Z})],sd.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],sd.prototype,`signature`,void 0);var cd=class{issuer=new ml;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:ml})],cd.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:Tc})],cd.prototype,`serialNumber`,void 0);var ld=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Uu,context:0,implicit:!0})],ld.prototype,`subjectKeyIdentifier`,void 0),X([J({type:cd})],ld.prototype,`issuerAndSerialNumber`,void 0),ld=X([q({type:G.Choice})],ld);var ud;(function(e){e[e.v0=0]=`v0`,e[e.v1=1]=`v1`,e[e.v2=2]=`v2`,e[e.v3=3]=`v3`,e[e.v4=4]=`v4`,e[e.v5=5]=`v5`})(ud||={});var dd=class extends Z{};dd=X([q({type:G.Sequence})],dd);var fd=class extends Z{};fd=X([q({type:G.Sequence})],fd);var pd=class extends Z{};pd=X([q({type:G.Sequence})],pd);var md=class extends Z{};md=X([q({type:G.Sequence})],md);var hd=class extends Z{};hd=X([q({type:G.Sequence})],hd);var gd=class extends Z{};gd=X([q({type:G.Sequence})],gd);var _d=class{attrType=``;attrValues=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],_d.prototype,`attrType`,void 0),X([J({type:K.Any,repeated:`set`})],_d.prototype,`attrValues`,void 0);var vd,yd=class{version=ud.v0;sid=new ld;digestAlgorithm=new dd;signedAttrs;signedAttrsRaw;signatureAlgorithm=new fd;signature=new xc;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],yd.prototype,`version`,void 0),X([J({type:ld})],yd.prototype,`sid`,void 0),X([J({type:dd})],yd.prototype,`digestAlgorithm`,void 0),X([J({type:_d,repeated:`set`,context:0,implicit:!0,optional:!0,raw:!0})],yd.prototype,`signedAttrs`,void 0),X([J({type:fd})],yd.prototype,`signatureAlgorithm`,void 0),X([J({type:xc})],yd.prototype,`signature`,void 0),X([J({type:_d,repeated:`set`,context:1,implicit:!0,optional:!0})],yd.prototype,`unsignedAttrs`,void 0);var bd=vd=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,vd.prototype)}};bd=vd=X([q({type:G.Set,itemType:yd})],bd);var xd=class extends yd{};xd=X([q({type:G.Sequence})],xd);var Sd=class extends Zu{};Sd=X([q({type:G.Choice})],Sd);var Cd=class{acIssuer=new vl;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};X([J({type:vl})],Cd.prototype,`acIssuer`,void 0),X([J({type:K.Integer})],Cd.prototype,`acSerial`,void 0),X([J({type:zu,repeated:`sequence`})],Cd.prototype,`attrs`,void 0);var wd,Td=wd=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,wd.prototype)}};Td=wd=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],Td);var Ed=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],Ed.prototype,`pathLenConstraint`,void 0),X([J({type:Td,implicit:!0,context:0,optional:!0})],Ed.prototype,`permittedAttrs`,void 0),X([J({type:Td,implicit:!0,context:1,optional:!0})],Ed.prototype,`excludedAttrs`,void 0),X([J({type:K.Boolean,defaultValue:!0})],Ed.prototype,`permitUnSpecified`,void 0);var Dd=class{issuer=new zl;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:zl})],Dd.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:Tc})],Dd.prototype,`serial`,void 0),X([J({type:K.BitString,optional:!0})],Dd.prototype,`issuerUID`,void 0);var Od;(function(e){e[e.publicKey=0]=`publicKey`,e[e.publicKeyCert=1]=`publicKeyCert`,e[e.otherObjectTypes=2]=`otherObjectTypes`})(Od||={});var kd=class{digestedObjectType=Od.publicKey;otherObjectTypeID;digestAlgorithm=new Z;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Enumerated})],kd.prototype,`digestedObjectType`,void 0),X([J({type:K.ObjectIdentifier,optional:!0})],kd.prototype,`otherObjectTypeID`,void 0),X([J({type:Z})],kd.prototype,`digestAlgorithm`,void 0),X([J({type:K.BitString})],kd.prototype,`objectDigest`,void 0);var Ad=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:zl,optional:!0})],Ad.prototype,`issuerName`,void 0),X([J({type:Dd,context:0,implicit:!0,optional:!0})],Ad.prototype,`baseCertificateID`,void 0),X([J({type:kd,context:1,implicit:!0,optional:!0})],Ad.prototype,`objectDigestInfo`,void 0);var jd=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};X([J({type:vl,repeated:`sequence`})],jd.prototype,`v1Form`,void 0),X([J({type:Ad,context:0,implicit:!0})],jd.prototype,`v2Form`,void 0),jd=X([q({type:G.Choice})],jd);var Md=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime})],Md.prototype,`notBeforeTime`,void 0),X([J({type:K.GeneralizedTime})],Md.prototype,`notAfterTime`,void 0);var Nd=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:Dd,implicit:!0,context:0,optional:!0})],Nd.prototype,`baseCertificateID`,void 0),X([J({type:zl,implicit:!0,context:1,optional:!0})],Nd.prototype,`entityName`,void 0),X([J({type:kd,implicit:!0,context:2,optional:!0})],Nd.prototype,`objectDigestInfo`,void 0);var Pd;(function(e){e[e.v2=1]=`v2`})(Pd||={});var Fd=class{version=Pd.v2;holder=new Nd;issuer=new jd;signature=new Z;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Md;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Fd.prototype,`version`,void 0),X([J({type:Nd})],Fd.prototype,`holder`,void 0),X([J({type:jd})],Fd.prototype,`issuer`,void 0),X([J({type:Z})],Fd.prototype,`signature`,void 0),X([J({type:K.Integer,converter:Tc})],Fd.prototype,`serialNumber`,void 0),X([J({type:Md})],Fd.prototype,`attrCertValidityPeriod`,void 0),X([J({type:zu,repeated:`sequence`})],Fd.prototype,`attributes`,void 0),X([J({type:K.BitString,optional:!0})],Fd.prototype,`issuerUniqueID`,void 0),X([J({type:td,optional:!0})],Fd.prototype,`extensions`,void 0);var Id=class{acinfo=new Fd;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Fd})],Id.prototype,`acinfo`,void 0),X([J({type:Z})],Id.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Id.prototype,`signatureValue`,void 0);var Ld;(function(e){e[e.unmarked=1]=`unmarked`,e[e.unclassified=2]=`unclassified`,e[e.restricted=4]=`restricted`,e[e.confidential=8]=`confidential`,e[e.secret=16]=`secret`,e[e.topSecret=32]=`topSecret`})(Ld||={});var Rd=class extends bc{},zd=class{type=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier,implicit:!0,context:0})],zd.prototype,`type`,void 0),X([J({type:K.Any,implicit:!0,context:1})],zd.prototype,`value`,void 0);var Bd=class{policyId=``;classList=new Rd(Ld.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Bd.prototype,`policyId`,void 0),X([J({type:Rd,defaultValue:new Rd(Ld.unclassified)})],Bd.prototype,`classList`,void 0),X([J({type:zd,repeated:`set`})],Bd.prototype,`securityCategories`,void 0);var Vd=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};X([J({type:xc})],Vd.prototype,`cotets`,void 0),X([J({type:K.ObjectIdentifier})],Vd.prototype,`oid`,void 0),X([J({type:K.Utf8String})],Vd.prototype,`string`,void 0);var Hd=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:zl,implicit:!0,context:0,optional:!0})],Hd.prototype,`policyAuthority`,void 0),X([J({type:Vd,repeated:`sequence`})],Hd.prototype,`values`,void 0),`${bl}`,`${bl}`,`${bl}`,`${Ol}`;var Ud=`${yl}.10`;`${Ud}`,`${Ud}`,`${Ud}`,`${Ud}`,`${Ud}`;var Wd=`2.5.4`;`${Wd}`;var Gd,Kd=class{targetCertificate=new Dd;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:Dd})],Kd.prototype,`targetCertificate`,void 0),X([J({type:vl,optional:!0})],Kd.prototype,`targetName`,void 0),X([J({type:kd,optional:!0})],Kd.prototype,`certDigestInfo`,void 0);var qd=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};X([J({type:vl,context:0,implicit:!0})],qd.prototype,`targetName`,void 0),X([J({type:vl,context:1,implicit:!0})],qd.prototype,`targetGroup`,void 0),X([J({type:Kd,context:2,implicit:!0})],qd.prototype,`targetCert`,void 0),qd=X([q({type:G.Choice})],qd);var Jd=Gd=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Gd.prototype)}};Jd=Gd=X([q({type:G.Sequence,itemType:qd})],Jd);var Yd,Xd=Yd=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Yd.prototype)}};Xd=Yd=X([q({type:G.Sequence,itemType:Jd})],Xd);var Zd=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};X([J({type:zl,implicit:!0,context:0,optional:!0})],Zd.prototype,`roleAuthority`,void 0),X([J({type:vl,implicit:!0,context:1})],Zd.prototype,`roleName`,void 0);var Qd=class{service=new vl;ident=new vl;authInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:vl})],Qd.prototype,`service`,void 0),X([J({type:vl})],Qd.prototype,`ident`,void 0),X([J({type:xc,optional:!0})],Qd.prototype,`authInfo`,void 0);var $d,ef=class{otherCertFormat=``;otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ef.prototype,`otherCertFormat`,void 0),X([J({type:K.Any})],ef.prototype,`otherCert`,void 0);var tf=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};X([J({type:id})],tf.prototype,`certificate`,void 0),X([J({type:Id,context:2,implicit:!0})],tf.prototype,`v2AttrCert`,void 0),X([J({type:ef,context:3,implicit:!0})],tf.prototype,`other`,void 0),tf=X([q({type:G.Choice})],tf);var nf=$d=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,$d.prototype)}};nf=$d=X([q({type:G.Set,itemType:tf})],nf);var rf=class{contentType=``;content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],rf.prototype,`contentType`,void 0),X([J({type:K.Any,context:0})],rf.prototype,`content`,void 0);var af=class{single;any;constructor(e={}){Object.assign(this,e)}};X([J({type:xc})],af.prototype,`single`,void 0),X([J({type:K.Any})],af.prototype,`any`,void 0),af=X([q({type:G.Choice})],af);var of=class{eContentType=``;eContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],of.prototype,`eContentType`,void 0),X([J({type:af,context:0,optional:!0})],of.prototype,`eContent`,void 0);var sf=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};X([J({type:xc,context:0,implicit:!0,optional:!0})],sf.prototype,`value`,void 0),X([J({type:xc,converter:jc,context:0,implicit:!0,optional:!0,repeated:`sequence`})],sf.prototype,`constructedValue`,void 0),sf=X([q({type:G.Choice})],sf);var cf=class{contentType=``;contentEncryptionAlgorithm=new md;encryptedContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],cf.prototype,`contentType`,void 0),X([J({type:md})],cf.prototype,`contentEncryptionAlgorithm`,void 0),X([J({type:sf,optional:!0})],cf.prototype,`encryptedContent`,void 0);var lf=class{keyAttrId=``;keyAttr;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],lf.prototype,`keyAttrId`,void 0),X([J({type:K.Any,optional:!0})],lf.prototype,`keyAttr`,void 0);var uf,df=class{subjectKeyIdentifier=new Uu;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:Uu})],df.prototype,`subjectKeyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],df.prototype,`date`,void 0),X([J({type:lf,optional:!0})],df.prototype,`other`,void 0);var ff=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:df,context:0,implicit:!0,optional:!0})],ff.prototype,`rKeyId`,void 0),X([J({type:cd,optional:!0})],ff.prototype,`issuerAndSerialNumber`,void 0),ff=X([q({type:G.Choice})],ff);var pf=class{rid=new ff;encryptedKey=new xc;constructor(e={}){Object.assign(this,e)}};X([J({type:ff})],pf.prototype,`rid`,void 0),X([J({type:xc})],pf.prototype,`encryptedKey`,void 0);var mf=uf=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,uf.prototype)}};mf=uf=X([q({type:G.Sequence,itemType:pf})],mf);var hf=class{algorithm=new Z;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],hf.prototype,`algorithm`,void 0),X([J({type:K.BitString})],hf.prototype,`publicKey`,void 0);var gf=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Uu,context:0,implicit:!0,optional:!0})],gf.prototype,`subjectKeyIdentifier`,void 0),X([J({type:hf,context:1,implicit:!0,optional:!0})],gf.prototype,`originatorKey`,void 0),X([J({type:cd,optional:!0})],gf.prototype,`issuerAndSerialNumber`,void 0),gf=X([q({type:G.Choice})],gf);var _f=class{version=ud.v3;originator=new gf;ukm;keyEncryptionAlgorithm=new pd;recipientEncryptedKeys=new mf;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],_f.prototype,`version`,void 0),X([J({type:gf,context:0})],_f.prototype,`originator`,void 0),X([J({type:xc,context:1,optional:!0})],_f.prototype,`ukm`,void 0),X([J({type:pd})],_f.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:mf})],_f.prototype,`recipientEncryptedKeys`,void 0);var vf=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Uu,context:0,implicit:!0})],vf.prototype,`subjectKeyIdentifier`,void 0),X([J({type:cd})],vf.prototype,`issuerAndSerialNumber`,void 0),vf=X([q({type:G.Choice})],vf);var yf=class{version=ud.v0;rid=new vf;keyEncryptionAlgorithm=new pd;encryptedKey=new xc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],yf.prototype,`version`,void 0),X([J({type:vf})],yf.prototype,`rid`,void 0),X([J({type:pd})],yf.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:xc})],yf.prototype,`encryptedKey`,void 0);var bf=class{keyIdentifier=new xc;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:xc})],bf.prototype,`keyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],bf.prototype,`date`,void 0),X([J({type:lf,optional:!0})],bf.prototype,`other`,void 0);var xf=class{version=ud.v4;kekid=new bf;keyEncryptionAlgorithm=new pd;encryptedKey=new xc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],xf.prototype,`version`,void 0),X([J({type:bf})],xf.prototype,`kekid`,void 0),X([J({type:pd})],xf.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:xc})],xf.prototype,`encryptedKey`,void 0);var Sf=class{version=ud.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new pd;encryptedKey=new xc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Sf.prototype,`version`,void 0),X([J({type:gd,context:0,optional:!0})],Sf.prototype,`keyDerivationAlgorithm`,void 0),X([J({type:pd})],Sf.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:xc})],Sf.prototype,`encryptedKey`,void 0);var Cf=class{oriType=``;oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Cf.prototype,`oriType`,void 0),X([J({type:K.Any})],Cf.prototype,`oriValue`,void 0);var wf=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};X([J({type:yf,optional:!0})],wf.prototype,`ktri`,void 0),X([J({type:_f,context:1,implicit:!0,optional:!0})],wf.prototype,`kari`,void 0),X([J({type:xf,context:2,implicit:!0,optional:!0})],wf.prototype,`kekri`,void 0),X([J({type:Sf,context:3,implicit:!0,optional:!0})],wf.prototype,`pwri`,void 0),X([J({type:Cf,context:4,implicit:!0,optional:!0})],wf.prototype,`ori`,void 0),wf=X([q({type:G.Choice})],wf);var Tf,Ef=Tf=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Tf.prototype)}};Ef=Tf=X([q({type:G.Set,itemType:wf})],Ef);var Df,Of=`${yl}.16`;`${Of}`,`${Of}`;var kf=class{otherRevInfoFormat=``;otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],kf.prototype,`otherRevInfoFormat`,void 0),X([J({type:K.Any})],kf.prototype,`otherRevInfo`,void 0);var Af=class{other=new kf;constructor(e={}){Object.assign(this,e)}};X([J({type:kf,context:1,implicit:!0})],Af.prototype,`other`,void 0),Af=X([q({type:G.Choice})],Af);var jf=Df=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Df.prototype)}};jf=Df=X([q({type:G.Set,itemType:Af})],jf);var Mf=class{certs;crls;constructor(e={}){Object.assign(this,e)}};X([J({type:nf,context:0,implicit:!0,optional:!0})],Mf.prototype,`certs`,void 0),X([J({type:jf,context:1,implicit:!0,optional:!0})],Mf.prototype,`crls`,void 0);var Nf,Pf=Nf=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Nf.prototype)}};Pf=Nf=X([q({type:G.Set,itemType:_d})],Pf);var Ff=class{version=ud.v0;originatorInfo;recipientInfos=new Ef;encryptedContentInfo=new cf;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Ff.prototype,`version`,void 0),X([J({type:Mf,context:0,implicit:!0,optional:!0})],Ff.prototype,`originatorInfo`,void 0),X([J({type:Ef})],Ff.prototype,`recipientInfos`,void 0),X([J({type:cf})],Ff.prototype,`encryptedContentInfo`,void 0),X([J({type:Pf,context:1,implicit:!0,optional:!0})],Ff.prototype,`unprotectedAttrs`,void 0);var If=`1.2.840.113549.1.7.2`,Lf,Rf=Lf=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Lf.prototype)}};Rf=Lf=X([q({type:G.Set,itemType:dd})],Rf);var zf=class{version=ud.v0;digestAlgorithms=new Rf;encapContentInfo=new of;certificates;crls;signerInfos=new bd;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],zf.prototype,`version`,void 0),X([J({type:Rf})],zf.prototype,`digestAlgorithms`,void 0),X([J({type:of})],zf.prototype,`encapContentInfo`,void 0),X([J({type:nf,context:0,implicit:!0,optional:!0})],zf.prototype,`certificates`,void 0),X([J({type:jf,context:1,implicit:!0,optional:!0})],zf.prototype,`crls`,void 0),X([J({type:bd})],zf.prototype,`signerInfos`,void 0);var Bf=`1.2.840.10045.2.1`,Vf=`1.2.840.10045.4.1`,Hf=`1.2.840.10045.4.3.1`,Uf=`1.2.840.10045.4.3.2`,Wf=`1.2.840.10045.4.3.3`,Gf=`1.2.840.10045.4.3.4`,Kf=`1.2.840.10045.3.1.7`,qf=`1.3.132.0.34`,Jf=`1.3.132.0.35`;function Yf(e){return new Z({algorithm:e})}var Xf=Yf(Vf);Yf(Hf);var Zf=Yf(Uf),Qf=Yf(Wf),$f=Yf(Gf),ep=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ep.prototype,`fieldType`,void 0),X([J({type:K.Any})],ep.prototype,`parameters`,void 0),ep=X([q({type:G.Sequence})],ep);var tp=class extends xc{},np=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};X([J({type:K.OctetString})],np.prototype,`a`,void 0),X([J({type:K.OctetString})],np.prototype,`b`,void 0),X([J({type:K.BitString,optional:!0})],np.prototype,`seed`,void 0),np=X([q({type:G.Sequence})],np);var rp;(function(e){e[e.ecpVer1=1]=`ecpVer1`})(rp||={});var ip=class{version=rp.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],ip.prototype,`version`,void 0),X([J({type:ep})],ip.prototype,`fieldID`,void 0),X([J({type:np})],ip.prototype,`curve`,void 0),X([J({type:tp})],ip.prototype,`base`,void 0),X([J({type:K.Integer,converter:Tc})],ip.prototype,`order`,void 0),X([J({type:K.Integer,optional:!0})],ip.prototype,`cofactor`,void 0),ip=X([q({type:G.Sequence})],ip);var ap=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ap.prototype,`namedCurve`,void 0),X([J({type:K.Null})],ap.prototype,`implicitCurve`,void 0),X([J({type:ip})],ap.prototype,`specifiedCurve`,void 0),ap=X([q({type:G.Choice})],ap);var op=class{version=1;privateKey=new xc;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],op.prototype,`version`,void 0),X([J({type:xc})],op.prototype,`privateKey`,void 0),X([J({type:ap,context:0,optional:!0})],op.prototype,`parameters`,void 0),X([J({type:K.BitString,context:1,optional:!0})],op.prototype,`publicKey`,void 0);var sp=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:Tc})],sp.prototype,`r`,void 0),X([J({type:K.Integer,converter:Tc})],sp.prototype,`s`,void 0);var cp=`1.2.840.113549.1.1`,lp=`${cp}.1`,up=`${cp}.7`,dp=`${cp}.9`,fp=`${cp}.10`,pp=`${cp}.2`,mp=`${cp}.4`,hp=`${cp}.5`,gp=`${cp}.14`,_p=`${cp}.11`,vp=`${cp}.12`,yp=`${cp}.13`,bp=`${cp}.15`,xp=`${cp}.16`,Sp=`1.3.14.3.2.26`,Cp=`2.16.840.1.101.3.4.2.4`,wp=`2.16.840.1.101.3.4.2.1`,Tp=`2.16.840.1.101.3.4.2.2`,Ep=`2.16.840.1.101.3.4.2.3`,Dp=`2.16.840.1.101.3.4.2.5`,Op=`2.16.840.1.101.3.4.2.6`,kp=`1.2.840.113549.2.2`,Ap=`1.2.840.113549.2.5`,jp=`${cp}.8`;function Mp(e){return new Z({algorithm:e,parameters:null})}Mp(kp),Mp(Ap);var Np=Mp(Sp);Mp(Cp),Mp(wp),Mp(Tp),Mp(Ep),Mp(Dp),Mp(Op);var Pp=new Z({algorithm:jp,parameters:Y.serialize(Np)}),Fp=new Z({algorithm:dp,parameters:Y.serialize(Ac.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});Mp(lp),Mp(pp),Mp(mp),Mp(hp),Mp(bp),Mp(xp),Mp(vp),Mp(yp),Mp(bp),Mp(xp);var Ip=class{hashAlgorithm=new Z(Np);maskGenAlgorithm=new Z({algorithm:jp,parameters:Y.serialize(Np)});pSourceAlgorithm=new Z(Fp);constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:Np})],Ip.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:Pp})],Ip.prototype,`maskGenAlgorithm`,void 0),X([J({type:Z,context:2,defaultValue:Fp})],Ip.prototype,`pSourceAlgorithm`,void 0),new Z({algorithm:up,parameters:Y.serialize(new Ip)});var Lp=class{hashAlgorithm=new Z(Np);maskGenAlgorithm=new Z({algorithm:jp,parameters:Y.serialize(Np)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:Np})],Lp.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:Pp})],Lp.prototype,`maskGenAlgorithm`,void 0),X([J({type:K.Integer,context:2,defaultValue:20})],Lp.prototype,`saltLength`,void 0),X([J({type:K.Integer,context:3,defaultValue:1})],Lp.prototype,`trailerField`,void 0),new Z({algorithm:fp,parameters:Y.serialize(new Lp)});var Rp=class{digestAlgorithm=new Z;digest=new xc;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Rp.prototype,`digestAlgorithm`,void 0),X([J({type:xc})],Rp.prototype,`digest`,void 0);var zp,Bp=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:Tc})],Bp.prototype,`prime`,void 0),X([J({type:K.Integer,converter:Tc})],Bp.prototype,`exponent`,void 0),X([J({type:K.Integer,converter:Tc})],Bp.prototype,`coefficient`,void 0);var Vp=zp=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,zp.prototype)}};Vp=zp=X([q({type:G.Sequence,itemType:Bp})],Vp);var Hp=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)}};X([J({type:K.Integer})],Hp.prototype,`version`,void 0),X([J({type:K.Integer,converter:Tc})],Hp.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:Tc})],Hp.prototype,`publicExponent`,void 0),X([J({type:K.Integer,converter:Tc})],Hp.prototype,`privateExponent`,void 0),X([J({type:K.Integer,converter:Tc})],Hp.prototype,`prime1`,void 0),X([J({type:K.Integer,converter:Tc})],Hp.prototype,`prime2`,void 0),X([J({type:K.Integer,converter:Tc})],Hp.prototype,`exponent1`,void 0),X([J({type:K.Integer,converter:Tc})],Hp.prototype,`exponent2`,void 0),X([J({type:K.Integer,converter:Tc})],Hp.prototype,`coefficient`,void 0),X([J({type:Vp,optional:!0})],Hp.prototype,`otherPrimeInfos`,void 0);var Up=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:Tc})],Up.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:Tc})],Up.prototype,`publicExponent`,void 0);var Wp;(function(e){e[e.Transient=0]=`Transient`,e[e.Singleton=1]=`Singleton`,e[e.ResolutionScoped=2]=`ResolutionScoped`,e[e.ContainerScoped=3]=`ContainerScoped`})(Wp||={});var Gp=Wp,Kp=function(e,t){return Kp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},Kp(e,t)};function qp(e,t){Kp(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function Jp(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Yp(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o={next:s(0),throw:s(1),return:s(2)};return typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}}function Xp(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Zp(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function Qp(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Zp(arguments[t]));return e}function $p(e){var t=Reflect.getMetadata(`design:paramtypes`,e)||[],n=Reflect.getOwnMetadata(`injectionTokens`,e)||{};return Object.keys(n).forEach(function(e){t[+e]=n[e]}),t}function em(e){return!!e.useClass}function tm(e){return!!e.useFactory}var nm=function(){function e(e){this.wrap=e,this.reflectMethods=[`get`,`getPrototypeOf`,`setPrototypeOf`,`getOwnPropertyDescriptor`,`defineProperty`,`has`,`set`,`deleteProperty`,`apply`,`construct`,`ownKeys`]}return e.prototype.createProxy=function(e){var t=this,n={},r=!1,i;return new Proxy(n,this.createHandler(function(){return r||=(i=e(t.wrap()),!0),i}))},e.prototype.createHandler=function(e){var t={};return this.reflectMethods.forEach(function(n){t[n]=function(){var t=[...arguments];return t[0]=e(),Reflect[n].apply(void 0,Qp(t))}}),t},e}();function rm(e){return typeof e==`string`||typeof e==`symbol`}function im(e){return typeof e==`object`&&`token`in e&&`multiple`in e}function am(e){return typeof e==`object`&&`token`in e&&`transform`in e}function om(e){return typeof e==`function`||e instanceof nm}function sm(e){return!!e.useToken}function cm(e){return e.useValue!=null}function lm(e){return em(e)||cm(e)||sm(e)||tm(e)}var um=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},e.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},e.prototype.setAll=function(e,t){this._registryMap.set(e,t)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}(),dm=function(e){qp(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(um),fm=function(){function e(){this.scopedResolutions=new Map}return e}();function pm(e,t){return e===null?`at position #`+t:`"`+e.split(`,`)[t].trim()+`" at position #`+t}function mm(e,t,n){return n===void 0&&(n=` `),Qp([e],t.message.split(`
|
|
35
|
+
`}function Vh(e,t={}){let n=[],r=t.label,i;for(Ih.lastIndex=0;i=Ih.exec(e);){let e=i[1].trim();if(r&&e!==r)continue;Lh(e);let t=zh(i[2]);n.push({label:e,data:kh.decode(t.base64Text),headers:t.headers,lineLength:t.base64Lines[0]?.length??64,newline:Bh(i[0])})}if(t.strict&&n.length===0)throw TypeError(r?`No PEM block with label '${r}' was found`:`No PEM blocks were found`);return n}function Hh(e,t,n={}){Lh(e);let r=n.lineLength??64;if(!Number.isInteger(r)||r<1)throw RangeError(`PEM lineLength must be a positive integer`);let i=n.newline??`
|
|
36
|
+
`,a=[`-----BEGIN ${e}-----`];if(n.headers){for(let[e,t]of Object.entries(n.headers))a.push(`${e}: ${t}`);a.push(``)}return a.push(...Rh(kh.encode(t),r)),a.push(`-----END ${e}-----`),`${a.join(i)}${i}`}function Uh(e,t={}){return Vh(e,t).map(({lineLength:e,newline:t,...n})=>n)}function Wh(e,t){let[n]=Uh(e,{label:t,strict:!0});return n.data}function Gh(e,t={}){let[n]=Vh(e,{...t,strict:!0}),r={label:n.label,headers:n.headers,lineLength:n.lineLength,newline:n.newline};return{bytes:n.data,format:r,normalized:Hh(n.label,n.data,r)}}function Kh(e,t){return Hh(t.label,e,t)}var qh={name:`pem`,encode:(e,t)=>{if(!t?.label)throw TypeError(`PEM label is required`);return Hh(t.label,e,t)},decode:(e,t)=>Wh(e,t?.label),format:Kh,is:e=>typeof e==`string`&&/-----BEGIN [^-]+-----/.test(e),parse:Gh};function Jh(e){return e.trim().toLowerCase()}function Yh(e){return e instanceof Error?e:Error(String(e))}function Xh(e,t,n){for(let t of[n.name,...n.aliases??[]])e.delete(Jh(t));t.delete(Jh(n.name))}function Zh(e,t,n){let r=e[n];if(typeof r!=`function`)throw Error(`Converter '${t}' does not support ${n}()`);return r}function Qh(e,t,n){let r=Jh(n.name||e),i=t.trim();if(!i)return 0;let a=!1;n.is&&(a=n.is(t));let o=!1;try{n.decode(t),o=!0}catch{o=!1}if(!a&&!o)return 0;switch(r){case`pem`:return+!!/-----BEGIN [^-]+-----/.test(t);case`hex`:{let e=i.replace(/^0x/i,``).replace(/[\s:.-]/g,``);return!e||/[^0-9a-f]/i.test(e)||e.length%2!=0?0:/^0x/i.test(i)||/[:\s.-]/.test(i)?.95:/[a-f]/.test(i)||/[A-F]/.test(i)?.8:.45}case`base64url`:return/[-_]/.test(i)?.95:/=/.test(i)?.1:.6;case`base64`:return/[+/=]/.test(i)?.9:.55;case`binary`:case`utf8`:case`utf16be`:case`utf16le`:return 0;default:return a&&o?.75:.5}}function $h(e=[]){let t=new Map,n=new Set,r={register(e,r={}){if(!e.name||!Jh(e.name))throw TypeError(`Converter name is required`);let i=[...new Set([e.name,...e.aliases??[]].map(Jh))],a=new Set;for(let e of i){let n=t.get(e);if(n){if(!r.override)throw Error(`Converter '${e}' is already registered`);a.add(n)}}for(let e of a)Xh(t,n,e);for(let n of i)t.set(n,e);return n.add(Jh(e.name)),this},unregister(e){let r=t.get(Jh(e));return r?(Xh(t,n,r),!0):!1},has(e){return t.has(Jh(e))},get(e){let n=t.get(Jh(e));if(!n)throw Error(`Converter '${e}' is not registered`);return n},list(){return[...n].map(e=>this.get(e))},encode(e,t,n){return this.get(e).encode(t,n)},decode(e,t,n){return this.get(e).decode(t,n)},tryDecode(e,t,n){try{return{ok:!0,bytes:this.decode(e,t,n)}}catch(e){return{ok:!1,error:Yh(e)}}},normalize(e,t,n){let r=this.get(e);return Zh(r,e,`normalize`).call(r,t,n)},parse(e,t,n){let r=this.get(e);return Zh(r,e,`parse`).call(r,t,n)},format(e,t,n){let r=this.get(e);return Zh(r,e,`format`).call(r,t,n)},transcode(e,t){let n=this.decode(t.from,e,t.fromOptions);return this.encode(t.to,n,t.toOptions)},detect(e,t={}){let n=t.formats?.length?t.formats.map(e=>String(e)):this.list().map(e=>e.name).filter(e=>![`binary`,`utf8`,`utf16be`,`utf16le`].includes(Jh(e))),r=new Map;for(let t of n){let n=this.get(t),i=Qh(t,e,n);if(i<=0)continue;let a=n.name,o=r.get(a);(!o||i>o.confidence)&&r.set(a,{format:a,confidence:i})}return[...r.values()].sort((e,t)=>t.confidence-e.confidence)}};for(let t of e)r.register(t);return r}$h([{name:`binary`,aliases:[`latin1`],encode:Zm,decode:Qm,is:$m},{name:`hex`,encode:mh,decode:hh,format:_h,is:ph,normalize:fh,parse:gh},{name:`base64`,aliases:[`b64`],encode:Dh,decode:Oh,is:Eh,normalize:wh},{name:`base64url`,aliases:[`base64-url`,`b64url`],encode:Nh,decode:Ph,is:Mh,normalize:jh},{name:`utf8`,aliases:[`utf-8`],encode:e=>yh(e),decode:e=>vh(e),is:e=>typeof e==`string`},{name:`utf16be`,aliases:[`utf16`,`utf-16`,`utf-16be`],encode:e=>xh(e),decode:e=>bh(e),is:e=>typeof e==`string`},{name:`utf16le`,aliases:[`utf-16le`,`ucs2`,`usc2`],encode:e=>xh(e,{littleEndian:!0}),decode:e=>bh(e,{littleEndian:!0}),is:e=>typeof e==`string`},qh]);var G;(function(e){e[e.Sequence=0]=`Sequence`,e[e.Set=1]=`Set`,e[e.Choice=2]=`Choice`})(G||={});var K;(function(e){e[e.Any=1]=`Any`,e[e.Boolean=2]=`Boolean`,e[e.OctetString=3]=`OctetString`,e[e.BitString=4]=`BitString`,e[e.Integer=5]=`Integer`,e[e.Enumerated=6]=`Enumerated`,e[e.ObjectIdentifier=7]=`ObjectIdentifier`,e[e.Utf8String=8]=`Utf8String`,e[e.BmpString=9]=`BmpString`,e[e.UniversalString=10]=`UniversalString`,e[e.NumericString=11]=`NumericString`,e[e.PrintableString=12]=`PrintableString`,e[e.TeletexString=13]=`TeletexString`,e[e.VideotexString=14]=`VideotexString`,e[e.IA5String=15]=`IA5String`,e[e.GraphicString=16]=`GraphicString`,e[e.VisibleString=17]=`VisibleString`,e[e.GeneralString=18]=`GeneralString`,e[e.CharacterString=19]=`CharacterString`,e[e.UTCTime=20]=`UTCTime`,e[e.GeneralizedTime=21]=`GeneralizedTime`,e[e.DATE=22]=`DATE`,e[e.TimeOfDay=23]=`TimeOfDay`,e[e.DateTime=24]=`DateTime`,e[e.Duration=25]=`Duration`,e[e.TIME=26]=`TIME`,e[e.Null=27]=`Null`,e[e.RelativeObjectIdentifier=28]=`RelativeObjectIdentifier`})(K||={});var eg=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e){if(typeof e==`number`)this.fromNumber(e);else if(Km(e))this.unusedBits=t,this.value=Ym(e);else throw TypeError(`Unsupported type of 'params' argument for BitString`)}}fromASN(e){if(!(e instanceof bp))throw TypeError(`Argument 'asn' is not instance of ASN.1 BitString`);return this.unusedBits=e.valueBlock.unusedBits,this.value=Ym(e.valueBlock.valueHex),this}toASN(){return new bp({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new bp({name:e})}toNumber(){let e=``,t=new Uint8Array(this.value);for(let n of t)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 t=e.toString(2),n=t.length+7>>3;this.unusedBits=(n<<3)-t.length;let r=new Uint8Array(n);t=t.padStart(n<<3,`0`).split(``).reverse().join(``);let i=0;for(;i<n;)r[i]=parseInt(t.slice(i<<3,(i<<3)+8),2),i++;this.value=r.buffer}},tg=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){this.buffer=typeof e==`number`?new ArrayBuffer(e):Km(e)?Ym(e):Array.isArray(e)?new Uint8Array(e).buffer:new ArrayBuffer(0)}fromASN(e){if(!(e instanceof _p))throw TypeError(`Argument 'asn' is not instance of ASN.1 OctetString`);return this.buffer=Ym(e.valueBlock.valueHex),this}toASN(){return new _p({valueHex:this.buffer})}toSchema(e){return new _p({name:e})}},ng={fromASN:e=>e instanceof dp?null:Ym(e.valueBeforeDecodeView),toASN:e=>{if(e===null)return new dp;let t=np(e);if(t.result.error)throw Error(t.result.error);return t.result}},rg={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Dp({value:+e})},ig={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new kp({value:e})},ag={fromASN:e=>Ym(e.valueBlock.valueHexView),toASN:e=>new Dp({valueHex:e})},og={fromASN:e=>Ym(e.valueBlock.valueHexView),toASN:e=>new bp({valueHex:e})},sg={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Np({value:e})},cg={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Lp({value:e})},lg={fromASN:e=>e.valueBlock.value,toASN:e=>new mp({value:e})},ug={fromASN:e=>Ym(e.valueBlock.valueHexView),toASN:e=>new _p({valueHex:e})},dg={fromASN:e=>new tg(e.getValue()),toASN:e=>e.toASN()};function fg(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var pg=fg(qp),mg=fg(Xp),hg=fg($p),gg=fg(tm),_g=fg(rm),vg=fg(am),yg=fg(sm),bg=fg(lm),xg=fg(dm),Sg=fg(pm),Cg=fg(hm),wg=fg(_m),Tg={fromASN:e=>e.toDate(),toASN:e=>new ym({valueDate:e})},Eg={fromASN:e=>e.toDate(),toASN:e=>new xm({valueDate:e})},Dg={fromASN:()=>null,toASN:()=>new dp};function Og(e){switch(e){case K.Any:return ng;case K.BitString:return og;case K.BmpString:return mg;case K.Boolean:return lg;case K.CharacterString:return wg;case K.Enumerated:return ig;case K.GeneralString:return Cg;case K.GeneralizedTime:return Eg;case K.GraphicString:return xg;case K.IA5String:return bg;case K.Integer:return rg;case K.Null:return Dg;case K.NumericString:return gg;case K.ObjectIdentifier:return sg;case K.RelativeObjectIdentifier:return cg;case K.OctetString:return ug;case K.PrintableString:return _g;case K.TeletexString:return vg;case K.UTCTime:return Tg;case K.UniversalString:return hg;case K.Utf8String:return pg;case K.VideotexString:return yg;case K.VisibleString:return Sg;default:return null}}function kg(e){return typeof e==`function`&&e.prototype?e.prototype.toASN&&e.prototype.fromASN?!0:kg(e.prototype):!!(e&&typeof e==`object`&&`toASN`in e&&`fromASN`in e)}function Ag(e){if(e){let t=Object.getPrototypeOf(e);return t?.prototype?.constructor===Array||Ag(t)}return!1}function jg(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;let n=new Uint8Array(e),r=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(n[t]!==r[t])return!1;return!0}var Mg=new class{items=new WeakMap;has(e){return this.items.has(e)}get(e,t=!1){let n=this.items.get(e);if(!n)throw Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!n.schema)throw Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){let t=this.get(e);t.schema||=this.create(e,!0)}createDefault(e){let t={type:G.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(t,n),t.items=Object.assign({},t.items,n.items)),t}create(e,t){let n=this.items.get(e)||this.createDefault(e),r=[];for(let e in n.items){let i=n.items[e],a=t?e:``,o;if(typeof i.type==`number`){let e=K[i.type],t=uf[e];if(!t)throw Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:a})}else kg(i.type)?o=new i.type().toSchema(a):i.optional?this.get(i.type).type===G.Choice?o=new Mm({name:a}):(o=this.create(i.type,!1),o.name=a):o=new Mm({name:a});let s=!!i.optional||i.defaultValue!==void 0;if(i.repeated&&(o.name=``,o=new(i.repeated===`set`?Vp:zp)({name:``,value:[new Pm({name:a,value:o})]})),i.context!==null&&i.context!==void 0){if(i.implicit){if(typeof i.type==`number`||kg(i.type)){let e=i.repeated?op:Uf;r.push(new e({name:a,optional:s,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);let e=!!i.repeated,t=e?o:this.get(i.type,!0).schema;t=`valueBlock`in t?t.valueBlock.value:t.value,r.push(new op({name:e?``:a,optional:s,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}}else r.push(new op({optional:s,idBlock:{tagClass:3,tagNumber:i.context},value:[o]}))}else o.optional=s,r.push(o)}switch(n.type){case G.Sequence:return new zp({value:r,name:``});case G.Set:return new Vp({value:r,name:``});case G.Choice:return new Nm({value:r,name:``});default:throw Error(`Unsupported ASN1 type in use`)}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){let t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}},q=e=>t=>{let n;Mg.has(t)?n=Mg.get(t):(n=Mg.createDefault(t),Mg.set(t,n)),Object.assign(n,e)},J=e=>(t,n)=>{let r;Mg.has(t.constructor)?r=Mg.get(t.constructor):(r=Mg.createDefault(t.constructor),Mg.set(t.constructor,r));let i=Object.assign({},e);if(typeof i.type==`number`&&!i.converter){let r=Og(e.type);if(!r)throw Error(`Cannot get default converter for property '${n}' of ${t.constructor.name}`);i.converter=r}i.raw=e.raw,r.items[n]=i},Ng=class extends Error{schemas=[]},Pg=class{static parse(e,t,n){let r=np(Ym(e),n?.berOptions);if(r.result.error)throw Error(r.result.error);return this.fromASN(r.result,t,n)}static fromASN(e,t,n){try{if(kg(t))return new t().fromASN(e);let r=Mg.get(t);Mg.cache(t);let i=r.schema,a=this.handleChoiceTypes(e,r,t,i,n);if(a?.result)return a.result;a?.targetSchema&&(i=a.targetSchema);let o=this.handleSequenceTypes(e,r,t,i),s=new t;return Ag(t)?this.handleArrayTypes(e,r,t,n):(this.processSchemaItems(r,o,s,n),s)}catch(e){throw e instanceof Ng&&e.schemas.push(t.name),e}}static handleChoiceTypes(e,t,n,r,i){if(e.constructor===op&&t.type===G.Choice&&e.idBlock.tagClass===3)for(let r in t.items){let a=t.items[r];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type==`function`&&Mg.has(a.type)){let t=Mg.get(a.type);if(t&&t.type===G.Sequence){let t=new zp;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock){t.valueBlock.value=e.valueBlock.value;let o=this.fromASN(t,a.type,i),s=new n;return s[r]=o,{result:s}}}}}else if(e.constructor===op&&t.type!==G.Choice){let n=new op({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:t.schema.valueBlock.value});for(let n in t.items)delete e[n];return{targetSchema:n}}return null}static handleSequenceTypes(e,t,n,r){if(t.type===G.Sequence){let t=Im({},e,r);if(!t.verified)throw new Ng(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}{let t=Im({},e,r);if(!t.verified)throw new Ng(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}}static processRepeatedField(e,t,n){let r=e.slice(t);if(r.length===1&&r[0].constructor.name===`Sequence`){let e=r[0];e.valueBlock&&e.valueBlock.value&&Array.isArray(e.valueBlock.value)&&(r=e.valueBlock.value)}if(typeof n.type==`number`){let e=Og(n.type);if(!e)throw Error(`No converter for ASN.1 type ${n.type}`);return r.filter(e=>e&&e.valueBlock).map(t=>{try{return e.fromASN(t)}catch{return}}).filter(e=>e!==void 0)}return r.filter(e=>e&&e.valueBlock).map(e=>{try{return this.fromASN(e,n.type)}catch{return}}).filter(e=>e!==void 0)}static processPrimitiveField(e,t){let n=Og(t.type);if(!n)throw Error(`No converter for ASN.1 type ${t.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type==`function`&&Mg.has(e.type)&&Mg.get(e.type).type===G.Choice}static processOptionalChoiceField(e,t){try{return{processed:!0,value:this.fromASN(e,t.type)}}catch(e){if(e instanceof Ng&&/Wrong values for Choice type/.test(e.message))return{processed:!1};throw e}}static handleArrayTypes(e,t,n,r){if(!(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);let i=t.itemType;if(typeof i==`number`){let t=Og(i);if(!t)throw Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,e=>t.fromASN(e))}return n.from(e.valueBlock.value,e=>this.fromASN(e,i,r))}static processSchemaItems(e,t,n,r){for(let i in e.items){let a=t.result[i];if(!a)continue;let o=e.items[i],s=o.type,c;c=typeof s==`number`||kg(s)?this.processPrimitiveSchemaItem(a,o,s,r):this.processComplexSchemaItem(a,o,s,r),c&&typeof c==`object`&&`value`in c&&`raw`in c?(n[i]=c.value,n[`${i}Raw`]=c.raw):n[i]=c}}static processPrimitiveSchemaItem(e,t,n,r){let i=t.converter??(kg(n)?new n:null);if(!i)throw Error(`Converter is empty`);return t.repeated?this.processRepeatedPrimitiveItem(e,t,i,r):this.processSinglePrimitiveItem(e,t,n,i,r)}static processRepeatedPrimitiveItem(e,t,n,r){if(t.implicit){let i=new(t.repeated===`sequence`?zp:Vp);i.valueBlock=e.valueBlock;let a=np(i.toBER(!1),r?.berOptions);if(a.offset===-1)throw Error(`Cannot parse the child item. ${a.result.error}`);if(!(`value`in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);let o=a.result.valueBlock.value;return Array.from(o,e=>n.fromASN(e))}return Array.from(e,e=>n.fromASN(e))}static processSinglePrimitiveItem(e,t,n,r,i){let a=e;if(t.implicit){let e;if(kg(n))e=new n().toSchema(``);else{let t=K[n],r=uf[t];if(!r)throw Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=a.valueBlock,a=np(e.toBER(!1),i?.berOptions).result}return r.fromASN(a)}static processComplexSchemaItem(e,t,n,r){if(t.repeated){if(!Array.isArray(e))throw Error(`Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.`);return Array.from(e,e=>this.fromASN(e,n,r))}{let i=this.handleImplicitTagging(e,t,n);if(this.isOptionalChoiceField(t))try{return this.fromASN(i,n,r)}catch(e){if(e instanceof Ng&&/Wrong values for Choice type/.test(e.message))return;throw e}{let a=this.fromASN(i,n,r);return t.raw?{value:a,raw:e.valueBeforeDecodeView}:a}}}static handleImplicitTagging(e,t,n){if(t.implicit&&typeof t.context==`number`){let t=Mg.get(n);if(t.type===G.Sequence){let t=new zp;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}else if(t.type===G.Set){let t=new Vp;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}}return e}},Fg=class e{static serialize(e){return e instanceof Rf?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&typeof t==`object`&&kg(t))return t.toASN();if(!(t&&typeof t==`object`))throw TypeError(`Parameter 1 should be type of Object.`);let n=t.constructor,r=Mg.get(n);Mg.cache(n);let i=[];if(r.itemType){if(!Array.isArray(t))throw TypeError(`Parameter 1 should be type of Array.`);if(typeof r.itemType==`number`){let e=Og(r.itemType);if(!e)throw Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);i=t.map(t=>e.toASN(t))}else i=t.map(e=>this.toAsnItem({type:r.itemType},`[]`,n,e))}else for(let a in r.items){let o=r.items[a],s=t[a];if(s===void 0||o.defaultValue===s||typeof o.defaultValue==`object`&&typeof s==`object`&&jg(this.serialize(o.defaultValue),this.serialize(s)))continue;let c=e.toAsnItem(o,a,n,s);if(typeof o.context==`number`){if(o.implicit){if(!o.repeated&&(typeof o.type==`number`||kg(o.type))){let e={};e.valueHex=c instanceof dp?Ym(c.valueBeforeDecodeView):c.valueBlock.toBER(),i.push(new Uf({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},...e}))}else i.push(new op({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:c.valueBlock.value}))}else i.push(new op({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:[c]}))}else o.repeated?i=i.concat(c):i.push(c)}let a;switch(r.type){case G.Sequence:a=new zp({value:i});break;case G.Set:a=new Vp({value:i});break;case G.Choice:if(!i[0])throw Error(`Schema '${n.name}' has wrong data. Choice cannot be empty.`);a=i[0]}return a}static toAsnItem(e,t,n,r){let i;if(typeof e.type==`number`){let a=e.converter;if(!a)throw Error(`Property '${t}' doesn't have converter for type ${K[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(r))throw TypeError(`Parameter 'objProp' should be type of Array.`);let t=Array.from(r,e=>a.toASN(e));i=new(e.repeated===`sequence`?zp:Vp)({value:t})}else i=a.toASN(r)}else if(e.repeated){if(!Array.isArray(r))throw TypeError(`Parameter 'objProp' should be type of Array.`);let t=Array.from(r,e=>this.toASN(e));i=new(e.repeated===`sequence`?zp:Vp)({value:t})}else i=this.toASN(r);return i}},Ig=class extends Array{constructor(e=[]){if(typeof e==`number`)super(e);else{super();for(let t of e)this.push(t)}}},Y=class e{static serialize(e){return Fg.serialize(e)}static parse(e,t,n){return Pg.parse(e,t,n)}static toString(t,n){let r=np(Km(t)?Ym(t):e.serialize(t),n?.berOptions);if(r.offset===-1)throw Error(`Cannot decode ASN.1 data. ${r.result.error}`);return r.result.toString()}};function X(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function Lg(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function Rg(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}var zg=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let t=e.split(`.`);if(t.length!==4)throw Error(`Invalid IPv4 address`);return t.map(e=>{let t=parseInt(e,10);if(isNaN(t)||t<0||t>255)throw Error(`Invalid IPv4 address part`);return t})}static parseIPv6(e){let t=this.expandIPv6(e).split(`:`);if(t.length!==8)throw Error(`Invalid IPv6 address`);return t.reduce((e,t)=>{let n=parseInt(t,16);if(isNaN(n)||n<0||n>65535)throw Error(`Invalid IPv6 address part`);return e.push(n>>8&255),e.push(n&255),e},[])}static expandIPv6(e){if(!e.includes(`::`))return e;let t=e.split(`::`);if(t.length>2)throw Error(`Invalid IPv6 address`);let n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-(n.length+r.length);if(i<0)throw Error(`Invalid IPv6 address`);return[...n,...Array(i).fill(`0`),...r].join(`:`)}static formatIPv6(e){let t=[];for(let n=0;n<16;n+=2)t.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(t.join(`:`))}static compressIPv6(e){let t=e.split(`:`),n=-1,r=0,i=-1,a=0;for(let e=0;e<t.length;e++)t[e]===`0`?(i===-1&&(i=e),a++):(a>r&&(n=i,r=a),i=-1,a=0);return a>r&&(n=i,r=a),r>1?`${t.slice(0,n).join(`:`)}::${t.slice(n+r).join(`:`)}`:e}static parseCIDR(e){let[t,n]=e.split(`/`),r=parseInt(n,10);if(this.isIPv4(t)){if(r<0||r>32)throw Error(`Invalid IPv4 prefix length`);return[this.parseIPv4(t),r]}if(r<0||r>128)throw Error(`Invalid IPv6 prefix length`);return[this.parseIPv6(t),r]}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return`::/0`;if(e.length!==16)return e;let t=parseInt(e.slice(8),16).toString(2).split(``).reduce((e,t)=>e+ +t,0),n=e.slice(0,8).replace(/(.{2})/g,e=>`${parseInt(e,16)}.`);return n=n.slice(0,-1),`${n}/${t}`}static toString(e){let t=new Uint8Array(e);if(t.length===4)return Array.from(t).join(`.`);if(t.length===16)return this.formatIPv6(t);if(t.length===8||t.length===32){let e=t.length/2,n=t.slice(0,e),r=t.slice(e);if(t.every(e=>e===0))return t.length===8?`0.0.0.0/0`:`::/0`;let i=r.reduce((e,t)=>e+(t.toString(2).match(/1/g)||[]).length,0);return t.length===8?`${Array.from(n).join(`.`)}/${i}`:`${this.formatIPv6(n)}/${i}`}return this.decodeIP(mh(e))}static fromString(e){if(e.includes(`/`)){let[t,n]=this.parseCIDR(e),r=new Uint8Array(t.length),i=n;for(let e=0;e<r.length;e++)i>=8?(r[e]=255,i-=8):i>0&&(r[e]=255<<8-i,i=0);let a=new Uint8Array(t.length*2);return a.set(t,0),a.set(r,t.length),a.buffer}let t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}},Bg,Vg,Hg,Ug=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||``}};X([J({type:K.TeletexString})],Ug.prototype,`teletexString`,void 0),X([J({type:K.PrintableString})],Ug.prototype,`printableString`,void 0),X([J({type:K.UniversalString})],Ug.prototype,`universalString`,void 0),X([J({type:K.Utf8String})],Ug.prototype,`utf8String`,void 0),X([J({type:K.BmpString})],Ug.prototype,`bmpString`,void 0),Ug=X([q({type:G.Choice})],Ug);var Wg=class extends Ug{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?mh(this.anyValue):super.toString())}};X([J({type:K.IA5String})],Wg.prototype,`ia5String`,void 0),X([J({type:K.Any})],Wg.prototype,`anyValue`,void 0),Wg=X([q({type:G.Choice})],Wg);var Gg=class{type=``;value=new Wg;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Gg.prototype,`type`,void 0),X([J({type:Wg})],Gg.prototype,`value`,void 0);var Kg=Bg=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,Bg.prototype)}};Kg=Bg=X([q({type:G.Set,itemType:Gg})],Kg);var qg=Vg=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,Vg.prototype)}};qg=Vg=X([q({type:G.Sequence,itemType:Kg})],qg);var Jg=Hg=class extends qg{constructor(e){super(e),Object.setPrototypeOf(this,Hg.prototype)}};Jg=Hg=X([q({type:G.Sequence})],Jg);var Yg={fromASN:e=>zg.toString(ug.fromASN(e)),toASN:e=>ug.toASN(zg.fromString(e))},Xg=class{typeId=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Xg.prototype,`typeId`,void 0),X([J({type:K.Any,context:0})],Xg.prototype,`value`,void 0);var Zg=class{nameAssigner;partyName=new Ug;constructor(e={}){Object.assign(this,e)}};X([J({type:Ug,optional:!0,context:0,implicit:!0})],Zg.prototype,`nameAssigner`,void 0),X([J({type:Ug,context:1,implicit:!0})],Zg.prototype,`partyName`,void 0);var Qg=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};X([J({type:Xg,context:0,implicit:!0})],Qg.prototype,`otherName`,void 0),X([J({type:K.IA5String,context:1,implicit:!0})],Qg.prototype,`rfc822Name`,void 0),X([J({type:K.IA5String,context:2,implicit:!0})],Qg.prototype,`dNSName`,void 0),X([J({type:K.Any,context:3,implicit:!0})],Qg.prototype,`x400Address`,void 0),X([J({type:Jg,context:4,implicit:!1})],Qg.prototype,`directoryName`,void 0),X([J({type:Zg,context:5})],Qg.prototype,`ediPartyName`,void 0),X([J({type:K.IA5String,context:6,implicit:!0})],Qg.prototype,`uniformResourceIdentifier`,void 0),X([J({type:K.OctetString,context:7,implicit:!0,converter:Yg})],Qg.prototype,`iPAddress`,void 0),X([J({type:K.ObjectIdentifier,context:8,implicit:!0})],Qg.prototype,`registeredID`,void 0),Qg=X([q({type:G.Choice})],Qg);var $g=`1.3.6.1.5.5.7`,e_=`${$g}.1`,t_=`${$g}.2`,n_=`${$g}.3`,r_=`${$g}.48`;`${t_}`,`${t_}`;var i_=`${r_}.1`,a_=`${r_}.2`,o_=`${r_}.3`,s_=`${r_}.5`,c_=`2.5.29`,l_,u_=`${e_}.1`,d_=class{accessMethod=``;accessLocation=new Qg;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],d_.prototype,`accessMethod`,void 0),X([J({type:Qg})],d_.prototype,`accessLocation`,void 0);var f_=l_=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,l_.prototype)}};f_=l_=X([q({type:G.Sequence,itemType:d_})],f_);var p_=`${c_}.35`,m_=class extends tg{},h_=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};X([J({type:m_,context:0,optional:!0,implicit:!0})],h_.prototype,`keyIdentifier`,void 0),X([J({type:Qg,context:1,optional:!0,implicit:!0,repeated:`sequence`})],h_.prototype,`authorityCertIssuer`,void 0),X([J({type:K.Integer,context:2,optional:!0,implicit:!0,converter:ag})],h_.prototype,`authorityCertSerialNumber`,void 0);var g_=`${c_}.19`,__=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Boolean,defaultValue:!1})],__.prototype,`cA`,void 0),X([J({type:K.Integer,optional:!0})],__.prototype,`pathLenConstraint`,void 0);var v_,y_=v_=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,v_.prototype)}};y_=v_=X([q({type:G.Sequence,itemType:Qg})],y_);var b_;`${c_}`;var x_=b_=class extends y_{constructor(e){super(e),Object.setPrototypeOf(this,b_.prototype)}};x_=b_=X([q({type:G.Sequence})],x_);var S_,C_=`${c_}.32`;`${C_}`;var w_=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||``}};X([J({type:K.IA5String})],w_.prototype,`ia5String`,void 0),X([J({type:K.VisibleString})],w_.prototype,`visibleString`,void 0),X([J({type:K.BmpString})],w_.prototype,`bmpString`,void 0),X([J({type:K.Utf8String})],w_.prototype,`utf8String`,void 0),w_=X([q({type:G.Choice})],w_);var T_=class{organization=new w_;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};X([J({type:w_})],T_.prototype,`organization`,void 0),X([J({type:K.Integer,repeated:`sequence`})],T_.prototype,`noticeNumbers`,void 0);var E_=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};X([J({type:T_,optional:!0})],E_.prototype,`noticeRef`,void 0),X([J({type:w_,optional:!0})],E_.prototype,`explicitText`,void 0);var D_=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};X([J({type:K.IA5String})],D_.prototype,`cPSuri`,void 0),X([J({type:E_})],D_.prototype,`userNotice`,void 0),D_=X([q({type:G.Choice})],D_);var O_=class{policyQualifierId=``;qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],O_.prototype,`policyQualifierId`,void 0),X([J({type:K.Any})],O_.prototype,`qualifier`,void 0);var k_=class{policyIdentifier=``;policyQualifiers;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],k_.prototype,`policyIdentifier`,void 0),X([J({type:O_,repeated:`sequence`,optional:!0})],k_.prototype,`policyQualifiers`,void 0);var A_=S_=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,S_.prototype)}};A_=S_=X([q({type:G.Sequence,itemType:k_})],A_),`${c_}`;var j_=class{value;constructor(e=0){this.value=e}};X([J({type:K.Integer})],j_.prototype,`value`,void 0),j_=X([q({type:G.Choice})],j_),`${c_}`;var M_=class extends j_{};M_=X([q({type:G.Choice})],M_);var N_,P_=`${c_}.31`,F_;(function(e){e[e.unused=1]=`unused`,e[e.keyCompromise=2]=`keyCompromise`,e[e.cACompromise=4]=`cACompromise`,e[e.affiliationChanged=8]=`affiliationChanged`,e[e.superseded=16]=`superseded`,e[e.cessationOfOperation=32]=`cessationOfOperation`,e[e.certificateHold=64]=`certificateHold`,e[e.privilegeWithdrawn=128]=`privilegeWithdrawn`,e[e.aACompromise=256]=`aACompromise`})(F_||={});var I_=class extends eg{toJSON(){let e=[],t=this.toNumber();return t&F_.aACompromise&&e.push(`aACompromise`),t&F_.affiliationChanged&&e.push(`affiliationChanged`),t&F_.cACompromise&&e.push(`cACompromise`),t&F_.certificateHold&&e.push(`certificateHold`),t&F_.cessationOfOperation&&e.push(`cessationOfOperation`),t&F_.keyCompromise&&e.push(`keyCompromise`),t&F_.privilegeWithdrawn&&e.push(`privilegeWithdrawn`),t&F_.superseded&&e.push(`superseded`),t&F_.unused&&e.push(`unused`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},L_=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:Qg,context:0,repeated:`sequence`,implicit:!0})],L_.prototype,`fullName`,void 0),X([J({type:Kg,context:1,implicit:!0})],L_.prototype,`nameRelativeToCRLIssuer`,void 0),L_=X([q({type:G.Choice})],L_);var R_=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:L_,context:0,optional:!0})],R_.prototype,`distributionPoint`,void 0),X([J({type:I_,context:1,optional:!0,implicit:!0})],R_.prototype,`reasons`,void 0),X([J({type:Qg,context:2,optional:!0,repeated:`sequence`,implicit:!0})],R_.prototype,`cRLIssuer`,void 0);var z_=N_=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,N_.prototype)}};z_=N_=X([q({type:G.Sequence,itemType:R_})],z_);var B_;`${c_}`;var V_=B_=class extends z_{constructor(e){super(e),Object.setPrototypeOf(this,B_.prototype)}};V_=B_=X([q({type:G.Sequence,itemType:R_})],V_),`${c_}`;var H_=class e{static ONLY=!1;distributionPoint;onlyContainsUserCerts=e.ONLY;onlyContainsCACerts=e.ONLY;onlySomeReasons;indirectCRL=e.ONLY;onlyContainsAttributeCerts=e.ONLY;constructor(e={}){Object.assign(this,e)}};X([J({type:L_,context:0,optional:!0})],H_.prototype,`distributionPoint`,void 0),X([J({type:K.Boolean,context:1,defaultValue:H_.ONLY,implicit:!0})],H_.prototype,`onlyContainsUserCerts`,void 0),X([J({type:K.Boolean,context:2,defaultValue:H_.ONLY,implicit:!0})],H_.prototype,`onlyContainsCACerts`,void 0),X([J({type:I_,context:3,optional:!0,implicit:!0})],H_.prototype,`onlySomeReasons`,void 0),X([J({type:K.Boolean,context:4,defaultValue:H_.ONLY,implicit:!0})],H_.prototype,`indirectCRL`,void 0),X([J({type:K.Boolean,context:5,defaultValue:H_.ONLY,implicit:!0})],H_.prototype,`onlyContainsAttributeCerts`,void 0),`${c_}`;var U_;(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(U_||={});var W_=class{reason=U_.unspecified;constructor(e=U_.unspecified){this.reason=e}toJSON(){return U_[this.reason]}toString(){return this.toJSON()}};X([J({type:K.Enumerated})],W_.prototype,`reason`,void 0),W_=X([q({type:G.Choice})],W_);var G_,K_=`${c_}.37`,q_=G_=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,G_.prototype)}};q_=G_=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],q_),`${K_}`;var J_=`${n_}.1`,Y_=`${n_}.2`,X_=`${n_}.3`,Z_=`${n_}.4`,Q_=`${n_}.8`,$_=`${n_}.9`;`${c_}`;var ev=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};X([J({type:K.Integer,converter:ag})],ev.prototype,`value`,void 0),ev=X([q({type:G.Choice})],ev),`${c_}`;var tv=class{value=new Date;constructor(e){e&&(this.value=e)}};X([J({type:K.GeneralizedTime})],tv.prototype,`value`,void 0),tv=X([q({type:G.Choice})],tv);var nv,rv=`${c_}.18`,iv=nv=class extends y_{constructor(e){super(e),Object.setPrototypeOf(this,nv.prototype)}};iv=nv=X([q({type:G.Sequence})],iv);var av=`${c_}.15`,ov;(function(e){e[e.digitalSignature=1]=`digitalSignature`,e[e.nonRepudiation=2]=`nonRepudiation`,e[e.keyEncipherment=4]=`keyEncipherment`,e[e.dataEncipherment=8]=`dataEncipherment`,e[e.keyAgreement=16]=`keyAgreement`,e[e.keyCertSign=32]=`keyCertSign`,e[e.cRLSign=64]=`cRLSign`,e[e.encipherOnly=128]=`encipherOnly`,e[e.decipherOnly=256]=`decipherOnly`})(ov||={});var sv=class extends eg{toJSON(){let e=this.toNumber(),t=[];return e&ov.cRLSign&&t.push(`crlSign`),e&ov.dataEncipherment&&t.push(`dataEncipherment`),e&ov.decipherOnly&&t.push(`decipherOnly`),e&ov.digitalSignature&&t.push(`digitalSignature`),e&ov.encipherOnly&&t.push(`encipherOnly`),e&ov.keyAgreement&&t.push(`keyAgreement`),e&ov.keyCertSign&&t.push(`keyCertSign`),e&ov.keyEncipherment&&t.push(`keyEncipherment`),e&ov.nonRepudiation&&t.push(`nonRepudiation`),t}toString(){return`[${this.toJSON().join(`, `)}]`}},cv;`${c_}`;var lv=class{base=new Qg;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};X([J({type:Qg})],lv.prototype,`base`,void 0),X([J({type:K.Integer,context:0,defaultValue:0,implicit:!0})],lv.prototype,`minimum`,void 0),X([J({type:K.Integer,context:1,optional:!0,implicit:!0})],lv.prototype,`maximum`,void 0);var uv=cv=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,cv.prototype)}};uv=cv=X([q({type:G.Sequence,itemType:lv})],uv);var dv=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};X([J({type:uv,context:0,optional:!0,implicit:!0})],dv.prototype,`permittedSubtrees`,void 0),X([J({type:uv,context:1,optional:!0,implicit:!0})],dv.prototype,`excludedSubtrees`,void 0),`${c_}`;var fv=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,implicit:!0,optional:!0,converter:ag})],fv.prototype,`requireExplicitPolicy`,void 0),X([J({type:K.Integer,context:1,implicit:!0,optional:!0,converter:ag})],fv.prototype,`inhibitPolicyMapping`,void 0);var pv;`${c_}`;var mv=class{issuerDomainPolicy=``;subjectDomainPolicy=``;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],mv.prototype,`issuerDomainPolicy`,void 0),X([J({type:K.ObjectIdentifier})],mv.prototype,`subjectDomainPolicy`,void 0);var hv=pv=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,pv.prototype)}};hv=pv=X([q({type:G.Sequence,itemType:mv})],hv);var gv,_v=`${c_}.17`,vv=gv=class extends y_{constructor(e){super(e),Object.setPrototypeOf(this,gv.prototype)}};vv=gv=X([q({type:G.Sequence})],vv);var yv=class{type=``;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],yv.prototype,`type`,void 0),X([J({type:K.Any,repeated:`set`})],yv.prototype,`values`,void 0);var bv;`${c_}`;var xv=bv=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,bv.prototype)}};xv=bv=X([q({type:G.Sequence,itemType:yv})],xv);var Sv=`${c_}.14`,Cv=class extends m_{};`${c_}`;var wv=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime,context:0,implicit:!0,optional:!0})],wv.prototype,`notBefore`,void 0),X([J({type:K.GeneralizedTime,context:1,implicit:!0,optional:!0})],wv.prototype,`notAfter`,void 0);var Tv;(function(e){e[e.keyUpdateAllowed=1]=`keyUpdateAllowed`,e[e.newExtensions=2]=`newExtensions`,e[e.pKIXCertificate=4]=`pKIXCertificate`})(Tv||={});var Ev=class extends eg{toJSON(){let e=[],t=this.toNumber();return t&Tv.pKIXCertificate&&e.push(`pKIXCertificate`),t&Tv.newExtensions&&e.push(`newExtensions`),t&Tv.keyUpdateAllowed&&e.push(`keyUpdateAllowed`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},Dv=class{entrustVers=``;entrustInfoFlags=new Ev;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralString})],Dv.prototype,`entrustVers`,void 0),X([J({type:Ev})],Dv.prototype,`entrustInfoFlags`,void 0);var Ov;`${e_}`;var kv=Ov=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,Ov.prototype)}};kv=Ov=X([q({type:G.Sequence,itemType:d_})],kv);var Z=class e{algorithm=``;parameters;constructor(e={}){Object.assign(this,e)}isEqual(t){return t instanceof e&&t.algorithm==this.algorithm&&(t.parameters&&this.parameters&&Xm(t.parameters,this.parameters)||t.parameters===this.parameters)}};X([J({type:K.ObjectIdentifier})],Z.prototype,`algorithm`,void 0),X([J({type:K.Any,optional:!0})],Z.prototype,`parameters`,void 0);var Av=class{algorithm=new Z;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Av.prototype,`algorithm`,void 0),X([J({type:K.BitString})],Av.prototype,`subjectPublicKey`,void 0);var jv=class{utcTime;generalTime;constructor(e){if(e){if(typeof e==`string`||typeof e==`number`||e instanceof Date){let t=new Date(e);t.setMilliseconds(0),t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw Error(`Cannot get time from CHOICE object`);return e}};X([J({type:K.UTCTime})],jv.prototype,`utcTime`,void 0),X([J({type:K.GeneralizedTime})],jv.prototype,`generalTime`,void 0),jv=X([q({type:G.Choice})],jv);var Mv=class{notBefore=new jv(new Date);notAfter=new jv(new Date);constructor(e){e&&(this.notBefore=new jv(e.notBefore),this.notAfter=new jv(e.notAfter))}};X([J({type:jv})],Mv.prototype,`notBefore`,void 0),X([J({type:jv})],Mv.prototype,`notAfter`,void 0);var Nv,Pv=class e{static CRITICAL=!1;extnID=``;critical=e.CRITICAL;extnValue=new tg;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Pv.prototype,`extnID`,void 0),X([J({type:K.Boolean,defaultValue:Pv.CRITICAL})],Pv.prototype,`critical`,void 0),X([J({type:tg})],Pv.prototype,`extnValue`,void 0);var Fv=Nv=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,Nv.prototype)}};Fv=Nv=X([q({type:G.Sequence,itemType:Pv})],Fv);var Iv;(function(e){e[e.v1=0]=`v1`,e[e.v2=1]=`v2`,e[e.v3=2]=`v3`})(Iv||={});var Lv=class{version=Iv.v1;serialNumber=new ArrayBuffer(0);signature=new Z;issuer=new Jg;validity=new Mv;subject=new Jg;subjectPublicKeyInfo=new Av;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,defaultValue:Iv.v1})],Lv.prototype,`version`,void 0),X([J({type:K.Integer,converter:ag})],Lv.prototype,`serialNumber`,void 0),X([J({type:Z})],Lv.prototype,`signature`,void 0),X([J({type:Jg})],Lv.prototype,`issuer`,void 0),X([J({type:Mv})],Lv.prototype,`validity`,void 0),X([J({type:Jg})],Lv.prototype,`subject`,void 0),X([J({type:Av})],Lv.prototype,`subjectPublicKeyInfo`,void 0),X([J({type:K.BitString,context:1,implicit:!0,optional:!0})],Lv.prototype,`issuerUniqueID`,void 0),X([J({type:K.BitString,context:2,implicit:!0,optional:!0})],Lv.prototype,`subjectUniqueID`,void 0),X([J({type:Fv,context:3,optional:!0})],Lv.prototype,`extensions`,void 0);var Rv=class{tbsCertificate=new Lv;tbsCertificateRaw;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Lv,raw:!0})],Rv.prototype,`tbsCertificate`,void 0),X([J({type:Z})],Rv.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Rv.prototype,`signatureValue`,void 0);var zv=class{userCertificate=new ArrayBuffer(0);revocationDate=new jv;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:ag})],zv.prototype,`userCertificate`,void 0),X([J({type:jv})],zv.prototype,`revocationDate`,void 0),X([J({type:Pv,optional:!0,repeated:`sequence`})],zv.prototype,`crlEntryExtensions`,void 0);var Bv=class{version;signature=new Z;issuer=new Jg;thisUpdate=new jv;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],Bv.prototype,`version`,void 0),X([J({type:Z})],Bv.prototype,`signature`,void 0),X([J({type:Jg})],Bv.prototype,`issuer`,void 0),X([J({type:jv})],Bv.prototype,`thisUpdate`,void 0),X([J({type:jv,optional:!0})],Bv.prototype,`nextUpdate`,void 0),X([J({type:zv,repeated:`sequence`,optional:!0})],Bv.prototype,`revokedCertificates`,void 0),X([J({type:Pv,optional:!0,context:0,repeated:`sequence`})],Bv.prototype,`crlExtensions`,void 0);var Vv=class{tbsCertList=new Bv;tbsCertListRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Bv,raw:!0})],Vv.prototype,`tbsCertList`,void 0),X([J({type:Z})],Vv.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Vv.prototype,`signature`,void 0);var Hv=class{issuer=new Jg;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Jg})],Hv.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:ag})],Hv.prototype,`serialNumber`,void 0);var Uv=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Cv,context:0,implicit:!0})],Uv.prototype,`subjectKeyIdentifier`,void 0),X([J({type:Hv})],Uv.prototype,`issuerAndSerialNumber`,void 0),Uv=X([q({type:G.Choice})],Uv);var Wv;(function(e){e[e.v0=0]=`v0`,e[e.v1=1]=`v1`,e[e.v2=2]=`v2`,e[e.v3=3]=`v3`,e[e.v4=4]=`v4`,e[e.v5=5]=`v5`})(Wv||={});var Gv=class extends Z{};Gv=X([q({type:G.Sequence})],Gv);var Kv=class extends Z{};Kv=X([q({type:G.Sequence})],Kv);var qv=class extends Z{};qv=X([q({type:G.Sequence})],qv);var Jv=class extends Z{};Jv=X([q({type:G.Sequence})],Jv);var Yv=class extends Z{};Yv=X([q({type:G.Sequence})],Yv);var Xv=class extends Z{};Xv=X([q({type:G.Sequence})],Xv);var Zv=class{attrType=``;attrValues=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Zv.prototype,`attrType`,void 0),X([J({type:K.Any,repeated:`set`})],Zv.prototype,`attrValues`,void 0);var Qv,$v=class{version=Wv.v0;sid=new Uv;digestAlgorithm=new Gv;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Kv;signature=new tg;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],$v.prototype,`version`,void 0),X([J({type:Uv})],$v.prototype,`sid`,void 0),X([J({type:Gv})],$v.prototype,`digestAlgorithm`,void 0),X([J({type:Zv,repeated:`set`,context:0,implicit:!0,optional:!0,raw:!0})],$v.prototype,`signedAttrs`,void 0),X([J({type:Kv})],$v.prototype,`signatureAlgorithm`,void 0),X([J({type:tg})],$v.prototype,`signature`,void 0),X([J({type:Zv,repeated:`set`,context:1,implicit:!0,optional:!0})],$v.prototype,`unsignedAttrs`,void 0);var ey=Qv=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,Qv.prototype)}};ey=Qv=X([q({type:G.Set,itemType:$v})],ey);var ty=class extends $v{};ty=X([q({type:G.Sequence})],ty);var ny=class extends jv{};ny=X([q({type:G.Choice})],ny);var ry=class{acIssuer=new Qg;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};X([J({type:Qg})],ry.prototype,`acIssuer`,void 0),X([J({type:K.Integer})],ry.prototype,`acSerial`,void 0),X([J({type:yv,repeated:`sequence`})],ry.prototype,`attrs`,void 0);var iy,ay=iy=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,iy.prototype)}};ay=iy=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],ay);var oy=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],oy.prototype,`pathLenConstraint`,void 0),X([J({type:ay,implicit:!0,context:0,optional:!0})],oy.prototype,`permittedAttrs`,void 0),X([J({type:ay,implicit:!0,context:1,optional:!0})],oy.prototype,`excludedAttrs`,void 0),X([J({type:K.Boolean,defaultValue:!0})],oy.prototype,`permitUnSpecified`,void 0);var sy=class{issuer=new y_;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:y_})],sy.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:ag})],sy.prototype,`serial`,void 0),X([J({type:K.BitString,optional:!0})],sy.prototype,`issuerUID`,void 0);var cy;(function(e){e[e.publicKey=0]=`publicKey`,e[e.publicKeyCert=1]=`publicKeyCert`,e[e.otherObjectTypes=2]=`otherObjectTypes`})(cy||={});var ly=class{digestedObjectType=cy.publicKey;otherObjectTypeID;digestAlgorithm=new Z;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Enumerated})],ly.prototype,`digestedObjectType`,void 0),X([J({type:K.ObjectIdentifier,optional:!0})],ly.prototype,`otherObjectTypeID`,void 0),X([J({type:Z})],ly.prototype,`digestAlgorithm`,void 0),X([J({type:K.BitString})],ly.prototype,`objectDigest`,void 0);var uy=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:y_,optional:!0})],uy.prototype,`issuerName`,void 0),X([J({type:sy,context:0,implicit:!0,optional:!0})],uy.prototype,`baseCertificateID`,void 0),X([J({type:ly,context:1,implicit:!0,optional:!0})],uy.prototype,`objectDigestInfo`,void 0);var dy=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};X([J({type:Qg,repeated:`sequence`})],dy.prototype,`v1Form`,void 0),X([J({type:uy,context:0,implicit:!0})],dy.prototype,`v2Form`,void 0),dy=X([q({type:G.Choice})],dy);var fy=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime})],fy.prototype,`notBeforeTime`,void 0),X([J({type:K.GeneralizedTime})],fy.prototype,`notAfterTime`,void 0);var py=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:sy,implicit:!0,context:0,optional:!0})],py.prototype,`baseCertificateID`,void 0),X([J({type:y_,implicit:!0,context:1,optional:!0})],py.prototype,`entityName`,void 0),X([J({type:ly,implicit:!0,context:2,optional:!0})],py.prototype,`objectDigestInfo`,void 0);var my;(function(e){e[e.v2=1]=`v2`})(my||={});var hy=class{version=my.v2;holder=new py;issuer=new dy;signature=new Z;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new fy;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],hy.prototype,`version`,void 0),X([J({type:py})],hy.prototype,`holder`,void 0),X([J({type:dy})],hy.prototype,`issuer`,void 0),X([J({type:Z})],hy.prototype,`signature`,void 0),X([J({type:K.Integer,converter:ag})],hy.prototype,`serialNumber`,void 0),X([J({type:fy})],hy.prototype,`attrCertValidityPeriod`,void 0),X([J({type:yv,repeated:`sequence`})],hy.prototype,`attributes`,void 0),X([J({type:K.BitString,optional:!0})],hy.prototype,`issuerUniqueID`,void 0),X([J({type:Fv,optional:!0})],hy.prototype,`extensions`,void 0);var gy=class{acinfo=new hy;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:hy})],gy.prototype,`acinfo`,void 0),X([J({type:Z})],gy.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],gy.prototype,`signatureValue`,void 0);var _y;(function(e){e[e.unmarked=1]=`unmarked`,e[e.unclassified=2]=`unclassified`,e[e.restricted=4]=`restricted`,e[e.confidential=8]=`confidential`,e[e.secret=16]=`secret`,e[e.topSecret=32]=`topSecret`})(_y||={});var vy=class extends eg{},yy=class{type=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier,implicit:!0,context:0})],yy.prototype,`type`,void 0),X([J({type:K.Any,implicit:!0,context:1})],yy.prototype,`value`,void 0);var by=class{policyId=``;classList=new vy(_y.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],by.prototype,`policyId`,void 0),X([J({type:vy,defaultValue:new vy(_y.unclassified)})],by.prototype,`classList`,void 0),X([J({type:yy,repeated:`set`})],by.prototype,`securityCategories`,void 0);var xy=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};X([J({type:tg})],xy.prototype,`cotets`,void 0),X([J({type:K.ObjectIdentifier})],xy.prototype,`oid`,void 0),X([J({type:K.Utf8String})],xy.prototype,`string`,void 0);var Sy=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:y_,implicit:!0,context:0,optional:!0})],Sy.prototype,`policyAuthority`,void 0),X([J({type:xy,repeated:`sequence`})],Sy.prototype,`values`,void 0),`${e_}`,`${e_}`,`${e_}`,`${c_}`;var Cy=`${$g}.10`;`${Cy}`,`${Cy}`,`${Cy}`,`${Cy}`,`${Cy}`;var wy=`2.5.4`;`${wy}`;var Ty,Ey=class{targetCertificate=new sy;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:sy})],Ey.prototype,`targetCertificate`,void 0),X([J({type:Qg,optional:!0})],Ey.prototype,`targetName`,void 0),X([J({type:ly,optional:!0})],Ey.prototype,`certDigestInfo`,void 0);var Dy=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};X([J({type:Qg,context:0,implicit:!0})],Dy.prototype,`targetName`,void 0),X([J({type:Qg,context:1,implicit:!0})],Dy.prototype,`targetGroup`,void 0),X([J({type:Ey,context:2,implicit:!0})],Dy.prototype,`targetCert`,void 0),Dy=X([q({type:G.Choice})],Dy);var Oy=Ty=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,Ty.prototype)}};Oy=Ty=X([q({type:G.Sequence,itemType:Dy})],Oy);var ky,Ay=ky=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,ky.prototype)}};Ay=ky=X([q({type:G.Sequence,itemType:Oy})],Ay);var jy=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};X([J({type:y_,implicit:!0,context:0,optional:!0})],jy.prototype,`roleAuthority`,void 0),X([J({type:Qg,implicit:!0,context:1})],jy.prototype,`roleName`,void 0);var My=class{service=new Qg;ident=new Qg;authInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:Qg})],My.prototype,`service`,void 0),X([J({type:Qg})],My.prototype,`ident`,void 0),X([J({type:tg,optional:!0})],My.prototype,`authInfo`,void 0);var Ny,Py=class{otherCertFormat=``;otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Py.prototype,`otherCertFormat`,void 0),X([J({type:K.Any})],Py.prototype,`otherCert`,void 0);var Fy=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};X([J({type:Rv})],Fy.prototype,`certificate`,void 0),X([J({type:gy,context:2,implicit:!0})],Fy.prototype,`v2AttrCert`,void 0),X([J({type:Py,context:3,implicit:!0})],Fy.prototype,`other`,void 0),Fy=X([q({type:G.Choice})],Fy);var Iy=Ny=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,Ny.prototype)}};Iy=Ny=X([q({type:G.Set,itemType:Fy})],Iy);var Ly=class{contentType=``;content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Ly.prototype,`contentType`,void 0),X([J({type:K.Any,context:0})],Ly.prototype,`content`,void 0);var Ry=class{single;any;constructor(e={}){Object.assign(this,e)}};X([J({type:tg})],Ry.prototype,`single`,void 0),X([J({type:K.Any})],Ry.prototype,`any`,void 0),Ry=X([q({type:G.Choice})],Ry);var zy=class{eContentType=``;eContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],zy.prototype,`eContentType`,void 0),X([J({type:Ry,context:0,optional:!0})],zy.prototype,`eContent`,void 0);var By=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};X([J({type:tg,context:0,implicit:!0,optional:!0})],By.prototype,`value`,void 0),X([J({type:tg,converter:dg,context:0,implicit:!0,optional:!0,repeated:`sequence`})],By.prototype,`constructedValue`,void 0),By=X([q({type:G.Choice})],By);var Vy=class{contentType=``;contentEncryptionAlgorithm=new Jv;encryptedContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Vy.prototype,`contentType`,void 0),X([J({type:Jv})],Vy.prototype,`contentEncryptionAlgorithm`,void 0),X([J({type:By,optional:!0})],Vy.prototype,`encryptedContent`,void 0);var Hy=class{keyAttrId=``;keyAttr;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Hy.prototype,`keyAttrId`,void 0),X([J({type:K.Any,optional:!0})],Hy.prototype,`keyAttr`,void 0);var Uy,Wy=class{subjectKeyIdentifier=new Cv;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:Cv})],Wy.prototype,`subjectKeyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],Wy.prototype,`date`,void 0),X([J({type:Hy,optional:!0})],Wy.prototype,`other`,void 0);var Gy=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Wy,context:0,implicit:!0,optional:!0})],Gy.prototype,`rKeyId`,void 0),X([J({type:Hv,optional:!0})],Gy.prototype,`issuerAndSerialNumber`,void 0),Gy=X([q({type:G.Choice})],Gy);var Ky=class{rid=new Gy;encryptedKey=new tg;constructor(e={}){Object.assign(this,e)}};X([J({type:Gy})],Ky.prototype,`rid`,void 0),X([J({type:tg})],Ky.prototype,`encryptedKey`,void 0);var qy=Uy=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,Uy.prototype)}};qy=Uy=X([q({type:G.Sequence,itemType:Ky})],qy);var Jy=class{algorithm=new Z;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Jy.prototype,`algorithm`,void 0),X([J({type:K.BitString})],Jy.prototype,`publicKey`,void 0);var Yy=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Cv,context:0,implicit:!0,optional:!0})],Yy.prototype,`subjectKeyIdentifier`,void 0),X([J({type:Jy,context:1,implicit:!0,optional:!0})],Yy.prototype,`originatorKey`,void 0),X([J({type:Hv,optional:!0})],Yy.prototype,`issuerAndSerialNumber`,void 0),Yy=X([q({type:G.Choice})],Yy);var Xy=class{version=Wv.v3;originator=new Yy;ukm;keyEncryptionAlgorithm=new qv;recipientEncryptedKeys=new qy;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Xy.prototype,`version`,void 0),X([J({type:Yy,context:0})],Xy.prototype,`originator`,void 0),X([J({type:tg,context:1,optional:!0})],Xy.prototype,`ukm`,void 0),X([J({type:qv})],Xy.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:qy})],Xy.prototype,`recipientEncryptedKeys`,void 0);var Zy=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Cv,context:0,implicit:!0})],Zy.prototype,`subjectKeyIdentifier`,void 0),X([J({type:Hv})],Zy.prototype,`issuerAndSerialNumber`,void 0),Zy=X([q({type:G.Choice})],Zy);var Qy=class{version=Wv.v0;rid=new Zy;keyEncryptionAlgorithm=new qv;encryptedKey=new tg;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Qy.prototype,`version`,void 0),X([J({type:Zy})],Qy.prototype,`rid`,void 0),X([J({type:qv})],Qy.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:tg})],Qy.prototype,`encryptedKey`,void 0);var $y=class{keyIdentifier=new tg;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:tg})],$y.prototype,`keyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],$y.prototype,`date`,void 0),X([J({type:Hy,optional:!0})],$y.prototype,`other`,void 0);var eb=class{version=Wv.v4;kekid=new $y;keyEncryptionAlgorithm=new qv;encryptedKey=new tg;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],eb.prototype,`version`,void 0),X([J({type:$y})],eb.prototype,`kekid`,void 0),X([J({type:qv})],eb.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:tg})],eb.prototype,`encryptedKey`,void 0);var tb=class{version=Wv.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new qv;encryptedKey=new tg;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],tb.prototype,`version`,void 0),X([J({type:Xv,context:0,optional:!0})],tb.prototype,`keyDerivationAlgorithm`,void 0),X([J({type:qv})],tb.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:tg})],tb.prototype,`encryptedKey`,void 0);var nb=class{oriType=``;oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],nb.prototype,`oriType`,void 0),X([J({type:K.Any})],nb.prototype,`oriValue`,void 0);var rb=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};X([J({type:Qy,optional:!0})],rb.prototype,`ktri`,void 0),X([J({type:Xy,context:1,implicit:!0,optional:!0})],rb.prototype,`kari`,void 0),X([J({type:eb,context:2,implicit:!0,optional:!0})],rb.prototype,`kekri`,void 0),X([J({type:tb,context:3,implicit:!0,optional:!0})],rb.prototype,`pwri`,void 0),X([J({type:nb,context:4,implicit:!0,optional:!0})],rb.prototype,`ori`,void 0),rb=X([q({type:G.Choice})],rb);var ib,ab=ib=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,ib.prototype)}};ab=ib=X([q({type:G.Set,itemType:rb})],ab);var ob,sb=`${$g}.16`;`${sb}`,`${sb}`;var cb=class{otherRevInfoFormat=``;otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],cb.prototype,`otherRevInfoFormat`,void 0),X([J({type:K.Any})],cb.prototype,`otherRevInfo`,void 0);var lb=class{other=new cb;constructor(e={}){Object.assign(this,e)}};X([J({type:cb,context:1,implicit:!0})],lb.prototype,`other`,void 0),lb=X([q({type:G.Choice})],lb);var ub=ob=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,ob.prototype)}};ub=ob=X([q({type:G.Set,itemType:lb})],ub);var db=class{certs;crls;constructor(e={}){Object.assign(this,e)}};X([J({type:Iy,context:0,implicit:!0,optional:!0})],db.prototype,`certs`,void 0),X([J({type:ub,context:1,implicit:!0,optional:!0})],db.prototype,`crls`,void 0);var fb,pb=fb=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,fb.prototype)}};pb=fb=X([q({type:G.Set,itemType:Zv})],pb);var mb=class{version=Wv.v0;originatorInfo;recipientInfos=new ab;encryptedContentInfo=new Vy;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],mb.prototype,`version`,void 0),X([J({type:db,context:0,implicit:!0,optional:!0})],mb.prototype,`originatorInfo`,void 0),X([J({type:ab})],mb.prototype,`recipientInfos`,void 0),X([J({type:Vy})],mb.prototype,`encryptedContentInfo`,void 0),X([J({type:pb,context:1,implicit:!0,optional:!0})],mb.prototype,`unprotectedAttrs`,void 0);var hb=`1.2.840.113549.1.7.2`,gb,_b=gb=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,gb.prototype)}};_b=gb=X([q({type:G.Set,itemType:Gv})],_b);var vb=class{version=Wv.v0;digestAlgorithms=new _b;encapContentInfo=new zy;certificates;crls;signerInfos=new ey;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],vb.prototype,`version`,void 0),X([J({type:_b})],vb.prototype,`digestAlgorithms`,void 0),X([J({type:zy})],vb.prototype,`encapContentInfo`,void 0),X([J({type:Iy,context:0,implicit:!0,optional:!0})],vb.prototype,`certificates`,void 0),X([J({type:ub,context:1,implicit:!0,optional:!0})],vb.prototype,`crls`,void 0),X([J({type:ey})],vb.prototype,`signerInfos`,void 0);var yb=`1.2.840.10045.2.1`,bb=`1.2.840.10045.4.1`,xb=`1.2.840.10045.4.3.1`,Sb=`1.2.840.10045.4.3.2`,Cb=`1.2.840.10045.4.3.3`,wb=`1.2.840.10045.4.3.4`,Tb=`1.2.840.10045.3.1.7`,Eb=`1.3.132.0.34`,Db=`1.3.132.0.35`;function Ob(e){return new Z({algorithm:e})}var kb=Ob(bb);Ob(xb);var Ab=Ob(Sb),jb=Ob(Cb),Mb=Ob(wb),Nb=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Nb.prototype,`fieldType`,void 0),X([J({type:K.Any})],Nb.prototype,`parameters`,void 0),Nb=X([q({type:G.Sequence})],Nb);var Pb=class extends tg{},Fb=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};X([J({type:K.OctetString})],Fb.prototype,`a`,void 0),X([J({type:K.OctetString})],Fb.prototype,`b`,void 0),X([J({type:K.BitString,optional:!0})],Fb.prototype,`seed`,void 0),Fb=X([q({type:G.Sequence})],Fb);var Ib;(function(e){e[e.ecpVer1=1]=`ecpVer1`})(Ib||={});var Lb=class{version=Ib.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Lb.prototype,`version`,void 0),X([J({type:Nb})],Lb.prototype,`fieldID`,void 0),X([J({type:Fb})],Lb.prototype,`curve`,void 0),X([J({type:Pb})],Lb.prototype,`base`,void 0),X([J({type:K.Integer,converter:ag})],Lb.prototype,`order`,void 0),X([J({type:K.Integer,optional:!0})],Lb.prototype,`cofactor`,void 0),Lb=X([q({type:G.Sequence})],Lb);var Rb=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Rb.prototype,`namedCurve`,void 0),X([J({type:K.Null})],Rb.prototype,`implicitCurve`,void 0),X([J({type:Lb})],Rb.prototype,`specifiedCurve`,void 0),Rb=X([q({type:G.Choice})],Rb);var zb=class{version=1;privateKey=new tg;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],zb.prototype,`version`,void 0),X([J({type:tg})],zb.prototype,`privateKey`,void 0),X([J({type:Rb,context:0,optional:!0})],zb.prototype,`parameters`,void 0),X([J({type:K.BitString,context:1,optional:!0})],zb.prototype,`publicKey`,void 0);var Bb=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:ag})],Bb.prototype,`r`,void 0),X([J({type:K.Integer,converter:ag})],Bb.prototype,`s`,void 0);var Vb=`1.2.840.113549.1.1`,Hb=`${Vb}.1`,Ub=`${Vb}.7`,Wb=`${Vb}.9`,Gb=`${Vb}.10`,Kb=`${Vb}.2`,qb=`${Vb}.4`,Jb=`${Vb}.5`,Yb=`${Vb}.14`,Xb=`${Vb}.11`,Zb=`${Vb}.12`,Qb=`${Vb}.13`,$b=`${Vb}.15`,ex=`${Vb}.16`,tx=`1.3.14.3.2.26`,nx=`2.16.840.1.101.3.4.2.4`,rx=`2.16.840.1.101.3.4.2.1`,ix=`2.16.840.1.101.3.4.2.2`,ax=`2.16.840.1.101.3.4.2.3`,ox=`2.16.840.1.101.3.4.2.5`,sx=`2.16.840.1.101.3.4.2.6`,cx=`1.2.840.113549.2.2`,lx=`1.2.840.113549.2.5`,ux=`${Vb}.8`;function dx(e){return new Z({algorithm:e,parameters:null})}dx(cx),dx(lx);var fx=dx(tx);dx(nx),dx(rx),dx(ix),dx(ax),dx(ox),dx(sx);var px=new Z({algorithm:ux,parameters:Y.serialize(fx)}),mx=new Z({algorithm:Wb,parameters:Y.serialize(ug.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});dx(Hb),dx(Kb),dx(qb),dx(Jb),dx($b),dx(ex),dx(Zb),dx(Qb),dx($b),dx(ex);var hx=class{hashAlgorithm=new Z(fx);maskGenAlgorithm=new Z({algorithm:ux,parameters:Y.serialize(fx)});pSourceAlgorithm=new Z(mx);constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:fx})],hx.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:px})],hx.prototype,`maskGenAlgorithm`,void 0),X([J({type:Z,context:2,defaultValue:mx})],hx.prototype,`pSourceAlgorithm`,void 0),new Z({algorithm:Ub,parameters:Y.serialize(new hx)});var gx=class{hashAlgorithm=new Z(fx);maskGenAlgorithm=new Z({algorithm:ux,parameters:Y.serialize(fx)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:fx})],gx.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:px})],gx.prototype,`maskGenAlgorithm`,void 0),X([J({type:K.Integer,context:2,defaultValue:20})],gx.prototype,`saltLength`,void 0),X([J({type:K.Integer,context:3,defaultValue:1})],gx.prototype,`trailerField`,void 0),new Z({algorithm:Gb,parameters:Y.serialize(new gx)});var _x=class{digestAlgorithm=new Z;digest=new tg;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],_x.prototype,`digestAlgorithm`,void 0),X([J({type:tg})],_x.prototype,`digest`,void 0);var vx,yx=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:ag})],yx.prototype,`prime`,void 0),X([J({type:K.Integer,converter:ag})],yx.prototype,`exponent`,void 0),X([J({type:K.Integer,converter:ag})],yx.prototype,`coefficient`,void 0);var bx=vx=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,vx.prototype)}};bx=vx=X([q({type:G.Sequence,itemType:yx})],bx);var xx=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)}};X([J({type:K.Integer})],xx.prototype,`version`,void 0),X([J({type:K.Integer,converter:ag})],xx.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:ag})],xx.prototype,`publicExponent`,void 0),X([J({type:K.Integer,converter:ag})],xx.prototype,`privateExponent`,void 0),X([J({type:K.Integer,converter:ag})],xx.prototype,`prime1`,void 0),X([J({type:K.Integer,converter:ag})],xx.prototype,`prime2`,void 0),X([J({type:K.Integer,converter:ag})],xx.prototype,`exponent1`,void 0),X([J({type:K.Integer,converter:ag})],xx.prototype,`exponent2`,void 0),X([J({type:K.Integer,converter:ag})],xx.prototype,`coefficient`,void 0),X([J({type:bx,optional:!0})],xx.prototype,`otherPrimeInfos`,void 0);var Sx=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:ag})],Sx.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:ag})],Sx.prototype,`publicExponent`,void 0);var Cx;(function(e){e[e.Transient=0]=`Transient`,e[e.Singleton=1]=`Singleton`,e[e.ResolutionScoped=2]=`ResolutionScoped`,e[e.ContainerScoped=3]=`ContainerScoped`})(Cx||={});var wx=Cx,Tx=function(e,t){return Tx=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},Tx(e,t)};function Ex(e,t){Tx(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function Dx(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Ox(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o={next:s(0),throw:s(1),return:s(2)};return typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(o){if(r)throw TypeError(`Generator is already executing.`);for(;n;)try{if(r=1,i&&(a=o[0]&2?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[o[0]&2,a.value]),o[0]){case 0:case 1:a=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,i=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1],a=o;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(o);break}a[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}}function kx(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Ax(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function jx(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Ax(arguments[t]));return e}function Mx(e){var t=Reflect.getMetadata(`design:paramtypes`,e)||[],n=Reflect.getOwnMetadata(`injectionTokens`,e)||{};return Object.keys(n).forEach(function(e){t[+e]=n[e]}),t}function Nx(e){return!!e.useClass}function Px(e){return!!e.useFactory}var Fx=function(){function e(e){this.wrap=e,this.reflectMethods=[`get`,`getPrototypeOf`,`setPrototypeOf`,`getOwnPropertyDescriptor`,`defineProperty`,`has`,`set`,`deleteProperty`,`apply`,`construct`,`ownKeys`]}return e.prototype.createProxy=function(e){var t=this,n={},r=!1,i;return new Proxy(n,this.createHandler(function(){return r||=(i=e(t.wrap()),!0),i}))},e.prototype.createHandler=function(e){var t={};return this.reflectMethods.forEach(function(n){t[n]=function(){var t=[...arguments];return t[0]=e(),Reflect[n].apply(void 0,jx(t))}}),t},e}();function Ix(e){return typeof e==`string`||typeof e==`symbol`}function Lx(e){return typeof e==`object`&&`token`in e&&`multiple`in e}function Rx(e){return typeof e==`object`&&`token`in e&&`transform`in e}function zx(e){return typeof e==`function`||e instanceof Fx}function Bx(e){return!!e.useToken}function Vx(e){return e.useValue!=null}function Hx(e){return Nx(e)||Vx(e)||Bx(e)||Px(e)}var Ux=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},e.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},e.prototype.setAll=function(e,t){this._registryMap.set(e,t)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}(),Wx=function(e){Ex(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Ux),Gx=function(){function e(){this.scopedResolutions=new Map}return e}();function Kx(e,t){return e===null?`at position #`+t:`"`+e.split(`,`)[t].trim()+`" at position #`+t}function qx(e,t,n){return n===void 0&&(n=` `),jx([e],t.message.split(`
|
|
37
37
|
`).map(function(e){return n+e})).join(`
|
|
38
|
-
`)}function hm(e,t,n){var r=Zp(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return mm(`Cannot inject the dependency `+pm(r===void 0?null:r,t)+` of "`+e.name+`" constructor. Reason:`,n)}function gm(e){return!(typeof e.dispose!=`function`||e.dispose.length>0)}var _m=function(e){qp(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(um),vm=function(e){qp(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(um),ym=function(){function e(){this.preResolution=new _m,this.postResolution=new vm}return e}(),bm=new Map,xm=new(function(){function e(e){this.parent=e,this._registry=new dm,this.interceptors=new ym,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,n){n===void 0&&(n={lifecycle:Gp.Transient}),this.ensureNotDisposed();var r=lm(t)?t:{useClass:t};if(sm(r))for(var i=[e],a=r;a!=null;){var o=a.useToken;if(i.includes(o))throw Error(`Token registration cycle detected! `+Qp(i,[o]).join(` -> `));i.push(o);var s=this._registry.get(o);a=s&&sm(s.provider)?s.provider:null}if((n.lifecycle===Gp.Singleton||n.lifecycle==Gp.ContainerScoped||n.lifecycle==Gp.ResolutionScoped)&&(cm(r)||tm(r)))throw Error(`Cannot use lifecycle "`+Gp[n.lifecycle]+`" with ValueProviders or FactoryProviders`);return this._registry.set(e,{provider:r,options:n}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),rm(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},e.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},e.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),rm(e)){if(rm(t))return this.register(e,{useToken:t},{lifecycle:Gp.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:Gp.Singleton});throw Error(`Cannot register a type name as a singleton without a "to" token`)}var n=e;return t&&!rm(t)&&(n=t),this.register(e,{useClass:n},{lifecycle:Gp.Singleton})},e.prototype.resolve=function(e,t,n){t===void 0&&(t=new fm),n===void 0&&(n=!1),this.ensureNotDisposed();var r=this.getRegistration(e);if(!r&&rm(e)){if(n)return;throw Error(`Attempted to resolve unregistered dependency token: "`+e.toString()+`"`)}if(this.executePreResolutionInterceptor(e,`Single`),r){var i=this.resolveRegistration(r,t);return this.executePostResolutionInterceptor(e,i,`Single`),i}if(om(e)){var i=this.construct(e,t);return this.executePostResolutionInterceptor(e,i,`Single`),i}throw Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,t){var n,r;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var a=Xp(this.interceptors.preResolution.getAll(e)),o=a.next();!o.done;o=a.next()){var s=o.value;s.options.frequency!=`Once`&&i.push(s),s.callback(e,t)}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,t,n){var r,i;if(this.interceptors.postResolution.has(e)){var a=[];try{for(var o=Xp(this.interceptors.postResolution.getAll(e)),s=o.next();!s.done;s=o.next()){var c=s.value;c.options.frequency!=`Once`&&a.push(c),c.callback(e,t,n)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}this.interceptors.postResolution.setAll(e,a)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===Gp.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var n=e.options.lifecycle===Gp.Singleton,r=e.options.lifecycle===Gp.ContainerScoped,i=n||r,a=cm(e.provider)?e.provider.useValue:sm(e.provider)?i?e.instance||=this.resolve(e.provider.useToken,t):this.resolve(e.provider.useToken,t):em(e.provider)?i?e.instance||=this.construct(e.provider.useClass,t):this.construct(e.provider.useClass,t):tm(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t);return e.options.lifecycle===Gp.ResolutionScoped&&t.scopedResolutions.set(e,a),a},e.prototype.resolveAll=function(e,t,n){var r=this;t===void 0&&(t=new fm),n===void 0&&(n=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&rm(e)){if(n)return[];throw Error(`Attempted to resolve unregistered dependency token: "`+e.toString()+`"`)}if(this.executePreResolutionInterceptor(e,`All`),i){var a=i.map(function(e){return r.resolveRegistration(e,t)});return this.executePostResolutionInterceptor(e,a,`All`),a}var o=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,o,`All`),o},e.prototype.isRegistered=function(e,t){return t===void 0&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var n=Xp(this._registry.entries()),r=n.next();!r.done;r=n.next()){var i=Zp(r.value,2),a=i[0],o=i[1];this._registry.setAll(a,o.filter(function(e){return!cm(e.provider)}).map(function(e){return e.instance=void 0,e}))}}catch(t){e={error:t}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){var t,n;this.ensureNotDisposed();var r=new e(this);try{for(var i=Xp(this._registry.entries()),a=i.next();!a.done;a=i.next()){var o=Zp(a.value,2),s=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===Gp.ContainerScoped})&&r._registry.setAll(s,c.map(function(e){return e.options.lifecycle===Gp.ContainerScoped?{provider:e.provider,options:e.options}:e}))}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return r},e.prototype.beforeResolution=function(e,t,n){n===void 0&&(n={frequency:`Always`}),this.interceptors.preResolution.set(e,{callback:t,options:n})},e.prototype.afterResolution=function(e,t,n){n===void 0&&(n={frequency:`Always`}),this.interceptors.postResolution.set(e,{callback:t,options:n})},e.prototype.dispose=function(){return Jp(this,void 0,void 0,function(){var e;return Yp(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(t){var n=t.dispose();n&&e.push(n)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var n=this;if(e instanceof nm)return e.createProxy(function(e){return n.resolve(e,t)});var r=(function(){var r=bm.get(e);if(!r||r.length===0){if(e.length===0)return new e;throw Error(`TypeInfo not known for "`+e.name+`"`)}var i=r.map(n.resolveParams(t,e));return new(e.bind.apply(e,Qp([void 0],i)))})();return gm(r)&&this.disposables.add(r),r},e.prototype.resolveParams=function(e,t){var n=this;return function(r,i){var a,o,s;try{return im(r)?am(r)?r.multiple?(a=n.resolve(r.transform)).transform.apply(a,Qp([n.resolveAll(r.token,new fm,r.isOptional)],r.transformArgs)):(o=n.resolve(r.transform)).transform.apply(o,Qp([n.resolve(r.token,e,r.isOptional)],r.transformArgs)):r.multiple?n.resolveAll(r.token,new fm,r.isOptional):n.resolve(r.token,e,r.isOptional):am(r)?(s=n.resolve(r.transform,e)).transform.apply(s,Qp([n.resolve(r.token,e)],r.transformArgs)):n.resolve(r,e)}catch(e){throw Error(hm(t,i,e))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw Error(`This container has been disposed, you cannot interact with a disposed container`)},e}());function Sm(e){return function(t){bm.set(t,$p(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){xm.register(e,t)}):xm.register(e.token,t))}}if(typeof Reflect>`u`||!Reflect.getMetadata)throw Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var Cm,wm=class{attrId=``;attrValues=[];constructor(e={}){Object.assign(e)}};X([J({type:K.ObjectIdentifier})],wm.prototype,`attrId`,void 0),X([J({type:K.Any,repeated:`set`})],wm.prototype,`attrValues`,void 0);var Tm=Cm=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Cm.prototype)}};Tm=Cm=X([q({type:G.Sequence,itemType:wm})],Tm);var Em,Dm=Em=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Em.prototype)}};Dm=Em=X([q({type:G.Sequence,itemType:rf})],Dm);var Om=`1.2.840.113549.1.12`,km=`${Om}.1`;`${km}`,`${km}`,`${km}`,`${km}`,`${km}`,`${km}`;var Am=`${Om}.10.1`;`${Am}`,`${Am}`,`${Am}`,`${Am}`,`${Am}`,`${Am}`;var jm=`1.2.840.113549.1.9`,Mm=class{certId=``;certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Mm.prototype,`certId`,void 0),X([J({type:K.Any,context:0})],Mm.prototype,`certValue`,void 0);var Nm=`${jm}.22`;`${Nm}`,`${Nm}`;var Pm=class{crlId=``;crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Pm.prototype,`crlId`,void 0),X([J({type:K.Any,context:0})],Pm.prototype,`crltValue`,void 0),`${jm}`;var Fm=class extends xc{},Im=class{encryptionAlgorithm=new Z;encryptedData=new Fm;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Im.prototype,`encryptionAlgorithm`,void 0),X([J({type:Fm})],Im.prototype,`encryptedData`,void 0);var Lm,Rm;(function(e){e[e.v1=0]=`v1`})(Rm||={});var zm=class extends xc{},Bm=Lm=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Lm.prototype)}};Bm=Lm=X([q({type:G.Sequence,itemType:zu})],Bm);var Vm=class{version=Rm.v1;privateKeyAlgorithm=new Z;privateKey=new zm;attributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Vm.prototype,`version`,void 0),X([J({type:Z})],Vm.prototype,`privateKeyAlgorithm`,void 0),X([J({type:zm})],Vm.prototype,`privateKey`,void 0),X([J({type:Bm,implicit:!0,context:0,optional:!0})],Vm.prototype,`attributes`,void 0);var Hm=class extends Vm{};Hm=X([q({type:G.Sequence})],Hm);var Um=class extends Im{};Um=X([q({type:G.Sequence})],Um);var Wm=class{secretTypeId=``;secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Wm.prototype,`secretTypeId`,void 0),X([J({type:K.Any,context:0})],Wm.prototype,`secretValue`,void 0);var Gm=class{mac=new Rp;macSalt=new xc;iterations=1;constructor(e={}){Object.assign(this,e)}};X([J({type:Rp})],Gm.prototype,`mac`,void 0),X([J({type:xc})],Gm.prototype,`macSalt`,void 0),X([J({type:K.Integer,defaultValue:1})],Gm.prototype,`iterations`,void 0);var Km=class{version=3;authSafe=new rf;macData=new Gm;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Km.prototype,`version`,void 0),X([J({type:rf})],Km.prototype,`authSafe`,void 0),X([J({type:Gm,optional:!0})],Km.prototype,`macData`,void 0);var qm,Jm=class{bagId=``;bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Jm.prototype,`bagId`,void 0),X([J({type:K.Any,context:0})],Jm.prototype,`bagValue`,void 0),X([J({type:wm,repeated:`set`,optional:!0})],Jm.prototype,`bagAttributes`,void 0);var Ym=qm=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,qm.prototype)}};Ym=qm=X([q({type:G.Sequence,itemType:Jm})],Ym);var Xm,Zm,Qm,$m=`1.2.840.113549.1.9`;`${$m}`;var eh=`${$m}.24`,th=`${$m}.25`,nh=`${$m}.26`,rh=`${$m}.27`;`${eh}`,`${eh}`,`${$m}`,`${$m}`,`${$m}`,`${$m}`,`${$m}`,`${$m}`;var ih=`${$m}.7`;`${$m}`,`${$m}`,`${$m}`;var ah=`${$m}.14`;`${$m}`,`${$m}`,`${$m}`,`${th}`,`${th}`,`${th}`,`${th}`,`${th}`;var oh=`1.3.6.1.5.5.7.9`;`${oh}`,`${oh}`,`${oh}`,`${oh}`,`${oh}`,`${nh}`,`${nh}`,`${rh}`,`${rh}`,`${$m}`,`${$m}`,`${$m}`,`${Wd}`;var sh=class extends ll{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};X([J({type:K.IA5String})],sh.prototype,`ia5String`,void 0),sh=X([q({type:G.Choice})],sh);var ch=class extends rf{};ch=X([q({type:G.Sequence})],ch);var lh=class extends Km{};lh=X([q({type:G.Sequence})],lh);var uh=class extends Im{};uh=X([q({type:G.Sequence})],uh);var dh=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.IA5String})],dh.prototype,`value`,void 0),dh=X([q({type:G.Choice})],dh);var fh=class extends sh{};fh=X([q({type:G.Choice})],fh);var ph=class extends ll{};ph=X([q({type:G.Choice})],ph);var mh=class{value;constructor(e=new Date){this.value=e}};X([J({type:K.GeneralizedTime})],mh.prototype,`value`,void 0),mh=X([q({type:G.Choice})],mh);var hh=class extends ll{};hh=X([q({type:G.Choice})],hh);var gh=class{value;constructor(e=`M`){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],gh.prototype,`value`,void 0),gh=X([q({type:G.Choice})],gh);var _h=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],_h.prototype,`value`,void 0),_h=X([q({type:G.Choice})],_h);var vh=class extends _h{};vh=X([q({type:G.Choice})],vh);var yh=class extends ll{};yh=X([q({type:G.Choice})],yh);var bh=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.ObjectIdentifier})],bh.prototype,`value`,void 0),bh=X([q({type:G.Choice})],bh);var xh=class extends Zu{};xh=X([q({type:G.Choice})],xh);var Sh=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};X([J({type:K.Integer})],Sh.prototype,`value`,void 0),Sh=X([q({type:G.Choice})],Sh);var Ch=class extends yd{};Ch=X([q({type:G.Sequence})],Ch);var wh=class extends ll{};wh=X([q({type:G.Choice})],wh);var Th=Xm=class extends td{constructor(e){super(e),Object.setPrototypeOf(this,Xm.prototype)}};Th=Xm=X([q({type:G.Sequence})],Th);var Eh=Zm=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Zm.prototype)}};Eh=Zm=X([q({type:G.Set,itemType:_d})],Eh);var Dh=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.BmpString})],Dh.prototype,`value`,void 0),Dh=X([q({type:G.Choice})],Dh);var Oh=class extends Z{};Oh=X([q({type:G.Sequence})],Oh);var kh=Qm=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Qm.prototype)}};kh=Qm=X([q({type:G.Sequence,itemType:Oh})],kh);var Ah,jh=Ah=class extends nl{constructor(e){super(e),Object.setPrototypeOf(this,Ah.prototype)}};jh=Ah=X([q({type:G.Sequence,itemType:zu})],jh);var Mh=class{version=0;subject=new ml;subjectPKInfo=new Xu;attributes=new jh;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Mh.prototype,`version`,void 0),X([J({type:ml})],Mh.prototype,`subject`,void 0),X([J({type:Xu})],Mh.prototype,`subjectPKInfo`,void 0),X([J({type:jh,implicit:!0,context:0,optional:!0})],Mh.prototype,`attributes`,void 0);var Nh=class{certificationRequestInfo=new Mh;certificationRequestInfoRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Mh,raw:!0})],Nh.prototype,`certificationRequestInfo`,void 0),X([J({type:Z})],Nh.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Nh.prototype,`signature`,void 0);var Ph=`crypto.algorithm`,Fh=class{getAlgorithms(){return xm.resolveAll(Ph)}toAsnAlgorithm(e){({...e});for(let t of this.getAlgorithms()){let n=t.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){let t=new Z({algorithm:e.name});return`parameters`in e&&(t.parameters=e.parameters),t}throw Error(`Cannot convert WebCrypto algorithm to ASN.1 algorithm`)}toWebAlgorithm(e){for(let t of this.getAlgorithms()){let n=t.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}},Ih=`crypto.algorithmProvider`;xm.registerSingleton(Ih,Fh);var Lh,Rh=`1.3.36.3.3.2.8.1.1`,zh=`${Rh}.1`,Bh=`${Rh}.2`,Vh=`${Rh}.3`,Hh=`${Rh}.4`,Uh=`${Rh}.5`,Wh=`${Rh}.6`,Gh=`${Rh}.7`,Kh=`${Rh}.8`,qh=`${Rh}.9`,Jh=`${Rh}.10`,Yh=`${Rh}.11`,Xh=`${Rh}.12`,Zh=`${Rh}.13`,Qh=`${Rh}.14`,$h=`brainpoolP160r1`,eg=`brainpoolP160t1`,tg=`brainpoolP192r1`,ng=`brainpoolP192t1`,rg=`brainpoolP224r1`,ig=`brainpoolP224t1`,ag=`brainpoolP256r1`,og=`brainpoolP256t1`,sg=`brainpoolP320r1`,cg=`brainpoolP320t1`,lg=`brainpoolP384r1`,ug=`brainpoolP384t1`,dg=`brainpoolP512r1`,fg=`brainpoolP512t1`,pg=`ECDSA`,mg=Lh=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case pg.toLowerCase():if(`hash`in e)switch((typeof e.hash==`string`?e.hash:e.hash.name).toLowerCase()){case`sha-1`:return Xf;case`sha-256`:return Zf;case`sha-384`:return Qf;case`sha-512`:return $f}else if(`namedCurve`in e){let t=``;switch(e.namedCurve){case`P-256`:t=Kf;break;case`K-256`:t=Lh.SECP256K1;break;case`P-384`:t=qf;break;case`P-521`:t=Jf;break;case $h:t=zh;break;case eg:t=Bh;break;case tg:t=Vh;break;case ng:t=Hh;break;case rg:t=Uh;break;case ig:t=Wh;break;case ag:t=Gh;break;case og:t=Kh;break;case sg:t=qh;break;case cg:t=Jh;break;case lg:t=Yh;break;case ug:t=Xh;break;case dg:t=Zh;break;case fg:t=Qh}if(t)return new Z({algorithm:Bf,parameters:Y.serialize(new ap({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Vf:return{name:pg,hash:{name:`SHA-1`}};case Uf:return{name:pg,hash:{name:`SHA-256`}};case Wf:return{name:pg,hash:{name:`SHA-384`}};case Gf:return{name:pg,hash:{name:`SHA-512`}};case Bf:if(!e.parameters)throw TypeError(`Cannot get required parameters from EC algorithm`);switch(Y.parse(e.parameters,ap).namedCurve){case Kf:return{name:pg,namedCurve:`P-256`};case Lh.SECP256K1:return{name:pg,namedCurve:`K-256`};case qf:return{name:pg,namedCurve:`P-384`};case Jf:return{name:pg,namedCurve:`P-521`};case zh:return{name:pg,namedCurve:$h};case Bh:return{name:pg,namedCurve:eg};case Vh:return{name:pg,namedCurve:tg};case Hh:return{name:pg,namedCurve:ng};case Uh:return{name:pg,namedCurve:rg};case Wh:return{name:pg,namedCurve:ig};case Gh:return{name:pg,namedCurve:ag};case Kh:return{name:pg,namedCurve:og};case qh:return{name:pg,namedCurve:sg};case Jh:return{name:pg,namedCurve:cg};case Yh:return{name:pg,namedCurve:lg};case Xh:return{name:pg,namedCurve:ug};case Zh:return{name:pg,namedCurve:dg};case Qh:return{name:pg,namedCurve:fg}}}return null}};mg.SECP256K1=`1.3.132.0.10`,mg=Lh=X([Sm()],mg),xm.registerSingleton(Ph,mg);var hg=Symbol(`name`),gg=Symbol(`value`),_g=class{constructor(e,t={},n=``){this[hg]=e,this[gg]=n;for(let e in t)this[e]=t[e]}};_g.NAME=hg,_g.VALUE=gg;var vg=class{static toTextObject(e){let t=new _g(`Algorithm Identifier`,{},yg.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Bf:{let n=new mg().toWebAlgorithm(e);n&&`namedCurve`in n?t[`Named Curve`]=n.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}},yg=class{static toString(e){return this.items[e]||e}};yg.items={[Sp]:`sha1`,[Cp]:`sha224`,[wp]:`sha256`,[Tp]:`sha384`,[Ep]:`sha512`,[lp]:`rsaEncryption`,[hp]:`sha1WithRSAEncryption`,[gp]:`sha224WithRSAEncryption`,[_p]:`sha256WithRSAEncryption`,[vp]:`sha384WithRSAEncryption`,[yp]:`sha512WithRSAEncryption`,[Bf]:`ecPublicKey`,[Vf]:`ecdsaWithSHA1`,[Hf]:`ecdsaWithSHA224`,[Uf]:`ecdsaWithSHA256`,[Wf]:`ecdsaWithSHA384`,[Gf]:`ecdsaWithSHA512`,[mu]:`TLS WWW server authentication`,[hu]:`TLS WWW client authentication`,[gu]:`Code Signing`,[_u]:`E-mail Protection`,[vu]:`Time Stamping`,[yu]:`OCSP Signing`,[If]:`Signed Data`};var bg=class{static serialize(e){return this.serializeObj(e).join(`
|
|
39
|
-
`)}static pad(e=0){return``.padStart(2*e,` `)}static serializeObj(e,t=0){let n=[],r=this.pad(t++),i=``,a=e[
|
|
40
|
-
`).replace(/\\0d/gi,`\r`).replace(/\\0g/gi,` `).replace(/\\(.)/g,`$1`)}toArrayBuffer(){return Y.serialize(this.asn)}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||
|
|
41
|
-
`)}if(!t)throw Error(`Required argument 'tag' is missed`);return this.encodeStruct({type:t,rawData:U.toArrayBuffer(e)})}static encodeStruct(e){let t=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${t}-----`),e.headers?.length){for(let t of e.headers)n.push(`${t.key}: ${t.value}`);n.push(``)}let r
|
|
42
|
-
`)}};Xg.CertificateTag=`CERTIFICATE`,Xg.CrlTag=`CRL`,Xg.CertificateRequestTag=`CERTIFICATE REQUEST`,Xg.PublicKeyTag=`PUBLIC KEY`,Xg.PrivateKeyTag=`PRIVATE KEY`;var Zg=class e extends Sg{static isAsnEncoded(e){return U.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(Xg.isPem(e))return Xg.decode(e)[0];if(yi.isHex(e))return yi.FromHex(e);if(yi.isBase64(e))return yi.FromBase64(e);if(yi.isBase64Url(e))return yi.FromBase64Url(e);throw TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}{let t=U.toUint8Array(e);if(t.length>0&&t[0]===48)return U.toArrayBuffer(e);let n=yi.ToBinary(e);if(Xg.isPem(n))return Xg.decode(n)[0];if(yi.isHex(n))return yi.FromHex(n);if(yi.isBase64(n))return yi.FromBase64(n);if(yi.isBase64Url(n))return yi.FromBase64Url(n);throw TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}}constructor(...t){e.isAsnEncoded(t[0])?super(e.toArrayBuffer(t[0]),t[1]):super(t[0])}toString(e=`pem`){switch(e){case`pem`:return Xg.encode(this.rawData,this.tag);default:return super.toString(e)}}},Qg=class e extends Zg{static async create(t,n=Eg.get()){if(t instanceof e)return t;if(Tg.isCryptoKey(t)){if(t.type!==`public`)throw TypeError(`Public key is required`);let r=await n.subtle.exportKey(`spki`,t);return new e(r)}if(t.publicKey)return t.publicKey;if(U.isBufferSource(t))return new e(t);throw TypeError(`Unsupported PublicKeyType`)}constructor(e){Zg.isAsnEncoded(e)?super(e,Xu):super(e),this.tag=Xg.PublicKeyTag}async export(...e){let t,n=[`verify`],r={hash:`SHA-256`,...this.algorithm};e.length>1?(r=e[0]||r,n=e[1]||n,t=e[2]||Eg.get()):t=e[0]||Eg.get();let i=this.rawData,a=Y.parse(this.rawData,Xu);return a.algorithm.algorithm===fp&&(i=$g(a,i)),t.subtle.importKey(`spki`,i,r,!0,n)}onInit(e){let t=xm.resolve(Ih),n=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case lp:{let t=Y.parse(e.subjectPublicKey,Up),r=U.toUint8Array(t.modulus);n.publicExponent=U.toUint8Array(t.publicExponent),n.modulusLength=(r[0]?r:r.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||Eg.get()):t=e[0]||Eg.get(),await t.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,n=`SHA-1`;e.length===1?typeof e[0]==`string`?(n=e[0],t=Eg.get()):t=e[0]:e.length===2?(n=e[0],t=e[1]):t=Eg.get();let r=Y.parse(this.rawData,Xu);return await t.subtle.digest(n,r.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,Xu);switch(e.Algorithm=bg.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Bf:e[`EC Point`]=t.subjectPublicKey;break;case lp:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function $g(e,t){return e.algorithm=new Z({algorithm:lp,parameters:null}),t=Y.serialize(e),t}var e_=class e extends Cg{static async create(t,n=!1,r=Eg.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let i=await(await Qg.create(t,r)).getKeyIdentifier(r);return new e(yi.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new Fl({keyIdentifier:new Pl(yi.FromHex(e[0]))});super(Nl,e[1],Y.serialize(t))}else{let t=e[0],n=new Fl({authorityCertIssuer:t.name instanceof Ug?Y.parse(t.name.rawData,zl):t.name,authorityCertSerialNumber:yi.FromHex(t.serialNumber)});super(Nl,e[1],Y.serialize(n))}}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Fl);t.keyIdentifier&&(this.keyId=yi.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?yi.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=Y.parse(this.value,Fl);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new Ug(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};e_.NAME=`Authority Key Identifier`;var t_=class extends Cg{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Ll);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new Ll({cA:e[0],pathLenConstraint:e[1]});super(Il,e[2],Y.serialize(t)),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}};t_.NAME=`Basic Constraints`;var n_;(function(e){e.serverAuth=`1.3.6.1.5.5.7.3.1`,e.clientAuth=`1.3.6.1.5.5.7.3.2`,e.codeSigning=`1.3.6.1.5.5.7.3.3`,e.emailProtection=`1.3.6.1.5.5.7.3.4`,e.timeStamping=`1.3.6.1.5.5.7.3.8`,e.ocspSigning=`1.3.6.1.5.5.7.3.9`})(n_||={});var r_=class extends Cg{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,pu);this.usages=t.map(e=>e)}else{let t=new pu(e[0]);super(fu,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.usages.map(e=>yg.toString(e)).join(`, `),e}};r_.NAME=`Extended Key Usages`;var i_;(function(e){e[e.digitalSignature=1]=`digitalSignature`,e[e.nonRepudiation=2]=`nonRepudiation`,e[e.keyEncipherment=4]=`keyEncipherment`,e[e.dataEncipherment=8]=`dataEncipherment`,e[e.keyAgreement=16]=`keyAgreement`,e[e.keyCertSign=32]=`keyCertSign`,e[e.cRLSign=64]=`cRLSign`,e[e.encipherOnly=128]=`encipherOnly`,e[e.decipherOnly=256]=`decipherOnly`})(i_||={});var a_=class extends Cg{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Du);this.usages=t.toNumber()}else{let t=new Du(e[0]);super(Tu,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,Du).toJSON().join(`, `),e}};a_.NAME=`Key Usages`;var o_=class e extends Cg{static async create(t,n=!1,r=Eg.get()){let i=await(await Qg.create(t,r)).getKeyIdentifier(r);return new e(yi.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Uu);this.keyId=yi.ToHex(t)}else{let t=typeof e[0]==`string`?yi.FromHex(e[0]):e[0],n=new Uu(t);super(Hu,e[1],Y.serialize(n)),this.keyId=yi.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,Uu),e}};o_.NAME=`Subject Key Identifier`;var s_=class extends Cg{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(Lu,e[1],new Ug(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Ru);this.names=new Ug(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};s_.NAME=`Subject Alternative Name`;var c_=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new Cg(e),n=this.items.get(t.type);return n?new n(e):t}};c_.items=new Map;var l_=class extends Cg{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Xl);this.policies=t.map(e=>e.policyIdentifier)}else{let t=e[0],n=e[1]??!1,r=new Xl(t.map(e=>new Yl({policyIdentifier:e})));super(Ul,n,Y.serialize(r)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new _g(``,{},yg.toString(e))),e}};l_.NAME=`Certificate Policies`,c_.register(Ul,l_);var u_=class extends Cg{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]==`string`){let t=e[0].map(e=>new iu({distributionPoint:new ru({fullName:[new vl({uniformResourceIdentifier:e})]})})),n=new au(t);super(eu,e[1],Y.serialize(n))}else{let t=new au(e[0]);super(eu,e[1],Y.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,au);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e[`Distribution Point`]=this.distributionPoints.map(e=>{let t={};return e.distributionPoint&&(t[``]=e.distributionPoint.fullName?.map(e=>new Hg(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};u_.NAME=`CRL Distribution Points`;var d_=class extends Cg{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Ml){let t=new Ml(e[0]);super(Al,e[1],Y.serialize(t))}else{let t=e[0],n=new Ml;p_(n,t,wl,`ocsp`),p_(n,t,Tl,`caIssuers`),p_(n,t,El,`timeStamping`),p_(n,t,Dl,`caRepository`),super(Al,e[1],Y.serialize(n))}this.ocsp??=[],this.caIssuers??=[],this.timeStamping??=[],this.caRepository??=[]}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],Y.parse(e.extnValue,Ml).forEach(e=>{switch(e.accessMethod){case wl:this.ocsp.push(new Hg(e.accessLocation));break;case Tl:this.caIssuers.push(new Hg(e.accessLocation));break;case El:this.timeStamping.push(new Hg(e.accessLocation));break;case Dl:this.caRepository.push(new Hg(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&f_(e,`OCSP`,this.ocsp),this.caIssuers.length&&f_(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&f_(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&f_(e,`CA Repository`,this.caRepository),e}};d_.NAME=`Authority Info Access`;function f_(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new _g(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[_g.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function p_(e,t,n,r){let i=t[r];i&&(Array.isArray(i)?i:[i]).forEach(t=>{typeof t==`string`&&(t=new Hg(`url`,t)),e.push(new jl({accessMethod:n,accessLocation:Y.parse(t.rawData,vl)}))})}var m_=class extends Cg{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(Cu,e[1],new Ug(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,zl);this.names=new Ug(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};m_.NAME=`Issuer Alternative Name`;var h_=class e extends Sg{constructor(...e){let t;if(U.isBufferSource(e[0]))t=U.toArrayBuffer(e[0]);else{let n=e[0],r=Array.isArray(e[1])?e[1].map(e=>U.toArrayBuffer(e)):[];t=Y.serialize(new zu({type:n,values:r}))}super(t,zu)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new _g(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[_g.NAME]===e.NAME&&(t[_g.NAME]=yg.toString(this.type)),t}};h_.NAME=`Attribute`;var g_=class extends h_{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=new wh({printableString:e[0]});super(ih,[Y.serialize(t)])}this.password??=``}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],wh);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[_g.VALUE]=this.password,e}};g_.NAME=`Challenge Password`;var __=class extends h_{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=e[0],n=new td;for(let e of t)n.push(Y.parse(e.rawData,ed));super(ah,[Y.serialize(n)])}this.items??=[]}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],td);this.items=e.map(e=>c_.create(Y.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[_g.NAME]]=n;return e}};__.NAME=`Extensions`;var v_=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new h_(e),n=this.items.get(t.type);return n?new n(e):t}};v_.items=new Map;var y_=`crypto.signatureFormatter`,b_=class{toAsnSignature(e,t){return U.toArrayBuffer(t)}toWebSignature(e,t){return U.toArrayBuffer(t)}},x_,S_=x_=class{static createPssParams(e,t){let n=x_.getHashAlgorithm(e);return n?new Lp({hashAlgorithm:n,maskGenAlgorithm:new Z({algorithm:jp,parameters:Y.serialize(n)}),saltLength:t}):null}static getHashAlgorithm(e){let t=xm.resolve(Ih);return typeof e==`string`?t.toAsnAlgorithm({name:e}):typeof e==`object`&&e&&`name`in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`rsassa-pkcs1-v1_5`:if(`hash`in e){let t;if(typeof e.hash==`string`)t=e.hash;else if(e.hash&&typeof e.hash==`object`&&`name`in e.hash&&typeof e.hash.name==`string`)t=e.hash.name.toUpperCase();else throw Error(`Cannot get hash algorithm name`);switch(t.toLowerCase()){case`sha-1`:return new Z({algorithm:hp,parameters:null});case`sha-256`:return new Z({algorithm:_p,parameters:null});case`sha-384`:return new Z({algorithm:vp,parameters:null});case`sha-512`:return new Z({algorithm:yp,parameters:null})}}else return new Z({algorithm:lp,parameters:null});break;case`rsa-pss`:if(`hash`in e){if(!(`saltLength`in e&&typeof e.saltLength==`number`))throw Error(`Cannot get 'saltLength' from 'alg' argument`);let t=x_.createPssParams(e.hash,e.saltLength);if(!t)throw Error(`Cannot create PSS parameters`);return new Z({algorithm:fp,parameters:Y.serialize(t)})}return new Z({algorithm:fp,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case lp:return{name:`RSASSA-PKCS1-v1_5`};case hp:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case _p:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case vp:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case yp:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case fp:if(e.parameters){let t=Y.parse(e.parameters,Lp);return{name:`RSA-PSS`,hash:xm.resolve(Ih).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:`RSA-PSS`}}return null}};S_=x_=X([Sm()],S_),xm.registerSingleton(Ph,S_);var C_=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new Z({algorithm:Sp});case`sha-256`:return new Z({algorithm:wp});case`sha-384`:return new Z({algorithm:Tp});case`sha-512`:return new Z({algorithm:Ep})}return null}toWebAlgorithm(e){switch(e.algorithm){case Sp:return{name:`SHA-1`};case wp:return{name:`SHA-256`};case Tp:return{name:`SHA-384`};case Ep:return{name:`SHA-512`}}return null}};C_=X([Sm()],C_),xm.registerSingleton(Ph,C_);var w_=class e{addPadding(e,t){let n=U.toUint8Array(t),r=new Uint8Array(e);return r.set(n,e-n.length),r.buffer}removePadding(e,t=!1){let n=U.toUint8Array(e);for(let e=0;e<n.length;e++)if(n[e]){n=n.slice(e);break}if(t&&n[0]>127){let e=new Uint8Array(n.length+1);return e.set(n,1),e.buffer}return n.buffer}toAsnSignature(t,n){if(t.name===`ECDSA`){let r=t.namedCurve,i=e.namedCurveSize.get(r)||e.defaultNamedCurveSize,a=new sp,o=U.toUint8Array(n);return a.r=this.removePadding(o.slice(0,i),!0),a.s=this.removePadding(o.slice(i,i+i),!0),Y.serialize(a)}return null}toWebSignature(t,n){if(t.name===`ECDSA`){let r=Y.parse(n,sp),i=t.namedCurve,a=e.namedCurveSize.get(i)||e.defaultNamedCurveSize;return bi(this.addPadding(a,this.removePadding(r.r)),this.addPadding(a,this.removePadding(r.s)))}return null}};w_.namedCurveSize=new Map,w_.defaultNamedCurveSize=32;var T_=`1.3.101.110`,E_=`1.3.101.111`,D_=`1.3.101.112`,O_=`1.3.101.113`,k_=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=D_;break;case`x25519`:t=T_;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=D_;break;case`ed448`:t=O_}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=T_;break;case`x448`:t=E_}}return t?new Z({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case D_:return{name:`Ed25519`};case O_:return{name:`EdDSA`,namedCurve:`Ed448`};case T_:return{name:`X25519`};case E_:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}};k_=X([Sm()],k_),xm.registerSingleton(Ph,k_);var A_,j_,M_,N_,P_,F_,I_,L_,R_=class extends Zg{get subjectName(){return rl(this,j_,`f`)||il(this,j_,new Ng(this.asn.certificationRequestInfo.subject),`f`),rl(this,j_,`f`)}get subject(){return rl(this,M_,`f`)||il(this,M_,this.subjectName.toString(),`f`),rl(this,M_,`f`)}get signatureAlgorithm(){if(!rl(this,N_,`f`)){let e=xm.resolve(Ih);il(this,N_,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return rl(this,N_,`f`)}get signature(){return rl(this,P_,`f`)||il(this,P_,this.asn.signature,`f`),rl(this,P_,`f`)}get publicKey(){return rl(this,F_,`f`)||il(this,F_,new Qg(this.asn.certificationRequestInfo.subjectPKInfo),`f`),rl(this,F_,`f`)}get attributes(){return rl(this,I_,`f`)||il(this,I_,this.asn.certificationRequestInfo.attributes.map(e=>v_.create(Y.serialize(e))),`f`),rl(this,I_,`f`)}get extensions(){if(!rl(this,L_,`f`)){il(this,L_,[],`f`);let e=this.getAttribute(ah);e instanceof __&&il(this,L_,e.items,`f`)}return rl(this,L_,`f`)}get tbs(){return rl(this,A_,`f`)||il(this,A_,this.asn.certificationRequestInfoRaw||Y.serialize(this.asn.certificationRequestInfo),`f`),rl(this,A_,`f`)}constructor(e){let t=Zg.isAsnEncoded(e)?[e,Nh]:[e];super(t[0],t[1]),A_.set(this,void 0),j_.set(this,void 0),M_.set(this,void 0),N_.set(this,void 0),P_.set(this,void 0),F_.set(this,void 0),I_.set(this,void 0),L_.set(this,void 0),this.tag=Xg.CertificateRequestTag}onInit(e){}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=Eg.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=xm.resolveAll(y_).reverse(),i=null;for(let e of r)if(i=e.toWebSignature(t,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(),t=Y.parse(this.rawData,Nh),n=t.certificationRequestInfo,r=new _g(``,{Version:`${nd[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new _g(``);for(let t of this.attributes){let n=t.toTextObject();e[n[_g.NAME]]=n}r.Attributes=e}return e.Data=r,e.Signature=new _g(``,{Algorithm:bg.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};A_=new WeakMap,j_=new WeakMap,M_=new WeakMap,N_=new WeakMap,P_=new WeakMap,F_=new WeakMap,I_=new WeakMap,L_=new WeakMap,R_.NAME=`PKCS#10 Certificate Request`;var z_,B_,V_,H_,U_,W_,G_,K_,q_,J_,Y_,X_,Z_=class extends Zg{get publicKey(){return rl(this,X_,`f`)||il(this,X_,new Qg(this.asn.tbsCertificate.subjectPublicKeyInfo),`f`),rl(this,X_,`f`)}get serialNumber(){if(!rl(this,B_,`f`)){let e=this.asn.tbsCertificate,t=new Uint8Array(e.serialNumber);t.length>1&&t[0]===0&&t[1]>127&&(t=t.slice(1)),il(this,B_,yi.ToHex(t),`f`)}return rl(this,B_,`f`)}get subjectName(){return rl(this,V_,`f`)||il(this,V_,new Ng(this.asn.tbsCertificate.subject),`f`),rl(this,V_,`f`)}get subject(){return rl(this,H_,`f`)||il(this,H_,this.subjectName.toString(),`f`),rl(this,H_,`f`)}get issuerName(){return rl(this,U_,`f`)||il(this,U_,new Ng(this.asn.tbsCertificate.issuer),`f`),rl(this,U_,`f`)}get issuer(){return rl(this,W_,`f`)||il(this,W_,this.issuerName.toString(),`f`),rl(this,W_,`f`)}get notBefore(){if(!rl(this,G_,`f`)){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw Error(`Cannot get 'notBefore' value`);il(this,G_,e,`f`)}return rl(this,G_,`f`)}get notAfter(){if(!rl(this,K_,`f`)){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw Error(`Cannot get 'notAfter' value`);il(this,K_,e,`f`)}return rl(this,K_,`f`)}get signatureAlgorithm(){if(!rl(this,q_,`f`)){let e=xm.resolve(Ih);il(this,q_,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return rl(this,q_,`f`)}get signature(){return rl(this,J_,`f`)||il(this,J_,this.asn.signatureValue,`f`),rl(this,J_,`f`)}get extensions(){return rl(this,Y_,`f`)||(il(this,Y_,[],`f`),this.asn.tbsCertificate.extensions&&il(this,Y_,this.asn.tbsCertificate.extensions.map(e=>c_.create(Y.serialize(e))),`f`)),rl(this,Y_,`f`)}get tbs(){return rl(this,z_,`f`)||il(this,z_,this.asn.tbsCertificateRaw||Y.serialize(this.asn.tbsCertificate),`f`),rl(this,z_,`f`)}constructor(e){let t=Zg.isAsnEncoded(e)?[e,id]:[e];super(t[0],t[1]),z_.set(this,void 0),B_.set(this,void 0),V_.set(this,void 0),H_.set(this,void 0),U_.set(this,void 0),W_.set(this,void 0),G_.set(this,void 0),K_.set(this,void 0),q_.set(this,void 0),J_.set(this,void 0),Y_.set(this,void 0),X_.set(this,void 0),this.tag=Xg.CertificateTag}onInit(e){}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e={},t=Eg.get()){let n,r,i=e.publicKey;try{if(!i)n={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(n,[`verify`],t);else if(`publicKey`in i)n={...i.publicKey.algorithm,...this.signatureAlgorithm},r=await i.publicKey.export(n,[`verify`],t);else if(i instanceof Qg)n={...i.algorithm,...this.signatureAlgorithm},r=await i.export(n,[`verify`],t);else if(U.isBufferSource(i)){let e=new Qg(i);n={...e.algorithm,...this.signatureAlgorithm},r=await e.export(n,[`verify`],t)}else n={...i.algorithm,...this.signatureAlgorithm},r=i}catch{return!1}let a=xm.resolveAll(y_).reverse(),o=null;for(let e of a)if(o=e.toWebSignature(n,this.signature),o)break;if(!o)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);let s=await t.subtle.verify(this.signatureAlgorithm,r,o,this.tbs);if(e.signatureOnly)return s;{let t=(e.date||new Date).getTime();return s&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=Eg.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=Eg.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,id),n=t.tbsCertificate,r=new _g(``,{Version:`${nd[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":bg.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new _g(``,{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(r[`Issuer Unique ID`]=n.issuerUniqueID),n.subjectUniqueID&&(r[`Subject Unique ID`]=n.subjectUniqueID),this.extensions.length){let e=new _g(``);for(let t of this.extensions){let n=t.toTextObject();e[n[_g.NAME]]=n}r.Extensions=e}return e.Data=r,e.Signature=new _g(``,{Algorithm:bg.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};z_=new WeakMap,B_=new WeakMap,V_=new WeakMap,H_=new WeakMap,U_=new WeakMap,W_=new WeakMap,G_=new WeakMap,K_=new WeakMap,q_=new WeakMap,J_=new WeakMap,Y_=new WeakMap,X_=new WeakMap,Z_.NAME=`Certificate`;function Q_(e,t=Eg.get()){let n=U.toUint8Array(yi.FromHex(e||``)),r=n&&n.length&&n.some(e=>e>0)?new Uint8Array(n):void 0;r||=t.getRandomValues(new Uint8Array(16));let i=0;for(;i<r.length-1&&r[i]===0;)i++;if(r=r.slice(i),r[0]>127){let e=new Uint8Array(r.length+1);e[0]=0,e.set(r,1),r=e}return r.buffer}var $_=class{static async createSelfSigned(e,t=Eg.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw 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},t)}static async create(e,t=Eg.get()){let n;n=e.publicKey instanceof Qg?e.publicKey.rawData:`publicKey`in e.publicKey?e.publicKey.publicKey.rawData:U.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey(`spki`,e.publicKey);let r=Q_(e.serialNumber,t),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),o=new id({tbsCertificate:new rd({version:nd.v3,serialNumber:r,validity:new Qu({notBefore:i,notAfter:a}),extensions:new td(e.extensions?.map(e=>Y.parse(e.rawData,ed))||[]),subjectPublicKeyInfo:Y.parse(n,Xu)})});if(e.subject){let t=e.subject instanceof Ng?e.subject:new Ng(e.subject);o.tbsCertificate.subject=Y.parse(t.toArrayBuffer(),ml)}if(e.issuer){let t=e.issuer instanceof Ng?e.issuer:new Ng(e.issuer);o.tbsCertificate.issuer=Y.parse(t.toArrayBuffer(),ml)}let s={hash:`SHA-256`},c=`signingKey`in e?{...s,...e.signingAlgorithm,...e.signingKey.algorithm}:{...s,...e.signingAlgorithm},l=xm.resolve(Ih);o.tbsCertificate.signature=o.signatureAlgorithm=l.toAsnAlgorithm(c);let u=Y.serialize(o.tbsCertificate),d=`signingKey`in e?await t.subtle.sign(c,e.signingKey,u):e.signature,f=xm.resolveAll(y_).reverse(),p=null;for(let e of f)if(p=e.toAsnSignature(c,d),p)break;if(!p)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return o.signatureValue=p,new Z_(Y.serialize(o))}},ev;(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(ev||={}),c_.register(Il,t_),c_.register(fu,r_),c_.register(Tu,a_),c_.register(Hu,o_),c_.register(Nl,e_),c_.register(Lu,s_),c_.register(eu,u_),c_.register(Al,d_),c_.register(Cu,m_),v_.register(ih,g_),v_.register(ah,__),xm.registerSingleton(y_,b_),xm.registerSingleton(y_,w_),w_.namedCurveSize.set(`P-256`,32),w_.namedCurveSize.set(`K-256`,32),w_.namedCurveSize.set(`P-384`,48),w_.namedCurveSize.set(`P-521`,66);var tv=R(((e,t)=>{function n(e){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(e)}t.exports=n})),nv=R(((e,t)=>{for(var n=te(`util`),r=tv(),i=/[\{\[]/,a=/[\}\]]/,o=`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`.split(`.`),s={},c=0;c<o.length;c++)s[o[c]]=!0;var l=function(e){return r(e)&&!s.hasOwnProperty(e)},u={s:function(e){return``+e},d:function(e){return``+Number(e)},o:function(e){return JSON.stringify(e)}},d=function(){var e=[],t=0,o={},s=function(n){for(var r=``;r.length<t*2;)r+=` `;e.push(r+n)},c=function(e){if(a.test(e.trim()[0])&&i.test(e[e.length-1])){t--,s(e),t++;return}if(i.test(e[e.length-1])){s(e),t++;return}if(a.test(e.trim()[0])){t--,s(e);return}s(e)},d=function(e){if(!e)return d;if(arguments.length===1&&e.indexOf(`
|
|
38
|
+
`)}function Jx(e,t,n){var r=Ax(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return qx(`Cannot inject the dependency `+Kx(r===void 0?null:r,t)+` of "`+e.name+`" constructor. Reason:`,n)}function Yx(e){return!(typeof e.dispose!=`function`||e.dispose.length>0)}var Xx=function(e){Ex(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Ux),Zx=function(e){Ex(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Ux),Qx=function(){function e(){this.preResolution=new Xx,this.postResolution=new Zx}return e}(),$x=new Map,eS=new(function(){function e(e){this.parent=e,this._registry=new Wx,this.interceptors=new Qx,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,n){n===void 0&&(n={lifecycle:wx.Transient}),this.ensureNotDisposed();var r=Hx(t)?t:{useClass:t};if(Bx(r))for(var i=[e],a=r;a!=null;){var o=a.useToken;if(i.includes(o))throw Error(`Token registration cycle detected! `+jx(i,[o]).join(` -> `));i.push(o);var s=this._registry.get(o);a=s&&Bx(s.provider)?s.provider:null}if((n.lifecycle===wx.Singleton||n.lifecycle==wx.ContainerScoped||n.lifecycle==wx.ResolutionScoped)&&(Vx(r)||Px(r)))throw Error(`Cannot use lifecycle "`+wx[n.lifecycle]+`" with ValueProviders or FactoryProviders`);return this._registry.set(e,{provider:r,options:n}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),Ix(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},e.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},e.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),Ix(e)){if(Ix(t))return this.register(e,{useToken:t},{lifecycle:wx.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:wx.Singleton});throw Error(`Cannot register a type name as a singleton without a "to" token`)}var n=e;return t&&!Ix(t)&&(n=t),this.register(e,{useClass:n},{lifecycle:wx.Singleton})},e.prototype.resolve=function(e,t,n){t===void 0&&(t=new Gx),n===void 0&&(n=!1),this.ensureNotDisposed();var r=this.getRegistration(e);if(!r&&Ix(e)){if(n)return;throw Error(`Attempted to resolve unregistered dependency token: "`+e.toString()+`"`)}if(this.executePreResolutionInterceptor(e,`Single`),r){var i=this.resolveRegistration(r,t);return this.executePostResolutionInterceptor(e,i,`Single`),i}if(zx(e)){var i=this.construct(e,t);return this.executePostResolutionInterceptor(e,i,`Single`),i}throw Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,t){var n,r;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var a=kx(this.interceptors.preResolution.getAll(e)),o=a.next();!o.done;o=a.next()){var s=o.value;s.options.frequency!=`Once`&&i.push(s),s.callback(e,t)}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,t,n){var r,i;if(this.interceptors.postResolution.has(e)){var a=[];try{for(var o=kx(this.interceptors.postResolution.getAll(e)),s=o.next();!s.done;s=o.next()){var c=s.value;c.options.frequency!=`Once`&&a.push(c),c.callback(e,t,n)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}this.interceptors.postResolution.setAll(e,a)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===wx.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var n=e.options.lifecycle===wx.Singleton,r=e.options.lifecycle===wx.ContainerScoped,i=n||r,a=Vx(e.provider)?e.provider.useValue:Bx(e.provider)?i?e.instance||=this.resolve(e.provider.useToken,t):this.resolve(e.provider.useToken,t):Nx(e.provider)?i?e.instance||=this.construct(e.provider.useClass,t):this.construct(e.provider.useClass,t):Px(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t);return e.options.lifecycle===wx.ResolutionScoped&&t.scopedResolutions.set(e,a),a},e.prototype.resolveAll=function(e,t,n){var r=this;t===void 0&&(t=new Gx),n===void 0&&(n=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&Ix(e)){if(n)return[];throw Error(`Attempted to resolve unregistered dependency token: "`+e.toString()+`"`)}if(this.executePreResolutionInterceptor(e,`All`),i){var a=i.map(function(e){return r.resolveRegistration(e,t)});return this.executePostResolutionInterceptor(e,a,`All`),a}var o=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,o,`All`),o},e.prototype.isRegistered=function(e,t){return t===void 0&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var n=kx(this._registry.entries()),r=n.next();!r.done;r=n.next()){var i=Ax(r.value,2),a=i[0],o=i[1];this._registry.setAll(a,o.filter(function(e){return!Vx(e.provider)}).map(function(e){return e.instance=void 0,e}))}}catch(t){e={error:t}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){var t,n;this.ensureNotDisposed();var r=new e(this);try{for(var i=kx(this._registry.entries()),a=i.next();!a.done;a=i.next()){var o=Ax(a.value,2),s=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===wx.ContainerScoped})&&r._registry.setAll(s,c.map(function(e){return e.options.lifecycle===wx.ContainerScoped?{provider:e.provider,options:e.options}:e}))}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return r},e.prototype.beforeResolution=function(e,t,n){n===void 0&&(n={frequency:`Always`}),this.interceptors.preResolution.set(e,{callback:t,options:n})},e.prototype.afterResolution=function(e,t,n){n===void 0&&(n={frequency:`Always`}),this.interceptors.postResolution.set(e,{callback:t,options:n})},e.prototype.dispose=function(){return Dx(this,void 0,void 0,function(){var e;return Ox(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(t){var n=t.dispose();n&&e.push(n)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var n=this;if(e instanceof Fx)return e.createProxy(function(e){return n.resolve(e,t)});var r=(function(){var r=$x.get(e);if(!r||r.length===0){if(e.length===0)return new e;throw Error(`TypeInfo not known for "`+e.name+`"`)}var i=r.map(n.resolveParams(t,e));return new(e.bind.apply(e,jx([void 0],i)))})();return Yx(r)&&this.disposables.add(r),r},e.prototype.resolveParams=function(e,t){var n=this;return function(r,i){var a,o,s;try{return Lx(r)?Rx(r)?r.multiple?(a=n.resolve(r.transform)).transform.apply(a,jx([n.resolveAll(r.token,new Gx,r.isOptional)],r.transformArgs)):(o=n.resolve(r.transform)).transform.apply(o,jx([n.resolve(r.token,e,r.isOptional)],r.transformArgs)):r.multiple?n.resolveAll(r.token,new Gx,r.isOptional):n.resolve(r.token,e,r.isOptional):Rx(r)?(s=n.resolve(r.transform,e)).transform.apply(s,jx([n.resolve(r.token,e)],r.transformArgs)):n.resolve(r,e)}catch(e){throw Error(Jx(t,i,e))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw Error(`This container has been disposed, you cannot interact with a disposed container`)},e}());function tS(e){return function(t){$x.set(t,Mx(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){eS.register(e,t)}):eS.register(e.token,t))}}if(typeof Reflect>`u`||!Reflect.getMetadata)throw Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var nS,rS=class{attrId=``;attrValues=[];constructor(e={}){Object.assign(e)}};X([J({type:K.ObjectIdentifier})],rS.prototype,`attrId`,void 0),X([J({type:K.Any,repeated:`set`})],rS.prototype,`attrValues`,void 0);var iS=nS=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,nS.prototype)}};iS=nS=X([q({type:G.Sequence,itemType:rS})],iS);var aS,oS=aS=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,aS.prototype)}};oS=aS=X([q({type:G.Sequence,itemType:Ly})],oS);var sS=`1.2.840.113549.1.12`,cS=`${sS}.1`;`${cS}`,`${cS}`,`${cS}`,`${cS}`,`${cS}`,`${cS}`;var lS=`${sS}.10.1`;`${lS}`,`${lS}`,`${lS}`,`${lS}`,`${lS}`,`${lS}`;var uS=`1.2.840.113549.1.9`,dS=class{certId=``;certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],dS.prototype,`certId`,void 0),X([J({type:K.Any,context:0})],dS.prototype,`certValue`,void 0);var fS=`${uS}.22`;`${fS}`,`${fS}`;var pS=class{crlId=``;crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],pS.prototype,`crlId`,void 0),X([J({type:K.Any,context:0})],pS.prototype,`crltValue`,void 0),`${uS}`;var mS=class extends tg{},hS=class{encryptionAlgorithm=new Z;encryptedData=new mS;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],hS.prototype,`encryptionAlgorithm`,void 0),X([J({type:mS})],hS.prototype,`encryptedData`,void 0);var gS,_S;(function(e){e[e.v1=0]=`v1`})(_S||={});var vS=class extends tg{},yS=gS=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,gS.prototype)}};yS=gS=X([q({type:G.Sequence,itemType:yv})],yS);var bS=class{version=_S.v1;privateKeyAlgorithm=new Z;privateKey=new vS;attributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],bS.prototype,`version`,void 0),X([J({type:Z})],bS.prototype,`privateKeyAlgorithm`,void 0),X([J({type:vS})],bS.prototype,`privateKey`,void 0),X([J({type:yS,implicit:!0,context:0,optional:!0})],bS.prototype,`attributes`,void 0);var xS=class extends bS{};xS=X([q({type:G.Sequence})],xS);var SS=class extends hS{};SS=X([q({type:G.Sequence})],SS);var CS=class{secretTypeId=``;secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],CS.prototype,`secretTypeId`,void 0),X([J({type:K.Any,context:0})],CS.prototype,`secretValue`,void 0);var wS=class{mac=new _x;macSalt=new tg;iterations=1;constructor(e={}){Object.assign(this,e)}};X([J({type:_x})],wS.prototype,`mac`,void 0),X([J({type:tg})],wS.prototype,`macSalt`,void 0),X([J({type:K.Integer,defaultValue:1})],wS.prototype,`iterations`,void 0);var TS=class{version=3;authSafe=new Ly;macData=new wS;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],TS.prototype,`version`,void 0),X([J({type:Ly})],TS.prototype,`authSafe`,void 0),X([J({type:wS,optional:!0})],TS.prototype,`macData`,void 0);var ES,DS=class{bagId=``;bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],DS.prototype,`bagId`,void 0),X([J({type:K.Any,context:0})],DS.prototype,`bagValue`,void 0),X([J({type:rS,repeated:`set`,optional:!0})],DS.prototype,`bagAttributes`,void 0);var OS=ES=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,ES.prototype)}};OS=ES=X([q({type:G.Sequence,itemType:DS})],OS);var kS,AS,jS,MS=`1.2.840.113549.1.9`;`${MS}`;var NS=`${MS}.24`,PS=`${MS}.25`,FS=`${MS}.26`,IS=`${MS}.27`;`${NS}`,`${NS}`,`${MS}`,`${MS}`,`${MS}`,`${MS}`,`${MS}`,`${MS}`;var LS=`${MS}.7`;`${MS}`,`${MS}`,`${MS}`;var RS=`${MS}.14`;`${MS}`,`${MS}`,`${MS}`,`${PS}`,`${PS}`,`${PS}`,`${PS}`,`${PS}`;var zS=`1.3.6.1.5.5.7.9`;`${zS}`,`${zS}`,`${zS}`,`${zS}`,`${zS}`,`${FS}`,`${FS}`,`${IS}`,`${IS}`,`${MS}`,`${MS}`,`${MS}`,`${wy}`;var BS=class extends Ug{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};X([J({type:K.IA5String})],BS.prototype,`ia5String`,void 0),BS=X([q({type:G.Choice})],BS);var VS=class extends Ly{};VS=X([q({type:G.Sequence})],VS);var HS=class extends TS{};HS=X([q({type:G.Sequence})],HS);var US=class extends hS{};US=X([q({type:G.Sequence})],US);var WS=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.IA5String})],WS.prototype,`value`,void 0),WS=X([q({type:G.Choice})],WS);var GS=class extends BS{};GS=X([q({type:G.Choice})],GS);var KS=class extends Ug{};KS=X([q({type:G.Choice})],KS);var qS=class{value;constructor(e=new Date){this.value=e}};X([J({type:K.GeneralizedTime})],qS.prototype,`value`,void 0),qS=X([q({type:G.Choice})],qS);var JS=class extends Ug{};JS=X([q({type:G.Choice})],JS);var YS=class{value;constructor(e=`M`){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],YS.prototype,`value`,void 0),YS=X([q({type:G.Choice})],YS);var XS=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],XS.prototype,`value`,void 0),XS=X([q({type:G.Choice})],XS);var ZS=class extends XS{};ZS=X([q({type:G.Choice})],ZS);var QS=class extends Ug{};QS=X([q({type:G.Choice})],QS);var $S=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.ObjectIdentifier})],$S.prototype,`value`,void 0),$S=X([q({type:G.Choice})],$S);var eC=class extends jv{};eC=X([q({type:G.Choice})],eC);var tC=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};X([J({type:K.Integer})],tC.prototype,`value`,void 0),tC=X([q({type:G.Choice})],tC);var nC=class extends $v{};nC=X([q({type:G.Sequence})],nC);var rC=class extends Ug{};rC=X([q({type:G.Choice})],rC);var iC=kS=class extends Fv{constructor(e){super(e),Object.setPrototypeOf(this,kS.prototype)}};iC=kS=X([q({type:G.Sequence})],iC);var aC=AS=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,AS.prototype)}};aC=AS=X([q({type:G.Set,itemType:Zv})],aC);var oC=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.BmpString})],oC.prototype,`value`,void 0),oC=X([q({type:G.Choice})],oC);var sC=class extends Z{};sC=X([q({type:G.Sequence})],sC);var cC=jS=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,jS.prototype)}};cC=jS=X([q({type:G.Sequence,itemType:sC})],cC);var lC,uC=lC=class extends Ig{constructor(e){super(e),Object.setPrototypeOf(this,lC.prototype)}};uC=lC=X([q({type:G.Sequence,itemType:yv})],uC);var dC=class{version=0;subject=new Jg;subjectPKInfo=new Av;attributes=new uC;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],dC.prototype,`version`,void 0),X([J({type:Jg})],dC.prototype,`subject`,void 0),X([J({type:Av})],dC.prototype,`subjectPKInfo`,void 0),X([J({type:uC,implicit:!0,context:0,optional:!0})],dC.prototype,`attributes`,void 0);var fC=class{certificationRequestInfo=new dC;certificationRequestInfoRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:dC,raw:!0})],fC.prototype,`certificationRequestInfo`,void 0),X([J({type:Z})],fC.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],fC.prototype,`signature`,void 0);var pC=`crypto.algorithm`,mC=class{getAlgorithms(){return eS.resolveAll(pC)}toAsnAlgorithm(e){({...e});for(let t of this.getAlgorithms()){let n=t.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){let t=new Z({algorithm:e.name});return`parameters`in e&&(t.parameters=e.parameters),t}throw Error(`Cannot convert WebCrypto algorithm to ASN.1 algorithm`)}toWebAlgorithm(e){for(let t of this.getAlgorithms()){let n=t.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}},hC=`crypto.algorithmProvider`;eS.registerSingleton(hC,mC);var gC,_C=`1.3.36.3.3.2.8.1.1`,vC=`${_C}.1`,yC=`${_C}.2`,bC=`${_C}.3`,xC=`${_C}.4`,SC=`${_C}.5`,CC=`${_C}.6`,wC=`${_C}.7`,TC=`${_C}.8`,EC=`${_C}.9`,DC=`${_C}.10`,OC=`${_C}.11`,kC=`${_C}.12`,AC=`${_C}.13`,jC=`${_C}.14`,MC=`brainpoolP160r1`,NC=`brainpoolP160t1`,PC=`brainpoolP192r1`,FC=`brainpoolP192t1`,IC=`brainpoolP224r1`,LC=`brainpoolP224t1`,RC=`brainpoolP256r1`,zC=`brainpoolP256t1`,BC=`brainpoolP320r1`,VC=`brainpoolP320t1`,HC=`brainpoolP384r1`,UC=`brainpoolP384t1`,WC=`brainpoolP512r1`,GC=`brainpoolP512t1`,KC=`ECDSA`,qC=gC=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case KC.toLowerCase():if(`hash`in e)switch((typeof e.hash==`string`?e.hash:e.hash.name).toLowerCase()){case`sha-1`:return kb;case`sha-256`:return Ab;case`sha-384`:return jb;case`sha-512`:return Mb}else if(`namedCurve`in e){let t=``;switch(e.namedCurve){case`P-256`:t=Tb;break;case`K-256`:t=gC.SECP256K1;break;case`P-384`:t=Eb;break;case`P-521`:t=Db;break;case MC:t=vC;break;case NC:t=yC;break;case PC:t=bC;break;case FC:t=xC;break;case IC:t=SC;break;case LC:t=CC;break;case RC:t=wC;break;case zC:t=TC;break;case BC:t=EC;break;case VC:t=DC;break;case HC:t=OC;break;case UC:t=kC;break;case WC:t=AC;break;case GC:t=jC}if(t)return new Z({algorithm:yb,parameters:Y.serialize(new Rb({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case bb:return{name:KC,hash:{name:`SHA-1`}};case Sb:return{name:KC,hash:{name:`SHA-256`}};case Cb:return{name:KC,hash:{name:`SHA-384`}};case wb:return{name:KC,hash:{name:`SHA-512`}};case yb:if(!e.parameters)throw TypeError(`Cannot get required parameters from EC algorithm`);switch(Y.parse(e.parameters,Rb).namedCurve){case Tb:return{name:KC,namedCurve:`P-256`};case gC.SECP256K1:return{name:KC,namedCurve:`K-256`};case Eb:return{name:KC,namedCurve:`P-384`};case Db:return{name:KC,namedCurve:`P-521`};case vC:return{name:KC,namedCurve:MC};case yC:return{name:KC,namedCurve:NC};case bC:return{name:KC,namedCurve:PC};case xC:return{name:KC,namedCurve:FC};case SC:return{name:KC,namedCurve:IC};case CC:return{name:KC,namedCurve:LC};case wC:return{name:KC,namedCurve:RC};case TC:return{name:KC,namedCurve:zC};case EC:return{name:KC,namedCurve:BC};case DC:return{name:KC,namedCurve:VC};case OC:return{name:KC,namedCurve:HC};case kC:return{name:KC,namedCurve:UC};case AC:return{name:KC,namedCurve:WC};case jC:return{name:KC,namedCurve:GC}}}return null}};qC.SECP256K1=`1.3.132.0.10`,qC=gC=X([tS()],qC),eS.registerSingleton(pC,qC);var JC=Symbol(`name`),YC=Symbol(`value`),XC=class{constructor(e,t={},n=``){this[JC]=e,this[YC]=n;for(let e in t)this[e]=t[e]}};XC.NAME=JC,XC.VALUE=YC;var ZC=class{static toTextObject(e){let t=new XC(`Algorithm Identifier`,{},QC.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case yb:{let n=new qC().toWebAlgorithm(e);n&&`namedCurve`in n?t[`Named Curve`]=n.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}},QC=class{static toString(e){return this.items[e]||e}};QC.items={[tx]:`sha1`,[nx]:`sha224`,[rx]:`sha256`,[ix]:`sha384`,[ax]:`sha512`,[Hb]:`rsaEncryption`,[Jb]:`sha1WithRSAEncryption`,[Yb]:`sha224WithRSAEncryption`,[Xb]:`sha256WithRSAEncryption`,[Zb]:`sha384WithRSAEncryption`,[Qb]:`sha512WithRSAEncryption`,[yb]:`ecPublicKey`,[bb]:`ecdsaWithSHA1`,[xb]:`ecdsaWithSHA224`,[Sb]:`ecdsaWithSHA256`,[Cb]:`ecdsaWithSHA384`,[wb]:`ecdsaWithSHA512`,[J_]:`TLS WWW server authentication`,[Y_]:`TLS WWW client authentication`,[X_]:`Code Signing`,[Z_]:`E-mail Protection`,[Q_]:`Time Stamping`,[$_]:`OCSP Signing`,[hb]:`Signed Data`};var $C=class{static serialize(e){return this.serializeObj(e).join(`
|
|
39
|
+
`)}static pad(e=0){return``.padStart(2*e,` `)}static serializeObj(e,t=0){let n=[],r=this.pad(t++),i=``,a=e[XC.VALUE];a&&(i=` ${a}`),n.push(`${r}${e[XC.NAME]}:${i}`),r=this.pad(t);for(let i in e){if(typeof i==`symbol`)continue;let a=e[i],o=i?`${i}: `:``;if(typeof a==`string`||typeof a==`number`||typeof a==`boolean`)n.push(`${r}${o}${a}`);else if(a instanceof Date)n.push(`${r}${o}${a.toUTCString()}`);else if(Array.isArray(a))for(let e of a)e[XC.NAME]=i,n.push(...this.serializeObj(e,t));else if(a instanceof XC)a[XC.NAME]=i,n.push(...this.serializeObj(a,t));else if(U.isBufferSource(a))i?(n.push(`${r}${o}`),n.push(...this.serializeBufferSource(a,t+1))):n.push(...this.serializeBufferSource(a,t));else if(`toTextObject`in a){let e=a.toTextObject();e[XC.NAME]=i,n.push(...this.serializeObj(e,t))}else throw TypeError(`Cannot serialize data in text format. Unsupported type.`)}return n}static serializeBufferSource(e,t=0){let n=this.pad(t),r=U.toUint8Array(e),i=[];for(let e=0;e<r.length;){let t=[];for(let n=0;n<16&&e<r.length;n++){n===8&&t.push(``);let i=r[e++].toString(16).padStart(2,`0`);t.push(i)}i.push(`${n}${t.join(` `)}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};$C.oidSerializer=QC,$C.algorithmSerializer=ZC;var ew,tw=class e{get rawData(){return Lg(this,ew,`f`)||Rg(this,ew,Y.serialize(this.asn),`f`),Lg(this,ew,`f`)}constructor(...e){ew.set(this,void 0),U.isBufferSource(e[0])?(this.asn=Y.parse(e[0],e[1]),Rg(this,ew,U.toArrayBuffer(e[0]),`f`),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(t){return t instanceof e&&tf(t.rawData,this.rawData)}toString(e=`text`){switch(e){case`asn`:return Y.toString(this.rawData);case`text`:return $C.serialize(this.toTextObject());case`hex`:return $d.ToHex(this.rawData);case`base64`:return $d.ToBase64(this.rawData);case`base64url`:return $d.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 XC(this.getTextName(),{},e)}};ew=new WeakMap,tw.NAME=`ASN`;var nw=class e extends tw{constructor(...e){let t;t=U.isBufferSource(e[0])?U.toArrayBuffer(e[0]):Y.serialize(new Pv({extnID:e[0],critical:e[1],extnValue:new tg(U.toArrayBuffer(e[2]))})),super(t,Pv)}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 t=this.toTextObjectEmpty(this.critical?`critical`:void 0);return t[XC.NAME]===e.NAME&&(t[XC.NAME]=QC.toString(this.type)),t}},rw,iw=class e{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[rw]=`CryptoProvider`,typeof self<`u`&&typeof crypto<`u`?this.set(e.DEFAULT,crypto):typeof global<`u`&&global.crypto&&global.crypto.subtle&&this.set(e.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}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(t=e.DEFAULT){let n=this.items.get(t.toLowerCase());if(!n)throw Error(`Cannot get Crypto by name '${t}'`);return n}set(t,n){if(typeof t==`string`){if(!n)throw TypeError(`Argument 'value' is required`);this.items.set(t.toLowerCase(),n)}else this.items.set(e.DEFAULT,t);return this}};rw=Symbol.toStringTag,iw.DEFAULT=`default`;var aw=new iw,ow=/^[0-2](?:\.[1-9][0-9]*)+$/;function sw(e){return new RegExp(ow).test(e)}var cw=class{constructor(e={}){this.items={};for(let t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return sw(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},lw=new cw;lw.register(`CN`,`2.5.4.3`),lw.register(`L`,`2.5.4.7`),lw.register(`ST`,`2.5.4.8`),lw.register(`O`,`2.5.4.10`),lw.register(`OU`,`2.5.4.11`),lw.register(`C`,`2.5.4.6`),lw.register(`DC`,`0.9.2342.19200300.100.1.25`),lw.register(`E`,`1.2.840.113549.1.9.1`),lw.register(`G`,`2.5.4.42`),lw.register(`I`,`2.5.4.43`),lw.register(`SN`,`2.5.4.4`),lw.register(`T`,`2.5.4.12`);function uw(e,t){return`\\${$d.ToHex($d.FromUtf8String(t)).toUpperCase()}`}function dw(e){return e.replace(/([,+"\\<>;])/g,`\\$1`).replace(/^([ #])/,`\\$1`).replace(/([ ]$)/,`\\$1`).replace(/([\r\n\t])/,uw)}var fw=class e{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new cw,this.asn=new Jg;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];this.extraNames.register(e,n)}this.asn=typeof e==`string`?this.fromString(e):e instanceof Jg?e:U.isBufferSource(e)?Y.parse(e,Jg):this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||lw.findId(e),n=[];for(let e of this.asn)for(let r of e)r.type===t&&n.push(r.value.toString());return n}getName(e){return this.extraNames.get(e)||lw.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${$d.ToHex(e.value.anyValue)}`:dw(e.value.toString())}`).join(`+`)).join(`, `)}toJSON(){let e=[];for(let t of this.asn){let n={};for(let e of t){let t=this.getName(e.type)||e.type;n[t]??(n[t]=[]),n[t].push(e.value.anyValue?`#${$d.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(n)}return e}fromString(e){let t=new Jg,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,r=null,i=`,`;for(;r=n.exec(`${e},`);){let[,e,n]=r,a=n[n.length-1];(a===`,`||a===`+`)&&(n=n.slice(0,n.length-1),r[3]=a);let o=r[3];e=this.getTypeOid(e);let s=this.createAttribute(e,n);i===`+`?t[t.length-1].push(s):t.push(new Kg([s])),i=o}return t}fromJSON(e){let t=new Jg;for(let n of e){let e=new Kg;for(let t in n){let r=this.getTypeOid(t),i=n[t];for(let t of i){let n=this.createAttribute(r,t);e.push(n)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||``),!e)throw Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(t,n){let r=new Gg({type:t});if(typeof n==`object`)for(let e in n)switch(e){case`ia5String`:r.value.ia5String=n[e];break;case`utf8String`:r.value.utf8String=n[e];break;case`universalString`:r.value.universalString=n[e];break;case`bmpString`:r.value.bmpString=n[e];break;case`printableString`:r.value.printableString=n[e]}else if(n[0]===`#`)r.value.anyValue=$d.FromHex(n.slice(1));else{let i=this.processStringValue(n);t===this.getName(`E`)||t===this.getName(`DC`)?r.value.ia5String=i:e.isPrintableString(i)?r.value.printableString=i:r.value.utf8String=i}return r}processStringValue(e){let t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,`
|
|
40
|
+
`).replace(/\\0d/gi,`\r`).replace(/\\0g/gi,` `).replace(/\\(.)/g,`$1`)}toArrayBuffer(){return Y.serialize(this.asn)}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||aw.get()):t=e[0]||aw.get(),await t.subtle.digest(n,this.toArrayBuffer())}},pw=`Cannot initialize GeneralName from ASN.1 data.`,mw=`${pw} Unsupported string format in use.`,hw=`${pw} Value doesn't match to GUID regular expression.`,gw=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,_w=`1.3.6.1.4.1.311.25.1`,vw=`1.3.6.1.4.1.311.20.2.3`,yw=`email`,bw=`guid`,xw=class extends tw{constructor(...e){let t;if(e.length===2)switch(e[0]){case`dn`:{let n=new fw(e[1]).toArrayBuffer(),r=Y.parse(n,Jg);t=new Qg({directoryName:r});break}case`dns`:t=new Qg({dNSName:e[1]});break;case yw:t=new Qg({rfc822Name:e[1]});break;case bw:{let n=new RegExp(gw,`i`).exec(e[1]);if(!n)throw Error(`Cannot parse GUID value. Value doesn't match to regular expression`);let r=n.slice(1).map((e,t)=>t<3?$d.ToHex(new Uint8Array($d.FromHex(e)).reverse()):e).join(``);t=new Qg({otherName:new Xg({typeId:_w,value:Y.serialize(new tg($d.FromHex(r)))})});break}case`ip`:t=new Qg({iPAddress:e[1]});break;case`id`:t=new Qg({registeredID:e[1]});break;case`upn`:t=new Qg({otherName:new Xg({typeId:vw,value:Y.serialize(pg.toASN(e[1]))})});break;case`url`:t=new Qg({uniformResourceIdentifier:e[1]});break;default:throw Error(`Cannot create GeneralName. Unsupported type of the name`)}else t=U.isBufferSource(e[0])?Y.parse(e[0],Qg):e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=`dns`,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=yw,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=`ip`,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=`url`,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=`id`,this.value=e.registeredID;else if(e.directoryName!=null)this.type=`dn`,this.value=new fw(e.directoryName).toString();else if(e.otherName!=null){if(e.otherName.typeId===_w){this.type=bw;let t=Y.parse(e.otherName.value,tg),n=new RegExp(gw,`i`).exec($d.ToHex(t));if(!n)throw Error(hw);this.value=n.slice(1).map((e,t)=>t<3?$d.ToHex(new Uint8Array($d.FromHex(e)).reverse()):e).join(`-`)}else if(e.otherName.typeId===vw)this.type=`upn`,this.value=Y.parse(e.otherName.value,Ug).toString();else throw Error(mw)}else throw Error(mw)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case`dn`:case`dns`:case bw:case`ip`:case`id`:case`upn`:case`url`:e=this.type.toUpperCase();break;case yw:e=`Email`;break;default:throw Error(`Unsupported GeneralName type`)}let t=this.value;return this.type===`id`&&(t=QC.toString(t)),new XC(e,void 0,t)}},Sw=class extends tw{constructor(e){let t;if(e instanceof y_)t=e;else if(Array.isArray(e)){let n=[];for(let t of e)if(t instanceof Qg)n.push(t);else{let e=Y.parse(new xw(t.type,t.value).rawData,Qg);n.push(e)}t=new y_(n)}else if(U.isBufferSource(e))t=Y.parse(e,y_);else throw Error(`Cannot initialize GeneralNames. Incorrect incoming arguments`);super(t)}onInit(e){let t=[];for(let n of e){let e=null;try{e=new xw(n)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let t of this.items){let n=t.toTextObject(),r=e[n[XC.NAME]];Array.isArray(r)||(r=[],e[n[XC.NAME]]=r),r.push(n)}return e}};Sw.NAME=`GeneralNames`;var Cw=`-{5}`,ww=`\\n`,Tw=`${Cw}BEGIN (${`[^${ww}]+`}(?=${Cw}))${Cw}`,Ew=`${Cw}END \\1${Cw}`,Dw=`\\n`,Ow=`${Tw}${Dw}(?:((?:${`[^:${ww}]+`}: ${`(?:[^${ww}]+${Dw}(?: +[^${ww}]+${Dw})*)`})+))?${Dw}?(${`(?:[a-zA-Z0-9=+/]+${Dw})+`})${Ew}`,kw=class{static isPem(e){return typeof e==`string`&&new RegExp(Ow,`g`).test(e.replace(/\r/g,``))}static decodeWithHeaders(e){e=e.replace(/\r/g,``);let t=new RegExp(Ow,`g`),n=[],r=null;for(;r=t.exec(e);){let e=r[3].replace(RegExp(`[${ww}]+`,`g`),``),t={type:r[1],headers:[],rawData:$d.FromBase64(e)},i=r[2];if(i){let e=i.split(new RegExp(Dw,`g`)),n=null;for(let r of e){let[e,i]=r.split(/:(.*)/);if(i===void 0){if(!n)throw Error(`Cannot parse PEM string. Incorrect header value`);n.value+=e.trim()}else n&&t.headers.push(n),n={key:e,value:i.trim()}}n&&t.headers.push(n)}n.push(t)}return n}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){let t=this.decode(e);if(!t.length)throw RangeError(`PEM string doesn't contain any objects`);return t[0]}static encode(e,t){if(Array.isArray(e)){let n=[];return t?e.forEach(e=>{if(!U.isBufferSource(e))throw TypeError(`Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource`);n.push(this.encodeStruct({type:t,rawData:U.toArrayBuffer(e)}))}):e.forEach(e=>{if(!(`type`in e))throw TypeError(`Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut`);n.push(this.encodeStruct(e))}),n.join(`
|
|
41
|
+
`)}if(!t)throw Error(`Required argument 'tag' is missed`);return this.encodeStruct({type:t,rawData:U.toArrayBuffer(e)})}static encodeStruct(e){let t=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${t}-----`),e.headers?.length){for(let t of e.headers)n.push(`${t.key}: ${t.value}`);n.push(``)}let r=$d.ToBase64(e.rawData),i,a=0,o=[];for(;a<r.length&&(r.length-a<64?i=r.substring(a):(i=r.substring(a,a+64),a+=64),i.length!==0)&&(o.push(i),!(i.length<64)););return n.push(...o),n.push(`-----END ${t}-----`),n.join(`
|
|
42
|
+
`)}};kw.CertificateTag=`CERTIFICATE`,kw.CrlTag=`CRL`,kw.CertificateRequestTag=`CERTIFICATE REQUEST`,kw.PublicKeyTag=`PUBLIC KEY`,kw.PrivateKeyTag=`PRIVATE KEY`;var Aw=class e extends tw{static isAsnEncoded(e){return U.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(kw.isPem(e))return kw.decode(e)[0];if($d.isHex(e))return $d.FromHex(e);if($d.isBase64(e))return $d.FromBase64(e);if($d.isBase64Url(e))return $d.FromBase64Url(e);throw TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}{let t=U.toUint8Array(e);if(t.length>0&&t[0]===48)return U.toArrayBuffer(e);let n=$d.ToBinary(e);if(kw.isPem(n))return kw.decode(n)[0];if($d.isHex(n))return $d.FromHex(n);if($d.isBase64(n))return $d.FromBase64(n);if($d.isBase64Url(n))return $d.FromBase64Url(n);throw TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}}constructor(...t){e.isAsnEncoded(t[0])?super(e.toArrayBuffer(t[0]),t[1]):super(t[0])}toString(e=`pem`){switch(e){case`pem`:return kw.encode(this.rawData,this.tag);default:return super.toString(e)}}},jw=class e extends Aw{static async create(t,n=aw.get()){if(t instanceof e)return t;if(iw.isCryptoKey(t)){if(t.type!==`public`)throw TypeError(`Public key is required`);let r=await n.subtle.exportKey(`spki`,t);return new e(r)}if(t.publicKey)return t.publicKey;if(U.isBufferSource(t))return new e(t);throw TypeError(`Unsupported PublicKeyType`)}constructor(e){Aw.isAsnEncoded(e)?super(e,Av):super(e),this.tag=kw.PublicKeyTag}async export(...e){let t,n=[`verify`],r={hash:`SHA-256`,...this.algorithm};e.length>1?(r=e[0]||r,n=e[1]||n,t=e[2]||aw.get()):t=e[0]||aw.get();let i=this.rawData,a=Y.parse(this.rawData,Av);return a.algorithm.algorithm===Gb&&(i=Mw(a,i)),t.subtle.importKey(`spki`,i,r,!0,n)}onInit(e){let t=eS.resolve(hC),n=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case Hb:{let t=Y.parse(e.subjectPublicKey,Sx),r=U.toUint8Array(t.modulus);n.publicExponent=U.toUint8Array(t.publicExponent),n.modulusLength=(r[0]?r:r.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||aw.get()):t=e[0]||aw.get(),await t.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,n=`SHA-1`;e.length===1?typeof e[0]==`string`?(n=e[0],t=aw.get()):t=e[0]:e.length===2?(n=e[0],t=e[1]):t=aw.get();let r=Y.parse(this.rawData,Av);return await t.subtle.digest(n,r.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,Av);switch(e.Algorithm=$C.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case yb:e[`EC Point`]=t.subjectPublicKey;break;case Hb:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function Mw(e,t){return e.algorithm=new Z({algorithm:Hb,parameters:null}),t=Y.serialize(e),t}var Nw=class e extends nw{static async create(t,n=!1,r=aw.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let i=await(await jw.create(t,r)).getKeyIdentifier(r);return new e($d.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new h_({keyIdentifier:new m_($d.FromHex(e[0]))});super(p_,e[1],Y.serialize(t))}else{let t=e[0],n=new h_({authorityCertIssuer:t.name instanceof Sw?Y.parse(t.name.rawData,y_):t.name,authorityCertSerialNumber:$d.FromHex(t.serialNumber)});super(p_,e[1],Y.serialize(n))}}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,h_);t.keyIdentifier&&(this.keyId=$d.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?$d.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=Y.parse(this.value,h_);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new Sw(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};Nw.NAME=`Authority Key Identifier`;var Pw=class extends nw{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,__);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new __({cA:e[0],pathLenConstraint:e[1]});super(g_,e[2],Y.serialize(t)),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}};Pw.NAME=`Basic Constraints`;var Fw;(function(e){e.serverAuth=`1.3.6.1.5.5.7.3.1`,e.clientAuth=`1.3.6.1.5.5.7.3.2`,e.codeSigning=`1.3.6.1.5.5.7.3.3`,e.emailProtection=`1.3.6.1.5.5.7.3.4`,e.timeStamping=`1.3.6.1.5.5.7.3.8`,e.ocspSigning=`1.3.6.1.5.5.7.3.9`})(Fw||={});var Iw=class extends nw{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,q_);this.usages=t.map(e=>e)}else{let t=new q_(e[0]);super(K_,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.usages.map(e=>QC.toString(e)).join(`, `),e}};Iw.NAME=`Extended Key Usages`;var Lw;(function(e){e[e.digitalSignature=1]=`digitalSignature`,e[e.nonRepudiation=2]=`nonRepudiation`,e[e.keyEncipherment=4]=`keyEncipherment`,e[e.dataEncipherment=8]=`dataEncipherment`,e[e.keyAgreement=16]=`keyAgreement`,e[e.keyCertSign=32]=`keyCertSign`,e[e.cRLSign=64]=`cRLSign`,e[e.encipherOnly=128]=`encipherOnly`,e[e.decipherOnly=256]=`decipherOnly`})(Lw||={});var Rw=class extends nw{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,sv);this.usages=t.toNumber()}else{let t=new sv(e[0]);super(av,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,sv).toJSON().join(`, `),e}};Rw.NAME=`Key Usages`;var zw=class e extends nw{static async create(t,n=!1,r=aw.get()){let i=await(await jw.create(t,r)).getKeyIdentifier(r);return new e($d.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Cv);this.keyId=$d.ToHex(t)}else{let t=typeof e[0]==`string`?$d.FromHex(e[0]):e[0],n=new Cv(t);super(Sv,e[1],Y.serialize(n)),this.keyId=$d.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,Cv),e}};zw.NAME=`Subject Key Identifier`;var Bw=class extends nw{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(_v,e[1],new Sw(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,vv);this.names=new Sw(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};Bw.NAME=`Subject Alternative Name`;var Vw=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new nw(e),n=this.items.get(t.type);return n?new n(e):t}};Vw.items=new Map;var Hw=class extends nw{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,A_);this.policies=t.map(e=>e.policyIdentifier)}else{let t=e[0],n=e[1]??!1,r=new A_(t.map(e=>new k_({policyIdentifier:e})));super(C_,n,Y.serialize(r)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new XC(``,{},QC.toString(e))),e}};Hw.NAME=`Certificate Policies`,Vw.register(C_,Hw);var Uw=class extends nw{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]==`string`){let t=e[0].map(e=>new R_({distributionPoint:new L_({fullName:[new Qg({uniformResourceIdentifier:e})]})})),n=new z_(t);super(P_,e[1],Y.serialize(n))}else{let t=new z_(e[0]);super(P_,e[1],Y.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,z_);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e[`Distribution Point`]=this.distributionPoints.map(e=>{let t={};return e.distributionPoint&&(t[``]=e.distributionPoint.fullName?.map(e=>new xw(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};Uw.NAME=`CRL Distribution Points`;var Ww=class extends nw{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof f_){let t=new f_(e[0]);super(u_,e[1],Y.serialize(t))}else{let t=e[0],n=new f_;Kw(n,t,i_,`ocsp`),Kw(n,t,a_,`caIssuers`),Kw(n,t,o_,`timeStamping`),Kw(n,t,s_,`caRepository`),super(u_,e[1],Y.serialize(n))}this.ocsp??=[],this.caIssuers??=[],this.timeStamping??=[],this.caRepository??=[]}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],Y.parse(e.extnValue,f_).forEach(e=>{switch(e.accessMethod){case i_:this.ocsp.push(new xw(e.accessLocation));break;case a_:this.caIssuers.push(new xw(e.accessLocation));break;case o_:this.timeStamping.push(new xw(e.accessLocation));break;case s_:this.caRepository.push(new xw(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Gw(e,`OCSP`,this.ocsp),this.caIssuers.length&&Gw(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&Gw(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&Gw(e,`CA Repository`,this.caRepository),e}};Ww.NAME=`Authority Info Access`;function Gw(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new XC(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[XC.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function Kw(e,t,n,r){let i=t[r];i&&(Array.isArray(i)?i:[i]).forEach(t=>{typeof t==`string`&&(t=new xw(`url`,t)),e.push(new d_({accessMethod:n,accessLocation:Y.parse(t.rawData,Qg)}))})}var qw=class extends nw{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(rv,e[1],new Sw(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,y_);this.names=new Sw(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};qw.NAME=`Issuer Alternative Name`;var Jw=class e extends tw{constructor(...e){let t;if(U.isBufferSource(e[0]))t=U.toArrayBuffer(e[0]);else{let n=e[0],r=Array.isArray(e[1])?e[1].map(e=>U.toArrayBuffer(e)):[];t=Y.serialize(new yv({type:n,values:r}))}super(t,yv)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new XC(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[XC.NAME]===e.NAME&&(t[XC.NAME]=QC.toString(this.type)),t}};Jw.NAME=`Attribute`;var Yw=class extends Jw{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=new rC({printableString:e[0]});super(LS,[Y.serialize(t)])}this.password??=``}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],rC);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[XC.VALUE]=this.password,e}};Yw.NAME=`Challenge Password`;var Xw=class extends Jw{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=e[0],n=new Fv;for(let e of t)n.push(Y.parse(e.rawData,Pv));super(RS,[Y.serialize(n)])}this.items??=[]}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],Fv);this.items=e.map(e=>Vw.create(Y.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[XC.NAME]]=n;return e}};Xw.NAME=`Extensions`;var Zw=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new Jw(e),n=this.items.get(t.type);return n?new n(e):t}};Zw.items=new Map;var Qw=`crypto.signatureFormatter`,$w=class{toAsnSignature(e,t){return U.toArrayBuffer(t)}toWebSignature(e,t){return U.toArrayBuffer(t)}},eT,tT=eT=class{static createPssParams(e,t){let n=eT.getHashAlgorithm(e);return n?new gx({hashAlgorithm:n,maskGenAlgorithm:new Z({algorithm:ux,parameters:Y.serialize(n)}),saltLength:t}):null}static getHashAlgorithm(e){let t=eS.resolve(hC);return typeof e==`string`?t.toAsnAlgorithm({name:e}):typeof e==`object`&&e&&`name`in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`rsassa-pkcs1-v1_5`:if(`hash`in e){let t;if(typeof e.hash==`string`)t=e.hash;else if(e.hash&&typeof e.hash==`object`&&`name`in e.hash&&typeof e.hash.name==`string`)t=e.hash.name.toUpperCase();else throw Error(`Cannot get hash algorithm name`);switch(t.toLowerCase()){case`sha-1`:return new Z({algorithm:Jb,parameters:null});case`sha-256`:return new Z({algorithm:Xb,parameters:null});case`sha-384`:return new Z({algorithm:Zb,parameters:null});case`sha-512`:return new Z({algorithm:Qb,parameters:null})}}else return new Z({algorithm:Hb,parameters:null});break;case`rsa-pss`:if(`hash`in e){if(!(`saltLength`in e&&typeof e.saltLength==`number`))throw Error(`Cannot get 'saltLength' from 'alg' argument`);let t=eT.createPssParams(e.hash,e.saltLength);if(!t)throw Error(`Cannot create PSS parameters`);return new Z({algorithm:Gb,parameters:Y.serialize(t)})}return new Z({algorithm:Gb,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Hb:return{name:`RSASSA-PKCS1-v1_5`};case Jb:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case Xb:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case Zb:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case Qb:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case Gb:if(e.parameters){let t=Y.parse(e.parameters,gx);return{name:`RSA-PSS`,hash:eS.resolve(hC).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:`RSA-PSS`}}return null}};tT=eT=X([tS()],tT),eS.registerSingleton(pC,tT);var nT=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new Z({algorithm:tx});case`sha-256`:return new Z({algorithm:rx});case`sha-384`:return new Z({algorithm:ix});case`sha-512`:return new Z({algorithm:ax})}return null}toWebAlgorithm(e){switch(e.algorithm){case tx:return{name:`SHA-1`};case rx:return{name:`SHA-256`};case ix:return{name:`SHA-384`};case ax:return{name:`SHA-512`}}return null}};nT=X([tS()],nT),eS.registerSingleton(pC,nT);var rT=class e{addPadding(e,t){let n=U.toUint8Array(t),r=new Uint8Array(e);return r.set(n,e-n.length),r.buffer}removePadding(e,t=!1){let n=U.toUint8Array(e);for(let e=0;e<n.length;e++)if(n[e]){n=n.slice(e);break}if(t&&n[0]>127){let e=new Uint8Array(n.length+1);return e.set(n,1),e.buffer}return n.buffer}toAsnSignature(t,n){if(t.name===`ECDSA`){let r=t.namedCurve,i=e.namedCurveSize.get(r)||e.defaultNamedCurveSize,a=new Bb,o=U.toUint8Array(n);return a.r=this.removePadding(o.slice(0,i),!0),a.s=this.removePadding(o.slice(i,i+i),!0),Y.serialize(a)}return null}toWebSignature(t,n){if(t.name===`ECDSA`){let r=Y.parse(n,Bb),i=t.namedCurve,a=e.namedCurveSize.get(i)||e.defaultNamedCurveSize;return ef(this.addPadding(a,this.removePadding(r.r)),this.addPadding(a,this.removePadding(r.s)))}return null}};rT.namedCurveSize=new Map,rT.defaultNamedCurveSize=32;var iT=`1.3.101.110`,aT=`1.3.101.111`,oT=`1.3.101.112`,sT=`1.3.101.113`,cT=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=oT;break;case`x25519`:t=iT;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=oT;break;case`ed448`:t=sT}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=iT;break;case`x448`:t=aT}}return t?new Z({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case oT:return{name:`Ed25519`};case sT:return{name:`EdDSA`,namedCurve:`Ed448`};case iT:return{name:`X25519`};case aT:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}};cT=X([tS()],cT),eS.registerSingleton(pC,cT);var lT,uT,dT,fT,pT,mT,hT,gT,_T=class extends Aw{get subjectName(){return Lg(this,uT,`f`)||Rg(this,uT,new fw(this.asn.certificationRequestInfo.subject),`f`),Lg(this,uT,`f`)}get subject(){return Lg(this,dT,`f`)||Rg(this,dT,this.subjectName.toString(),`f`),Lg(this,dT,`f`)}get signatureAlgorithm(){if(!Lg(this,fT,`f`)){let e=eS.resolve(hC);Rg(this,fT,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return Lg(this,fT,`f`)}get signature(){return Lg(this,pT,`f`)||Rg(this,pT,this.asn.signature,`f`),Lg(this,pT,`f`)}get publicKey(){return Lg(this,mT,`f`)||Rg(this,mT,new jw(this.asn.certificationRequestInfo.subjectPKInfo),`f`),Lg(this,mT,`f`)}get attributes(){return Lg(this,hT,`f`)||Rg(this,hT,this.asn.certificationRequestInfo.attributes.map(e=>Zw.create(Y.serialize(e))),`f`),Lg(this,hT,`f`)}get extensions(){if(!Lg(this,gT,`f`)){Rg(this,gT,[],`f`);let e=this.getAttribute(RS);e instanceof Xw&&Rg(this,gT,e.items,`f`)}return Lg(this,gT,`f`)}get tbs(){return Lg(this,lT,`f`)||Rg(this,lT,this.asn.certificationRequestInfoRaw||Y.serialize(this.asn.certificationRequestInfo),`f`),Lg(this,lT,`f`)}constructor(e){let t=Aw.isAsnEncoded(e)?[e,fC]:[e];super(t[0],t[1]),lT.set(this,void 0),uT.set(this,void 0),dT.set(this,void 0),fT.set(this,void 0),pT.set(this,void 0),mT.set(this,void 0),hT.set(this,void 0),gT.set(this,void 0),this.tag=kw.CertificateRequestTag}onInit(e){}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=aw.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=eS.resolveAll(Qw).reverse(),i=null;for(let e of r)if(i=e.toWebSignature(t,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(),t=Y.parse(this.rawData,fC),n=t.certificationRequestInfo,r=new XC(``,{Version:`${Iv[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new XC(``);for(let t of this.attributes){let n=t.toTextObject();e[n[XC.NAME]]=n}r.Attributes=e}return e.Data=r,e.Signature=new XC(``,{Algorithm:$C.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};lT=new WeakMap,uT=new WeakMap,dT=new WeakMap,fT=new WeakMap,pT=new WeakMap,mT=new WeakMap,hT=new WeakMap,gT=new WeakMap,_T.NAME=`PKCS#10 Certificate Request`;var vT,yT,bT,xT,ST,CT,wT,TT,ET,DT,OT,kT,AT=class extends Aw{get publicKey(){return Lg(this,kT,`f`)||Rg(this,kT,new jw(this.asn.tbsCertificate.subjectPublicKeyInfo),`f`),Lg(this,kT,`f`)}get serialNumber(){if(!Lg(this,yT,`f`)){let e=this.asn.tbsCertificate,t=new Uint8Array(e.serialNumber);t.length>1&&t[0]===0&&t[1]>127&&(t=t.slice(1)),Rg(this,yT,$d.ToHex(t),`f`)}return Lg(this,yT,`f`)}get subjectName(){return Lg(this,bT,`f`)||Rg(this,bT,new fw(this.asn.tbsCertificate.subject),`f`),Lg(this,bT,`f`)}get subject(){return Lg(this,xT,`f`)||Rg(this,xT,this.subjectName.toString(),`f`),Lg(this,xT,`f`)}get issuerName(){return Lg(this,ST,`f`)||Rg(this,ST,new fw(this.asn.tbsCertificate.issuer),`f`),Lg(this,ST,`f`)}get issuer(){return Lg(this,CT,`f`)||Rg(this,CT,this.issuerName.toString(),`f`),Lg(this,CT,`f`)}get notBefore(){if(!Lg(this,wT,`f`)){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw Error(`Cannot get 'notBefore' value`);Rg(this,wT,e,`f`)}return Lg(this,wT,`f`)}get notAfter(){if(!Lg(this,TT,`f`)){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw Error(`Cannot get 'notAfter' value`);Rg(this,TT,e,`f`)}return Lg(this,TT,`f`)}get signatureAlgorithm(){if(!Lg(this,ET,`f`)){let e=eS.resolve(hC);Rg(this,ET,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return Lg(this,ET,`f`)}get signature(){return Lg(this,DT,`f`)||Rg(this,DT,this.asn.signatureValue,`f`),Lg(this,DT,`f`)}get extensions(){return Lg(this,OT,`f`)||(Rg(this,OT,[],`f`),this.asn.tbsCertificate.extensions&&Rg(this,OT,this.asn.tbsCertificate.extensions.map(e=>Vw.create(Y.serialize(e))),`f`)),Lg(this,OT,`f`)}get tbs(){return Lg(this,vT,`f`)||Rg(this,vT,this.asn.tbsCertificateRaw||Y.serialize(this.asn.tbsCertificate),`f`),Lg(this,vT,`f`)}constructor(e){let t=Aw.isAsnEncoded(e)?[e,Rv]:[e];super(t[0],t[1]),vT.set(this,void 0),yT.set(this,void 0),bT.set(this,void 0),xT.set(this,void 0),ST.set(this,void 0),CT.set(this,void 0),wT.set(this,void 0),TT.set(this,void 0),ET.set(this,void 0),DT.set(this,void 0),OT.set(this,void 0),kT.set(this,void 0),this.tag=kw.CertificateTag}onInit(e){}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e={},t=aw.get()){let n,r,i=e.publicKey;try{if(!i)n={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(n,[`verify`],t);else if(`publicKey`in i)n={...i.publicKey.algorithm,...this.signatureAlgorithm},r=await i.publicKey.export(n,[`verify`],t);else if(i instanceof jw)n={...i.algorithm,...this.signatureAlgorithm},r=await i.export(n,[`verify`],t);else if(U.isBufferSource(i)){let e=new jw(i);n={...e.algorithm,...this.signatureAlgorithm},r=await e.export(n,[`verify`],t)}else n={...i.algorithm,...this.signatureAlgorithm},r=i}catch{return!1}let a=eS.resolveAll(Qw).reverse(),o=null;for(let e of a)if(o=e.toWebSignature(n,this.signature),o)break;if(!o)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);let s=await t.subtle.verify(this.signatureAlgorithm,r,o,this.tbs);if(e.signatureOnly)return s;{let t=(e.date||new Date).getTime();return s&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=aw.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=aw.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,Rv),n=t.tbsCertificate,r=new XC(``,{Version:`${Iv[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":$C.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new XC(``,{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(r[`Issuer Unique ID`]=n.issuerUniqueID),n.subjectUniqueID&&(r[`Subject Unique ID`]=n.subjectUniqueID),this.extensions.length){let e=new XC(``);for(let t of this.extensions){let n=t.toTextObject();e[n[XC.NAME]]=n}r.Extensions=e}return e.Data=r,e.Signature=new XC(``,{Algorithm:$C.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};vT=new WeakMap,yT=new WeakMap,bT=new WeakMap,xT=new WeakMap,ST=new WeakMap,CT=new WeakMap,wT=new WeakMap,TT=new WeakMap,ET=new WeakMap,DT=new WeakMap,OT=new WeakMap,kT=new WeakMap,AT.NAME=`Certificate`;function jT(e,t=aw.get()){let n=U.toUint8Array($d.FromHex(e||``)),r=n&&n.length&&n.some(e=>e>0)?new Uint8Array(n):void 0;r||=t.getRandomValues(new Uint8Array(16));let i=0;for(;i<r.length-1&&r[i]===0;)i++;if(r=r.slice(i),r[0]>127){let e=new Uint8Array(r.length+1);e[0]=0,e.set(r,1),r=e}return r.buffer}var MT=class{static async createSelfSigned(e,t=aw.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw 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},t)}static async create(e,t=aw.get()){let n;n=e.publicKey instanceof jw?e.publicKey.rawData:`publicKey`in e.publicKey?e.publicKey.publicKey.rawData:U.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey(`spki`,e.publicKey);let r=jT(e.serialNumber,t),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),o=new Rv({tbsCertificate:new Lv({version:Iv.v3,serialNumber:r,validity:new Mv({notBefore:i,notAfter:a}),extensions:new Fv(e.extensions?.map(e=>Y.parse(e.rawData,Pv))||[]),subjectPublicKeyInfo:Y.parse(n,Av)})});if(e.subject){let t=e.subject instanceof fw?e.subject:new fw(e.subject);o.tbsCertificate.subject=Y.parse(t.toArrayBuffer(),Jg)}if(e.issuer){let t=e.issuer instanceof fw?e.issuer:new fw(e.issuer);o.tbsCertificate.issuer=Y.parse(t.toArrayBuffer(),Jg)}let s={hash:`SHA-256`},c=`signingKey`in e?{...s,...e.signingAlgorithm,...e.signingKey.algorithm}:{...s,...e.signingAlgorithm},l=eS.resolve(hC);o.tbsCertificate.signature=o.signatureAlgorithm=l.toAsnAlgorithm(c);let u=Y.serialize(o.tbsCertificate),d=`signingKey`in e?await t.subtle.sign(c,e.signingKey,u):e.signature,f=eS.resolveAll(Qw).reverse(),p=null;for(let e of f)if(p=e.toAsnSignature(c,d),p)break;if(!p)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return o.signatureValue=p,new AT(Y.serialize(o))}},NT;(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(NT||={}),Vw.register(g_,Pw),Vw.register(K_,Iw),Vw.register(av,Rw),Vw.register(Sv,zw),Vw.register(p_,Nw),Vw.register(_v,Bw),Vw.register(P_,Uw),Vw.register(u_,Ww),Vw.register(rv,qw),Zw.register(LS,Yw),Zw.register(RS,Xw),eS.registerSingleton(Qw,$w),eS.registerSingleton(Qw,rT),rT.namedCurveSize.set(`P-256`,32),rT.namedCurveSize.set(`K-256`,32),rT.namedCurveSize.set(`P-384`,48),rT.namedCurveSize.set(`P-521`,66);var PT=R(((e,t)=>{function n(e){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(e)}t.exports=n})),FT=R(((e,t)=>{for(var n=ne(`util`),r=PT(),i=/[\{\[]/,a=/[\}\]]/,o=`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`.split(`.`),s={},c=0;c<o.length;c++)s[o[c]]=!0;var l=function(e){return r(e)&&!s.hasOwnProperty(e)},u={s:function(e){return``+e},d:function(e){return``+Number(e)},o:function(e){return JSON.stringify(e)}},d=function(){var e=[],t=0,o={},s=function(n){for(var r=``;r.length<t*2;)r+=` `;e.push(r+n)},c=function(e){if(a.test(e.trim()[0])&&i.test(e[e.length-1])){t--,s(e),t++;return}if(i.test(e[e.length-1])){s(e),t++;return}if(a.test(e.trim()[0])){t--,s(e);return}s(e)},d=function(e){if(!e)return d;if(arguments.length===1&&e.indexOf(`
|
|
43
43
|
`)>-1)for(var t=e.trim().split(`
|
|
44
44
|
`),r=0;r<t.length;r++)c(t[r].trim());else c(n.format.apply(n,arguments));return d};return d.scope={},d.formats=u,d.sym=function(e){return(!e||!l(e))&&(e=`tmp`),o[e]||(o[e]=0),e+(o[e]++||``)},d.property=function(e,t){return arguments.length===1&&(t=e,e=``),t+=``,r(t)?e?e+`.`+t:t:e?e+`[`+JSON.stringify(t)+`]`:JSON.stringify(t)},d.toString=function(){return e.join(`
|
|
45
|
-
`)},d.toFunction=function(e){e||={};var t=`return (`+d.toString()+`)`;Object.keys(d.scope).forEach(function(t){e[t]||(e[t]=d.scope[t])});var n=Object.keys(e).map(function(e){return e}),r=n.map(function(t){return e[t]});return Function.apply(null,n.concat(t)).apply(null,r)},arguments.length&&d.apply(null,arguments),d};d.formats=u,t.exports=d})),
|
|
45
|
+
`)},d.toFunction=function(e){e||={};var t=`return (`+d.toString()+`)`;Object.keys(d.scope).forEach(function(t){e[t]||(e[t]=d.scope[t])});var n=Object.keys(e).map(function(e){return e}),r=n.map(function(t){return e[t]});return Function.apply(null,n.concat(t)).apply(null,r)},arguments.length&&d.apply(null,arguments),d};d.formats=u,t.exports=d})),IT=R(((e,t)=>{var n=class{constructor(){this.next=null,this.buffer=null}};t.exports=class e{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let t=new n;t.buffer=e,this.length>0?this.tail.next=t:this.head=t,this.tail=t,this.length+=e.length,this.count+=1}unshift(e){let t=new n;t.buffer=e,t.next=this.head,this.isEmpty()&&(this.tail=t),this.head=t,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,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(t,n){if(t<0||t>=this.length||n<0||n>this.length||n<t)return new e;let r=new e,i=this.head,a=t,o=n;for(;i;){if(i.buffer.length>a){a===0&&i.buffer.length<=o?r.push(i.buffer):i.buffer.length>=o?r.push(i.buffer.slice(a,o)):r.push(i.buffer.slice(a));break}a-=i.buffer.length,o-=i.buffer.length,i=i.next}if(i.buffer.length<o)for(;i;){if(i.buffer.length===o){r.push(i.buffer);break}if(i.buffer.length>o){r.push(i.buffer.slice(0,o));break}a<0&&i.buffer.length<o&&r.push(i.buffer),a-=i.buffer.length,o-=i.buffer.length,i=i.next}return r}}})),LT=R(((e,t)=>{var n=FT(),r=IT(),i=class e{constructor(){this.queue=new r,this.offset=0}get length(){return this.queue.length-this.offset}append(t){if(Buffer.isBuffer(t)){if(this.offset>0){let e=this.queue.shift();this.queue.unshift(e.slice(this.offset)),this.offset=0}this.queue.push(t)}else if(Array.isArray(t))for(let e=0;e<t.length;e+=1)this.append(t[e]);else if(t instanceof e){if(this.offset>0){let e=this.queue.shift();this.queue.unshift(e.slice(this.offset)),this.offset=0}if(t.offset>0){let e=t.queue.shift();t.queue.unshift(e.slice(t.offset)),t.offset=0}let e=t.queue.head;for(;e;)this.queue.push(e.buffer),e=e.next}}get(e){let t=e;for(;t>=this.length;)t-=this.length;for(;t<0;)t+=this.length;let n=this.queue.head,{offset:r}=this;for(;n;){if(n.buffer.length-r>t)return n.buffer[t+r];t-=n.buffer.length-r,r=0,n=n.next}}slice(e,t){for(typeof e!=`number`&&(e=0),typeof t!=`number`&&(t=this.length);e<0;)e+=this.length;for(;t<0;)t+=this.length;if(t=Math.min(t,this.length),e>=this.length||t===0)return Buffer.alloc(0);let n=e;e=Math.min(n,t),t=Math.max(n,t);let r=this.queue.slice(e+this.offset,t+this.offset);if(r.count===1)return r.first;let i=r.head,a=Buffer.allocUnsafe(r.length),o=0;for(let e=0;e<r.count;e+=1)a.set(i.buffer,o),o+=i.buffer.length,i=i.next;return a}toString(e,t,n){return this.slice(t,n).toString(e)}consume(e){let t=e;for(;this.length>0;){let e=this.queue.first.length-this.offset;if(t>=e)this.queue.shift(),t-=e,this.offset=0;else{this.offset+=t;break}}}indexOf(e,t=0){if(!Number.isInteger(e))throw TypeError(`Invalid argument 1`);if(e<0||e>255)throw Error(`Invalid argument 1`);for(Number.isInteger(t)||(t=0);t>=this.length;)t-=this.length;for(;t<0;)t+=this.length;let n=this.queue.head,r=0,i=()=>{r+=n.buffer.length,n=n.next};for(;n;){let a=0;if(n===this.queue.head&&(a+=this.offset),t>=n.buffer.length-a){t-=n.buffer.length-a,i();continue}t<n.buffer.length&&(a+=t);let o=n.buffer.indexOf(e,a);if(o>-1)return o+r-this.offset;i(),a>this.offset&&(t=0)}return-1}},a={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(a).forEach(e=>{let t=n();t(`
|
|
46
46
|
function bufferlist_${e}(offset = 0) {
|
|
47
47
|
const start = offset + this.offset;
|
|
48
48
|
const head = this.queue.first;
|
|
@@ -76,7 +76,7 @@ import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/pr
|
|
|
76
76
|
buf.${e}(value, 0, size);
|
|
77
77
|
this.append(buf);
|
|
78
78
|
}
|
|
79
|
-
`),i.prototype[e]=t.toFunction()}),t.exports=i})),
|
|
79
|
+
`),i.prototype[e]=t.toFunction()}),t.exports=i})),RT=R(((e,t)=>{t.exports=class extends Error{constructor(e,t){let n=`requested ${e} bytes but only ${t} available`;super(n),this.name=`NotEnoughDataError`}}})),zT=R(((e,t)=>{var{Transform:n}=ne(`stream`),r=FT(),i=LT(),a=RT(),o=Symbol(`buffer`),s=class extends n{constructor(e={}){super(e),this[o]=new i}get buffer(){return this[o]}get length(){return this.buffer.length}append(e){this.buffer.append(e)}get(e){return this.buffer.get(e)}slice(e,t){return this.buffer.slice(e,t)}consume(e){this.buffer.consume(e)}toString(e,t,n){return this.buffer.toString(e,t,n)}indexOf(e,t=0){return this.buffer.indexOf(e,t)}readBuffer(e){l(e,this.length);let t=this.slice(0,e);return this.consume(e),t}writeBuffer(e){this.append(e)}},c={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(c).forEach(e=>{let t=r();t(`
|
|
80
80
|
function binary_${e}() {
|
|
81
81
|
const bytes = ${t.formats.d(c[e])};
|
|
82
82
|
assertSize(bytes, this.length);
|
|
@@ -102,7 +102,7 @@ import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/pr
|
|
|
102
102
|
function binary_${e}(value, size) {
|
|
103
103
|
this.buffer.${e}(value, size);
|
|
104
104
|
}
|
|
105
|
-
`),s.prototype[e]=t.toFunction()});function l(e,t){if(e>t)throw new a(e,t)}t.exports=s})),sv=R(((e,t)=>{t.exports=function(e){return typeof e==`object`&&!!e&&Array.isArray(e)===!1}})),cv=R(((e,t)=>{var n=sv();function r(e){return n(e)===!0&&Object.prototype.toString.call(e)===`[object Object]`}t.exports=function(e){var t,n;return!(r(e)===!1||(t=e.constructor,typeof t!=`function`)||(n=t.prototype,r(n)===!1)||n.hasOwnProperty(`isPrototypeOf`)===!1)}})),lv=R(((e,t)=>{t.exports={isType:n,isUserType:cv(),isFunction:r,isDecodeType:a,isEncodeType:o};function n(e){return i(e)&&r(e.encode)&&r(e.decode)}function r(e){return typeof e==`function`}function i(e){return typeof e==`object`&&!!e}function a(e){return i(e)&&r(e.decode)}function o(e){return i(e)&&r(e.encode)}})),uv=R(((e,t)=>{t.exports={skip:Symbol(`skip`),bytes:Symbol(`bytes`)}})),dv=R(((e,t)=>{var n=uv();t.exports=class e{constructor(){this[n.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[n.bytes]}static clone(t){let n=new e;return t instanceof e&&(n.node=t.node,n.current=t.current),n}static clean(t){t instanceof e&&(t.node=void 0,t.current=void 0)}}})),fv=R(((e,t)=>{var{isType:n,isUserType:r,isDecodeType:i}=lv(),a=ov(),o=uv(),s=dv();t.exports={decode:c,decodeCommon:l};function c(e,t){let n=e;Buffer.isBuffer(e)&&(n=new a,n.append(e));let r=new s,i=l(n,t,r);return c.bytes=r.bytes,s.clean(r),i}function l(e,t,r){if(n(t)){let n=t.decode.call(r,e);return r[o.bytes]+=t.decode.bytes,n}return u(e,t,r)}function u(e,t,n){d(t);let r=Object.create(null);n.node===void 0&&(n.node=r),n.current=r;let a=Object.keys(t);for(let s=0;s<a.length;s+=1){let c=a[s],l=t[c];if(!i(l)){r[c]=u(e,l,n),n.current=r;continue}let d=l.decode.call(n,e);n[o.bytes]+=l.decode.bytes,l[o.skip]!==!0&&(r[c]=d)}return r}function d(e){if(!r(e))throw TypeError(`Argument #2 should be a plain object.`)}})),pv=R(((e,t)=>{var{isUserType:n,isEncodeType:r,isType:i}=lv(),a=uv(),o=dv(),s=ov();t.exports={encode:c,encodeCommon:l};function c(e,t,n){let r=new o;if(t instanceof s){let e=n;n=t,t=e}return n instanceof s||(n=new s),l(e,n,t,r),c.bytes=r.bytes,o.clean(r),n}function l(e,t,n,r){i(n)?(n.encode.call(r,e,t),r[a.bytes]+=n.encode.bytes):u(e,t,n,r)}function u(e,t,n,i){d(n),i.node===void 0&&(i.node=e),i.current=e;let o=Object.keys(n);for(let s=0;s<o.length;s+=1){let c=o[s],l=n[c],d=e[c];if(!r(l)){u(d,t,l,i),i.current=e;continue}l.encode.call(i,d,t),i[a.bytes]+=l.encode.bytes}}function d(e){if(!n(e))throw TypeError("Argument `schema` should be a plain object.")}})),mv=R(((e,t)=>{var{isUserType:n,isType:r}=lv(),i=dv(),a=uv();t.exports={encodingLength:o,encodingLengthCommon:s};function o(e,t){let n=new i;return s(e,t,n),i.clean(n),n.bytes}function s(e,t,n){r(t)?n[a.bytes]+=t.encodingLength.call(n,e):c(e,t,n)}function c(e,t,i){if(!n(t))throw TypeError("Argument `schema` should be a plain object.");i.node===void 0&&(i.node=e),i.current=e;let o=Object.keys(t);for(let n=0;n<o.length;n+=1){let s=o[n],l=t[s],u=e[s];if(!r(l)){c(u,l,i),i.current=e;continue}i[a.bytes]+=l.encodingLength.call(i,u)}}})),hv=R(((e,t)=>{var{decodeCommon:n}=fv(),{encodeCommon:r}=pv(),{encodingLengthCommon:i}=mv(),{isType:a,isUserType:o,isFunction:s}=lv(),c=dv();t.exports=l;function l(e,t,n=`count`){if(!a(e)&&!o(e))throw TypeError(`Argument #1 should be a valid type.`);let l=n===`bytes`,h=typeof t==`number`,g=a(t),_=s(t);if(!h&&!g&&!_)throw TypeError(`Unknown type of argument #1.`);return{encode:v,decode:y,encodingLength:b};function v(n,a){u(n);let o=c.clone(this);v.bytes=0;let s=0;if(g?s=n.length:h?s=t:_&&(s=t(o),d(s)),l||f(s,n.length),l){let t=c.clone(o);for(let r of n)i(r,e,t);g&&(s=t.bytes),f(t.bytes,s),c.clean(t)}g&&(t.encode.call(o,s,a),v.bytes+=t.encode.bytes),n.forEach(t=>{r(t,a,e,o)}),v.bytes+=o.bytes,c.clean(o)}function y(n){let r=0;y.bytes=0;let i=c.clone(this);h?r=t:g?(r=t.decode.call(i,n),y.bytes+=t.decode.bytes):_&&(r=t(i)),d(r);let a;return a=l?p(e,r,n,i):m(e,r,n,i),y.bytes+=i.bytes,c.clean(i),a}function b(n){u(n);let r=c.clone(this),a=0;if(h&&l)return t;g&&!l&&(a=t.encodingLength(n.length));for(let t of n)i(t,e,r);return c.clean(r),a+=r.bytes,g&&l&&(a+=t.encodingLength(a)),a}}function u(e){if(!Array.isArray(e))throw TypeError(`Argument #1 should be an Array.`)}function d(e){if(typeof e!=`number`)throw TypeError(`Length of an array should be a number.`)}function f(e,t){if(e!==t)throw Error(`Argument #1 required length ${e} instead of ${t}`)}function p(e,t,r,i){let a=[],o=i.bytes,s=0;for(;s<t;)a.push(n(r,e,i)),s=i.bytes-o;if(s>t)throw Error(`Incorrect length of an array.`);return a}function m(e,t,r,i){let a=Array(t);for(let o=0;o<t;o+=1)a[o]=n(r,e,i);return a}})),gv=R(((e,t)=>{var{isType:n,isFunction:r}=lv(),i=av(),a=ov();t.exports=o;function o(e){let t=typeof e==`number`,a=n(e),o=r(e),u=e===null;if(!t&&!a&&!o&&!u)throw TypeError(`Unknown type of argument #1.`);return{encode:d,decode:f,encodingLength:p};function d(n,r){s(n),d.bytes=0;let i=this;if(t&&c(e,n.length),a&&(e.encode.call(i,n.length,r),d.bytes+=e.encode.bytes),o){let t=e(i);l(t),c(t,n.length)}r.writeBuffer(Buffer.isBuffer(n)?n:n.buffer),d.bytes+=n.length,u&&(r.writeUInt8(0),d.bytes+=1)}function f(n){let r=0;f.bytes=0;let s=this;if(t)r=e;else if(a)r=e.decode.call(s,n),f.bytes+=e.decode.bytes,l(r);else if(o)r=e(s),l(r);else if(u&&(r=n.indexOf(0),r===-1))throw new i(n.length+1,n.length);let c=n.readBuffer(r);return f.bytes+=r,u&&(f.bytes+=1,n.consume(1)),c}function p(n){s(n);let r=0;return t?e:(u?r=1:a&&(r=e.encodingLength(n.length)),r+n.length)}}function s(e){if(!Buffer.isBuffer(e)&&!(e instanceof a))throw TypeError(`Argument 1 should be a Buffer or a BinaryStream.`)}function c(e,t){if(e!==t)throw Error(`Buffer required length ${e} instead of ${t}`)}function l(e){if(typeof e!=`number`)throw TypeError(`Length of a buffer should be a number.`)}})),_v=R(((e,t)=>{var{isType:n}=lv();t.exports=r;function r(e){if(!n(e))throw TypeError(`Argument #1 should be valid type.`);function t(n){let r=this,i=e.decode.call(r,n);return t.bytes=e.decode.bytes,!!i}function r(t,n){let i=this;e.encode.call(i,+!!t,n),r.bytes=e.encode.bytes}return{encode:r,decode:t,encodingLength:e.encodingLength}}})),vv=R(((e,t)=>{var{decodeCommon:n}=fv(),{encodeCommon:r}=pv(),{encodingLengthCommon:i}=mv(),{isType:a,isFunction:o}=lv(),s=uv(),c=dv();t.exports=l;function l(e,t=1){if(!a(e))throw TypeError(`Invalid data type.`);if(!Number.isInteger(t)&&!o(t))throw TypeError(`Argument #2 should be a valid integer or function.`);return{[s.skip]:!0,encodingLength:l,decode:u,encode:d};function l(n){let r=c.clone(this),a=o(t)?t(r):t;return i(n,e,r),c.clean(r),r.bytes*a}function u(r){let i=c.clone(this);u.bytes=0;let a=o(t)?t(i):t;if(a===0){c.clean(i);return}for(let t=a;t>0;--t)n(r,e,i);u.bytes=i.bytes,c.clean(i)}function d(n,i){d.bytes=0;let a=c.clone(this),s=o(t)?t(a):t;if(s===0){c.clean(a);return}for(let t=s;t>0;--t)r(0,i,e,a);d.bytes=a.bytes,c.clean(a)}}})),yv=R(((e,t)=>{var{isType:n}=lv(),r=av();t.exports=i;function i(e,t=`ascii`){if(!Buffer.isEncoding(t))throw Error(`Argument #2 should be an encoding name.`);if(typeof e==`number`)return{encode:s(e,t),decode:c(e,t),encodingLength:()=>e};if(n(e))return{encode:l(e,t),decode:u(e,t),encodingLength:d(e,t)};if(e===null)return{encode:a(t),decode:o(t),encodingLength(e){return Buffer.byteLength(e,t)+1}};if(typeof e==`function`)return{encode:f(e,t),decode:p(e,t),encodingLength(e){return Buffer.byteLength(e,t)}};throw TypeError(`Unknown type of argument #1.`)}function a(e){return function t(n,r){let i=Buffer.from(n.toString(),e);r.writeBuffer(i),r.writeInt8(0),t.bytes=i.length+1}}function o(e){return function t(n){let i=n.indexOf(0);if(i===-1)throw new r(n.length+1,n.length);let a=i+1,o=n.readBuffer(a);return t.bytes=a,o.toString(e,0,i)}}function s(e,t){return function n(r,i){if(r=r.toString(),Buffer.byteLength(r,t)!==e)throw Error(`Size of string should be ${e} in bytes.`);let a=Buffer.from(r,t);i.writeBuffer(a),n.bytes=a.length}}function c(e,t){return function n(r){let i=r.readBuffer(e);return n.bytes=e,i.toString(t)}}function l(e,t){return function n(r,i){r=r.toString();let a=this;e.encode.call(a,Buffer.byteLength(r,t),i),n.bytes=e.encode.bytes;let o=Buffer.from(r,t);i.writeBuffer(o),n.bytes+=o.length}}function u(e,t){return function n(r){let i=e.decode.call(this,r);if(typeof i!=`number`)throw TypeError(`Size of a string should be a number.`);let a=r.readBuffer(i);return n.bytes=e.decode.bytes+a.length,a.toString(t)}}function d(e,t){return function(n){let r=Buffer.byteLength(n,t);return e.encodingLength(r)+r}}function f(e,t){return function n(r,i){n.bytes=0;let a=e(this),o=Buffer.from(r.toString(),t);m(a),h(a,o.length),i.writeBuffer(o),n.bytes+=o.length}}function p(e,t){return function n(r){let i=e(this);m(i);let a=r.readBuffer(i);return n.bytes=i,a.toString(t)}}function m(e){if(typeof e!=`number`)throw TypeError(`Length of a buffer should be a number.`)}function h(e,t){if(e!==t)throw Error(`Buffer required length ${e} instead of ${t}`)}})),bv=R(((e,t)=>{var n=nv();t.exports={doublebe:r(8,`writeDoubleBE`,`readDoubleBE`),doublele:r(8,`writeDoubleLE`,`readDoubleLE`),floatbe:r(4,`writeFloatBE`,`readFloatBE`),floatle:r(4,`writeFloatLE`,`readFloatLE`),int8:r(1,`writeInt8`,`readInt8`),uint8:r(1,`writeUInt8`,`readUInt8`),int16be:r(2,`writeInt16BE`,`readInt16BE`),uint16be:r(2,`writeUInt16BE`,`readUInt16BE`),int16le:r(2,`writeInt16LE`,`readInt16LE`),uint16le:r(2,`writeUInt16LE`,`readUInt16LE`),int32be:r(4,`writeInt32BE`,`readInt32BE`),uint32be:r(4,`writeUInt32BE`,`readUInt32BE`),int32le:r(4,`writeInt32LE`,`readInt32LE`),uint32le:r(4,`writeUInt32LE`,`readUInt32LE`),int24be:i(3,`writeIntBE`,`readIntBE`),uint24be:i(3,`writeUIntBE`,`readUIntBE`),int24le:i(3,`writeIntLE`,`readIntLE`),uint24le:i(3,`writeUIntLE`,`readUIntLE`),int40be:i(5,`writeIntBE`,`readIntBE`),uint40be:i(5,`writeUIntBE`,`readUIntBE`),int40le:i(5,`writeIntLE`,`readIntLE`),uint40le:i(5,`writeUIntLE`,`readUIntLE`),int48be:i(6,`writeIntBE`,`readIntBE`),uint48be:i(6,`writeUIntBE`,`readUIntBE`),int48le:i(6,`writeIntLE`,`readIntLE`),uint48le:i(6,`writeUIntLE`,`readUIntLE`)};function r(e,t,r){let i=n(),a=n();return i(`
|
|
105
|
+
`),s.prototype[e]=t.toFunction()});function l(e,t){if(e>t)throw new a(e,t)}t.exports=s})),BT=R(((e,t)=>{t.exports=function(e){return typeof e==`object`&&!!e&&Array.isArray(e)===!1}})),VT=R(((e,t)=>{var n=BT();function r(e){return n(e)===!0&&Object.prototype.toString.call(e)===`[object Object]`}t.exports=function(e){var t,n;return!(r(e)===!1||(t=e.constructor,typeof t!=`function`)||(n=t.prototype,r(n)===!1)||n.hasOwnProperty(`isPrototypeOf`)===!1)}})),HT=R(((e,t)=>{t.exports={isType:n,isUserType:VT(),isFunction:r,isDecodeType:a,isEncodeType:o};function n(e){return i(e)&&r(e.encode)&&r(e.decode)}function r(e){return typeof e==`function`}function i(e){return typeof e==`object`&&!!e}function a(e){return i(e)&&r(e.decode)}function o(e){return i(e)&&r(e.encode)}})),UT=R(((e,t)=>{t.exports={skip:Symbol(`skip`),bytes:Symbol(`bytes`)}})),WT=R(((e,t)=>{var n=UT();t.exports=class e{constructor(){this[n.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[n.bytes]}static clone(t){let n=new e;return t instanceof e&&(n.node=t.node,n.current=t.current),n}static clean(t){t instanceof e&&(t.node=void 0,t.current=void 0)}}})),GT=R(((e,t)=>{var{isType:n,isUserType:r,isDecodeType:i}=HT(),a=zT(),o=UT(),s=WT();t.exports={decode:c,decodeCommon:l};function c(e,t){let n=e;Buffer.isBuffer(e)&&(n=new a,n.append(e));let r=new s,i=l(n,t,r);return c.bytes=r.bytes,s.clean(r),i}function l(e,t,r){if(n(t)){let n=t.decode.call(r,e);return r[o.bytes]+=t.decode.bytes,n}return u(e,t,r)}function u(e,t,n){d(t);let r=Object.create(null);n.node===void 0&&(n.node=r),n.current=r;let a=Object.keys(t);for(let s=0;s<a.length;s+=1){let c=a[s],l=t[c];if(!i(l)){r[c]=u(e,l,n),n.current=r;continue}let d=l.decode.call(n,e);n[o.bytes]+=l.decode.bytes,l[o.skip]!==!0&&(r[c]=d)}return r}function d(e){if(!r(e))throw TypeError(`Argument #2 should be a plain object.`)}})),KT=R(((e,t)=>{var{isUserType:n,isEncodeType:r,isType:i}=HT(),a=UT(),o=WT(),s=zT();t.exports={encode:c,encodeCommon:l};function c(e,t,n){let r=new o;if(t instanceof s){let e=n;n=t,t=e}return n instanceof s||(n=new s),l(e,n,t,r),c.bytes=r.bytes,o.clean(r),n}function l(e,t,n,r){i(n)?(n.encode.call(r,e,t),r[a.bytes]+=n.encode.bytes):u(e,t,n,r)}function u(e,t,n,i){d(n),i.node===void 0&&(i.node=e),i.current=e;let o=Object.keys(n);for(let s=0;s<o.length;s+=1){let c=o[s],l=n[c],d=e[c];if(!r(l)){u(d,t,l,i),i.current=e;continue}l.encode.call(i,d,t),i[a.bytes]+=l.encode.bytes}}function d(e){if(!n(e))throw TypeError("Argument `schema` should be a plain object.")}})),qT=R(((e,t)=>{var{isUserType:n,isType:r}=HT(),i=WT(),a=UT();t.exports={encodingLength:o,encodingLengthCommon:s};function o(e,t){let n=new i;return s(e,t,n),i.clean(n),n.bytes}function s(e,t,n){r(t)?n[a.bytes]+=t.encodingLength.call(n,e):c(e,t,n)}function c(e,t,i){if(!n(t))throw TypeError("Argument `schema` should be a plain object.");i.node===void 0&&(i.node=e),i.current=e;let o=Object.keys(t);for(let n=0;n<o.length;n+=1){let s=o[n],l=t[s],u=e[s];if(!r(l)){c(u,l,i),i.current=e;continue}i[a.bytes]+=l.encodingLength.call(i,u)}}})),JT=R(((e,t)=>{var{decodeCommon:n}=GT(),{encodeCommon:r}=KT(),{encodingLengthCommon:i}=qT(),{isType:a,isUserType:o,isFunction:s}=HT(),c=WT();t.exports=l;function l(e,t,n=`count`){if(!a(e)&&!o(e))throw TypeError(`Argument #1 should be a valid type.`);let l=n===`bytes`,h=typeof t==`number`,g=a(t),_=s(t);if(!h&&!g&&!_)throw TypeError(`Unknown type of argument #1.`);return{encode:v,decode:y,encodingLength:b};function v(n,a){u(n);let o=c.clone(this);v.bytes=0;let s=0;if(g?s=n.length:h?s=t:_&&(s=t(o),d(s)),l||f(s,n.length),l){let t=c.clone(o);for(let r of n)i(r,e,t);g&&(s=t.bytes),f(t.bytes,s),c.clean(t)}g&&(t.encode.call(o,s,a),v.bytes+=t.encode.bytes),n.forEach(t=>{r(t,a,e,o)}),v.bytes+=o.bytes,c.clean(o)}function y(n){let r=0;y.bytes=0;let i=c.clone(this);h?r=t:g?(r=t.decode.call(i,n),y.bytes+=t.decode.bytes):_&&(r=t(i)),d(r);let a;return a=l?p(e,r,n,i):m(e,r,n,i),y.bytes+=i.bytes,c.clean(i),a}function b(n){u(n);let r=c.clone(this),a=0;if(h&&l)return t;g&&!l&&(a=t.encodingLength(n.length));for(let t of n)i(t,e,r);return c.clean(r),a+=r.bytes,g&&l&&(a+=t.encodingLength(a)),a}}function u(e){if(!Array.isArray(e))throw TypeError(`Argument #1 should be an Array.`)}function d(e){if(typeof e!=`number`)throw TypeError(`Length of an array should be a number.`)}function f(e,t){if(e!==t)throw Error(`Argument #1 required length ${e} instead of ${t}`)}function p(e,t,r,i){let a=[],o=i.bytes,s=0;for(;s<t;)a.push(n(r,e,i)),s=i.bytes-o;if(s>t)throw Error(`Incorrect length of an array.`);return a}function m(e,t,r,i){let a=Array(t);for(let o=0;o<t;o+=1)a[o]=n(r,e,i);return a}})),YT=R(((e,t)=>{var{isType:n,isFunction:r}=HT(),i=RT(),a=zT();t.exports=o;function o(e){let t=typeof e==`number`,a=n(e),o=r(e),u=e===null;if(!t&&!a&&!o&&!u)throw TypeError(`Unknown type of argument #1.`);return{encode:d,decode:f,encodingLength:p};function d(n,r){s(n),d.bytes=0;let i=this;if(t&&c(e,n.length),a&&(e.encode.call(i,n.length,r),d.bytes+=e.encode.bytes),o){let t=e(i);l(t),c(t,n.length)}r.writeBuffer(Buffer.isBuffer(n)?n:n.buffer),d.bytes+=n.length,u&&(r.writeUInt8(0),d.bytes+=1)}function f(n){let r=0;f.bytes=0;let s=this;if(t)r=e;else if(a)r=e.decode.call(s,n),f.bytes+=e.decode.bytes,l(r);else if(o)r=e(s),l(r);else if(u&&(r=n.indexOf(0),r===-1))throw new i(n.length+1,n.length);let c=n.readBuffer(r);return f.bytes+=r,u&&(f.bytes+=1,n.consume(1)),c}function p(n){s(n);let r=0;return t?e:(u?r=1:a&&(r=e.encodingLength(n.length)),r+n.length)}}function s(e){if(!Buffer.isBuffer(e)&&!(e instanceof a))throw TypeError(`Argument 1 should be a Buffer or a BinaryStream.`)}function c(e,t){if(e!==t)throw Error(`Buffer required length ${e} instead of ${t}`)}function l(e){if(typeof e!=`number`)throw TypeError(`Length of a buffer should be a number.`)}})),XT=R(((e,t)=>{var{isType:n}=HT();t.exports=r;function r(e){if(!n(e))throw TypeError(`Argument #1 should be valid type.`);function t(n){let r=this,i=e.decode.call(r,n);return t.bytes=e.decode.bytes,!!i}function r(t,n){let i=this;e.encode.call(i,+!!t,n),r.bytes=e.encode.bytes}return{encode:r,decode:t,encodingLength:e.encodingLength}}})),ZT=R(((e,t)=>{var{decodeCommon:n}=GT(),{encodeCommon:r}=KT(),{encodingLengthCommon:i}=qT(),{isType:a,isFunction:o}=HT(),s=UT(),c=WT();t.exports=l;function l(e,t=1){if(!a(e))throw TypeError(`Invalid data type.`);if(!Number.isInteger(t)&&!o(t))throw TypeError(`Argument #2 should be a valid integer or function.`);return{[s.skip]:!0,encodingLength:l,decode:u,encode:d};function l(n){let r=c.clone(this),a=o(t)?t(r):t;return i(n,e,r),c.clean(r),r.bytes*a}function u(r){let i=c.clone(this);u.bytes=0;let a=o(t)?t(i):t;if(a===0){c.clean(i);return}for(let t=a;t>0;--t)n(r,e,i);u.bytes=i.bytes,c.clean(i)}function d(n,i){d.bytes=0;let a=c.clone(this),s=o(t)?t(a):t;if(s===0){c.clean(a);return}for(let t=s;t>0;--t)r(0,i,e,a);d.bytes=a.bytes,c.clean(a)}}})),QT=R(((e,t)=>{var{isType:n}=HT(),r=RT();t.exports=i;function i(e,t=`ascii`){if(!Buffer.isEncoding(t))throw Error(`Argument #2 should be an encoding name.`);if(typeof e==`number`)return{encode:s(e,t),decode:c(e,t),encodingLength:()=>e};if(n(e))return{encode:l(e,t),decode:u(e,t),encodingLength:d(e,t)};if(e===null)return{encode:a(t),decode:o(t),encodingLength(e){return Buffer.byteLength(e,t)+1}};if(typeof e==`function`)return{encode:f(e,t),decode:p(e,t),encodingLength(e){return Buffer.byteLength(e,t)}};throw TypeError(`Unknown type of argument #1.`)}function a(e){return function t(n,r){let i=Buffer.from(n.toString(),e);r.writeBuffer(i),r.writeInt8(0),t.bytes=i.length+1}}function o(e){return function t(n){let i=n.indexOf(0);if(i===-1)throw new r(n.length+1,n.length);let a=i+1,o=n.readBuffer(a);return t.bytes=a,o.toString(e,0,i)}}function s(e,t){return function n(r,i){if(r=r.toString(),Buffer.byteLength(r,t)!==e)throw Error(`Size of string should be ${e} in bytes.`);let a=Buffer.from(r,t);i.writeBuffer(a),n.bytes=a.length}}function c(e,t){return function n(r){let i=r.readBuffer(e);return n.bytes=e,i.toString(t)}}function l(e,t){return function n(r,i){r=r.toString();let a=this;e.encode.call(a,Buffer.byteLength(r,t),i),n.bytes=e.encode.bytes;let o=Buffer.from(r,t);i.writeBuffer(o),n.bytes+=o.length}}function u(e,t){return function n(r){let i=e.decode.call(this,r);if(typeof i!=`number`)throw TypeError(`Size of a string should be a number.`);let a=r.readBuffer(i);return n.bytes=e.decode.bytes+a.length,a.toString(t)}}function d(e,t){return function(n){let r=Buffer.byteLength(n,t);return e.encodingLength(r)+r}}function f(e,t){return function n(r,i){n.bytes=0;let a=e(this),o=Buffer.from(r.toString(),t);m(a),h(a,o.length),i.writeBuffer(o),n.bytes+=o.length}}function p(e,t){return function n(r){let i=e(this);m(i);let a=r.readBuffer(i);return n.bytes=i,a.toString(t)}}function m(e){if(typeof e!=`number`)throw TypeError(`Length of a buffer should be a number.`)}function h(e,t){if(e!==t)throw Error(`Buffer required length ${e} instead of ${t}`)}})),$T=R(((e,t)=>{var n=FT();t.exports={doublebe:r(8,`writeDoubleBE`,`readDoubleBE`),doublele:r(8,`writeDoubleLE`,`readDoubleLE`),floatbe:r(4,`writeFloatBE`,`readFloatBE`),floatle:r(4,`writeFloatLE`,`readFloatLE`),int8:r(1,`writeInt8`,`readInt8`),uint8:r(1,`writeUInt8`,`readUInt8`),int16be:r(2,`writeInt16BE`,`readInt16BE`),uint16be:r(2,`writeUInt16BE`,`readUInt16BE`),int16le:r(2,`writeInt16LE`,`readInt16LE`),uint16le:r(2,`writeUInt16LE`,`readUInt16LE`),int32be:r(4,`writeInt32BE`,`readInt32BE`),uint32be:r(4,`writeUInt32BE`,`readUInt32BE`),int32le:r(4,`writeInt32LE`,`readInt32LE`),uint32le:r(4,`writeUInt32LE`,`readUInt32LE`),int24be:i(3,`writeIntBE`,`readIntBE`),uint24be:i(3,`writeUIntBE`,`readUIntBE`),int24le:i(3,`writeIntLE`,`readIntLE`),uint24le:i(3,`writeUIntLE`,`readUIntLE`),int40be:i(5,`writeIntBE`,`readIntBE`),uint40be:i(5,`writeUIntBE`,`readUIntBE`),int40le:i(5,`writeIntLE`,`readIntLE`),uint40le:i(5,`writeUIntLE`,`readUIntLE`),int48be:i(6,`writeIntBE`,`readIntBE`),uint48be:i(6,`writeUIntBE`,`readUIntBE`),int48le:i(6,`writeIntLE`,`readIntLE`),uint48le:i(6,`writeUIntLE`,`readUIntLE`)};function r(e,t,r){let i=n(),a=n();return i(`
|
|
106
106
|
function decode_${r}(rstream) {
|
|
107
107
|
decode_${r}.bytes = ${i.formats.d(e)};
|
|
108
108
|
return rstream.${r}()
|
|
@@ -122,7 +122,7 @@ import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/pr
|
|
|
122
122
|
wstream.${t}(value, ${i.formats.d(e)});
|
|
123
123
|
encode_${t}.bytes = ${i.formats.d(e)};
|
|
124
124
|
}
|
|
125
|
-
`),{encodingLength:()=>e,encode:a.toFunction(),decode:i.toFunction()}}})),
|
|
125
|
+
`),{encodingLength:()=>e,encode:a.toFunction(),decode:i.toFunction()}}})),eE=R(((e,t)=>{var{isType:n,isFunction:r,isUserType:i}=HT(),a=UT(),{decodeCommon:o}=GT(),{encodeCommon:s}=KT(),{encodingLengthCommon:c}=qT(),l=WT();t.exports=u;function u(e,t){if(!n(t)&&!i(t))throw TypeError(`Argument #2 should be a valid type.`);let u={encode:d,decode:f,encodingLength:p,[a.skip]:!1};return u;function d(n,i){let o=l.clone(this);d.bytes=0;let c=r(e)?!!e(o):!!e;if(u[a.skip]=!c,!c){l.clean(o);return}s(n,i,t,o),d.bytes=o.bytes,l.clean(o)}function f(n){let i=l.clone(this);f.bytes=0;let s=r(e)?!!e(i):!!e;if(u[a.skip]=!s,!s){l.clean(i);return}let c=o(n,t,i);return f.bytes=i.bytes,l.clean(i),c}function p(n){let i=l.clone(this);return(r(e)?e(i):e)&&c(n,t,i),l.clean(i),i.bytes}}})),tE=R(((e,t)=>{var n=UT(),{decodeCommon:r}=GT(),i=WT();t.exports=a;function a(...e){if(e.length===0)throw TypeError(`You should set at least one condition type.`);let t={decode:a,encode:()=>{},[n.skip]:!0};return t;function a(o){a.bytes=0;let s=i.clone(this);for(let c of e){let e=r(o,c,s);if(c[n.skip]!==!0)return a.bytes=s.bytes,i.clean(s),t[n.skip]=!1,e}t[n.skip]=!0}}})),nE=R(((e,t)=>{var n=FT(),r=RT(),i=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,t){return this.stream.slice(e,t)}toString(e,t,n){return this.stream.toString(e,t,n)}readBuffer(e){o(this.index+e,this.length);let t=this.stream.slice(this.index,this.index+e);return this.index+=e,t}indexOf(e,t=0){return this.stream.indexOf(e,this.index+t)-this.index}},a={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(a).forEach(e=>{let t=n(),r=a[e];t(`
|
|
126
126
|
function transaction_${e}() {
|
|
127
127
|
assertSize(this.index + ${t.formats.d(r)}, this.length);
|
|
128
128
|
const value = this.stream.buffer.${e}(this.index);
|
|
@@ -136,10 +136,10 @@ import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/pr
|
|
|
136
136
|
this.index += bytes;
|
|
137
137
|
return value;
|
|
138
138
|
}
|
|
139
|
-
`),i.prototype[e]=t.toFunction({assertSize:o})}),t.exports=i;function o(e,t){if(e>t)throw new r(e,t)}})),wv=R(((e,t)=>{var n=ov(),r=hv(),i=gv(),a=_v(),o=vv(),s=yv(),c=bv(),l=xv(),u=Sv(),{encode:d}=pv(),{decode:f}=fv(),{encodingLength:p}=mv(),m=Cv(),h=av(),g={array:r,bool:a,buffer:i,reserved:o,string:s,when:l,select:u};for(let e of Object.keys(c))g[e]=c[e];var _=Symbol(`schema`);function v(e){let t=new n({readableObjectMode:!1,writableObjectMode:!0,transform:b});return t[_]=e,t}function y(e){let t=null,r=Buffer.isBuffer(e);r||(t=e);let i=new n({transform:x,readableObjectMode:!0,writableObjectMode:!1});return i[_]=t,r&&i.append(e),i}function b(e,t,n){try{d(e,this[_],this);let t=this.slice();this.consume(t.length),n(null,t)}catch(e){n(e)}}function x(e,t,n){this.append(e);try{for(;this.length>0;){let e=new m(this),t=f(e,this[_]);e.commit(),this.push(t)}n()}catch(e){e instanceof h?n():n(e)}}t.exports={createEncodeStream:v,createDecodeStream:y,encode:d,decode:f,encodingLength:p,createEncode:v,createDecode:y,types:g,BinaryStream:n,NotEnoughDataError:h}})),Tv=V(ti(),1),Q=wv(),Ev=T&&typeof T==`object`&&`webcrypto`in T?T.webcrypto:T&&typeof T==`object`&&`randomBytes`in T?T:void 0;function Dv(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function Ov(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function kv(e,...t){if(!Dv(e))throw Error(`Uint8Array expected`);if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length `+t+`, got length=`+e.length)}function Av(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.createHasher`);Ov(e.outputLen),Ov(e.blockLen)}function jv(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function Mv(e,t){kv(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function Nv(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Pv(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Fv(e,t){return e<<32-t|e>>>t}var Iv=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Lv=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Rv(e){if(kv(e),Iv)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Lv[e[n]];return t}var zv={_0:48,_9:57,A:65,F:70,a:97,f:102};function Bv(e){if(e>=zv._0&&e<=zv._9)return e-zv._0;if(e>=zv.A&&e<=zv.F)return e-(zv.A-10);if(e>=zv.a&&e<=zv.f)return e-(zv.a-10)}function Vv(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Iv)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw Error(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=Bv(e.charCodeAt(i)),a=Bv(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw Error(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function Hv(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function Uv(e){return typeof e==`string`&&(e=Hv(e)),kv(e),e}function Wv(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];kv(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var Gv=class{};function Kv(e){let t=t=>e().update(Uv(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function qv(e=32){if(Ev&&typeof Ev.getRandomValues==`function`)return Ev.getRandomValues(new Uint8Array(e));if(Ev&&typeof Ev.randomBytes==`function`)return Uint8Array.from(Ev.randomBytes(e));throw Error(`crypto.getRandomValues must be defined`)}var Jv=BigInt(0),Yv=BigInt(1);function Xv(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function Zv(e,t,n=``){let r=Dv(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function Qv(e){let t=e.toString(16);return t.length&1?`0`+t:t}function $v(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?Jv:BigInt(`0x`+e)}function ey(e){return $v(Rv(e))}function ty(e){return kv(e),$v(Rv(Uint8Array.from(e).reverse()))}function ny(e,t){return Vv(e.toString(16).padStart(t*2,`0`))}function ry(e,t){return ny(e,t).reverse()}function iy(e,t,n){let r;if(typeof t==`string`)try{r=Vv(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(Dv(t))r=Uint8Array.from(t);else throw Error(e+` must be hex string or Uint8Array`);let i=r.length;if(typeof n==`number`&&i!==n)throw Error(e+` of length `+n+` expected, got `+i);return r}var ay=e=>typeof e==`bigint`&&Jv<=e;function oy(e,t,n){return ay(e)&&ay(t)&&ay(n)&&t<=e&&e<n}function sy(e,t,n,r){if(!oy(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function cy(e){let t=0;for(;e>Jv;e>>=Yv,t+=1);return t}var ly=e=>(Yv<<BigInt(e))-Yv;function uy(e,t,n){if(typeof e!=`number`||e<2)throw Error(`hashLen must be a number`);if(typeof t!=`number`||t<2)throw Error(`qByteLen must be a number`);if(typeof n!=`function`)throw Error(`hmacFn must be a function`);let r=e=>new Uint8Array(e),i=e=>Uint8Array.of(e),a=r(e),o=r(e),s=0,c=()=>{a.fill(1),o.fill(0),s=0},l=(...e)=>n(o,a,...e),u=(e=r(0))=>{o=l(i(0),e),a=l(),e.length!==0&&(o=l(i(1),e),a=l())},d=()=>{if(s++>=1e3)throw Error(`drbg: tried 1000 values`);let e=0,n=[];for(;e<t;){a=l();let t=a.slice();n.push(t),e+=a.length}return Wv(...n)};return(e,t)=>{c(),u(e);let n;for(;!(n=t(d()));)u();return c(),n}}function dy(e,t,n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function fy(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e(n,...r);return t.set(n,a),a}}var py=BigInt(0),my=BigInt(1),hy=BigInt(2),gy=BigInt(3),_y=BigInt(4),vy=BigInt(5),yy=BigInt(7),by=BigInt(8),xy=BigInt(9),Sy=BigInt(16);function Cy(e,t){let n=e%t;return n>=py?n:t+n}function wy(e,t){if(e===py)throw Error(`invert: expected non-zero number`);if(t<=py)throw Error(`invert: expected positive modulus, got `+t);let n=Cy(e,t),r=t,i=py,a=my,o=my,s=py;for(;n!==py;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==my)throw Error(`invert: does not exist`);return Cy(i,t)}function Ty(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function Ey(e,t){let n=(e.ORDER+my)/_y,r=e.pow(t,n);return Ty(e,r,t),r}function Dy(e,t){let n=(e.ORDER-vy)/by,r=e.mul(t,hy),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,hy),i),s=e.mul(a,e.sub(o,e.ONE));return Ty(e,s,t),s}function Oy(e){let t=Ly(e),n=ky(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+yy)/Sy;return(e,t)=>{let n=e.pow(t,o),s=e.mul(n,r),c=e.mul(n,i),l=e.mul(n,a),u=e.eql(e.sqr(s),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,s,u),s=e.cmov(l,c,d);let f=e.eql(e.sqr(s),t),p=e.cmov(n,s,f);return Ty(e,p,t),p}}function ky(e){if(e<gy)throw Error(`sqrt is not defined for small field`);let t=e-my,n=0;for(;t%hy===py;)t/=hy,n++;let r=hy,i=Ly(e);for(;Fy(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Ey;let a=i.pow(r,t),o=(t+my)/hy;return function(e,r){if(e.is0(r))return r;if(Fy(e,r)!==1)throw Error(`Cannot find square root`);let i=n,s=e.mul(e.ONE,a),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw Error(`Cannot find square root`);let r=my<<BigInt(i-t-1),a=e.pow(s,r);i=t,s=e.sqr(a),c=e.mul(c,s),l=e.mul(l,a)}return l}}function Ay(e){return e%_y===gy?Ey:e%by===vy?Dy:e%Sy===xy?Oy(e):ky(e)}var jy=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function My(e){return dy(e,jy.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function Ny(e,t,n){if(n<py)throw Error(`invalid exponent, negatives unsupported`);if(n===py)return e.ONE;if(n===my)return t;let r=e.ONE,i=t;for(;n>py;)n&my&&(r=e.mul(r,i)),i=e.sqr(i),n>>=my;return r}function Py(e,t,n=!1){let r=Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),a=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),a),r}function Fy(e,t){let n=(e.ORDER-my)/hy,r=e.pow(t,n),i=e.eql(r,e.ONE),a=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function Iy(e,t){t!==void 0&&Ov(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Ly(e,t,n=!1,r={}){if(e<=py)throw Error(`invalid field: expected ORDER > 0, got `+e);let i,a,o=!1,s;if(typeof t==`object`&&t){if(r.sqrt||n)throw Error(`cannot specify opts in two arguments`);let e=t;e.BITS&&(i=e.BITS),e.sqrt&&(a=e.sqrt),typeof e.isLE==`boolean`&&(n=e.isLE),typeof e.modFromBytes==`boolean`&&(o=e.modFromBytes),s=e.allowedLengths}else typeof t==`number`&&(i=t),r.sqrt&&(a=r.sqrt);let{nBitLength:c,nByteLength:l}=Iy(e,i);if(l>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);let u,d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:ly(c),ZERO:py,ONE:my,allowedLengths:s,create:t=>Cy(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return py<=t&&t<e},is0:e=>e===py,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&my)===my,neg:t=>Cy(-t,e),eql:(e,t)=>e===t,sqr:t=>Cy(t*t,e),add:(t,n)=>Cy(t+n,e),sub:(t,n)=>Cy(t-n,e),mul:(t,n)=>Cy(t*n,e),pow:(e,t)=>Ny(d,e,t),div:(t,n)=>Cy(t*wy(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>wy(t,e),sqrt:a||(t=>(u||=Ay(e),u(d,t))),toBytes:e=>n?ry(e,l):ny(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw Error(`Field.fromBytes: expected `+s+` bytes, got `+t.length);let e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw Error(`Field.fromBytes: expected `+l+` bytes, got `+t.length);let i=n?ty(t):ey(t);if(o&&(i=Cy(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>Py(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function Ry(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function zy(e){let t=Ry(e);return t+Math.ceil(t/2)}function By(e,t,n=!1){let r=e.length,i=Ry(t),a=zy(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=Cy(n?ty(e):ey(e),t-my)+my;return n?ry(o,i):ny(o,i)}function Vy(e,t,n,r){if(typeof e.setBigUint64==`function`)return e.setBigUint64(t,n,r);let i=BigInt(32),a=BigInt(4294967295),o=Number(n>>i&a),s=Number(n&a),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,s,r)}function Hy(e,t,n){return e&t^~e&n}function Uy(e,t,n){return e&t^e&n^t&n}var Wy=class extends Gv{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Pv(this.buffer)}update(e){jv(this),e=Uv(e),kv(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=Pv(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){jv(this),Mv(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,Nv(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;Vy(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=Pv(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen should be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Gy=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ky=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),qy=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Jy=BigInt(2**32-1),Yy=BigInt(32);function Xy(e,t=!1){return t?{h:Number(e&Jy),l:Number(e>>Yy&Jy)}:{h:Number(e>>Yy&Jy)|0,l:Number(e&Jy)|0}}function Zy(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=Xy(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var Qy=(e,t,n)=>e>>>n,$y=(e,t,n)=>e<<32-n|t>>>n,eb=(e,t,n)=>e>>>n|t<<32-n,tb=(e,t,n)=>e<<32-n|t>>>n,nb=(e,t,n)=>e<<64-n|t>>>n-32,rb=(e,t,n)=>e>>>n-32|t<<64-n;function ib(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var ab=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ob=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,sb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),cb=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,lb=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),ub=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,db=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]),fb=new Uint32Array(64),pb=class extends Wy{constructor(e=32){super(64,e,8,!1),this.A=Gy[0]|0,this.B=Gy[1]|0,this.C=Gy[2]|0,this.D=Gy[3]|0,this.E=Gy[4]|0,this.F=Gy[5]|0,this.G=Gy[6]|0,this.H=Gy[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)fb[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=fb[e-15],n=fb[e-2],r=Fv(t,7)^Fv(t,18)^t>>>3,i=Fv(n,17)^Fv(n,19)^n>>>10;fb[e]=i+fb[e-7]+r+fb[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=Fv(o,6)^Fv(o,11)^Fv(o,25),u=l+t+Hy(o,s,c)+db[e]+fb[e]|0,d=(Fv(n,2)^Fv(n,13)^Fv(n,22))+Uy(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){Nv(fb)}destroy(){this.set(0,0,0,0,0,0,0,0),Nv(this.buffer)}},mb=Zy(`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`.split(`.`).map(e=>BigInt(e))),hb=mb[0],gb=mb[1],_b=new Uint32Array(80),vb=new Uint32Array(80),yb=class extends Wy{constructor(e=64){super(128,e,16,!1),this.Ah=qy[0]|0,this.Al=qy[1]|0,this.Bh=qy[2]|0,this.Bl=qy[3]|0,this.Ch=qy[4]|0,this.Cl=qy[5]|0,this.Dh=qy[6]|0,this.Dl=qy[7]|0,this.Eh=qy[8]|0,this.El=qy[9]|0,this.Fh=qy[10]|0,this.Fl=qy[11]|0,this.Gh=qy[12]|0,this.Gl=qy[13]|0,this.Hh=qy[14]|0,this.Hl=qy[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:h}=this;return[e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h]}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let n=0;n<16;n++,t+=4)_b[n]=e.getUint32(t),vb[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=_b[e-15]|0,n=vb[e-15]|0,r=eb(t,n,1)^eb(t,n,8)^Qy(t,n,7),i=tb(t,n,1)^tb(t,n,8)^$y(t,n,7),a=_b[e-2]|0,o=vb[e-2]|0,s=eb(a,o,19)^nb(a,o,61)^Qy(a,o,6),c=sb(i,tb(a,o,19)^rb(a,o,61)^$y(a,o,6),vb[e-7],vb[e-16]),l=cb(c,r,s,_b[e-7],_b[e-16]);_b[e]=l|0,vb[e]=c|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:h,Hh:g,Hl:_}=this;for(let e=0;e<80;e++){let t=eb(u,d,14)^eb(u,d,18)^nb(u,d,41),v=tb(u,d,14)^tb(u,d,18)^rb(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=lb(_,v,b,gb[e],vb[e]),S=ub(x,g,t,y,hb[e],_b[e]),C=x|0,w=eb(n,r,28)^nb(n,r,34)^nb(n,r,39),T=tb(n,r,28)^rb(n,r,34)^rb(n,r,39),E=n&i^n&o^i&o,D=r&a^r&s^a&s;g=m|0,_=h|0,m=f|0,h=p|0,f=u|0,p=d|0,{h:u,l:d}=ib(c|0,l|0,S|0,C|0),c=o|0,l=s|0,o=i|0,s=a|0,i=n|0,a=r|0;let O=ab(C,T,D);n=ob(O,S,w,E),r=O|0}({h:n,l:r}=ib(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=ib(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=ib(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=ib(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=ib(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=ib(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=ib(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=ib(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){Nv(_b,vb)}destroy(){Nv(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},bb=class extends yb{constructor(){super(48),this.Ah=Ky[0]|0,this.Al=Ky[1]|0,this.Bh=Ky[2]|0,this.Bl=Ky[3]|0,this.Ch=Ky[4]|0,this.Cl=Ky[5]|0,this.Dh=Ky[6]|0,this.Dl=Ky[7]|0,this.Eh=Ky[8]|0,this.El=Ky[9]|0,this.Fh=Ky[10]|0,this.Fl=Ky[11]|0,this.Gh=Ky[12]|0,this.Gl=Ky[13]|0,this.Hh=Ky[14]|0,this.Hl=Ky[15]|0}},xb=Kv(()=>new pb),Sb=Kv(()=>new yb),Cb=Kv(()=>new bb),wb=class extends Gv{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Av(e);let n=Uv(t);if(this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),Nv(i)}update(e){return jv(this),this.iHash.update(e),this}digestInto(e){jv(this),kv(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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Tb=(e,t,n)=>new wb(e,t).update(n).digest();Tb.create=(e,t)=>new wb(e,t);var Eb=BigInt(0),Db=BigInt(1);function Ob(e,t){let n=t.negate();return e?n:t}function kb(e,t){let n=Py(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Ab(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function jb(e,t){Ab(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:ly(e),maxNumber:i,shiftBy:BigInt(e)}}function Mb(e,t,n){let{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n,s=Number(e&i),c=e>>o;s>r&&(s-=a,c+=Db);let l=t*r,u=l+Math.abs(s)-1,d=s===0,f=s<0,p=t%2!=0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function Nb(e,t){if(!Array.isArray(e))throw Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function Pb(e,t){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw Error(`invalid scalar at index `+n)})}var Fb=new WeakMap,Ib=new WeakMap;function Lb(e){return Ib.get(e)||1}function Rb(e){if(e!==Eb)throw Error(`invalid wNAF`)}var zb=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Eb;)t&Db&&(n=n.add(r)),r=r.double(),t>>=Db;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=jb(t,this.bits),i=[],a=e,o=a;for(let e=0;e<n;e++){o=a,i.push(o);for(let e=1;e<r;e++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw Error(`invalid scalar`);let r=this.ZERO,i=this.BASE,a=jb(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Mb(n,e,a);n=o,c?i=i.add(Ob(u,t[d])):r=r.add(Ob(l,t[s]))}return Rb(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=jb(e,this.bits);for(let e=0;e<i.windows&&n!==Eb;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=Mb(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return Rb(n),r}getPrecomputes(e,t,n){let r=Fb.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),Fb.set(t,r))),r}cached(e,t,n){let r=Lb(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=Lb(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Ab(t,this.bits),Ib.set(e,t),Fb.delete(e)}hasCache(e){return Lb(e)!==1}};function Bb(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>Eb||r>Eb;)n&Db&&(a=a.add(i)),r&Db&&(o=o.add(i)),i=i.double(),n>>=Db,r>>=Db;return{p1:a,p2:o}}function Vb(e,t,n,r){Nb(n,e),Pb(r,t);let i=n.length,a=r.length;if(i!==a)throw Error(`arrays of points and scalars must have equal length`);let o=e.ZERO,s=cy(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=ly(c),u=Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c,f=o;for(let e=d;e>=0;e-=c){u.fill(o);for(let t=0;t<a;t++){let i=r[t],a=Number(i>>BigInt(e)&l);u[a]=u[a].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(f=f.add(t),e!==0)for(let e=0;e<c;e++)f=f.double()}return f}function Hb(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return My(t),t}return Ly(e,{isLE:n})}function Ub(e,t,n={},r){if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(typeof n==`bigint`&&n>Eb))throw Error(`CURVE.${e} must be positive bigint`)}let i=Hb(t.p,n.Fp,r),a=Hb(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}var Wb=(e,t)=>(e+(e>=0?t:-t)/Zb)/t;function Gb(e,t,n){let[[r,i],[a,o]]=t,s=Wb(o*e,n),c=Wb(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<Yb,f=u<Yb;d&&(l=-l),f&&(u=-u);let p=ly(Math.ceil(cy(n)/2))+Xb;if(l<Yb||l>=p||u<Yb||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}function Kb(e){if(![`compact`,`recovered`,`der`].includes(e))throw Error(`Signature format must be "compact", "recovered", or "der"`);return e}function qb(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return Xv(n.lowS,`lowS`),Xv(n.prehash,`prehash`),n.format!==void 0&&Kb(n.format),n}var Jb={Err:class extends Error{constructor(e=``){super(e)}},_tlv:{encode:(e,t)=>{let{Err:n}=Jb;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length&1)throw new n(`tlv.encode: unpadded data`);let r=t.length/2,i=Qv(r);if(i.length/2&128)throw new n(`tlv.encode: long form length too big`);let a=r>127?Qv(i.length/2|128):``;return Qv(e)+a+i+t},decode(e,t){let{Err:n}=Jb,r=0;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length<2||t[r++]!==e)throw new n(`tlv.decode: wrong tlv`);let i=t[r++],a=!!(i&128),o=0;if(!a)o=i;else{let e=i&127;if(!e)throw new n(`tlv.decode(long): indefinite length not supported`);if(e>4)throw new n(`tlv.decode(long): byte length is too big`);let a=t.subarray(r,r+e);if(a.length!==e)throw new n(`tlv.decode: length bytes not complete`);if(a[0]===0)throw new n(`tlv.decode(long): zero leftmost byte`);for(let e of a)o=o<<8|e;if(r+=e,o<128)throw new n(`tlv.decode(long): not minimal encoding`)}let s=t.subarray(r,r+o);if(s.length!==o)throw new n(`tlv.decode: wrong value length`);return{v:s,l:t.subarray(r+o)}}},_int:{encode(e){let{Err:t}=Jb;if(e<Yb)throw new t(`integer: negative integers are not allowed`);let n=Qv(e);if(Number.parseInt(n[0],16)&8&&(n=`00`+n),n.length&1)throw new t(`unexpected DER parsing assertion: unpadded hex`);return n},decode(e){let{Err:t}=Jb;if(e[0]&128)throw new t(`invalid signature integer: negative`);if(e[0]===0&&!(e[1]&128))throw new t(`invalid signature integer: unnecessary leading zero`);return ey(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=Jb,i=iy(`signature`,e),{v:a,l:o}=r.decode(48,i);if(o.length)throw new t(`invalid signature: left bytes after parsing`);let{v:s,l:c}=r.decode(2,a),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t(`invalid signature: left bytes after parsing`);return{r:n.decode(s),s:n.decode(l)}},hexFromSig(e){let{_tlv:t,_int:n}=Jb,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Yb=BigInt(0),Xb=BigInt(1),Zb=BigInt(2),Qb=BigInt(3),$b=BigInt(4);function ex(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=iy(`private key`,t);try{r=e.fromBytes(i)}catch{throw Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw Error(`invalid private key: out of range [1..N-1]`);return r}function tx(e,t={}){let n=Ub(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;dy(t,{},{allowInfinityPoint:`boolean`,clearCofactor:`function`,isTorsionFree:`function`,fromBytes:`function`,toBytes:`function`,endo:`object`,wrapPrivateKey:`boolean`});let{endo:c}=t;if(c&&(!r.is0(a.a)||typeof c.beta!=`bigint`||!Array.isArray(c.basises)))throw Error(`invalid endo: expected "beta": bigint and "basises": array`);let l=rx(r,i);function u(){if(!r.isOdd)throw Error(`compression is not supported: Field does not have .isOdd()`)}function d(e,t,n){let{x:i,y:a}=t.toAffine(),o=r.toBytes(i);return Xv(n,`isCompressed`),n?(u(),Wv(nx(!r.isOdd(a)),o)):Wv(Uint8Array.of(4),o,r.toBytes(a))}function f(e){Zv(e,void 0,`Point`);let{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,a=e[0],o=e.subarray(1);if(i===t&&(a===2||a===3)){let e=r.fromBytes(o);if(!r.isValid(e))throw Error(`bad point: is not on curve, wrong x`);let t=h(e),n;try{n=r.sqrt(t)}catch(e){let t=e instanceof Error?`: `+e.message:``;throw Error(`bad point: is not on curve, sqrt error`+t)}u();let i=r.isOdd(n);return(a&1)==1!==i&&(n=r.neg(n)),{x:e,y:n}}if(i===n&&a===4){let e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,e*2));if(!g(t,n))throw Error(`bad point: is not on curve`);return{x:t,y:n}}throw Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}let p=t.toBytes||d,m=t.fromBytes||f;function h(e){let t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,a.a)),a.b)}function g(e,t){let n=r.sqr(t),i=h(e);return r.eql(n,i)}if(!g(a.Gx,a.Gy))throw Error(`bad curve params: generator point`);let _=r.mul(r.pow(a.a,Qb),$b),v=r.mul(r.sqr(a.b),BigInt(27));if(r.is0(r.add(_,v)))throw Error(`bad curve params: a or b`);function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof T))throw Error(`ProjectivePoint expected`)}function x(e){if(!c||!c.basises)throw Error(`no endo`);return Gb(e,c.basises,i.ORDER)}let S=fy((e,t)=>{let{X:n,Y:i,Z:a}=e;if(r.eql(a,r.ONE))return{x:n,y:i};let o=e.is0();t??=o?r.ONE:r.inv(a);let s=r.mul(n,t),c=r.mul(i,t),l=r.mul(a,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw Error(`invZ was invalid`);return{x:s,y:c}}),C=fy(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw Error(`bad point: ZERO`)}let{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error(`bad point: x or y not field elements`);if(!g(n,i))throw Error(`bad point: equation left != right`);if(!e.isTorsionFree())throw Error(`bad point: not in prime-order subgroup`);return!0});function w(e,t,n,i,a){return n=new T(r.mul(n.X,e),n.Y,n.Z),t=Ob(i,t),n=Ob(a,n),t.add(n)}class T{constructor(e,t,n){this.X=y(`x`,e),this.Y=y(`y`,t,!0),this.Z=y(`z`,n),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){let{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error(`invalid affine point`);if(e instanceof T)throw Error(`projective point not allowed`);return r.is0(t)&&r.is0(n)?T.ZERO:new T(t,n,r.ONE)}static fromBytes(e){let t=T.fromAffine(m(Zv(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return T.fromBytes(iy(`pointHex`,e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return D.createCache(this,e),t||this.multiply(Qb),this}assertValidity(){C(this)}hasEvenY(){let{y:e}=this.toAffine();if(!r.isOdd)throw Error(`Field doesn't support isOdd`);return!r.isOdd(e)}equals(e){b(e);let{X:t,Y:n,Z:i}=this,{X:a,Y:o,Z:s}=e,c=r.eql(r.mul(t,s),r.mul(a,i)),l=r.eql(r.mul(n,s),r.mul(o,i));return c&&l}negate(){return new T(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=a,n=r.mul(t,Qb),{X:i,Y:o,Z:s}=this,c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),f=r.mul(o,o),p=r.mul(s,s),m=r.mul(i,o);return m=r.add(m,m),u=r.mul(i,s),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,p),l=r.add(c,l),c=r.sub(f,l),l=r.add(f,l),l=r.mul(c,l),c=r.mul(m,c),u=r.mul(n,u),p=r.mul(e,p),m=r.sub(d,p),m=r.mul(e,m),m=r.add(m,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,p),d=r.mul(d,m),l=r.add(l,d),p=r.mul(o,s),p=r.add(p,p),d=r.mul(p,m),c=r.sub(c,d),u=r.mul(p,f),u=r.add(u,u),u=r.add(u,u),new T(c,l,u)}add(e){b(e);let{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:c}=e,l=r.ZERO,u=r.ZERO,d=r.ZERO,f=a.a,p=r.mul(a.b,Qb),m=r.mul(t,o),h=r.mul(n,s),g=r.mul(i,c),_=r.add(t,n),v=r.add(o,s);_=r.mul(_,v),v=r.add(m,h),_=r.sub(_,v),v=r.add(t,i);let y=r.add(o,c);return v=r.mul(v,y),y=r.add(m,g),v=r.sub(v,y),y=r.add(n,i),l=r.add(s,c),y=r.mul(y,l),l=r.add(h,g),y=r.sub(y,l),d=r.mul(f,v),l=r.mul(p,g),d=r.add(l,d),l=r.sub(h,d),d=r.add(h,d),u=r.mul(l,d),h=r.add(m,m),h=r.add(h,m),g=r.mul(f,g),v=r.mul(p,v),h=r.add(h,g),g=r.sub(m,g),g=r.mul(f,g),v=r.add(v,g),m=r.mul(h,v),u=r.add(u,m),m=r.mul(y,v),l=r.mul(_,l),l=r.sub(l,m),m=r.mul(_,h),d=r.mul(y,d),d=r.add(d,m),new T(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(T.ZERO)}multiply(e){let{endo:n}=t;if(!i.isValidNot0(e))throw Error(`invalid scalar: out of range`);let r,a,o=e=>D.cached(this,e,e=>kb(T,e));if(n){let{k1neg:t,k1:i,k2neg:s,k2:c}=x(e),{p:l,f:u}=o(i),{p:d,f}=o(c);a=u.add(f),r=w(n.beta,l,d,t,s)}else{let{p:t,f:n}=o(e);r=t,a=n}return kb(T,[r,a])[0]}multiplyUnsafe(e){let{endo:n}=t,r=this;if(!i.isValid(e))throw Error(`invalid scalar: out of range`);if(e===Yb||r.is0())return T.ZERO;if(e===Xb)return r;if(D.hasCache(this))return this.multiply(e);if(n){let{k1neg:t,k1:i,k2neg:a,k2:o}=x(e),{p1:s,p2:c}=Bb(T,r,i,o);return w(n.beta,s,c,t,a)}return D.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){let r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return S(this,e)}isTorsionFree(){let{isTorsionFree:e}=t;return o===Xb?!0:e?e(T,this):D.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===Xb?this:e?e(T,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Xv(e,`isCompressed`),this.assertValidity(),p(T,this,e)}toHex(e=!0){return Rv(this.toBytes(e))}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return kb(T,e)}static msm(e,t){return Vb(T,i,e,t)}static fromPrivateKey(e){return T.BASE.multiply(ex(i,e))}}T.BASE=new T(a.Gx,a.Gy,r.ONE),T.ZERO=new T(r.ZERO,r.ONE,r.ZERO),T.Fp=r,T.Fn=i;let E=i.BITS,D=new zb(T,t.endo?Math.ceil(E/2):E);return T.BASE.precompute(8),T}function nx(e){return Uint8Array.of(e?2:3)}function rx(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function ix(e,t={}){let{Fn:n}=e,r=t.randomBytes||qv,i=Object.assign(rx(e.Fp,n),{seed:zy(n.ORDER)});function a(e){try{return!!ex(n,e)}catch{return!1}}function o(t,n){let{publicKey:r,publicKeyUncompressed:a}=i;try{let i=t.length;return n===!0&&i!==r||n===!1&&i!==a?!1:!!e.fromBytes(t)}catch{return!1}}function s(e=r(i.seed)){return By(Zv(e,i.seed,`seed`),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(ex(n,t)).toBytes(r)}function l(e){let t=s(e);return{secretKey:t,publicKey:c(t)}}function u(t){if(typeof t==`bigint`)return!1;if(t instanceof e)return!0;let{secretKey:r,publicKey:a,publicKeyUncompressed:o}=i;if(n.allowedLengths||r===a)return;let s=iy(`key`,t).length;return s===a||s===o}function d(t,r,i=!0){if(u(t)===!0)throw Error(`first arg must be private key`);if(u(r)===!1)throw Error(`second arg must be public key`);let a=ex(n,t);return e.fromHex(r).multiply(a).toBytes(i)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:l,Point:e,utils:{isValidSecretKey:a,isValidPublicKey:o,randomSecretKey:s,isValidPrivateKey:a,randomPrivateKey:s,normPrivateKeyToScalar:e=>ex(n,e),precompute(t=8,n=e.BASE){return n.precompute(t,!1)}},lengths:i})}function ax(e,t,n={}){Av(t),dy(n,{},{hmac:`function`,lowS:`boolean`,randomBytes:`function`,bits2int:`function`,bits2int_modN:`function`});let r=n.randomBytes||qv,i=n.hmac||((e,...n)=>Tb(t,e,Wv(...n))),{Fp:a,Fn:o}=e,{ORDER:s,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p}=ix(e,n),m={prehash:!1,lowS:typeof n.lowS==`boolean`&&n.lowS,format:void 0,extraEntropy:!1},h=`compact`;function g(e){return e>s>>Xb}function _(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function v(e,t){Kb(t);let n=p.signature;return Zv(e,t===`compact`?n:t===`recovered`?n+1:void 0,`${t} signature`)}class y{constructor(e,t,n){this.r=_(`r`,e),this.s=_(`s`,t),n!=null&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=h){v(e,t);let n;if(t===`der`){let{r:t,s:n}=Jb.toSig(Zv(e));return new y(t,n)}t===`recovered`&&(n=e[0],t=`compact`,e=e.subarray(1));let r=o.BYTES,i=e.subarray(0,r),a=e.subarray(r,r*2);return new y(o.fromBytes(i),o.fromBytes(a),n)}static fromHex(e,t){return this.fromBytes(Vv(e),t)}addRecoveryBit(e){return new y(this.r,this.s,e)}recoverPublicKey(t){let n=a.ORDER,{r,s:i,recovery:c}=this;if(c==null||![0,1,2,3].includes(c))throw Error(`recovery id invalid`);if(s*Zb<n&&c>1)throw Error(`recovery id is ambiguous for h>1 curve`);let l=c===2||c===3?r+s:r;if(!a.isValid(l))throw Error(`recovery id 2 or 3 invalid`);let u=a.toBytes(l),d=e.fromBytes(Wv(nx(!(c&1)),u)),f=o.inv(l),p=x(iy(`msgHash`,t)),m=o.create(-p*f),h=o.create(i*f),g=e.BASE.multiplyUnsafe(m).add(d.multiplyUnsafe(h));if(g.is0())throw Error(`point at infinify`);return g.assertValidity(),g}hasHighS(){return g(this.s)}toBytes(e=h){if(Kb(e),e===`der`)return Vv(Jb.hexFromSig(this));let t=o.toBytes(this.r),n=o.toBytes(this.s);if(e===`recovered`){if(this.recovery==null)throw Error(`recovery bit must be present`);return Wv(Uint8Array.of(this.recovery),t,n)}return Wv(t,n)}toHex(e){return Rv(this.toBytes(e))}assertValidity(){}static fromCompact(e){return y.fromBytes(iy(`sig`,e),`compact`)}static fromDER(e){return y.fromBytes(iy(`sig`,e),`der`)}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes(`der`)}toDERHex(){return Rv(this.toBytes(`der`))}toCompactRawBytes(){return this.toBytes(`compact`)}toCompactHex(){return Rv(this.toBytes(`compact`))}}let b=n.bits2int||function(e){if(e.length>8192)throw Error(`input is too large`);let t=ey(e),n=e.length*8-c;return n>0?t>>BigInt(n):t},x=n.bits2int_modN||function(e){return o.create(b(e))},S=ly(c);function C(e){return sy(`num < 2^`+c,e,Yb,S),o.toBytes(e)}function w(e,n){return Zv(e,void 0,`message`),n?Zv(t(e),void 0,`prehashed message`):e}function T(t,n,i){if([`recovered`,`canonical`].some(e=>e in i))throw Error(`sign() legacy options not supported`);let{lowS:a,prehash:s,extraEntropy:c}=qb(i,m);t=w(t,s);let l=x(t),u=ex(o,n),d=[C(u),C(l)];if(c!=null&&c!==!1){let e=c===!0?r(p.secretKey):c;d.push(iy(`extraEntropy`,e))}let f=Wv(...d),h=l;function _(t){let n=b(t);if(!o.isValidNot0(n))return;let r=o.inv(n),i=e.BASE.multiply(n).toAffine(),s=o.create(i.x);if(s===Yb)return;let c=o.create(r*o.create(h+s*u));if(c===Yb)return;let l=(i.x===s?0:2)|Number(i.y&Xb),d=c;return a&&g(c)&&(d=o.neg(c),l^=1),new y(s,d,l)}return{seed:f,k2sig:_}}function E(e,n,r={}){e=iy(`message`,e);let{seed:a,k2sig:s}=T(e,n,r);return uy(t.outputLen,o.BYTES,i)(a,s)}function D(e){let t,n=typeof e==`string`||Dv(e),r=!n&&typeof e==`object`&&!!e&&typeof e.r==`bigint`&&typeof e.s==`bigint`;if(!n&&!r)throw Error(`invalid signature, expected Uint8Array, hex string or Signature instance`);if(r)t=new y(e.r,e.s);else if(n){try{t=y.fromBytes(iy(`sig`,e),`der`)}catch(e){if(!(e instanceof Jb.Err))throw e}if(!t)try{t=y.fromBytes(iy(`sig`,e),`compact`)}catch{return!1}}return t||!1}function O(t,n,r,i={}){let{lowS:a,prehash:s,format:c}=qb(i,m);if(r=iy(`publicKey`,r),n=w(iy(`message`,n),s),`strict`in i)throw Error(`options.strict was renamed to lowS`);let l=c===void 0?D(t):y.fromBytes(iy(`sig`,t),c);if(l===!1)return!1;try{let t=e.fromBytes(r);if(a&&l.hasHighS())return!1;let{r:i,s}=l,c=x(n),u=o.inv(s),d=o.create(c*u),f=o.create(i*u),p=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(f));return!p.is0()&&o.create(p.x)===i}catch{return!1}}function k(e,t,n={}){let{prehash:r}=qb(n,m);return t=w(t,r),y.fromBytes(e,`recovered`).recoverPublicKey(t).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p,Point:e,sign:E,verify:O,recoverPublicKey:k,Signature:y,hash:t})}function ox(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:Ly(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}function sx(e){let{CURVE:t,curveOpts:n}=ox(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function cx(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Iy(n.Fn.ORDER,n.Fn.BITS))})}function lx(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=sx(e);return cx(e,ax(tx(t,n),r,i))}function ux(e,t){let n=t=>lx({...e,hash:t});return{...n(t),create:n}}var dx={p:BigInt(`0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff`),n:BigInt(`0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551`),h:BigInt(1),a:BigInt(`0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc`),b:BigInt(`0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b`),Gx:BigInt(`0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296`),Gy:BigInt(`0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5`)},fx={p:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff`),n:BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973`),h:BigInt(1),a:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc`),b:BigInt(`0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef`),Gx:BigInt(`0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7`),Gy:BigInt(`0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f`)},px={p:BigInt(`0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),n:BigInt(`0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409`),h:BigInt(1),a:BigInt(`0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc`),b:BigInt(`0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00`),Gx:BigInt(`0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66`),Gy:BigInt(`0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650`)},mx=Ly(dx.p),hx=Ly(fx.p),gx=Ly(px.p),_x=ux({...dx,Fp:mx,lowS:!1},xb);ux({...fx,Fp:hx,lowS:!1},Cb),ux({...px,Fp:gx,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Sb);var vx=_x,yx=R((e=>{e.toString=function(e){switch(e){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_`+e},e.toType=function(e){switch(e.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 e.toUpperCase().startsWith(`UNKNOWN_`)?parseInt(e.slice(8)):0}})),bx=R((e=>{e.toString=function(e){switch(e){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_`+e},e.toRcode=function(e){switch(e.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}})),xx=R((e=>{e.toString=function(e){switch(e){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_`+e},e.toOpcode=function(e){switch(e.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}})),Sx=R((e=>{e.toString=function(e){switch(e){case 1:return`IN`;case 2:return`CS`;case 3:return`CH`;case 4:return`HS`;case 255:return`ANY`}return`UNKNOWN_`+e},e.toClass=function(e){switch(e.toUpperCase()){case`IN`:return 1;case`CS`:return 2;case`CH`:return 3;case`HS`:return 4;case`ANY`:return 255}return 0}})),Cx=R((e=>{e.toString=function(e){switch(e){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 e<0?null:`OPTION_${e}`},e.toCode=function(e){if(typeof e==`number`)return e;if(!e)return-1;switch(e.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 t=e.match(/_(\d+)$/);return t?parseInt(t[1],10):-1}})),wx=R(((e,t)=>{var n=(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.decode=c,e.encode=s,e.familyOf=o,e.name=void 0,e.sizeOf=a,e.v6=e.v4=void 0;let t=/^(\d{1,3}\.){3,3}\d{1,3}$/,n=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,r={name:`v4`,size:4,isFormat:e=>t.test(e),encode(e,t,n){n=~~n,t||=new Uint8Array(n+4);let r=e.length,i=0;for(let a=0;a<r;){let r=e.charCodeAt(a++);r===46?(t[n++]=i,i=0):i=i*10+(r-48)}return t[n]=i,t},decode(e,t){return t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`}};e.v4=r;let i={name:`v6`,size:16,isFormat:e=>e.length>0&&n.test(e),encode(e,t,n){n=~~n;let r=n+16,i=-1,a=0,o=0,s=!0,c=!1;t||=new Uint8Array(n+16);for(let l=0;l<e.length;l++){let u=e.charCodeAt(l);u===58?(s?i===-1?n<r&&(i=n):(n<r&&(t[n]=0),n<r-1&&(t[n+1]=0),n+=2):(c===!0?(n<r&&(t[n]=o),n++):(n<r&&(t[n]=a>>8),n<r-1&&(t[n+1]=a&255),n+=2),a=0,o=0),s=!0,c=!1):u===46?(n<r&&(t[n]=o),n++,o=0,a=0,s=!1,c=!0):(s=!1,u>=97?u-=87:u>=65?u-=55:(u-=48,o=o*10+u),a=(a<<4)+u)}if(s===!1)c===!0?(n<r&&(t[n]=o),n++):(n<r&&(t[n]=a>>8),n<r-1&&(t[n+1]=a&255),n+=2);else if(i===0)n<r&&(t[n]=0),n<r-1&&(t[n+1]=0),n+=2;else if(i!==-1){n+=2;for(let e=Math.min(n-1,r-1);e>=i+2;e--)t[e]=t[e-2];t[i]=0,t[i+1]=0,i=n}if(i!==n&&i!==-1)for(n>r-2&&(n=r-2);r>i;)t[--r]=n<r&&n>i?t[--n]:0;else for(;n<r;)t[n++]=0;return t},decode(e,t){t=~~t;let n=``;for(let r=0;r<16;r+=2)r!==0&&(n+=`:`),n+=(e[t+r]<<8|e[t+r+1]).toString(16);return n.replace(/(^|:)0(:0)*:0(:|$)/,`$1::$3`).replace(/:{3,4}/,`::`)}};e.v6=i,e.name=`ip`;function a(e){if(r.isFormat(e))return r.size;if(i.isFormat(e))return i.size;throw Error(`Invalid ip address: ${e}`)}function o(e){return a(e)===r.size?1:2}function s(e,t,n){n=~~n;let o=a(e);return typeof t==`function`&&(t=t(n+o)),o===r.size?r.encode(e,t,n):i.encode(e,t,n)}function c(e,t,n){if(t=~~t,n||=e.length-t,n===r.size)return r.decode(e,t,n);if(n===i.size)return i.decode(e,t,n);throw Error(`Invalid buffer size needs to be ${r.size} for v4 or ${i.size} for v6.`)}return`default`in e?e.default:e})({});typeof define==`function`&&define.amd?define([],function(){return n}):typeof t==`object`&&typeof e==`object`&&(t.exports=n)})),Tx=R((e=>{var t=te(`buffer`).Buffer,n=yx(),r=bx(),i=xx(),a=Sx(),o=Cx(),s=wx(),c=0,l=32768,u=32768,d=-32769,f=32768,p=-32769,m=e.name={};m.encode=function(e,n,r,{mail:i=!1}={}){n||=t.alloc(m.encodingLength(e)),r||=0;let a=r,o=e.replace(/^\.|\.$/gm,``);if(o.length){let e=[];if(i){let t=``;o.split(`.`).forEach(n=>{n.endsWith(`\\`)?t+=(t.length?`.`:``)+n.slice(0,-1):e.length===0&&t.length?e.push(t+`.`+n):e.push(n)})}else e=o.split(`.`);for(let t=0;t<e.length;t++){let i=n.write(e[t],r+1);n[r]=i,r+=i+1}}return n[r++]=0,m.encode.bytes=r-a,n},m.encode.bytes=0,m.decode=function(e,t,{mail:n=!1}={}){t||=0;let r=[],i=t,a=0,o=0,s=!1;for(;;){if(t>=e.length)throw Error(`Cannot decode name (buffer overflow)`);let c=e[t++];if(o+=+!s,c===0)break;if(!(c&192)){if(t+c>e.length)throw Error(`Cannot decode name (buffer overflow)`);if(a+=c+1,a>254)throw Error(`Cannot decode name (name too long)`);let i=e.toString(`utf-8`,t,t+c);n&&(i=i.replace(/\./g,`\\.`)),r.push(i),t+=c,o+=s?0:c}else if((c&192)==192){if(t+1>e.length)throw Error(`Cannot decode name (buffer overflow)`);let n=e.readUInt16BE(t-1)-49152;if(n>=i)throw Error(`Cannot decode name (bad pointer)`);t=n,i=n,o+=+!s,s=!0}else throw Error(`Cannot decode name (bad label)`)}return m.decode.bytes=o,r.length===0?`.`:r.join(`.`)},m.decode.bytes=0,m.encodingLength=function(e){return e===`.`||e===`..`?1:t.byteLength(e.replace(/^\.|\.$/gm,``))+2};var h={};h.encode=function(e,n,r){n||=t.alloc(h.encodingLength(e)),r||=0;let i=n.write(e,r+1);return n[r]=i,h.encode.bytes=i+1,n},h.encode.bytes=0,h.decode=function(e,t){t||=0;let n=e[t],r=e.toString(`utf-8`,t+1,t+1+n);return h.decode.bytes=n+1,r},h.decode.bytes=0,h.encodingLength=function(e){return t.byteLength(e)+1};var g={};g.encode=function(e,t,n){t||=g.encodingLength(e),n||=0;let r=(e.flags||0)&32767,i=e.type===`response`?l:c;return t.writeUInt16BE(e.id||0,n),t.writeUInt16BE(r|i,n+2),t.writeUInt16BE(e.questions.length,n+4),t.writeUInt16BE(e.answers.length,n+6),t.writeUInt16BE(e.authorities.length,n+8),t.writeUInt16BE(e.additionals.length,n+10),t},g.encode.bytes=12,g.decode=function(e,t){if(t||=0,e.length<12)throw Error(`Header must be 12 bytes`);let n=e.readUInt16BE(t+2);return{id:e.readUInt16BE(t),type:n&l?`response`:`query`,flags:n&32767,flag_qr:(n>>15&1)==1,opcode:i.toString(n>>11&15),flag_aa:(n>>10&1)==1,flag_tc:(n>>9&1)==1,flag_rd:(n>>8&1)==1,flag_ra:(n>>7&1)==1,flag_z:(n>>6&1)==1,flag_ad:(n>>5&1)==1,flag_cd:(n>>4&1)==1,rcode:r.toString(n&15),questions:Array(e.readUInt16BE(t+4)),answers:Array(e.readUInt16BE(t+6)),authorities:Array(e.readUInt16BE(t+8)),additionals:Array(e.readUInt16BE(t+10))}},g.decode.bytes=12,g.encodingLength=function(){return 12};var _=e.unknown={};_.encode=function(e,n,r){return n||=t.alloc(_.encodingLength(e)),r||=0,n.writeUInt16BE(e.length,r),e.copy(n,r+2),_.encode.bytes=e.length+2,n},_.encode.bytes=0,_.decode=function(e,t){t||=0;let n=e.readUInt16BE(t),r=e.slice(t+2,t+2+n);return _.decode.bytes=n+2,r},_.decode.bytes=0,_.encodingLength=function(e){return e.length+2};var v=e.ns={};v.encode=function(e,n,r){return n||=t.alloc(v.encodingLength(e)),r||=0,m.encode(e,n,r+2),n.writeUInt16BE(m.encode.bytes,r),v.encode.bytes=m.encode.bytes+2,n},v.encode.bytes=0,v.decode=function(e,t){t||=0;let n=e.readUInt16BE(t),r=m.decode(e,t+2);return v.decode.bytes=n+2,r},v.decode.bytes=0,v.encodingLength=function(e){return m.encodingLength(e)+2};var y=e.soa={};y.encode=function(e,n,r){n||=t.alloc(y.encodingLength(e)),r||=0;let i=r;return r+=2,m.encode(e.mname,n,r),r+=m.encode.bytes,m.encode(e.rname,n,r,{mail:!0}),r+=m.encode.bytes,n.writeUInt32BE(e.serial||0,r),r+=4,n.writeUInt32BE(e.refresh||0,r),r+=4,n.writeUInt32BE(e.retry||0,r),r+=4,n.writeUInt32BE(e.expire||0,r),r+=4,n.writeUInt32BE(e.minimum||0,r),r+=4,n.writeUInt16BE(r-i-2,i),y.encode.bytes=r-i,n},y.encode.bytes=0,y.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.mname=m.decode(e,t),t+=m.decode.bytes,r.rname=m.decode(e,t,{mail:!0}),t+=m.decode.bytes,r.serial=e.readUInt32BE(t),t+=4,r.refresh=e.readUInt32BE(t),t+=4,r.retry=e.readUInt32BE(t),t+=4,r.expire=e.readUInt32BE(t),t+=4,r.minimum=e.readUInt32BE(t),t+=4,y.decode.bytes=t-n,r},y.decode.bytes=0,y.encodingLength=function(e){return 22+m.encodingLength(e.mname)+m.encodingLength(e.rname)};var b=e.txt={};b.encode=function(e,n,r){Array.isArray(e)||(e=[e]);for(let n=0;n<e.length;n++)if(typeof e[n]==`string`&&(e[n]=t.from(e[n])),!t.isBuffer(e[n]))throw Error(`Must be a Buffer`);n||=t.alloc(b.encodingLength(e)),r||=0;let i=r;return r+=2,e.forEach(function(e){n[r++]=e.length,e.copy(n,r,0,e.length),r+=e.length}),n.writeUInt16BE(r-i-2,i),b.encode.bytes=r-i,n},b.encode.bytes=0,b.decode=function(e,t){t||=0;let n=t,r=e.readUInt16BE(t);t+=2;let i=[];for(;r>0;){let n=e[t++];if(--r,r<n)throw Error(`Buffer overflow`);i.push(e.slice(t,t+n)),t+=n,r-=n}return b.decode.bytes=t-n,i},b.decode.bytes=0,b.encodingLength=function(e){Array.isArray(e)||(e=[e]);let n=2;return e.forEach(function(e){n+=typeof e==`string`?t.byteLength(e)+1:e.length+1}),n};var x=e.null={};x.encode=function(e,n,r){n||=t.alloc(x.encodingLength(e)),r||=0,typeof e==`string`&&(e=t.from(e)),e||=t.alloc(0);let i=r;r+=2;let a=e.length;return e.copy(n,r,0,a),r+=a,n.writeUInt16BE(r-i-2,i),x.encode.bytes=r-i,n},x.encode.bytes=0,x.decode=function(e,t){t||=0;let n=t,r=e.readUInt16BE(t);t+=2;let i=e.slice(t,t+r);return t+=r,x.decode.bytes=t-n,i},x.decode.bytes=0,x.encodingLength=function(e){return e?(t.isBuffer(e)?e.length:t.byteLength(e))+2:2};var S=e.hinfo={};S.encode=function(e,n,r){n||=t.alloc(S.encodingLength(e)),r||=0;let i=r;return r+=2,h.encode(e.cpu,n,r),r+=h.encode.bytes,h.encode(e.os,n,r),r+=h.encode.bytes,n.writeUInt16BE(r-i-2,i),S.encode.bytes=r-i,n},S.encode.bytes=0,S.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.cpu=h.decode(e,t),t+=h.decode.bytes,r.os=h.decode(e,t),t+=h.decode.bytes,S.decode.bytes=t-n,r},S.decode.bytes=0,S.encodingLength=function(e){return h.encodingLength(e.cpu)+h.encodingLength(e.os)+2};var C=e.ptr={},w=e.cname=C,T=e.dname=C;C.encode=function(e,n,r){return n||=t.alloc(C.encodingLength(e)),r||=0,m.encode(e,n,r+2),n.writeUInt16BE(m.encode.bytes,r),C.encode.bytes=m.encode.bytes+2,n},C.encode.bytes=0,C.decode=function(e,t){t||=0;let n=m.decode(e,t+2);return C.decode.bytes=m.decode.bytes+2,n},C.decode.bytes=0,C.encodingLength=function(e){return m.encodingLength(e)+2};var E=e.srv={};E.encode=function(e,n,r){n||=t.alloc(E.encodingLength(e)),r||=0,n.writeUInt16BE(e.priority||0,r+2),n.writeUInt16BE(e.weight||0,r+4),n.writeUInt16BE(e.port||0,r+6),m.encode(e.target,n,r+8);let i=m.encode.bytes+6;return n.writeUInt16BE(i,r),E.encode.bytes=i+2,n},E.encode.bytes=0,E.decode=function(e,t){t||=0;let n=e.readUInt16BE(t),r={};return r.priority=e.readUInt16BE(t+2),r.weight=e.readUInt16BE(t+4),r.port=e.readUInt16BE(t+6),r.target=m.decode(e,t+8),E.decode.bytes=n+2,r},E.decode.bytes=0,E.encodingLength=function(e){return 8+m.encodingLength(e.target)};var D=e.caa={};D.ISSUER_CRITICAL=128,D.encode=function(e,n,r){let i=D.encodingLength(e);return n||=t.alloc(D.encodingLength(e)),r||=0,e.issuerCritical&&(e.flags=D.ISSUER_CRITICAL),n.writeUInt16BE(i-2,r),r+=2,n.writeUInt8(e.flags||0,r),r+=1,h.encode(e.tag,n,r),r+=h.encode.bytes,n.write(e.value,r),r+=t.byteLength(e.value),D.encode.bytes=i,n},D.encode.bytes=0,D.decode=function(e,t){t||=0;let n=e.readUInt16BE(t);t+=2;let r=t,i={};return i.flags=e.readUInt8(t),t+=1,i.tag=h.decode(e,t),t+=h.decode.bytes,i.value=e.toString(`utf-8`,t,r+n),i.issuerCritical=!!(i.flags&D.ISSUER_CRITICAL),D.decode.bytes=n+2,i},D.decode.bytes=0,D.encodingLength=function(e){return h.encodingLength(e.tag)+h.encodingLength(e.value)+2};var O=e.mx={};O.encode=function(e,n,r){n||=t.alloc(O.encodingLength(e)),r||=0;let i=r;return r+=2,n.writeUInt16BE(e.preference||0,r),r+=2,m.encode(e.exchange,n,r),r+=m.encode.bytes,n.writeUInt16BE(r-i-2,i),O.encode.bytes=r-i,n},O.encode.bytes=0,O.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.preference=e.readUInt16BE(t),t+=2,r.exchange=m.decode(e,t),t+=m.decode.bytes,O.decode.bytes=t-n,r},O.encodingLength=function(e){return 4+m.encodingLength(e.exchange)};var k=e.a={};k.encode=function(e,n,r){return n||=t.alloc(k.encodingLength(e)),r||=0,n.writeUInt16BE(4,r),r+=2,s.v4.encode(e,n,r),k.encode.bytes=6,n},k.encode.bytes=0,k.decode=function(e,t){t||=0,t+=2;let n=s.v4.decode(e,t);return k.decode.bytes=6,n},k.decode.bytes=0,k.encodingLength=function(){return 6};var A=e.aaaa={};A.encode=function(e,n,r){return n||=t.alloc(A.encodingLength(e)),r||=0,n.writeUInt16BE(16,r),r+=2,s.v6.encode(e,n,r),A.encode.bytes=18,n},A.encode.bytes=0,A.decode=function(e,t){t||=0,t+=2;let n=s.v6.decode(e,t);return A.decode.bytes=18,n},A.decode.bytes=0,A.encodingLength=function(){return 18};var j=e.option={};j.encode=function(e,n,r){n||=t.alloc(j.encodingLength(e)),r||=0;let i=r,a=o.toCode(e.code);if(n.writeUInt16BE(a,r),r+=2,e.data)n.writeUInt16BE(e.data.length,r),r+=2,e.data.copy(n,r),r+=e.data.length;else switch(a){case 8:let i=e.sourcePrefixLength||0,a=e.family||s.familyOf(e.ip),o=s.encode(e.ip,t.alloc),c=Math.ceil(i/8);n.writeUInt16BE(c+4,r),r+=2,n.writeUInt16BE(a,r),r+=2,n.writeUInt8(i,r++),n.writeUInt8(e.scopePrefixLength||0,r++),o.copy(n,r,0,c),r+=c;break;case 11:e.timeout?(n.writeUInt16BE(2,r),r+=2,n.writeUInt16BE(e.timeout,r),r+=2):(n.writeUInt16BE(0,r),r+=2);break;case 12:let l=e.length||0;n.writeUInt16BE(l,r),r+=2,n.fill(0,r,r+l),r+=l;break;case 14:let u=e.tags.length*2;n.writeUInt16BE(u,r),r+=2;for(let t of e.tags)n.writeUInt16BE(t,r),r+=2;break;default:throw Error(`Unknown roption code: ${e.code}`)}return j.encode.bytes=r-i,n},j.encode.bytes=0,j.decode=function(e,n){n||=0;let r={};r.code=e.readUInt16BE(n),r.type=o.toString(r.code),n+=2;let i=e.readUInt16BE(n);switch(n+=2,r.data=e.slice(n,n+i),r.code){case 8:r.family=e.readUInt16BE(n),n+=2,r.sourcePrefixLength=e.readUInt8(n++),r.scopePrefixLength=e.readUInt8(n++);let a=t.alloc(r.family===1?4:16);e.copy(a,0,n,n+i-4),r.ip=s.decode(a);break;case 11:i>0&&(r.timeout=e.readUInt16BE(n),n+=2);break;case 14:r.tags=[];for(let t=0;t<i;t+=2)r.tags.push(e.readUInt16BE(n)),n+=2}return j.decode.bytes=i+4,r},j.decode.bytes=0,j.encodingLength=function(e){if(e.data)return e.data.length+4;switch(o.toCode(e.code)){case 8:let t=e.sourcePrefixLength||0;return Math.ceil(t/8)+8;case 11:return typeof e.timeout==`number`?6:4;case 12:return e.length+4;case 14:return 4+e.tags.length*2}throw Error(`Unknown roption code: ${e.code}`)};var M=e.opt={};M.encode=function(e,n,r){n||=t.alloc(M.encodingLength(e)),r||=0;let i=r,a=ae(e,j);return n.writeUInt16BE(a,r),r=oe(e,j,n,r+2),M.encode.bytes=r-i,n},M.encode.bytes=0,M.decode=function(e,t){t||=0;let n=t,r=[],i=e.readUInt16BE(t);t+=2;let a=0;for(;i>0;)r[a++]=j.decode(e,t),t+=j.decode.bytes,i-=j.decode.bytes;return M.decode.bytes=t-n,r},M.decode.bytes=0,M.encodingLength=function(e){return 2+ae(e||[],j)};var N=e.dnskey={};N.PROTOCOL_DNSSEC=3,N.ZONE_KEY=128,N.SECURE_ENTRYPOINT=32768,N.encode=function(e,n,r){n||=t.alloc(N.encodingLength(e)),r||=0;let i=r,a=e.key;if(!t.isBuffer(a))throw Error(`Key must be a Buffer`);return r+=2,n.writeUInt16BE(e.flags,r),r+=2,n.writeUInt8(N.PROTOCOL_DNSSEC,r),r+=1,n.writeUInt8(e.algorithm,r),r+=1,a.copy(n,r,0,a.length),r+=a.length,N.encode.bytes=r-i,n.writeUInt16BE(N.encode.bytes-2,i),n},N.encode.bytes=0,N.decode=function(e,t){t||=0;let n=t;var r={},i=e.readUInt16BE(t);if(t+=2,r.flags=e.readUInt16BE(t),t+=2,e.readUInt8(t)!==N.PROTOCOL_DNSSEC)throw Error(`Protocol must be 3`);return t+=1,r.algorithm=e.readUInt8(t),t+=1,r.key=e.slice(t,n+i+2),t+=r.key.length,N.decode.bytes=t-n,r},N.decode.bytes=0,N.encodingLength=function(e){return 6+t.byteLength(e.key)};var P=e.rrsig={};P.encode=function(e,r,i){r||=t.alloc(P.encodingLength(e)),i||=0;let a=i,o=e.signature;if(!t.isBuffer(o))throw Error(`Signature must be a Buffer`);return i+=2,r.writeUInt16BE(n.toType(e.typeCovered),i),i+=2,r.writeUInt8(e.algorithm,i),i+=1,r.writeUInt8(e.labels,i),i+=1,r.writeUInt32BE(e.originalTTL,i),i+=4,r.writeUInt32BE(e.expiration,i),i+=4,r.writeUInt32BE(e.inception,i),i+=4,r.writeUInt16BE(e.keyTag,i),i+=2,m.encode(e.signersName,r,i),i+=m.encode.bytes,o.copy(r,i,0,o.length),i+=o.length,P.encode.bytes=i-a,r.writeUInt16BE(P.encode.bytes-2,a),r},P.encode.bytes=0,P.decode=function(e,t){t||=0;let r=t;var i={},a=e.readUInt16BE(t);return t+=2,i.typeCovered=n.toString(e.readUInt16BE(t)),t+=2,i.algorithm=e.readUInt8(t),t+=1,i.labels=e.readUInt8(t),t+=1,i.originalTTL=e.readUInt32BE(t),t+=4,i.expiration=e.readUInt32BE(t),t+=4,i.inception=e.readUInt32BE(t),t+=4,i.keyTag=e.readUInt16BE(t),t+=2,i.signersName=m.decode(e,t),t+=m.decode.bytes,i.signature=e.slice(t,r+a+2),t+=i.signature.length,P.decode.bytes=t-r,i},P.decode.bytes=0,P.encodingLength=function(e){return 20+m.encodingLength(e.signersName)+t.byteLength(e.signature)};var F=e.rp={};F.encode=function(e,n,r){n||=t.alloc(F.encodingLength(e)),r||=0;let i=r;return r+=2,m.encode(e.mbox||`.`,n,r,{mail:!0}),r+=m.encode.bytes,m.encode(e.txt||`.`,n,r),r+=m.encode.bytes,F.encode.bytes=r-i,n.writeUInt16BE(F.encode.bytes-2,i),n},F.encode.bytes=0,F.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.mbox=m.decode(e,t,{mail:!0})||`.`,t+=m.decode.bytes,r.txt=m.decode(e,t)||`.`,t+=m.decode.bytes,F.decode.bytes=t-n,r},F.decode.bytes=0,F.encodingLength=function(e){return 2+m.encodingLength(e.mbox||`.`)+m.encodingLength(e.txt||`.`)};var I={};I.encode=function(e,r,i){r||=t.alloc(I.encodingLength(e)),i||=0;let a=i;for(var o=[],s=0;s<e.length;s++){var c=n.toType(e[s]);o[c>>8]===void 0&&(o[c>>8]=[]),o[c>>8][c>>3&31]|=1<<7-(c&7)}for(s=0;s<o.length;s++)if(o[s]!==void 0){var l=t.from(o[s]);r.writeUInt8(s,i),i+=1,r.writeUInt8(l.length,i),i+=1,l.copy(r,i),i+=l.length}return I.encode.bytes=i-a,r},I.encode.bytes=0,I.decode=function(e,t,r){t||=0;let i=t;for(var a=[];t-i<r;){var o=e.readUInt8(t);t+=1;var s=e.readUInt8(t);t+=1;for(var c=0;c<s;c++)for(var l=e.readUInt8(t+c),u=0;u<8;u++)if(l&1<<7-u){var d=n.toString(o<<8|c<<3|u);a.push(d)}t+=s}return I.decode.bytes=t-i,a},I.decode.bytes=0,I.encodingLength=function(e){for(var t=[],r=0;r<e.length;r++){var i=n.toType(e[r]);t[i>>8]=Math.max(t[i>>8]||0,i&255)}var a=0;for(r=0;r<t.length;r++)t[r]!==void 0&&(a+=2+Math.ceil((t[r]+1)/8));return a};var L=e.nsec={};L.encode=function(e,n,r){n||=t.alloc(L.encodingLength(e)),r||=0;let i=r;return r+=2,m.encode(e.nextDomain,n,r),r+=m.encode.bytes,I.encode(e.rrtypes,n,r),r+=I.encode.bytes,L.encode.bytes=r-i,n.writeUInt16BE(L.encode.bytes-2,i),n},L.encode.bytes=0,L.decode=function(e,t){t||=0;let n=t;var r={},i=e.readUInt16BE(t);return t+=2,r.nextDomain=m.decode(e,t),t+=m.decode.bytes,r.rrtypes=I.decode(e,t,i-(t-n)),t+=I.decode.bytes,L.decode.bytes=t-n,r},L.decode.bytes=0,L.encodingLength=function(e){return 2+m.encodingLength(e.nextDomain)+I.encodingLength(e.rrtypes)};var R=e.nsec3={};R.encode=function(e,n,r){n||=t.alloc(R.encodingLength(e)),r||=0;let i=r,a=e.salt;if(!t.isBuffer(a))throw Error(`salt must be a Buffer`);let o=e.nextDomain;if(!t.isBuffer(o))throw Error(`nextDomain must be a Buffer`);return r+=2,n.writeUInt8(e.algorithm,r),r+=1,n.writeUInt8(e.flags,r),r+=1,n.writeUInt16BE(e.iterations,r),r+=2,n.writeUInt8(a.length,r),r+=1,a.copy(n,r,0,a.length),r+=a.length,n.writeUInt8(o.length,r),r+=1,o.copy(n,r,0,o.length),r+=o.length,I.encode(e.rrtypes,n,r),r+=I.encode.bytes,R.encode.bytes=r-i,n.writeUInt16BE(R.encode.bytes-2,i),n},R.encode.bytes=0,R.decode=function(e,t){t||=0;let n=t;var r={},i=e.readUInt16BE(t);t+=2,r.algorithm=e.readUInt8(t),t+=1,r.flags=e.readUInt8(t),t+=1,r.iterations=e.readUInt16BE(t),t+=2;let a=e.readUInt8(t);t+=1,r.salt=e.slice(t,t+a),t+=a;let o=e.readUInt8(t);return t+=1,r.nextDomain=e.slice(t,t+o),t+=o,r.rrtypes=I.decode(e,t,i-(t-n)),t+=I.decode.bytes,R.decode.bytes=t-n,r},R.decode.bytes=0,R.encodingLength=function(e){return 8+e.salt.length+e.nextDomain.length+I.encodingLength(e.rrtypes)};var z=e.ds={};z.encode=function(e,n,r){n||=t.alloc(z.encodingLength(e)),r||=0;let i=r,a=e.digest;if(!t.isBuffer(a))throw Error(`Digest must be a Buffer`);return r+=2,n.writeUInt16BE(e.keyTag,r),r+=2,n.writeUInt8(e.algorithm,r),r+=1,n.writeUInt8(e.digestType,r),r+=1,a.copy(n,r,0,a.length),r+=a.length,z.encode.bytes=r-i,n.writeUInt16BE(z.encode.bytes-2,i),n},z.encode.bytes=0,z.decode=function(e,t){t||=0;let n=t;var r={},i=e.readUInt16BE(t);return t+=2,r.keyTag=e.readUInt16BE(t),t+=2,r.algorithm=e.readUInt8(t),t+=1,r.digestType=e.readUInt8(t),t+=1,r.digest=e.slice(t,n+i+2),t+=r.digest.length,z.decode.bytes=t-n,r},z.decode.bytes=0,z.encodingLength=function(e){return 6+t.byteLength(e.digest)};var B=e.sshfp={};B.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}},B.encode=function(e,n,r){n||=t.alloc(B.encodingLength(e)),r||=0;let i=r;r+=2,n[r]=e.algorithm,r+=1,n[r]=e.hash,r+=1;let a=t.from(e.fingerprint.toUpperCase(),`hex`);if(a.length!==B.getFingerprintLengthForHashType(e.hash))throw Error(`Invalid fingerprint length`);return a.copy(n,r),r+=a.byteLength,B.encode.bytes=r-i,n.writeUInt16BE(B.encode.bytes-2,i),n},B.encode.bytes=0,B.decode=function(e,t){t||=0;let n=t,r={};t+=2,r.algorithm=e[t],t+=1,r.hash=e[t],t+=1;let i=B.getFingerprintLengthForHashType(r.hash);return r.fingerprint=e.slice(t,t+i).toString(`hex`).toUpperCase(),t+=i,B.decode.bytes=t-n,r},B.decode.bytes=0,B.encodingLength=function(e){return 4+t.from(e.fingerprint,`hex`).byteLength};var V=e.naptr={};V.encode=function(e,n,r){n||=t.alloc(V.encodingLength(e)),r||=0;let i=r;return r+=2,n.writeUInt16BE(e.order||0,r),r+=2,n.writeUInt16BE(e.preference||0,r),r+=2,h.encode(e.flags,n,r),r+=h.encode.bytes,h.encode(e.services,n,r),r+=h.encode.bytes,h.encode(e.regexp,n,r),r+=h.encode.bytes,m.encode(e.replacement,n,r),r+=m.encode.bytes,V.encode.bytes=r-i,n.writeUInt16BE(V.encode.bytes-2,i),n},V.encode.bytes=0,V.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.order=e.readUInt16BE(t),t+=2,r.preference=e.readUInt16BE(t),t+=2,r.flags=h.decode(e,t),t+=h.decode.bytes,r.services=h.decode(e,t),t+=h.decode.bytes,r.regexp=h.decode(e,t),t+=h.decode.bytes,r.replacement=m.decode(e,t),t+=m.decode.bytes,V.decode.bytes=t-n,r},V.decode.bytes=0,V.encodingLength=function(e){return h.encodingLength(e.flags)+h.encodingLength(e.services)+h.encodingLength(e.regexp)+m.encodingLength(e.replacement)+6};var ee=e.tlsa={};ee.encode=function(e,n,r){n||=t.alloc(ee.encodingLength(e)),r||=0;let i=r,a=e.certificate;if(!t.isBuffer(a))throw Error(`Certificate must be a Buffer`);return r+=2,n.writeUInt8(e.usage,r),r+=1,n.writeUInt8(e.selector,r),r+=1,n.writeUInt8(e.matchingType,r),r+=1,a.copy(n,r,0,a.length),r+=a.length,ee.encode.bytes=r-i,n.writeUInt16BE(ee.encode.bytes-2,i),n},ee.encode.bytes=0,ee.decode=function(e,t){t||=0;let n=t,r={},i=e.readUInt16BE(t);return t+=2,r.usage=e.readUInt8(t),t+=1,r.selector=e.readUInt8(t),t+=1,r.matchingType=e.readUInt8(t),t+=1,r.certificate=e.slice(t,n+i+2),t+=r.certificate.length,ee.decode.bytes=t-n,r},ee.decode.bytes=0,ee.encodingLength=function(e){return 5+t.byteLength(e.certificate)};var ne=e.record=function(e){switch(e.toUpperCase()){case`A`:return k;case`PTR`:return C;case`CNAME`:return w;case`DNAME`:return T;case`TXT`:return b;case`NULL`:return x;case`AAAA`:return A;case`SRV`:return E;case`HINFO`:return S;case`CAA`:return D;case`NS`:return v;case`SOA`:return y;case`MX`:return O;case`OPT`:return M;case`DNSKEY`:return N;case`RRSIG`:return P;case`RP`:return F;case`NSEC`:return L;case`NSEC3`:return R;case`SSHFP`:return B;case`DS`:return z;case`NAPTR`:return V;case`TLSA`:return ee}return _},re=e.answer={};re.encode=function(e,r,i){r||=t.alloc(re.encodingLength(e)),i||=0;let o=i;if(m.encode(e.name,r,i),i+=m.encode.bytes,r.writeUInt16BE(n.toType(e.type),i),e.type.toUpperCase()===`OPT`){if(e.name!==`.`)throw Error(`OPT name must be root.`);r.writeUInt16BE(e.udpPayloadSize||4096,i+2),r.writeUInt8(e.extendedRcode||0,i+4),r.writeUInt8(e.ednsVersion||0,i+5),r.writeUInt16BE(e.flags||0,i+6),i+=8,M.encode(e.options||[],r,i),i+=M.encode.bytes}else{let t=a.toClass(e.class===void 0?`IN`:e.class);e.flush&&(t|=u),r.writeUInt16BE(t,i+2),r.writeUInt32BE(e.ttl||0,i+4),i+=8;let n=ne(e.type);n.encode(e.data,r,i),i+=n.encode.bytes}return re.encode.bytes=i-o,r},re.encode.bytes=0,re.decode=function(e,t){t||=0;let r={},i=t;if(r.name=m.decode(e,t),t+=m.decode.bytes,r.type=n.toString(e.readUInt16BE(t)),r.type===`OPT`)r.udpPayloadSize=e.readUInt16BE(t+2),r.extendedRcode=e.readUInt8(t+4),r.ednsVersion=e.readUInt8(t+5),r.flags=e.readUInt16BE(t+6),r.flag_do=(r.flags>>15&1)==1,r.options=M.decode(e,t+8),t+=8+M.decode.bytes;else{let n=e.readUInt16BE(t+2);r.ttl=e.readUInt32BE(t+4),r.class=a.toString(n&d),r.flush=!!(n&u);let i=ne(r.type);r.data=i.decode(e,t+8),t+=8+i.decode.bytes}return re.decode.bytes=t-i,r},re.decode.bytes=0,re.encodingLength=function(e){let t=e.data!==null&&e.data!==void 0?e.data:e.options;return m.encodingLength(e.name)+8+ne(e.type).encodingLength(t)};var ie=e.question={};ie.encode=function(e,r,i){r||=t.alloc(ie.encodingLength(e)),i||=0;let o=i;return m.encode(e.name,r,i),i+=m.encode.bytes,r.writeUInt16BE(n.toType(e.type),i),i+=2,r.writeUInt16BE(a.toClass(e.class===void 0?`IN`:e.class),i),i+=2,ie.encode.bytes=i-o,e},ie.encode.bytes=0,ie.decode=function(e,t){t||=0;let r=t,i={};return i.name=m.decode(e,t),t+=m.decode.bytes,i.type=n.toString(e.readUInt16BE(t)),t+=2,i.class=a.toString(e.readUInt16BE(t)),t+=2,i.class&f&&(i.class&=p),ie.decode.bytes=t-r,i},ie.decode.bytes=0,ie.encodingLength=function(e){return m.encodingLength(e.name)+4},e.AUTHORITATIVE_ANSWER=1024,e.TRUNCATED_RESPONSE=512,e.RECURSION_DESIRED=256,e.RECURSION_AVAILABLE=128,e.AUTHENTIC_DATA=32,e.CHECKING_DISABLED=16,e.DNSSEC_OK=32768,e.encode=function(n,r,i){let a=!r;a&&(r=t.alloc(e.encodingLength(n))),i||=0;let o=i;return n.questions||=[],n.answers||=[],n.authorities||=[],n.additionals||=[],g.encode(n,r,i),i+=g.encode.bytes,i=oe(n.questions,ie,r,i),i=oe(n.answers,re,r,i),i=oe(n.authorities,re,r,i),i=oe(n.additionals,re,r,i),e.encode.bytes=i-o,a&&e.encode.bytes!==r.length?r.slice(0,e.encode.bytes):r},e.encode.bytes=0,e.decode=function(t,n){n||=0;let r=n,i=g.decode(t,n);return n+=g.decode.bytes,n=se(i.questions,ie,t,n),n=se(i.answers,re,t,n),n=se(i.authorities,re,t,n),n=se(i.additionals,re,t,n),e.decode.bytes=n-r,i},e.decode.bytes=0,e.encodingLength=function(e){return g.encodingLength(e)+ae(e.questions||[],ie)+ae(e.answers||[],re)+ae(e.authorities||[],re)+ae(e.additionals||[],re)},e.streamEncode=function(n){let r=e.encode(n),i=t.alloc(2);i.writeUInt16BE(r.byteLength);let a=t.concat([i,r]);return e.streamEncode.bytes=a.byteLength,a},e.streamEncode.bytes=0,e.streamDecode=function(t){let n=t.readUInt16BE(0);if(t.byteLength<n+2)return null;let r=e.decode(t.slice(2));return e.streamDecode.bytes=e.decode.bytes,r},e.streamDecode.bytes=0;function ae(e,t){let n=0;for(let r=0;r<e.length;r++)n+=t.encodingLength(e[r]);return n}function oe(e,t,n,r){for(let i=0;i<e.length;i++)t.encode(e[i],n,r),r+=t.encode.bytes;return r}function se(e,t,n,r){for(let i=0;i<e.length;i++)e[i]=t.decode(n,r),r+=t.decode.bytes;return r}})),Ex=R(((e,t)=>{var n=c;process.nextTick(s,42),t.exports=r;function r(e){var t=s;return r;function r(e){t(e||a)}function s(r){var a=[r];t=c,e(l);function c(e){a.push(e)}function l(e){var r=arguments;for(t=i(e)?s:c;a.length;)c(a.shift());function c(e){n(o,e,r)}}}}function i(e){return Object.prototype.toString.call(e)===`[object Error]`}function a(){}function o(e,t){e.apply(null,t)}function s(e){e===42&&(n=process.nextTick)}function c(e,t,n){process.nextTick(function(){e(t,n)})}})),Dx=V(R(((e,t)=>{var n=Tx(),r=te(`dgram`),i=Ex(),a=te(`events`),o=te(`os`),s=function(){};t.exports=function(e){e||={};var t=new a.EventEmitter,o=typeof e.port==`number`?e.port:5353,u=e.type||`udp4`,d=e.ip||e.host||(u===`udp4`?`224.0.0.251`:null),f={address:d,port:o},p={},m=!1,h=null;if(u===`udp6`&&(!d||!e.interface))throw Error("For IPv6 multicast you must specify `ip` and `interface`");var g=e.socket||r.createSocket({type:u,reuseAddr:e.reuseAddr!==!1,toString:function(){return u}});g.on(`error`,function(e){e.code===`EACCES`||e.code===`EADDRINUSE`?t.emit(`error`,e):t.emit(`warning`,e)}),g.on(`message`,function(e,r){try{e=n.decode(e)}catch(e){t.emit(`warning`,e);return}t.emit(`packet`,e,r),e.type===`query`&&t.emit(`query`,e,r),e.type===`response`&&t.emit(`response`,e,r)}),g.on(`listening`,function(){o||=f.port=g.address().port,e.multicast!==!1&&(t.update(),h=setInterval(t.update,5e3),g.setMulticastTTL(e.ttl||255),g.setMulticastLoopback(e.loopback!==!1))});var _=i(function(t){if(!o||e.bind===!1)return t(null);g.once(`error`,t),g.bind(o,e.bind||e.interface,function(){g.removeListener(`error`,t),t(null)})});return _(function(e){if(e)return t.emit(`error`,e);t.emit(`ready`)}),t.send=function(e,r,i){if(typeof r==`function`)return t.send(e,null,r);i||=s,r?!r.host&&!r.address&&(r.address=f.address):r=f,_(a);function a(t){if(m)return i();if(t)return i(t);var a=n.encode(e);g.send(a,0,a.length,r.port,r.address||r.host,i)}},t.response=t.respond=function(e,r,i){Array.isArray(e)&&(e={answers:e}),e.type=`response`,e.flags=(e.flags||0)|n.AUTHORITATIVE_ANSWER,t.send(e,r,i)},t.query=function(e,n,r,i){if(typeof n==`function`)return t.query(e,null,null,n);if(typeof n==`object`&&n&&n.port)return t.query(e,null,n,r);if(typeof r==`function`)return t.query(e,n,null,r);i||=s,typeof e==`string`&&(e=[{name:e,type:n||`ANY`}]),Array.isArray(e)&&(e={type:`query`,questions:e}),e.type=`query`,t.send(e,r,i)},t.destroy=function(e){if(e||=s,m)return process.nextTick(e);for(var t in m=!0,clearInterval(h),p)try{g.dropMembership(d,t)}catch{}p={},g.close(e)},t.update=function(){for(var n=e.interface?[].concat(e.interface):l(),r=!1,i=0;i<n.length;i++){var a=n[i];if(!p[a])try{g.addMembership(d,a),p[a]=!0,r=!0}catch(e){t.emit(`warning`,e)}}if(r){if(g.setMulticastInterface)try{g.setMulticastInterface(e.interface||c())}catch(e){t.emit(`warning`,e)}t.emit(`networkInterface`)}},t};function c(){for(var e=o.networkInterfaces(),t=Object.keys(e),n=0;n<t.length;n++)for(var r=e[t[n]],i=0;i<r.length;i++){var a=r[i];if(u(a.family)&&!a.internal)return o.platform()===`darwin`&&t[n]===`en0`?a.address:`0.0.0.0`}return`127.0.0.1`}function l(){for(var e=o.networkInterfaces(),t=Object.keys(e),n=[],r=0;r<t.length;r++)for(var i=e[t[r]],a=0;a<i.length;a++){var s=i[a];if(u(s.family)){n.push(s.address);break}}return n}function u(e){return e===4||e===`IPv4`}}))(),1);function Ox(){return c(2).readUInt16BE(0)}function kx(){return c(4).readUInt32BE(0)}var Ax=class{constructor(e){this.bitLength=e}value=0;set(e,t,n){return n&=(1<<e)-1,this.value|=n<<this.bitLength-e-t,this}get buffer(){let e=Math.ceil(this.bitLength/8),t=Buffer.alloc(e);return t.writeUIntBE(this.value,0,e),t}},jx=class{constructor(e){if(this.bitLength=e,e>32)throw Error()}_value=0n;offset=0n;set(e,t=1){let n=BigInt(e),r=BigInt(t);return n&=(1n<<r)-1n,this._value|=n<<BigInt(this.bitLength)-r-this.offset,this.offset+=r,this}get value(){return Number(this._value)}get buffer(){let e=Math.ceil(this.bitLength/8),t=Buffer.alloc(e);return t.writeUIntBE(this.value,0,e),t}};function Mx(e,t,n=1){let r=e.toString(2).split(``);r=[...Array(8-r.length).fill(`0`),...r];let i=r.slice(t,t+n).join(``);return Number.parseInt(i,2)}function Nx(e,t){return Px(e)(t)}function Px(e,t){let n=e.reduce((e,t)=>e+t,0),r=t?Buffer.alloc(n):void 0;return t=>{let i=r||Buffer.alloc(n),a=0;return t.forEach((t,n)=>{let r=e[n];r===8?i.writeBigUInt64BE(t,a):i.writeUIntBE(t,a,r),a+=r}),i}}function Fx(e,t){let n=0;return t.map(t=>{let r;return r=t===8?e.readBigUInt64BE(n):e.readUIntBE(n,t),n+=t,r})}var Ix=class{constructor(e){this.uint8Array=e}position=0;bitsPending=0;writeBits(e,t){if(e==0)return this;t&=4294967295>>>32-e;let n;return this.bitsPending>0?this.bitsPending>e?(this.uint8Array[this.position-1]|=t<<this.bitsPending-e,n=e,this.bitsPending-=e):this.bitsPending==e?(this.uint8Array[this.position-1]|=t,n=e,this.bitsPending=0):(this.uint8Array[this.position-1]|=t>>e-this.bitsPending,n=this.bitsPending,this.bitsPending=0):(n=Math.min(8,e),this.bitsPending=8-n,this.uint8Array[this.position++]=t>>e-n<<this.bitsPending),e-=n,e>0&&this.writeBits(e,t),this}readBits(e){return this._readBits(e)}_readBits(e,t){if(t===void 0&&(t=0),e==0)return t;let n,r;if(this.bitsPending>0){let t=this.uint8Array[this.position-1]&255>>8-this.bitsPending;r=Math.min(this.bitsPending,e),this.bitsPending-=r,n=t>>this.bitsPending}else r=Math.min(8,e),this.bitsPending=8-r,n=this.uint8Array[this.position++]>>this.bitsPending;return e-=r,t=t<<r|n,e>0?this._readBits(e,t):t}seekTo(e){this.position=e/8|0,this.bitsPending=e%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},Lx=3988292384,Rx=2197175160;function zx(e){return typeof e!=`string`}function Bx(e){let t=Array(256),n=0;for(let r=0;r<256;++r)n=r,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,t[r]=n;return new Int32Array(t)}function Vx(e){let t=new Int32Array(4096),n=0,r=0,i=0;for(i=0;i<256;++i)t[i]=e[i];for(i=0;i<256;++i)for(r=e[i],n=256+i;n<4096;n+=256)r=t[n]=r>>>8^e[r&255];let a=[];for(i=1;i<16;++i)a[i-1]=t.subarray(i*256,i*256+256);return a}function Hx(e,t,n){let r=t^-1,i=0,a=e.length,o=0,s=0;for(;i<a;)o=e.charCodeAt(i++),o<128?r=r>>>8^n[(r^o)&255]:o<2048?(r=r>>>8^n[(r^(192|o>>6&31))&255],r=r>>>8^n[(r^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,s=e.charCodeAt(i++)&1023,r=r>>>8^n[(r^(240|o>>8&7))&255],r=r>>>8^n[(r^(128|o>>2&63))&255],r=r>>>8^n[(r^(128|s>>6&15|(o&3)<<4))&255],r=r>>>8^n[(r^(128|s&63))&255]):(r=r>>>8^n[(r^(224|o>>12&15))&255],r=r>>>8^n[(r^(128|o>>6&63))&255],r=r>>>8^n[(r^(128|o&63))&255]);return~r>>>0}function Ux(e,t,n,r){let[i,a,o,s,c,l,u,d,f,p,m,h,g,_,v]=r,y=t^-1,b=0,x=e.length-15;for(;b<x;)y=v[e[b++]^y&255]^_[e[b++]^y>>>8&255]^g[e[b++]^y>>>16&255]^h[e[b++]^y>>>24]^m[e[b++]]^p[e[b++]]^f[e[b++]]^d[e[b++]]^u[e[b++]]^l[e[b++]]^c[e[b++]]^s[e[b++]]^o[e[b++]]^a[e[b++]]^i[e[b++]]^n[e[b++]];for(x+=15;b<x;)y=y>>>8^n[(y^e[b++])&255];return~y>>>0}var Wx=Bx(Lx),Gx=Vx(Wx),Kx=Bx(Rx),qx=Vx(Kx);function Jx(e,t=0){return zx(e)?Ux(e,t,Wx,Gx):Hx(e,t,Wx)}function Yx(e,t=0){return zx(e)?Ux(e,t,Kx,qx):Hx(e,t,Kx)}function Xx(e,t){return e+t&255}function Zx(e,t){return e+t&65535}function Qx(e,t){return Number(BigInt(e)+BigInt(t)&4294967295n)}function $x(e){return e&16777215}function eS(e,t){let n=32768;return e<t&&t-e>n||e>t&&e-t<n}function tS(e,t){let n=2147483648;return e<t&&t-e>n||e>t&&e-t<n}function nS(e,t){return e===t||tS(e,t)}var rS=e=>Number.parseInt(e,10),iS=(e,t)=>t?t[e]:void 0;async function aS(e,t,n=`udp4`,r){let i;for(let a=e;a<=t;a++){let o=f(n);if(setImmediate(()=>o.bind({port:a,address:iS(n,r)})),await new Promise(e=>{o.once(`error`,t=>e(t)),o.once(`listening`,()=>e())})){await new Promise(e=>o.close(()=>e()));continue}if(i=o.address()?.port,await new Promise(e=>o.close(()=>e())),e<=i&&i<=t)break}if(!i)throw Error(`port not found`);return i}function oS(e){return e===`IPv4`?4:e===`IPv6`?6:e}var sS=ui.default.debug,$=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=e=>{};execute=(...e)=>{if(!this.ended){for(let t of this.event.stack)t.execute(...e);(async()=>{for(let t of this.event.promiseStack)await t.execute(...e)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let e of this.event.stack)e.complete&&e.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&=(this.onended(),void 0)}};error=e=>{if(!this.ended){for(let t of this.event.stack)t.error&&t.error(e);this.allUnsubscribe()}};allUnsubscribe=()=>{this.ended||(this.event={stack:[],promiseStack:[],eventId:0})};subscribe=(e,t,n)=>{let r=this.event.eventId;this.event.stack.push({execute:e,id:r,complete:t,error:n}),this.event.eventId++;let i=()=>{this.event.stack=this.event.stack.filter(e=>e.id!==r&&e)};return{unSubscribe:i,disposer:e=>{e.push(i)}}};pipe(e){this.subscribe((...t)=>{e.execute(...t)})}queuingSubscribe=(e,t,n)=>{if(this.ended)throw Error(`event completed`);let r=this.event.eventId;this.event.promiseStack.push({execute:e,id:r,complete:t,error:n}),this.event.eventId++;let i=()=>{this.event.stack=this.event.stack.filter(e=>e.id!==r&&e)};return{unSubscribe:i,disposer:e=>{e.push(i)}}};once=(e,t,n)=>{let r=this.subscribe((...t)=>{r.unSubscribe(),e(...t)},t,n)};watch=(e,t)=>new Promise((n,r)=>{let i=t&&setTimeout(()=>{r(`Event watch timeout`)},t),{unSubscribe:a}=this.subscribe((...t)=>{e(...t)&&(i&&clearTimeout(i),a(),n(t))})});asPromise=e=>new Promise((t,n)=>{let r=e&&setTimeout(()=>{n(`Event asPromise timeout`)},e);this.once((...e)=>{r&&clearTimeout(r),t(e)},()=>{r&&clearTimeout(r),t([])},e=>{r&&clearTimeout(r),n(e)})});get returnTrigger(){let{execute:e,error:t,complete:n}=this;return{execute:e,error:t,complete:n}}get returnListener(){let{subscribe:e,once:t,asPromise:n}=this;return{subscribe:e,once:t,asPromise:n}}get length(){return this.event.stack.length}},cS=class{_disposer=[];push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e()),this._disposer=[]}},lS=sS(`werift-ice:packages/ice/src/transport.ts`),uS=class e{constructor(e,t={}){this.socketType=e,this.options=t,this.socket=f(e),this.socket.on(`message`,(e,t)=>{oS(t.family)===6&&([t.address]=t.address.split(`%`)),this.rinfo=t;try{this.onData(e,[t.address,t.port])}catch(e){lS(`onData error`,e)}})}type=`udp`;socket;rinfo;onData=()=>{};closed=!1;static async init(t,n={}){let r=new e(t,n);return await r.init(),r}async init(){let e=iS(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let t=await aS(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else this.socket.bind({address:e});await new Promise(e=>this.socket.once(`listening`,e))}send=async(e,t)=>{if(t&&!_.isIP(t[0]))return new Promise((n,r)=>{this.socket.send(e,t[1],t[0],i=>{i?(lS(`send error`,t,e),r(i)):n()})});t??=[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,t[1],t[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()}})},dS=class e{type=`tcp`;stream;constructor(e){this.stream=new pS(`tcp`,()=>v({port:e[1],host:e[0]}))}static async init(t){let n=new e(t);return await n.init(),n}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}send=async(e,t)=>{await this.stream.send(e,t)};close=async()=>{await this.stream.close()}},fS=class e{type=`tls`;stream;constructor(e,t={}){this.stream=new pS(`tls`,()=>C.connect({...t,host:e[0],port:e[1]}))}static async init(t,n={}){let r=new e(t,n);return await r.init(),r}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}send=async(e,t)=>{await this.stream.send(e,t)};close=async()=>{await this.stream.close()}},pS=class{constructor(e,t,n=e===`tls`?`secureConnect`:`connect`){this.createClient=t,this.connectEvent=n,this.type=e,this.connect()}type;connecting;client;onData=()=>{};closed=!1;connect(){if(this.closed)return;this.client&&this.client.destroy();let e=this.createClient();this.client=e,this.connecting=new Promise((t,n)=>{let r=()=>{e.off(`error`,i),t()},i=t=>{e.off(this.connectEvent,r),n(t)};e.once(this.connectEvent,r),e.once(`error`,i)}),e.on(`data`,e=>{let t=[this.client.remoteAddress,this.client.remotePort];this.onData(e,t)}),e.on(`end`,()=>{this.connect()}),e.on(`error`,e=>{lS(`${this.type} transport error`,e)})}async waitForConnect(){await this.connecting}get address(){return{}}send=async(e,t)=>{await this.connecting,await new Promise((t,n)=>{this.client.write(e,e=>{if(e){n(e);return}t()})})};close=async()=>{this.closed=!0,this.client?.destroy()}},mS={rsa_1:1,ecdsa_3:3},hS={sha256_4:4},gS={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},_S=Object.values(gS),vS={x25519_29:29,secp256r1_23:23},yS=Object.values(vS),bS={named_curve_3:3},xS={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},SS=[1,64],CS=[{hash:hS.sha256_4,signature:mS.rsa_1},{hash:hS.sha256_4,signature:mS.ecdsa_3}],wS=()=>{let e=vx.utils.randomPrivateKey(),t=vx.getPublicKey(e,!1);return{privateKey:Buffer.from(e),publicKey:Buffer.from(t)}},TS=({publicKey:e,privateKey:t})=>{let n=vx.getSharedSecret(t,e);return Buffer.from(n).subarray(1)};function ES(e,t,n){switch(n){case vS.secp256r1_23:return TS({publicKey:e,privateKey:t});case vS.x25519_29:return Buffer.from(Tv.default.scalarMult(t,e));default:throw Error()}}function DS(e,t,n){let r=o(e,t);return r.update(n),r.digest()}function OS(e,t,n,r=`sha256`){let i=n,a=[],o=t;do{o=DS(r,e,o);let i=DS(r,e,Buffer.concat([o,t]));a.push(i),n-=i.length}while(n>0);return Buffer.concat(a,i)}function kS(e,t,n){return OS(e,Buffer.concat([Buffer.from(`master secret`),t,n]),48)}function AS(e,t){let n=MS(`sha256`,t);return OS(e,Buffer.concat([Buffer.from(`extended master secret`),n]),48)}function jS(e,t,n,r,i,a){let o=a?r:i,s=a?i:r;return OS(n,Buffer.concat([Buffer.from(e),o,s]),t)}function MS(e,t){return a(e).update(t).digest()}function NS(e,t,n,r=12){let i=MS(`sha256`,t);return OS(e,Buffer.concat([Buffer.from(n),i]),r)}function PS(e,t){return NS(e,t,`client finished`)}function FS(e,t){return NS(e,t,`server finished`)}function IS(e,t,n,r,i,a,o=`sha256`){let s=r*2+i*2,c=e,l=Buffer.concat([n,t]),u=OS(c,Buffer.concat([Buffer.from(`key expansion`),l]),s,o),d=(0,Q.createDecode)(u),f=d.readBuffer(r),p=d.readBuffer(r),m=d.readBuffer(i),h=d.readBuffer(i),g=Buffer.alloc(a,0),_=Buffer.alloc(a,0);return m.copy(g,0),h.copy(_,0),{clientWriteKey:f,serverWriteKey:p,clientNonce:g,serverNonce:_}}var LS={CLIENT:1,SERVER:2},RS=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...e){throw Error(`not implemented`)}encrypt(...e){throw Error(`not implemented`)}decrypt(...e){throw Error(`not implemented`)}toString(){return this.name}},zS=d;Eg.set(zS);var BS=class{constructor(e,t,n,r){this.sessionType=e,this.certPem=t,this.keyPem=n,t&&n&&r&&this.parseX509(t,n,r)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(e,t)=>{let n=(()=>{switch(e.signature){case mS.rsa_1:return`RSASSA-PKCS1-v1_5`;case mS.ecdsa_3:return`ECDSA`}})(),r=(()=>{switch(e.hash){case hS.sha256_4:return`SHA-256`}})(),i=(()=>{switch(t){case vS.secp256r1_23:return`P-256`;case vS.x25519_29:return n===`ECDSA`?`P-256`:`X25519`;default:if(n===`ECDSA`)return`P-256`;if(n===`RSASSA-PKCS1-v1_5`)return`X25519`}})(),a=(()=>{switch(n){case`ECDSA`:return{name:n,hash:r,namedCurve:i};case`RSASSA-PKCS1-v1_5`:return{name:n,hash:r,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),o=await zS.subtle.generateKey(a,!0,[`sign`,`verify`]);return{certPem:(await $_.createSelfSigned({serialNumber:c(8).toString(`hex`),name:`C=AU, ST=Some-State, O=Internet Widgits Pty Ltd`,notBefore:new Date,notAfter:new Date(Date.now()+31536e7),signingAlgorithm:a,keys:o})).toString(`pem`),keyPem:Xg.encode(await zS.subtle.exportKey(`pkcs8`,o.privateKey),`private key`),signatureHash:e}};encryptPacket(e){let t=e.recordLayerHeader,n=t.protocolVersion.major<<8|t.protocolVersion.minor,r=this.cipher.encrypt(this.sessionType,e.fragment,{type:t.contentType,version:n,epoch:t.epoch,sequenceNumber:t.sequenceNumber});return e.fragment=r,e.recordLayerHeader.contentLen=r.length,e}decryptPacket(e){let t=e.recordLayerHeader,n=t.protocolVersion.major<<8|t.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,e.fragment,{type:t.contentType,version:n,epoch:t.epoch,sequenceNumber:t.sequenceNumber})}verifyData(e){return this.sessionType===LS.CLIENT?PS(this.masterSecret,e):FS(this.masterSecret,e)}signatureData(e,t){let n=s(t).update(e),r=this.localPrivateKey.toPEM().toString();return n.sign(r)}generateKeySignature(e){let t=this.sessionType===LS.CLIENT?this.localRandom:this.remoteRandom,n=this.sessionType===LS.SERVER?this.localRandom:this.remoteRandom,r=this.valueKeySignature(t.serialize(),n.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(r,e)}parseX509(e,t,n){let r=di.Certificate.fromPEM(Buffer.from(e)),i=di.PrivateKey.fromPEM(Buffer.from(t));this.localCert=r.raw,this.localPrivateKey=i,this.signatureHashAlgorithm=n}valueKeySignature(e,t,n,r){let i=Buffer.from((0,Q.encode)({type:bS.named_curve_3,curve:r,len:n.length},{type:Q.types.uint8,curve:Q.types.uint16be,len:Q.types.uint8}).slice());return Buffer.concat([e,t,i,n])}},VS=class{srtpProfile;static findMatchingSRTPProfile(e,t){for(let n of t)if(e.includes(n))return n}},HS=e=>`0x`+e.toString(`hex`).replace(/(.)(.)/g,`$1$2 `).split(` `).filter(e=>e!=null&&e.length>0).join(`,0x`),US=e=>Object.entries({...e}).reduce((e,[t,n])=>((typeof n==`number`||typeof n==`string`)&&(e[t]=n),Buffer.isBuffer(n)&&(e[t]=HS(n)),e),{}),WS=class e{constructor(e,t,n,r,i,a){this.msg_type=e,this.length=t,this.message_seq=n,this.fragment_offset=r,this.fragment_length=i,this.fragment=a}static spec={msg_type:Q.types.uint8,length:Q.types.uint24be,message_seq:Q.types.uint16be,fragment_offset:Q.types.uint24be,fragment_length:Q.types.uint24be,fragment:Q.types.buffer(e=>e.current.fragment_length)};get summary(){return US(this)}static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}chunk(t){let n=0,r=this.fragment.length;if(r===0)return[new e(this.msg_type,r,this.message_seq,n,0,this.fragment)];let i=[];for(t||=1240;n<r;){let a=Math.min(t,r-n),o=Buffer.from(this.fragment.slice(n,n+a));if(o.length<=0)throw Error(`Zero or less bytes processed while fragmenting handshake message.`);i.push(new e(this.msg_type,r,this.message_seq,n,o.length,o)),n+=o.length}return i}static assemble(t){if(!t?.length)throw Error(`cannot reassemble handshake from empty array`);t=t.sort((e,t)=>e.fragment_offset-t.fragment_offset);let n=Buffer.alloc(t[0].length);for(let e of t)e.fragment.copy(n,e.fragment_offset);return new e(t[0].msg_type,t[0].length,t[0].message_seq,0,n.length,n)}static findAllFragments(e,t){let n=e.find(e=>e.msg_type===t);return!n||!e?.length?[]:e.filter(e=>e.msg_type===n.msg_type&&e.message_seq===n.message_seq&&e.length===n.length)}},{uint16be:GS,uint24be:KS,buffer:qS,array:JS,uint8:YS,string:XS}=Q.types,ZS=JS({type:GS,data:qS(GS)},GS,`bytes`),QS=qS(KS),$S=YS,eC=XS(GS),tC={hash:YS,signature:YS},nC={major:YS,minor:YS},rC=class e{constructor(e=Math.floor(Date.now()/1e3),t=c(28)){this.gmt_unix_time=e,this.random_bytes=t}static spec={gmt_unix_time:Q.types.uint32be,random_bytes:Q.types.buffer(28)};static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}static from(t){return new e(...Object.values(t))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}},iC=class e{constructor(e,t,n,r,i,a,o){this.clientVersion=e,this.random=t,this.sessionId=n,this.cookie=r,this.cipherSuites=i,this.compressionMethods=a,this.extensions=o}msgType=1;messageSeq=0;static spec={clientVersion:{major:Q.types.uint8,minor:Q.types.uint8},random:rC.spec,sessionId:Q.types.buffer(Q.types.uint8),cookie:Q.types.buffer(Q.types.uint8),cipherSuites:Q.types.array(Q.types.uint16be,Q.types.uint16be,`bytes`),compressionMethods:Q.types.array(Q.types.uint8,Q.types.uint8,`bytes`),extensions:ZS};static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},aC=class e{constructor(e,t,n,r,i){this.epoch=e,this.sequenceNumber=t,this.contentType=n,this.protocolVersion=r,this.contentLen=i}static spec={epoch:Q.types.uint16be,sequenceNumber:Q.types.uint48be,contentType:Q.types.uint8,protocolVersion:nC,contentLen:Q.types.uint16be};static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}},oC=class e{constructor(e,t){this.recordLayerHeader=e,this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:HS(this.fragment)}}static createEmpty(){return new e(void 0,void 0)}static deSerialize(t){if(t.length<13)throw Error(`Invalid DTLS record: buffer is too short`);let n=t.readUInt8(0),r=t.readUInt8(1),i=t.readUInt8(2),a=t.readUInt16BE(3),o=t.slice(5,11).readUIntBE(0,6),s=t.readUInt16BE(11);if(t.length<13+s)throw Error(`Invalid DTLS record: fragment length exceeds buffer`);let c=t.slice(13,13+s);return new e({contentType:n,protocolVersion:{major:r,minor:i},epoch:a,sequenceNumber:o,contentLen:s},c)}serialize(){let e=this.fragment.length,t=13+e,n=Buffer.alloc(t);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 aC(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},sC=e=>t=>(e.lastFlight=t,t.flatMap(t=>(t.messageSeq=e.sequenceNumber++,t.toFragment().chunk()))),cC=e=>(t,n)=>t.map(t=>new oC({contentType:t.type,protocolVersion:e.version,epoch:e.epoch,sequenceNumber:n,contentLen:t.fragment.length},t.fragment)),lC=(e=>(e[e.CloseNotify=0]=`CloseNotify`,e[e.UnexpectedMessage=10]=`UnexpectedMessage`,e[e.BadRecordMac=20]=`BadRecordMac`,e[e.DecryptionFailed=21]=`DecryptionFailed`,e[e.RecordOverflow=22]=`RecordOverflow`,e[e.DecompressionFailure=30]=`DecompressionFailure`,e[e.HandshakeFailure=40]=`HandshakeFailure`,e[e.NoCertificate=41]=`NoCertificate`,e[e.BadCertificate=42]=`BadCertificate`,e[e.UnsupportedCertificate=43]=`UnsupportedCertificate`,e[e.CertificateRevoked=44]=`CertificateRevoked`,e[e.CertificateExpired=45]=`CertificateExpired`,e[e.CertificateUnknown=46]=`CertificateUnknown`,e[e.IllegalParameter=47]=`IllegalParameter`,e[e.UnknownCa=48]=`UnknownCa`,e[e.AccessDenied=49]=`AccessDenied`,e[e.DecodeError=50]=`DecodeError`,e[e.DecryptError=51]=`DecryptError`,e[e.ExportRestriction=60]=`ExportRestriction`,e[e.ProtocolVersion=70]=`ProtocolVersion`,e[e.InsufficientSecurity=71]=`InsufficientSecurity`,e[e.InternalError=80]=`InternalError`,e[e.UserCanceled=90]=`UserCanceled`,e[e.NoRenegotiation=100]=`NoRenegotiation`,e[e.UnsupportedExtension=110]=`UnsupportedExtension`,e))(lC||{}),uC=sS(`werift-dtls : packages/dtls/src/flight/flight.ts : warn`),dC=sS(`werift-dtls : packages/dtls/src/flight/flight.ts : err`),fC=class e{constructor(e,t,n,r){this.transport=e,this.dtls=t,this.flight=n,this.nextFlight=r}state=`PREPARING`;static RetransmitCount=10;createPacket(e){let t=sC(this.dtls)(e);return this.dtls.bufferHandshakeCache(t,!0,this.flight),cC(this.dtls)(t.map(e=>({type:22,fragment:e.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(t){let n=0;for(;n<=e.RetransmitCount;n++){if(this.setState(`SENDING`),this.send(t).catch(e=>{dC(`fail to send`,dC)}),this.setState(`WAITING`),this.nextFlight===void 0){this.setState(`FINISHED`);break}if(await E(1e3*((n+1)/2)),this.dtls.flight>=this.nextFlight){this.setState(`FINISHED`);break}uC(this.dtls.sessionId,`retransmit`,n,this.dtls.flight)}if(n>e.RetransmitCount)throw dC(this.dtls.sessionId,`retransmit failed`,n),Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(e=>this.transport.send(e)));setState(e){this.state=e}},pC=class extends fC{constructor(e,t,n){super(e,t,1,3),this.cipher=n}async exec(e){if(this.dtls.flight===1)throw Error();this.dtls.flight=1;let t=new iC({major:254,minor:253},new rC,Buffer.from([]),Buffer.from([]),_S,[0],e);this.dtls.version=t.clientVersion,this.cipher.localRandom=rC.from(t.random);let n=this.createPacket([t]),r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}},mC=sS(`werift-dtls : packages/dtls/src/flight/client/flight3.ts : log`),hC=class extends fC{constructor(e,t){super(e,t,3,5)}async exec(e){if(this.dtls.flight===3)throw Error();this.dtls.flight=3,this.dtls.handshakeCache=[];let[t]=this.dtls.lastFlight;mC(`dtls version`,t.clientVersion),t.cookie=e.cookie,this.dtls.cookie=e.cookie;let n=this.createPacket([t]),r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}},gC={NULL:0,ECDHE:1},_C={NULL:0,RSA:1,ECDSA:2,PSK:3},vC={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},yC=class{id=0;name;signType;keyType;toString(){return this.name}};function bC(){let e=new yC;return e.id=vC.RSA,e.name=`RSA`,e.keyType=_C.RSA,e}function xC(){let e=new yC;return e.id=vC.ECDHE_RSA,e.name=`ECDHE_RSA`,e.signType=gC.ECDHE,e.keyType=_C.RSA,e}function SC(){let e=new yC;return e.id=vC.ECDHE_ECDSA,e.name=`ECDHE_ECDSA`,e.signType=gC.ECDHE,e.keyType=_C.ECDSA,e}function CC(){let e=new yC;return e.id=vC.PSK,e.name=`PSK`,e.signType=gC.NULL,e.keyType=_C.PSK,e}function wC(){let e=new yC;return e.id=vC.ECDHE_PSK,e.name=`ECDHE_PSK`,e.signType=gC.ECDHE,e.keyType=_C.PSK,e}var TC=sS(`werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err`),EC=class extends RS{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return US(this)}init(e,t,n){let r=IS(e,n,t,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=r.clientWriteKey,this.serverWriteKey=r.serverWriteKey,this.clientNonce=r.clientNonce,this.serverNonce=r.serverNonce}encrypt(e,t,n){let i=e===LS.CLIENT,a=i?this.clientNonce:this.serverNonce,o=i?this.clientWriteKey:this.serverWriteKey;if(!a||!o)throw Error();a.writeUInt16BE(n.epoch,this.nonceImplicitLength),a.writeUIntBE(n.sequenceNumber,this.nonceImplicitLength+2,6);let s=a.slice(this.nonceImplicitLength),c=this.encodeAdditionalBuffer(n,t.length),l=r(this.blockAlgorithm,o,a,{authTagLength:this.authTagLength});l.setAAD(c,{plaintextLength:t.length});let u=l.update(t),d=l.final(),f=l.getAuthTag();return Buffer.concat([s,u,d,f])}encodeAdditionalBuffer(e,t){let n=Buffer.alloc(13);return n.writeUInt16BE(e.epoch,0),n.writeUintBE(e.sequenceNumber,2,6),n.writeUInt8(e.type,8),n.writeUInt16BE(e.version,9),n.writeUInt16BE(t,11),n}decrypt(e,t,n){let r=e===LS.CLIENT,a=r?this.serverNonce:this.clientNonce,o=r?this.serverWriteKey:this.clientWriteKey;if(!a||!o)throw Error();t.subarray(0,this.nonceExplicitLength).copy(a,this.nonceImplicitLength);let s=t.subarray(this.nonceExplicitLength,t.length-this.authTagLength),c=t.subarray(t.length-this.authTagLength),l=this.encodeAdditionalBuffer(n,s.length),u=i(this.blockAlgorithm,o,a,{authTagLength:this.authTagLength});u.setAuthTag(c),u.setAAD(l,{plaintextLength:s.length});let d=u.update(s);try{let e=u.final();return e.length>0?Buffer.concat([d,e]):d}catch(r){throw TC(`decrypt failed`,r,e,HS(t),n,this.summary),r}}},DC={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},OC={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},kC={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},AC=bC(),jC=xC(),MC=SC(),NC=CC(),PC=wC();function FC(e){switch(e){case DC.TLS_RSA_WITH_AES_128_GCM_SHA256:return IC(DC.TLS_RSA_WITH_AES_128_GCM_SHA256,`TLS_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,AC,OC);case DC.TLS_RSA_WITH_AES_256_GCM_SHA384:return IC(DC.TLS_RSA_WITH_AES_256_GCM_SHA384,`TLS_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,AC,kC,`sha384`);case DC.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return IC(DC.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,jC,OC);case DC.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return IC(DC.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,jC,kC,`sha384`);case DC.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return IC(DC.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,MC,OC);case DC.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return IC(DC.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,MC,kC,`sha384`);case DC.TLS_PSK_WITH_AES_128_GCM_SHA256:return IC(DC.TLS_PSK_WITH_AES_128_GCM_SHA256,`TLS_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,NC,OC,`sha256`);case DC.TLS_PSK_WITH_AES_256_GCM_SHA384:return IC(DC.TLS_PSK_WITH_AES_256_GCM_SHA384,`TLS_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,NC,kC,`sha384`);case DC.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return IC(DC.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,PC,OC,`sha256`);case DC.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return IC(DC.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,PC,kC,`sha384`)}return null}function IC(e,t,n,r,i,a=`sha256`){let o=new EC;return o.id=e,o.name=t,o.blockAlgorithm=n,o.kx=r,o.hashAlgorithm=a,o.keyLength=i.K_LEN,o.nonceLength=i.N_MAX,o.nonceImplicitLength=4,o.nonceExplicitLength=8,o.ivLength=o.nonceImplicitLength,o.authTagLength=16,o}function LC(e){switch(e){case vS.secp256r1_23:{let{privateKey:t,publicKey:n}=wS();return{curve:e,privateKey:t,publicKey:n}}case vS.x25519_29:{let t=Tv.default.box.keyPair();return{curve:e,privateKey:Buffer.from(t.secretKey.buffer),publicKey:Buffer.from(t.publicKey.buffer)}}default:throw Error()}}var RC=class{static type=23},zC=class e{static type=65281;static spec={type:Q.types.uint16be,data:Q.types.uint8};type=e.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new e}static deSerialize(t){return new e((0,Q.decode)(t,e.spec))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},BC=class e{static type=14;static spec={type:Q.types.uint16be,data:Q.types.buffer(Q.types.uint16be)};type=e.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(t,n){return new e({profiles:t,mki:n})}static deSerialize(t){let n=new e((0,Q.decode)(t,e.spec)),r=n.data.readUInt16BE(),i=Array(r/2);for(let e=0;e<i.length;e++)i[e]=n.data.readUInt16BE(e*2+2);return n.profiles=i,n.mki=n.data.slice(r+2),n}serialize(){let t=Buffer.alloc(2);t.writeUInt16BE(this.profiles.length*2);let n=Buffer.concat([t,...this.profiles.map(e=>{let t=Buffer.alloc(2);return t.writeUInt16BE(e),t}),this.mki]);this.data=n;let r=(0,Q.encode)(this,e.spec).slice();return Buffer.from(r)}static fromData(t){let n=Buffer.alloc(4);return n.writeUInt16BE(e.type),n.writeUInt16BE(t.length,2),e.deSerialize(Buffer.concat([n,t]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},VC=class e{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:Q.types.array(QS,Q.types.uint24be,`bytes`)};static createEmpty(){return new e(void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},HC=class e{constructor(e=1){this.type=e}static spec={type:Q.types.uint8};static createEmpty(){return new e}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}},UC=class e{constructor(e,t){this.algorithm=e,this.signature=t}msgType=15;messageSeq;static spec={algorithm:Q.types.uint16be,signature:Q.types.buffer(Q.types.uint16be)};static createEmpty(){return new e(void 0,void 0)}static deSerialize(t){let n=(0,Q.decode)(t,e.spec);return new e(...Object.values(n))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},WC=class e{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:Q.types.buffer(Q.types.uint8)};static createEmpty(){return new e(void 0)}static deSerialize(t){let n=(0,Q.decode)(t,e.spec);return new e(...Object.values(n))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},GC=class e{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new e(void 0)}static deSerialize(t){return new e(t)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},KC=class e{constructor(e,t,n){this.certificateTypes=e,this.signatures=t,this.authorities=n}msgType=13;messageSeq;static spec={certificateTypes:Q.types.array($S,Q.types.uint8,`bytes`),signatures:Q.types.array(tC,Q.types.uint16be,`bytes`),authorities:Q.types.array(eC,Q.types.uint16be,`bytes`)};static createEmpty(){return new e(void 0,void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},qC=class e{constructor(e,t,n,r,i,a){this.serverVersion=e,this.random=t,this.sessionId=n,this.cipherSuite=r,this.compressionMethod=i,this.extensions=a}msgType=2;messageSeq;static spec={serverVersion:nC,random:rC.spec,sessionId:Q.types.buffer(Q.types.uint8),cipherSuite:Q.types.uint16be,compressionMethod:Q.types.uint8};static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){let n=(0,Q.decode)(t,e.spec),r=new e(...Object.values(n));return r.serialize().length<t.length?new e(...Object.values((0,Q.decode)(t,{...e.spec,extensions:ZS}))):r}serialize(){let t=this.extensions===void 0?(0,Q.encode)(this,e.spec).slice():(0,Q.encode)(this,{...e.spec,extensions:ZS}).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},JC=class e{msgType=14;messageSeq;static spec={};static createEmpty(){return new e}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}};function YC(e,t){return Buffer.from((0,Q.encode)(e,t).slice())}var XC=class e{constructor(e,t,n,r,i,a,o,s){this.ellipticCurveType=e,this.namedCurve=t,this.publicKeyLength=n,this.publicKey=r,this.hashAlgorithm=i,this.signatureAlgorithm=a,this.signatureLength=o,this.signature=s}msgType=12;messageSeq;static spec={ellipticCurveType:Q.types.uint8,namedCurve:Q.types.uint16be,publicKeyLength:Q.types.uint8,publicKey:Q.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:Q.types.uint8,signatureAlgorithm:Q.types.uint8,signatureLength:Q.types.uint16be,signature:Q.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){let n=(0,Q.decode)(t,e.spec);return new e(...Object.values(n))}serialize(){return YC(this,e.spec)}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},ZC=e=>{switch(e){case 1:case 7:return 16}},QC=e=>{switch(e){case 1:return 14;case 7:return 12}};sS(`werift-rtp : packages/rtp/src/codec/av1.ts`),Object.entries({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`}).reduce((e,[t,n])=>(e[n]=Number(t),e),{}),Buffer.from([0,0,0,1]);function $C(e,t){let n=Buffer.alloc(t);return e.copy(n),n}function ew(e){return Number.parseInt(e.toString(),10)}function tw(e){let t=e[0];return t>127&&t<192}var nw=class e{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(t,n,r,i){let a=new e({type:t,count:n,version:2,length:i}).serialize();return Buffer.concat([a,r])}serialize(){let e=new Ax(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),Nx([1,1,2],[e.value,this.type,this.length])}static deSerialize(t){let[n,r,i]=Fx(t,[1,1,2]),a=Mx(n,0,2),o=Mx(n,2,1)>0,s=Mx(n,3,5);return new e({version:a,padding:o,count:s,type:r,length:i})}},rw=class e{static count=4;count=e.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(t){let[n,r]=Fx(t,[4,4]),i=[];for(let e=8;e<t.length;e+=8)i.push({ssrc:t.readUInt32BE(e),sequenceNumber:t[e+4]});return new e({senderSsrc:n,mediaSsrc:r,fir:i})}serialize(){let e=Nx([4,4],[this.senderSsrc,this.mediaSsrc]),t=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:e,sequenceNumber:n},r)=>{t.writeUInt32BE(e,r*8),t[r*8+4]=n}),Buffer.concat([e,t])}},iw=class e{static count=1;count=e.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(t){let[n,r]=Fx(t,[4,4]);return new e({senderSsrc:n,mediaSsrc:r})}serialize(){return Nx([4,4],[this.senderSsrc,this.mediaSsrc])}},aw=class e{static count=15;length;count=e.count;senderSsrc;mediaSsrc;uniqueID=`REMB`;ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let[n,r,i,a,o]=Fx(t,[4,4,4,1,1]),s=Mx(o,0,6),c=(Mx(o,6,2)<<16)+(t[14]<<8)+t[15],l=s>46?18446744073709551615n:BigInt(c)<<BigInt(s),u=[];for(let e=16;e<t.length;e+=4){let n=t.slice(e).readUIntBE(0,4);u.push(n)}return new e({senderSsrc:n,mediaSsrc:r,uniqueID:Nx([4],[i]).toString(),ssrcNum:a,brExp:s,brMantissa:c,ssrcFeedbacks:u,bitrate:l})}serialize(){let e=Buffer.concat([Nx([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),Nx([1],[this.ssrcNum])]),t=new Ax(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);let n=Buffer.concat(this.ssrcFeedbacks.map(e=>Nx([4],[e]))),r=Buffer.concat([e,Nx([3],[t.value]),n]);return this.length=r.length/4,r}},ow=sS(`werift-rtp: /rtcp/psfb/index`),sw=class e{static type=206;type=e.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return nw.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(t,n){let r;switch(n.count){case rw.count:r=rw.deSerialize(t);break;case iw.count:r=iw.deSerialize(t);break;case aw.count:r=aw.deSerialize(t);break;default:ow(`unknown psfb packet`,n.count)}return new e({feedback:r})}},cw=class e{ssrc=0;reports=[];static type=201;type=e.type;constructor(e={}){Object.assign(this,e)}serialize(){let t=Nx([4],[this.ssrc]);return t=Buffer.concat([t,...this.reports.map(e=>e.serialize())]),nw.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let[r]=Fx(t,[4]),i=4,a=[];for(let e=0;e<n;e++)a.push(lw.deSerialize(t.slice(i,i+24))),i+=24;return new e({ssrc:r,reports:a})}},lw=class e{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 Nx([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(t){let[n,r,i,a,o,s,c]=Fx(t,[4,1,3,4,4,4,4]);return new e({ssrc:n,fractionLost:r,packetsLost:i,highestSequence:a,jitter:o,lsr:s,dlsr:c})}},uw=205,dw=class e{static count=1;count=e.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e),this.header||=new nw({type:uw,count:this.count,version:2})}static deSerialize(t,n){let[r,i]=Fx(t,[4,4]),a=[];for(let e=8;e<t.length;e+=4){let[n,r]=Fx(t.subarray(e),[2,2]);a.push(n);for(let e=0;e<16;e++)r>>e&1&&a.push(n+e+1)}return new e({header:n,senderSsrc:r,mediaSourceSsrc:i,lost:a})}serialize(){let e=Nx([4,4],[this.senderSsrc,this.mediaSourceSsrc]),t=[];if(this.lost.length>0){let e=this.lost[0],n=0;this.lost.slice(1).forEach(r=>{let i=r-e-1;i>=0&&i<16?n|=1<<i:(t.push(Nx([2,2],[e,n])),e=r,n=0)}),t.push(Nx([2,2],[e,n]))}let n=Buffer.concat([e,Buffer.concat(t)]);return this.header.length=n.length/4,Buffer.concat([this.header.serialize(),n])}},fw=sS(`werift/rtp/rtcp/rtpfb/twcc`),pw=class e{static count=15;count=e.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||=new nw({type:205,count:this.count,version:2})}static deSerialize(t,n){let[r,i,a,o,s,c]=Fx(t,[4,4,2,2,3,1]),l=[],u=[],d=16;for(let e=0;e<o;){let n=Mx(t.slice(d,d+1)[0],0,1),r;switch(n){case 0:{let n=mw.deSerialize(t.slice(d,d+2));r=n;let i=Math.min(o-e,n.runLength);if(n.packetStatus===1||n.packetStatus===2)for(let e=0;e<i;e++)u.push(new gw({type:n.packetStatus}));e+=i}break;case 1:{let n=hw.deSerialize(t.slice(d,d+2));r=n,n.symbolSize===0&&n.symbolList.forEach(e=>{e===1&&u.push(new gw({type:1}))}),n.symbolSize===1&&n.symbolList.forEach(e=>{(e===1||e===2)&&u.push(new gw({type:e}))}),e+=n.symbolList.length}}if(!r)throw Error();d+=2,l.push(r)}let f=d;return u.forEach(e=>{e.type===1&&(e.deSerialize(t.slice(f,f+1)),f++),e.type===2&&(e.deSerialize(t.slice(f,f+2)),f+=2)}),new e({senderSsrc:r,mediaSourceSsrc:i,baseSequenceNumber:a,packetStatusCount:o,referenceTime:s,fbPktCount:c,recvDeltas:u,packetChunks:l,header:n})}serialize(){let e=Nx([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),t=Buffer.concat(this.packetChunks.map(e=>e.serialize())),n=Buffer.concat(this.recvDeltas.map(e=>{try{return e.serialize()}catch(e){fw(e?.message);return}}).filter(e=>e)),r=Buffer.concat([e,t,n]);if(this.header.padding&&r.length%4!=0){let e=4-r.length%4,t=Buffer.alloc(e);return t[t.length-1]=t.length,this.header.length=Math.floor((r.length+t.length)/4),Buffer.concat([this.header.serialize(),r,t])}return this.header.length=Math.floor(r.length/4),Buffer.concat([this.header.serialize(),r])}get packetResults(){let e=this.baseSequenceNumber-1,t=this.packetChunks.filter(e=>e instanceof mw).flatMap(t=>t.results(e)),n=0,r=BigInt(this.referenceTime)*64n;for(let e of t){let t=this.recvDeltas[n];e.received&&t&&(r+=BigInt(t.delta)/1000n,e.delta=t.delta,e.receivedAtMs=Number(r),n++)}return t}},mw=class e{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(t){let n=Mx(t[0],1,2),r=(Mx(t[0],3,5)<<8)+t[1];return new e({type:0,packetStatus:n,runLength:r})}serialize(){return new jx(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let t=this.packetStatus===1||this.packetStatus===2,n=[];for(let r=0;r<=this.runLength;++r)n.push(new _w({sequenceNumber:++e,received:t}));return n}},hw=class e{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=Mx(t[0],1,1),r=[];function i(e,t){for(let n=0;n<e;n++)t(n)}switch(n){case 0:i(6,e=>r.push(Mx(t[0],2+e,1))),i(8,e=>r.push(Mx(t[1],e,1)));break;case 1:i(3,e=>r.push(Mx(t[0],2+e*2,2))),i(4,e=>r.push(Mx(t[1],e*2,2)));break;default:n=(Mx(t[0],2,6)<<8)+t[1]}return new e({type:1,symbolSize:n,symbolList:r})}serialize(){let e=Buffer.alloc(2),t=new jx(16).set(1).set(this.symbolSize),n=this.symbolSize===0?1:2;return this.symbolList.forEach(e=>{t.set(e,n)}),e.writeUInt16BE(t.value),e}},gw=class e{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n,r;if(t.length===1?(n=1,r=250*t[0]):t.length===2&&(n=2,r=250*t.readInt16BE()),n===void 0||r===void 0)throw Error();return new e({type:n,delta:r})}deSerialize(t){let n=e.deSerialize(t);this.delta=n.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||=2):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}if(this.type===2){let e=Buffer.alloc(2);return e.writeInt16BE(this.delta),e}throw Error(`errDeltaExceedLimit `+this.delta+` `+this.type)}},_w=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(e){Object.assign(this,e)}},vw=sS(`werift-rtp:packages/rtp/rtcp/rtpfb/index`),yw=class e{static type=uw;type=e.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(t,n){let r;switch(n.count){case dw.count:r=dw.deSerialize(t,n);break;case pw.count:r=pw.deSerialize(t,n);break;default:vw(`unknown rtpfb packet`,n.count)}return new e({feedback:r,header:n})}},bw=class e{static type=202;type=e.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(t=>e+=t.length),e}serialize(){let e=Buffer.concat(this.chunks.map(e=>e.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return nw.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(t,n){let r=[];for(let e=0;e<t.length;){let n=xw.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({chunks:r})}},xw=class e{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(t=>e+=t.length),e+=1,e+=Cw(e),e}serialize(){let e=Buffer.concat([Nx([4],[this.source]),Buffer.concat(this.items.map(e=>e.serialize()))]);return Buffer.concat([e,Buffer.alloc(Cw(e.length))])}static deSerialize(t){let n=t.readUInt32BE(),r=[];for(let e=4;e<t.length&&t[e]!==0;){let n=Sw.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({source:n,items:r})}},Sw=class e{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([Nx([1,1],[this.type,e.length]),e])}static deSerialize(t){let n=t[0],r=t[1],i=t.slice(2,2+r).toString();return new e({type:n,text:i})}};function Cw(e){return e%4==0?0:4-e%4}var ww=class e{ssrc=0;senderInfo;reports=[];static type=200;type=e.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 t=Buffer.alloc(4);return t.writeUInt32BE(this.ssrc),t=Buffer.concat([t,this.senderInfo.serialize()]),t=Buffer.concat([t,...this.reports.map(e=>e.serialize())]),nw.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let r=t.readUInt32BE(),i=Tw.deSerialize(t.subarray(4,24)),a=24,o=[];for(let e=0;e<n;e++)o.push(lw.deSerialize(t.subarray(a,a+24))),a+=24;return new e({ssrc:r,senderInfo:i,reports:o})}},Tw=class e{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:Ew(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return Nx([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(t){let[n,r,i,a]=Fx(t,[8,4,4,4]);return new e({ntpTimestamp:n,rtpTimestamp:r,packetCount:i,octetCount:a})}},Ew=e=>{let[t,n]=Fx(Nx([8],[e]),[4,4]);return Number(`${t}.${n}`)},Dw=sS(`werift-rtp:packages/rtp/src/rtcp/rtcp.ts`),Ow=class{static deSerialize(e){let t=0,n=[];for(;t<e.length;){let r=nw.deSerialize(e.subarray(t,t+4));t+=4;let i=e.subarray(t);t+=r.length*4,r.padding&&(i=i.subarray(0,i.length-i.subarray(-1)[0]));try{switch(r.type){case ww.type:n.push(ww.deSerialize(i,r.count));break;case cw.type:n.push(cw.deSerialize(i,r.count));break;case bw.type:n.push(bw.deSerialize(i,r));break;case yw.type:n.push(yw.deSerialize(i,r));break;case sw.type:n.push(sw.deSerialize(i,r))}}catch(e){Dw(`deSerialize RTCP`,e)}}return n}};function kw(e){return e.length>=2&&e[1]>=192&&e[1]<=208}var Aw={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`};function jw(e,t){return e.map(e=>{let n=t[e.id];if(!n)return{uri:`unknown`,value:e.payload};switch(n){case Aw.sdesMid:case Aw.sdesRTPStreamID:case Aw.repairedRtpStreamId:return{uri:n,value:Lw(e.payload)};case Aw.transportWideCC:return{uri:n,value:Rw(e.payload)};case Aw.absSendTime:return{uri:n,value:zw(e.payload)};case Aw.audioLevelIndication:return{uri:n,value:Bw(e.payload)};case Aw.videoOrientation:return{uri:n,value:Vw(e.payload)};default:return{uri:n,value:e.payload}}}).reduce((e,t)=>(t&&(e[t.uri]=t.value),e),{})}function Mw(e){return Buffer.from(e)}function Nw(e){return Buffer.from(e)}function Pw(e){return Buffer.from(e)}function Fw(e){return Nx([2],[e])}function Iw(e){let t=Buffer.alloc(3),n=e>>14n&16777215n;return t.writeUIntBE(Number(n),0,3),t}function Lw(e){return e.toString()}function Rw(e){return e.readUInt16BE()}function zw(e){return Fx(e,[3])[0]}function Bw(e){let t=new Ix(e);return{v:t.readBits(1)===1,level:t.readBits(7)}}function Vw(e){let t=new Ix(e);return t.readBits(4),{c:t.readBits(1),f:t.readBits(1),r1:t.readBits(1),r0:t.readBits(1)}}var Hw=sS(`packages/rtp/src/rtp/red/packet.ts`),Uw=class e{header;blocks=[];static deSerialize(t){let n=t instanceof ArrayBuffer?Buffer.from(t):t,r=new e,i=0;return[r.header,i]=Ww.deSerialize(n),r.header.fields.forEach(({blockLength:e,timestampOffset:t,blockPT:a})=>{if(e&&t){let o=n.subarray(i,i+e);r.blocks.push({block:o,blockPT:a,timestampOffset:t}),i+=e}else{let e=n.subarray(i);r.blocks.push({block:e,blockPT:a})}}),r}serialize(){this.header=new Ww;for(let{timestampOffset:e,blockPT:t,block:n}of this.blocks)e?this.header.fields.push({fBit:1,blockPT:t,blockLength:n.length,timestampOffset:e}):this.header.fields.push({fBit:0,blockPT:t});let e=this.header.serialize();for(let{block:t}of this.blocks)e=Buffer.concat([e,t]);return e}},Ww=class e{fields=[];static deSerialize(t){let n=0,r=new e;for(;;){let e={};r.fields.push(e);let i=new Ix(t.subarray(n));if(e.fBit=i.readBits(1),e.blockPT=i.readBits(7),n++,e.fBit===0)break;e.timestampOffset=i.readBits(14),e.blockLength=i.readBits(10),n+=3}return[r,n]}serialize(){let e=Buffer.alloc(0);for(let t of this.fields)try{if(t.timestampOffset&&t.blockLength){let n=new Ix(Buffer.alloc(4)).writeBits(1,t.fBit).writeBits(7,t.blockPT).writeBits(14,t.timestampOffset).writeBits(10,t.blockLength);e=Buffer.concat([e,n.uint8Array])}else{let n=new Ix(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,n.uint8Array])}}catch(e){Hw(e?.message)}return e}},Gw=class{constructor(e=1){this.distance=e}cache=[];cacheSize=10;push(e){this.cache.push(e),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let e=new Uw,t=this.cache.slice(-(this.distance+1)),n=t.pop();return n?(t.forEach(t=>{let r=Qx(n.timestamp,-t.timestamp);r>Kw||e.blocks.push({block:t.block,blockPT:t.blockPT,timestampOffset:r})}),e.blocks.push({block:n.block,blockPT:n.blockPT}),e):e}},Kw=16383,qw=class{size=150;sequenceNumbers=[];push(e,t){let n=[];return e.blocks.forEach(({blockPT:r,timestampOffset:i,block:a},o)=>{let s=Zx(t.header.sequenceNumber,-(e.blocks.length-(o+1)));i?n.push(new tT(new eT({timestamp:Qx(t.header.timestamp,-i),payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:!0}),a)):n.push(new tT(new eT({timestamp:t.header.timestamp,payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:!0}),a))}),n.filter(e=>!this.sequenceNumbers.includes(e.header.sequenceNumber)&&(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(e.header.sequenceNumber),!0))}},Jw={OneByte:48862,TwoByte:4096},Yw=2,Xw=4,Zw=8,Qw=12,$w=4,eT=class e{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=Jw.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=new e,r=0,i=t[r++];n.version=Mx(i,0,2),n.padding=Mx(i,2)>0,n.extension=Mx(i,3)>0,n.csrcLength=Mx(i,4,4),n.csrc=[...Array(n.csrcLength)].map(()=>{let e=t.readUInt32BE(r);return r+=4,e}),r+=Qw-1;let a=t[1];n.marker=Mx(a,0)>0,n.payloadType=Mx(a,1,7),n.sequenceNumber=t.readUInt16BE(Yw),n.timestamp=t.readUInt32BE(Xw),n.ssrc=t.readUInt32BE(Zw);for(let e=0;e<n.csrc.length;e++){let r=Qw+e*$w;n.csrc[e]=t.subarray(r).readUInt32BE()}if(n.extension){n.extensionProfile=t.subarray(r).readUInt16BE(),r+=2;let e=t.subarray(r).readUInt16BE()*4;switch(n.extensionLength=e,r+=2,n.extensionProfile){case Jw.OneByte:{let i=r+e;for(;r<i;){if(t[r]===0){r++;continue}let e=t[r]>>4,i=(t[r]&(t[r]^240))+1;if(r++,e===15)break;let a={id:e,payload:t.subarray(r,r+i)};n.extensions=[...n.extensions,a],r+=i}}break;case Jw.TwoByte:{let i=r+e;for(;r<i;){if(t[r]===0){r++;continue}let e=t[r];r++;let i=t[r];r++;let a={id:e,payload:t.subarray(r,r+i)};n.extensions=[...n.extensions,a],r+=i}}break;default:{let i={id:0,payload:t.subarray(r,r+e)};n.extensions=[...n.extensions,i],r+=n.extensions[0].payload.length}}}return n.payloadOffset=r,n.padding&&(n.paddingSize=t[t.length-1]),n}get serializeSize(){let{csrc:e,extensionProfile:t,extensions:n}=this,r=12+e.length*$w;if(n.length>0||this.extension===!0){let e=4;switch(t){case Jw.OneByte:for(let t of n)e+=1+t.payload.length;break;case Jw.TwoByte:for(let t of n)e+=2+t.payload.length;break;default:e+=n[0].payload.length}r+=Math.floor((e+3)/4)*4}return r}serialize(e){let t=Buffer.alloc(e),n=0,r=new Ax(8);r.set(2,0,this.version),this.padding&&r.set(1,2,1),this.extensions.length>0&&(this.extension=!0),this.extension&&r.set(1,3,1),r.set(4,4,this.csrc.length),t.writeUInt8(r.value,n++);let i=new Ax(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),t.writeUInt8(i.value,n++),t.writeUInt16BE(this.sequenceNumber,Yw),n+=2,t.writeUInt32BE(this.timestamp,Xw),n+=4,t.writeUInt32BE(this.ssrc,Zw),n+=4;for(let e of this.csrc)t.writeUInt32BE(e,n),n+=4;if(this.extension){let e=n;t.writeUInt16BE(this.extensionProfile,n),n+=4;let r=n;switch(this.extensionProfile){case Jw.OneByte:for(let e of this.extensions)t.writeUInt8(e.id<<4|e.payload.length-1,n++),e.payload.copy(t,n),n+=e.payload.length;break;case Jw.TwoByte:for(let e of this.extensions)t.writeUInt8(e.id,n++),t.writeUInt8(e.payload.length,n++),e.payload.copy(t,n),n+=e.payload.length;break;default:{let e=this.extensions[0].payload.length;if(e%4!=0)throw Error();this.extensions[0].payload.copy(t,n),n+=e}}let i=n-r,a=Math.trunc((i+3)/4)*4;t.writeUInt16BE(Math.trunc(a/4),e+2);for(let e=0;e<a-i;e++)t.writeUInt8(0,n),n++}return this.payloadOffset=n,t}},tT=class e{constructor(e,t){this.header=e,this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new e(new eT({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:t}=this.header;if(this.payload.copy(e,t),this.header.padding){let t=Buffer.alloc(this.header.paddingSize);t.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),e=Buffer.concat([e,t])}return e}static deSerialize(t){let n=eT.deSerialize(t);return new e(n,t.subarray(n.payloadOffset,t.length-n.paddingSize))}clear(){this.payload=null}};function nT(e,t,n){return new tT(new eT({payloadType:t,marker:e.header.marker,sequenceNumber:e.payload.readUInt16BE(0),timestamp:e.header.timestamp,ssrc:n}),e.payload.subarray(2))}function rT(e,t,n,r){let i=Buffer.allocUnsafe(2);return i.writeUInt16BE(e.header.sequenceNumber,0),new tT(new eT({payloadType:t,marker:e.header.marker,sequenceNumber:n,timestamp:e.header.timestamp,ssrc:r,csrc:e.header.csrc,extensions:e.header.extensions}),Buffer.concat([i,e.payload]))}var iT=class{constructor(e,t,n,r){this.srtpSessionKey=e,this.srtpSessionSalt=t,this.srtcpSessionKey=n,this.srtcpSessionSalt=r}encryptRtp(e,t,n){return Buffer.from([])}decryptRtp(e,t,n){return[]}encryptRTCP(e,t){return Buffer.from([])}decryptRTCP(e){return[]}},aT=class extends Error{constructor(e){super(e),this.name=`SrtpAuthenticationError`}},oT=12,sT=8;function cT(e,t,n=`Failed to authenticate SRTP packet`){let r=e.length-t;uT(e.length>=oT+t,n);let i=dT(()=>eT.deSerialize(e.subarray(0,r)),n);return i.paddingSize=0,uT(i.payloadOffset>=oT&&i.payloadOffset<=r,n),i}function lT(e,t,n,r=`Failed to authenticate SRTCP packet`){return uT(e.length>=sT+t+n,r),dT(()=>nw.deSerialize(e.subarray(0,4)),r)}function uT(e,t){if(!e)throw new aT(t)}function dT(e,t){try{return e()}catch{throw new aT(t)}}function fT(e,t,n=`Failed to authenticate SRTP packet`){if(!e.padding)return e.paddingSize=0,e;uT(t.length>e.payloadOffset,n);let r=t[t.length-1];return uT(r>0&&r<=t.length-e.payloadOffset,n),e.paddingSize=r,e}var pT=class extends iT{constructor(e,t,n,r,i,a){super(e,t,n,r),this.srtpSessionAuthTag=i,this.srtcpSessionAuthTag=a}authTagLength=10;encryptRtp(e,t,n){let i=e.serialize(e.serializeSize),a=this.generateCounter(e.sequenceNumber,n,e.ssrc,this.srtpSessionSalt),o=r(`aes-128-ctr`,this.srtpSessionKey,a).update(t),s=this.generateSrtpAuthTag(n,i,o);return Buffer.concat([i,o,s])}decryptRtp(e,t,n=cT(e,this.authTagLength)){let r=e.length-this.authTagLength,a=e.subarray(0,r);hT(e.subarray(r),this.generateSrtpAuthTag(t,a.subarray(0,n.payloadOffset),a.subarray(n.payloadOffset)),`Failed to authenticate SRTP packet`);let o=this.generateCounter(n.sequenceNumber,t,n.ssrc,this.srtpSessionSalt),s=i(`aes-128-ctr`,this.srtpSessionKey,o),c=a.subarray(n.payloadOffset),l=s.update(c),u=Buffer.concat([a.subarray(0,n.payloadOffset),l]);return[u,fT(n,u,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){let n=Buffer.from(e),i=n.readUInt32BE(4),a=this.generateCounter(t&65535,t>>16,i,this.srtcpSessionSalt);r(`aes-128-ctr`,this.srtcpSessionKey,a).update(n.slice(8)).copy(n,8),n=Buffer.concat([n,Buffer.alloc(4)]),n.writeUInt32BE(t,n.length-4),n[n.length-4]|=128;let o=this.generateSrtcpAuthTag(n);return n=Buffer.concat([n,o]),n}decryptRTCP(e){let t=lT(e,this.authTagLength,mT),n=e.length-(this.authTagLength+mT),r=e.subarray(0,e.length-this.authTagLength);hT(e.subarray(e.length-this.authTagLength),this.generateSrtcpAuthTag(r),`Failed to authenticate SRTCP packet`);let a=Buffer.from(e).slice(0,n);if(!(e[n]>>>7))return[a,t];let o=e.readUInt32BE(n);o&=2147483647;let s=e.readUInt32BE(4),c=this.generateCounter(o&65535,o>>16,s,this.srtcpSessionSalt);return i(`aes-128-ctr`,this.srtcpSessionKey,c).update(a.subarray(8)).copy(a,8),[a,t]}generateSrtcpAuthTag(e){return o(`sha1`,this.srtcpSessionAuthTag).update(e).digest().slice(0,10)}generateCounter(e,t,n,r){let i=Buffer.alloc(16);i.writeUInt32BE(n,4),i.writeUInt32BE(t,8),i.writeUInt32BE(Number(BigInt(e)<<16n),12);for(let e=0;e<r.length;e++)i[e]^=r[e];return i}generateSrtpAuthTag(e,...t){let n=o(`sha1`,this.srtpSessionAuthTag),r=Buffer.alloc(4);r.writeUInt32BE(e);for(let e of t)n.update(e);return n.update(r).digest().subarray(0,10)}},mT=4;function hT(e,t,n){if(e.length!==t.length||!u(e,t))throw new aT(n)}var gT=class extends iT{aeadAuthTagLen=16;rtpIvWriter=Px([2,4,4,2],!0);rtcpIvWriter=Px([2,4,2,4],!0);aadWriter=Px([4],!0);constructor(e,t,n,r){super(e,t,n,r)}encryptRtp(e,t,n){let i=e.serialize(e.serializeSize),a=this.rtpInitializationVector(e,n),o=r(`aes-128-gcm`,this.srtpSessionKey,a);o.setAAD(i);let s=o.update(t);o.final();let c=o.getAuthTag();return Buffer.concat([i,s,c])}decryptRtp(e,t,n=cT(e,this.aeadAuthTagLen)){let r=e.subarray(0,n.payloadOffset),a=e.length-this.aeadAuthTagLen,o=e.subarray(a),s=Buffer.from([]);s=$C(s,e.length-this.aeadAuthTagLen),r.copy(s);let c=this.rtpInitializationVector(n,t),l=e.slice(n.payloadOffset,a),u=i(`aes-128-gcm`,this.srtpSessionKey,c);u.setAAD(r),u.setAuthTag(o);let d=u.update(l);return yT(u,`SRTP`),d.copy(s,n.payloadOffset),[s,fT(n,s,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){let n=e.readUInt32BE(4),i=e.length+this.aeadAuthTagLen,a=Buffer.from([]);a=$C(a,i+_T),e.slice(0,8).copy(a);let o=this.rtcpInitializationVector(n,t),s=this.rtcpAdditionalAuthenticatedData(e,t),c=r(`aes-128-gcm`,this.srtcpSessionKey,o);c.setAAD(s);let l=c.update(e.slice(8));return c.final(),l.copy(a,8),c.getAuthTag().copy(a,8+l.length),s.slice(8,12).copy(a,i),a}decryptRTCP(e){let t=lT(e,this.aeadAuthTagLen,_T),n=e.length-_T,r=n-this.aeadAuthTagLen,a=e.readUInt32BE(4),o=e.readUInt32BE(n),s=o>>>31==1,c=o&~(vT<<24),l=this.rtcpInitializationVector(a,c),u=s?Buffer.concat([e.subarray(0,8),e.subarray(n)]):Buffer.concat([e.subarray(0,r),e.subarray(n)]),d=s?e.slice(8,r):Buffer.alloc(0),f=s?Buffer.alloc(r):Buffer.from(e.subarray(0,r));s&&e.slice(0,8).copy(f);let p=i(`aes-128-gcm`,this.srtcpSessionKey,l);p.setAAD(u),p.setAuthTag(e.subarray(r,n));let m=p.update(d);return yT(p,`SRTCP`),s&&m.copy(f,8),[f,t]}rtpInitializationVector(e,t){let n=this.rtpIvWriter([0,e.ssrc,t,e.sequenceNumber]);for(let e=0;e<n.length;e++)n[e]^=this.srtpSessionSalt[e];return n}rtcpInitializationVector(e,t){let n=this.rtcpIvWriter([0,e,0,t]);for(let e=0;e<n.length;e++)n[e]^=this.srtcpSessionSalt[e];return n}rtcpAdditionalAuthenticatedData(e,t){let n=Buffer.concat([e.subarray(0,8),this.aadWriter([t])]);return n[8]|=vT,n}},_T=4,vT=128;function yT(e,t){try{e.final()}catch{throw new aT(`Failed to authenticate ${t} packet`)}}function bT(e,t){let n=r(`aes-128-ecb`,e,null);return n.setAutoPadding(!1),Buffer.concat([n.update(t),n.final()])}var xT=class{constructor(e,t,n){this.masterKey=e,this.masterSalt=t,this.profile=n;{let e=14-t.length;e>0&&(this.masterSalt=Buffer.concat([t,Buffer.alloc(e)]))}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=o(`sha1`,this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=o(`sha1`,this.srtcpSessionAuthTag),n){case 1:this.cipher=new pT(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case 7:this.cipher=new gT(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt)}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(e){let t=Buffer.from(this.masterSalt),n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];return t=Buffer.concat([t,Buffer.from([0,0])]),bT(this.masterKey,t)}generateSessionSalt(e){let t=Buffer.from(this.masterSalt),n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];return t=Buffer.concat([t,Buffer.from([0,0])]),t=bT(this.masterKey,t),t.subarray(0,14)}generateSessionAuthTag(e){let t=Buffer.from(this.masterSalt),n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];let r=Buffer.concat([t,Buffer.from([0,0])]),i=Buffer.concat([t,Buffer.from([0,1])]);return r=bT(this.masterKey,r),i=bT(this.masterKey,i),Buffer.concat([r,i.subarray(0,4)])}getSrtpSsrcState(e){let t=this.srtpSSRCStates[e];return t||(t={ssrc:e,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[e]=t,t)}getSrtcpSsrcState(e){let t=this.srtcpSSRCStates[e];return t||(t={srtcpIndex:0,ssrc:e},this.srtcpSSRCStates[e]=t,t)}updateRolloverCount(e,t){t.rolloverHasProcessed?e===0?t.lastSequenceNumber>ST&&t.rolloverCounter++:t.lastSequenceNumber<ST&&e>CT-ST?t.rolloverCounter>0&&t.rolloverCounter--:e<ST&&t.lastSequenceNumber>CT-ST&&t.rolloverCounter++:t.rolloverHasProcessed=!0,t.lastSequenceNumber=e}generateSrtpAuthTag(e,t){this.srtpSessionAuth=o(`sha1`,this.srtpSessionAuthTag);let n=Buffer.alloc(4);return n.writeUInt32BE(t),this.srtpSessionAuth.update(e).update(n).digest().slice(0,10)}index(e){let t=this.srtcpSSRCStates[e];return t?t.srtcpIndex:0}setIndex(e,t){let n=this.getSrtcpSsrcState(e);n.srtcpIndex=t%2147483647}},ST=100,CT=65535,wT=class extends xT{constructor(e,t,n){super(e,t,n)}encryptRTCP(e){let t=e.readUInt32BE(4),n=this.getSrtcpSsrcState(t);return n.srtcpIndex++,n.srtcpIndex>>TT&&(n.srtcpIndex=0),this.cipher.encryptRTCP(e,n.srtcpIndex)}decryptRTCP(e){return this.cipher.decryptRTCP(e)}},TT=2147483647,ET=class{constructor(e){this.ContextCls=e}localContext;remoteContext;onData;start(e,t,n,r,i){this.localContext=new this.ContextCls(e,t,i),this.remoteContext=new this.ContextCls(n,r,i)}},DT=class extends ET{constructor(e){super(wT),this.config=e,this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}decrypt=e=>{let[t]=this.remoteContext.decryptRTCP(e);return t};encrypt(e){return this.localContext.encryptRTCP(e)}},OT=class extends xT{constructor(e,t,n){super(e,t,n)}encryptRtp(e,t){let n=this.getSrtpSsrcState(t.ssrc);return this.updateRolloverCount(t.sequenceNumber,n),this.cipher.encryptRtp(t,e,n.rolloverCounter)}decryptRtp(e){let t=cT(e,this.rtpAuthTagLength),n=this.srtpSSRCStates[t.ssrc],r=n?{...n}:{ssrc:t.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(t.sequenceNumber,r);let i=this.cipher.decryptRtp(e,r.rolloverCounter,t);return n?Object.assign(n,r):this.srtpSSRCStates[t.ssrc]=r,i}get rtpAuthTagLength(){return this.profile===7?16:10}},kT=class extends ET{constructor(e){super(OT),this.config=e,this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}decrypt=e=>{let[t]=this.remoteContext.decryptRtp(e);return t};encrypt(e,t){return this.localContext.encryptRtp(e,t)}},AT=sS(`werift-dtls : packages/dtls/src/flight/client/flight5.ts : log`),jT=class extends fC{constructor(e,t,n,r){super(e,t,5,7),this.cipher=n,this.srtp=r}handleHandshake(e){this.dtls.bufferHandshakeCache([e],!1,4);let t=(()=>{switch(e.msg_type){case 2:return qC.deSerialize(e.fragment);case 11:return VC.deSerialize(e.fragment);case 12:return XC.deSerialize(e.fragment);case 13:return KC.deSerialize(e.fragment);case 14:return JC.deSerialize(e.fragment)}})();t&&MT[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}async exec(){if(this.dtls.flight===5){AT(this.dtls.sessionId,`flight5 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let e=this.dtls.requestedCertificateTypes.length>0;AT(this.dtls.sessionId,`send flight5`,e);let t=[e&&this.sendCertificate(),this.sendClientKeyExchange(),e&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(e=>e);this.dtls.lastMessage=t,await this.transmit(t)}sendCertificate(){let e=new VC([Buffer.from(this.cipher.localCert)]),t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw Error();let e=new WC(this.cipher.localKeyPair.publicKey),t=this.createPacket([e]),n=Buffer.concat(t.map(e=>e.serialize())),r=this.cipher.localKeyPair,i=this.cipher.remoteKeyPair;if(!i.publicKey)throw Error(`not exist`);let a=ES(i.publicKey,r.privateKey,r.curve);AT(this.dtls.sessionId,`extendedMasterSecret`,this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let o=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?AS(a,o):kS(a,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=FC(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),AT(this.dtls.sessionId,`cipher`,this.cipher.cipher.summary),n}sendCertificateVerify(){let e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize())),t=this.cipher.signatureData(e,`sha256`),n=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case mS.ecdsa_3:return xS.ecdsa_secp256r1_sha256;case mS.rsa_1:return xS.rsa_pkcs1_sha256}})();if(!n)throw Error();AT(this.dtls.sessionId,`signatureScheme`,this.cipher.signatureHashAlgorithm?.signature,n);let r=new UC(n,t),i=this.createPacket([r]);return Buffer.concat(i.map(e=>e.serialize()))}sendChangeCipherSpec(){let e=HC.createEmpty().serialize(),t=cC(this.dtls)([{type:20,fragment:e}],++this.dtls.recordSequenceNumber);return Buffer.concat(t.map(e=>e.serialize()))}sendFinished(){let e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize())),t=new GC(this.cipher.verifyData(e));this.dtls.epoch=1;let[n]=this.createPacket([t]);this.dtls.recordSequenceNumber=0;let r=this.cipher.encryptPacket(n).serialize();return AT(this.dtls.sessionId,`finished`,this.cipher.cipher.summary),r}},MT={};MT[2]=({cipher:e,srtp:t,dtls:n})=>r=>{AT(n.sessionId,`serverHello`,r.cipherSuite),e.remoteRandom=rC.from(r.random),e.cipherSuite=r.cipherSuite,AT(n.sessionId,`selected cipherSuite`,e.cipherSuite),r.extensions&&r.extensions.forEach(e=>{switch(e.type){case BC.type:{let r=BC.fromData(e.data),i=VS.findMatchingSRTPProfile(r.profiles,n.options.srtpProfiles||[]);if(AT(n.sessionId,`selected srtp profile`,i),i==null)return;t.srtpProfile=i}break;case RC.type:n.remoteExtendedMasterSecret=!0;break;case zC.type:AT(n.sessionId,`RenegotiationIndication`)}})},MT[11]=({cipher:e,dtls:t})=>n=>{AT(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},MT[12]=({cipher:e,dtls:t})=>n=>{if(!e.localRandom||!e.remoteRandom)throw Error();AT(t.sessionId,`ServerKeyExchange`,n),AT(t.sessionId,`selected curve`,n.namedCurve),e.remoteKeyPair={curve:n.namedCurve,publicKey:n.publicKey},e.localKeyPair=LC(n.namedCurve)},MT[13]=({dtls:e})=>t=>{AT(e.sessionId,`certificate_request`,t),e.requestedCertificateTypes=t.certificateTypes,e.requestedSignatureAlgorithms=t.signatures},MT[14]=({dtls:e})=>t=>{AT(e.sessionId,`server_hello_done`,t)};var NT=class e{constructor(e,t){this.serverVersion=e,this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:nC,cookie:Q.types.buffer(Q.types.uint8)};static createEmpty(){return new e(void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let e=this.serialize();return new WS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},PT=sS(`werift-dtls : packages/dtls/src/context/dtls.ts : log`),FT=class{constructor(e,t){this.options=e,this.sessionType=t}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(([e],[t])=>Number(e)-Number(t)).flatMap(([,{data:e}])=>e.sort((e,t)=>e.message_seq-t.message_seq))}checkHandshakesExist=e=>!e.find(e=>this.sortedHandshakeCache.find(t=>t.msg_type===e)==null);bufferHandshakeCache(e,t,n){this.handshakeCache[n]||(this.handshakeCache[n]={data:[],isLocal:t,flight:n});let r=e.filter(e=>{let r=this.handshakeCache[n].data.find(t=>t.msg_type===e.msg_type);return!r||(PT(this.sessionId,`exist`,r.summary,t,n),!1)});this.handshakeCache[n].data=[...this.handshakeCache[n].data,...r]}},IT=class{constructor(e){this.socket=e}send=(e,t)=>this.socket.send(e,t)},LT=class e{static type=10;static spec={type:Q.types.uint16be,data:Q.types.array(Q.types.uint16be,Q.types.uint16be,`bytes`)};type=e.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new e}static fromData(t){return new e({type:e.type,data:(0,Q.decode)(t,e.spec.data)})}static deSerialize(t){return new e((0,Q.decode)(t,e.spec))}serialize(){return Buffer.from((0,Q.encode)(this,e.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},RT=class e{static type=13;static spec={type:Q.types.uint16be,data:Q.types.array({hash:Q.types.uint8,signature:Q.types.uint8},Q.types.uint16be,`bytes`)};type=e.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new e}static deSerialize(t){return new e((0,Q.decode)(t,e.spec))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}static fromData(t){let n=Buffer.alloc(2);return n.writeUInt16BE(e.type),e.deSerialize(Buffer.concat([n,t]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},zT=class e{constructor(e,t){this.level=e,this.description=t}static spec={level:Q.types.uint8,description:Q.types.uint8};static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}},BT=sS(`werift-dtls : packages/dtls/record/receive.ts : log`),VT=sS(`werift-dtls : packages/dtls/record/receive.ts : err`),HT=e=>{let t=0,n=[];for(;e.length>t;){let r=e.readUInt16BE(t+11);if(e.length<t+(12+r))break;let i=oC.deSerialize(e.subarray(t));n.push(i),t+=13+r}return n},UT=(e,t)=>n=>{switch(n.recordLayerHeader.contentType){case 20:return BT(e.sessionId,`change cipher spec`),[{type:20,data:void 0}];case 22:{let r=n.fragment;try{n.recordLayerHeader.epoch>0&&(BT(e.sessionId,`decrypt handshake`),r=t.decryptPacket(n))}catch(t){throw VT(e.sessionId,`decrypt failed`,t),t}try{let e=0,t=[];for(;r.length>e;){let n=WS.deSerialize(r.subarray(e));t.push({type:22,data:n}),e+=n.fragment_length+12}return t}catch(t){throw VT(e.sessionId,`decSerialize failed`,t,r),t}}case 23:return[{type:23,data:t.decryptPacket(n)}];case 21:{let r=zT.deSerialize(n.fragment);if(lC[r.description]==null){let e=t.decryptPacket(n);r=zT.deSerialize(e)}if(VT(e.sessionId,`ContentType.alert`,r,lC[r.description],`flight`,e.flight,`lastFlight`,e.lastFlight),r.level>1)throw Error(`alert fatal error`);return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},WT=sS(`werift-dtls : packages/dtls/src/socket.ts : log`),GT=sS(`werift-dtls : packages/dtls/src/socket.ts : err`),KT=class{constructor(e,t){this.options=e,this.sessionType=t,this.dtls=new FT(this.options,this.sessionType),this.cipher=new BS(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new IT(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new $;onData=new $;onError=new $;onClose=new $;transport;cipher;dtls;srtp=new VS;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){WT(`renegotiation`,this.sessionType),this.connected=!1,this.cipher=new BS(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new FT(this.options,this.sessionType),this.srtp=new VS,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=e=>{let t=HT(e);for(let e of t)try{let t=UT(this.dtls,this.cipher)(e);for(let e of t)switch(e.type){case 22:{let t=e.data,n=this.handleFragmentHandshake([t]),r=Object.values(n.reduce((e,t)=>(e[t.msg_type]||(e[t.msg_type]=[]),e[t.msg_type].push(t),e),{})).map(e=>WS.assemble(e)).sort((e,t)=>e.msg_type-t.msg_type);this.onHandleHandshakes(r).catch(e=>{GT(this.dtls.sessionId,`onHandleHandshakes error`,e),this.onError.execute(e)})}break;case 23:this.onData.execute(e.data);break;case 21:this.onClose.execute()}}catch(e){GT(this.dtls.sessionId,`catch udpOnMessage error`,e)}};setupExtensions(){if(WT(this.dtls.sessionId,`support srtpProfiles`,this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let e=BC.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{let e=LT.createEmpty();e.data=yS,this.extensions.push(e.extension)}{let e=RT.createEmpty();e.data=CS,this.extensions.push(e.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:RC.type,data:Buffer.alloc(0)});{let e=zC.createEmpty();this.extensions.push(e.extension)}}waitForReady=e=>new Promise(async(t,n)=>{for(let n=0;n<10;n++)if(e()){t();break}else await E(100*n);n(`waitForReady timeout`)});handleFragmentHandshake(e){let t=e.filter(e=>e.fragment_length===e.length||(this.bufferFragmentedHandshakes.push(e),!1));if(this.bufferFragmentedHandshakes.length>1){let[e]=this.bufferFragmentedHandshakes.slice(-1);e.fragment_offset+e.fragment_length===e.length&&(t=[...this.bufferFragmentedHandshakes,...t],this.bufferFragmentedHandshakes=[])}return t}send=async(e,t)=>{let n=cC(this.dtls)([{type:23,fragment:e}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(n).serialize(),t)};close(){this.transport.socket.close()}extractSessionKeys(e,t){let n=this.exportKeyingMaterial(`EXTRACTOR-dtls_srtp`,e*2+t*2),{clientKey:r,serverKey:i,clientSalt:a,serverSalt:o}=(0,Q.decode)(n,{clientKey:Q.types.buffer(e),serverKey:Q.types.buffer(e),clientSalt:Q.types.buffer(t),serverSalt:Q.types.buffer(t)});return this.sessionType===LS.CLIENT?{localKey:r,localSalt:a,remoteKey:i,remoteSalt:o}:{localKey:i,localSalt:o,remoteKey:r,remoteSalt:a}}exportKeyingMaterial(e,t){return jS(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===LS.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},qT=sS(`werift-dtls : packages/dtls/src/client.ts : log`),JT=class extends KT{constructor(e){super(e,LS.CLIENT),this.onHandleHandshakes=this.handleHandshakes,qT(this.dtls.sessionId,`start client`)}async connect(){await new pC(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async e=>{qT(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(let t of e)switch(t.msg_type){case 3:{let e=NT.deSerialize(t.fragment);await new hC(this.transport,this.dtls).exec(e)}break;case 2:if(this.connected)return;this.flight5=new jT(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(t);break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(t);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(t);let e=[11,12,this.options.certificateRequest&&13].filter(e=>typeof e==`number`);await this.waitForReady(()=>this.dtls.checkHandshakesExist(e)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),qT(this.dtls.sessionId,`dtls connected`)}}},YT=sS(`werift-dtls : packages/dtls/flight/server/flight2.ts : log`),XT=(e,t,n,r)=>i=>{YT(`dtls version`,i.clientVersion),t.flight=2,t.recordSequenceNumber=0,t.sequenceNumber=0,i.extensions.forEach(e=>{switch(e.type){case LT.type:{let r=LT.fromData(e.data).data;YT(t.sessionId,`curves`,r),n.namedCurve=r.filter(e=>yS.includes(e))[0],YT(t.sessionId,`curve selected`,n.namedCurve)}break;case RT.type:{if(!n.signatureHashAlgorithm)throw Error(`need to set certificate`);let r=RT.fromData(e.data).data;YT(t.sessionId,`hash,signature`,r);let i=r.find(e=>e.signature===n.signatureHashAlgorithm?.signature)?.signature,a=r.find(e=>e.hash===n.signatureHashAlgorithm?.hash)?.hash;if(i==null||a==null)throw Error(`invalid signatureHash`)}break;case BC.type:{if(!t.options?.srtpProfiles||t.options.srtpProfiles.length===0)return;let n=BC.fromData(e.data);YT(t.sessionId,`srtp profiles`,n.profiles);let i=VS.findMatchingSRTPProfile(n.profiles,t.options?.srtpProfiles);if(!i)throw Error();r.srtpProfile=i,YT(t.sessionId,`srtp profile selected`,r.srtpProfile)}break;case RC.type:t.remoteExtendedMasterSecret=!0;break;case zC.type:YT(t.sessionId,`RenegotiationIndication`,e.data);break;case 43:YT(`dtls supported version`,[...e.data.subarray(1)].map(e=>e.toString(10)))}}),n.localRandom=new rC,n.remoteRandom=rC.from(i.random);let a=i.cipherSuites;YT(t.sessionId,`cipher suites`,a);let o=(()=>{switch(n.signatureHashAlgorithm?.signature){case mS.ecdsa_3:return gS.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case mS.rsa_1:return gS.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!a.includes(o))throw Error(`dtls cipher suite negotiation failed`);n.cipherSuite=o,YT(t.sessionId,`selected cipherSuite`,n.cipherSuite),n.localKeyPair=LC(n.namedCurve),t.cookie||=c(20);let s=new NT({major:254,minor:253},t.cookie),l=sC(t)([s]),u=cC(t)(l.map(e=>({type:22,fragment:e.serialize()})),++t.recordSequenceNumber).map(e=>e.serialize());for(let t of u)e.send(t)},ZT=sS(`werift-dtls : packages/dtls/flight/server/flight4.ts : log`),QT=class extends fC{constructor(e,t,n,r){super(e,t,4,6),this.cipher=n,this.srtp=r}async exec(e,t=!1){if(this.dtls.flight===4){ZT(this.dtls.sessionId,`flight4 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([e],!1,4);let n=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),t&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(e=>e);this.dtls.lastMessage=n,await this.transmit(n)}sendServerHello(){let e=[];this.srtp.srtpProfile&&e.push(BC.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&e.push({type:RC.type,data:Buffer.alloc(0)});let t=zC.createEmpty();e.push(t.extension);let n=new qC(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,e),r=this.createPacket([n]);return Buffer.concat(r.map(e=>e.serialize()))}sendCertificate(){let e=new VC([Buffer.from(this.cipher.localCert)]),t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendServerKeyExchange(){let e=this.cipher.generateKeySignature(`sha256`);if(!this.cipher.signatureHashAlgorithm)throw Error(`not exist`);let t=new XC(bS.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,e.length,e),n=this.createPacket([t]);return Buffer.concat(n.map(e=>e.serialize()))}sendCertificateRequest(){let e=new KC(SS,CS,[]);ZT(this.dtls.sessionId,`sendCertificateRequest`,e);let t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendServerHelloDone(){let e=new JC,t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}},$T=sS(`werift-dtls : packages/dtls/flight/server/flight6.ts`),eE=class extends fC{constructor(e,t,n){super(e,t,6),this.cipher=n}handleHandshake(e){this.dtls.bufferHandshakeCache([e],!1,5);let t=(()=>{switch(e.msg_type){case 11:return VC.deSerialize(e.fragment);case 15:return UC.deSerialize(e.fragment);case 16:return WC.deSerialize(e.fragment);case 20:return GC.deSerialize(e.fragment)}})();if(t){let e=tE[t.msgType];if(!e)return;e({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){$T(this.dtls.sessionId,`flight6 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let e=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=e,await this.transmit(e)}sendChangeCipherSpec(){let e=HC.createEmpty().serialize(),t=cC(this.dtls)([{type:20,fragment:e}],++this.dtls.recordSequenceNumber);return Buffer.concat(t.map(e=>e.serialize()))}sendFinished(){let e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize())),t=new GC(this.cipher.verifyData(e));this.dtls.epoch=1;let[n]=this.createPacket([t]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(n).serialize()}},tE={};tE[16]=({cipher:e,dtls:t})=>n=>{if(e.remoteKeyPair={curve:e.namedCurve,publicKey:n.publicKey},!e.remoteKeyPair.publicKey||!e.localKeyPair||!e.remoteRandom||!e.localRandom)throw Error(`not exist`);let r=ES(e.remoteKeyPair.publicKey,e.localKeyPair.privateKey,e.localKeyPair.curve);$T(t.sessionId,`extendedMasterSecret`,t.options.extendedMasterSecret,t.remoteExtendedMasterSecret);let i=Buffer.concat(t.sortedHandshakeCache.map(e=>e.serialize()));e.masterSecret=t.options.extendedMasterSecret&&t.remoteExtendedMasterSecret?AS(r,i):kS(r,e.remoteRandom.serialize(),e.localRandom.serialize()),e.cipher=FC(e.cipherSuite),e.cipher.init(e.masterSecret,e.localRandom.serialize(),e.remoteRandom.serialize()),$T(t.sessionId,`setup cipher`,e.cipher.summary)},tE[11]=({cipher:e,dtls:t})=>n=>{$T(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},tE[15]=({cipher:e,dtls:t})=>n=>{if(!e.remoteCertificate)throw Error(`client certificate missing before certificate verify`);$T(t.sessionId,`certificate_verify`,n.algorithm)},tE[20]=({dtls:e})=>t=>{$T(e.sessionId,`finished`,t)};var nE=sS(`werift-dtls : packages/dtls/src/server.ts : log`),rE=class extends KT{constructor(e){super(e,LS.SERVER),this.onHandleHandshakes=this.handleHandshakes,nE(this.dtls.sessionId,`start server`)}flight6;handleHandshakes=async e=>{nE(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(let t of e)switch(t.msg_type){case 1:{this.connected&&this.renegotiation();let e=iC.deSerialize(t.fragment);e.cookie.length===0?(nE(this.dtls.sessionId,`send flight2`),XT(this.transport,this.dtls,this.cipher,this.srtp)(e)):this.dtls.cookie&&e.cookie.equals(this.dtls.cookie)?(nE(this.dtls.sessionId,`send flight4`),await new QT(this.transport,this.dtls,this.cipher,this.srtp).exec(t,this.options.certificateRequest)):nE(`wrong state`,{dtlsCookie:this.dtls.cookie?.toString(`hex`).slice(10),helloCookie:e.cookie.toString(`hex`).slice(10)})}break;case 11:case 15:case 16:if(this.connected)return;this.flight6=new eE(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(t);break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(t);let e=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(e=>typeof e==`number`);await this.waitForReady(()=>this.dtls.checkHandshakesExist(e)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),nE(this.dtls.sessionId,`dtls connected`)}}}},iE=554869826,aE=1398035790;function oE(e){if(e.length<20||e[0]&192||e.readUInt32BE(4)!==554869826)return!1;let t=e.readUInt16BE(2);return t%4==0&&e.length===20+t}function sE(e){let t=Buffer.alloc(2);return t.writeUInt16BE(e.length,0),Buffer.concat([t,e])}function cE(e){let t=[],n=0;for(;e.length-n>=2;){let r=e.readUInt16BE(n);if(e.length-n<r+2)break;t.push(e.subarray(n+2,n+2+r)),n+=2+r}return{frames:t,rest:e.subarray(n)}}function lE(e){if(x(e)){let t=Buffer.allocUnsafe(4),n=e.split(`.`);for(let e=0;e<4;e++)t[e]=Number(n[e])&255;return t}if(!S(e))throw Error(`Invalid ip address: ${e}`);let t=e.split(`:`,8);for(let e=0;e<t.length;e++){let n;x(t[e])&&(n=lE(t[e]),t[e]=n.subarray(0,2).toString(`hex`)),n&&++e<8&&t.splice(e,0,n.subarray(2,4).toString(`hex`))}if(t[0]===``)for(;t.length<8;)t.unshift(`0`);else if(t[t.length-1]===``)for(;t.length<8;)t.push(`0`);else if(t.length<8){let e=0;for(;e<t.length&&t[e]!==``;e++);let n=[];for(let e=9-t.length;e>0;e--)n.push(`0`);t.splice(e,1,...n)}let n=Buffer.allocUnsafe(16),r=0;for(let e of t){let t=Number.parseInt(e,16)||0;n[r++]=t>>8&255,n[r++]=t&255}return n}function uE(e){if(e.length===4)return`${e[0]}.${e[1]}.${e[2]}.${e[3]}`;if(e.length!==16)throw Error(`Invalid ip address buffer length: ${e.length}`);let t=[];for(let n=0;n<16;n+=2)t.push(e.readUInt16BE(n).toString(16));let n=t.join(`:`);return n=n.replace(/(^|:)0(:0)*:0(:|$)/,`$1::$3`),n=n.replace(/:{3,4}/,`::`),n}function dE(e){return x(e)}function fE(e){let[t]=e,n=dE(t)?1:2,r=Buffer.alloc(4);return r.writeUInt8(0,0),r.writeUInt8(n,1),r.writeUInt16BE(e[1],2),Buffer.concat([r,lE(t)])}function pE(e){if(e.length<4)throw Error(`STUN error code is less than 4 bytes`);let t=e.readUInt8(2),n=e.readUInt8(3),r=e.slice(4).toString(`utf8`);return[t*100+n,r]}function mE(e){if(e.length<4)throw Error(`STUN address length is less than 4 bytes`);let t=e.readUInt8(1),n=e.readUInt16BE(2),r=e.slice(4);switch(t){case 1:if(r.length!==4)throw Error(`STUN address has invalid length for IPv4`);return[uE(r),n];case 2:if(r.length!==16)throw Error(`STUN address has invalid length for IPv6`);return[uE(r),n];default:throw Error(`STUN address has unknown protocol`)}}var hE=Buffer.alloc(6);hE.writeUInt16BE(iE>>16,0),hE.writeUInt32BE(iE,2);function gE(e,t){let n=[...hE,...t],r=e.slice(0,2);for(let t=2;t<e.length;t++){let i=e[t]^n[t-2],a=Buffer.alloc(1);a.writeUIntBE(i,0,1),r=Buffer.concat([r,a])}return r}function _E(e,t){return mE(gE(e,t))}function vE(e){let t=Buffer.alloc(4);t.writeUInt16BE(0,0),t.writeUInt8(Math.floor(e[0]/100),2),t.writeUInt8(e[0]%100,3);let n=Buffer.from(e[1],`utf8`);return Buffer.concat([t,n])}function yE(e){let t=Buffer.alloc(e.length*2);return e.forEach((e,n)=>{t.writeUInt16BE(e,n*2)}),t}function bE(e){if(e.length%2!=0)throw Error(`UNKNOWN-ATTRIBUTES must have an even length`);let t=[];for(let n=0;n<e.length;n+=2)t.push(e.readUInt16BE(n));return t}function xE(e,t){return gE(fE(e),t)}var SE=e=>{let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t},CE=e=>e.readUInt32BE(0),wE=e=>{let t=Buffer.alloc(4);return t.writeUInt16BE(e,0),t},TE=e=>e.readUInt16BE(0),EE=e=>{let t=Buffer.allocUnsafe(8);return t.writeBigUInt64BE(e,0),t},DE=e=>e.readBigUInt64BE(0),OE=e=>Buffer.from(e,`utf8`),kE=e=>e.toString(`utf8`),AE=e=>{if([...e].length>=128)throw Error(`SOFTWARE must be shorter than 128 characters`);return OE(e)},jE=e=>e,ME=e=>e,NE=[[1,`MAPPED-ADDRESS`,fE,mE],[3,`CHANGE-REQUEST`,SE,CE],[4,`SOURCE-ADDRESS`,fE,mE],[5,`CHANGED-ADDRESS`,fE,mE],[6,`USERNAME`,OE,kE],[8,`MESSAGE-INTEGRITY`,jE,ME],[9,`ERROR-CODE`,vE,pE],[10,`UNKNOWN-ATTRIBUTES`,yE,bE],[12,`CHANNEL-NUMBER`,wE,TE],[13,`LIFETIME`,SE,CE],[18,`XOR-PEER-ADDRESS`,xE,_E],[19,`DATA`,jE,ME],[20,`REALM`,OE,kE],[21,`NONCE`,jE,ME],[22,`XOR-RELAYED-ADDRESS`,xE,_E],[23,`REQUESTED-ADDRESS-FAMILY`,SE,CE],[24,`EVEN-PORT`,jE,ME],[25,`REQUESTED-TRANSPORT`,SE,CE],[28,`MESSAGE-INTEGRITY-SHA256`,jE,ME],[29,`PASSWORD-ALGORITHM`,jE,ME],[30,`USERHASH`,jE,ME],[32,`XOR-MAPPED-ADDRESS`,xE,_E],[34,`RESERVATION-TOKEN`,jE,ME],[36,`PRIORITY`,SE,CE],[37,`USE-CANDIDATE`,()=>Buffer.alloc(0),()=>null],[32770,`PASSWORD-ALGORITHMS`,jE,ME],[32771,`ALTERNATE-DOMAIN`,OE,kE],[32802,`SOFTWARE`,AE,kE],[32803,`ALTERNATE-SERVER`,fE,mE],[32808,`FINGERPRINT`,SE,CE],[32809,`ICE-CONTROLLED`,EE,DE],[32810,`ICE-CONTROLLING`,EE,DE],[32811,`RESPONSE-ORIGIN`,fE,mE],[32812,`OTHER-ADDRESS`,fE,mE]],PE=class{constructor(e=[]){this.attributes=e}getAttributes(){return this.attributes}setAttribute(e,t){let n=this.attributes.find(t=>t[0]===e);return n?n[1]=t:this.attributes.push([e,t]),this}getAttributeValue(e){return this.attributes.find(t=>t[0]===e)?.[1]}get attributesKeys(){return this.attributes.map(e=>e[0])}clear(){this.attributes=[]}},FE=NE.reduce((e,t)=>(e[t[0]]=t,e),{}),IE=NE.reduce((e,t)=>(e[t[1]]=t,e),{});function LE(e,t){if(!oE(e))return;let n=e.readUInt16BE(0),r=Buffer.from(e.slice(8,20)),i=new PE,a=[],o=!1;for(let n=20;n<e.length;){if(n+4>e.length)return;let s=e.readUInt16BE(n),c=e.readUInt16BE(n+2),l=n+4,u=l+c;if(u>e.length)return;let d=e.slice(l,u),f=UE(c);if(u+f>e.length)return;let p=FE[s];if(p){let[,a,,s]=p,c;try{c=s.name===_E.name?s(d,r):s(d)}catch{return}if(i.setAttribute(a,c),a===`FINGERPRINT`){let t=VE(e.slice(0,n));if(i.getAttributeValue(`FINGERPRINT`)!==t)return}else if(a===`MESSAGE-INTEGRITY`&&t){let r=HE(e.slice(0,n),t),a=i.getAttributeValue(`MESSAGE-INTEGRITY`);if(!r.equals(a))return;o=!0}}else a.push({type:s,length:c,value:Buffer.from(d)});n=u+f}if(!t||o)return new RE(n&16111,n&272,r,i.getAttributes(),a)}var RE=class extends PE{constructor(e,t,n=c(12),r=[],i=[]){super(r),this.messageMethod=e,this.messageClass=t,this.transactionId=n,this.rawAttributes=i}toJSON(){return this.json}get json(){return{messageMethod:this.messageMethod,messageClass:this.messageClass,attributes:this.attributes,rawAttributes:this.rawAttributes.map(e=>({type:e.type,length:e.value.length}))}}get transactionIdHex(){return this.transactionId.toString(`hex`)}appendRawAttribute(e,t){return this.rawAttributes.push({type:e,value:Buffer.from(t)}),this}get unknownAttributeTypes(){return this.rawAttributes.map(e=>e.type)}get bytes(){let e=Buffer.concat(this.serializedAttributes.map(e=>zE(e.type,e.value))),t=Buffer.alloc(8);return t.writeUInt16BE(this.messageMethod|this.messageClass,0),t.writeUInt16BE(e.length,2),t.writeUInt32BE(iE,4),Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){return this.setAttribute(`MESSAGE-INTEGRITY`,this.messageIntegrity(e)),this}messageIntegrity(e){let t=BE(this.bytes,this.bytes.length-20+24);return Buffer.from(o(`sha1`,e).update(t).digest(`hex`),`hex`)}addFingerprint(){return this.setAttribute(`FINGERPRINT`,VE(this.bytes)),this}get serializedAttributes(){let e=[];for(let t of this.attributesKeys){let n=this.getAttributeValue(t),[r,,i]=IE[t],a=i.name===xE.name?i(n,this.transactionId):i(n);e.push({type:r,value:a})}return e.push(...this.rawAttributes.map(e=>({type:e.type,value:Buffer.from(e.value)}))),e}};function zE(e,t){let n=t.length,r=UE(n),i=Buffer.alloc(4);return i.writeUInt16BE(e,0),i.writeUInt16BE(n,2),Buffer.concat([i,t,Buffer.alloc(r)])}var BE=(e,t)=>{let n=Buffer.alloc(e.length);return e.copy(n,0,0,2),n.writeUInt16BE(t,2),e.copy(n,4,4),n};function VE(e){return(Jx(BE(e,e.length-20+8))^aE)>>>0}function HE(e,t){let n=BE(e,e.length-20+24);return Buffer.from(o(`sha1`,t).update(n).digest(`hex`),`hex`)}function UE(e){let t=e%4;return t===0?0:4-t}var WE=class extends Error{response;addr},GE=class extends WE{constructor(e,t){super(),this.response=e,this.addr=t}get str(){let e=`STUN transaction failed`,t=this.response.getAttributeValue(`ERROR-CODE`);if(t){let[n,r]=t;e+=` (${n} - ${r})`}return e}},KE=class extends WE{get str(){return`STUN transaction timed out`}},qE=sS(`werift-ice:packages/ice/src/stun/transaction.ts`);async function JE(e,t=0){return b(e[0])?e:[(await D.lookup(e[0],{family:t})).address,e[1]]}function YE(e,t){return typeof e==`object`&&e?e:{retransmissions:typeof e==`number`?e:void 0,onRequestSent:t}}function XE(e,t){return e[0]===t[0]&&e[1]===t[1]}var ZE=class{constructor(e,t,n,r,i){this.request=e,this.addr=t,this.protocol=n;let a=YE(r,i);this.triesMax=1+(a.retransmissions??6),this.timeoutDelay=a.responseTimeout??50,this.onRequestSent=a.onRequestSent,this.signal=a.signal,this.expectedAddr=t,this.integrityKey=a.integrityKey}timeoutDelay;ended=!1;tries=0;triesMax;onResponse=new $;onRequestSent;signal;expectedAddr;integrityKey;waitTimer;waitResolve;onAbort;responseReceived=(e,t)=>{if(!(this.ended||this.onResponse.length===0)){if(!XE(this.expectedAddr,t)){qE(`ignore STUN response from unexpected address`,t,`expected`,this.expectedAddr);return}if(this.integrityKey&&!(e.attributesKeys.includes(`MESSAGE-INTEGRITY`)||e.attributesKeys.includes(`MESSAGE-INTEGRITY-SHA256`))){qE(`ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)`);return}e.messageClass===256?(this.onResponse.execute(e,t),this.onResponse.complete()):this.onResponse.error(new GE(e,t))}};run=async()=>{try{if(this.signal?.aborted)throw new KE;return this.attachAbortListener(),this.retry().catch(e=>{qE(`retry failed`,e)}),await this.onResponse.asPromise()}catch(e){throw e}finally{this.cancel()}};attachAbortListener(){this.signal&&(this.onAbort=()=>{this.failWithTimeout()},this.signal.addEventListener(`abort`,this.onAbort,{once:!0}))}failWithTimeout(){this.ended||(this.ended=!0,this.clearWait(),this.onResponse.length>0&&this.onResponse.error(new KE))}clearWait(){this.waitTimer!==void 0&&(clearTimeout(this.waitTimer),this.waitTimer=void 0);let e=this.waitResolve;this.waitResolve=void 0,e?.()}wait(e){return new Promise(t=>{if(this.ended||this.signal?.aborted){t();return}this.waitResolve=t,this.waitTimer=setTimeout(()=>{this.waitTimer=void 0,this.waitResolve=void 0,t()},e)})}retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.onRequestSent?.(this.tries),this.protocol.sendStun(this.request,this.addr).catch(e=>{qE(`send stun failed`,e)}),await this.wait(this.timeoutDelay),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&!this.ended&&(qE(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.failWithTimeout())};cancel(){this.ended=!0,this.clearWait(),this.signal&&this.onAbort&&(this.signal.removeEventListener(`abort`,this.onAbort),this.onAbort=void 0)}};function QE(e,t,n){let r=YE(t,n);return e&&!r.integrityKey&&(r.integrityKey=e),r}var $E=sS(`werift-ice:packages/ice/src/stun/tcpProtocol.ts`);function eD(e){return`${e[0]}:${e[1]}`}function tD(e){if(e.remoteAddress&&e.remotePort)return[e.remoteAddress,e.remotePort]}async function nD(e,t,n){return await new Promise((r,i)=>{let a=t=>{e.off(`listening`,o),i(t)},o=()=>{e.off(`error`,a),r()};e.once(`error`,a),e.once(`listening`,o),e.listen({host:t,port:n??0,exclusive:!0})})}var rD=class e{static type=`tcp`;type=e.type;transactions={};localCandidate;sentMessage;localIp;onRequestReceived=new $;onDataReceived=new $;sockets=new Map;rememberSocket(e){let t=e.remoteAddr;t&&this.sockets.set(eD(t),e)}forgetSocket(e){e&&this.sockets.delete(eD(e))}registerSocket(e,t){let n={socket:e,buffer:Buffer.alloc(0),remoteAddr:t};return t&&this.rememberSocket(n),e.on(`data`,t=>{n.buffer=Buffer.concat([n.buffer,t]);let{frames:r,rest:i}=cE(n.buffer);n.buffer=i;let a=n.remoteAddr??tD(e);if(!n.remoteAddr&&a&&(n.remoteAddr=a,this.rememberSocket(n)),a)for(let e of r)e.length!==0&&this.handleFrame(e,a)}),e.on(`close`,()=>{this.forgetSocket(n.remoteAddr)}),e.on(`error`,e=>{$E(`tcp socket error`,e)}),n}handleFrame(e,t){try{let n=LE(e);if(!n){this.onDataReceived.execute(e);return}if((n.messageClass===256||n.messageClass===272)&&this.transactions[n.transactionIdHex]){let r=this.transactions[n.transactionIdHex],i=r.integrityKey?LE(e,r.integrityKey):n;if(!i){$E(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){$E(`tcp frame parse error`,e)}}async sendFrame(e,t){let n=await this.getSocket(t);await new Promise((t,r)=>{n.socket.write(sE(e),e=>{if(e){r(e);return}t()})})}async sendStun(e,t){await this.sendFrame(e.bytes,t)}async sendData(e,t){await this.sendFrame(e,t)}async request(e,t,n,r,i){if(this.transactions[e.transactionIdHex])throw Error(`already requested`);n&&(e.addMessageIntegrity(n),e.addFingerprint());let a=await JE(t),o=QE(n,r,i),s=new ZE(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}finally{delete this.transactions[e.transactionIdHex]}}async pruneForSelection(e){for(let[t,n]of this.sockets.entries())e&&t===eD(e)||(n.socket.destroy(),this.sockets.delete(t))}get activeSocketCount(){return this.sockets.size}get address(){return{}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()}),await this.pruneForSelection(),this.onRequestReceived.complete(),this.onDataReceived.complete()}},iD=class extends rD{pendingSockets=new Map;async connectionMade(e){this.localIp=e}async getSocket(e){let t=eD(e),n=this.sockets.get(t);if(n)return n;let r=this.pendingSockets.get(t);if(r)return await r;let i=new Promise((t,n)=>{let r=v({host:e[0],port:e[1],localAddress:this.localIp}),i=this.registerSocket(r,e),a=e=>{r.off(`connect`,o),n(e)},o=()=>{r.off(`error`,a),t(i)};r.once(`error`,a),r.once(`connect`,o)});this.pendingSockets.set(t,i);try{return await i}finally{this.pendingSockets.delete(t)}}},aD=class extends rD{server=y(e=>{this.registerSocket(e,tD(e))});async connectionMade(e,t){if(this.localIp=e,t){let n;for(let r=t[0];r<=t[1];r++)try{await nD(this.server,e,r);return}catch(e){n=e}throw n??Error(`tcp port not found`)}await nD(this.server,e)}async getSocket(e){let t=this.sockets.get(eD(e));if(!t)throw Error(`tcp passive connection not established`);return t}get listeningPort(){let e=this.server.address();if(!e||typeof e==`string`)throw Error(`tcp passive protocol is not listening`);return e.port}async close(){await super.close(),await new Promise(e=>{this.server.close(()=>e())})}},oD=sS(`werift-ice : packages/ice/src/stun/protocol.ts`),sD=class e{static type=`stun`;type=e.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new $;onDataReceived=new $;constructor(){}connectionMade=async(e,t,n)=>{this.transport=e?await uS.init(`udp4`,{portRange:t,interfaceAddresses:n}):await uS.init(`udp6`,{portRange:t,interfaceAddresses:n}),this.transport.onData=(e,t)=>{this.datagramReceived(e,t)}};datagramReceived(e,t){try{let n=LE(e);if(!n){this.localCandidate&&this.onDataReceived.execute(e);return}if((n.messageClass===256||n.messageClass===272)&&this.transactionsKeys.includes(n.transactionIdHex)){let r=this.transactions[n.transactionIdHex],i=r.integrityKey?LE(e,r.integrityKey):n;if(!i){oD(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){oD(`datagramReceived error`,e)}}getExtraInfo(){let{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed)return;let n=e.bytes;await this.transport.send(n,t).catch(()=>{oD(`sendStun failed`,t,e)})}async sendData(e,t){this.transport.closed||await this.transport.send(e,t)}async request(e,t,n,r,i){if(this.transactionsKeys.includes(e.transactionIdHex))throw Error(`already request ed`);n&&(e.addMessageIntegrity(n),e.addFingerprint());let a=await JE(t,this.transport.socketType===`udp6`?6:4),o=QE(n,r,i),s=new ZE(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}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()}};function cD(e,t,n){return a(`md5`).update(Buffer.from([e,t,n].join(`:`))).digest()}function lD(e){return c(e).toString(`hex`).substring(0,e)}function uD(){return c(12)}var dD=class{queue=[];wait=new $;put(e){this.queue.push(e),this.queue.length===1&&this.wait.execute(e)}get(){return this.queue.shift()||new Promise(e=>{this.wait.subscribe(t=>{this.queue.shift(),e(t)})})}},fD=e=>{let t,n,r=new Promise((e,r)=>{t=e,n=r});r.then(()=>{i.execute(void 0),i.complete()}).catch(e=>{i.execute(e??Error()),i.complete()});let i=new $;return e(t,n,i).catch(()=>{}),{awaitable:r,resolve:t,reject:n}};function pD(e){return e.length>=4&&(e[0]&192)==64}function mD(e,t){let n=Buffer.alloc(4);return n.writeUInt16BE(e,0),n.writeUInt16BE(t.length,2),Buffer.concat([n,t])}function hD(e){if(!pD(e)||e.length<4)return;let t=e.readUInt16BE(0),n=e.readUInt16BE(2);if(!(e.length<4+n))return{channelNumber:t,data:e.subarray(4,4+n)}}function gD(e){let t=UE(e.length);return t>0?Buffer.concat([e,Buffer.alloc(t)]):e}function _D(e){let t=[],n=0,r=!1;for(;e.length-n>=4;){let i;if(pD(e.subarray(n))){let t=e.readUInt16BE(n+2);i=4+t+UE(t)}else if(e[n]&192){r=!0;break}else{if(e.length-n<20)break;let t=e.readUInt16BE(n+2);i=20+t+UE(t)}if(e.length-n<i)break;t.push(e.subarray(n,n+i)),n+=i}return{frames:t,malformed:r,rest:e.subarray(n)}}var vD=sS(`werift-ice:packages/ice/src/turn/protocol.ts`),yD=500,bD=600,xD=285212672;function SD(e){return e.type===`tcp`||e.type===`tls`}function CD(e){return e[0]}function wD(e){return JSON.stringify(e)}var TD=class e{constructor(e){this.turn=e,e.onData.subscribe((e,t)=>{this.handleStunMessage(e,t)}).disposer(this.disposer)}static type=`turn`;type=e.type;localCandidate;disposer=new cS;onRequestReceived=new $;onDataReceived=new $;handleStunMessage=(e,t)=>{try{let n=LE(e);if(!n){this.onDataReceived.execute(e);return}if(n.messageClass===256||n.messageClass===272){let r=this.turn.transactions[n.transactionIdHex];if(r){let i=r.integrityKey?LE(e,r.integrityKey):n;if(!i){vD(`STUN over TURN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){vD(`datagramReceived error`,e)}};async request(e,t,n,r,i){if(this.turn.transactions[e.transactionIdHex])throw Error(`exist`);n&&(e.addMessageIntegrity(n),e.addFingerprint());let a=await JE(t),o=QE(n,r,i),s=new ZE(e,a,this,o);this.turn.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){return this.disposer.dispose(),this.turn.close()}},ED=class e{constructor(e,t,n,r,i,a={}){this.server=e,this.username=t,this.password=n,this.lifetime=r,this.transport=i,this.options=a,this.channelRefreshTime=this.options.channelRefreshTime??yD}static type=`turn`;type=e.type;onData=new $;onRequestReceived=new $;onDataReceived=new $;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBindQueue=Promise.resolve();channelBindingByAddr=new Map;tcpBuffer=Buffer.alloc(0);permissionByAddr={};permissionQueue=Promise.resolve();creatingPermissionByAddr=new Map;async connectionMade(){this.transport.onData=(e,t)=>{this.dataReceived(e,t)};let e=new RE(3,0);e.setAttribute(`LIFETIME`,this.lifetime).setAttribute(`REQUESTED-TRANSPORT`,xD);let[t]=await this.requestWithRetry(e,this.server).catch(e=>{throw vD(`connect error`,e),e});this.relayedAddress=t.getAttributeValue(`XOR-RELAYED-ADDRESS`),this.mappedAddress=t.getAttributeValue(`XOR-MAPPED-ADDRESS`);let n=t.getAttributeValue(`LIFETIME`);vD(`connect`,this.relayedAddress,this.mappedAddress,{exp:n}),this.refresh(n)}handleChannelData(e){let t=hD(e),n=t&&this.addrByChannel[t.channelNumber];n&&t&&this.onData.execute(t.data,n)}handleSTUNMessage(e,t){try{let n=LE(e);if(!n)throw Error(`not stun message`);if(n.messageClass===256||n.messageClass===272){let r=this.transactions[n.transactionIdHex];if(r){let i=r.integrityKey?LE(e,r.integrityKey):n;if(!i){vD(`TURN STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}}else n.messageClass===0&&this.onData.execute(e,t);if(n.getAttributeValue(`DATA`)){let e=n.getAttributeValue(`DATA`),r=n.getAttributeValue(`XOR-PEER-ADDRESS`)??t;this.onData.execute(e,r)}}catch{vD(`parse error`,e.toString())}}dataReceived(e,t){let n=(e,t)=>{e.length>=4&&pD(e)?this.handleChannelData(e):this.handleSTUNMessage(e,t)};if(SD(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);let{frames:r,rest:i}=_D(this.tcpBuffer);this.tcpBuffer=i;for(let e of r)n(e,t)}else n(e,t)}async send(e,t){this.transport.closed||await this.transport.send(SD(this.transport)?gD(e):e,t)}async createPermission(e){let t=new RE(8,0);t.setAttribute(`XOR-PEER-ADDRESS`,e).setAttribute(`USERNAME`,this.username).setAttribute(`REALM`,this.realm).setAttribute(`NONCE`,this.nonce),await this.requestWithRetry(t,this.server)}refresh=e=>{this.refreshHandle=fD(async(t,n,r)=>{let i=!0;for(r.once(()=>{i=!1});i;){let t=5/6*e*1e3;vD(`refresh delay`,t,{exp:e}),await E(t);let n=new RE(4,0);n.setAttribute(`LIFETIME`,e);try{let[t]=await this.requestWithRetry(n,this.server);e=t.getAttributeValue(`LIFETIME`),vD(`refresh`,{exp:e})}catch(e){vD(`refresh error`,e)}}})};async request(e,t,n,r,i){if(this.transactions[e.transactionIdHex])throw Error(`exist`);this.integrityKey&&e.setAttribute(`USERNAME`,this.username).setAttribute(`REALM`,this.realm).setAttribute(`NONCE`,this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let a=await JE(t),o=QE(this.integrityKey,r,i),s=new ZE(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,t){let n,r;try{[n,r]=await this.request(e,t)}catch(t){if(t instanceof GE==0)throw vD(`requestWithRetry error`,t),t;this.server=t.addr;let[i]=t.response.getAttributeValue(`ERROR-CODE`),a=t.response.getAttributeValue(`NONCE`),o=t.response.getAttributeValue(`REALM`);if((i===401&&o||i===438&&this.realm)&&a)vD(`retry with nonce`,i),this.nonce=a,i===401&&(this.realm=o),this.integrityKey=kD(this.username,this.realm,this.password),e.transactionId=uD(),[n,r]=await this.request(e,this.server);else throw t}return[n,r]}async sendData(e,t){let n;try{n=await this.getChannel(t)}catch(e){vD(`channelBind error; falling back to Send Indication`,e)}if(!n){await this.getPermission(t);let n=new RE(6,16).setAttribute(`DATA`,e).setAttribute(`XOR-PEER-ADDRESS`,t);await this.sendStun(n,this.server);return}await this.send(mD(n.number,e),this.server)}async getPermission(e){let t=CD(e);if(this.permissionByAddr[t])return;let n=this.creatingPermissionByAddr.get(t);if(n)return n;let r=this.permissionQueue.then(async()=>{this.permissionByAddr[t]||(await this.createPermission(e),this.permissionByAddr[t]=!0)});this.permissionQueue=r.then(()=>void 0,()=>void 0),this.creatingPermissionByAddr.set(t,r);try{await r}catch(e){throw vD(`createPermission error`,e),e}finally{this.creatingPermissionByAddr.get(t)===r&&this.creatingPermissionByAddr.delete(t)}}async getChannel(e){let t=wD(e),n=this.channelBindingByAddr.get(t);if(n)return n;let r=this.channelByAddr[t],i=rS(Date.now()/1e3);if(r&&r.refreshAt>i)return r;let a=this.channelBindQueue.then(()=>this.ensureChannel(e));this.channelBindQueue=a.then(()=>void 0,()=>void 0),this.channelBindingByAddr.set(t,a);try{return await a}catch(e){throw vD(`channelBind error`,e),e}finally{this.channelBindingByAddr.get(t)===a&&this.channelBindingByAddr.delete(t)}}async ensureChannel(e){let t=wD(e),n=rS(Date.now()/1e3),r=this.channelByAddr[t];if(r&&r.refreshAt>n)return r;let i=!r;r||(r={number:this.channelNumber++,address:e,refreshAt:0},this.channelByAddr[t]=r,this.addrByChannel[r.number]=e);try{return await this.channelBind(r.number,e),r.refreshAt=rS(Date.now()/1e3)+this.channelRefreshTime,vD(i?`channelBind`:`channelBind refresh`,r),r}catch(e){throw i&&(delete this.channelByAddr[t],delete this.addrByChannel[r.number]),e}}async channelBind(e,t){let n=new RE(9,0);n.setAttribute(`CHANNEL-NUMBER`,e).setAttribute(`XOR-PEER-ADDRESS`,t);let[r]=await this.requestWithRetry(n,this.server);if(r.messageMethod!==9)throw Error(`should be CHANNEL_BIND`)}async sendStun(e,t){await this.send(e.bytes,t)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};async function DD({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){r??=bD,c??=o?`tls`:`udp`;let l=c===`udp`?await uS.init(`udp4`,{portRange:i,interfaceAddresses:a}):c===`tcp`?await dS.init(e):await fS.init(e,s),u=new ED(e,t,n,r,l);return await u.connectionMade(),u}async function OD({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){return new TD(await DD({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}))}function kD(e,t,n){return cD(e,t,n)}var AD=class e{constructor(e,t,n,r,i,a,o,s,c,l,u,d){this.foundation=e,this.component=t,this.transport=n,this.priority=r,this.host=i,this.port=a,this.type=o,this.relatedAddress=s,this.relatedPort=c,this.tcptype=l,this.generation=u,this.ufrag=d}id=l().toString();refreshId(){this.id=l().toString()}static fromSdp(t){let n=t.split(` `);if(n.length<8)throw Error(`SDP does not have enough properties`);let r={foundation:n[0],component:Number(n[1]),transport:n[2],priority:Number(n[3]),host:n[4],port:Number(n[5]),type:n[7]};for(let e=8,t=n.length-1;e<t;e+=2)n[e]===`raddr`?r.related_address=n[e+1]:n[e]===`rport`?r.related_port=Number(n[e+1]):n[e]===`tcptype`?r.tcptype=n[e+1]:n[e]===`generation`?r.generation=Number(n[e+1]):n[e]===`ufrag`&&(r.ufrag=n[e+1]);let{foundation:i,component:a,transport:o,priority:s,host:c,port:l,type:u}=r;return new e(i,a,o,s,c,l,u,r.related_address,r.related_port,r.tcptype,r.generation,r.ufrag)}canPairWith(e){let t=w(this.host),n=w(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&LD(this,e)&&t===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}},jD={host:126,prflx:110,srflx:100,relay:0},MD={host:105,prflx:90,srflx:80,relay:0},ND={active:6,passive:4,so:2},PD={active:4,passive:2,so:6};function FD(e){return e?.toLowerCase()??`udp`}function ID(e){switch(e){case`active`:case`passive`:case`so`:return e;default:return}}function LD(e,t){if(FD(e.transport)!==`tcp`)return!0;let n=ID(e.tcptype),r=ID(t.tcptype);return!n||!r?!1:n===`active`&&r===`passive`||n===`passive`&&r===`active`||n===`so`&&r===`so`}function RD({candidateType:e,transport:t=`udp`,tcptype:n,otherPreference:r=8191}){if(FD(t)!==`tcp`)return r;let i=ID(n)??`active`;return 8192*(e===`srflx`||e===`prflx`?PD[i]:ND[i])+r}function zD(e,t=`udp`){return(FD(t)===`tcp`?MD:jD)[e]??0}function BD(e,t,n){let r=`${e}|${t}|${n}`;return a(`md5`).update(r,`ascii`).digest(`hex`).slice(7)}function VD(e,t=65535){let n=typeof t==`number`?`udp`:FD(t.transport),r=typeof t==`number`?t:t.localPreference??RD({candidateType:e,transport:n,tcptype:t.tcptype,otherPreference:t.otherPreference});return(1<<24)*zD(e,n)+256*r+255}function HD(e){switch(e){case`passive`:return`active`;case`active`:return`passive`;default:return`so`}}var UD=class{cache=new Map;mdnsInstance=(0,Dx.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(e){return new Promise((t,n)=>{let r=()=>{this.mdnsInstance.removeListener(`response`,a),clearTimeout(i)},i=setTimeout(()=>{r(),n(Error(`No mDNS response`))},1e4),a=n=>{let i=n.answers?.[0];i?.type===`A`&&i.name===e&&(r(),t(i.data))};this.mdnsInstance.on(`response`,a),this.mdnsInstance.query(e,`A`)})}close(){this.mdnsInstance.destroy()}},WD=sS(`werift-ice : packages/ice/src/ice.ts : log`),GD=class{constructor(e,t,n){this.protocol=e,this.remoteCandidate=t,this.iceControlling=n}id=l().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;requestsReceived=0;requestsSent=0;responsesReceived=0;responsesSent=0;retransmissionsReceived=0;retransmissionsSent=0;consentRequestsSent=0;requestTransactionIds=new Set;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(e){this._state=e}get localCandidate(){if(!this.protocol.localCandidate)throw 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 ZD(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}noteIncomingRequest(e){return this.requestTransactionIds.has(e)?(this.retransmissionsReceived++,!0):(this.requestTransactionIds.add(e),!1)}},KD=1e3;function qD(e){return e===void 0||!Number.isFinite(e)||e<=0?KD:Math.max(500,Math.round(e*1e3*2+200))}var JD={iceLite:!1,useTcp:!1,useIpv4:!0,useIpv6:!0};function YD(e){if(![`host`,`relay`,`srflx`].includes(e.type))throw Error(`Unexpected candidate type "${e.type}"`);return e}function XD(e,t){return e.sort((e,n)=>ZD(e.localCandidate,e.remoteCandidate,t)-ZD(n.localCandidate,n.remoteCandidate,t)).reverse()}function ZD(e,t,n){let r=n&&e.priority||t.priority,i=n&&t.priority||e.priority;return 1*Math.min(r,i)+2*Math.max(r,i)+ +(r>i)}async function QD(e,t){let n=new RE(1,0);try{let[r]=await e.request(n,t),i=e.localCandidate;if(!i)throw Error(`not exist`);return new AD(BD(`srflx`,i.transport,i.host),i.component,i.transport,VD(`srflx`,{transport:i.transport,tcptype:i.tcptype}),r.getAttributeValue(`XOR-MAPPED-ADDRESS`)[0],r.getAttributeValue(`XOR-MAPPED-ADDRESS`)[1],`srflx`,i.host,i.port,i.tcptype)}catch(e){WD(`error serverReflexiveCandidate`,e)}}function $D(e){return e&&Number.isNaN(e[1])?[e[0],443]:e}function eO(e,t,n={},r){let i=[`ipsec`,`tun`,`utun`,`tap`],a=[`vmnet`,`veth`],{useLinkLocalAddress:o}=n,s=Object.keys(e).map(n=>{for(let e of[...i,...a])if(n.startsWith(e))return{nic:n,addresses:[]};return{nic:n,addresses:(e[n]??[]).filter(e=>oS(e.family)===t&&!e.internal&&(o?!0:!r(e))).map(e=>e.address)}}).filter(e=>!!e);return s.sort((e,t)=>e.nic.localeCompare(t.nic)),Object.values(s).flatMap(e=>e.addresses)}var tO=sS(`werift-ice : packages/ice/src/utils.ts`);function nO(e){return oS(e.family)===4&&e.address?.startsWith(`169.254.`)||oS(e.family)===6&&e.address?.startsWith(`fe80::`)}function rO(e,{useLinkLocalAddress:t}={}){let n=m.networkInterfaces();return tO(n),eO(n,e,{useLinkLocalAddress:t},nO)}function iO(e,t,n={}){let r=[];return e&&r.push(...rO(4,n)),t&&r.push(...rO(6,n)),r}var aO=sS(`werift-ice : packages/ice/src/ice.ts : log`),oO=class{constructor(e,t){this._iceControlling=e,this.options={...JD,...t},this.iceLite&&(this._iceControlling=!1);let{stunServer:n,turnServer:r}=this.options;this.stunServer=$D(n)??[`stun.l.google.com`,19302],this.turnServer=$D(r),this.restart(),aO(`new Connection`,this.options)}localUsername=lD(4);localPassword=lD(22);remoteIsLite=!1;remotePassword=``;remoteUsername=``;checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=c(8).readBigUInt64BE(0);state=`new`;lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new dD;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;consentFresh=!1;consentSessionId=0;consentExpiryTimer;consentRequestAbort;onData=new $;stateChanged=new $;onIceCandidate=new $;get iceControlling(){return this._iceControlling}set iceControlling(e){this.iceLite&&(e=!1),!this.nominated&&this.applyIceControlling(e)}get iceLite(){return this.options.iceLite}async restart(){this.generation++,this.localUsername=lD(4),this.localPassword=lD(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 dD,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let e of this.protocols)e.localCandidate&&(e.localCandidate.refreshId(),e.localCandidate.generation=this.generation,e.localCandidate.ufrag=this.localUsername);this.stopConsentLifecycle()}resetNominatedPair(){aO(`resetNominatedPair`),this.nominated=void 0,this.nominating=!1,this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:n}){aO(`setRemoteParams`,{iceLite:e,usernameFragment:t,password:n}),this.remoteIsLite=e,this.remoteUsername=t,this.remotePassword=n}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;for(let e of this.protocols)e.localCandidate&&(e.localCandidate.generation=this.generation,e.localCandidate.ufrag=this.localUsername,this.appendLocalCandidate(e.localCandidate));let e=iO(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:t}=this.options;if(t){let n=e.filter(e=>Object.values(t).includes(e));n.length&&(e=n)}this.options.additionalHostAddresses&&(e=Array.from(new Set([...this.options.additionalHostAddresses,...e])));let n=this.getCandidatePromises(e,5);await Promise.allSettled(n),this.localCandidatesEnd=!0}this.setState(`completed`)}appendLocalCandidate(e){this.localCandidates.push(e),this.onIceCandidate.execute(e)}ensureProtocol(e){e.onRequestReceived.subscribe((t,n,r)=>{if(t.messageMethod!==1){this.respondError(t,n,e,[400,`Bad Request`]);return}let{remoteUsername:i}=cO(t.getAttributeValue(`USERNAME`)),a=this.userHistory[i]??this.localPassword,{iceControlling:o}=this;if(o&&t.attributesKeys.includes(`ICE-CONTROLLING`)){if(this.tieBreaker>=t.getAttributeValue(`ICE-CONTROLLING`)){this.respondError(t,n,e,[487,`Role Conflict`]);return}this.switchRole(!1)}else if(!o&&t.attributesKeys.includes(`ICE-CONTROLLED`)){if(this.iceLite||this.tieBreaker<t.getAttributeValue(`ICE-CONTROLLED`)){this.respondError(t,n,e,[487,`Role Conflict`]);return}this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(t,n,e))return;let s=new RE(1,256,t.transactionId);s.setAttribute(`XOR-MAPPED-ADDRESS`,n).addMessageIntegrity(Buffer.from(a,`utf8`)).addFingerprint(),e.sendStun(s,n).catch(e=>{aO(`sendStun error`,e)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([t,n,e]):this.checkIncoming(t,n,e)}),e.onDataReceived.subscribe(t=>{try{let n=this.nominated;n&&n.protocol===e&&(n.packetsReceived++,n.bytesReceived+=t.length),this.onData.execute(t)}catch(e){aO(`dataReceived`,e)}})}getCandidatePromises(e,t=5){let n=[],{stunServer:r,turnServer:i}=this,{turnUsername:a,turnPassword:o}=this.options,s=this.iceLite,c=!s&&this.options.forceTurn&&i&&a&&o;e=e.filter(e=>!this.protocols.find(t=>t.localIp===e));let l=c?[]:e.map(async e=>{let t=new sD;this.ensureProtocol(t);try{await t.connectionMade(w(e),this.options.portRange,this.options.interfaceAddresses),t.localIp=e,this.protocols.push(t),aO(`protocol`,t.localIp);let n=[e,t.getExtraInfo()[1]];return t.localCandidate=new AD(BD(`host`,`udp`,n[0]),1,`udp`,VD(`host`,{transport:`udp`}),n[0],n[1],`host`,void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(t),this.appendLocalCandidate(t.localCandidate),t}catch(e){aO(`error protocol STUN`,e)}});if(c||n.push(...l.map(e=>e.then(e=>e?.localCandidate))),!c&&this.options.useTcp){let t=e.map(async e=>{let t=new aD;if(this.ensureProtocol(t),await t.connectionMade(e,this.options.portRange),t.localIp=e,t.localCandidate=new AD(BD(`host`,`tcp`,e),1,`tcp`,VD(`host`,{transport:`tcp`,tcptype:`passive`}),e,t.listeningPort,`host`,void 0,void 0,`passive`,this.generation,this.localUsername),this.protocols.push(t),this.appendLocalCandidate(t.localCandidate),!s){let t=new iD;this.ensureProtocol(t),await t.connectionMade(e),t.localIp=e,t.localCandidate=new AD(BD(`host`,`tcp`,e),1,`tcp`,VD(`host`,{transport:`tcp`,tcptype:`active`}),e,9,`host`,void 0,void 0,`active`,this.generation,this.localUsername),this.protocols.push(t),this.pairLocalProtocol(t),this.appendLocalCandidate(t.localCandidate)}});n.push(...t)}if(!s&&!c&&r){let e=l.map(async e=>{let n=await e;if(n)return new Promise(async(e,i)=>{let a=setTimeout(i,t*1e3);if(n.localCandidate?.host&&w(n.localCandidate?.host)){let t=await QD(n,r).catch(e=>{aO(`error`,e)});t&&this.appendLocalCandidate(t),clearTimeout(a),e(t)}else clearTimeout(a),e()}).catch(e=>{aO(`query STUN server`,e)})});n.push(...e)}if(!s&&i&&a&&o){let e=(async()=>{let e=this.options.turnTransport??`udp`,t=await OD({address:i,username:a,password:o},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:e,tlsOptions:this.options.turnTlsOptions}).catch(async t=>{if(e===`udp`)return await OD({address:i,username:a,password:o},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:`tcp`});throw t});this.ensureProtocol(t),this.protocols.push(t);let n=t.turn.relayedAddress,r=t.turn.mappedAddress;return aO(`turn candidateAddress`,n),t.localCandidate=new AD(BD(`relay`,`udp`,n[0]),1,`udp`,VD(`relay`),n[0],n[1],`relay`,r[0],r[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(t.localCandidate),t.localCandidate})().catch(e=>{aO(`query TURN server`,e)});n.push(e)}return n}async connect(){if(aO(`start connect ice`),!this.localCandidatesEnd&&!this.localCandidatesStart)throw Error(`Local candidates gathering was not performed`);if(!this.remoteUsername||!this.remotePassword)throw Error(`Remote username or password is missing`);for(let e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList(),this.iceLite||this.unfreezeInitial(),aO(`earlyChecks`,this.localPassword,this.earlyChecks.length);for(let e of this.earlyChecks)this.checkIncoming(...e);if(this.earlyChecks=[],this.earlyChecksDone=!0,this.iceLite){if(!this.nominated){let e=2;for(;!this.checkListDone&&this.state!==`closed`&&(e=await this.checkListState.get(),aO(`checkListState`,e),e!==1););if(e!==1&&!this.nominated)throw Error(`ICE negotiation failed`)}this.setState(`connected`);return}for(;this.state!==`closed`&&this.schedulingChecks();)await O.setTimeout(20);let e=2;for(;this.checkList.length>0&&e===2;)e=await this.checkListState.get(),aO(`checkListState`,e);for(let e of this.checkList)e.handle?.resolve?.();if(e!==1)throw Error(`ICE negotiation failed`);this.queryConsent(),this.setState(`connected`)}unfreezeInitial(){let[e]=this.checkList;if(!e)return;e.state===0&&e.updateState(1);let t=new Set(e.localCandidate.foundation);for(let n of this.checkList)n.component===e.component&&!t.has(n.localCandidate.foundation)&&n.state===0&&(n.updateState(1),t.add(n.localCandidate.foundation))}schedulingChecks(){{let e=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===sD.type)).find(e=>e.state===1);if(e)return e.handle=this.checkStart(e),!0}{let e=this.checkList.find(e=>e.state===0);if(e)return e.handle=this.checkStart(e),!0}return!this.remoteCandidatesEnd&&!this.checkListDone}stopConsentLifecycle(){this.consentSessionId++,this.consentFresh=!1,this.consentExpiryTimer!==void 0&&(clearTimeout(this.consentExpiryTimer),this.consentExpiryTimer=void 0),this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0;let e=this.queryConsentHandle;this.queryConsentHandle=void 0,e?.resolve?.()}shouldNominateConsentRequest(e){return this.iceControlling&&this.remoteIsLite&&this.nominated?.id===e.id}canSendApplicationData(){return!this.nominated||this.state===`closed`||this.state===`failed`?!1:this.iceLite?!0:this.consentFresh}abortableDelay(e,t){return new Promise((n,r)=>{if(t.aborted){r(new DOMException(`The operation was aborted`,`AbortError`));return}let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`The operation was aborted`,`AbortError`))};t.addEventListener(`abort`,a,{once:!0})})}queryConsent=()=>{if(this.iceLite)return;this.stopConsentLifecycle();let e=this.consentSessionId;this.consentFresh=!0;let t=fD(async(n,r,i)=>{let a=!1,o=new AbortController,s=()=>{this.consentExpiryTimer!==void 0&&(clearTimeout(this.consentExpiryTimer),this.consentExpiryTimer=void 0)},c=()=>{a||e!==this.consentSessionId||(s(),this.consentExpiryTimer=setTimeout(()=>{this.consentExpiryTimer=void 0,!(a||e!==this.consentSessionId)&&this.state!==`closed`&&this.state!==`failed`&&(aO(`Consent to send expired`),this.consentFresh=!1,this.consentSessionId++,this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0,this.queryConsentHandle===t&&(this.queryConsentHandle=void 0),a=!0,o.abort(),this.setState(`failed`))},3e4))};i.once(()=>{a=!0,e===this.consentSessionId&&(s(),this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0),o.abort(),this.queryConsentHandle===t&&(this.queryConsentHandle=void 0)}),c();let l=()=>5*(.8+.4*Math.random())*1e3,u=Date.now()+l(),d=()=>this.state===`closed`||this.state===`failed`;try{for(;!d()&&!a&&e===this.consentSessionId&&(await this.abortableDelay(Math.max(0,u-Date.now()),o.signal),!(a||d()||e!==this.consentSessionId));){u=Date.now()+l();let t=this.nominated;if(!t)break;let n=t.id,r=this.generation,i=this.remotePassword,{localUsername:o,remoteUsername:s,iceControlling:d}=this,f=this.buildRequest({nominate:this.shouldNominateConsentRequest(t),localUsername:o,remoteUsername:s,iceControlling:d,localCandidate:t.localCandidate});this.consentRequestAbort?.abort();let p=new AbortController;this.consentRequestAbort=p,t.consentRequestsSent++,t.requestsSent++;let m=qD(t.rtt),h=performance.now();t.protocol.request(f,t.remoteAddr,Buffer.from(i,`utf8`),{retransmissions:0,responseTimeout:m,signal:p.signal,onRequestSent:e=>{e>0&&t.retransmissionsSent++}}).then(()=>{if(e!==this.consentSessionId||a)return;let o=this.state;if(o===`closed`||o===`failed`||this.nominated?.id!==n||this.generation!==r||this.remotePassword!==i)return;let s=(performance.now()-h)/1e3;t.rtt=s,t.totalRoundTripTime+=s,t.roundTripTimeMeasurements++,t.responsesReceived++,this.consentFresh=!0,c(),o===`disconnected`&&this.setState(`connected`)}).catch(t=>{e===this.consentSessionId&&this.nominated?.id===n&&aO(`no stun response`,t)})}}catch{}finally{e===this.consentSessionId&&s()}});this.queryConsentHandle=t};async close(){this.setState(`closed`),this.stopConsentLifecycle(),this.checkList&&!this.checkListDone&&this.checkListState.put(new Promise(e=>{e(2)})),this.nominated=void 0;for(let e of this.protocols)e.close&&await e.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(e){this.state=e,this.stateChanged.execute(e)}async addRemoteCandidate(e){if(!e){this.remoteCandidatesEnd=!0;return}if(e.host.includes(`.local`))try{this.lookup||=new UD,e.host=await this.lookup.lookup(e.host)}catch{return}try{YD(e)}catch{return}aO(`addRemoteCandidate`,e),this._remoteCandidates.push(e),this.pairRemoteCandidate(e),this.sortCheckList()}send=async e=>{if(!this.canSendApplicationData())return;let t=this.nominated;await t.protocol.sendData(e,t.remoteAddr),t.packetsSent++,t.bytesSent+=e.length};getDefaultCandidate(){let[e]=this.localCandidates.sort((e,t)=>e.priority-t.priority);return e}set remoteCandidates(e){if(this.remoteCandidatesEnd)throw Error(`Cannot set remote candidates after end-of-candidates.`);this._remoteCandidates=[];for(let t of e){try{YD(t)}catch{continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){XD(this.checkList,this.iceControlling)}findPair(e,t){return this.checkList.find(n=>n.protocol===e&&n.remoteCandidate===t)}applyIceControlling(e){this._iceControlling=e;for(let t of this.checkList)t.iceControlling=e}switchRole(e){aO(`switch role`,e),this.iceLite&&(e=!1),this.applyIceControlling(e),this.sortCheckList()}checkComplete(e){if(e.handle=void 0,e.state===3){if(e.nominated&&(e.remoteCandidate.generation==null||e.remoteCandidate.generation===this.generation)&&this.nominated==null){aO(`nominated`,e.toJSON()),this.nominated=e,this.nominating=!1,this.pruneTcpConnections(e),!this.iceLite&&(this.state===`connected`||this.state===`completed`)&&this.queryConsent();for(let t of this.checkList)t.component===e.component&&[1,0].includes(t.state)&&t.updateState(4)}if(this.nominated){this.checkListDone||=(aO(`ICE completed`),this.checkListState.put(new Promise(e=>e(1))),!0);return}aO(`not completed`,e.toJSON());for(let t of this.checkList)t.localCandidate.foundation===e.localCandidate.foundation&&t.state===0&&t.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:t})=>!e.includes(t)))return}(this.iceControlling||!this.checkList.find(({state:e})=>e===3))&&(this.checkListDone||(aO(`ICE failed`),this.checkListState.put(new Promise(e=>{e(2)}))))}checkStart=e=>fD(async t=>{aO(`check start`,e.toJSON()),e.updateState(2);let n={},{remotePassword:r,remoteUsername:i,generation:a}=this,o=e.localCandidate.ufrag??this.localUsername,s=this.iceControlling&&!this.remoteIsLite,c=this.buildRequest({nominate:s,localUsername:o,remoteUsername:i,iceControlling:this.iceControlling,localCandidate:e.localCandidate}),l=performance.now();try{e.requestsSent++;let[t,s]=await e.protocol.request(c,e.remoteAddr,Buffer.from(r,`utf8`),e.localCandidate.transport.toLowerCase()===`tcp`?0:4,t=>{t>0&&e.retransmissionsSent++});e.responsesReceived++;let u=(performance.now()-l)/1e3;e.rtt=u,e.totalRoundTripTime+=u,e.roundTripTimeMeasurements++,aO(`response received`,c.toJSON(),t.toJSON(),s,{localUsername:o,remoteUsername:i,remotePassword:r,generation:a,rtt:u}),n.response=t,n.addr=s}catch(n){let s=n;if(aO(`failure case`,c.toJSON(),s.response?JSON.stringify(s.response.toJSON(),null,2):n,{localUsername:o,remoteUsername:i,remotePassword:r,generation:a},e.remoteAddr),s.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(e).awaitable,t();return}if(s.response?.getAttributeValue(`ERROR-CODE`)[0]===401){aO(`retry 401`,e.toJSON()),await this.checkStart(e).awaitable,t();return}aO(`checkStart CandidatePairState.FAILED`,e.toJSON()),e.updateState(4),this.checkComplete(e),t();return}if(n.addr[0]!==e.remoteAddr[0]||n.addr[1]!==e.remoteAddr[1]){e.updateState(4),this.checkComplete(e),t();return}if(s||e.remoteNominated)e.nominated=!0;else if(this.iceControlling&&!this.nominating){this.nominating=!0;let t=this.buildRequest({nominate:!0,localUsername:o,remoteUsername:i,iceControlling:this.iceControlling,localCandidate:e.localCandidate});try{e.requestsSent++,await e.protocol.request(t,e.remoteAddr,Buffer.from(this.remotePassword,`utf8`),e.localCandidate.transport.toLowerCase()===`tcp`?0:4,t=>{t>0&&e.retransmissionsSent++}),e.responsesReceived++}catch{e.updateState(4),this.checkComplete(e);return}e.nominated=!0}e.updateState(3),this.checkComplete(e),t()});addPair(e){this.checkList.push(e),this.sortCheckList()}checkIncoming(e,t,n){let{remoteUsername:r}=cO(e.getAttributeValue(`USERNAME`)),i,[a,o]=t;for(let e of this.remoteCandidates)if(e.host===a&&e.port===o){i=e;break}i||(i=new AD(lD(10),1,n.localCandidate?.transport??`udp`,e.getAttributeValue(`PRIORITY`),a,o,`prflx`,void 0,void 0,n.localCandidate?.transport===`tcp`?HD(n.localCandidate.tcptype):void 0,void 0,void 0),this._remoteCandidates.push(i));let s=this.findPair(n,i);if(s||(s=new GD(n,i,this.iceControlling),s.updateState(1),this.addPair(s)),s.noteIncomingRequest(e.transactionIdHex),s.requestsReceived++,s.responsesSent++,s.localCandidate.ufrag=r,aO(`Triggered Checks`,e.toJSON(),s.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),this.iceLite){e.attributesKeys.includes(`USE-CANDIDATE`)&&!this.iceControlling&&(s.remoteNominated=!0,s.nominated=!0,s.updateState(3),this.checkComplete(s));return}[1,4].includes(s.state)&&(s.handle=this.checkStart(s)),e.attributesKeys.includes(`USE-CANDIDATE`)&&!this.iceControlling&&(s.remoteNominated=!0,s.state===3&&(s.nominated=!0,this.checkComplete(s)))}tryPair(e,t){if(e.localCandidate?.canPairWith(t)&&(e.localCandidate.transport.toLowerCase()!==`tcp`||e.localCandidate.tcptype!==`passive`||t.type===`prflx`)&&!this.findPair(e,t)){let n=new GD(e,t,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(n))return;n.updateState(1),this.addPair(n)}}pairLocalProtocol(e){for(let t of this.remoteCandidates)this.tryPair(e,t)}pairRemoteCandidate=e=>{for(let t of this.protocols)this.tryPair(t,e)};buildRequest({nominate:e,remoteUsername:t,localUsername:n,iceControlling:r,localCandidate:i}){let a=sO({remoteUsername:t,localUsername:n}),o=new RE(1,0);return o.setAttribute(`USERNAME`,a).setAttribute(`PRIORITY`,VD(`prflx`,{transport:i?.transport,tcptype:i?.tcptype})),r?(o.setAttribute(`ICE-CONTROLLING`,this.tieBreaker),e&&o.setAttribute(`USE-CANDIDATE`,null)):o.setAttribute(`ICE-CONTROLLED`,this.tieBreaker),o}pruneTcpConnections(e){for(let t of this.protocols)t.localCandidate?.transport.toLowerCase()===`tcp`&&`pruneForSelection`in t&&typeof t.pruneForSelection==`function`&&t.pruneForSelection(t===e.protocol?e.remoteAddr:void 0)}respondError(e,t,n,r){let i=new RE(e.messageMethod,272,e.transactionId);i.setAttribute(`ERROR-CODE`,r).addMessageIntegrity(Buffer.from(this.localPassword,`utf8`)).addFingerprint(),n.sendStun(i,t).catch(e=>{aO(`sendStun error`,e)})}},sO=({remoteUsername:e,localUsername:t})=>`${e}:${t}`,cO=e=>{let[t,n]=e.split(`:`);return{remoteUsername:t,localUsername:n}};function lO(e){return e.map((e,t)=>[t,e])}function uO(e,t){let n=e.split(t);return[n[0],n.slice(1).join(t)]}var dO=class extends k{emit(e,...t){if(typeof e!=`string`)return super.emit(e,...t);if(t.length===0)return super.emit(e,new Event(e));let[n,...r]=t;if(n&&typeof n==`object`&&!(`type`in n))try{Object.defineProperty(n,"type",{configurable:!0,enumerable:!0,value:e})}catch{return super.emit(e,{type:e,...n},...r)}return super.emit(e,n,...r)}addEventListener=(e,t,n)=>{if(typeof n==`object`&&n?.once){this.once(e,t);return}this.addListener(e,t)};removeEventListener=(e,t)=>{this.removeListener(e,t)};dispatchEvent=e=>this.emit(e.type,e)},fO=sS(`werift:packages/webrtc/src/dataChannel.ts`);function pO(e){return Buffer.isBuffer(e)?e.length:Buffer.byteLength(e)}var mO=class extends dO{constructor(e,t,n=!0){if(super(),this.sctp=e,this.parameters=t,this.sendOpen=n,this.id=this.parameters.id,t.negotiated){if(this.id==null||this.id<0||this.id>65534)throw Error(`ID must be in range 0-65534 if data channel is negotiated out-of-band`);this.sctp.dataChannelAddNegotiated(this)}else n&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}statsId=l().toString();stateChange=new $;stateChanged=new $;onMessage=new $;error=new $;bufferedAmountLow=new $;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??null}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime??null}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(e){if(e<0||e>4294967295)throw Error(`bufferedAmountLowThreshold must be in range 0 - 4294967295`);this._bufferedAmountLowThreshold=e}setId(e){this.id=e}setReadyState(e){if(e!==this.readyState){switch(this.readyState=e,this.stateChange.execute(e),this.stateChanged.execute(e),e){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()}fO(`change state`,e)}}addBufferedAmount(e){let t=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+e<=this.bufferedAmountLowThreshold;this.bufferedAmount+=e,t&&(this.bufferedAmountLow.execute(),this.emit(`bufferedamountlow`))}send(e){let t=this.sctp.datachannelSend(this,e);this.messagesSent++,this.bytesSent+=t}close(){this.sctp.dataChannelClose(this)}},hO=class{label=``;maxPacketLifeTime;maxRetransmits;ordered=!0;protocol=``;negotiated=!1;id;constructor(e={}){Object.assign(this,e)}},gO=()=>({type:`nack`}),_O=()=>({type:`nack`,parameter:`pli`}),vO=()=>({type:`goog-remb`}),yO=()=>({type:`transport-cc`}),bO=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction=`all`;constructor(e){Object.assign(this,e)}get name(){return this.mimeType.split(`/`)[1]}get contentType(){return this.mimeType.split(`/`)[0]}get str(){let e=`${this.name}/${this.clockRate}`;return this.channels===2&&(e+=`/2`),e}},xO=class{id;uri;constructor(e){Object.assign(this,e)}},SO=class{type;parameter;constructor(e={}){Object.assign(this,e)}},CO=class{ssrc;constructor(e={}){Object.assign(this,e)}},wO=class{ssrc;payloadType;rtx;constructor(e){Object.assign(this,e)}},TO=class{rid;direction;constructor(e){Object.assign(this,e)}},EO=(e={})=>new bO({mimeType:`video/h264`,clockRate:9e4,rtcpFeedback:[gO(),_O(),vO()],parameters:`profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1`,...e}),DO=(e={})=>new bO({mimeType:`video/VP8`,clockRate:9e4,rtcpFeedback:[gO(),_O(),vO()],...e}),OO=(e={})=>new bO({mimeType:`video/VP9`,clockRate:9e4,rtcpFeedback:[gO(),_O(),vO()],...e}),kO=(e={})=>new bO({mimeType:`video/AV1X`,clockRate:9e4,rtcpFeedback:[gO(),_O(),vO()],...e}),AO=(e={})=>new bO({mimeType:`audio/OPUS`,clockRate:48e3,channels:2,...e}),jO=(e={})=>new bO({mimeType:`audio/PCMU`,clockRate:8e3,channels:1,payloadType:0,...e}),MO=[kO(),OO(),DO(),EO(),AO(),jO()].map(e=>e.mimeType);MO.filter(e=>e.toLowerCase().startsWith(`video/`)),MO.filter(e=>e.toLowerCase().startsWith(`audio/`));var NO=2,PO=3,FO=0,IO=50,LO=51,RO=53,zO=56,BO=57,VO=`0.0.0.0`,HO=9,UO={auto:`actpass`,client:`active`,server:`passive`},WO=Object.keys(UO).reduce((e,t)=>{let n=UO[t];return e[n]=t,e},{}),GO=[`apt`,`max-fr`,`max-fs`,`maxplaybackrate`,`minptime`,`stereo`,`useinbandfec`],KO=[`cname`,`msid`,`mslabel`,`label`],qO={SRTP_AES128_CM_HMAC_SHA1_80:1,SRTP_AEAD_AES_128_GCM:7},JO=[`sendonly`,`sendrecv`],YO=[`sendrecv`,`recvonly`],XO=class extends Map{constructor(e){if(super(),e)for(let t of e)this.set(t.id,t)}};function ZO(e,...t){return`${e}_${t.filter(e=>e!==void 0).join(`_`)}`}function QO(e,t,n){return ZO(`codec`,e,t,n)}function $O(){return performance.timeOrigin+performance.now()}function ek(e){let t=[];for(let[n,r]of Object.entries(e))if(n!==`id`){if(n.endsWith(`Id`)){typeof r==`string`&&t.push(r);continue}if(n.endsWith(`Ids`)&&Array.isArray(r))for(let e of r)typeof e==`string`&&t.push(e)}return t}function tk(e,t){let n=new Map;for(let t of e)n.set(t.id,t);if(!t)return new XO([...n.values()]);let r=new Set,i=[...new Set(Array.from(t))];for(;i.length>0;){let e=i.shift();if(!e||r.has(e))continue;let t=n.get(e);t&&(r.add(e),i.push(...ek(t)))}return new XO([...r].map(e=>n.get(e)).filter(e=>!!e))}var nk=class{constructor(e,t,n,r,i){this.kind=e,this.receiver=n,this.sender=r,this._direction=i,t&&this.setDtlsTransport(t)}id=l().toString();onTrack=new $;mid=null;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(e){this._codecs=e}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}set direction(e){this.setDirection(e)}setDirection(e){this._direction=e,this._currentDirection&&this._currentDirection!==`stopped`&&JO.includes(this._currentDirection)&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection??null}setCurrentDirection(e){this._currentDirection=e}setDtlsTransport(e){this.receiver.setDtlsTransport(e),this.sender.setDtlsTransport(e)}get msid(){return this.msids[0]}get msids(){return this.sender.streamIds.map(e=>`${e} ${this.sender.trackId}`)}addTrack(e){this.receiver.addTrack(e)&&this.onTrack.execute(e,this)}stop(){this.stopping||=!0}forceStop(){this.stopped||(this.stopping=!0,this.stopped=!0,this.setCurrentDirection(`stopped`),this.receiver.stop(),this.sender.stop())}getPayloadType(e){return this.codecs.find(t=>t.mimeType.toLowerCase().includes(e.toLowerCase()))?.payloadType}getCodecStats(){let e=$O();return this.collectCodecStats(e)}collectCodecStats(e){let t=[];if(!this.dtlsTransport)return t;let n=ZO(`transport`,this.dtlsTransport.id);for(let r of this.codecs){let i={type:`codec`,id:QO(n,r.payloadType,this.id),timestamp:e,payloadType:r.payloadType,transportId:n,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,sdpFmtpLine:r.parameters};t.push(i)}return t}},rk=[`inactive`,`sendonly`,`recvonly`,`sendrecv`],ik=class extends dO{uuid=l().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new $;onReceiveRtcp=new $;onSourceChanged=new $;stopped=!1;muted=!0;constructor(e){super(),Object.assign(this,e),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=e=>{if(this.remote)throw Error(`this is remoteTrack`);if(this.stopped)return;let t=Buffer.isBuffer(e)?tT.deSerialize(e):e;t.header.payloadType=this.codec?.payloadType??t.header.payloadType,this.onReceiveRtp.execute(t)}},ak=class{id;tracks=[];constructor(e={}){Array.isArray(e)?this.tracks=e:Object.assign(this,e),this.id??=l().toString()}addTrack(e){e.streamId=this.id,this.tracks.push(e)}removeTrack(e){this.tracks=this.tracks.filter(t=>t!==e),e.streamId===this.id&&(e.streamId=void 0)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(e=>e.kind===`audio`)}getVideoTracks(){return this.tracks.filter(e=>e.kind===`video`)}},ok=sS(`werift:packages/webrtc/src/utils.ts`);function sk(e,t){return(e=>e.match(/(.{2})/g).join(`:`))((e=>e.toUpperCase())(a(t).update(e).digest(`hex`)))}var ck={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`};function lk(e){return ck[e.trim().toLowerCase()]}function uk(e){return e.replace(/[^0-9a-f]/gi,``).toLowerCase()}function dk(e){let t=e[0];return t>19&&t<64}var fk=(e,t)=>rk[rk.indexOf(e)&rk.indexOf(t)];function pk(e){return e===`sendonly`?`recvonly`:e===`recvonly`?`sendonly`:e}var mk=Date.now,hk=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,gk=()=>hk+process.hrtime.bigint()/1000n,_k=()=>Date.now()/1e3,vk=()=>{let[e,t]=((A.timeOrigin+A.now()-Date.UTC(1900,0,1))/1e3).toString().split(`.`).map(Number);return Nx([4,4],[e,t]).readBigUInt64BE()},yk=e=>{let[t,n]=Fx(Nx([8],[e]),[4,4]);return t*1e3+n+Date.UTC(1900,0,1)},bk=e=>{let[,t,n]=Fx(Nx([8],[e]),[2,2,2,2]);return Nx([2,2],[t,n]).readUInt32BE()};function xk(e){let t={};for(let n of e){let e=Array.isArray(n.urls)?n.urls:[n.urls];for(let r of e){let e=Ck(r);e&&(!t.stunServer&&e.kind===`stun`&&(t.stunServer=e.address),!t.turnServer&&e.kind===`turn`&&(t.turnServer=e.address,t.turnTransport=e.transport,t.turnUsername=n.username,t.turnPassword=n.credential))}}return ok(`iceOptions`,t),t}function Sk({configuredTurnTransport:e,forceTurnTCP:t,parsedTurnTransport:n}){if(n)return n;if(e)return e;if(t)return`tcp`}function Ck(e){let t=/^(stun|stuns|turn|turns):(.+)$/i.exec(e.trim());if(!t)return;let[,n,r]=t,i=n.toLowerCase(),[a]=r.split(`?`,1),[,o=``]=r.split(`?`),s=Ek(a,Tk(i));if(!s)return;if(i===`stun`||i===`stuns`)return{kind:`stun`,address:s};let c=wk({scheme:i,transportParam:new URLSearchParams(o).get(`transport`)});if(c!==`invalid`)return{kind:`turn`,address:s,transport:c}}function wk({scheme:e,transportParam:t}){return t==null?e===`turns`?`tls`:void 0:t===`udp`?e===`turns`?`invalid`:`udp`:t===`tcp`?e===`turns`?`tls`:`tcp`:`invalid`}function Tk(e){return e===`stuns`||e===`turns`?5349:3478}function Ek(e,t){let n=e.startsWith(`//`)?e.slice(2):e;if(!n)return;if(n.startsWith(`[`)){let e=n.indexOf(`]`);return e===-1?void 0:[n.slice(1,e),Dk(n.slice(e+1),t)]}let r=n.indexOf(`:`),i=n.lastIndexOf(`:`);return r!==-1&&r===i?[n.slice(0,r),Dk(n.slice(r+1),t)]:[n,t]}function Dk(e,t){let n=e.startsWith(`:`)?e.slice(1):e,r=Number.parseInt(n,10);return Number.isFinite(r)?r:t}BS.createSelfSignedCertificateWithKey;var Ok=(e,t)=>{if(!e||typeof e!=`object`)return typeof t==`object`&&t?t:e;if(!t||typeof t!=`object`)return t??e;for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];r!=null&&(e[n]=r)}return e},kk=sS(`werift:packages/webrtc/src/media/receiver/nack.ts`),Ak=150,jk=class{constructor(e){this.receiver=e}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new $;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(e){return this._lost[e]}setLost(e,t){this._lost[e]=t,!(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(e){kk(`failed to send nack`,e)}},5))}removeLost(e){delete this._lost[e]}addPacket(e){let{sequenceNumber:t,ssrc:n}=e.header;if(this.mediaSourceSsrc=n,this.newEstSeqNum===0){this.newEstSeqNum=t;return}if(this.getLost(t)){this.removeLost(t);return}if(t===Zx(this.newEstSeqNum,1))this.newEstSeqNum=t;else if(t>Zx(this.newEstSeqNum,1)){for(let e=Zx(this.newEstSeqNum,1);e<t;e=Zx(e,1))this.setLost(e,1);this.newEstSeqNum=t,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>Ak&&(this._lost=Object.entries(this._lost).slice(-Ak).reduce((e,[t,n])=>(e[t]=n,e),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(e=>{if(this._lost[e]++>this.retryCount)return this.removeLost(e),e})}sendNack=()=>new Promise((e,t)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let n=new dw({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),r=new yw({feedback:n});this.receiver.dtlsTransport.sendRtcp([r]).then(e).catch(t),this.updateRetryCount(),this.onPacketLost.execute(n)}})},Mk=sS(`werift:packages/webrtc/media/receiver/receiverTwcc`),Nk=class{constructor(e,t,n){this.dtlsTransport=e,this.rtcpSsrc=t,this.mediaSourceSsrc=n,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(e){this.extensionInfo[e]={tsn:e,timestamp:gk()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await E(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let e=Object.values(this.extensionInfo).sort((e,t)=>e.tsn-t.tsn),t=e[0].tsn,n=e.slice(-1)[0].tsn,r=[],i=e[0].tsn,a=Zx(n-t,1),o,s,c=[];for(let e=t;e<=n;e++){let t=this.extensionInfo[e]?.timestamp;if(t){this.lastTimestamp||=t,o||=this.lastTimestamp;let i=t-this.lastTimestamp;this.lastTimestamp=t;let a=new gw({delta:Number(i)});a.parseDelta(),c.push(a),s!=null&&s.status!==a.type&&(r.push(new mw({packetStatus:s.status,runLength:e-s.minTSN})),s={minTSN:e,status:a.type}),e===n&&(s==null?r.push(new mw({packetStatus:a.type,runLength:1})):r.push(new mw({packetStatus:s.status,runLength:e-s.minTSN+1}))),s??={minTSN:e,status:a.type}}}if(!o)return;let l=new yw({feedback:new pw({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:i,packetStatusCount:a,referenceTime:$x(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:r})});this.dtlsTransport.sendRtcp([l]).catch(e=>{Mk(e)}),this.extensionInfo={},this.fbPktCount=Xx(this.fbPktCount,1)}},Pk=class{base_seq;max_seq;cycles=0;packets_received=0;bytesReceived=0;headerBytesReceived=0;lastPacketReceivedTimestamp;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(e){this.clockRate=e}add(e,t=Date.now()/1e3){let n=this.max_seq==null||eS(e.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.bytesReceived+=e.payload.length,this.headerBytesReceived+=e.header.serializeSize,this.lastPacketReceivedTimestamp=$O(),this.base_seq??=e.header.sequenceNumber,n){let n=rS(t*this.clockRate);if(this.max_seq!=null&&e.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=e.header.sequenceNumber,e.header.timestamp!==this.last_timestamp&&this.packets_received>1){let t=Math.abs(n-(this.last_arrival??0)-(e.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=t-(this.jitter_q4+8>>4)}this.last_arrival=n,this.last_timestamp=e.header.timestamp}}get fraction_lost(){let e=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let t=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let n=e-t;return e==0||n<=0?0:Math.floor((n<<8)/e)}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 e=this.packets_expected-this.packets_received;return e<0?0:e}},Fk=sS(`werift:packages/webrtc/src/transport/dtls.ts`);function Ik(e){if(e){if(e.major===254&&e.minor===253)return`DTLS 1.2`;if(e.major===254&&e.minor===255)return`DTLS 1.0`}}function Lk(e){switch(e){case 1:return`AES_CM_128_HMAC_SHA1_80`;case 7:return`AEAD_AES_128_GCM`;default:return}}var Rk=class e{constructor(t,n,r,i=[]){this.config=t,this.iceTransport=n,this.localCertificate=r,this.srtpProfiles=i,this.localCertificate??=e.localCertificate}id=l().toString();state=`new`;role=`auto`;srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new $;onRtcp=new $;onRtp=new $;events=new dO;onstatechange;static localCertificate;static localCertificatePromise;remoteParameters;addEventListener=(e,t,n)=>{this.events.addEventListener(e,t,n)};removeEventListener=(e,t)=>{this.events.removeEventListener(e,t)};dispatchEvent=e=>this.events.dispatchEvent(e);get localParameters(){return new Vk(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){return this.localCertificate?this.localCertificate:(this.localCertificatePromise||=(async()=>{let{certPem:e,keyPem:t,signatureHash:n}=await BS.createSelfSignedCertificateWithKey({signature:mS.ecdsa_3,hash:hS.sha256_4},vS.secp256r1_23);return this.localCertificate=new zk(t,e,n),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let t=Hk([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),n=e.role===`auto`&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new Vk(t,n)}async start(){if(this.state!==`new`)throw Error(`state must be new`);if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw Error(`remote fingerprint not exist`);this.role===`auto`&&(this.role=this.iceTransport.role===`controlling`?`server`:`client`),this.setState(`connecting`),await new Promise(async(e,t)=>{this.dtls=this.role===`server`?new rE({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Kk(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):new JT({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Kk(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0}),this.dtls.onData.subscribe(e=>{this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()||this.dataReceiver(e)}),this.dtls.onClose.subscribe(()=>{this.state!==`failed`&&this.setState(`closed`)}),this.dtls.onConnect.once(e),this.dtls.onError.once(e=>{this.setState(`failed`),Fk(`dtls failed`,e),t(e)}),this.dtls instanceof JT&&(await E(100),this.dtls.connect().catch(e=>{this.setState(`failed`),Fk(`dtls connect failed`,e),t(e)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState(`failed`),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState(`connected`),Fk(`dtls connected`)}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw Error(`remote fingerprint not exist`);let e=this.dtls?.remoteCertificate;if(!e)throw Error(`remote certificate not available`);let t=this.remoteParameters.fingerprints.flatMap(({algorithm:e,value:t})=>{let n=lk(e);if(!n)return[];let r=uk(t);if(!r)throw Error(`remote fingerprint value is empty`);return[{normalizedAlgorithm:n,normalizedValue:r}]});if(t.length===0)throw Error(`no supported remote fingerprint algorithms`);let n=Wk(t),r=t.filter(({normalizedAlgorithm:e})=>e===n),i=r.reduce((t,{normalizedAlgorithm:n})=>(t.has(n)||t.set(n,uk(sk(e,n))),t),new Map);if(!r.some(({normalizedAlgorithm:e,normalizedValue:t})=>i.get(e)===t))throw Error(`remote certificate fingerprint mismatch`)}updateSrtpSession(){if(!this.dtls)throw Error();let e=this.dtls.srtp.srtpProfile;if(!e)throw Error(`need srtpProfile`);Fk(`selected SRTP Profile`,e);let{localKey:t,localSalt:n,remoteKey:r,remoteSalt:i}=this.dtls.extractSessionKeys(ZC(e),QC(e)),a={keys:{localMasterKey:t,localMasterSalt:n,remoteMasterKey:r,remoteMasterSalt:i},profile:e};this.srtp=new kT(a),this.srtcp=new DT(a)}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())&&tw(e)){if(this.bytesReceived+=e.length,this.packetsReceived++,kw(e)){let t;try{t=this.srtcp.decrypt(e)}catch(e){if(e instanceof aT){Fk(`dropping invalid SRTCP packet`,e);return}throw e}let n;try{n=Ow.deSerialize(t)}catch(e){Fk(`dropping malformed SRTCP packet`,e);return}for(let e of n)try{this.onRtcp.execute(e)}catch(e){Fk(`RTCP error`,e)}}else{let t;try{t=this.srtp.decrypt(e)}catch(e){if(e instanceof aT){Fk(`dropping invalid SRTP packet`,e);return}throw e}let n;try{n=tT.deSerialize(t)}catch(e){Fk(`dropping malformed SRTP packet`,e);return}try{this.onRtp.execute(n)}catch(e){Fk(`RTP error`,e)}}}}))}sendData=async e=>{if(!(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random())){if(!this.dtls)throw Error(`dtls not established`);await this.dtls.send(e)}};async sendRtp(e,t){try{let n=this.srtp.encrypt(e,t);return this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()?n.length:(this.bytesSent+=n.length,this.packetsSent++,await this.iceTransport.connection.send(n).catch(()=>{}),n.length)}catch(e){return Fk(`failed to send`,e),0}}async sendRtcp(e){let t=Buffer.concat(e.map(e=>e.serialize())),n=this.srtcp.encrypt(t);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,t=!0){e!=this.state&&(this.state=e,this.onStateChange.execute(e),t&&(this.onstatechange?.(),this.events.emit(`statechange`)))}async stop(){this.setState(`closed`,!1),await this.iceTransport.stop()}async getStats(e=$O()){let t=[],n=ZO(`transport`,this.id),r={type:`transport`,id:n,timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,iceRole:this.iceTransport.role===`unknown`?void 0:this.iceTransport.role,iceLocalUsernameFragment:this.iceTransport.localParameters.usernameFragment,selectedCandidatePairId:this.iceTransport.connection.nominated?ZO(`candidate-pair`,this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?ZO(`certificate`,this.id,`local`):void 0,remoteCertificateId:this.dtls?.remoteCertificate?ZO(`certificate`,this.id,`remote`):void 0,dtlsRole:this.role===`auto`?void 0:this.role,tlsVersion:Ik(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:Lk(this.dtls?.srtp.srtpProfile),iceRestarts:this.iceTransport.iceRestarts};if(t.push(r),this.localCertificate){let n=this.localCertificate.getFingerprints();if(n.length>0){let r={type:`certificate`,id:ZO(`certificate`,this.id,`local`),timestamp:e,fingerprint:n[0].value,fingerprintAlgorithm:n[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString(`base64`)};t.push(r)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0&&this.dtls?.remoteCertificate){let n={type:`certificate`,id:ZO(`certificate`,this.id,`remote`),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:Buffer.from(this.dtls.remoteCertificate).toString(`base64`)};t.push(n)}let i=await this.iceTransport.getStats(e,n);return t.push(...i),t}},zk=class{constructor(e,t,n){this.certPem=t,this.signatureHash=n;let r=di.Certificate.fromPEM(Buffer.from(t));this.publicKey=r.publicKey.toPEM(),this.privateKey=di.PrivateKey.fromPEM(Buffer.from(e)).toPEM()}publicKey;privateKey;getFingerprints(){return[new Bk(`sha-256`,sk(di.Certificate.fromPEM(Buffer.from(this.certPem)).raw,`sha256`))]}},Bk=class{constructor(e,t){this.algorithm=e,this.value=t}},Vk=class{constructor(e=[],t){this.fingerprints=e,this.role=t}},Hk=e=>{let t=new Set;return e.filter(({algorithm:e,value:n})=>{let r=`${lk(e)??e.trim().toLowerCase()}:${uk(n)}`;return!t.has(r)&&(t.add(r),!0)})},Uk=[`sha512`,`sha384`,`sha256`,`sha224`,`sha1`],Wk=e=>Uk.find(t=>e.some(({normalizedAlgorithm:e})=>e===t))??e[0].normalizedAlgorithm,Gk=class{constructor(e){this.ice=e,e.onData.subscribe(e=>{dk(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type=`ice`;send=e=>this.ice.send(e);async close(){this.closed=!0,this.ice.close()}},Kk=e=>new Gk(e),qk=sS(`werift:packages/webrtc/src/transport/ice.ts`);function Jk(e){switch(e){case 0:return`frozen`;case 1:return`waiting`;case 2:return`in-progress`;case 3:return`succeeded`;case 4:return`failed`;default:return`failed`}}var Yk=class{constructor(e){this.iceGather=e,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)},this.iceGather.onGatheringStateChange.subscribe(()=>{this.ongatheringstatechange?.(),this.events.emit(`gatheringstatechange`)})}id=l().toString();connection;state=`new`;component=`rtp`;iceRestarts=0;waitStart;renominating=!1;events=new dO;onstatechange;ongatheringstatechange;onStateChange=new $;onIceCandidate=new $;onNegotiationNeeded=new $;addEventListener=(e,t,n)=>{this.events.addEventListener(e,t,n)};removeEventListener=(e,t)=>{this.events.removeEventListener(e,t)};dispatchEvent=e=>this.events.dispatchEvent(e);get role(){return!this.connection.remoteUsername||!this.connection.remotePassword?`unknown`:this.connection.iceControlling?`controlling`:`controlled`}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}getRemoteCandidates(){return this.connection.remoteCandidates.filter(e=>e.type!==`prflx`).map(e=>Zk(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>Zk(e).toJSON())}getSelectedCandidatePair(){let e=this.connection.candidatePairs.find(e=>e.nominated)??this.connection.candidatePairs.find(e=>e.state===3);return e?{local:Zk(e.localCandidate).toJSON(),remote:Zk(e.remoteCandidate).toJSON()}:null}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){return!this.connection.remoteUsername||!this.connection.remotePassword?null:new tA({iceLite:this.connection.remoteIsLite,password:this.connection.remotePassword,usernameFragment:this.connection.remoteUsername})}setState(e,t=!0){e!==this.state&&(this.state=e,this.onStateChange.execute(e),t&&(this.onstatechange?.(),this.events.emit(`statechange`)))}gather(){return this.iceGather.gather()}addRemoteCandidate=e=>{if(!this.connection.remoteCandidatesEnd)return e?this.connection.addRemoteCandidate(Qk(e)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(e,t=!1){t&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==e.usernameFragment||this.connection.remotePassword!==e.password)&&(this.renominating?(qk(`renomination`,e),this.connection.resetNominatedPair(),this.renominating=!1):(qk(`restart`,e),this.restart())),this.connection.setRemoteParams(e)}restart(){this.iceRestarts++,this.connection.restart(),this.setState(`new`),this.iceGather.gatheringState=`new`,this.waitStart=void 0,this.onNegotiationNeeded.execute()}async start(){if(this.state===`closed`)throw Error(`RTCIceTransport is closed`);if(!this.connection.remotePassword||!this.connection.remoteUsername)throw Error(`remoteParams missing`);this.waitStart&&await this.waitStart.asPromise(),this.waitStart=new $,this.setState(`checking`);try{await this.connection.connect()}catch(e){throw this.setState(`failed`),e}this.waitStart.execute(),this.waitStart.complete(),this.waitStart=void 0}async stop(){this.state!==`closed`&&(this.setState(`closed`,!1),await this.connection.close()),this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(e=$O(),t=ZO(`transport`,this.id)){let n=[];for(let r of this.connection.localCandidates){let i={type:`local-candidate`,id:ZO(`local-candidate`,r.id),timestamp:e,transportId:t,address:r.host,port:r.port,protocol:r.transport,candidateType:r.type,priority:r.priority,foundation:r.foundation,relatedAddress:r.relatedAddress,relatedPort:r.relatedPort,usernameFragment:r.ufrag,tcpType:r.tcptype};n.push(i)}for(let r of this.connection.remoteCandidates){let i={type:`remote-candidate`,id:ZO(`remote-candidate`,r.id),timestamp:e,transportId:t,address:r.host,port:r.port,protocol:r.transport,candidateType:r.type,priority:r.priority,foundation:r.foundation,relatedAddress:r.relatedAddress,relatedPort:r.relatedPort,usernameFragment:r.ufrag,tcpType:r.tcptype};n.push(i)}let r=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(e=>e.nominated),...this.connection.candidatePairs.filter(e=>!e.nominated)]:[];for(let i of r){let r={type:`candidate-pair`,id:ZO(`candidate-pair`,i.id),timestamp:e,transportId:t,localCandidateId:ZO(`local-candidate`,i.localCandidate.id),remoteCandidateId:ZO(`remote-candidate`,i.remoteCandidate.id),state:Jk(i.state),nominated:i.nominated,packetsSent:i.packetsSent,packetsReceived:i.packetsReceived,bytesSent:i.bytesSent,bytesReceived:i.bytesReceived,currentRoundTripTime:i.rtt,totalRoundTripTime:i.totalRoundTripTime,roundTripTimeMeasurements:i.roundTripTimeMeasurements,requestsReceived:i.requestsReceived,requestsSent:i.requestsSent,responsesReceived:i.responsesReceived,responsesSent:i.responsesSent,retransmissionsReceived:i.retransmissionsReceived,retransmissionsSent:i.retransmissionsSent,consentRequestsSent:i.consentRequestsSent};n.push(r)}return n}},Xk=class{constructor(e={}){this.options=e,this.connection=new oO(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(Zk(e))})}onIceCandidate=()=>{};gatheringState=`new`;connection;onGatheringStateChange=new $;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(Zk)}get localParameters(){return new tA({iceLite:this.connection.iceLite,usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(e){e!==this.gatheringState&&(this.gatheringState=e,this.onGatheringStateChange.execute(e))}};function Zk(e){let t=new eA(e.component,e.foundation,e.host,e.port,e.priority,e.transport,e.type,e.generation,e.ufrag);return t.relatedAddress=e.relatedAddress,t.relatedPort=e.relatedPort,t.tcpType=e.tcptype,t}function Qk(e){return new AD(e.foundation,e.component,e.protocol,e.priority,e.ip,e.port,e.type,e.relatedAddress,e.relatedPort,e.tcpType,e.generation,e.ufrag)}var $k=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(e){Object.assign(this,e)}static fromSdp(e){return Zk(AD.fromSdp(e)).toJSON()}static isThis(e){if(typeof e?.candidate==`string`)return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},eA=class{constructor(e,t,n,r,i,a,o,s,c){this.component=e,this.foundation=t,this.ip=n,this.port=r,this.priority=i,this.protocol=a,this.type=o,this.generation=s,this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new $k({candidate:vj(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate)throw Error(`candidate is required`);let t=Sj(e.candidate.startsWith(`candidate:`)?e.candidate.slice(10):e.candidate);return t.sdpMLineIndex=e.sdpMLineIndex??void 0,t.sdpMid=e.sdpMid??void 0,t}catch{}}},tA=class{iceLite=!1;usernameFragment;password;constructor(e={}){Object.assign(this,e)}},nA=class e{constructor(e=0,t=Buffer.from(``)){this.flags=e,this._body=t}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return e.type}get bytes(){if(!this.body)throw 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(SA(this.body.length))].map(()=>Buffer.from(`\0`))])}},rA=class extends nA{constructor(e=0,t){super(e,t),this.flags=e,t?(this.initiateTag=t.readUInt32BE(0),this.advertisedRwnd=t.readUInt32BE(4),this.outboundStreams=t.readUInt16BE(8),this.inboundStreams=t.readUInt16BE(10),this.initialTsn=t.readUInt32BE(12),this.params=wA(t.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 e=Buffer.alloc(16);return e.writeUInt32BE(this.initiateTag,0),e.writeUInt32BE(this.advertisedRwnd,4),e.writeUInt16BE(this.outboundStreams,8),e.writeUInt16BE(this.inboundStreams,10),e.writeUInt32BE(this.initialTsn,12),Buffer.concat([e,CA(this.params)])}},iA=class e extends rA{static type=1;get type(){return e.type}},aA=class e extends rA{static type=2;get type(){return e.type}},oA=class e extends rA{static type=130;get type(){return e.type}},sA=class e extends nA{constructor(e=0,t){if(super(e,t),this.flags=e,t){this.cumulativeTsn=t.readUInt32BE(0);let e=4;for(;e<t.length;)this.streams.push([t.readUInt16BE(e),t.readUInt16BE(e+2)]),e+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return e.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([e,t])=>{let n=Buffer.alloc(4);return n.writeUInt16BE(e,0),n.writeUInt16BE(t,2),n})])}},cA=class e extends nA{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.tsn=t.readUInt32BE(0),this.streamId=t.readUInt16BE(4),this.streamSeqNum=t.readUInt16BE(6),this.protocol=t.readUInt32BE(8),this.userData=t.slice(12))}static type=0;get type(){return e.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,t=Buffer.alloc(16);t.writeUInt8(this.type,0),t.writeUInt8(this.flags,1),t.writeUInt16BE(e,2),t.writeUInt32BE(this.tsn,4),t.writeUInt16BE(this.streamId,8),t.writeUInt16BE(this.streamSeqNum,10),t.writeUInt32BE(this.protocol,12);let n=Buffer.concat([t,this.userData]);return e%4&&(n=Buffer.concat([n,...[...Array(SA(e))].map(()=>Buffer.from(`\0`))])),n}},lA=class e extends nA{static type=10;get type(){return e.type}},uA=class e extends nA{static type=11;get type(){return e.type}},dA=class extends nA{constructor(e=0,t=void 0){super(e,t),this.flags=e,t&&(this.params=wA(t))}params=[];get body(){return CA(this.params)}},fA=class e extends dA{static type=6;get type(){return e.type}},pA=class e extends dA{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 e.type}get descriptions(){return this.params.map(([t,n])=>({name:(Object.entries(e.CODE).find(([,e])=>e===t)||[])[0],body:n}))}},mA=class e extends dA{static type=4;get type(){return e.type}},hA=class e extends dA{static type=5;get type(){return e.type}},gA=class e extends dA{static type=130;get type(){return e.type}},_A=class e extends nA{constructor(e=0,t){if(super(e,t),this.flags=e,t){this.cumulativeTsn=t.readUInt32BE(0),this.advertisedRwnd=t.readUInt32BE(4);let e=t.readUInt16BE(8),n=t.readUInt16BE(10),r=12;[...Array(e)].forEach(()=>{this.gaps.push([t.readUInt16BE(r),t.readUInt16BE(r+2)]),r+=4}),[...Array(n)].forEach(()=>{this.duplicates.push(t.readUInt32BE(r)),r+=4})}}static type=3;get type(){return e.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),t=Buffer.alloc(16);t.writeUInt8(this.type,0),t.writeUInt8(this.flags,1),t.writeUInt16BE(e,2),t.writeUInt32BE(this.cumulativeTsn,4),t.writeUInt32BE(this.advertisedRwnd,8),t.writeUInt16BE(this.gaps.length,12),t.writeUInt16BE(this.duplicates.length,14);let n=Buffer.concat([t,...this.gaps.map(e=>{let t=Buffer.alloc(4);return t.writeUInt16BE(e[0],0),t.writeUInt16BE(e[1],2),t})]);return n=Buffer.concat([n,...this.duplicates.map(e=>{let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t})]),n}},vA=class e extends nA{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.cumulativeTsn=t.readUInt32BE(0))}static type=7;get type(){return e.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},yA=class e extends nA{static type=8;get type(){return e.type}},bA=class e extends nA{static type=14;get type(){return e.type}},xA=[cA,iA,aA,_A,mA,hA,fA,vA,yA,pA,lA,uA,bA,gA,sA].reduce((e,t)=>(e[t.type]=t,e),{});function SA(e){let t=e%4;return t?4-t:0}function CA(e){let t=Buffer.from(``),n=Buffer.from(``);return e.forEach(([e,r])=>{let i=r.length+4,a=Buffer.alloc(4);a.writeUInt16BE(e,0),a.writeUInt16BE(i,2),t=Buffer.concat([t,n,a,r]),n=Buffer.concat([...Array(SA(i))].map(()=>Buffer.from(`\0`)))}),t}function wA(e){let t=[],n=0;for(;n<=e.length-4;){let r=e.readUInt16BE(n),i=e.readUInt16BE(n+2);t.push([r,e.slice(n+4,n+i)]),n+=i+SA(i)}return t}function TA(e){if(e.length<12)throw Error(`SCTP packet length is less than 12 bytes`);let t=e.readUInt16BE(0),n=e.readUInt16BE(2),r=e.readUInt32BE(4);if(e.readUInt32LE(8)!==Yx(Buffer.concat([e.slice(0,8),Buffer.from(`\0\0\0\0`),e.slice(12)])))throw Error(`SCTP packet has invalid checksum`);let i=[],a=12;for(;a+4<=e.length;){let t=e.readUInt8(a),n=e.readUInt8(a+1),r=e.readUInt16BE(a+2),o=e.slice(a+4,a+r),s=xA[t.toString()];if(s)i.push(new s(n,o));else throw Error(`unknown`);a+=r+SA(r)}return[t,n,r,i]}function EA(e,t,n,r){let i=Buffer.alloc(8);i.writeUInt16BE(e,0),i.writeUInt16BE(t,2),i.writeUInt32BE(n,4);let a=r.bytes,o=Yx(Buffer.concat([i,Buffer.from(`\0\0\0\0`),a])),s=Buffer.alloc(4);return s.writeUInt32LE(o,0),Buffer.concat([i,s,a])}function DA(e){return e.map((e,t)=>[t,e])}function OA(e){return e.reduce((e,t)=>(e[t]=new $,e),{})}var kA=class e{constructor(e,t,n,r){this.requestSequence=e,this.responseSequence=t,this.lastTsn=n,this.streams=r}static type=13;get type(){return e.type}get bytes(){let e=Buffer.allocUnsafe(12);return e.writeUInt32BE(this.requestSequence,0),e.writeUInt32BE(this.responseSequence,4),e.writeUInt32BE(this.lastTsn,8),Buffer.concat([e,...this.streams.map(e=>{let t=Buffer.allocUnsafe(2);return t.writeUInt16BE(e,0),t})])}static parse(t){let n=t.readUInt32BE(0),r=t.readUInt32BE(4),i=t.readUInt32BE(8),a=[];for(let e=12;e<t.length;e+=2)a.push(t.readUInt16BE(e));return new e(n,r,i,a)}},AA=class e{constructor(e,t){this.requestSequence=e,this.newStreams=t}static type=17;get type(){return e.type}get bytes(){let e=Buffer.allocUnsafe(8);return e.writeUInt32BE(this.requestSequence,0),e.writeUInt16BE(this.newStreams,4),e.writeUInt16BE(0,6),e}static parse(t){let n=t.readUInt32BE(0),r=t.readUInt16BE(4);return new e(n,r)}},jA={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},MA=class e{constructor(e,t){this.responseSequence=e,this.result=t}static type=16;get type(){return e.type}get bytes(){let e=Buffer.allocUnsafe(8);return e.writeUInt32BE(this.responseSequence,0),e.writeUInt32BE(this.result,4),e}static parse(t){let n=t.readUInt32BE(0),r=t.readUInt32BE(4);return new e(n,r)}},NA={13:kA,16:MA,17:AA},PA=sS(`werift/sctp/sctp`),FA=24,IA=60,LA=65535,RA=1200,zA=1,BA=2,VA=4,HA=10,UA=8,WA=1/8,GA=1/4,KA=3,qA=1,JA=60,YA=2**32,XA=200,ZA=30,QA=135,$A=7,ej=32776,tj=49152,nj=[`new`,`closed`,`connected`,`connecting`],rj=class e{constructor(e,t=5e3){this.transport=e,this.port=t,this.localPort=this.port,this.transport.onData=e=>{this.handleData(e)}}flush=new $;stateChanged=OA(nj);onReconfigStreams=new $;onReceive=new $;onSackReceived=async()=>{};associationState=1;started=!1;state=`new`;isServer=!0;isStopping=!1;isClosed=!1;hmacKey=c(16);localPartialReliability=!0;localPort;localVerificationTag=kx();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1048576;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=LA;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*RA;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=LA;localTsn=Number(kx());lastSackedTsn=oj(this.localTsn);advancedPeerAckTsn=oj(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=KA;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=ZA;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(t,n=5e3){let r=new e(t,n);return r.isServer=!1,r}static server(t,n=5e3){let r=new e(t,n);return r.isServer=!0,r}async handleData(e){if(this.isStopped)return;let t,[,,n,r]=TA(e);if(r.filter(e=>e.type===iA.type).length>0){if(r.length!=1)throw Error();t=0}else t=this.localVerificationTag;if(n===t){this.sackHasNewDataInPacket=!1;for(let e of r)await this.receiveChunk(e);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),void 0),await this.sendSack();return}this.sackTimeout||=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch(e=>{PA(`send delayed sack failed`,e.message)})},XA)}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],t;[...this.sackMisOrdered].sort().forEach(n=>{let r=(n-this.lastReceivedTsn)%YA;n===t?e[e.length-1][1]=r:e.push([r,r]),t=sj(n)});let n=new _A(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(e=>{PA(`send sack failed`,e.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case cA.type:this.receiveDataChunk(e);break;case iA.type:{if(!this.isServer)return;let t=e;PA(`receive init`,t),this.lastReceivedTsn=oj(t.initialTsn),this.reconfigResponseSeq=oj(t.initialTsn),this.remoteVerificationTag=t.initiateTag,this.ssthresh=t.advertisedRwnd,this.peerAdvertisedRwnd=t.advertisedRwnd,this.getExtensions(t.params),this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);let n=new aA;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 r=Math.floor(Date.now()/1e3),i=Buffer.allocUnsafe(4);i.writeUInt32BE(r,0);let a=i;a=Buffer.concat([a,o(`sha1`,this.hmacKey).update(a).digest()]),n.params.push([$A,a]),PA(`send initAck`,n),await this.sendChunk(n).catch(e=>{PA(`send initAck failed`,e.message)})}break;case aA.type:{if(this.associationState!=2)return;let t=e;this.timer1Cancel(),this.lastReceivedTsn=oj(t.initialTsn),this.reconfigResponseSeq=oj(t.initialTsn),this.remoteVerificationTag=t.initiateTag,this.ssthresh=t.advertisedRwnd,this.peerAdvertisedRwnd=t.advertisedRwnd,this.getExtensions(t.params),this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);let n=new lA;for(let[e,r]of t.params)if(e===$A){n.body=r;break}await this.sendChunk(n).catch(e=>{PA(`send echo failed`,e.message)}),this.timer1Start(n),this.setState(3)}break;case _A.type:await this.receiveSackChunk(e);break;case mA.type:{let t=new hA;t.params=e.params,await this.sendChunk(t).catch(e=>{PA(`send heartbeat ack failed`,e.message)})}break;case fA.type:this.setState(1);break;case vA.type:{this.timer2Cancel(),this.setState(7);let e=new yA;await this.sendChunk(e).catch(e=>{PA(`send shutdown ack failed`,e.message)}),this.t2Start(e),this.setState(6)}break;case pA.type:PA(`ErrorChunk`,e.descriptions);break;case lA.type:{if(!this.isServer)return;let t=e.body,n=o(`sha1`,this.hmacKey).update(t.slice(0,4)).digest();if(t?.length!=FA||!t.slice(4).equals(n)){PA(`x State cookie is invalid`);return}let r=Math.floor(Date.now()/1e3),i=t.readUInt32BE(0);if(i<r-IA||i>r){let e=new pA(0,void 0);e.params.push([pA.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(`\0`)))]),await this.sendChunk(e).catch(e=>{PA(`send errorChunk failed`,e.message)});return}let a=new uA;await this.sendChunk(a).catch(e=>{PA(`send cookieAck failed`,e.message)}),this.setState(4)}break;case uA.type:if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4);break;case bA.type:if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1);break;case gA.type:{if(this.associationState!=4)return;let t=e;for(let[e,n]of t.params){let t=NA[e];t&&await this.receiveReconfigParam(t.parse(n))}}break;case sA.type:this.receiveForwardTsnChunk(e)}}getExtensions(e){for(let[t,n]of e)t===tj?this.remotePartialReliability=!0:t===ej&&(this.remoteExtensions=[...n])}async receiveReconfigParam(e){switch(PA(`receiveReconfigParam`,NA[e.type]),e.type){case kA.type:{let t=e,n=new MA(t.requestSequence,jA.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence,await this.sendReconfigParam(n),await Promise.all(t.streams.map(async e=>{delete this.inboundStreams[e],this.outboundStreamSeq[e]&&(this.reconfigQueue.includes(e)||this.reconfigQueue.push(e))})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(t.streams)}break;case MA.type:{let t=e;if(t.result!==jA.ReconfigResultSuccessPerformed)PA(`OutgoingSSNResetRequestParam failed`,Object.keys(jA).find(e=>jA[e]===t.result));else if(t.responseSequence===this.reconfigRequest?.requestSequence){let e=this.reconfigRequest.streams.map(e=>(delete this.outboundStreamSeq[e],e));this.onReconfigStreams.execute(e),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=KA,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case AA.type:{let t=e;this._inboundStreamsCount+=t.newStreams;let n=new MA(t.requestSequence,1);this.reconfigResponseSeq=t.requestSequence,await this.sendReconfigParam(n)}}}receiveDataChunk(e){if(this.sackNeeded=!0,this.markReceived(e.tsn)){this.sackImmediate=!0;return}this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(e.flags&zA)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let t=this.getInboundStream(e.streamId);t.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let e of t.popMessages())this.advertisedRwnd+=e[2].length,this.receive(...e)}async receiveSackChunk(e){if(tS(this.lastSackedTsn,e.cumulativeTsn))return;let t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let n=this.flightSize>=this.cwnd,r=0,i=0;for(;this.sentQueue.length>0&&nS(this.lastSackedTsn,this.sentQueue[0].tsn);){let e=this.sentQueue.shift();r++,e?.acked||(i+=e.bookSize,this.flightSizeDecrease(e)),r===1&&e.sentCount===1&&this.updateRto(t-e.sentTime)}this.sentQueue.length||(this.sentQueue=[]);let a=!1;if(e.gaps.length>0){let t=new Set,n;e.gaps.forEach(r=>{for(let i=r[0];i<r[1]+1;i++)n=(e.cumulativeTsn+i)%YA,t.add(n)});let r=e.cumulativeTsn;for(let e of this.sentQueue){if(tS(e.tsn,n))break;t.has(e.tsn)&&!e.acked&&(i+=e.bookSize,e.acked=!0,this.flightSizeDecrease(e),r=e.tsn)}for(let e of this.sentQueue){if(tS(e.tsn,r))break;t.has(e.tsn)||(e.misses++,e.misses===3&&(e.misses=0,this.maybeAbandon(e)||(e.retransmit=!0),e.acked=!1,this.flightSizeDecrease(e),a=!0))}}this.fastRecoveryExit===void 0?(r&&n&&(this.cwnd<=this.ssthresh?this.cwnd+=Math.min(i,RA):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=RA))),a&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*RA),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):nS(e.cumulativeTsn,this.fastRecoveryExit)&&(this.fastRecoveryExit=void 0),this.sentQueue.length===0?this.timer3Cancel():r>0&&this.timer3Restart(),this.peerAdvertisedRwnd=e.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(e){if(this.sackNeeded=!0,this.sackImmediate=!0,nS(this.lastReceivedTsn,e.cumulativeTsn))return;let t=e=>tS(e,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let e of[...this.sackMisOrdered].sort())if(e===sj(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;this.sackDuplicates=this.sackDuplicates.filter(t),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let[t,n]of e.streams){let e=this.getInboundStream(t);e.streamSequenceNumber=Zx(n,1);for(let t of e.popMessages())this.advertisedRwnd+=t[2].length,this.receive(...t)}Object.values(this.inboundStreams).forEach(e=>{this.advertisedRwnd+=e.pruneChunks(this.lastReceivedTsn)})}updateRto(e){this.srtt?(this.rttvar=(1-GA)*this.rttvar+GA*Math.abs(this.srtt-e),this.srtt=(1-WA)*this.srtt+WA*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(qA,Math.min(this.srtt+4*this.rttvar,JA))}receive(e,t,n){this.onReceive.execute(e,t,n)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new ij),this.inboundStreams[e]}markReceived(e){if(nS(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e))return this.sackDuplicates.push(e),!0;this.sackMisOrdered.add(e);for(let e of[...this.sackMisOrdered].sort())if(e===sj(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;let t=e=>tS(e,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(t),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t)),!1}send=async(e,t,n,{expiry:r,maxRetransmits:i,ordered:a}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let o=a&&this.outboundStreamSeq[e]||0,s=Math.ceil(n.length/RA),c=0,l=[];for(let u=0;u<s;u++){let d=new cA(0,void 0);d.flags=0,a||(d.flags=VA),u===0&&(d.flags|=BA),u===s-1&&(d.flags|=zA),d.tsn=this.localTsn,d.streamId=e,d.streamSeqNum=o,d.protocol=t,d.userData=n.slice(c,c+RA),d.bookSize=d.userData.length,d.expiry=r,d.maxRetransmits=i,c+=RA,this.localTsn=sj(this.localTsn),l.push(d)}for(l.forEach(e=>{this.outboundQueue.push(e)}),a&&(this.outboundStreamSeq[e]=Zx(o,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(e=>{PA(`send forwardTsn failed`,e.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit==null?4*RA:2*RA,t=Math.min(this.flightSize+e,this.cwnd),n=!0;for(let e of this.sentQueue){if(e.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=t)break;this.flightSizeIncrease(e),e.misses=0,e.retransmit=!1,e.sentCount++,await this.sendChunk(e).catch(e=>{PA(`send data failed`,e.message)}),n&&this.timer3Restart()}n=!1}for(;this.outboundQueue.length>0&&this.flightSize<t&&this.peerRwnd>0;){let e=this.outboundQueue.shift();if(!e)break;if(e.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(e);break}this.sentQueue.push(e),this.flightSizeIncrease(e),e.sentCount++,e.sentTime=Date.now()/1e3,await this.sendChunk(e).catch(e=>{PA(`send data outboundQueue failed`,e.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)],t=e.slice(0,QA);this.reconfigQueue=e.slice(QA);let n=new kA(this.reconfigRequestSeq,this.reconfigResponseSeq,oj(this.localTsn),t);this.reconfigRequestSeq=sj(this.reconfigRequestSeq),this.reconfigRequest=n,await this.sendReconfigParam(n),this.timerReconfigHandleStart()}}async sendReconfigParam(e){PA(`sendReconfigParam`,e);let t=new gA;t.params.push([e.type,e.bytes]),await this.sendChunk(t).catch(e=>{PA(`send reconfig failed`,e.message)})}async sendResetRequest(e){PA(`sendResetRequest`,e);let t=new cA(0,void 0);t.streamId=e,this.outboundQueue.push(t),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 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>UA)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{PA(`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 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>HA)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{PA(`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 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*RA),this.cwnd=RA,this.transmit())};timer3Cancel(){this.timer3Handle&&=(clearTimeout(this.timer3Handle),void 0)}timerReconfigHandleStart(){this.isStopped||(this.timerReconfigHandle||=(PA(`timerReconfigHandleStart`,{rto:this.rto}),this.timerReconfigFailures=0,setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)))}timerReconfigHandleExpired=async()=>{if(!this.isStopped){if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>HA)PA(`timerReconfigFailures`,this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(PA(`timerReconfigHandleExpired`,this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(PA(`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),void 0)}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState===4){if(this.flightSize===0&&this.outboundQueue.length===0){let e=new mA,t=Buffer.allocUnsafe(4);t.writeUInt32BE(Math.floor(Date.now()/1e3),0),e.params.push([1,t]),await this.sendChunk(e).catch(e=>{PA(`send heartbeat failed`,e.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw Error(`heartbeat interval must be > 0`);this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){tS(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,t={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let n=this.sentQueue.shift();this.advancedPeerAckTsn=n.tsn,e++,n.flags&VA||(t[n.streamId]=n.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new sA(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(t).map(([e,t])=>[Number(e),t]))}maybeAbandon(e){if(e.abandoned)return!0;if(!(e.maxRetransmits&&e.maxRetransmits<e.sentCount||e.expiry&&e.expiry<Date.now()/1e3))return!1;let t=this.sentQueue.findIndex(t=>t.type===e.type);for(let e=t;e>=0;e--){let t=this.sentQueue[e];if(t.abandoned=!0,t.retransmit=!1,t.flags&zA)break}for(let e=t;e<this.sentQueue.length;e++){let t=this.sentQueue[e];if(t.abandoned=!0,t.retransmit=!1,t.flags&zA)break}return!0}static getCapabilities(){return new aj(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 iA;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),PA(`send init`,e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(e){PA(`send init failed`,e.message)}}setExtensions(e){let t=[];this.localPartialReliability&&(e.push([tj,Buffer.from(``)]),t.push(sA.type)),t.push(oA.type),e.push([ej,Buffer.from(t)])}async sendChunk(e){if(this.state===`closed`)return;if(this.remotePort===void 0)throw Error(`invalid remote port`);let t=EA(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}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),void 0),this.setConnectionState(`closed`),this.removeAllListeners())}setConnectionState(e){this.state=e,PA(`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),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 fA;await this.sendChunk(e).catch(e=>{PA(`send abort failed`,e.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},ij=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(e){if(this.reassembly.length===0||tS(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(let[t,n]of DA(this.reassembly)){if(n.tsn===e.tsn)throw Error(`duplicate chunk in reassembly`);if(tS(n.tsn,e.tsn)){this.reassembly.splice(t,0,e);break}}}*popMessages(){let e=0,t,n,r;for(;e<this.reassembly.length;){let i=this.reassembly[e];if(t===void 0){if(r=!(i.flags&VA),!(i.flags&BA)){if(r)break;e++;continue}if(r&&eS(i.streamSeqNum,this.streamSequenceNumber))break;n=i.tsn,t=e}else if(i.tsn!==n){if(r)break;t=void 0,e++;continue}if(i.flags&zA){let n=this.reassembly.slice(t,e+1).map(e=>e.userData).reduce((e,t)=>(e.push(t),e.push(Buffer.from(``)),e),[]);n.pop();let a=Buffer.concat(n);this.reassembly=[...this.reassembly.slice(0,t),...this.reassembly.slice(e+1)],r&&i.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=Zx(this.streamSequenceNumber,1)),e=t,yield[i.streamId,i.protocol,a]}else e++;n=sj(n)}}pruneChunks(e){let t=-1,n=0;for(let[r,i]of this.reassembly.entries())if(nS(e,i.tsn))t=r,n+=i.userData.length;else break;return this.reassembly=this.reassembly.slice(t+1),n}},aj=class{constructor(e){this.maxMessageSize=e}};function oj(e){return(e-1)%YA}function sj(e){return(e+1)%YA}var cj=sS(`werift:packages/webrtc/src/transport/sctp.ts`),lj=65536,uj=class e{constructor(e=5e3,t=lj){this.port=e,this.maxMessageSize=t}dtlsTransport;sctp;onDataChannel=new $;id=l().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=lj;dataChannelQueue=[];dataChannelId;eventDisposer=[];get transport(){return this.dtlsTransport}setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(e=>e()),this.dtlsTransport=e,this.sctp=new rj(new fj(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(e=>{e.forEach(e=>{let t=this.dataChannels[e];t&&(t.setReadyState(`closing`),t.setReadyState(`closed`),delete this.dataChannels[e])})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(e=>{e.negotiated&&e.readyState!==`open`&&e.setReadyState(`open`)}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(e=>{e.setReadyState(`closed`)}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(e=>{e===`closed`&&this.sctp.setState(1)})].map(e=>e.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(t=>t.label===e)}datachannelReceive=async(e,t,n)=>{if(t===IO&&n.length>0)switch(cj(`DCEP`,e,t,n),n[0]){case PO:{if(n.length<12){cj(`DATA_CHANNEL_OPEN data.length not enough`);return}if(Object.keys(this.dataChannels).includes(e.toString()))cj(`datachannel already opened`,`retransmit ack`);else{let t=n.readUInt8(1),r=n.readUInt32BE(4),i=n.readUInt16BE(8),a=n.readUInt16BE(10),o=12,s=n.slice(o,o+i).toString(`utf8`);o+=i;let c=n.slice(o,o+a).toString(`utf8`);cj(`DATA_CHANNEL_OPEN`,{channelType:t,reliability:r,streamId:e,label:s,protocol:c});let l=(t&3)==1?r:void 0,u=(t&3)==2?r:void 0,d=new hO({label:s,ordered:!(t&128),maxPacketLifeTime:u,maxRetransmits:l,protocol:c,id:e}),f=new mO(this,d,!1);f.isCreatedByRemote=!0,this.dataChannels[e]=f,this.onDataChannel.execute(f),f.setReadyState(`open`)}let t=this.dataChannels[e],r=Buffer.allocUnsafe(1);r.writeUInt8(NO,0),this.dataChannelQueue.push([t,IO,r]),await this.dataChannelFlush()}break;case NO:{cj(`DATA_CHANNEL_ACK`,e,t);let n=this.dataChannels[e];if(!n)throw Error(`channel not found`);n.setReadyState(`open`)}}else{let r=this.dataChannels[e];if(r){let e=(()=>{switch(t){case LO:return n.toString(`utf8`);case zO:return``;case RO:return n;case BO:return Buffer.from([]);default:throw Error()}})();r.messagesReceived++,r.bytesReceived+=n.length,r.onMessage.execute(e),r.emit(`message`,{data:e}),r.onmessage&&r.onmessage({data:e})}}};dataChannelAddNegotiated(e){if(e.id==null||this.dataChannels[e.id])throw Error();this.dataChannels[e.id]=e,this.sctp.associationState===4&&e.setReadyState(`open`)}dataChannelOpen(e){if(e.id!==void 0){if(this.dataChannels[e.id])throw Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let t=FO,n=0;e.ordered||(t=128),e.maxRetransmits===null?e.maxPacketLifeTime!==null&&(t|=2,n=e.maxPacketLifeTime):(t|=1,n=e.maxRetransmits);let r=Buffer.allocUnsafe(12);r.writeUInt8(PO,0),r.writeUInt8(t,1),r.writeUInt16BE(0,2),r.writeUInt32BE(n,4),r.writeUInt16BE(e.label.length,8),r.writeUInt16BE(e.protocol.length,10);let i=Buffer.concat([r,Buffer.from(e.label,`utf8`),Buffer.from(e.protocol,`utf8`)]);this.dataChannelQueue.push([e,IO,i]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,t,n]=this.dataChannelQueue.shift(),r=e.id;if(r===void 0){for(r=this.dataChannelId;Object.keys(this.dataChannels).includes(r.toString());)r+=2;this.dataChannels[r]=e,e.setId(r)}if(t===IO)await this.sctp.send(r,t,n,{ordered:!0});else{let i=e.maxPacketLifeTime===null?void 0:Date.now()+e.maxPacketLifeTime/1e3;await this.sctp.send(r,t,n,{expiry:i,maxRetransmits:e.maxRetransmits??void 0,ordered:e.ordered}),e.addBufferedAmount(-n.length)}}this.dataChannelQueue=[]}}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,t)=>{let n=Buffer.isBuffer(t)?t:Buffer.from(t),r=pO(t);return this.assertSendableMessageSize(r),e.addBufferedAmount(r),this.dataChannelQueue.push(typeof t==`string`?[e,LO,n]:[e,RO,n]),this.sctp.associationState!==4&&cj(`sctp not established`,this.sctp.associationState),this.dataChannelFlush(),r};getCapabilities(){return e.getCapabilities(this.maxMessageSize)}static getCapabilities(e=lj){return new dj(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??65536}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.dataChannelId=+!this.isServer,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(t=>t[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id),e.id!==void 0&&delete this.dataChannels[e.id],e.setReadyState(`closed`)))}},dj=class{constructor(e){this.maxMessageSize=e}},fj=class{constructor(e){this.dtls=e}set onData(e){this.dtls.dataReceiver=e}send=e=>this.dtls.sendData(e);close(){}},pj=class e{version=0;origin;name=`-`;time=`0 0`;host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];cachedJson;static parse(t){let[n,r]=yj(t),i=new e;n.forEach(e=>{if(e.startsWith(`v=`))i.version=Number.parseInt(e.slice(2),10);else if(e.startsWith(`o=`))i.origin=e.slice(2);else if(e.startsWith(`s=`))i.name=e.slice(2);else if(e.startsWith(`c=`))i.host=gj(e.slice(2));else if(e.startsWith(`t=`))i.time=e.slice(2);else if(e.startsWith(`a=`)){let[t,n]=bj(e);switch(t){case`fingerprint`:{let[e,t]=n?.split(` `)||[];i.dtlsFingerprints.push(new Bk(e,t))}break;case`ice-lite`:i.iceLite=!0;break;case`ice-options`:i.iceOptions=n;break;case`ice-pwd`:i.icePassword=n;break;case`ice-ufrag`:i.iceUsernameFragment=n;break;case`group`:xj(i.group,n);break;case`msid-semantic`:xj(i.msidSemantic,n);break;case`setup`:i.dtlsRole=WO[n];break;case`extmap-allow-mixed`:i.extMapAllowMixed=!0}}});let a=i.group.find(e=>e.semantic===`BUNDLE`);return r.forEach(e=>{let t=e[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!t)throw Error(`m line not found`);let n=t[1],r=t[4].split(` `),o=[`audio`,`video`].includes(n)?r.map(e=>Number(e)):void 0,s=new mj(n,Number.parseInt(t[2]),t[3],o||r);if(s.dtlsParams=new Vk([...i.dtlsFingerprints],i.dtlsRole),s.iceParams=new tA({iceLite:i.iceLite,usernameFragment:i.iceUsernameFragment,password:i.icePassword}),s.iceOptions=i.iceOptions,i.media.push(s),e.slice(1).forEach(e=>{if(e.startsWith(`c=`))s.host=gj(e.slice(2));else if(e.startsWith(`a=`)){let[t,n]=bj(e);switch(t){case`candidate`:if(!n)throw Error();s.iceCandidates.push(Sj(n));break;case`end-of-candidates`:s.iceCandidatesComplete=!0;break;case`extmap`:{let[e,t]=n.split(` `);e.includes(`/`)&&([e]=e.split(`/`)),s.rtp.headerExtensions.push(new xO({id:Number.parseInt(e),uri:t}))}break;case`fingerprint`:{if(!n)throw Error();let[e,t]=n.split(` `);s.dtlsParams?.fingerprints.push(new Bk(e,t))}break;case`ice-options`:s.iceOptions=n;break;case`ice-pwd`:s.iceParams.password=n;break;case`ice-ufrag`:s.iceParams.usernameFragment=n;break;case`ice-lite`:s.iceParams.iceLite=!0;break;case`max-message-size`:s.sctpCapabilities=new dj(Number.parseInt(n,10));break;case`mid`:s.rtp.muxId=n;break;case`msid`:s.msids.push(n);break;case`rtcp`:{let[e,t]=uO(n,` `);s.rtcpPort=Number.parseInt(e),s.rtcpHost=gj(t)}break;case`rtcp-mux`:s.rtcpMux=!0;break;case`setup`:s.dtlsParams.role=WO[n];break;case`recvonly`:case`sendonly`:case`sendrecv`:case`inactive`:s.direction=t;break;case`rtpmap`:{let[e,t]=uO(n,` `),[r,i,a]=t.split(`/`),o;s.kind===`audio`&&(o=a?Number.parseInt(a):1);let c=new bO({mimeType:s.kind+`/`+r,channels:o,clockRate:Number.parseInt(i),payloadType:Number.parseInt(e)});s.rtp.codecs.push(c)}break;case`sctpmap`:{if(!n)throw Error();let[e,t]=uO(n,` `);s.sctpMap[Number.parseInt(e)]=t,s.sctpPort=Number.parseInt(e)}break;case`sctp-port`:if(!n)throw Error();s.sctpPort=Number.parseInt(n);break;case`ssrc`:{let[e,t]=uO(n,` `),r=Number.parseInt(e),[i,a]=uO(t,`:`),o=s.ssrc.find(e=>e.ssrc===r);o||(o=new Ej({ssrc:r}),s.ssrc.push(o)),KO.includes(i)&&(o[i]=a)}break;case`ssrc-group`:xj(s.ssrcGroup,n);break;case`rid`:{let[e,t]=uO(n,` `);s.simulcastParameters.push(new TO({rid:e,direction:t}))}}}}),(!s.iceParams.usernameFragment||!s.iceParams.password)&&s.rtp.muxId&&a&&a.items.includes(s.rtp.muxId))for(let e=0;e<a.items.length;e++){if(!a.items.includes(e.toString()))continue;let t=i.media[e];if(t.iceParams?.usernameFragment&&t.iceParams.password){s.iceParams={...t.iceParams};break}}s.dtlsParams.role||(s.dtlsParams=void 0);let c=e=>s.rtp.codecs.find(t=>t.payloadType===e);e.slice(1).forEach(e=>{if(e.startsWith(`a=`)){let[t,n]=bj(e);if(t===`fmtp`){let[e,t]=uO(n,` `),r=c(Number(e));r.parameters=t}else if(t===`rtcp-fb`){let[e,t,r]=n.split(` `);s.rtp.codecs.forEach(n=>{[`*`,n.payloadType.toString()].includes(e)&&n.rtcpFeedback.push(new SO({type:t,parameter:r}))})}}})}),i}webrtcTrackId(e){if(e.msid?.includes(` `)){let t=e.msid.split(` `);for(let e of this.msidSemantic)if(e.semantic===`WMS`&&(e.items.includes(t[0])||e.items.includes(`*`)))return t[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${_j(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(t=>e.push(`a=group:${t.str}`)),this.extMapAllowMixed&&e.push(`a=extmap-allow-mixed`),this.msidSemantic.forEach(t=>e.push(`a=msid-semantic:${t.str}`));let t=this.media.map(e=>e.toString()).join(``);return e.join(`\r
|
|
139
|
+
`),i.prototype[e]=t.toFunction({assertSize:o})}),t.exports=i;function o(e,t){if(e>t)throw new r(e,t)}})),rE=R(((e,t)=>{var n=zT(),r=JT(),i=YT(),a=XT(),o=ZT(),s=QT(),c=$T(),l=eE(),u=tE(),{encode:d}=KT(),{decode:f}=GT(),{encodingLength:p}=qT(),m=nE(),h=RT(),g={array:r,bool:a,buffer:i,reserved:o,string:s,when:l,select:u};for(let e of Object.keys(c))g[e]=c[e];var _=Symbol(`schema`);function v(e){let t=new n({readableObjectMode:!1,writableObjectMode:!0,transform:b});return t[_]=e,t}function y(e){let t=null,r=Buffer.isBuffer(e);r||(t=e);let i=new n({transform:x,readableObjectMode:!0,writableObjectMode:!1});return i[_]=t,r&&i.append(e),i}function b(e,t,n){try{d(e,this[_],this);let t=this.slice();this.consume(t.length),n(null,t)}catch(e){n(e)}}function x(e,t,n){this.append(e);try{for(;this.length>0;){let e=new m(this),t=f(e,this[_]);e.commit(),this.push(t)}n()}catch(e){e instanceof h?n():n(e)}}t.exports={createEncodeStream:v,createDecodeStream:y,encode:d,decode:f,encodingLength:p,createEncode:v,createDecode:y,types:g,BinaryStream:n,NotEnoughDataError:h}})),iE=B(Fd(),1),Q=rE(),aE=T&&typeof T==`object`&&`webcrypto`in T?T.webcrypto:T&&typeof T==`object`&&`randomBytes`in T?T:void 0;function oE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function sE(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function cE(e,...t){if(!oE(e))throw Error(`Uint8Array expected`);if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length `+t+`, got length=`+e.length)}function lE(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.createHasher`);sE(e.outputLen),sE(e.blockLen)}function uE(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function dE(e,t){cE(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function fE(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function pE(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function mE(e,t){return e<<32-t|e>>>t}var hE=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,gE=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function _E(e){if(cE(e),hE)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=gE[e[n]];return t}var vE={_0:48,_9:57,A:65,F:70,a:97,f:102};function yE(e){if(e>=vE._0&&e<=vE._9)return e-vE._0;if(e>=vE.A&&e<=vE.F)return e-(vE.A-10);if(e>=vE.a&&e<=vE.f)return e-(vE.a-10)}function bE(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(hE)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw Error(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=yE(e.charCodeAt(i)),a=yE(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw Error(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function xE(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function SE(e){return typeof e==`string`&&(e=xE(e)),cE(e),e}function CE(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];cE(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var wE=class{};function TE(e){let t=t=>e().update(SE(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function EE(e=32){if(aE&&typeof aE.getRandomValues==`function`)return aE.getRandomValues(new Uint8Array(e));if(aE&&typeof aE.randomBytes==`function`)return Uint8Array.from(aE.randomBytes(e));throw Error(`crypto.getRandomValues must be defined`)}var DE=BigInt(0),OE=BigInt(1);function kE(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function AE(e,t,n=``){let r=oE(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function jE(e){let t=e.toString(16);return t.length&1?`0`+t:t}function ME(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?DE:BigInt(`0x`+e)}function NE(e){return ME(_E(e))}function PE(e){return cE(e),ME(_E(Uint8Array.from(e).reverse()))}function FE(e,t){return bE(e.toString(16).padStart(t*2,`0`))}function IE(e,t){return FE(e,t).reverse()}function LE(e,t,n){let r;if(typeof t==`string`)try{r=bE(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(oE(t))r=Uint8Array.from(t);else throw Error(e+` must be hex string or Uint8Array`);let i=r.length;if(typeof n==`number`&&i!==n)throw Error(e+` of length `+n+` expected, got `+i);return r}var RE=e=>typeof e==`bigint`&&DE<=e;function zE(e,t,n){return RE(e)&&RE(t)&&RE(n)&&t<=e&&e<n}function BE(e,t,n,r){if(!zE(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function VE(e){let t=0;for(;e>DE;e>>=OE,t+=1);return t}var HE=e=>(OE<<BigInt(e))-OE;function UE(e,t,n){if(typeof e!=`number`||e<2)throw Error(`hashLen must be a number`);if(typeof t!=`number`||t<2)throw Error(`qByteLen must be a number`);if(typeof n!=`function`)throw Error(`hmacFn must be a function`);let r=e=>new Uint8Array(e),i=e=>Uint8Array.of(e),a=r(e),o=r(e),s=0,c=()=>{a.fill(1),o.fill(0),s=0},l=(...e)=>n(o,a,...e),u=(e=r(0))=>{o=l(i(0),e),a=l(),e.length!==0&&(o=l(i(1),e),a=l())},d=()=>{if(s++>=1e3)throw Error(`drbg: tried 1000 values`);let e=0,n=[];for(;e<t;){a=l();let t=a.slice();n.push(t),e+=a.length}return CE(...n)};return(e,t)=>{c(),u(e);let n;for(;!(n=t(d()));)u();return c(),n}}function WE(e,t,n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function GE(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e(n,...r);return t.set(n,a),a}}var KE=BigInt(0),qE=BigInt(1),JE=BigInt(2),YE=BigInt(3),XE=BigInt(4),ZE=BigInt(5),QE=BigInt(7),$E=BigInt(8),eD=BigInt(9),tD=BigInt(16);function nD(e,t){let n=e%t;return n>=KE?n:t+n}function rD(e,t){if(e===KE)throw Error(`invert: expected non-zero number`);if(t<=KE)throw Error(`invert: expected positive modulus, got `+t);let n=nD(e,t),r=t,i=KE,a=qE,o=qE,s=KE;for(;n!==KE;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==qE)throw Error(`invert: does not exist`);return nD(i,t)}function iD(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function aD(e,t){let n=(e.ORDER+qE)/XE,r=e.pow(t,n);return iD(e,r,t),r}function oD(e,t){let n=(e.ORDER-ZE)/$E,r=e.mul(t,JE),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,JE),i),s=e.mul(a,e.sub(o,e.ONE));return iD(e,s,t),s}function sD(e){let t=gD(e),n=cD(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+QE)/tD;return(e,t)=>{let n=e.pow(t,o),s=e.mul(n,r),c=e.mul(n,i),l=e.mul(n,a),u=e.eql(e.sqr(s),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,s,u),s=e.cmov(l,c,d);let f=e.eql(e.sqr(s),t),p=e.cmov(n,s,f);return iD(e,p,t),p}}function cD(e){if(e<YE)throw Error(`sqrt is not defined for small field`);let t=e-qE,n=0;for(;t%JE===KE;)t/=JE,n++;let r=JE,i=gD(e);for(;mD(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return aD;let a=i.pow(r,t),o=(t+qE)/JE;return function(e,r){if(e.is0(r))return r;if(mD(e,r)!==1)throw Error(`Cannot find square root`);let i=n,s=e.mul(e.ONE,a),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw Error(`Cannot find square root`);let r=qE<<BigInt(i-t-1),a=e.pow(s,r);i=t,s=e.sqr(a),c=e.mul(c,s),l=e.mul(l,a)}return l}}function lD(e){return e%XE===YE?aD:e%$E===ZE?oD:e%tD===eD?sD(e):cD(e)}var uD=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function dD(e){return WE(e,uD.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function fD(e,t,n){if(n<KE)throw Error(`invalid exponent, negatives unsupported`);if(n===KE)return e.ONE;if(n===qE)return t;let r=e.ONE,i=t;for(;n>KE;)n&qE&&(r=e.mul(r,i)),i=e.sqr(i),n>>=qE;return r}function pD(e,t,n=!1){let r=Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),a=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),a),r}function mD(e,t){let n=(e.ORDER-qE)/JE,r=e.pow(t,n),i=e.eql(r,e.ONE),a=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function hD(e,t){t!==void 0&&sE(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function gD(e,t,n=!1,r={}){if(e<=KE)throw Error(`invalid field: expected ORDER > 0, got `+e);let i,a,o=!1,s;if(typeof t==`object`&&t){if(r.sqrt||n)throw Error(`cannot specify opts in two arguments`);let e=t;e.BITS&&(i=e.BITS),e.sqrt&&(a=e.sqrt),typeof e.isLE==`boolean`&&(n=e.isLE),typeof e.modFromBytes==`boolean`&&(o=e.modFromBytes),s=e.allowedLengths}else typeof t==`number`&&(i=t),r.sqrt&&(a=r.sqrt);let{nBitLength:c,nByteLength:l}=hD(e,i);if(l>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);let u,d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:HE(c),ZERO:KE,ONE:qE,allowedLengths:s,create:t=>nD(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return KE<=t&&t<e},is0:e=>e===KE,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&qE)===qE,neg:t=>nD(-t,e),eql:(e,t)=>e===t,sqr:t=>nD(t*t,e),add:(t,n)=>nD(t+n,e),sub:(t,n)=>nD(t-n,e),mul:(t,n)=>nD(t*n,e),pow:(e,t)=>fD(d,e,t),div:(t,n)=>nD(t*rD(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>rD(t,e),sqrt:a||(t=>(u||=lD(e),u(d,t))),toBytes:e=>n?IE(e,l):FE(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw Error(`Field.fromBytes: expected `+s+` bytes, got `+t.length);let e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw Error(`Field.fromBytes: expected `+l+` bytes, got `+t.length);let i=n?PE(t):NE(t);if(o&&(i=nD(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>pD(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function _D(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function vD(e){let t=_D(e);return t+Math.ceil(t/2)}function yD(e,t,n=!1){let r=e.length,i=_D(t),a=vD(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=nD(n?PE(e):NE(e),t-qE)+qE;return n?IE(o,i):FE(o,i)}function bD(e,t,n,r){if(typeof e.setBigUint64==`function`)return e.setBigUint64(t,n,r);let i=BigInt(32),a=BigInt(4294967295),o=Number(n>>i&a),s=Number(n&a),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,s,r)}function xD(e,t,n){return e&t^~e&n}function SD(e,t,n){return e&t^e&n^t&n}var CD=class extends wE{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=pE(this.buffer)}update(e){uE(this),e=SE(e),cE(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=pE(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){uE(this),dE(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,fE(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;bD(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=pE(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen should be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},wD=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),TD=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),ED=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),DD=BigInt(2**32-1),OD=BigInt(32);function kD(e,t=!1){return t?{h:Number(e&DD),l:Number(e>>OD&DD)}:{h:Number(e>>OD&DD)|0,l:Number(e&DD)|0}}function AD(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=kD(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var jD=(e,t,n)=>e>>>n,MD=(e,t,n)=>e<<32-n|t>>>n,ND=(e,t,n)=>e>>>n|t<<32-n,PD=(e,t,n)=>e<<32-n|t>>>n,FD=(e,t,n)=>e<<64-n|t>>>n-32,ID=(e,t,n)=>e>>>n-32|t<<64-n;function LD(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var RD=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),zD=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,BD=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),VD=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,HD=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),UD=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,WD=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]),GD=new Uint32Array(64),KD=class extends CD{constructor(e=32){super(64,e,8,!1),this.A=wD[0]|0,this.B=wD[1]|0,this.C=wD[2]|0,this.D=wD[3]|0,this.E=wD[4]|0,this.F=wD[5]|0,this.G=wD[6]|0,this.H=wD[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)GD[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=GD[e-15],n=GD[e-2],r=mE(t,7)^mE(t,18)^t>>>3,i=mE(n,17)^mE(n,19)^n>>>10;GD[e]=i+GD[e-7]+r+GD[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=mE(o,6)^mE(o,11)^mE(o,25),u=l+t+xD(o,s,c)+WD[e]+GD[e]|0,d=(mE(n,2)^mE(n,13)^mE(n,22))+SD(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){fE(GD)}destroy(){this.set(0,0,0,0,0,0,0,0),fE(this.buffer)}},qD=AD(`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`.split(`.`).map(e=>BigInt(e))),JD=qD[0],YD=qD[1],XD=new Uint32Array(80),ZD=new Uint32Array(80),QD=class extends CD{constructor(e=64){super(128,e,16,!1),this.Ah=ED[0]|0,this.Al=ED[1]|0,this.Bh=ED[2]|0,this.Bl=ED[3]|0,this.Ch=ED[4]|0,this.Cl=ED[5]|0,this.Dh=ED[6]|0,this.Dl=ED[7]|0,this.Eh=ED[8]|0,this.El=ED[9]|0,this.Fh=ED[10]|0,this.Fl=ED[11]|0,this.Gh=ED[12]|0,this.Gl=ED[13]|0,this.Hh=ED[14]|0,this.Hl=ED[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:h}=this;return[e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h]}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let n=0;n<16;n++,t+=4)XD[n]=e.getUint32(t),ZD[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=XD[e-15]|0,n=ZD[e-15]|0,r=ND(t,n,1)^ND(t,n,8)^jD(t,n,7),i=PD(t,n,1)^PD(t,n,8)^MD(t,n,7),a=XD[e-2]|0,o=ZD[e-2]|0,s=ND(a,o,19)^FD(a,o,61)^jD(a,o,6),c=BD(i,PD(a,o,19)^ID(a,o,61)^MD(a,o,6),ZD[e-7],ZD[e-16]),l=VD(c,r,s,XD[e-7],XD[e-16]);XD[e]=l|0,ZD[e]=c|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:h,Hh:g,Hl:_}=this;for(let e=0;e<80;e++){let t=ND(u,d,14)^ND(u,d,18)^FD(u,d,41),v=PD(u,d,14)^PD(u,d,18)^ID(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=HD(_,v,b,YD[e],ZD[e]),S=UD(x,g,t,y,JD[e],XD[e]),C=x|0,w=ND(n,r,28)^FD(n,r,34)^FD(n,r,39),T=PD(n,r,28)^ID(n,r,34)^ID(n,r,39),E=n&i^n&o^i&o,D=r&a^r&s^a&s;g=m|0,_=h|0,m=f|0,h=p|0,f=u|0,p=d|0,{h:u,l:d}=LD(c|0,l|0,S|0,C|0),c=o|0,l=s|0,o=i|0,s=a|0,i=n|0,a=r|0;let O=RD(C,T,D);n=zD(O,S,w,E),r=O|0}({h:n,l:r}=LD(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=LD(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=LD(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=LD(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=LD(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=LD(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=LD(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=LD(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){fE(XD,ZD)}destroy(){fE(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},$D=class extends QD{constructor(){super(48),this.Ah=TD[0]|0,this.Al=TD[1]|0,this.Bh=TD[2]|0,this.Bl=TD[3]|0,this.Ch=TD[4]|0,this.Cl=TD[5]|0,this.Dh=TD[6]|0,this.Dl=TD[7]|0,this.Eh=TD[8]|0,this.El=TD[9]|0,this.Fh=TD[10]|0,this.Fl=TD[11]|0,this.Gh=TD[12]|0,this.Gl=TD[13]|0,this.Hh=TD[14]|0,this.Hl=TD[15]|0}},eO=TE(()=>new KD),tO=TE(()=>new QD),nO=TE(()=>new $D),rO=class extends wE{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,lE(e);let n=SE(t);if(this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),fE(i)}update(e){return uE(this),this.iHash.update(e),this}digestInto(e){uE(this),cE(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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},iO=(e,t,n)=>new rO(e,t).update(n).digest();iO.create=(e,t)=>new rO(e,t);var aO=BigInt(0),oO=BigInt(1);function sO(e,t){let n=t.negate();return e?n:t}function cO(e,t){let n=pD(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function lO(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function uO(e,t){lO(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:HE(e),maxNumber:i,shiftBy:BigInt(e)}}function dO(e,t,n){let{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n,s=Number(e&i),c=e>>o;s>r&&(s-=a,c+=oO);let l=t*r,u=l+Math.abs(s)-1,d=s===0,f=s<0,p=t%2!=0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function fO(e,t){if(!Array.isArray(e))throw Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function pO(e,t){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw Error(`invalid scalar at index `+n)})}var mO=new WeakMap,hO=new WeakMap;function gO(e){return hO.get(e)||1}function _O(e){if(e!==aO)throw Error(`invalid wNAF`)}var vO=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>aO;)t&oO&&(n=n.add(r)),r=r.double(),t>>=oO;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=uO(t,this.bits),i=[],a=e,o=a;for(let e=0;e<n;e++){o=a,i.push(o);for(let e=1;e<r;e++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw Error(`invalid scalar`);let r=this.ZERO,i=this.BASE,a=uO(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=dO(n,e,a);n=o,c?i=i.add(sO(u,t[d])):r=r.add(sO(l,t[s]))}return _O(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=uO(e,this.bits);for(let e=0;e<i.windows&&n!==aO;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=dO(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return _O(n),r}getPrecomputes(e,t,n){let r=mO.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),mO.set(t,r))),r}cached(e,t,n){let r=gO(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=gO(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){lO(t,this.bits),hO.set(e,t),mO.delete(e)}hasCache(e){return gO(e)!==1}};function yO(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>aO||r>aO;)n&oO&&(a=a.add(i)),r&oO&&(o=o.add(i)),i=i.double(),n>>=oO,r>>=oO;return{p1:a,p2:o}}function bO(e,t,n,r){fO(n,e),pO(r,t);let i=n.length,a=r.length;if(i!==a)throw Error(`arrays of points and scalars must have equal length`);let o=e.ZERO,s=VE(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=HE(c),u=Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c,f=o;for(let e=d;e>=0;e-=c){u.fill(o);for(let t=0;t<a;t++){let i=r[t],a=Number(i>>BigInt(e)&l);u[a]=u[a].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(f=f.add(t),e!==0)for(let e=0;e<c;e++)f=f.double()}return f}function xO(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return dD(t),t}return gD(e,{isLE:n})}function SO(e,t,n={},r){if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(typeof n==`bigint`&&n>aO))throw Error(`CURVE.${e} must be positive bigint`)}let i=xO(t.p,n.Fp,r),a=xO(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}var CO=(e,t)=>(e+(e>=0?t:-t)/AO)/t;function wO(e,t,n){let[[r,i],[a,o]]=t,s=CO(o*e,n),c=CO(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<OO,f=u<OO;d&&(l=-l),f&&(u=-u);let p=HE(Math.ceil(VE(n)/2))+kO;if(l<OO||l>=p||u<OO||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}function TO(e){if(![`compact`,`recovered`,`der`].includes(e))throw Error(`Signature format must be "compact", "recovered", or "der"`);return e}function EO(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return kE(n.lowS,`lowS`),kE(n.prehash,`prehash`),n.format!==void 0&&TO(n.format),n}var DO={Err:class extends Error{constructor(e=``){super(e)}},_tlv:{encode:(e,t)=>{let{Err:n}=DO;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length&1)throw new n(`tlv.encode: unpadded data`);let r=t.length/2,i=jE(r);if(i.length/2&128)throw new n(`tlv.encode: long form length too big`);let a=r>127?jE(i.length/2|128):``;return jE(e)+a+i+t},decode(e,t){let{Err:n}=DO,r=0;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length<2||t[r++]!==e)throw new n(`tlv.decode: wrong tlv`);let i=t[r++],a=!!(i&128),o=0;if(!a)o=i;else{let e=i&127;if(!e)throw new n(`tlv.decode(long): indefinite length not supported`);if(e>4)throw new n(`tlv.decode(long): byte length is too big`);let a=t.subarray(r,r+e);if(a.length!==e)throw new n(`tlv.decode: length bytes not complete`);if(a[0]===0)throw new n(`tlv.decode(long): zero leftmost byte`);for(let e of a)o=o<<8|e;if(r+=e,o<128)throw new n(`tlv.decode(long): not minimal encoding`)}let s=t.subarray(r,r+o);if(s.length!==o)throw new n(`tlv.decode: wrong value length`);return{v:s,l:t.subarray(r+o)}}},_int:{encode(e){let{Err:t}=DO;if(e<OO)throw new t(`integer: negative integers are not allowed`);let n=jE(e);if(Number.parseInt(n[0],16)&8&&(n=`00`+n),n.length&1)throw new t(`unexpected DER parsing assertion: unpadded hex`);return n},decode(e){let{Err:t}=DO;if(e[0]&128)throw new t(`invalid signature integer: negative`);if(e[0]===0&&!(e[1]&128))throw new t(`invalid signature integer: unnecessary leading zero`);return NE(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=DO,i=LE(`signature`,e),{v:a,l:o}=r.decode(48,i);if(o.length)throw new t(`invalid signature: left bytes after parsing`);let{v:s,l:c}=r.decode(2,a),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t(`invalid signature: left bytes after parsing`);return{r:n.decode(s),s:n.decode(l)}},hexFromSig(e){let{_tlv:t,_int:n}=DO,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},OO=BigInt(0),kO=BigInt(1),AO=BigInt(2),jO=BigInt(3),MO=BigInt(4);function NO(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=LE(`private key`,t);try{r=e.fromBytes(i)}catch{throw Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw Error(`invalid private key: out of range [1..N-1]`);return r}function PO(e,t={}){let n=SO(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;WE(t,{},{allowInfinityPoint:`boolean`,clearCofactor:`function`,isTorsionFree:`function`,fromBytes:`function`,toBytes:`function`,endo:`object`,wrapPrivateKey:`boolean`});let{endo:c}=t;if(c&&(!r.is0(a.a)||typeof c.beta!=`bigint`||!Array.isArray(c.basises)))throw Error(`invalid endo: expected "beta": bigint and "basises": array`);let l=IO(r,i);function u(){if(!r.isOdd)throw Error(`compression is not supported: Field does not have .isOdd()`)}function d(e,t,n){let{x:i,y:a}=t.toAffine(),o=r.toBytes(i);return kE(n,`isCompressed`),n?(u(),CE(FO(!r.isOdd(a)),o)):CE(Uint8Array.of(4),o,r.toBytes(a))}function f(e){AE(e,void 0,`Point`);let{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,a=e[0],o=e.subarray(1);if(i===t&&(a===2||a===3)){let e=r.fromBytes(o);if(!r.isValid(e))throw Error(`bad point: is not on curve, wrong x`);let t=h(e),n;try{n=r.sqrt(t)}catch(e){let t=e instanceof Error?`: `+e.message:``;throw Error(`bad point: is not on curve, sqrt error`+t)}u();let i=r.isOdd(n);return(a&1)==1!==i&&(n=r.neg(n)),{x:e,y:n}}if(i===n&&a===4){let e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,e*2));if(!g(t,n))throw Error(`bad point: is not on curve`);return{x:t,y:n}}throw Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}let p=t.toBytes||d,m=t.fromBytes||f;function h(e){let t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,a.a)),a.b)}function g(e,t){let n=r.sqr(t),i=h(e);return r.eql(n,i)}if(!g(a.Gx,a.Gy))throw Error(`bad curve params: generator point`);let _=r.mul(r.pow(a.a,jO),MO),v=r.mul(r.sqr(a.b),BigInt(27));if(r.is0(r.add(_,v)))throw Error(`bad curve params: a or b`);function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof T))throw Error(`ProjectivePoint expected`)}function x(e){if(!c||!c.basises)throw Error(`no endo`);return wO(e,c.basises,i.ORDER)}let S=GE((e,t)=>{let{X:n,Y:i,Z:a}=e;if(r.eql(a,r.ONE))return{x:n,y:i};let o=e.is0();t??=o?r.ONE:r.inv(a);let s=r.mul(n,t),c=r.mul(i,t),l=r.mul(a,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw Error(`invZ was invalid`);return{x:s,y:c}}),C=GE(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw Error(`bad point: ZERO`)}let{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error(`bad point: x or y not field elements`);if(!g(n,i))throw Error(`bad point: equation left != right`);if(!e.isTorsionFree())throw Error(`bad point: not in prime-order subgroup`);return!0});function w(e,t,n,i,a){return n=new T(r.mul(n.X,e),n.Y,n.Z),t=sO(i,t),n=sO(a,n),t.add(n)}class T{constructor(e,t,n){this.X=y(`x`,e),this.Y=y(`y`,t,!0),this.Z=y(`z`,n),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){let{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error(`invalid affine point`);if(e instanceof T)throw Error(`projective point not allowed`);return r.is0(t)&&r.is0(n)?T.ZERO:new T(t,n,r.ONE)}static fromBytes(e){let t=T.fromAffine(m(AE(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return T.fromBytes(LE(`pointHex`,e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return D.createCache(this,e),t||this.multiply(jO),this}assertValidity(){C(this)}hasEvenY(){let{y:e}=this.toAffine();if(!r.isOdd)throw Error(`Field doesn't support isOdd`);return!r.isOdd(e)}equals(e){b(e);let{X:t,Y:n,Z:i}=this,{X:a,Y:o,Z:s}=e,c=r.eql(r.mul(t,s),r.mul(a,i)),l=r.eql(r.mul(n,s),r.mul(o,i));return c&&l}negate(){return new T(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=a,n=r.mul(t,jO),{X:i,Y:o,Z:s}=this,c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),f=r.mul(o,o),p=r.mul(s,s),m=r.mul(i,o);return m=r.add(m,m),u=r.mul(i,s),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,p),l=r.add(c,l),c=r.sub(f,l),l=r.add(f,l),l=r.mul(c,l),c=r.mul(m,c),u=r.mul(n,u),p=r.mul(e,p),m=r.sub(d,p),m=r.mul(e,m),m=r.add(m,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,p),d=r.mul(d,m),l=r.add(l,d),p=r.mul(o,s),p=r.add(p,p),d=r.mul(p,m),c=r.sub(c,d),u=r.mul(p,f),u=r.add(u,u),u=r.add(u,u),new T(c,l,u)}add(e){b(e);let{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:c}=e,l=r.ZERO,u=r.ZERO,d=r.ZERO,f=a.a,p=r.mul(a.b,jO),m=r.mul(t,o),h=r.mul(n,s),g=r.mul(i,c),_=r.add(t,n),v=r.add(o,s);_=r.mul(_,v),v=r.add(m,h),_=r.sub(_,v),v=r.add(t,i);let y=r.add(o,c);return v=r.mul(v,y),y=r.add(m,g),v=r.sub(v,y),y=r.add(n,i),l=r.add(s,c),y=r.mul(y,l),l=r.add(h,g),y=r.sub(y,l),d=r.mul(f,v),l=r.mul(p,g),d=r.add(l,d),l=r.sub(h,d),d=r.add(h,d),u=r.mul(l,d),h=r.add(m,m),h=r.add(h,m),g=r.mul(f,g),v=r.mul(p,v),h=r.add(h,g),g=r.sub(m,g),g=r.mul(f,g),v=r.add(v,g),m=r.mul(h,v),u=r.add(u,m),m=r.mul(y,v),l=r.mul(_,l),l=r.sub(l,m),m=r.mul(_,h),d=r.mul(y,d),d=r.add(d,m),new T(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(T.ZERO)}multiply(e){let{endo:n}=t;if(!i.isValidNot0(e))throw Error(`invalid scalar: out of range`);let r,a,o=e=>D.cached(this,e,e=>cO(T,e));if(n){let{k1neg:t,k1:i,k2neg:s,k2:c}=x(e),{p:l,f:u}=o(i),{p:d,f}=o(c);a=u.add(f),r=w(n.beta,l,d,t,s)}else{let{p:t,f:n}=o(e);r=t,a=n}return cO(T,[r,a])[0]}multiplyUnsafe(e){let{endo:n}=t,r=this;if(!i.isValid(e))throw Error(`invalid scalar: out of range`);if(e===OO||r.is0())return T.ZERO;if(e===kO)return r;if(D.hasCache(this))return this.multiply(e);if(n){let{k1neg:t,k1:i,k2neg:a,k2:o}=x(e),{p1:s,p2:c}=yO(T,r,i,o);return w(n.beta,s,c,t,a)}return D.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){let r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return S(this,e)}isTorsionFree(){let{isTorsionFree:e}=t;return o===kO?!0:e?e(T,this):D.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===kO?this:e?e(T,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return kE(e,`isCompressed`),this.assertValidity(),p(T,this,e)}toHex(e=!0){return _E(this.toBytes(e))}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return cO(T,e)}static msm(e,t){return bO(T,i,e,t)}static fromPrivateKey(e){return T.BASE.multiply(NO(i,e))}}T.BASE=new T(a.Gx,a.Gy,r.ONE),T.ZERO=new T(r.ZERO,r.ONE,r.ZERO),T.Fp=r,T.Fn=i;let E=i.BITS,D=new vO(T,t.endo?Math.ceil(E/2):E);return T.BASE.precompute(8),T}function FO(e){return Uint8Array.of(e?2:3)}function IO(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function LO(e,t={}){let{Fn:n}=e,r=t.randomBytes||EE,i=Object.assign(IO(e.Fp,n),{seed:vD(n.ORDER)});function a(e){try{return!!NO(n,e)}catch{return!1}}function o(t,n){let{publicKey:r,publicKeyUncompressed:a}=i;try{let i=t.length;return n===!0&&i!==r||n===!1&&i!==a?!1:!!e.fromBytes(t)}catch{return!1}}function s(e=r(i.seed)){return yD(AE(e,i.seed,`seed`),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(NO(n,t)).toBytes(r)}function l(e){let t=s(e);return{secretKey:t,publicKey:c(t)}}function u(t){if(typeof t==`bigint`)return!1;if(t instanceof e)return!0;let{secretKey:r,publicKey:a,publicKeyUncompressed:o}=i;if(n.allowedLengths||r===a)return;let s=LE(`key`,t).length;return s===a||s===o}function d(t,r,i=!0){if(u(t)===!0)throw Error(`first arg must be private key`);if(u(r)===!1)throw Error(`second arg must be public key`);let a=NO(n,t);return e.fromHex(r).multiply(a).toBytes(i)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:l,Point:e,utils:{isValidSecretKey:a,isValidPublicKey:o,randomSecretKey:s,isValidPrivateKey:a,randomPrivateKey:s,normPrivateKeyToScalar:e=>NO(n,e),precompute(t=8,n=e.BASE){return n.precompute(t,!1)}},lengths:i})}function RO(e,t,n={}){lE(t),WE(n,{},{hmac:`function`,lowS:`boolean`,randomBytes:`function`,bits2int:`function`,bits2int_modN:`function`});let r=n.randomBytes||EE,i=n.hmac||((e,...n)=>iO(t,e,CE(...n))),{Fp:a,Fn:o}=e,{ORDER:s,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p}=LO(e,n),m={prehash:!1,lowS:typeof n.lowS==`boolean`&&n.lowS,format:void 0,extraEntropy:!1},h=`compact`;function g(e){return e>s>>kO}function _(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function v(e,t){TO(t);let n=p.signature;return AE(e,t===`compact`?n:t===`recovered`?n+1:void 0,`${t} signature`)}class y{constructor(e,t,n){this.r=_(`r`,e),this.s=_(`s`,t),n!=null&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=h){v(e,t);let n;if(t===`der`){let{r:t,s:n}=DO.toSig(AE(e));return new y(t,n)}t===`recovered`&&(n=e[0],t=`compact`,e=e.subarray(1));let r=o.BYTES,i=e.subarray(0,r),a=e.subarray(r,r*2);return new y(o.fromBytes(i),o.fromBytes(a),n)}static fromHex(e,t){return this.fromBytes(bE(e),t)}addRecoveryBit(e){return new y(this.r,this.s,e)}recoverPublicKey(t){let n=a.ORDER,{r,s:i,recovery:c}=this;if(c==null||![0,1,2,3].includes(c))throw Error(`recovery id invalid`);if(s*AO<n&&c>1)throw Error(`recovery id is ambiguous for h>1 curve`);let l=c===2||c===3?r+s:r;if(!a.isValid(l))throw Error(`recovery id 2 or 3 invalid`);let u=a.toBytes(l),d=e.fromBytes(CE(FO(!(c&1)),u)),f=o.inv(l),p=x(LE(`msgHash`,t)),m=o.create(-p*f),h=o.create(i*f),g=e.BASE.multiplyUnsafe(m).add(d.multiplyUnsafe(h));if(g.is0())throw Error(`point at infinify`);return g.assertValidity(),g}hasHighS(){return g(this.s)}toBytes(e=h){if(TO(e),e===`der`)return bE(DO.hexFromSig(this));let t=o.toBytes(this.r),n=o.toBytes(this.s);if(e===`recovered`){if(this.recovery==null)throw Error(`recovery bit must be present`);return CE(Uint8Array.of(this.recovery),t,n)}return CE(t,n)}toHex(e){return _E(this.toBytes(e))}assertValidity(){}static fromCompact(e){return y.fromBytes(LE(`sig`,e),`compact`)}static fromDER(e){return y.fromBytes(LE(`sig`,e),`der`)}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes(`der`)}toDERHex(){return _E(this.toBytes(`der`))}toCompactRawBytes(){return this.toBytes(`compact`)}toCompactHex(){return _E(this.toBytes(`compact`))}}let b=n.bits2int||function(e){if(e.length>8192)throw Error(`input is too large`);let t=NE(e),n=e.length*8-c;return n>0?t>>BigInt(n):t},x=n.bits2int_modN||function(e){return o.create(b(e))},S=HE(c);function C(e){return BE(`num < 2^`+c,e,OO,S),o.toBytes(e)}function w(e,n){return AE(e,void 0,`message`),n?AE(t(e),void 0,`prehashed message`):e}function T(t,n,i){if([`recovered`,`canonical`].some(e=>e in i))throw Error(`sign() legacy options not supported`);let{lowS:a,prehash:s,extraEntropy:c}=EO(i,m);t=w(t,s);let l=x(t),u=NO(o,n),d=[C(u),C(l)];if(c!=null&&c!==!1){let e=c===!0?r(p.secretKey):c;d.push(LE(`extraEntropy`,e))}let f=CE(...d),h=l;function _(t){let n=b(t);if(!o.isValidNot0(n))return;let r=o.inv(n),i=e.BASE.multiply(n).toAffine(),s=o.create(i.x);if(s===OO)return;let c=o.create(r*o.create(h+s*u));if(c===OO)return;let l=(i.x===s?0:2)|Number(i.y&kO),d=c;return a&&g(c)&&(d=o.neg(c),l^=1),new y(s,d,l)}return{seed:f,k2sig:_}}function E(e,n,r={}){e=LE(`message`,e);let{seed:a,k2sig:s}=T(e,n,r);return UE(t.outputLen,o.BYTES,i)(a,s)}function D(e){let t,n=typeof e==`string`||oE(e),r=!n&&typeof e==`object`&&!!e&&typeof e.r==`bigint`&&typeof e.s==`bigint`;if(!n&&!r)throw Error(`invalid signature, expected Uint8Array, hex string or Signature instance`);if(r)t=new y(e.r,e.s);else if(n){try{t=y.fromBytes(LE(`sig`,e),`der`)}catch(e){if(!(e instanceof DO.Err))throw e}if(!t)try{t=y.fromBytes(LE(`sig`,e),`compact`)}catch{return!1}}return t||!1}function O(t,n,r,i={}){let{lowS:a,prehash:s,format:c}=EO(i,m);if(r=LE(`publicKey`,r),n=w(LE(`message`,n),s),`strict`in i)throw Error(`options.strict was renamed to lowS`);let l=c===void 0?D(t):y.fromBytes(LE(`sig`,t),c);if(l===!1)return!1;try{let t=e.fromBytes(r);if(a&&l.hasHighS())return!1;let{r:i,s}=l,c=x(n),u=o.inv(s),d=o.create(c*u),f=o.create(i*u),p=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(f));return!p.is0()&&o.create(p.x)===i}catch{return!1}}function k(e,t,n={}){let{prehash:r}=EO(n,m);return t=w(t,r),y.fromBytes(e,`recovered`).recoverPublicKey(t).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p,Point:e,sign:E,verify:O,recoverPublicKey:k,Signature:y,hash:t})}function zO(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:gD(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}function BO(e){let{CURVE:t,curveOpts:n}=zO(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function VO(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,hD(n.Fn.ORDER,n.Fn.BITS))})}function HO(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=BO(e);return VO(e,RO(PO(t,n),r,i))}function UO(e,t){let n=t=>HO({...e,hash:t});return{...n(t),create:n}}var WO={p:BigInt(`0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff`),n:BigInt(`0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551`),h:BigInt(1),a:BigInt(`0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc`),b:BigInt(`0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b`),Gx:BigInt(`0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296`),Gy:BigInt(`0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5`)},GO={p:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff`),n:BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973`),h:BigInt(1),a:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc`),b:BigInt(`0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef`),Gx:BigInt(`0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7`),Gy:BigInt(`0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f`)},KO={p:BigInt(`0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),n:BigInt(`0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409`),h:BigInt(1),a:BigInt(`0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc`),b:BigInt(`0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00`),Gx:BigInt(`0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66`),Gy:BigInt(`0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650`)},qO=gD(WO.p),JO=gD(GO.p),YO=gD(KO.p),XO=UO({...WO,Fp:qO,lowS:!1},eO);UO({...GO,Fp:JO,lowS:!1},nO),UO({...KO,Fp:YO,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},tO);var ZO=XO,QO=R((e=>{e.toString=function(e){switch(e){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_`+e},e.toType=function(e){switch(e.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 e.toUpperCase().startsWith(`UNKNOWN_`)?parseInt(e.slice(8)):0}})),$O=R((e=>{e.toString=function(e){switch(e){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_`+e},e.toRcode=function(e){switch(e.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}})),ek=R((e=>{e.toString=function(e){switch(e){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_`+e},e.toOpcode=function(e){switch(e.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}})),tk=R((e=>{e.toString=function(e){switch(e){case 1:return`IN`;case 2:return`CS`;case 3:return`CH`;case 4:return`HS`;case 255:return`ANY`}return`UNKNOWN_`+e},e.toClass=function(e){switch(e.toUpperCase()){case`IN`:return 1;case`CS`:return 2;case`CH`:return 3;case`HS`:return 4;case`ANY`:return 255}return 0}})),nk=R((e=>{e.toString=function(e){switch(e){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 e<0?null:`OPTION_${e}`},e.toCode=function(e){if(typeof e==`number`)return e;if(!e)return-1;switch(e.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 t=e.match(/_(\d+)$/);return t?parseInt(t[1],10):-1}})),rk=R(((e,t)=>{var n=(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.decode=c,e.encode=s,e.familyOf=o,e.name=void 0,e.sizeOf=a,e.v6=e.v4=void 0;let t=/^(\d{1,3}\.){3,3}\d{1,3}$/,n=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,r={name:`v4`,size:4,isFormat:e=>t.test(e),encode(e,t,n){n=~~n,t||=new Uint8Array(n+4);let r=e.length,i=0;for(let a=0;a<r;){let r=e.charCodeAt(a++);r===46?(t[n++]=i,i=0):i=i*10+(r-48)}return t[n]=i,t},decode(e,t){return t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`}};e.v4=r;let i={name:`v6`,size:16,isFormat:e=>e.length>0&&n.test(e),encode(e,t,n){n=~~n;let r=n+16,i=-1,a=0,o=0,s=!0,c=!1;t||=new Uint8Array(n+16);for(let l=0;l<e.length;l++){let u=e.charCodeAt(l);u===58?(s?i===-1?n<r&&(i=n):(n<r&&(t[n]=0),n<r-1&&(t[n+1]=0),n+=2):(c===!0?(n<r&&(t[n]=o),n++):(n<r&&(t[n]=a>>8),n<r-1&&(t[n+1]=a&255),n+=2),a=0,o=0),s=!0,c=!1):u===46?(n<r&&(t[n]=o),n++,o=0,a=0,s=!1,c=!0):(s=!1,u>=97?u-=87:u>=65?u-=55:(u-=48,o=o*10+u),a=(a<<4)+u)}if(s===!1)c===!0?(n<r&&(t[n]=o),n++):(n<r&&(t[n]=a>>8),n<r-1&&(t[n+1]=a&255),n+=2);else if(i===0)n<r&&(t[n]=0),n<r-1&&(t[n+1]=0),n+=2;else if(i!==-1){n+=2;for(let e=Math.min(n-1,r-1);e>=i+2;e--)t[e]=t[e-2];t[i]=0,t[i+1]=0,i=n}if(i!==n&&i!==-1)for(n>r-2&&(n=r-2);r>i;)t[--r]=n<r&&n>i?t[--n]:0;else for(;n<r;)t[n++]=0;return t},decode(e,t){t=~~t;let n=``;for(let r=0;r<16;r+=2)r!==0&&(n+=`:`),n+=(e[t+r]<<8|e[t+r+1]).toString(16);return n.replace(/(^|:)0(:0)*:0(:|$)/,`$1::$3`).replace(/:{3,4}/,`::`)}};e.v6=i,e.name=`ip`;function a(e){if(r.isFormat(e))return r.size;if(i.isFormat(e))return i.size;throw Error(`Invalid ip address: ${e}`)}function o(e){return a(e)===r.size?1:2}function s(e,t,n){n=~~n;let o=a(e);return typeof t==`function`&&(t=t(n+o)),o===r.size?r.encode(e,t,n):i.encode(e,t,n)}function c(e,t,n){if(t=~~t,n||=e.length-t,n===r.size)return r.decode(e,t,n);if(n===i.size)return i.decode(e,t,n);throw Error(`Invalid buffer size needs to be ${r.size} for v4 or ${i.size} for v6.`)}return`default`in e?e.default:e})({});typeof define==`function`&&define.amd?define([],function(){return n}):typeof t==`object`&&typeof e==`object`&&(t.exports=n)})),ik=R((e=>{var t=ne(`buffer`).Buffer,n=QO(),r=$O(),i=ek(),a=tk(),o=nk(),s=rk(),c=0,l=32768,u=32768,d=-32769,f=32768,p=-32769,m=e.name={};m.encode=function(e,n,r,{mail:i=!1}={}){n||=t.alloc(m.encodingLength(e)),r||=0;let a=r,o=e.replace(/^\.|\.$/gm,``);if(o.length){let e=[];if(i){let t=``;o.split(`.`).forEach(n=>{n.endsWith(`\\`)?t+=(t.length?`.`:``)+n.slice(0,-1):e.length===0&&t.length?e.push(t+`.`+n):e.push(n)})}else e=o.split(`.`);for(let t=0;t<e.length;t++){let i=n.write(e[t],r+1);n[r]=i,r+=i+1}}return n[r++]=0,m.encode.bytes=r-a,n},m.encode.bytes=0,m.decode=function(e,t,{mail:n=!1}={}){t||=0;let r=[],i=t,a=0,o=0,s=!1;for(;;){if(t>=e.length)throw Error(`Cannot decode name (buffer overflow)`);let c=e[t++];if(o+=+!s,c===0)break;if(!(c&192)){if(t+c>e.length)throw Error(`Cannot decode name (buffer overflow)`);if(a+=c+1,a>254)throw Error(`Cannot decode name (name too long)`);let i=e.toString(`utf-8`,t,t+c);n&&(i=i.replace(/\./g,`\\.`)),r.push(i),t+=c,o+=s?0:c}else if((c&192)==192){if(t+1>e.length)throw Error(`Cannot decode name (buffer overflow)`);let n=e.readUInt16BE(t-1)-49152;if(n>=i)throw Error(`Cannot decode name (bad pointer)`);t=n,i=n,o+=+!s,s=!0}else throw Error(`Cannot decode name (bad label)`)}return m.decode.bytes=o,r.length===0?`.`:r.join(`.`)},m.decode.bytes=0,m.encodingLength=function(e){return e===`.`||e===`..`?1:t.byteLength(e.replace(/^\.|\.$/gm,``))+2};var h={};h.encode=function(e,n,r){n||=t.alloc(h.encodingLength(e)),r||=0;let i=n.write(e,r+1);return n[r]=i,h.encode.bytes=i+1,n},h.encode.bytes=0,h.decode=function(e,t){t||=0;let n=e[t],r=e.toString(`utf-8`,t+1,t+1+n);return h.decode.bytes=n+1,r},h.decode.bytes=0,h.encodingLength=function(e){return t.byteLength(e)+1};var g={};g.encode=function(e,t,n){t||=g.encodingLength(e),n||=0;let r=(e.flags||0)&32767,i=e.type===`response`?l:c;return t.writeUInt16BE(e.id||0,n),t.writeUInt16BE(r|i,n+2),t.writeUInt16BE(e.questions.length,n+4),t.writeUInt16BE(e.answers.length,n+6),t.writeUInt16BE(e.authorities.length,n+8),t.writeUInt16BE(e.additionals.length,n+10),t},g.encode.bytes=12,g.decode=function(e,t){if(t||=0,e.length<12)throw Error(`Header must be 12 bytes`);let n=e.readUInt16BE(t+2);return{id:e.readUInt16BE(t),type:n&l?`response`:`query`,flags:n&32767,flag_qr:(n>>15&1)==1,opcode:i.toString(n>>11&15),flag_aa:(n>>10&1)==1,flag_tc:(n>>9&1)==1,flag_rd:(n>>8&1)==1,flag_ra:(n>>7&1)==1,flag_z:(n>>6&1)==1,flag_ad:(n>>5&1)==1,flag_cd:(n>>4&1)==1,rcode:r.toString(n&15),questions:Array(e.readUInt16BE(t+4)),answers:Array(e.readUInt16BE(t+6)),authorities:Array(e.readUInt16BE(t+8)),additionals:Array(e.readUInt16BE(t+10))}},g.decode.bytes=12,g.encodingLength=function(){return 12};var _=e.unknown={};_.encode=function(e,n,r){return n||=t.alloc(_.encodingLength(e)),r||=0,n.writeUInt16BE(e.length,r),e.copy(n,r+2),_.encode.bytes=e.length+2,n},_.encode.bytes=0,_.decode=function(e,t){t||=0;let n=e.readUInt16BE(t),r=e.slice(t+2,t+2+n);return _.decode.bytes=n+2,r},_.decode.bytes=0,_.encodingLength=function(e){return e.length+2};var v=e.ns={};v.encode=function(e,n,r){return n||=t.alloc(v.encodingLength(e)),r||=0,m.encode(e,n,r+2),n.writeUInt16BE(m.encode.bytes,r),v.encode.bytes=m.encode.bytes+2,n},v.encode.bytes=0,v.decode=function(e,t){t||=0;let n=e.readUInt16BE(t),r=m.decode(e,t+2);return v.decode.bytes=n+2,r},v.decode.bytes=0,v.encodingLength=function(e){return m.encodingLength(e)+2};var y=e.soa={};y.encode=function(e,n,r){n||=t.alloc(y.encodingLength(e)),r||=0;let i=r;return r+=2,m.encode(e.mname,n,r),r+=m.encode.bytes,m.encode(e.rname,n,r,{mail:!0}),r+=m.encode.bytes,n.writeUInt32BE(e.serial||0,r),r+=4,n.writeUInt32BE(e.refresh||0,r),r+=4,n.writeUInt32BE(e.retry||0,r),r+=4,n.writeUInt32BE(e.expire||0,r),r+=4,n.writeUInt32BE(e.minimum||0,r),r+=4,n.writeUInt16BE(r-i-2,i),y.encode.bytes=r-i,n},y.encode.bytes=0,y.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.mname=m.decode(e,t),t+=m.decode.bytes,r.rname=m.decode(e,t,{mail:!0}),t+=m.decode.bytes,r.serial=e.readUInt32BE(t),t+=4,r.refresh=e.readUInt32BE(t),t+=4,r.retry=e.readUInt32BE(t),t+=4,r.expire=e.readUInt32BE(t),t+=4,r.minimum=e.readUInt32BE(t),t+=4,y.decode.bytes=t-n,r},y.decode.bytes=0,y.encodingLength=function(e){return 22+m.encodingLength(e.mname)+m.encodingLength(e.rname)};var b=e.txt={};b.encode=function(e,n,r){Array.isArray(e)||(e=[e]);for(let n=0;n<e.length;n++)if(typeof e[n]==`string`&&(e[n]=t.from(e[n])),!t.isBuffer(e[n]))throw Error(`Must be a Buffer`);n||=t.alloc(b.encodingLength(e)),r||=0;let i=r;return r+=2,e.forEach(function(e){n[r++]=e.length,e.copy(n,r,0,e.length),r+=e.length}),n.writeUInt16BE(r-i-2,i),b.encode.bytes=r-i,n},b.encode.bytes=0,b.decode=function(e,t){t||=0;let n=t,r=e.readUInt16BE(t);t+=2;let i=[];for(;r>0;){let n=e[t++];if(--r,r<n)throw Error(`Buffer overflow`);i.push(e.slice(t,t+n)),t+=n,r-=n}return b.decode.bytes=t-n,i},b.decode.bytes=0,b.encodingLength=function(e){Array.isArray(e)||(e=[e]);let n=2;return e.forEach(function(e){n+=typeof e==`string`?t.byteLength(e)+1:e.length+1}),n};var x=e.null={};x.encode=function(e,n,r){n||=t.alloc(x.encodingLength(e)),r||=0,typeof e==`string`&&(e=t.from(e)),e||=t.alloc(0);let i=r;r+=2;let a=e.length;return e.copy(n,r,0,a),r+=a,n.writeUInt16BE(r-i-2,i),x.encode.bytes=r-i,n},x.encode.bytes=0,x.decode=function(e,t){t||=0;let n=t,r=e.readUInt16BE(t);t+=2;let i=e.slice(t,t+r);return t+=r,x.decode.bytes=t-n,i},x.decode.bytes=0,x.encodingLength=function(e){return e?(t.isBuffer(e)?e.length:t.byteLength(e))+2:2};var S=e.hinfo={};S.encode=function(e,n,r){n||=t.alloc(S.encodingLength(e)),r||=0;let i=r;return r+=2,h.encode(e.cpu,n,r),r+=h.encode.bytes,h.encode(e.os,n,r),r+=h.encode.bytes,n.writeUInt16BE(r-i-2,i),S.encode.bytes=r-i,n},S.encode.bytes=0,S.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.cpu=h.decode(e,t),t+=h.decode.bytes,r.os=h.decode(e,t),t+=h.decode.bytes,S.decode.bytes=t-n,r},S.decode.bytes=0,S.encodingLength=function(e){return h.encodingLength(e.cpu)+h.encodingLength(e.os)+2};var C=e.ptr={},w=e.cname=C,T=e.dname=C;C.encode=function(e,n,r){return n||=t.alloc(C.encodingLength(e)),r||=0,m.encode(e,n,r+2),n.writeUInt16BE(m.encode.bytes,r),C.encode.bytes=m.encode.bytes+2,n},C.encode.bytes=0,C.decode=function(e,t){t||=0;let n=m.decode(e,t+2);return C.decode.bytes=m.decode.bytes+2,n},C.decode.bytes=0,C.encodingLength=function(e){return m.encodingLength(e)+2};var E=e.srv={};E.encode=function(e,n,r){n||=t.alloc(E.encodingLength(e)),r||=0,n.writeUInt16BE(e.priority||0,r+2),n.writeUInt16BE(e.weight||0,r+4),n.writeUInt16BE(e.port||0,r+6),m.encode(e.target,n,r+8);let i=m.encode.bytes+6;return n.writeUInt16BE(i,r),E.encode.bytes=i+2,n},E.encode.bytes=0,E.decode=function(e,t){t||=0;let n=e.readUInt16BE(t),r={};return r.priority=e.readUInt16BE(t+2),r.weight=e.readUInt16BE(t+4),r.port=e.readUInt16BE(t+6),r.target=m.decode(e,t+8),E.decode.bytes=n+2,r},E.decode.bytes=0,E.encodingLength=function(e){return 8+m.encodingLength(e.target)};var D=e.caa={};D.ISSUER_CRITICAL=128,D.encode=function(e,n,r){let i=D.encodingLength(e);return n||=t.alloc(D.encodingLength(e)),r||=0,e.issuerCritical&&(e.flags=D.ISSUER_CRITICAL),n.writeUInt16BE(i-2,r),r+=2,n.writeUInt8(e.flags||0,r),r+=1,h.encode(e.tag,n,r),r+=h.encode.bytes,n.write(e.value,r),r+=t.byteLength(e.value),D.encode.bytes=i,n},D.encode.bytes=0,D.decode=function(e,t){t||=0;let n=e.readUInt16BE(t);t+=2;let r=t,i={};return i.flags=e.readUInt8(t),t+=1,i.tag=h.decode(e,t),t+=h.decode.bytes,i.value=e.toString(`utf-8`,t,r+n),i.issuerCritical=!!(i.flags&D.ISSUER_CRITICAL),D.decode.bytes=n+2,i},D.decode.bytes=0,D.encodingLength=function(e){return h.encodingLength(e.tag)+h.encodingLength(e.value)+2};var O=e.mx={};O.encode=function(e,n,r){n||=t.alloc(O.encodingLength(e)),r||=0;let i=r;return r+=2,n.writeUInt16BE(e.preference||0,r),r+=2,m.encode(e.exchange,n,r),r+=m.encode.bytes,n.writeUInt16BE(r-i-2,i),O.encode.bytes=r-i,n},O.encode.bytes=0,O.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.preference=e.readUInt16BE(t),t+=2,r.exchange=m.decode(e,t),t+=m.decode.bytes,O.decode.bytes=t-n,r},O.encodingLength=function(e){return 4+m.encodingLength(e.exchange)};var k=e.a={};k.encode=function(e,n,r){return n||=t.alloc(k.encodingLength(e)),r||=0,n.writeUInt16BE(4,r),r+=2,s.v4.encode(e,n,r),k.encode.bytes=6,n},k.encode.bytes=0,k.decode=function(e,t){t||=0,t+=2;let n=s.v4.decode(e,t);return k.decode.bytes=6,n},k.decode.bytes=0,k.encodingLength=function(){return 6};var A=e.aaaa={};A.encode=function(e,n,r){return n||=t.alloc(A.encodingLength(e)),r||=0,n.writeUInt16BE(16,r),r+=2,s.v6.encode(e,n,r),A.encode.bytes=18,n},A.encode.bytes=0,A.decode=function(e,t){t||=0,t+=2;let n=s.v6.decode(e,t);return A.decode.bytes=18,n},A.decode.bytes=0,A.encodingLength=function(){return 18};var j=e.option={};j.encode=function(e,n,r){n||=t.alloc(j.encodingLength(e)),r||=0;let i=r,a=o.toCode(e.code);if(n.writeUInt16BE(a,r),r+=2,e.data)n.writeUInt16BE(e.data.length,r),r+=2,e.data.copy(n,r),r+=e.data.length;else switch(a){case 8:let i=e.sourcePrefixLength||0,a=e.family||s.familyOf(e.ip),o=s.encode(e.ip,t.alloc),c=Math.ceil(i/8);n.writeUInt16BE(c+4,r),r+=2,n.writeUInt16BE(a,r),r+=2,n.writeUInt8(i,r++),n.writeUInt8(e.scopePrefixLength||0,r++),o.copy(n,r,0,c),r+=c;break;case 11:e.timeout?(n.writeUInt16BE(2,r),r+=2,n.writeUInt16BE(e.timeout,r),r+=2):(n.writeUInt16BE(0,r),r+=2);break;case 12:let l=e.length||0;n.writeUInt16BE(l,r),r+=2,n.fill(0,r,r+l),r+=l;break;case 14:let u=e.tags.length*2;n.writeUInt16BE(u,r),r+=2;for(let t of e.tags)n.writeUInt16BE(t,r),r+=2;break;default:throw Error(`Unknown roption code: ${e.code}`)}return j.encode.bytes=r-i,n},j.encode.bytes=0,j.decode=function(e,n){n||=0;let r={};r.code=e.readUInt16BE(n),r.type=o.toString(r.code),n+=2;let i=e.readUInt16BE(n);switch(n+=2,r.data=e.slice(n,n+i),r.code){case 8:r.family=e.readUInt16BE(n),n+=2,r.sourcePrefixLength=e.readUInt8(n++),r.scopePrefixLength=e.readUInt8(n++);let a=t.alloc(r.family===1?4:16);e.copy(a,0,n,n+i-4),r.ip=s.decode(a);break;case 11:i>0&&(r.timeout=e.readUInt16BE(n),n+=2);break;case 14:r.tags=[];for(let t=0;t<i;t+=2)r.tags.push(e.readUInt16BE(n)),n+=2}return j.decode.bytes=i+4,r},j.decode.bytes=0,j.encodingLength=function(e){if(e.data)return e.data.length+4;switch(o.toCode(e.code)){case 8:let t=e.sourcePrefixLength||0;return Math.ceil(t/8)+8;case 11:return typeof e.timeout==`number`?6:4;case 12:return e.length+4;case 14:return 4+e.tags.length*2}throw Error(`Unknown roption code: ${e.code}`)};var M=e.opt={};M.encode=function(e,n,r){n||=t.alloc(M.encodingLength(e)),r||=0;let i=r,a=oe(e,j);return n.writeUInt16BE(a,r),r=se(e,j,n,r+2),M.encode.bytes=r-i,n},M.encode.bytes=0,M.decode=function(e,t){t||=0;let n=t,r=[],i=e.readUInt16BE(t);t+=2;let a=0;for(;i>0;)r[a++]=j.decode(e,t),t+=j.decode.bytes,i-=j.decode.bytes;return M.decode.bytes=t-n,r},M.decode.bytes=0,M.encodingLength=function(e){return 2+oe(e||[],j)};var N=e.dnskey={};N.PROTOCOL_DNSSEC=3,N.ZONE_KEY=128,N.SECURE_ENTRYPOINT=32768,N.encode=function(e,n,r){n||=t.alloc(N.encodingLength(e)),r||=0;let i=r,a=e.key;if(!t.isBuffer(a))throw Error(`Key must be a Buffer`);return r+=2,n.writeUInt16BE(e.flags,r),r+=2,n.writeUInt8(N.PROTOCOL_DNSSEC,r),r+=1,n.writeUInt8(e.algorithm,r),r+=1,a.copy(n,r,0,a.length),r+=a.length,N.encode.bytes=r-i,n.writeUInt16BE(N.encode.bytes-2,i),n},N.encode.bytes=0,N.decode=function(e,t){t||=0;let n=t;var r={},i=e.readUInt16BE(t);if(t+=2,r.flags=e.readUInt16BE(t),t+=2,e.readUInt8(t)!==N.PROTOCOL_DNSSEC)throw Error(`Protocol must be 3`);return t+=1,r.algorithm=e.readUInt8(t),t+=1,r.key=e.slice(t,n+i+2),t+=r.key.length,N.decode.bytes=t-n,r},N.decode.bytes=0,N.encodingLength=function(e){return 6+t.byteLength(e.key)};var P=e.rrsig={};P.encode=function(e,r,i){r||=t.alloc(P.encodingLength(e)),i||=0;let a=i,o=e.signature;if(!t.isBuffer(o))throw Error(`Signature must be a Buffer`);return i+=2,r.writeUInt16BE(n.toType(e.typeCovered),i),i+=2,r.writeUInt8(e.algorithm,i),i+=1,r.writeUInt8(e.labels,i),i+=1,r.writeUInt32BE(e.originalTTL,i),i+=4,r.writeUInt32BE(e.expiration,i),i+=4,r.writeUInt32BE(e.inception,i),i+=4,r.writeUInt16BE(e.keyTag,i),i+=2,m.encode(e.signersName,r,i),i+=m.encode.bytes,o.copy(r,i,0,o.length),i+=o.length,P.encode.bytes=i-a,r.writeUInt16BE(P.encode.bytes-2,a),r},P.encode.bytes=0,P.decode=function(e,t){t||=0;let r=t;var i={},a=e.readUInt16BE(t);return t+=2,i.typeCovered=n.toString(e.readUInt16BE(t)),t+=2,i.algorithm=e.readUInt8(t),t+=1,i.labels=e.readUInt8(t),t+=1,i.originalTTL=e.readUInt32BE(t),t+=4,i.expiration=e.readUInt32BE(t),t+=4,i.inception=e.readUInt32BE(t),t+=4,i.keyTag=e.readUInt16BE(t),t+=2,i.signersName=m.decode(e,t),t+=m.decode.bytes,i.signature=e.slice(t,r+a+2),t+=i.signature.length,P.decode.bytes=t-r,i},P.decode.bytes=0,P.encodingLength=function(e){return 20+m.encodingLength(e.signersName)+t.byteLength(e.signature)};var F=e.rp={};F.encode=function(e,n,r){n||=t.alloc(F.encodingLength(e)),r||=0;let i=r;return r+=2,m.encode(e.mbox||`.`,n,r,{mail:!0}),r+=m.encode.bytes,m.encode(e.txt||`.`,n,r),r+=m.encode.bytes,F.encode.bytes=r-i,n.writeUInt16BE(F.encode.bytes-2,i),n},F.encode.bytes=0,F.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.mbox=m.decode(e,t,{mail:!0})||`.`,t+=m.decode.bytes,r.txt=m.decode(e,t)||`.`,t+=m.decode.bytes,F.decode.bytes=t-n,r},F.decode.bytes=0,F.encodingLength=function(e){return 2+m.encodingLength(e.mbox||`.`)+m.encodingLength(e.txt||`.`)};var I={};I.encode=function(e,r,i){r||=t.alloc(I.encodingLength(e)),i||=0;let a=i;for(var o=[],s=0;s<e.length;s++){var c=n.toType(e[s]);o[c>>8]===void 0&&(o[c>>8]=[]),o[c>>8][c>>3&31]|=1<<7-(c&7)}for(s=0;s<o.length;s++)if(o[s]!==void 0){var l=t.from(o[s]);r.writeUInt8(s,i),i+=1,r.writeUInt8(l.length,i),i+=1,l.copy(r,i),i+=l.length}return I.encode.bytes=i-a,r},I.encode.bytes=0,I.decode=function(e,t,r){t||=0;let i=t;for(var a=[];t-i<r;){var o=e.readUInt8(t);t+=1;var s=e.readUInt8(t);t+=1;for(var c=0;c<s;c++)for(var l=e.readUInt8(t+c),u=0;u<8;u++)if(l&1<<7-u){var d=n.toString(o<<8|c<<3|u);a.push(d)}t+=s}return I.decode.bytes=t-i,a},I.decode.bytes=0,I.encodingLength=function(e){for(var t=[],r=0;r<e.length;r++){var i=n.toType(e[r]);t[i>>8]=Math.max(t[i>>8]||0,i&255)}var a=0;for(r=0;r<t.length;r++)t[r]!==void 0&&(a+=2+Math.ceil((t[r]+1)/8));return a};var L=e.nsec={};L.encode=function(e,n,r){n||=t.alloc(L.encodingLength(e)),r||=0;let i=r;return r+=2,m.encode(e.nextDomain,n,r),r+=m.encode.bytes,I.encode(e.rrtypes,n,r),r+=I.encode.bytes,L.encode.bytes=r-i,n.writeUInt16BE(L.encode.bytes-2,i),n},L.encode.bytes=0,L.decode=function(e,t){t||=0;let n=t;var r={},i=e.readUInt16BE(t);return t+=2,r.nextDomain=m.decode(e,t),t+=m.decode.bytes,r.rrtypes=I.decode(e,t,i-(t-n)),t+=I.decode.bytes,L.decode.bytes=t-n,r},L.decode.bytes=0,L.encodingLength=function(e){return 2+m.encodingLength(e.nextDomain)+I.encodingLength(e.rrtypes)};var R=e.nsec3={};R.encode=function(e,n,r){n||=t.alloc(R.encodingLength(e)),r||=0;let i=r,a=e.salt;if(!t.isBuffer(a))throw Error(`salt must be a Buffer`);let o=e.nextDomain;if(!t.isBuffer(o))throw Error(`nextDomain must be a Buffer`);return r+=2,n.writeUInt8(e.algorithm,r),r+=1,n.writeUInt8(e.flags,r),r+=1,n.writeUInt16BE(e.iterations,r),r+=2,n.writeUInt8(a.length,r),r+=1,a.copy(n,r,0,a.length),r+=a.length,n.writeUInt8(o.length,r),r+=1,o.copy(n,r,0,o.length),r+=o.length,I.encode(e.rrtypes,n,r),r+=I.encode.bytes,R.encode.bytes=r-i,n.writeUInt16BE(R.encode.bytes-2,i),n},R.encode.bytes=0,R.decode=function(e,t){t||=0;let n=t;var r={},i=e.readUInt16BE(t);t+=2,r.algorithm=e.readUInt8(t),t+=1,r.flags=e.readUInt8(t),t+=1,r.iterations=e.readUInt16BE(t),t+=2;let a=e.readUInt8(t);t+=1,r.salt=e.slice(t,t+a),t+=a;let o=e.readUInt8(t);return t+=1,r.nextDomain=e.slice(t,t+o),t+=o,r.rrtypes=I.decode(e,t,i-(t-n)),t+=I.decode.bytes,R.decode.bytes=t-n,r},R.decode.bytes=0,R.encodingLength=function(e){return 8+e.salt.length+e.nextDomain.length+I.encodingLength(e.rrtypes)};var ee=e.ds={};ee.encode=function(e,n,r){n||=t.alloc(ee.encodingLength(e)),r||=0;let i=r,a=e.digest;if(!t.isBuffer(a))throw Error(`Digest must be a Buffer`);return r+=2,n.writeUInt16BE(e.keyTag,r),r+=2,n.writeUInt8(e.algorithm,r),r+=1,n.writeUInt8(e.digestType,r),r+=1,a.copy(n,r,0,a.length),r+=a.length,ee.encode.bytes=r-i,n.writeUInt16BE(ee.encode.bytes-2,i),n},ee.encode.bytes=0,ee.decode=function(e,t){t||=0;let n=t;var r={},i=e.readUInt16BE(t);return t+=2,r.keyTag=e.readUInt16BE(t),t+=2,r.algorithm=e.readUInt8(t),t+=1,r.digestType=e.readUInt8(t),t+=1,r.digest=e.slice(t,n+i+2),t+=r.digest.length,ee.decode.bytes=t-n,r},ee.decode.bytes=0,ee.encodingLength=function(e){return 6+t.byteLength(e.digest)};var z=e.sshfp={};z.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}},z.encode=function(e,n,r){n||=t.alloc(z.encodingLength(e)),r||=0;let i=r;r+=2,n[r]=e.algorithm,r+=1,n[r]=e.hash,r+=1;let a=t.from(e.fingerprint.toUpperCase(),`hex`);if(a.length!==z.getFingerprintLengthForHashType(e.hash))throw Error(`Invalid fingerprint length`);return a.copy(n,r),r+=a.byteLength,z.encode.bytes=r-i,n.writeUInt16BE(z.encode.bytes-2,i),n},z.encode.bytes=0,z.decode=function(e,t){t||=0;let n=t,r={};t+=2,r.algorithm=e[t],t+=1,r.hash=e[t],t+=1;let i=z.getFingerprintLengthForHashType(r.hash);return r.fingerprint=e.slice(t,t+i).toString(`hex`).toUpperCase(),t+=i,z.decode.bytes=t-n,r},z.decode.bytes=0,z.encodingLength=function(e){return 4+t.from(e.fingerprint,`hex`).byteLength};var B=e.naptr={};B.encode=function(e,n,r){n||=t.alloc(B.encodingLength(e)),r||=0;let i=r;return r+=2,n.writeUInt16BE(e.order||0,r),r+=2,n.writeUInt16BE(e.preference||0,r),r+=2,h.encode(e.flags,n,r),r+=h.encode.bytes,h.encode(e.services,n,r),r+=h.encode.bytes,h.encode(e.regexp,n,r),r+=h.encode.bytes,m.encode(e.replacement,n,r),r+=m.encode.bytes,B.encode.bytes=r-i,n.writeUInt16BE(B.encode.bytes-2,i),n},B.encode.bytes=0,B.decode=function(e,t){t||=0;let n=t,r={};return t+=2,r.order=e.readUInt16BE(t),t+=2,r.preference=e.readUInt16BE(t),t+=2,r.flags=h.decode(e,t),t+=h.decode.bytes,r.services=h.decode(e,t),t+=h.decode.bytes,r.regexp=h.decode(e,t),t+=h.decode.bytes,r.replacement=m.decode(e,t),t+=m.decode.bytes,B.decode.bytes=t-n,r},B.decode.bytes=0,B.encodingLength=function(e){return h.encodingLength(e.flags)+h.encodingLength(e.services)+h.encodingLength(e.regexp)+m.encodingLength(e.replacement)+6};var te=e.tlsa={};te.encode=function(e,n,r){n||=t.alloc(te.encodingLength(e)),r||=0;let i=r,a=e.certificate;if(!t.isBuffer(a))throw Error(`Certificate must be a Buffer`);return r+=2,n.writeUInt8(e.usage,r),r+=1,n.writeUInt8(e.selector,r),r+=1,n.writeUInt8(e.matchingType,r),r+=1,a.copy(n,r,0,a.length),r+=a.length,te.encode.bytes=r-i,n.writeUInt16BE(te.encode.bytes-2,i),n},te.encode.bytes=0,te.decode=function(e,t){t||=0;let n=t,r={},i=e.readUInt16BE(t);return t+=2,r.usage=e.readUInt8(t),t+=1,r.selector=e.readUInt8(t),t+=1,r.matchingType=e.readUInt8(t),t+=1,r.certificate=e.slice(t,n+i+2),t+=r.certificate.length,te.decode.bytes=t-n,r},te.decode.bytes=0,te.encodingLength=function(e){return 5+t.byteLength(e.certificate)};var re=e.record=function(e){switch(e.toUpperCase()){case`A`:return k;case`PTR`:return C;case`CNAME`:return w;case`DNAME`:return T;case`TXT`:return b;case`NULL`:return x;case`AAAA`:return A;case`SRV`:return E;case`HINFO`:return S;case`CAA`:return D;case`NS`:return v;case`SOA`:return y;case`MX`:return O;case`OPT`:return M;case`DNSKEY`:return N;case`RRSIG`:return P;case`RP`:return F;case`NSEC`:return L;case`NSEC3`:return R;case`SSHFP`:return z;case`DS`:return ee;case`NAPTR`:return B;case`TLSA`:return te}return _},ie=e.answer={};ie.encode=function(e,r,i){r||=t.alloc(ie.encodingLength(e)),i||=0;let o=i;if(m.encode(e.name,r,i),i+=m.encode.bytes,r.writeUInt16BE(n.toType(e.type),i),e.type.toUpperCase()===`OPT`){if(e.name!==`.`)throw Error(`OPT name must be root.`);r.writeUInt16BE(e.udpPayloadSize||4096,i+2),r.writeUInt8(e.extendedRcode||0,i+4),r.writeUInt8(e.ednsVersion||0,i+5),r.writeUInt16BE(e.flags||0,i+6),i+=8,M.encode(e.options||[],r,i),i+=M.encode.bytes}else{let t=a.toClass(e.class===void 0?`IN`:e.class);e.flush&&(t|=u),r.writeUInt16BE(t,i+2),r.writeUInt32BE(e.ttl||0,i+4),i+=8;let n=re(e.type);n.encode(e.data,r,i),i+=n.encode.bytes}return ie.encode.bytes=i-o,r},ie.encode.bytes=0,ie.decode=function(e,t){t||=0;let r={},i=t;if(r.name=m.decode(e,t),t+=m.decode.bytes,r.type=n.toString(e.readUInt16BE(t)),r.type===`OPT`)r.udpPayloadSize=e.readUInt16BE(t+2),r.extendedRcode=e.readUInt8(t+4),r.ednsVersion=e.readUInt8(t+5),r.flags=e.readUInt16BE(t+6),r.flag_do=(r.flags>>15&1)==1,r.options=M.decode(e,t+8),t+=8+M.decode.bytes;else{let n=e.readUInt16BE(t+2);r.ttl=e.readUInt32BE(t+4),r.class=a.toString(n&d),r.flush=!!(n&u);let i=re(r.type);r.data=i.decode(e,t+8),t+=8+i.decode.bytes}return ie.decode.bytes=t-i,r},ie.decode.bytes=0,ie.encodingLength=function(e){let t=e.data!==null&&e.data!==void 0?e.data:e.options;return m.encodingLength(e.name)+8+re(e.type).encodingLength(t)};var ae=e.question={};ae.encode=function(e,r,i){r||=t.alloc(ae.encodingLength(e)),i||=0;let o=i;return m.encode(e.name,r,i),i+=m.encode.bytes,r.writeUInt16BE(n.toType(e.type),i),i+=2,r.writeUInt16BE(a.toClass(e.class===void 0?`IN`:e.class),i),i+=2,ae.encode.bytes=i-o,e},ae.encode.bytes=0,ae.decode=function(e,t){t||=0;let r=t,i={};return i.name=m.decode(e,t),t+=m.decode.bytes,i.type=n.toString(e.readUInt16BE(t)),t+=2,i.class=a.toString(e.readUInt16BE(t)),t+=2,i.class&f&&(i.class&=p),ae.decode.bytes=t-r,i},ae.decode.bytes=0,ae.encodingLength=function(e){return m.encodingLength(e.name)+4},e.AUTHORITATIVE_ANSWER=1024,e.TRUNCATED_RESPONSE=512,e.RECURSION_DESIRED=256,e.RECURSION_AVAILABLE=128,e.AUTHENTIC_DATA=32,e.CHECKING_DISABLED=16,e.DNSSEC_OK=32768,e.encode=function(n,r,i){let a=!r;a&&(r=t.alloc(e.encodingLength(n))),i||=0;let o=i;return n.questions||=[],n.answers||=[],n.authorities||=[],n.additionals||=[],g.encode(n,r,i),i+=g.encode.bytes,i=se(n.questions,ae,r,i),i=se(n.answers,ie,r,i),i=se(n.authorities,ie,r,i),i=se(n.additionals,ie,r,i),e.encode.bytes=i-o,a&&e.encode.bytes!==r.length?r.slice(0,e.encode.bytes):r},e.encode.bytes=0,e.decode=function(t,n){n||=0;let r=n,i=g.decode(t,n);return n+=g.decode.bytes,n=ce(i.questions,ae,t,n),n=ce(i.answers,ie,t,n),n=ce(i.authorities,ie,t,n),n=ce(i.additionals,ie,t,n),e.decode.bytes=n-r,i},e.decode.bytes=0,e.encodingLength=function(e){return g.encodingLength(e)+oe(e.questions||[],ae)+oe(e.answers||[],ie)+oe(e.authorities||[],ie)+oe(e.additionals||[],ie)},e.streamEncode=function(n){let r=e.encode(n),i=t.alloc(2);i.writeUInt16BE(r.byteLength);let a=t.concat([i,r]);return e.streamEncode.bytes=a.byteLength,a},e.streamEncode.bytes=0,e.streamDecode=function(t){let n=t.readUInt16BE(0);if(t.byteLength<n+2)return null;let r=e.decode(t.slice(2));return e.streamDecode.bytes=e.decode.bytes,r},e.streamDecode.bytes=0;function oe(e,t){let n=0;for(let r=0;r<e.length;r++)n+=t.encodingLength(e[r]);return n}function se(e,t,n,r){for(let i=0;i<e.length;i++)t.encode(e[i],n,r),r+=t.encode.bytes;return r}function ce(e,t,n,r){for(let i=0;i<e.length;i++)e[i]=t.decode(n,r),r+=t.decode.bytes;return r}})),ak=R(((e,t)=>{var n=c;process.nextTick(s,42),t.exports=r;function r(e){var t=s;return r;function r(e){t(e||a)}function s(r){var a=[r];t=c,e(l);function c(e){a.push(e)}function l(e){var r=arguments;for(t=i(e)?s:c;a.length;)c(a.shift());function c(e){n(o,e,r)}}}}function i(e){return Object.prototype.toString.call(e)===`[object Error]`}function a(){}function o(e,t){e.apply(null,t)}function s(e){e===42&&(n=process.nextTick)}function c(e,t,n){process.nextTick(function(){e(t,n)})}})),ok=B(R(((e,t)=>{var n=ik(),r=ne(`dgram`),i=ak(),a=ne(`events`),o=ne(`os`),s=function(){};t.exports=function(e){e||={};var t=new a.EventEmitter,o=typeof e.port==`number`?e.port:5353,u=e.type||`udp4`,d=e.ip||e.host||(u===`udp4`?`224.0.0.251`:null),f={address:d,port:o},p={},m=!1,h=null;if(u===`udp6`&&(!d||!e.interface))throw Error("For IPv6 multicast you must specify `ip` and `interface`");var g=e.socket||r.createSocket({type:u,reuseAddr:e.reuseAddr!==!1,toString:function(){return u}});g.on(`error`,function(e){e.code===`EACCES`||e.code===`EADDRINUSE`?t.emit(`error`,e):t.emit(`warning`,e)}),g.on(`message`,function(e,r){try{e=n.decode(e)}catch(e){t.emit(`warning`,e);return}t.emit(`packet`,e,r),e.type===`query`&&t.emit(`query`,e,r),e.type===`response`&&t.emit(`response`,e,r)}),g.on(`listening`,function(){o||=f.port=g.address().port,e.multicast!==!1&&(t.update(),h=setInterval(t.update,5e3),g.setMulticastTTL(e.ttl||255),g.setMulticastLoopback(e.loopback!==!1))});var _=i(function(t){if(!o||e.bind===!1)return t(null);g.once(`error`,t),g.bind(o,e.bind||e.interface,function(){g.removeListener(`error`,t),t(null)})});return _(function(e){if(e)return t.emit(`error`,e);t.emit(`ready`)}),t.send=function(e,r,i){if(typeof r==`function`)return t.send(e,null,r);i||=s,r?!r.host&&!r.address&&(r.address=f.address):r=f,_(a);function a(t){if(m)return i();if(t)return i(t);var a=n.encode(e);g.send(a,0,a.length,r.port,r.address||r.host,i)}},t.response=t.respond=function(e,r,i){Array.isArray(e)&&(e={answers:e}),e.type=`response`,e.flags=(e.flags||0)|n.AUTHORITATIVE_ANSWER,t.send(e,r,i)},t.query=function(e,n,r,i){if(typeof n==`function`)return t.query(e,null,null,n);if(typeof n==`object`&&n&&n.port)return t.query(e,null,n,r);if(typeof r==`function`)return t.query(e,n,null,r);i||=s,typeof e==`string`&&(e=[{name:e,type:n||`ANY`}]),Array.isArray(e)&&(e={type:`query`,questions:e}),e.type=`query`,t.send(e,r,i)},t.destroy=function(e){if(e||=s,m)return process.nextTick(e);for(var t in m=!0,clearInterval(h),p)try{g.dropMembership(d,t)}catch{}p={},g.close(e)},t.update=function(){for(var n=e.interface?[].concat(e.interface):l(),r=!1,i=0;i<n.length;i++){var a=n[i];if(!p[a])try{g.addMembership(d,a),p[a]=!0,r=!0}catch(e){t.emit(`warning`,e)}}if(r){if(g.setMulticastInterface)try{g.setMulticastInterface(e.interface||c())}catch(e){t.emit(`warning`,e)}t.emit(`networkInterface`)}},t};function c(){for(var e=o.networkInterfaces(),t=Object.keys(e),n=0;n<t.length;n++)for(var r=e[t[n]],i=0;i<r.length;i++){var a=r[i];if(u(a.family)&&!a.internal)return o.platform()===`darwin`&&t[n]===`en0`?a.address:`0.0.0.0`}return`127.0.0.1`}function l(){for(var e=o.networkInterfaces(),t=Object.keys(e),n=[],r=0;r<t.length;r++)for(var i=e[t[r]],a=0;a<i.length;a++){var s=i[a];if(u(s.family)){n.push(s.address);break}}return n}function u(e){return e===4||e===`IPv4`}}))(),1);function sk(){return c(2).readUInt16BE(0)}function ck(){return c(4).readUInt32BE(0)}var lk=class{constructor(e){this.bitLength=e}value=0;set(e,t,n){return n&=(1<<e)-1,this.value|=n<<this.bitLength-e-t,this}get buffer(){let e=Math.ceil(this.bitLength/8),t=Buffer.alloc(e);return t.writeUIntBE(this.value,0,e),t}},uk=class{constructor(e){if(this.bitLength=e,e>32)throw Error()}_value=0n;offset=0n;set(e,t=1){let n=BigInt(e),r=BigInt(t);return n&=(1n<<r)-1n,this._value|=n<<BigInt(this.bitLength)-r-this.offset,this.offset+=r,this}get value(){return Number(this._value)}get buffer(){let e=Math.ceil(this.bitLength/8),t=Buffer.alloc(e);return t.writeUIntBE(this.value,0,e),t}};function dk(e,t,n=1){let r=e.toString(2).split(``);r=[...Array(8-r.length).fill(`0`),...r];let i=r.slice(t,t+n).join(``);return Number.parseInt(i,2)}function fk(e,t){return pk(e)(t)}function pk(e,t){let n=e.reduce((e,t)=>e+t,0),r=t?Buffer.alloc(n):void 0;return t=>{let i=r||Buffer.alloc(n),a=0;return t.forEach((t,n)=>{let r=e[n];r===8?i.writeBigUInt64BE(t,a):i.writeUIntBE(t,a,r),a+=r}),i}}function mk(e,t){let n=0;return t.map(t=>{let r;return r=t===8?e.readBigUInt64BE(n):e.readUIntBE(n,t),n+=t,r})}var hk=class{constructor(e){this.uint8Array=e}position=0;bitsPending=0;writeBits(e,t){if(e==0)return this;t&=4294967295>>>32-e;let n;return this.bitsPending>0?this.bitsPending>e?(this.uint8Array[this.position-1]|=t<<this.bitsPending-e,n=e,this.bitsPending-=e):this.bitsPending==e?(this.uint8Array[this.position-1]|=t,n=e,this.bitsPending=0):(this.uint8Array[this.position-1]|=t>>e-this.bitsPending,n=this.bitsPending,this.bitsPending=0):(n=Math.min(8,e),this.bitsPending=8-n,this.uint8Array[this.position++]=t>>e-n<<this.bitsPending),e-=n,e>0&&this.writeBits(e,t),this}readBits(e){return this._readBits(e)}_readBits(e,t){if(t===void 0&&(t=0),e==0)return t;let n,r;if(this.bitsPending>0){let t=this.uint8Array[this.position-1]&255>>8-this.bitsPending;r=Math.min(this.bitsPending,e),this.bitsPending-=r,n=t>>this.bitsPending}else r=Math.min(8,e),this.bitsPending=8-r,n=this.uint8Array[this.position++]>>this.bitsPending;return e-=r,t=t<<r|n,e>0?this._readBits(e,t):t}seekTo(e){this.position=e/8|0,this.bitsPending=e%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},gk=3988292384,_k=2197175160;function vk(e){return typeof e!=`string`}function yk(e){let t=Array(256),n=0;for(let r=0;r<256;++r)n=r,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,n=n&1?e^n>>>1:n>>>1,t[r]=n;return new Int32Array(t)}function bk(e){let t=new Int32Array(4096),n=0,r=0,i=0;for(i=0;i<256;++i)t[i]=e[i];for(i=0;i<256;++i)for(r=e[i],n=256+i;n<4096;n+=256)r=t[n]=r>>>8^e[r&255];let a=[];for(i=1;i<16;++i)a[i-1]=t.subarray(i*256,i*256+256);return a}function xk(e,t,n){let r=t^-1,i=0,a=e.length,o=0,s=0;for(;i<a;)o=e.charCodeAt(i++),o<128?r=r>>>8^n[(r^o)&255]:o<2048?(r=r>>>8^n[(r^(192|o>>6&31))&255],r=r>>>8^n[(r^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,s=e.charCodeAt(i++)&1023,r=r>>>8^n[(r^(240|o>>8&7))&255],r=r>>>8^n[(r^(128|o>>2&63))&255],r=r>>>8^n[(r^(128|s>>6&15|(o&3)<<4))&255],r=r>>>8^n[(r^(128|s&63))&255]):(r=r>>>8^n[(r^(224|o>>12&15))&255],r=r>>>8^n[(r^(128|o>>6&63))&255],r=r>>>8^n[(r^(128|o&63))&255]);return~r>>>0}function Sk(e,t,n,r){let[i,a,o,s,c,l,u,d,f,p,m,h,g,_,v]=r,y=t^-1,b=0,x=e.length-15;for(;b<x;)y=v[e[b++]^y&255]^_[e[b++]^y>>>8&255]^g[e[b++]^y>>>16&255]^h[e[b++]^y>>>24]^m[e[b++]]^p[e[b++]]^f[e[b++]]^d[e[b++]]^u[e[b++]]^l[e[b++]]^c[e[b++]]^s[e[b++]]^o[e[b++]]^a[e[b++]]^i[e[b++]]^n[e[b++]];for(x+=15;b<x;)y=y>>>8^n[(y^e[b++])&255];return~y>>>0}var Ck=yk(gk),wk=bk(Ck),Tk=yk(_k),Ek=bk(Tk);function Dk(e,t=0){return vk(e)?Sk(e,t,Ck,wk):xk(e,t,Ck)}function Ok(e,t=0){return vk(e)?Sk(e,t,Tk,Ek):xk(e,t,Tk)}function kk(e,t){return e+t&255}function Ak(e,t){return e+t&65535}function jk(e,t){return Number(BigInt(e)+BigInt(t)&4294967295n)}function Mk(e){return e&16777215}function Nk(e,t){let n=32768;return e<t&&t-e>n||e>t&&e-t<n}function Pk(e,t){let n=2147483648;return e<t&&t-e>n||e>t&&e-t<n}function Fk(e,t){return e===t||Pk(e,t)}var Ik=e=>Number.parseInt(e,10),Lk=(e,t)=>t?t[e]:void 0;async function Rk(e,t,n=`udp4`,r){let i;for(let a=e;a<=t;a++){let o=f(n);if(setImmediate(()=>o.bind({port:a,address:Lk(n,r)})),await new Promise(e=>{o.once(`error`,t=>e(t)),o.once(`listening`,()=>e())})){await new Promise(e=>o.close(()=>e()));continue}if(i=o.address()?.port,await new Promise(e=>o.close(()=>e())),e<=i&&i<=t)break}if(!i)throw Error(`port not found`);return i}function zk(e){return e===`IPv4`?4:e===`IPv6`?6:e}var Bk=Wd.default.debug,$=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=e=>{};execute=(...e)=>{if(!this.ended){for(let t of this.event.stack)t.execute(...e);(async()=>{for(let t of this.event.promiseStack)await t.execute(...e)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let e of this.event.stack)e.complete&&e.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&=(this.onended(),void 0)}};error=e=>{if(!this.ended){for(let t of this.event.stack)t.error&&t.error(e);this.allUnsubscribe()}};allUnsubscribe=()=>{this.ended||(this.event={stack:[],promiseStack:[],eventId:0})};subscribe=(e,t,n)=>{let r=this.event.eventId;this.event.stack.push({execute:e,id:r,complete:t,error:n}),this.event.eventId++;let i=()=>{this.event.stack=this.event.stack.filter(e=>e.id!==r&&e)};return{unSubscribe:i,disposer:e=>{e.push(i)}}};pipe(e){this.subscribe((...t)=>{e.execute(...t)})}queuingSubscribe=(e,t,n)=>{if(this.ended)throw Error(`event completed`);let r=this.event.eventId;this.event.promiseStack.push({execute:e,id:r,complete:t,error:n}),this.event.eventId++;let i=()=>{this.event.stack=this.event.stack.filter(e=>e.id!==r&&e)};return{unSubscribe:i,disposer:e=>{e.push(i)}}};once=(e,t,n)=>{let r=this.subscribe((...t)=>{r.unSubscribe(),e(...t)},t,n)};watch=(e,t)=>new Promise((n,r)=>{let i=t&&setTimeout(()=>{r(`Event watch timeout`)},t),{unSubscribe:a}=this.subscribe((...t)=>{e(...t)&&(i&&clearTimeout(i),a(),n(t))})});asPromise=e=>new Promise((t,n)=>{let r=e&&setTimeout(()=>{n(`Event asPromise timeout`)},e);this.once((...e)=>{r&&clearTimeout(r),t(e)},()=>{r&&clearTimeout(r),t([])},e=>{r&&clearTimeout(r),n(e)})});get returnTrigger(){let{execute:e,error:t,complete:n}=this;return{execute:e,error:t,complete:n}}get returnListener(){let{subscribe:e,once:t,asPromise:n}=this;return{subscribe:e,once:t,asPromise:n}}get length(){return this.event.stack.length}},Vk=class{_disposer=[];push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e()),this._disposer=[]}},Hk=Bk(`werift-ice:packages/ice/src/transport.ts`),Uk=class e{constructor(e,t={}){this.socketType=e,this.options=t,this.socket=f(e),this.socket.on(`message`,(e,t)=>{zk(t.family)===6&&([t.address]=t.address.split(`%`)),this.rinfo=t;try{this.onData(e,[t.address,t.port])}catch(e){Hk(`onData error`,e)}})}type=`udp`;socket;rinfo;onData=()=>{};closed=!1;static async init(t,n={}){let r=new e(t,n);return await r.init(),r}async init(){let e=Lk(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let t=await Rk(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else this.socket.bind({address:e});await new Promise(e=>this.socket.once(`listening`,e))}send=async(e,t)=>{if(t&&!_.isIP(t[0]))return new Promise((n,r)=>{this.socket.send(e,t[1],t[0],i=>{i?(Hk(`send error`,t,e),r(i)):n()})});t??=[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,t[1],t[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()}})},Wk=class e{type=`tcp`;stream;constructor(e){this.stream=new Kk(`tcp`,()=>v({port:e[1],host:e[0]}))}static async init(t){let n=new e(t);return await n.init(),n}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}send=async(e,t)=>{await this.stream.send(e,t)};close=async()=>{await this.stream.close()}},Gk=class e{type=`tls`;stream;constructor(e,t={}){this.stream=new Kk(`tls`,()=>C.connect({...t,host:e[0],port:e[1]}))}static async init(t,n={}){let r=new e(t,n);return await r.init(),r}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}send=async(e,t)=>{await this.stream.send(e,t)};close=async()=>{await this.stream.close()}},Kk=class{constructor(e,t,n=e===`tls`?`secureConnect`:`connect`){this.createClient=t,this.connectEvent=n,this.type=e,this.connect()}type;connecting;client;onData=()=>{};closed=!1;connect(){if(this.closed)return;this.client&&this.client.destroy();let e=this.createClient();this.client=e,this.connecting=new Promise((t,n)=>{let r=()=>{e.off(`error`,i),t()},i=t=>{e.off(this.connectEvent,r),n(t)};e.once(this.connectEvent,r),e.once(`error`,i)}),e.on(`data`,e=>{let t=[this.client.remoteAddress,this.client.remotePort];this.onData(e,t)}),e.on(`end`,()=>{this.connect()}),e.on(`error`,e=>{Hk(`${this.type} transport error`,e)})}async waitForConnect(){await this.connecting}get address(){return{}}send=async(e,t)=>{await this.connecting,await new Promise((t,n)=>{this.client.write(e,e=>{if(e){n(e);return}t()})})};close=async()=>{this.closed=!0,this.client?.destroy()}},qk={rsa_1:1,ecdsa_3:3},Jk={sha256_4:4},Yk={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},Xk=Object.values(Yk),Zk={x25519_29:29,secp256r1_23:23},Qk=Object.values(Zk),$k={named_curve_3:3},eA={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},tA=[1,64],nA=[{hash:Jk.sha256_4,signature:qk.rsa_1},{hash:Jk.sha256_4,signature:qk.ecdsa_3}],rA=()=>{let e=ZO.utils.randomPrivateKey(),t=ZO.getPublicKey(e,!1);return{privateKey:Buffer.from(e),publicKey:Buffer.from(t)}},iA=({publicKey:e,privateKey:t})=>{let n=ZO.getSharedSecret(t,e);return Buffer.from(n).subarray(1)};function aA(e,t,n){switch(n){case Zk.secp256r1_23:return iA({publicKey:e,privateKey:t});case Zk.x25519_29:return Buffer.from(iE.default.scalarMult(t,e));default:throw Error()}}function oA(e,t,n){let r=o(e,t);return r.update(n),r.digest()}function sA(e,t,n,r=`sha256`){let i=n,a=[],o=t;do{o=oA(r,e,o);let i=oA(r,e,Buffer.concat([o,t]));a.push(i),n-=i.length}while(n>0);return Buffer.concat(a,i)}function cA(e,t,n){return sA(e,Buffer.concat([Buffer.from(`master secret`),t,n]),48)}function lA(e,t){let n=dA(`sha256`,t);return sA(e,Buffer.concat([Buffer.from(`extended master secret`),n]),48)}function uA(e,t,n,r,i,a){let o=a?r:i,s=a?i:r;return sA(n,Buffer.concat([Buffer.from(e),o,s]),t)}function dA(e,t){return a(e).update(t).digest()}function fA(e,t,n,r=12){let i=dA(`sha256`,t);return sA(e,Buffer.concat([Buffer.from(n),i]),r)}function pA(e,t){return fA(e,t,`client finished`)}function mA(e,t){return fA(e,t,`server finished`)}function hA(e,t,n,r,i,a,o=`sha256`){let s=r*2+i*2,c=e,l=Buffer.concat([n,t]),u=sA(c,Buffer.concat([Buffer.from(`key expansion`),l]),s,o),d=(0,Q.createDecode)(u),f=d.readBuffer(r),p=d.readBuffer(r),m=d.readBuffer(i),h=d.readBuffer(i),g=Buffer.alloc(a,0),_=Buffer.alloc(a,0);return m.copy(g,0),h.copy(_,0),{clientWriteKey:f,serverWriteKey:p,clientNonce:g,serverNonce:_}}var gA={CLIENT:1,SERVER:2},_A=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...e){throw Error(`not implemented`)}encrypt(...e){throw Error(`not implemented`)}decrypt(...e){throw Error(`not implemented`)}toString(){return this.name}},vA=d;aw.set(vA);var yA=class{constructor(e,t,n,r){this.sessionType=e,this.certPem=t,this.keyPem=n,t&&n&&r&&this.parseX509(t,n,r)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(e,t)=>{let n=(()=>{switch(e.signature){case qk.rsa_1:return`RSASSA-PKCS1-v1_5`;case qk.ecdsa_3:return`ECDSA`}})(),r=(()=>{switch(e.hash){case Jk.sha256_4:return`SHA-256`}})(),i=(()=>{switch(t){case Zk.secp256r1_23:return`P-256`;case Zk.x25519_29:return n===`ECDSA`?`P-256`:`X25519`;default:if(n===`ECDSA`)return`P-256`;if(n===`RSASSA-PKCS1-v1_5`)return`X25519`}})(),a=(()=>{switch(n){case`ECDSA`:return{name:n,hash:r,namedCurve:i};case`RSASSA-PKCS1-v1_5`:return{name:n,hash:r,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),o=await vA.subtle.generateKey(a,!0,[`sign`,`verify`]);return{certPem:(await MT.createSelfSigned({serialNumber:c(8).toString(`hex`),name:`C=AU, ST=Some-State, O=Internet Widgits Pty Ltd`,notBefore:new Date,notAfter:new Date(Date.now()+31536e7),signingAlgorithm:a,keys:o})).toString(`pem`),keyPem:kw.encode(await vA.subtle.exportKey(`pkcs8`,o.privateKey),`private key`),signatureHash:e}};encryptPacket(e){let t=e.recordLayerHeader,n=t.protocolVersion.major<<8|t.protocolVersion.minor,r=this.cipher.encrypt(this.sessionType,e.fragment,{type:t.contentType,version:n,epoch:t.epoch,sequenceNumber:t.sequenceNumber});return e.fragment=r,e.recordLayerHeader.contentLen=r.length,e}decryptPacket(e){let t=e.recordLayerHeader,n=t.protocolVersion.major<<8|t.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,e.fragment,{type:t.contentType,version:n,epoch:t.epoch,sequenceNumber:t.sequenceNumber})}verifyData(e){return this.sessionType===gA.CLIENT?pA(this.masterSecret,e):mA(this.masterSecret,e)}signatureData(e,t){let n=s(t).update(e),r=this.localPrivateKey.toPEM().toString();return n.sign(r)}generateKeySignature(e){let t=this.sessionType===gA.CLIENT?this.localRandom:this.remoteRandom,n=this.sessionType===gA.SERVER?this.localRandom:this.remoteRandom,r=this.valueKeySignature(t.serialize(),n.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(r,e)}parseX509(e,t,n){let r=Gd.Certificate.fromPEM(Buffer.from(e)),i=Gd.PrivateKey.fromPEM(Buffer.from(t));this.localCert=r.raw,this.localPrivateKey=i,this.signatureHashAlgorithm=n}valueKeySignature(e,t,n,r){let i=Buffer.from((0,Q.encode)({type:$k.named_curve_3,curve:r,len:n.length},{type:Q.types.uint8,curve:Q.types.uint16be,len:Q.types.uint8}).slice());return Buffer.concat([e,t,i,n])}},bA=class{srtpProfile;static findMatchingSRTPProfile(e,t){for(let n of t)if(e.includes(n))return n}},xA=e=>`0x`+e.toString(`hex`).replace(/(.)(.)/g,`$1$2 `).split(` `).filter(e=>e!=null&&e.length>0).join(`,0x`),SA=e=>Object.entries({...e}).reduce((e,[t,n])=>((typeof n==`number`||typeof n==`string`)&&(e[t]=n),Buffer.isBuffer(n)&&(e[t]=xA(n)),e),{}),CA=class e{constructor(e,t,n,r,i,a){this.msg_type=e,this.length=t,this.message_seq=n,this.fragment_offset=r,this.fragment_length=i,this.fragment=a}static spec={msg_type:Q.types.uint8,length:Q.types.uint24be,message_seq:Q.types.uint16be,fragment_offset:Q.types.uint24be,fragment_length:Q.types.uint24be,fragment:Q.types.buffer(e=>e.current.fragment_length)};get summary(){return SA(this)}static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}chunk(t){let n=0,r=this.fragment.length;if(r===0)return[new e(this.msg_type,r,this.message_seq,n,0,this.fragment)];let i=[];for(t||=1240;n<r;){let a=Math.min(t,r-n),o=Buffer.from(this.fragment.slice(n,n+a));if(o.length<=0)throw Error(`Zero or less bytes processed while fragmenting handshake message.`);i.push(new e(this.msg_type,r,this.message_seq,n,o.length,o)),n+=o.length}return i}static assemble(t){if(!t?.length)throw Error(`cannot reassemble handshake from empty array`);t=t.sort((e,t)=>e.fragment_offset-t.fragment_offset);let n=Buffer.alloc(t[0].length);for(let e of t)e.fragment.copy(n,e.fragment_offset);return new e(t[0].msg_type,t[0].length,t[0].message_seq,0,n.length,n)}static findAllFragments(e,t){let n=e.find(e=>e.msg_type===t);return!n||!e?.length?[]:e.filter(e=>e.msg_type===n.msg_type&&e.message_seq===n.message_seq&&e.length===n.length)}},{uint16be:wA,uint24be:TA,buffer:EA,array:DA,uint8:OA,string:kA}=Q.types,AA=DA({type:wA,data:EA(wA)},wA,`bytes`),jA=EA(TA),MA=OA,NA=kA(wA),PA={hash:OA,signature:OA},FA={major:OA,minor:OA},IA=class e{constructor(e=Math.floor(Date.now()/1e3),t=c(28)){this.gmt_unix_time=e,this.random_bytes=t}static spec={gmt_unix_time:Q.types.uint32be,random_bytes:Q.types.buffer(28)};static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}static from(t){return new e(...Object.values(t))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}},LA=class e{constructor(e,t,n,r,i,a,o){this.clientVersion=e,this.random=t,this.sessionId=n,this.cookie=r,this.cipherSuites=i,this.compressionMethods=a,this.extensions=o}msgType=1;messageSeq=0;static spec={clientVersion:{major:Q.types.uint8,minor:Q.types.uint8},random:IA.spec,sessionId:Q.types.buffer(Q.types.uint8),cookie:Q.types.buffer(Q.types.uint8),cipherSuites:Q.types.array(Q.types.uint16be,Q.types.uint16be,`bytes`),compressionMethods:Q.types.array(Q.types.uint8,Q.types.uint8,`bytes`),extensions:AA};static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},RA=class e{constructor(e,t,n,r,i){this.epoch=e,this.sequenceNumber=t,this.contentType=n,this.protocolVersion=r,this.contentLen=i}static spec={epoch:Q.types.uint16be,sequenceNumber:Q.types.uint48be,contentType:Q.types.uint8,protocolVersion:FA,contentLen:Q.types.uint16be};static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}},zA=class e{constructor(e,t){this.recordLayerHeader=e,this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:xA(this.fragment)}}static createEmpty(){return new e(void 0,void 0)}static deSerialize(t){if(t.length<13)throw Error(`Invalid DTLS record: buffer is too short`);let n=t.readUInt8(0),r=t.readUInt8(1),i=t.readUInt8(2),a=t.readUInt16BE(3),o=t.slice(5,11).readUIntBE(0,6),s=t.readUInt16BE(11);if(t.length<13+s)throw Error(`Invalid DTLS record: fragment length exceeds buffer`);let c=t.slice(13,13+s);return new e({contentType:n,protocolVersion:{major:r,minor:i},epoch:a,sequenceNumber:o,contentLen:s},c)}serialize(){let e=this.fragment.length,t=13+e,n=Buffer.alloc(t);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 RA(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},BA=e=>t=>(e.lastFlight=t,t.flatMap(t=>(t.messageSeq=e.sequenceNumber++,t.toFragment().chunk()))),VA=e=>(t,n)=>t.map(t=>new zA({contentType:t.type,protocolVersion:e.version,epoch:e.epoch,sequenceNumber:n,contentLen:t.fragment.length},t.fragment)),HA=(e=>(e[e.CloseNotify=0]=`CloseNotify`,e[e.UnexpectedMessage=10]=`UnexpectedMessage`,e[e.BadRecordMac=20]=`BadRecordMac`,e[e.DecryptionFailed=21]=`DecryptionFailed`,e[e.RecordOverflow=22]=`RecordOverflow`,e[e.DecompressionFailure=30]=`DecompressionFailure`,e[e.HandshakeFailure=40]=`HandshakeFailure`,e[e.NoCertificate=41]=`NoCertificate`,e[e.BadCertificate=42]=`BadCertificate`,e[e.UnsupportedCertificate=43]=`UnsupportedCertificate`,e[e.CertificateRevoked=44]=`CertificateRevoked`,e[e.CertificateExpired=45]=`CertificateExpired`,e[e.CertificateUnknown=46]=`CertificateUnknown`,e[e.IllegalParameter=47]=`IllegalParameter`,e[e.UnknownCa=48]=`UnknownCa`,e[e.AccessDenied=49]=`AccessDenied`,e[e.DecodeError=50]=`DecodeError`,e[e.DecryptError=51]=`DecryptError`,e[e.ExportRestriction=60]=`ExportRestriction`,e[e.ProtocolVersion=70]=`ProtocolVersion`,e[e.InsufficientSecurity=71]=`InsufficientSecurity`,e[e.InternalError=80]=`InternalError`,e[e.UserCanceled=90]=`UserCanceled`,e[e.NoRenegotiation=100]=`NoRenegotiation`,e[e.UnsupportedExtension=110]=`UnsupportedExtension`,e))(HA||{}),UA=Bk(`werift-dtls : packages/dtls/src/flight/flight.ts : warn`),WA=Bk(`werift-dtls : packages/dtls/src/flight/flight.ts : err`),GA=class e{constructor(e,t,n,r){this.transport=e,this.dtls=t,this.flight=n,this.nextFlight=r}state=`PREPARING`;static RetransmitCount=10;createPacket(e){let t=BA(this.dtls)(e);return this.dtls.bufferHandshakeCache(t,!0,this.flight),VA(this.dtls)(t.map(e=>({type:22,fragment:e.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(t){let n=0;for(;n<=e.RetransmitCount;n++){if(this.setState(`SENDING`),this.send(t).catch(e=>{WA(`fail to send`,WA)}),this.setState(`WAITING`),this.nextFlight===void 0){this.setState(`FINISHED`);break}if(await E(1e3*((n+1)/2)),this.dtls.flight>=this.nextFlight){this.setState(`FINISHED`);break}UA(this.dtls.sessionId,`retransmit`,n,this.dtls.flight)}if(n>e.RetransmitCount)throw WA(this.dtls.sessionId,`retransmit failed`,n),Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(e=>this.transport.send(e)));setState(e){this.state=e}},KA=class extends GA{constructor(e,t,n){super(e,t,1,3),this.cipher=n}async exec(e){if(this.dtls.flight===1)throw Error();this.dtls.flight=1;let t=new LA({major:254,minor:253},new IA,Buffer.from([]),Buffer.from([]),Xk,[0],e);this.dtls.version=t.clientVersion,this.cipher.localRandom=IA.from(t.random);let n=this.createPacket([t]),r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}},qA=Bk(`werift-dtls : packages/dtls/src/flight/client/flight3.ts : log`),JA=class extends GA{constructor(e,t){super(e,t,3,5)}async exec(e){if(this.dtls.flight===3)throw Error();this.dtls.flight=3,this.dtls.handshakeCache=[];let[t]=this.dtls.lastFlight;qA(`dtls version`,t.clientVersion),t.cookie=e.cookie,this.dtls.cookie=e.cookie;let n=this.createPacket([t]),r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}},YA={NULL:0,ECDHE:1},XA={NULL:0,RSA:1,ECDSA:2,PSK:3},ZA={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},QA=class{id=0;name;signType;keyType;toString(){return this.name}};function $A(){let e=new QA;return e.id=ZA.RSA,e.name=`RSA`,e.keyType=XA.RSA,e}function ej(){let e=new QA;return e.id=ZA.ECDHE_RSA,e.name=`ECDHE_RSA`,e.signType=YA.ECDHE,e.keyType=XA.RSA,e}function tj(){let e=new QA;return e.id=ZA.ECDHE_ECDSA,e.name=`ECDHE_ECDSA`,e.signType=YA.ECDHE,e.keyType=XA.ECDSA,e}function nj(){let e=new QA;return e.id=ZA.PSK,e.name=`PSK`,e.signType=YA.NULL,e.keyType=XA.PSK,e}function rj(){let e=new QA;return e.id=ZA.ECDHE_PSK,e.name=`ECDHE_PSK`,e.signType=YA.ECDHE,e.keyType=XA.PSK,e}var ij=Bk(`werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err`),aj=class extends _A{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return SA(this)}init(e,t,n){let r=hA(e,n,t,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=r.clientWriteKey,this.serverWriteKey=r.serverWriteKey,this.clientNonce=r.clientNonce,this.serverNonce=r.serverNonce}encrypt(e,t,n){let i=e===gA.CLIENT,a=i?this.clientNonce:this.serverNonce,o=i?this.clientWriteKey:this.serverWriteKey;if(!a||!o)throw Error();a.writeUInt16BE(n.epoch,this.nonceImplicitLength),a.writeUIntBE(n.sequenceNumber,this.nonceImplicitLength+2,6);let s=a.slice(this.nonceImplicitLength),c=this.encodeAdditionalBuffer(n,t.length),l=r(this.blockAlgorithm,o,a,{authTagLength:this.authTagLength});l.setAAD(c,{plaintextLength:t.length});let u=l.update(t),d=l.final(),f=l.getAuthTag();return Buffer.concat([s,u,d,f])}encodeAdditionalBuffer(e,t){let n=Buffer.alloc(13);return n.writeUInt16BE(e.epoch,0),n.writeUintBE(e.sequenceNumber,2,6),n.writeUInt8(e.type,8),n.writeUInt16BE(e.version,9),n.writeUInt16BE(t,11),n}decrypt(e,t,n){let r=e===gA.CLIENT,a=r?this.serverNonce:this.clientNonce,o=r?this.serverWriteKey:this.clientWriteKey;if(!a||!o)throw Error();t.subarray(0,this.nonceExplicitLength).copy(a,this.nonceImplicitLength);let s=t.subarray(this.nonceExplicitLength,t.length-this.authTagLength),c=t.subarray(t.length-this.authTagLength),l=this.encodeAdditionalBuffer(n,s.length),u=i(this.blockAlgorithm,o,a,{authTagLength:this.authTagLength});u.setAuthTag(c),u.setAAD(l,{plaintextLength:s.length});let d=u.update(s);try{let e=u.final();return e.length>0?Buffer.concat([d,e]):d}catch(r){throw ij(`decrypt failed`,r,e,xA(t),n,this.summary),r}}},oj={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},sj={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},cj={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},lj=$A(),uj=ej(),dj=tj(),fj=nj(),pj=rj();function mj(e){switch(e){case oj.TLS_RSA_WITH_AES_128_GCM_SHA256:return hj(oj.TLS_RSA_WITH_AES_128_GCM_SHA256,`TLS_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,lj,sj);case oj.TLS_RSA_WITH_AES_256_GCM_SHA384:return hj(oj.TLS_RSA_WITH_AES_256_GCM_SHA384,`TLS_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,lj,cj,`sha384`);case oj.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return hj(oj.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,uj,sj);case oj.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return hj(oj.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,uj,cj,`sha384`);case oj.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return hj(oj.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,dj,sj);case oj.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return hj(oj.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,dj,cj,`sha384`);case oj.TLS_PSK_WITH_AES_128_GCM_SHA256:return hj(oj.TLS_PSK_WITH_AES_128_GCM_SHA256,`TLS_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,fj,sj,`sha256`);case oj.TLS_PSK_WITH_AES_256_GCM_SHA384:return hj(oj.TLS_PSK_WITH_AES_256_GCM_SHA384,`TLS_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,fj,cj,`sha384`);case oj.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return hj(oj.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,pj,sj,`sha256`);case oj.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return hj(oj.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,pj,cj,`sha384`)}return null}function hj(e,t,n,r,i,a=`sha256`){let o=new aj;return o.id=e,o.name=t,o.blockAlgorithm=n,o.kx=r,o.hashAlgorithm=a,o.keyLength=i.K_LEN,o.nonceLength=i.N_MAX,o.nonceImplicitLength=4,o.nonceExplicitLength=8,o.ivLength=o.nonceImplicitLength,o.authTagLength=16,o}function gj(e){switch(e){case Zk.secp256r1_23:{let{privateKey:t,publicKey:n}=rA();return{curve:e,privateKey:t,publicKey:n}}case Zk.x25519_29:{let t=iE.default.box.keyPair();return{curve:e,privateKey:Buffer.from(t.secretKey.buffer),publicKey:Buffer.from(t.publicKey.buffer)}}default:throw Error()}}var _j=class{static type=23},vj=class e{static type=65281;static spec={type:Q.types.uint16be,data:Q.types.uint8};type=e.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new e}static deSerialize(t){return new e((0,Q.decode)(t,e.spec))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},yj=class e{static type=14;static spec={type:Q.types.uint16be,data:Q.types.buffer(Q.types.uint16be)};type=e.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(t,n){return new e({profiles:t,mki:n})}static deSerialize(t){let n=new e((0,Q.decode)(t,e.spec)),r=n.data.readUInt16BE(),i=Array(r/2);for(let e=0;e<i.length;e++)i[e]=n.data.readUInt16BE(e*2+2);return n.profiles=i,n.mki=n.data.slice(r+2),n}serialize(){let t=Buffer.alloc(2);t.writeUInt16BE(this.profiles.length*2);let n=Buffer.concat([t,...this.profiles.map(e=>{let t=Buffer.alloc(2);return t.writeUInt16BE(e),t}),this.mki]);this.data=n;let r=(0,Q.encode)(this,e.spec).slice();return Buffer.from(r)}static fromData(t){let n=Buffer.alloc(4);return n.writeUInt16BE(e.type),n.writeUInt16BE(t.length,2),e.deSerialize(Buffer.concat([n,t]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},bj=class e{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:Q.types.array(jA,Q.types.uint24be,`bytes`)};static createEmpty(){return new e(void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},xj=class e{constructor(e=1){this.type=e}static spec={type:Q.types.uint8};static createEmpty(){return new e}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}},Sj=class e{constructor(e,t){this.algorithm=e,this.signature=t}msgType=15;messageSeq;static spec={algorithm:Q.types.uint16be,signature:Q.types.buffer(Q.types.uint16be)};static createEmpty(){return new e(void 0,void 0)}static deSerialize(t){let n=(0,Q.decode)(t,e.spec);return new e(...Object.values(n))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Cj=class e{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:Q.types.buffer(Q.types.uint8)};static createEmpty(){return new e(void 0)}static deSerialize(t){let n=(0,Q.decode)(t,e.spec);return new e(...Object.values(n))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},wj=class e{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new e(void 0)}static deSerialize(t){return new e(t)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Tj=class e{constructor(e,t,n){this.certificateTypes=e,this.signatures=t,this.authorities=n}msgType=13;messageSeq;static spec={certificateTypes:Q.types.array(MA,Q.types.uint8,`bytes`),signatures:Q.types.array(PA,Q.types.uint16be,`bytes`),authorities:Q.types.array(NA,Q.types.uint16be,`bytes`)};static createEmpty(){return new e(void 0,void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Ej=class e{constructor(e,t,n,r,i,a){this.serverVersion=e,this.random=t,this.sessionId=n,this.cipherSuite=r,this.compressionMethod=i,this.extensions=a}msgType=2;messageSeq;static spec={serverVersion:FA,random:IA.spec,sessionId:Q.types.buffer(Q.types.uint8),cipherSuite:Q.types.uint16be,compressionMethod:Q.types.uint8};static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){let n=(0,Q.decode)(t,e.spec),r=new e(...Object.values(n));return r.serialize().length<t.length?new e(...Object.values((0,Q.decode)(t,{...e.spec,extensions:AA}))):r}serialize(){let t=this.extensions===void 0?(0,Q.encode)(this,e.spec).slice():(0,Q.encode)(this,{...e.spec,extensions:AA}).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Dj=class e{msgType=14;messageSeq;static spec={};static createEmpty(){return new e}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}};function Oj(e,t){return Buffer.from((0,Q.encode)(e,t).slice())}var kj=class e{constructor(e,t,n,r,i,a,o,s){this.ellipticCurveType=e,this.namedCurve=t,this.publicKeyLength=n,this.publicKey=r,this.hashAlgorithm=i,this.signatureAlgorithm=a,this.signatureLength=o,this.signature=s}msgType=12;messageSeq;static spec={ellipticCurveType:Q.types.uint8,namedCurve:Q.types.uint16be,publicKeyLength:Q.types.uint8,publicKey:Q.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:Q.types.uint8,signatureAlgorithm:Q.types.uint8,signatureLength:Q.types.uint16be,signature:Q.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new e(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(t){let n=(0,Q.decode)(t,e.spec);return new e(...Object.values(n))}serialize(){return Oj(this,e.spec)}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Aj=e=>{switch(e){case 1:case 7:return 16}},jj=e=>{switch(e){case 1:return 14;case 7:return 12}};Bk(`werift-rtp : packages/rtp/src/codec/av1.ts`),Object.entries({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`}).reduce((e,[t,n])=>(e[n]=Number(t),e),{}),Buffer.from([0,0,0,1]);function Mj(e,t){let n=Buffer.alloc(t);return e.copy(n),n}function Nj(e){return Number.parseInt(e.toString(),10)}function Pj(e){let t=e[0];return t>127&&t<192}var Fj=class e{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(t,n,r,i){let a=new e({type:t,count:n,version:2,length:i}).serialize();return Buffer.concat([a,r])}serialize(){let e=new lk(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),fk([1,1,2],[e.value,this.type,this.length])}static deSerialize(t){let[n,r,i]=mk(t,[1,1,2]),a=dk(n,0,2),o=dk(n,2,1)>0,s=dk(n,3,5);return new e({version:a,padding:o,count:s,type:r,length:i})}},Ij=class e{static count=4;count=e.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(t){let[n,r]=mk(t,[4,4]),i=[];for(let e=8;e<t.length;e+=8)i.push({ssrc:t.readUInt32BE(e),sequenceNumber:t[e+4]});return new e({senderSsrc:n,mediaSsrc:r,fir:i})}serialize(){let e=fk([4,4],[this.senderSsrc,this.mediaSsrc]),t=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:e,sequenceNumber:n},r)=>{t.writeUInt32BE(e,r*8),t[r*8+4]=n}),Buffer.concat([e,t])}},Lj=class e{static count=1;count=e.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(t){let[n,r]=mk(t,[4,4]);return new e({senderSsrc:n,mediaSsrc:r})}serialize(){return fk([4,4],[this.senderSsrc,this.mediaSsrc])}},Rj=class e{static count=15;length;count=e.count;senderSsrc;mediaSsrc;uniqueID=`REMB`;ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let[n,r,i,a,o]=mk(t,[4,4,4,1,1]),s=dk(o,0,6),c=(dk(o,6,2)<<16)+(t[14]<<8)+t[15],l=s>46?18446744073709551615n:BigInt(c)<<BigInt(s),u=[];for(let e=16;e<t.length;e+=4){let n=t.slice(e).readUIntBE(0,4);u.push(n)}return new e({senderSsrc:n,mediaSsrc:r,uniqueID:fk([4],[i]).toString(),ssrcNum:a,brExp:s,brMantissa:c,ssrcFeedbacks:u,bitrate:l})}serialize(){let e=Buffer.concat([fk([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),fk([1],[this.ssrcNum])]),t=new lk(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);let n=Buffer.concat(this.ssrcFeedbacks.map(e=>fk([4],[e]))),r=Buffer.concat([e,fk([3],[t.value]),n]);return this.length=r.length/4,r}},zj=Bk(`werift-rtp: /rtcp/psfb/index`),Bj=class e{static type=206;type=e.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return Fj.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(t,n){let r;switch(n.count){case Ij.count:r=Ij.deSerialize(t);break;case Lj.count:r=Lj.deSerialize(t);break;case Rj.count:r=Rj.deSerialize(t);break;default:zj(`unknown psfb packet`,n.count)}return new e({feedback:r})}},Vj=class e{ssrc=0;reports=[];static type=201;type=e.type;constructor(e={}){Object.assign(this,e)}serialize(){let t=fk([4],[this.ssrc]);return t=Buffer.concat([t,...this.reports.map(e=>e.serialize())]),Fj.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let[r]=mk(t,[4]),i=4,a=[];for(let e=0;e<n;e++)a.push(Hj.deSerialize(t.slice(i,i+24))),i+=24;return new e({ssrc:r,reports:a})}},Hj=class e{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 fk([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(t){let[n,r,i,a,o,s,c]=mk(t,[4,1,3,4,4,4,4]);return new e({ssrc:n,fractionLost:r,packetsLost:i,highestSequence:a,jitter:o,lsr:s,dlsr:c})}},Uj=205,Wj=class e{static count=1;count=e.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e),this.header||=new Fj({type:Uj,count:this.count,version:2})}static deSerialize(t,n){let[r,i]=mk(t,[4,4]),a=[];for(let e=8;e<t.length;e+=4){let[n,r]=mk(t.subarray(e),[2,2]);a.push(n);for(let e=0;e<16;e++)r>>e&1&&a.push(n+e+1)}return new e({header:n,senderSsrc:r,mediaSourceSsrc:i,lost:a})}serialize(){let e=fk([4,4],[this.senderSsrc,this.mediaSourceSsrc]),t=[];if(this.lost.length>0){let e=this.lost[0],n=0;this.lost.slice(1).forEach(r=>{let i=r-e-1;i>=0&&i<16?n|=1<<i:(t.push(fk([2,2],[e,n])),e=r,n=0)}),t.push(fk([2,2],[e,n]))}let n=Buffer.concat([e,Buffer.concat(t)]);return this.header.length=n.length/4,Buffer.concat([this.header.serialize(),n])}},Gj=Bk(`werift/rtp/rtcp/rtpfb/twcc`),Kj=class e{static count=15;count=e.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||=new Fj({type:205,count:this.count,version:2})}static deSerialize(t,n){let[r,i,a,o,s,c]=mk(t,[4,4,2,2,3,1]),l=[],u=[],d=16;for(let e=0;e<o;){let n=dk(t.slice(d,d+1)[0],0,1),r;switch(n){case 0:{let n=qj.deSerialize(t.slice(d,d+2));r=n;let i=Math.min(o-e,n.runLength);if(n.packetStatus===1||n.packetStatus===2)for(let e=0;e<i;e++)u.push(new Yj({type:n.packetStatus}));e+=i}break;case 1:{let n=Jj.deSerialize(t.slice(d,d+2));r=n,n.symbolSize===0&&n.symbolList.forEach(e=>{e===1&&u.push(new Yj({type:1}))}),n.symbolSize===1&&n.symbolList.forEach(e=>{(e===1||e===2)&&u.push(new Yj({type:e}))}),e+=n.symbolList.length}}if(!r)throw Error();d+=2,l.push(r)}let f=d;return u.forEach(e=>{e.type===1&&(e.deSerialize(t.slice(f,f+1)),f++),e.type===2&&(e.deSerialize(t.slice(f,f+2)),f+=2)}),new e({senderSsrc:r,mediaSourceSsrc:i,baseSequenceNumber:a,packetStatusCount:o,referenceTime:s,fbPktCount:c,recvDeltas:u,packetChunks:l,header:n})}serialize(){let e=fk([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),t=Buffer.concat(this.packetChunks.map(e=>e.serialize())),n=Buffer.concat(this.recvDeltas.map(e=>{try{return e.serialize()}catch(e){Gj(e?.message);return}}).filter(e=>e)),r=Buffer.concat([e,t,n]);if(this.header.padding&&r.length%4!=0){let e=4-r.length%4,t=Buffer.alloc(e);return t[t.length-1]=t.length,this.header.length=Math.floor((r.length+t.length)/4),Buffer.concat([this.header.serialize(),r,t])}return this.header.length=Math.floor(r.length/4),Buffer.concat([this.header.serialize(),r])}get packetResults(){let e=this.baseSequenceNumber-1,t=this.packetChunks.filter(e=>e instanceof qj).flatMap(t=>t.results(e)),n=0,r=BigInt(this.referenceTime)*64n;for(let e of t){let t=this.recvDeltas[n];e.received&&t&&(r+=BigInt(t.delta)/1000n,e.delta=t.delta,e.receivedAtMs=Number(r),n++)}return t}},qj=class e{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(t){let n=dk(t[0],1,2),r=(dk(t[0],3,5)<<8)+t[1];return new e({type:0,packetStatus:n,runLength:r})}serialize(){return new uk(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let t=this.packetStatus===1||this.packetStatus===2,n=[];for(let r=0;r<=this.runLength;++r)n.push(new Xj({sequenceNumber:++e,received:t}));return n}},Jj=class e{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=dk(t[0],1,1),r=[];function i(e,t){for(let n=0;n<e;n++)t(n)}switch(n){case 0:i(6,e=>r.push(dk(t[0],2+e,1))),i(8,e=>r.push(dk(t[1],e,1)));break;case 1:i(3,e=>r.push(dk(t[0],2+e*2,2))),i(4,e=>r.push(dk(t[1],e*2,2)));break;default:n=(dk(t[0],2,6)<<8)+t[1]}return new e({type:1,symbolSize:n,symbolList:r})}serialize(){let e=Buffer.alloc(2),t=new uk(16).set(1).set(this.symbolSize),n=this.symbolSize===0?1:2;return this.symbolList.forEach(e=>{t.set(e,n)}),e.writeUInt16BE(t.value),e}},Yj=class e{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n,r;if(t.length===1?(n=1,r=250*t[0]):t.length===2&&(n=2,r=250*t.readInt16BE()),n===void 0||r===void 0)throw Error();return new e({type:n,delta:r})}deSerialize(t){let n=e.deSerialize(t);this.delta=n.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||=2):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}if(this.type===2){let e=Buffer.alloc(2);return e.writeInt16BE(this.delta),e}throw Error(`errDeltaExceedLimit `+this.delta+` `+this.type)}},Xj=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(e){Object.assign(this,e)}},Zj=Bk(`werift-rtp:packages/rtp/rtcp/rtpfb/index`),Qj=class e{static type=Uj;type=e.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(t,n){let r;switch(n.count){case Wj.count:r=Wj.deSerialize(t,n);break;case Kj.count:r=Kj.deSerialize(t,n);break;default:Zj(`unknown rtpfb packet`,n.count)}return new e({feedback:r,header:n})}},$j=class e{static type=202;type=e.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(t=>e+=t.length),e}serialize(){let e=Buffer.concat(this.chunks.map(e=>e.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return Fj.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(t,n){let r=[];for(let e=0;e<t.length;){let n=eM.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({chunks:r})}},eM=class e{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(t=>e+=t.length),e+=1,e+=nM(e),e}serialize(){let e=Buffer.concat([fk([4],[this.source]),Buffer.concat(this.items.map(e=>e.serialize()))]);return Buffer.concat([e,Buffer.alloc(nM(e.length))])}static deSerialize(t){let n=t.readUInt32BE(),r=[];for(let e=4;e<t.length&&t[e]!==0;){let n=tM.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({source:n,items:r})}},tM=class e{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([fk([1,1],[this.type,e.length]),e])}static deSerialize(t){let n=t[0],r=t[1],i=t.slice(2,2+r).toString();return new e({type:n,text:i})}};function nM(e){return e%4==0?0:4-e%4}var rM=class e{ssrc=0;senderInfo;reports=[];static type=200;type=e.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 t=Buffer.alloc(4);return t.writeUInt32BE(this.ssrc),t=Buffer.concat([t,this.senderInfo.serialize()]),t=Buffer.concat([t,...this.reports.map(e=>e.serialize())]),Fj.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let r=t.readUInt32BE(),i=iM.deSerialize(t.subarray(4,24)),a=24,o=[];for(let e=0;e<n;e++)o.push(Hj.deSerialize(t.subarray(a,a+24))),a+=24;return new e({ssrc:r,senderInfo:i,reports:o})}},iM=class e{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:aM(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return fk([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(t){let[n,r,i,a]=mk(t,[8,4,4,4]);return new e({ntpTimestamp:n,rtpTimestamp:r,packetCount:i,octetCount:a})}},aM=e=>{let[t,n]=mk(fk([8],[e]),[4,4]);return Number(`${t}.${n}`)},oM=Bk(`werift-rtp:packages/rtp/src/rtcp/rtcp.ts`),sM=class{static deSerialize(e){let t=0,n=[];for(;t<e.length;){let r=Fj.deSerialize(e.subarray(t,t+4));t+=4;let i=e.subarray(t);t+=r.length*4,r.padding&&(i=i.subarray(0,i.length-i.subarray(-1)[0]));try{switch(r.type){case rM.type:n.push(rM.deSerialize(i,r.count));break;case Vj.type:n.push(Vj.deSerialize(i,r.count));break;case $j.type:n.push($j.deSerialize(i,r));break;case Qj.type:n.push(Qj.deSerialize(i,r));break;case Bj.type:n.push(Bj.deSerialize(i,r))}}catch(e){oM(`deSerialize RTCP`,e)}}return n}};function cM(e){return e.length>=2&&e[1]>=192&&e[1]<=208}var lM={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`};function uM(e,t){return e.map(e=>{let n=t[e.id];if(!n)return{uri:`unknown`,value:e.payload};switch(n){case lM.sdesMid:case lM.sdesRTPStreamID:case lM.repairedRtpStreamId:return{uri:n,value:gM(e.payload)};case lM.transportWideCC:return{uri:n,value:_M(e.payload)};case lM.absSendTime:return{uri:n,value:vM(e.payload)};case lM.audioLevelIndication:return{uri:n,value:yM(e.payload)};case lM.videoOrientation:return{uri:n,value:bM(e.payload)};default:return{uri:n,value:e.payload}}}).reduce((e,t)=>(t&&(e[t.uri]=t.value),e),{})}function dM(e){return Buffer.from(e)}function fM(e){return Buffer.from(e)}function pM(e){return Buffer.from(e)}function mM(e){return fk([2],[e])}function hM(e){let t=Buffer.alloc(3),n=e>>14n&16777215n;return t.writeUIntBE(Number(n),0,3),t}function gM(e){return e.toString()}function _M(e){return e.readUInt16BE()}function vM(e){return mk(e,[3])[0]}function yM(e){let t=new hk(e);return{v:t.readBits(1)===1,level:t.readBits(7)}}function bM(e){let t=new hk(e);return t.readBits(4),{c:t.readBits(1),f:t.readBits(1),r1:t.readBits(1),r0:t.readBits(1)}}var xM=Bk(`packages/rtp/src/rtp/red/packet.ts`),SM=class e{header;blocks=[];static deSerialize(t){let n=t instanceof ArrayBuffer?Buffer.from(t):t,r=new e,i=0;return[r.header,i]=CM.deSerialize(n),r.header.fields.forEach(({blockLength:e,timestampOffset:t,blockPT:a})=>{if(e&&t){let o=n.subarray(i,i+e);r.blocks.push({block:o,blockPT:a,timestampOffset:t}),i+=e}else{let e=n.subarray(i);r.blocks.push({block:e,blockPT:a})}}),r}serialize(){this.header=new CM;for(let{timestampOffset:e,blockPT:t,block:n}of this.blocks)e?this.header.fields.push({fBit:1,blockPT:t,blockLength:n.length,timestampOffset:e}):this.header.fields.push({fBit:0,blockPT:t});let e=this.header.serialize();for(let{block:t}of this.blocks)e=Buffer.concat([e,t]);return e}},CM=class e{fields=[];static deSerialize(t){let n=0,r=new e;for(;;){let e={};r.fields.push(e);let i=new hk(t.subarray(n));if(e.fBit=i.readBits(1),e.blockPT=i.readBits(7),n++,e.fBit===0)break;e.timestampOffset=i.readBits(14),e.blockLength=i.readBits(10),n+=3}return[r,n]}serialize(){let e=Buffer.alloc(0);for(let t of this.fields)try{if(t.timestampOffset&&t.blockLength){let n=new hk(Buffer.alloc(4)).writeBits(1,t.fBit).writeBits(7,t.blockPT).writeBits(14,t.timestampOffset).writeBits(10,t.blockLength);e=Buffer.concat([e,n.uint8Array])}else{let n=new hk(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,n.uint8Array])}}catch(e){xM(e?.message)}return e}},wM=class{constructor(e=1){this.distance=e}cache=[];cacheSize=10;push(e){this.cache.push(e),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let e=new SM,t=this.cache.slice(-(this.distance+1)),n=t.pop();return n?(t.forEach(t=>{let r=jk(n.timestamp,-t.timestamp);r>TM||e.blocks.push({block:t.block,blockPT:t.blockPT,timestampOffset:r})}),e.blocks.push({block:n.block,blockPT:n.blockPT}),e):e}},TM=16383,EM=class{size=150;sequenceNumbers=[];push(e,t){let n=[];return e.blocks.forEach(({blockPT:r,timestampOffset:i,block:a},o)=>{let s=Ak(t.header.sequenceNumber,-(e.blocks.length-(o+1)));i?n.push(new PM(new NM({timestamp:jk(t.header.timestamp,-i),payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:!0}),a)):n.push(new PM(new NM({timestamp:t.header.timestamp,payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:!0}),a))}),n.filter(e=>!this.sequenceNumbers.includes(e.header.sequenceNumber)&&(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(e.header.sequenceNumber),!0))}},DM={OneByte:48862,TwoByte:4096},OM=2,kM=4,AM=8,jM=12,MM=4,NM=class e{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=DM.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=new e,r=0,i=t[r++];n.version=dk(i,0,2),n.padding=dk(i,2)>0,n.extension=dk(i,3)>0,n.csrcLength=dk(i,4,4),n.csrc=[...Array(n.csrcLength)].map(()=>{let e=t.readUInt32BE(r);return r+=4,e}),r+=jM-1;let a=t[1];n.marker=dk(a,0)>0,n.payloadType=dk(a,1,7),n.sequenceNumber=t.readUInt16BE(OM),n.timestamp=t.readUInt32BE(kM),n.ssrc=t.readUInt32BE(AM);for(let e=0;e<n.csrc.length;e++){let r=jM+e*MM;n.csrc[e]=t.subarray(r).readUInt32BE()}if(n.extension){n.extensionProfile=t.subarray(r).readUInt16BE(),r+=2;let e=t.subarray(r).readUInt16BE()*4;switch(n.extensionLength=e,r+=2,n.extensionProfile){case DM.OneByte:{let i=r+e;for(;r<i;){if(t[r]===0){r++;continue}let e=t[r]>>4,i=(t[r]&(t[r]^240))+1;if(r++,e===15)break;let a={id:e,payload:t.subarray(r,r+i)};n.extensions=[...n.extensions,a],r+=i}}break;case DM.TwoByte:{let i=r+e;for(;r<i;){if(t[r]===0){r++;continue}let e=t[r];r++;let i=t[r];r++;let a={id:e,payload:t.subarray(r,r+i)};n.extensions=[...n.extensions,a],r+=i}}break;default:{let i={id:0,payload:t.subarray(r,r+e)};n.extensions=[...n.extensions,i],r+=n.extensions[0].payload.length}}}return n.payloadOffset=r,n.padding&&(n.paddingSize=t[t.length-1]),n}get serializeSize(){let{csrc:e,extensionProfile:t,extensions:n}=this,r=12+e.length*MM;if(n.length>0||this.extension===!0){let e=4;switch(t){case DM.OneByte:for(let t of n)e+=1+t.payload.length;break;case DM.TwoByte:for(let t of n)e+=2+t.payload.length;break;default:e+=n[0].payload.length}r+=Math.floor((e+3)/4)*4}return r}serialize(e){let t=Buffer.alloc(e),n=0,r=new lk(8);r.set(2,0,this.version),this.padding&&r.set(1,2,1),this.extensions.length>0&&(this.extension=!0),this.extension&&r.set(1,3,1),r.set(4,4,this.csrc.length),t.writeUInt8(r.value,n++);let i=new lk(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),t.writeUInt8(i.value,n++),t.writeUInt16BE(this.sequenceNumber,OM),n+=2,t.writeUInt32BE(this.timestamp,kM),n+=4,t.writeUInt32BE(this.ssrc,AM),n+=4;for(let e of this.csrc)t.writeUInt32BE(e,n),n+=4;if(this.extension){let e=n;t.writeUInt16BE(this.extensionProfile,n),n+=4;let r=n;switch(this.extensionProfile){case DM.OneByte:for(let e of this.extensions)t.writeUInt8(e.id<<4|e.payload.length-1,n++),e.payload.copy(t,n),n+=e.payload.length;break;case DM.TwoByte:for(let e of this.extensions)t.writeUInt8(e.id,n++),t.writeUInt8(e.payload.length,n++),e.payload.copy(t,n),n+=e.payload.length;break;default:{let e=this.extensions[0].payload.length;if(e%4!=0)throw Error();this.extensions[0].payload.copy(t,n),n+=e}}let i=n-r,a=Math.trunc((i+3)/4)*4;t.writeUInt16BE(Math.trunc(a/4),e+2);for(let e=0;e<a-i;e++)t.writeUInt8(0,n),n++}return this.payloadOffset=n,t}},PM=class e{constructor(e,t){this.header=e,this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new e(new NM({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:t}=this.header;if(this.payload.copy(e,t),this.header.padding){let t=Buffer.alloc(this.header.paddingSize);t.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),e=Buffer.concat([e,t])}return e}static deSerialize(t){let n=NM.deSerialize(t);return new e(n,t.subarray(n.payloadOffset,t.length-n.paddingSize))}clear(){this.payload=null}};function FM(e,t,n){return new PM(new NM({payloadType:t,marker:e.header.marker,sequenceNumber:e.payload.readUInt16BE(0),timestamp:e.header.timestamp,ssrc:n}),e.payload.subarray(2))}function IM(e,t,n,r){let i=Buffer.allocUnsafe(2);return i.writeUInt16BE(e.header.sequenceNumber,0),new PM(new NM({payloadType:t,marker:e.header.marker,sequenceNumber:n,timestamp:e.header.timestamp,ssrc:r,csrc:e.header.csrc,extensions:e.header.extensions}),Buffer.concat([i,e.payload]))}var LM=class{constructor(e,t,n,r){this.srtpSessionKey=e,this.srtpSessionSalt=t,this.srtcpSessionKey=n,this.srtcpSessionSalt=r}encryptRtp(e,t,n){return Buffer.from([])}decryptRtp(e,t,n){return[]}encryptRTCP(e,t){return Buffer.from([])}decryptRTCP(e){return[]}},RM=class extends Error{constructor(e){super(e),this.name=`SrtpAuthenticationError`}},zM=12,BM=8;function VM(e,t,n=`Failed to authenticate SRTP packet`){let r=e.length-t;UM(e.length>=zM+t,n);let i=WM(()=>NM.deSerialize(e.subarray(0,r)),n);return i.paddingSize=0,UM(i.payloadOffset>=zM&&i.payloadOffset<=r,n),i}function HM(e,t,n,r=`Failed to authenticate SRTCP packet`){return UM(e.length>=BM+t+n,r),WM(()=>Fj.deSerialize(e.subarray(0,4)),r)}function UM(e,t){if(!e)throw new RM(t)}function WM(e,t){try{return e()}catch{throw new RM(t)}}function GM(e,t,n=`Failed to authenticate SRTP packet`){if(!e.padding)return e.paddingSize=0,e;UM(t.length>e.payloadOffset,n);let r=t[t.length-1];return UM(r>0&&r<=t.length-e.payloadOffset,n),e.paddingSize=r,e}var KM=class extends LM{constructor(e,t,n,r,i,a){super(e,t,n,r),this.srtpSessionAuthTag=i,this.srtcpSessionAuthTag=a}authTagLength=10;encryptRtp(e,t,n){let i=e.serialize(e.serializeSize),a=this.generateCounter(e.sequenceNumber,n,e.ssrc,this.srtpSessionSalt),o=r(`aes-128-ctr`,this.srtpSessionKey,a).update(t),s=this.generateSrtpAuthTag(n,i,o);return Buffer.concat([i,o,s])}decryptRtp(e,t,n=VM(e,this.authTagLength)){let r=e.length-this.authTagLength,a=e.subarray(0,r);JM(e.subarray(r),this.generateSrtpAuthTag(t,a.subarray(0,n.payloadOffset),a.subarray(n.payloadOffset)),`Failed to authenticate SRTP packet`);let o=this.generateCounter(n.sequenceNumber,t,n.ssrc,this.srtpSessionSalt),s=i(`aes-128-ctr`,this.srtpSessionKey,o),c=a.subarray(n.payloadOffset),l=s.update(c),u=Buffer.concat([a.subarray(0,n.payloadOffset),l]);return[u,GM(n,u,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){let n=Buffer.from(e),i=n.readUInt32BE(4),a=this.generateCounter(t&65535,t>>16,i,this.srtcpSessionSalt);r(`aes-128-ctr`,this.srtcpSessionKey,a).update(n.slice(8)).copy(n,8),n=Buffer.concat([n,Buffer.alloc(4)]),n.writeUInt32BE(t,n.length-4),n[n.length-4]|=128;let o=this.generateSrtcpAuthTag(n);return n=Buffer.concat([n,o]),n}decryptRTCP(e){let t=HM(e,this.authTagLength,qM),n=e.length-(this.authTagLength+qM),r=e.subarray(0,e.length-this.authTagLength);JM(e.subarray(e.length-this.authTagLength),this.generateSrtcpAuthTag(r),`Failed to authenticate SRTCP packet`);let a=Buffer.from(e).slice(0,n);if(!(e[n]>>>7))return[a,t];let o=e.readUInt32BE(n);o&=2147483647;let s=e.readUInt32BE(4),c=this.generateCounter(o&65535,o>>16,s,this.srtcpSessionSalt);return i(`aes-128-ctr`,this.srtcpSessionKey,c).update(a.subarray(8)).copy(a,8),[a,t]}generateSrtcpAuthTag(e){return o(`sha1`,this.srtcpSessionAuthTag).update(e).digest().slice(0,10)}generateCounter(e,t,n,r){let i=Buffer.alloc(16);i.writeUInt32BE(n,4),i.writeUInt32BE(t,8),i.writeUInt32BE(Number(BigInt(e)<<16n),12);for(let e=0;e<r.length;e++)i[e]^=r[e];return i}generateSrtpAuthTag(e,...t){let n=o(`sha1`,this.srtpSessionAuthTag),r=Buffer.alloc(4);r.writeUInt32BE(e);for(let e of t)n.update(e);return n.update(r).digest().subarray(0,10)}},qM=4;function JM(e,t,n){if(e.length!==t.length||!u(e,t))throw new RM(n)}var YM=class extends LM{aeadAuthTagLen=16;rtpIvWriter=pk([2,4,4,2],!0);rtcpIvWriter=pk([2,4,2,4],!0);aadWriter=pk([4],!0);constructor(e,t,n,r){super(e,t,n,r)}encryptRtp(e,t,n){let i=e.serialize(e.serializeSize),a=this.rtpInitializationVector(e,n),o=r(`aes-128-gcm`,this.srtpSessionKey,a);o.setAAD(i);let s=o.update(t);o.final();let c=o.getAuthTag();return Buffer.concat([i,s,c])}decryptRtp(e,t,n=VM(e,this.aeadAuthTagLen)){let r=e.subarray(0,n.payloadOffset),a=e.length-this.aeadAuthTagLen,o=e.subarray(a),s=Buffer.from([]);s=Mj(s,e.length-this.aeadAuthTagLen),r.copy(s);let c=this.rtpInitializationVector(n,t),l=e.slice(n.payloadOffset,a),u=i(`aes-128-gcm`,this.srtpSessionKey,c);u.setAAD(r),u.setAuthTag(o);let d=u.update(l);return QM(u,`SRTP`),d.copy(s,n.payloadOffset),[s,GM(n,s,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){let n=e.readUInt32BE(4),i=e.length+this.aeadAuthTagLen,a=Buffer.from([]);a=Mj(a,i+XM),e.slice(0,8).copy(a);let o=this.rtcpInitializationVector(n,t),s=this.rtcpAdditionalAuthenticatedData(e,t),c=r(`aes-128-gcm`,this.srtcpSessionKey,o);c.setAAD(s);let l=c.update(e.slice(8));return c.final(),l.copy(a,8),c.getAuthTag().copy(a,8+l.length),s.slice(8,12).copy(a,i),a}decryptRTCP(e){let t=HM(e,this.aeadAuthTagLen,XM),n=e.length-XM,r=n-this.aeadAuthTagLen,a=e.readUInt32BE(4),o=e.readUInt32BE(n),s=o>>>31==1,c=o&~(ZM<<24),l=this.rtcpInitializationVector(a,c),u=s?Buffer.concat([e.subarray(0,8),e.subarray(n)]):Buffer.concat([e.subarray(0,r),e.subarray(n)]),d=s?e.slice(8,r):Buffer.alloc(0),f=s?Buffer.alloc(r):Buffer.from(e.subarray(0,r));s&&e.slice(0,8).copy(f);let p=i(`aes-128-gcm`,this.srtcpSessionKey,l);p.setAAD(u),p.setAuthTag(e.subarray(r,n));let m=p.update(d);return QM(p,`SRTCP`),s&&m.copy(f,8),[f,t]}rtpInitializationVector(e,t){let n=this.rtpIvWriter([0,e.ssrc,t,e.sequenceNumber]);for(let e=0;e<n.length;e++)n[e]^=this.srtpSessionSalt[e];return n}rtcpInitializationVector(e,t){let n=this.rtcpIvWriter([0,e,0,t]);for(let e=0;e<n.length;e++)n[e]^=this.srtcpSessionSalt[e];return n}rtcpAdditionalAuthenticatedData(e,t){let n=Buffer.concat([e.subarray(0,8),this.aadWriter([t])]);return n[8]|=ZM,n}},XM=4,ZM=128;function QM(e,t){try{e.final()}catch{throw new RM(`Failed to authenticate ${t} packet`)}}function $M(e,t){let n=r(`aes-128-ecb`,e,null);return n.setAutoPadding(!1),Buffer.concat([n.update(t),n.final()])}var eN=class{constructor(e,t,n){this.masterKey=e,this.masterSalt=t,this.profile=n;{let e=14-t.length;e>0&&(this.masterSalt=Buffer.concat([t,Buffer.alloc(e)]))}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=o(`sha1`,this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=o(`sha1`,this.srtcpSessionAuthTag),n){case 1:this.cipher=new KM(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case 7:this.cipher=new YM(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt)}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(e){let t=Buffer.from(this.masterSalt),n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];return t=Buffer.concat([t,Buffer.from([0,0])]),$M(this.masterKey,t)}generateSessionSalt(e){let t=Buffer.from(this.masterSalt),n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];return t=Buffer.concat([t,Buffer.from([0,0])]),t=$M(this.masterKey,t),t.subarray(0,14)}generateSessionAuthTag(e){let t=Buffer.from(this.masterSalt),n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];let r=Buffer.concat([t,Buffer.from([0,0])]),i=Buffer.concat([t,Buffer.from([0,1])]);return r=$M(this.masterKey,r),i=$M(this.masterKey,i),Buffer.concat([r,i.subarray(0,4)])}getSrtpSsrcState(e){let t=this.srtpSSRCStates[e];return t||(t={ssrc:e,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[e]=t,t)}getSrtcpSsrcState(e){let t=this.srtcpSSRCStates[e];return t||(t={srtcpIndex:0,ssrc:e},this.srtcpSSRCStates[e]=t,t)}updateRolloverCount(e,t){t.rolloverHasProcessed?e===0?t.lastSequenceNumber>tN&&t.rolloverCounter++:t.lastSequenceNumber<tN&&e>nN-tN?t.rolloverCounter>0&&t.rolloverCounter--:e<tN&&t.lastSequenceNumber>nN-tN&&t.rolloverCounter++:t.rolloverHasProcessed=!0,t.lastSequenceNumber=e}generateSrtpAuthTag(e,t){this.srtpSessionAuth=o(`sha1`,this.srtpSessionAuthTag);let n=Buffer.alloc(4);return n.writeUInt32BE(t),this.srtpSessionAuth.update(e).update(n).digest().slice(0,10)}index(e){let t=this.srtcpSSRCStates[e];return t?t.srtcpIndex:0}setIndex(e,t){let n=this.getSrtcpSsrcState(e);n.srtcpIndex=t%2147483647}},tN=100,nN=65535,rN=class extends eN{constructor(e,t,n){super(e,t,n)}encryptRTCP(e){let t=e.readUInt32BE(4),n=this.getSrtcpSsrcState(t);return n.srtcpIndex++,n.srtcpIndex>>iN&&(n.srtcpIndex=0),this.cipher.encryptRTCP(e,n.srtcpIndex)}decryptRTCP(e){return this.cipher.decryptRTCP(e)}},iN=2147483647,aN=class{constructor(e){this.ContextCls=e}localContext;remoteContext;onData;start(e,t,n,r,i){this.localContext=new this.ContextCls(e,t,i),this.remoteContext=new this.ContextCls(n,r,i)}},oN=class extends aN{constructor(e){super(rN),this.config=e,this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}decrypt=e=>{let[t]=this.remoteContext.decryptRTCP(e);return t};encrypt(e){return this.localContext.encryptRTCP(e)}},sN=class extends eN{constructor(e,t,n){super(e,t,n)}encryptRtp(e,t){let n=this.getSrtpSsrcState(t.ssrc);return this.updateRolloverCount(t.sequenceNumber,n),this.cipher.encryptRtp(t,e,n.rolloverCounter)}decryptRtp(e){let t=VM(e,this.rtpAuthTagLength),n=this.srtpSSRCStates[t.ssrc],r=n?{...n}:{ssrc:t.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(t.sequenceNumber,r);let i=this.cipher.decryptRtp(e,r.rolloverCounter,t);return n?Object.assign(n,r):this.srtpSSRCStates[t.ssrc]=r,i}get rtpAuthTagLength(){return this.profile===7?16:10}},cN=class extends aN{constructor(e){super(sN),this.config=e,this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}decrypt=e=>{let[t]=this.remoteContext.decryptRtp(e);return t};encrypt(e,t){return this.localContext.encryptRtp(e,t)}},lN=Bk(`werift-dtls : packages/dtls/src/flight/client/flight5.ts : log`),uN=class extends GA{constructor(e,t,n,r){super(e,t,5,7),this.cipher=n,this.srtp=r}handleHandshake(e){this.dtls.bufferHandshakeCache([e],!1,4);let t=(()=>{switch(e.msg_type){case 2:return Ej.deSerialize(e.fragment);case 11:return bj.deSerialize(e.fragment);case 12:return kj.deSerialize(e.fragment);case 13:return Tj.deSerialize(e.fragment);case 14:return Dj.deSerialize(e.fragment)}})();t&&dN[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}async exec(){if(this.dtls.flight===5){lN(this.dtls.sessionId,`flight5 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let e=this.dtls.requestedCertificateTypes.length>0;lN(this.dtls.sessionId,`send flight5`,e);let t=[e&&this.sendCertificate(),this.sendClientKeyExchange(),e&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(e=>e);this.dtls.lastMessage=t,await this.transmit(t)}sendCertificate(){let e=new bj([Buffer.from(this.cipher.localCert)]),t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw Error();let e=new Cj(this.cipher.localKeyPair.publicKey),t=this.createPacket([e]),n=Buffer.concat(t.map(e=>e.serialize())),r=this.cipher.localKeyPair,i=this.cipher.remoteKeyPair;if(!i.publicKey)throw Error(`not exist`);let a=aA(i.publicKey,r.privateKey,r.curve);lN(this.dtls.sessionId,`extendedMasterSecret`,this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let o=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?lA(a,o):cA(a,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=mj(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),lN(this.dtls.sessionId,`cipher`,this.cipher.cipher.summary),n}sendCertificateVerify(){let e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize())),t=this.cipher.signatureData(e,`sha256`),n=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case qk.ecdsa_3:return eA.ecdsa_secp256r1_sha256;case qk.rsa_1:return eA.rsa_pkcs1_sha256}})();if(!n)throw Error();lN(this.dtls.sessionId,`signatureScheme`,this.cipher.signatureHashAlgorithm?.signature,n);let r=new Sj(n,t),i=this.createPacket([r]);return Buffer.concat(i.map(e=>e.serialize()))}sendChangeCipherSpec(){let e=xj.createEmpty().serialize(),t=VA(this.dtls)([{type:20,fragment:e}],++this.dtls.recordSequenceNumber);return Buffer.concat(t.map(e=>e.serialize()))}sendFinished(){let e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize())),t=new wj(this.cipher.verifyData(e));this.dtls.epoch=1;let[n]=this.createPacket([t]);this.dtls.recordSequenceNumber=0;let r=this.cipher.encryptPacket(n).serialize();return lN(this.dtls.sessionId,`finished`,this.cipher.cipher.summary),r}},dN={};dN[2]=({cipher:e,srtp:t,dtls:n})=>r=>{lN(n.sessionId,`serverHello`,r.cipherSuite),e.remoteRandom=IA.from(r.random),e.cipherSuite=r.cipherSuite,lN(n.sessionId,`selected cipherSuite`,e.cipherSuite),r.extensions&&r.extensions.forEach(e=>{switch(e.type){case yj.type:{let r=yj.fromData(e.data),i=bA.findMatchingSRTPProfile(r.profiles,n.options.srtpProfiles||[]);if(lN(n.sessionId,`selected srtp profile`,i),i==null)return;t.srtpProfile=i}break;case _j.type:n.remoteExtendedMasterSecret=!0;break;case vj.type:lN(n.sessionId,`RenegotiationIndication`)}})},dN[11]=({cipher:e,dtls:t})=>n=>{lN(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},dN[12]=({cipher:e,dtls:t})=>n=>{if(!e.localRandom||!e.remoteRandom)throw Error();lN(t.sessionId,`ServerKeyExchange`,n),lN(t.sessionId,`selected curve`,n.namedCurve),e.remoteKeyPair={curve:n.namedCurve,publicKey:n.publicKey},e.localKeyPair=gj(n.namedCurve)},dN[13]=({dtls:e})=>t=>{lN(e.sessionId,`certificate_request`,t),e.requestedCertificateTypes=t.certificateTypes,e.requestedSignatureAlgorithms=t.signatures},dN[14]=({dtls:e})=>t=>{lN(e.sessionId,`server_hello_done`,t)};var fN=class e{constructor(e,t){this.serverVersion=e,this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:FA,cookie:Q.types.buffer(Q.types.uint8)};static createEmpty(){return new e(void 0,void 0)}static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let e=this.serialize();return new CA(this.msgType,e.length,this.messageSeq,0,e.length,e)}},pN=Bk(`werift-dtls : packages/dtls/src/context/dtls.ts : log`),mN=class{constructor(e,t){this.options=e,this.sessionType=t}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(([e],[t])=>Number(e)-Number(t)).flatMap(([,{data:e}])=>e.sort((e,t)=>e.message_seq-t.message_seq))}checkHandshakesExist=e=>!e.find(e=>this.sortedHandshakeCache.find(t=>t.msg_type===e)==null);bufferHandshakeCache(e,t,n){this.handshakeCache[n]||(this.handshakeCache[n]={data:[],isLocal:t,flight:n});let r=e.filter(e=>{let r=this.handshakeCache[n].data.find(t=>t.msg_type===e.msg_type);return!r||(pN(this.sessionId,`exist`,r.summary,t,n),!1)});this.handshakeCache[n].data=[...this.handshakeCache[n].data,...r]}},hN=class{constructor(e){this.socket=e}send=(e,t)=>this.socket.send(e,t)},gN=class e{static type=10;static spec={type:Q.types.uint16be,data:Q.types.array(Q.types.uint16be,Q.types.uint16be,`bytes`)};type=e.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new e}static fromData(t){return new e({type:e.type,data:(0,Q.decode)(t,e.spec.data)})}static deSerialize(t){return new e((0,Q.decode)(t,e.spec))}serialize(){return Buffer.from((0,Q.encode)(this,e.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},_N=class e{static type=13;static spec={type:Q.types.uint16be,data:Q.types.array({hash:Q.types.uint8,signature:Q.types.uint8},Q.types.uint16be,`bytes`)};type=e.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new e}static deSerialize(t){return new e((0,Q.decode)(t,e.spec))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}static fromData(t){let n=Buffer.alloc(2);return n.writeUInt16BE(e.type),e.deSerialize(Buffer.concat([n,t]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},vN=class e{constructor(e,t){this.level=e,this.description=t}static spec={level:Q.types.uint8,description:Q.types.uint8};static deSerialize(t){return new e(...Object.values((0,Q.decode)(t,e.spec)))}serialize(){let t=(0,Q.encode)(this,e.spec).slice();return Buffer.from(t)}},yN=Bk(`werift-dtls : packages/dtls/record/receive.ts : log`),bN=Bk(`werift-dtls : packages/dtls/record/receive.ts : err`),xN=e=>{let t=0,n=[];for(;e.length>t;){let r=e.readUInt16BE(t+11);if(e.length<t+(12+r))break;let i=zA.deSerialize(e.subarray(t));n.push(i),t+=13+r}return n},SN=(e,t)=>n=>{switch(n.recordLayerHeader.contentType){case 20:return yN(e.sessionId,`change cipher spec`),[{type:20,data:void 0}];case 22:{let r=n.fragment;try{n.recordLayerHeader.epoch>0&&(yN(e.sessionId,`decrypt handshake`),r=t.decryptPacket(n))}catch(t){throw bN(e.sessionId,`decrypt failed`,t),t}try{let e=0,t=[];for(;r.length>e;){let n=CA.deSerialize(r.subarray(e));t.push({type:22,data:n}),e+=n.fragment_length+12}return t}catch(t){throw bN(e.sessionId,`decSerialize failed`,t,r),t}}case 23:return[{type:23,data:t.decryptPacket(n)}];case 21:{let r=vN.deSerialize(n.fragment);if(HA[r.description]==null){let e=t.decryptPacket(n);r=vN.deSerialize(e)}if(bN(e.sessionId,`ContentType.alert`,r,HA[r.description],`flight`,e.flight,`lastFlight`,e.lastFlight),r.level>1)throw Error(`alert fatal error`);return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},CN=Bk(`werift-dtls : packages/dtls/src/socket.ts : log`),wN=Bk(`werift-dtls : packages/dtls/src/socket.ts : err`),TN=class{constructor(e,t){this.options=e,this.sessionType=t,this.dtls=new mN(this.options,this.sessionType),this.cipher=new yA(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new hN(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new $;onData=new $;onError=new $;onClose=new $;transport;cipher;dtls;srtp=new bA;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){CN(`renegotiation`,this.sessionType),this.connected=!1,this.cipher=new yA(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new mN(this.options,this.sessionType),this.srtp=new bA,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=e=>{let t=xN(e);for(let e of t)try{let t=SN(this.dtls,this.cipher)(e);for(let e of t)switch(e.type){case 22:{let t=e.data,n=this.handleFragmentHandshake([t]),r=Object.values(n.reduce((e,t)=>(e[t.msg_type]||(e[t.msg_type]=[]),e[t.msg_type].push(t),e),{})).map(e=>CA.assemble(e)).sort((e,t)=>e.msg_type-t.msg_type);this.onHandleHandshakes(r).catch(e=>{wN(this.dtls.sessionId,`onHandleHandshakes error`,e),this.onError.execute(e)})}break;case 23:this.onData.execute(e.data);break;case 21:this.onClose.execute()}}catch(e){wN(this.dtls.sessionId,`catch udpOnMessage error`,e)}};setupExtensions(){if(CN(this.dtls.sessionId,`support srtpProfiles`,this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let e=yj.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{let e=gN.createEmpty();e.data=Qk,this.extensions.push(e.extension)}{let e=_N.createEmpty();e.data=nA,this.extensions.push(e.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:_j.type,data:Buffer.alloc(0)});{let e=vj.createEmpty();this.extensions.push(e.extension)}}waitForReady=e=>new Promise(async(t,n)=>{for(let n=0;n<10;n++)if(e()){t();break}else await E(100*n);n(`waitForReady timeout`)});handleFragmentHandshake(e){let t=e.filter(e=>e.fragment_length===e.length||(this.bufferFragmentedHandshakes.push(e),!1));if(this.bufferFragmentedHandshakes.length>1){let[e]=this.bufferFragmentedHandshakes.slice(-1);e.fragment_offset+e.fragment_length===e.length&&(t=[...this.bufferFragmentedHandshakes,...t],this.bufferFragmentedHandshakes=[])}return t}send=async(e,t)=>{let n=VA(this.dtls)([{type:23,fragment:e}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(n).serialize(),t)};close(){this.transport.socket.close()}extractSessionKeys(e,t){let n=this.exportKeyingMaterial(`EXTRACTOR-dtls_srtp`,e*2+t*2),{clientKey:r,serverKey:i,clientSalt:a,serverSalt:o}=(0,Q.decode)(n,{clientKey:Q.types.buffer(e),serverKey:Q.types.buffer(e),clientSalt:Q.types.buffer(t),serverSalt:Q.types.buffer(t)});return this.sessionType===gA.CLIENT?{localKey:r,localSalt:a,remoteKey:i,remoteSalt:o}:{localKey:i,localSalt:o,remoteKey:r,remoteSalt:a}}exportKeyingMaterial(e,t){return uA(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===gA.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},EN=Bk(`werift-dtls : packages/dtls/src/client.ts : log`),DN=class extends TN{constructor(e){super(e,gA.CLIENT),this.onHandleHandshakes=this.handleHandshakes,EN(this.dtls.sessionId,`start client`)}async connect(){await new KA(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async e=>{EN(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(let t of e)switch(t.msg_type){case 3:{let e=fN.deSerialize(t.fragment);await new JA(this.transport,this.dtls).exec(e)}break;case 2:if(this.connected)return;this.flight5=new uN(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(t);break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(t);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(t);let e=[11,12,this.options.certificateRequest&&13].filter(e=>typeof e==`number`);await this.waitForReady(()=>this.dtls.checkHandshakesExist(e)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),EN(this.dtls.sessionId,`dtls connected`)}}},ON=Bk(`werift-dtls : packages/dtls/flight/server/flight2.ts : log`),kN=(e,t,n,r)=>i=>{ON(`dtls version`,i.clientVersion),t.flight=2,t.recordSequenceNumber=0,t.sequenceNumber=0,i.extensions.forEach(e=>{switch(e.type){case gN.type:{let r=gN.fromData(e.data).data;ON(t.sessionId,`curves`,r),n.namedCurve=r.filter(e=>Qk.includes(e))[0],ON(t.sessionId,`curve selected`,n.namedCurve)}break;case _N.type:{if(!n.signatureHashAlgorithm)throw Error(`need to set certificate`);let r=_N.fromData(e.data).data;ON(t.sessionId,`hash,signature`,r);let i=r.find(e=>e.signature===n.signatureHashAlgorithm?.signature)?.signature,a=r.find(e=>e.hash===n.signatureHashAlgorithm?.hash)?.hash;if(i==null||a==null)throw Error(`invalid signatureHash`)}break;case yj.type:{if(!t.options?.srtpProfiles||t.options.srtpProfiles.length===0)return;let n=yj.fromData(e.data);ON(t.sessionId,`srtp profiles`,n.profiles);let i=bA.findMatchingSRTPProfile(n.profiles,t.options?.srtpProfiles);if(!i)throw Error();r.srtpProfile=i,ON(t.sessionId,`srtp profile selected`,r.srtpProfile)}break;case _j.type:t.remoteExtendedMasterSecret=!0;break;case vj.type:ON(t.sessionId,`RenegotiationIndication`,e.data);break;case 43:ON(`dtls supported version`,[...e.data.subarray(1)].map(e=>e.toString(10)))}}),n.localRandom=new IA,n.remoteRandom=IA.from(i.random);let a=i.cipherSuites;ON(t.sessionId,`cipher suites`,a);let o=(()=>{switch(n.signatureHashAlgorithm?.signature){case qk.ecdsa_3:return Yk.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case qk.rsa_1:return Yk.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!a.includes(o))throw Error(`dtls cipher suite negotiation failed`);n.cipherSuite=o,ON(t.sessionId,`selected cipherSuite`,n.cipherSuite),n.localKeyPair=gj(n.namedCurve),t.cookie||=c(20);let s=new fN({major:254,minor:253},t.cookie),l=BA(t)([s]),u=VA(t)(l.map(e=>({type:22,fragment:e.serialize()})),++t.recordSequenceNumber).map(e=>e.serialize());for(let t of u)e.send(t)},AN=Bk(`werift-dtls : packages/dtls/flight/server/flight4.ts : log`),jN=class extends GA{constructor(e,t,n,r){super(e,t,4,6),this.cipher=n,this.srtp=r}async exec(e,t=!1){if(this.dtls.flight===4){AN(this.dtls.sessionId,`flight4 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([e],!1,4);let n=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),t&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(e=>e);this.dtls.lastMessage=n,await this.transmit(n)}sendServerHello(){let e=[];this.srtp.srtpProfile&&e.push(yj.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&e.push({type:_j.type,data:Buffer.alloc(0)});let t=vj.createEmpty();e.push(t.extension);let n=new Ej(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,e),r=this.createPacket([n]);return Buffer.concat(r.map(e=>e.serialize()))}sendCertificate(){let e=new bj([Buffer.from(this.cipher.localCert)]),t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendServerKeyExchange(){let e=this.cipher.generateKeySignature(`sha256`);if(!this.cipher.signatureHashAlgorithm)throw Error(`not exist`);let t=new kj($k.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,e.length,e),n=this.createPacket([t]);return Buffer.concat(n.map(e=>e.serialize()))}sendCertificateRequest(){let e=new Tj(tA,nA,[]);AN(this.dtls.sessionId,`sendCertificateRequest`,e);let t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendServerHelloDone(){let e=new Dj,t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}},MN=Bk(`werift-dtls : packages/dtls/flight/server/flight6.ts`),NN=class extends GA{constructor(e,t,n){super(e,t,6),this.cipher=n}handleHandshake(e){this.dtls.bufferHandshakeCache([e],!1,5);let t=(()=>{switch(e.msg_type){case 11:return bj.deSerialize(e.fragment);case 15:return Sj.deSerialize(e.fragment);case 16:return Cj.deSerialize(e.fragment);case 20:return wj.deSerialize(e.fragment)}})();if(t){let e=PN[t.msgType];if(!e)return;e({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){MN(this.dtls.sessionId,`flight6 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let e=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=e,await this.transmit(e)}sendChangeCipherSpec(){let e=xj.createEmpty().serialize(),t=VA(this.dtls)([{type:20,fragment:e}],++this.dtls.recordSequenceNumber);return Buffer.concat(t.map(e=>e.serialize()))}sendFinished(){let e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize())),t=new wj(this.cipher.verifyData(e));this.dtls.epoch=1;let[n]=this.createPacket([t]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(n).serialize()}},PN={};PN[16]=({cipher:e,dtls:t})=>n=>{if(e.remoteKeyPair={curve:e.namedCurve,publicKey:n.publicKey},!e.remoteKeyPair.publicKey||!e.localKeyPair||!e.remoteRandom||!e.localRandom)throw Error(`not exist`);let r=aA(e.remoteKeyPair.publicKey,e.localKeyPair.privateKey,e.localKeyPair.curve);MN(t.sessionId,`extendedMasterSecret`,t.options.extendedMasterSecret,t.remoteExtendedMasterSecret);let i=Buffer.concat(t.sortedHandshakeCache.map(e=>e.serialize()));e.masterSecret=t.options.extendedMasterSecret&&t.remoteExtendedMasterSecret?lA(r,i):cA(r,e.remoteRandom.serialize(),e.localRandom.serialize()),e.cipher=mj(e.cipherSuite),e.cipher.init(e.masterSecret,e.localRandom.serialize(),e.remoteRandom.serialize()),MN(t.sessionId,`setup cipher`,e.cipher.summary)},PN[11]=({cipher:e,dtls:t})=>n=>{MN(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},PN[15]=({cipher:e,dtls:t})=>n=>{if(!e.remoteCertificate)throw Error(`client certificate missing before certificate verify`);MN(t.sessionId,`certificate_verify`,n.algorithm)},PN[20]=({dtls:e})=>t=>{MN(e.sessionId,`finished`,t)};var FN=Bk(`werift-dtls : packages/dtls/src/server.ts : log`),IN=class extends TN{constructor(e){super(e,gA.SERVER),this.onHandleHandshakes=this.handleHandshakes,FN(this.dtls.sessionId,`start server`)}flight6;handleHandshakes=async e=>{FN(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(let t of e)switch(t.msg_type){case 1:{this.connected&&this.renegotiation();let e=LA.deSerialize(t.fragment);e.cookie.length===0?(FN(this.dtls.sessionId,`send flight2`),kN(this.transport,this.dtls,this.cipher,this.srtp)(e)):this.dtls.cookie&&e.cookie.equals(this.dtls.cookie)?(FN(this.dtls.sessionId,`send flight4`),await new jN(this.transport,this.dtls,this.cipher,this.srtp).exec(t,this.options.certificateRequest)):FN(`wrong state`,{dtlsCookie:this.dtls.cookie?.toString(`hex`).slice(10),helloCookie:e.cookie.toString(`hex`).slice(10)})}break;case 11:case 15:case 16:if(this.connected)return;this.flight6=new NN(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(t);break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(t);let e=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(e=>typeof e==`number`);await this.waitForReady(()=>this.dtls.checkHandshakesExist(e)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),FN(this.dtls.sessionId,`dtls connected`)}}}},LN=554869826,RN=1398035790;function zN(e){if(e.length<20||e[0]&192||e.readUInt32BE(4)!==554869826)return!1;let t=e.readUInt16BE(2);return t%4==0&&e.length===20+t}function BN(e){let t=Buffer.alloc(2);return t.writeUInt16BE(e.length,0),Buffer.concat([t,e])}function VN(e){let t=[],n=0;for(;e.length-n>=2;){let r=e.readUInt16BE(n);if(e.length-n<r+2)break;t.push(e.subarray(n+2,n+2+r)),n+=2+r}return{frames:t,rest:e.subarray(n)}}function HN(e){if(x(e)){let t=Buffer.allocUnsafe(4),n=e.split(`.`);for(let e=0;e<4;e++)t[e]=Number(n[e])&255;return t}if(!S(e))throw Error(`Invalid ip address: ${e}`);let t=e.split(`:`,8);for(let e=0;e<t.length;e++){let n;x(t[e])&&(n=HN(t[e]),t[e]=n.subarray(0,2).toString(`hex`)),n&&++e<8&&t.splice(e,0,n.subarray(2,4).toString(`hex`))}if(t[0]===``)for(;t.length<8;)t.unshift(`0`);else if(t[t.length-1]===``)for(;t.length<8;)t.push(`0`);else if(t.length<8){let e=0;for(;e<t.length&&t[e]!==``;e++);let n=[];for(let e=9-t.length;e>0;e--)n.push(`0`);t.splice(e,1,...n)}let n=Buffer.allocUnsafe(16),r=0;for(let e of t){let t=Number.parseInt(e,16)||0;n[r++]=t>>8&255,n[r++]=t&255}return n}function UN(e){if(e.length===4)return`${e[0]}.${e[1]}.${e[2]}.${e[3]}`;if(e.length!==16)throw Error(`Invalid ip address buffer length: ${e.length}`);let t=[];for(let n=0;n<16;n+=2)t.push(e.readUInt16BE(n).toString(16));let n=t.join(`:`);return n=n.replace(/(^|:)0(:0)*:0(:|$)/,`$1::$3`),n=n.replace(/:{3,4}/,`::`),n}function WN(e){return x(e)}function GN(e){let[t]=e,n=WN(t)?1:2,r=Buffer.alloc(4);return r.writeUInt8(0,0),r.writeUInt8(n,1),r.writeUInt16BE(e[1],2),Buffer.concat([r,HN(t)])}function KN(e){if(e.length<4)throw Error(`STUN error code is less than 4 bytes`);let t=e.readUInt8(2),n=e.readUInt8(3),r=e.slice(4).toString(`utf8`);return[t*100+n,r]}function qN(e){if(e.length<4)throw Error(`STUN address length is less than 4 bytes`);let t=e.readUInt8(1),n=e.readUInt16BE(2),r=e.slice(4);switch(t){case 1:if(r.length!==4)throw Error(`STUN address has invalid length for IPv4`);return[UN(r),n];case 2:if(r.length!==16)throw Error(`STUN address has invalid length for IPv6`);return[UN(r),n];default:throw Error(`STUN address has unknown protocol`)}}var JN=Buffer.alloc(6);JN.writeUInt16BE(LN>>16,0),JN.writeUInt32BE(LN,2);function YN(e,t){let n=[...JN,...t],r=e.slice(0,2);for(let t=2;t<e.length;t++){let i=e[t]^n[t-2],a=Buffer.alloc(1);a.writeUIntBE(i,0,1),r=Buffer.concat([r,a])}return r}function XN(e,t){return qN(YN(e,t))}function ZN(e){let t=Buffer.alloc(4);t.writeUInt16BE(0,0),t.writeUInt8(Math.floor(e[0]/100),2),t.writeUInt8(e[0]%100,3);let n=Buffer.from(e[1],`utf8`);return Buffer.concat([t,n])}function QN(e){let t=Buffer.alloc(e.length*2);return e.forEach((e,n)=>{t.writeUInt16BE(e,n*2)}),t}function $N(e){if(e.length%2!=0)throw Error(`UNKNOWN-ATTRIBUTES must have an even length`);let t=[];for(let n=0;n<e.length;n+=2)t.push(e.readUInt16BE(n));return t}function eP(e,t){return YN(GN(e),t)}var tP=e=>{let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t},nP=e=>e.readUInt32BE(0),rP=e=>{let t=Buffer.alloc(4);return t.writeUInt16BE(e,0),t},iP=e=>e.readUInt16BE(0),aP=e=>{let t=Buffer.allocUnsafe(8);return t.writeBigUInt64BE(e,0),t},oP=e=>e.readBigUInt64BE(0),sP=e=>Buffer.from(e,`utf8`),cP=e=>e.toString(`utf8`),lP=e=>{if([...e].length>=128)throw Error(`SOFTWARE must be shorter than 128 characters`);return sP(e)},uP=e=>e,dP=e=>e,fP=[[1,`MAPPED-ADDRESS`,GN,qN],[3,`CHANGE-REQUEST`,tP,nP],[4,`SOURCE-ADDRESS`,GN,qN],[5,`CHANGED-ADDRESS`,GN,qN],[6,`USERNAME`,sP,cP],[8,`MESSAGE-INTEGRITY`,uP,dP],[9,`ERROR-CODE`,ZN,KN],[10,`UNKNOWN-ATTRIBUTES`,QN,$N],[12,`CHANNEL-NUMBER`,rP,iP],[13,`LIFETIME`,tP,nP],[18,`XOR-PEER-ADDRESS`,eP,XN],[19,`DATA`,uP,dP],[20,`REALM`,sP,cP],[21,`NONCE`,uP,dP],[22,`XOR-RELAYED-ADDRESS`,eP,XN],[23,`REQUESTED-ADDRESS-FAMILY`,tP,nP],[24,`EVEN-PORT`,uP,dP],[25,`REQUESTED-TRANSPORT`,tP,nP],[28,`MESSAGE-INTEGRITY-SHA256`,uP,dP],[29,`PASSWORD-ALGORITHM`,uP,dP],[30,`USERHASH`,uP,dP],[32,`XOR-MAPPED-ADDRESS`,eP,XN],[34,`RESERVATION-TOKEN`,uP,dP],[36,`PRIORITY`,tP,nP],[37,`USE-CANDIDATE`,()=>Buffer.alloc(0),()=>null],[32770,`PASSWORD-ALGORITHMS`,uP,dP],[32771,`ALTERNATE-DOMAIN`,sP,cP],[32802,`SOFTWARE`,lP,cP],[32803,`ALTERNATE-SERVER`,GN,qN],[32808,`FINGERPRINT`,tP,nP],[32809,`ICE-CONTROLLED`,aP,oP],[32810,`ICE-CONTROLLING`,aP,oP],[32811,`RESPONSE-ORIGIN`,GN,qN],[32812,`OTHER-ADDRESS`,GN,qN]],pP=class{constructor(e=[]){this.attributes=e}getAttributes(){return this.attributes}setAttribute(e,t){let n=this.attributes.find(t=>t[0]===e);return n?n[1]=t:this.attributes.push([e,t]),this}getAttributeValue(e){return this.attributes.find(t=>t[0]===e)?.[1]}get attributesKeys(){return this.attributes.map(e=>e[0])}clear(){this.attributes=[]}},mP=fP.reduce((e,t)=>(e[t[0]]=t,e),{}),hP=fP.reduce((e,t)=>(e[t[1]]=t,e),{});function gP(e,t){if(!zN(e))return;let n=e.readUInt16BE(0),r=Buffer.from(e.slice(8,20)),i=new pP,a=[],o=!1;for(let n=20;n<e.length;){if(n+4>e.length)return;let s=e.readUInt16BE(n),c=e.readUInt16BE(n+2),l=n+4,u=l+c;if(u>e.length)return;let d=e.slice(l,u),f=SP(c);if(u+f>e.length)return;let p=mP[s];if(p){let[,a,,s]=p,c;try{c=s.name===XN.name?s(d,r):s(d)}catch{return}if(i.setAttribute(a,c),a===`FINGERPRINT`){let t=bP(e.slice(0,n));if(i.getAttributeValue(`FINGERPRINT`)!==t)return}else if(a===`MESSAGE-INTEGRITY`&&t){let r=xP(e.slice(0,n),t),a=i.getAttributeValue(`MESSAGE-INTEGRITY`);if(!r.equals(a))return;o=!0}}else a.push({type:s,length:c,value:Buffer.from(d)});n=u+f}if(!t||o)return new _P(n&16111,n&272,r,i.getAttributes(),a)}var _P=class extends pP{constructor(e,t,n=c(12),r=[],i=[]){super(r),this.messageMethod=e,this.messageClass=t,this.transactionId=n,this.rawAttributes=i}toJSON(){return this.json}get json(){return{messageMethod:this.messageMethod,messageClass:this.messageClass,attributes:this.attributes,rawAttributes:this.rawAttributes.map(e=>({type:e.type,length:e.value.length}))}}get transactionIdHex(){return this.transactionId.toString(`hex`)}appendRawAttribute(e,t){return this.rawAttributes.push({type:e,value:Buffer.from(t)}),this}get unknownAttributeTypes(){return this.rawAttributes.map(e=>e.type)}get bytes(){let e=Buffer.concat(this.serializedAttributes.map(e=>vP(e.type,e.value))),t=Buffer.alloc(8);return t.writeUInt16BE(this.messageMethod|this.messageClass,0),t.writeUInt16BE(e.length,2),t.writeUInt32BE(LN,4),Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){return this.setAttribute(`MESSAGE-INTEGRITY`,this.messageIntegrity(e)),this}messageIntegrity(e){let t=yP(this.bytes,this.bytes.length-20+24);return Buffer.from(o(`sha1`,e).update(t).digest(`hex`),`hex`)}addFingerprint(){return this.setAttribute(`FINGERPRINT`,bP(this.bytes)),this}get serializedAttributes(){let e=[];for(let t of this.attributesKeys){let n=this.getAttributeValue(t),[r,,i]=hP[t],a=i.name===eP.name?i(n,this.transactionId):i(n);e.push({type:r,value:a})}return e.push(...this.rawAttributes.map(e=>({type:e.type,value:Buffer.from(e.value)}))),e}};function vP(e,t){let n=t.length,r=SP(n),i=Buffer.alloc(4);return i.writeUInt16BE(e,0),i.writeUInt16BE(n,2),Buffer.concat([i,t,Buffer.alloc(r)])}var yP=(e,t)=>{let n=Buffer.alloc(e.length);return e.copy(n,0,0,2),n.writeUInt16BE(t,2),e.copy(n,4,4),n};function bP(e){return(Dk(yP(e,e.length-20+8))^RN)>>>0}function xP(e,t){let n=yP(e,e.length-20+24);return Buffer.from(o(`sha1`,t).update(n).digest(`hex`),`hex`)}function SP(e){let t=e%4;return t===0?0:4-t}var CP=class extends Error{response;addr},wP=class extends CP{constructor(e,t){super(),this.response=e,this.addr=t}get str(){let e=`STUN transaction failed`,t=this.response.getAttributeValue(`ERROR-CODE`);if(t){let[n,r]=t;e+=` (${n} - ${r})`}return e}},TP=class extends CP{get str(){return`STUN transaction timed out`}},EP=Bk(`werift-ice:packages/ice/src/stun/transaction.ts`);async function DP(e,t=0){return b(e[0])?e:[(await D.lookup(e[0],{family:t})).address,e[1]]}function OP(e,t){return typeof e==`object`&&e?e:{retransmissions:typeof e==`number`?e:void 0,onRequestSent:t}}function kP(e,t){return e[0]===t[0]&&e[1]===t[1]}var AP=class{constructor(e,t,n,r,i){this.request=e,this.addr=t,this.protocol=n;let a=OP(r,i);this.triesMax=1+(a.retransmissions??6),this.timeoutDelay=a.responseTimeout??50,this.onRequestSent=a.onRequestSent,this.signal=a.signal,this.expectedAddr=t,this.integrityKey=a.integrityKey}timeoutDelay;ended=!1;tries=0;triesMax;onResponse=new $;onRequestSent;signal;expectedAddr;integrityKey;waitTimer;waitResolve;onAbort;responseReceived=(e,t)=>{if(!(this.ended||this.onResponse.length===0)){if(!kP(this.expectedAddr,t)){EP(`ignore STUN response from unexpected address`,t,`expected`,this.expectedAddr);return}if(this.integrityKey&&!(e.attributesKeys.includes(`MESSAGE-INTEGRITY`)||e.attributesKeys.includes(`MESSAGE-INTEGRITY-SHA256`))){EP(`ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)`);return}e.messageClass===256?(this.onResponse.execute(e,t),this.onResponse.complete()):this.onResponse.error(new wP(e,t))}};run=async()=>{try{if(this.signal?.aborted)throw new TP;return this.attachAbortListener(),this.retry().catch(e=>{EP(`retry failed`,e)}),await this.onResponse.asPromise()}catch(e){throw e}finally{this.cancel()}};attachAbortListener(){this.signal&&(this.onAbort=()=>{this.failWithTimeout()},this.signal.addEventListener(`abort`,this.onAbort,{once:!0}))}failWithTimeout(){this.ended||(this.ended=!0,this.clearWait(),this.onResponse.length>0&&this.onResponse.error(new TP))}clearWait(){this.waitTimer!==void 0&&(clearTimeout(this.waitTimer),this.waitTimer=void 0);let e=this.waitResolve;this.waitResolve=void 0,e?.()}wait(e){return new Promise(t=>{if(this.ended||this.signal?.aborted){t();return}this.waitResolve=t,this.waitTimer=setTimeout(()=>{this.waitTimer=void 0,this.waitResolve=void 0,t()},e)})}retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.onRequestSent?.(this.tries),this.protocol.sendStun(this.request,this.addr).catch(e=>{EP(`send stun failed`,e)}),await this.wait(this.timeoutDelay),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&!this.ended&&(EP(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.failWithTimeout())};cancel(){this.ended=!0,this.clearWait(),this.signal&&this.onAbort&&(this.signal.removeEventListener(`abort`,this.onAbort),this.onAbort=void 0)}};function jP(e,t,n){let r=OP(t,n);return e&&!r.integrityKey&&(r.integrityKey=e),r}var MP=Bk(`werift-ice:packages/ice/src/stun/tcpProtocol.ts`);function NP(e){return`${e[0]}:${e[1]}`}function PP(e){if(e.remoteAddress&&e.remotePort)return[e.remoteAddress,e.remotePort]}async function FP(e,t,n){return await new Promise((r,i)=>{let a=t=>{e.off(`listening`,o),i(t)},o=()=>{e.off(`error`,a),r()};e.once(`error`,a),e.once(`listening`,o),e.listen({host:t,port:n??0,exclusive:!0})})}var IP=class e{static type=`tcp`;type=e.type;transactions={};localCandidate;sentMessage;localIp;onRequestReceived=new $;onDataReceived=new $;sockets=new Map;rememberSocket(e){let t=e.remoteAddr;t&&this.sockets.set(NP(t),e)}forgetSocket(e){e&&this.sockets.delete(NP(e))}registerSocket(e,t){let n={socket:e,buffer:Buffer.alloc(0),remoteAddr:t};return t&&this.rememberSocket(n),e.on(`data`,t=>{n.buffer=Buffer.concat([n.buffer,t]);let{frames:r,rest:i}=VN(n.buffer);n.buffer=i;let a=n.remoteAddr??PP(e);if(!n.remoteAddr&&a&&(n.remoteAddr=a,this.rememberSocket(n)),a)for(let e of r)e.length!==0&&this.handleFrame(e,a)}),e.on(`close`,()=>{this.forgetSocket(n.remoteAddr)}),e.on(`error`,e=>{MP(`tcp socket error`,e)}),n}handleFrame(e,t){try{let n=gP(e);if(!n){this.onDataReceived.execute(e);return}if((n.messageClass===256||n.messageClass===272)&&this.transactions[n.transactionIdHex]){let r=this.transactions[n.transactionIdHex],i=r.integrityKey?gP(e,r.integrityKey):n;if(!i){MP(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){MP(`tcp frame parse error`,e)}}async sendFrame(e,t){let n=await this.getSocket(t);await new Promise((t,r)=>{n.socket.write(BN(e),e=>{if(e){r(e);return}t()})})}async sendStun(e,t){await this.sendFrame(e.bytes,t)}async sendData(e,t){await this.sendFrame(e,t)}async request(e,t,n,r,i){if(this.transactions[e.transactionIdHex])throw Error(`already requested`);n&&(e.addMessageIntegrity(n),e.addFingerprint());let a=await DP(t),o=jP(n,r,i),s=new AP(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}finally{delete this.transactions[e.transactionIdHex]}}async pruneForSelection(e){for(let[t,n]of this.sockets.entries())e&&t===NP(e)||(n.socket.destroy(),this.sockets.delete(t))}get activeSocketCount(){return this.sockets.size}get address(){return{}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()}),await this.pruneForSelection(),this.onRequestReceived.complete(),this.onDataReceived.complete()}},LP=class extends IP{pendingSockets=new Map;async connectionMade(e){this.localIp=e}async getSocket(e){let t=NP(e),n=this.sockets.get(t);if(n)return n;let r=this.pendingSockets.get(t);if(r)return await r;let i=new Promise((t,n)=>{let r=v({host:e[0],port:e[1],localAddress:this.localIp}),i=this.registerSocket(r,e),a=e=>{r.off(`connect`,o),n(e)},o=()=>{r.off(`error`,a),t(i)};r.once(`error`,a),r.once(`connect`,o)});this.pendingSockets.set(t,i);try{return await i}finally{this.pendingSockets.delete(t)}}},RP=class extends IP{server=y(e=>{this.registerSocket(e,PP(e))});async connectionMade(e,t){if(this.localIp=e,t){let n;for(let r=t[0];r<=t[1];r++)try{await FP(this.server,e,r);return}catch(e){n=e}throw n??Error(`tcp port not found`)}await FP(this.server,e)}async getSocket(e){let t=this.sockets.get(NP(e));if(!t)throw Error(`tcp passive connection not established`);return t}get listeningPort(){let e=this.server.address();if(!e||typeof e==`string`)throw Error(`tcp passive protocol is not listening`);return e.port}async close(){await super.close(),await new Promise(e=>{this.server.close(()=>e())})}},zP=Bk(`werift-ice : packages/ice/src/stun/protocol.ts`),BP=class e{static type=`stun`;type=e.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new $;onDataReceived=new $;constructor(){}connectionMade=async(e,t,n)=>{this.transport=e?await Uk.init(`udp4`,{portRange:t,interfaceAddresses:n}):await Uk.init(`udp6`,{portRange:t,interfaceAddresses:n}),this.transport.onData=(e,t)=>{this.datagramReceived(e,t)}};datagramReceived(e,t){try{let n=gP(e);if(!n){this.localCandidate&&this.onDataReceived.execute(e);return}if((n.messageClass===256||n.messageClass===272)&&this.transactionsKeys.includes(n.transactionIdHex)){let r=this.transactions[n.transactionIdHex],i=r.integrityKey?gP(e,r.integrityKey):n;if(!i){zP(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){zP(`datagramReceived error`,e)}}getExtraInfo(){let{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed)return;let n=e.bytes;await this.transport.send(n,t).catch(()=>{zP(`sendStun failed`,t,e)})}async sendData(e,t){this.transport.closed||await this.transport.send(e,t)}async request(e,t,n,r,i){if(this.transactionsKeys.includes(e.transactionIdHex))throw Error(`already request ed`);n&&(e.addMessageIntegrity(n),e.addFingerprint());let a=await DP(t,this.transport.socketType===`udp6`?6:4),o=jP(n,r,i),s=new AP(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}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()}};function VP(e,t,n){return a(`md5`).update(Buffer.from([e,t,n].join(`:`))).digest()}function HP(e){return c(e).toString(`hex`).substring(0,e)}function UP(){return c(12)}var WP=class{queue=[];wait=new $;put(e){this.queue.push(e),this.queue.length===1&&this.wait.execute(e)}get(){return this.queue.shift()||new Promise(e=>{this.wait.subscribe(t=>{this.queue.shift(),e(t)})})}},GP=e=>{let t,n,r=new Promise((e,r)=>{t=e,n=r});r.then(()=>{i.execute(void 0),i.complete()}).catch(e=>{i.execute(e??Error()),i.complete()});let i=new $;return e(t,n,i).catch(()=>{}),{awaitable:r,resolve:t,reject:n}};function KP(e){return e.length>=4&&(e[0]&192)==64}function qP(e,t){let n=Buffer.alloc(4);return n.writeUInt16BE(e,0),n.writeUInt16BE(t.length,2),Buffer.concat([n,t])}function JP(e){if(!KP(e)||e.length<4)return;let t=e.readUInt16BE(0),n=e.readUInt16BE(2);if(!(e.length<4+n))return{channelNumber:t,data:e.subarray(4,4+n)}}function YP(e){let t=SP(e.length);return t>0?Buffer.concat([e,Buffer.alloc(t)]):e}function XP(e){let t=[],n=0,r=!1;for(;e.length-n>=4;){let i;if(KP(e.subarray(n))){let t=e.readUInt16BE(n+2);i=4+t+SP(t)}else if(e[n]&192){r=!0;break}else{if(e.length-n<20)break;let t=e.readUInt16BE(n+2);i=20+t+SP(t)}if(e.length-n<i)break;t.push(e.subarray(n,n+i)),n+=i}return{frames:t,malformed:r,rest:e.subarray(n)}}var ZP=Bk(`werift-ice:packages/ice/src/turn/protocol.ts`),QP=500,$P=600,eF=285212672;function tF(e){return e.type===`tcp`||e.type===`tls`}function nF(e){return e[0]}function rF(e){return JSON.stringify(e)}var iF=class e{constructor(e){this.turn=e,e.onData.subscribe((e,t)=>{this.handleStunMessage(e,t)}).disposer(this.disposer)}static type=`turn`;type=e.type;localCandidate;disposer=new Vk;onRequestReceived=new $;onDataReceived=new $;handleStunMessage=(e,t)=>{try{let n=gP(e);if(!n){this.onDataReceived.execute(e);return}if(n.messageClass===256||n.messageClass===272){let r=this.turn.transactions[n.transactionIdHex];if(r){let i=r.integrityKey?gP(e,r.integrityKey):n;if(!i){ZP(`STUN over TURN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){ZP(`datagramReceived error`,e)}};async request(e,t,n,r,i){if(this.turn.transactions[e.transactionIdHex])throw Error(`exist`);n&&(e.addMessageIntegrity(n),e.addFingerprint());let a=await DP(t),o=jP(n,r,i),s=new AP(e,a,this,o);this.turn.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){return this.disposer.dispose(),this.turn.close()}},aF=class e{constructor(e,t,n,r,i,a={}){this.server=e,this.username=t,this.password=n,this.lifetime=r,this.transport=i,this.options=a,this.channelRefreshTime=this.options.channelRefreshTime??QP}static type=`turn`;type=e.type;onData=new $;onRequestReceived=new $;onDataReceived=new $;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBindQueue=Promise.resolve();channelBindingByAddr=new Map;tcpBuffer=Buffer.alloc(0);permissionByAddr={};permissionQueue=Promise.resolve();creatingPermissionByAddr=new Map;async connectionMade(){this.transport.onData=(e,t)=>{this.dataReceived(e,t)};let e=new _P(3,0);e.setAttribute(`LIFETIME`,this.lifetime).setAttribute(`REQUESTED-TRANSPORT`,eF);let[t]=await this.requestWithRetry(e,this.server).catch(e=>{throw ZP(`connect error`,e),e});this.relayedAddress=t.getAttributeValue(`XOR-RELAYED-ADDRESS`),this.mappedAddress=t.getAttributeValue(`XOR-MAPPED-ADDRESS`);let n=t.getAttributeValue(`LIFETIME`);ZP(`connect`,this.relayedAddress,this.mappedAddress,{exp:n}),this.refresh(n)}handleChannelData(e){let t=JP(e),n=t&&this.addrByChannel[t.channelNumber];n&&t&&this.onData.execute(t.data,n)}handleSTUNMessage(e,t){try{let n=gP(e);if(!n)throw Error(`not stun message`);if(n.messageClass===256||n.messageClass===272){let r=this.transactions[n.transactionIdHex];if(r){let i=r.integrityKey?gP(e,r.integrityKey):n;if(!i){ZP(`TURN STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}}else n.messageClass===0&&this.onData.execute(e,t);if(n.getAttributeValue(`DATA`)){let e=n.getAttributeValue(`DATA`),r=n.getAttributeValue(`XOR-PEER-ADDRESS`)??t;this.onData.execute(e,r)}}catch{ZP(`parse error`,e.toString())}}dataReceived(e,t){let n=(e,t)=>{e.length>=4&&KP(e)?this.handleChannelData(e):this.handleSTUNMessage(e,t)};if(tF(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);let{frames:r,rest:i}=XP(this.tcpBuffer);this.tcpBuffer=i;for(let e of r)n(e,t)}else n(e,t)}async send(e,t){this.transport.closed||await this.transport.send(tF(this.transport)?YP(e):e,t)}async createPermission(e){let t=new _P(8,0);t.setAttribute(`XOR-PEER-ADDRESS`,e).setAttribute(`USERNAME`,this.username).setAttribute(`REALM`,this.realm).setAttribute(`NONCE`,this.nonce),await this.requestWithRetry(t,this.server)}refresh=e=>{this.refreshHandle=GP(async(t,n,r)=>{let i=!0;for(r.once(()=>{i=!1});i;){let t=5/6*e*1e3;ZP(`refresh delay`,t,{exp:e}),await E(t);let n=new _P(4,0);n.setAttribute(`LIFETIME`,e);try{let[t]=await this.requestWithRetry(n,this.server);e=t.getAttributeValue(`LIFETIME`),ZP(`refresh`,{exp:e})}catch(e){ZP(`refresh error`,e)}}})};async request(e,t,n,r,i){if(this.transactions[e.transactionIdHex])throw Error(`exist`);this.integrityKey&&e.setAttribute(`USERNAME`,this.username).setAttribute(`REALM`,this.realm).setAttribute(`NONCE`,this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let a=await DP(t),o=jP(this.integrityKey,r,i),s=new AP(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,t){let n,r;try{[n,r]=await this.request(e,t)}catch(t){if(t instanceof wP==0)throw ZP(`requestWithRetry error`,t),t;this.server=t.addr;let[i]=t.response.getAttributeValue(`ERROR-CODE`),a=t.response.getAttributeValue(`NONCE`),o=t.response.getAttributeValue(`REALM`);if((i===401&&o||i===438&&this.realm)&&a)ZP(`retry with nonce`,i),this.nonce=a,i===401&&(this.realm=o),this.integrityKey=cF(this.username,this.realm,this.password),e.transactionId=UP(),[n,r]=await this.request(e,this.server);else throw t}return[n,r]}async sendData(e,t){let n;try{n=await this.getChannel(t)}catch(e){ZP(`channelBind error; falling back to Send Indication`,e)}if(!n){await this.getPermission(t);let n=new _P(6,16).setAttribute(`DATA`,e).setAttribute(`XOR-PEER-ADDRESS`,t);await this.sendStun(n,this.server);return}await this.send(qP(n.number,e),this.server)}async getPermission(e){let t=nF(e);if(this.permissionByAddr[t])return;let n=this.creatingPermissionByAddr.get(t);if(n)return n;let r=this.permissionQueue.then(async()=>{this.permissionByAddr[t]||(await this.createPermission(e),this.permissionByAddr[t]=!0)});this.permissionQueue=r.then(()=>void 0,()=>void 0),this.creatingPermissionByAddr.set(t,r);try{await r}catch(e){throw ZP(`createPermission error`,e),e}finally{this.creatingPermissionByAddr.get(t)===r&&this.creatingPermissionByAddr.delete(t)}}async getChannel(e){let t=rF(e),n=this.channelBindingByAddr.get(t);if(n)return n;let r=this.channelByAddr[t],i=Ik(Date.now()/1e3);if(r&&r.refreshAt>i)return r;let a=this.channelBindQueue.then(()=>this.ensureChannel(e));this.channelBindQueue=a.then(()=>void 0,()=>void 0),this.channelBindingByAddr.set(t,a);try{return await a}catch(e){throw ZP(`channelBind error`,e),e}finally{this.channelBindingByAddr.get(t)===a&&this.channelBindingByAddr.delete(t)}}async ensureChannel(e){let t=rF(e),n=Ik(Date.now()/1e3),r=this.channelByAddr[t];if(r&&r.refreshAt>n)return r;let i=!r;r||(r={number:this.channelNumber++,address:e,refreshAt:0},this.channelByAddr[t]=r,this.addrByChannel[r.number]=e);try{return await this.channelBind(r.number,e),r.refreshAt=Ik(Date.now()/1e3)+this.channelRefreshTime,ZP(i?`channelBind`:`channelBind refresh`,r),r}catch(e){throw i&&(delete this.channelByAddr[t],delete this.addrByChannel[r.number]),e}}async channelBind(e,t){let n=new _P(9,0);n.setAttribute(`CHANNEL-NUMBER`,e).setAttribute(`XOR-PEER-ADDRESS`,t);let[r]=await this.requestWithRetry(n,this.server);if(r.messageMethod!==9)throw Error(`should be CHANNEL_BIND`)}async sendStun(e,t){await this.send(e.bytes,t)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};async function oF({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){r??=$P,c??=o?`tls`:`udp`;let l=c===`udp`?await Uk.init(`udp4`,{portRange:i,interfaceAddresses:a}):c===`tcp`?await Wk.init(e):await Gk.init(e,s),u=new aF(e,t,n,r,l);return await u.connectionMade(),u}async function sF({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){return new iF(await oF({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}))}function cF(e,t,n){return VP(e,t,n)}var lF=class e{constructor(e,t,n,r,i,a,o,s,c,l,u,d){this.foundation=e,this.component=t,this.transport=n,this.priority=r,this.host=i,this.port=a,this.type=o,this.relatedAddress=s,this.relatedPort=c,this.tcptype=l,this.generation=u,this.ufrag=d}id=l().toString();refreshId(){this.id=l().toString()}static fromSdp(t){let n=t.split(` `);if(n.length<8)throw Error(`SDP does not have enough properties`);let r={foundation:n[0],component:Number(n[1]),transport:n[2],priority:Number(n[3]),host:n[4],port:Number(n[5]),type:n[7]};for(let e=8,t=n.length-1;e<t;e+=2)n[e]===`raddr`?r.related_address=n[e+1]:n[e]===`rport`?r.related_port=Number(n[e+1]):n[e]===`tcptype`?r.tcptype=n[e+1]:n[e]===`generation`?r.generation=Number(n[e+1]):n[e]===`ufrag`&&(r.ufrag=n[e+1]);let{foundation:i,component:a,transport:o,priority:s,host:c,port:l,type:u}=r;return new e(i,a,o,s,c,l,u,r.related_address,r.related_port,r.tcptype,r.generation,r.ufrag)}canPairWith(e){let t=w(this.host),n=w(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&gF(this,e)&&t===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}},uF={host:126,prflx:110,srflx:100,relay:0},dF={host:105,prflx:90,srflx:80,relay:0},fF={active:6,passive:4,so:2},pF={active:4,passive:2,so:6};function mF(e){return e?.toLowerCase()??`udp`}function hF(e){switch(e){case`active`:case`passive`:case`so`:return e;default:return}}function gF(e,t){if(mF(e.transport)!==`tcp`)return!0;let n=hF(e.tcptype),r=hF(t.tcptype);return!n||!r?!1:n===`active`&&r===`passive`||n===`passive`&&r===`active`||n===`so`&&r===`so`}function _F({candidateType:e,transport:t=`udp`,tcptype:n,otherPreference:r=8191}){if(mF(t)!==`tcp`)return r;let i=hF(n)??`active`;return 8192*(e===`srflx`||e===`prflx`?pF[i]:fF[i])+r}function vF(e,t=`udp`){return(mF(t)===`tcp`?dF:uF)[e]??0}function yF(e,t,n){let r=`${e}|${t}|${n}`;return a(`md5`).update(r,`ascii`).digest(`hex`).slice(7)}function bF(e,t=65535){let n=typeof t==`number`?`udp`:mF(t.transport),r=typeof t==`number`?t:t.localPreference??_F({candidateType:e,transport:n,tcptype:t.tcptype,otherPreference:t.otherPreference});return(1<<24)*vF(e,n)+256*r+255}function xF(e){switch(e){case`passive`:return`active`;case`active`:return`passive`;default:return`so`}}var SF=class{cache=new Map;mdnsInstance=(0,ok.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(e){return new Promise((t,n)=>{let r=()=>{this.mdnsInstance.removeListener(`response`,a),clearTimeout(i)},i=setTimeout(()=>{r(),n(Error(`No mDNS response`))},1e4),a=n=>{let i=n.answers?.[0];i?.type===`A`&&i.name===e&&(r(),t(i.data))};this.mdnsInstance.on(`response`,a),this.mdnsInstance.query(e,`A`)})}close(){this.mdnsInstance.destroy()}},CF=Bk(`werift-ice : packages/ice/src/ice.ts : log`),wF=class{constructor(e,t,n){this.protocol=e,this.remoteCandidate=t,this.iceControlling=n}id=l().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;requestsReceived=0;requestsSent=0;responsesReceived=0;responsesSent=0;retransmissionsReceived=0;retransmissionsSent=0;consentRequestsSent=0;requestTransactionIds=new Set;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(e){this._state=e}get localCandidate(){if(!this.protocol.localCandidate)throw 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 AF(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}noteIncomingRequest(e){return this.requestTransactionIds.has(e)?(this.retransmissionsReceived++,!0):(this.requestTransactionIds.add(e),!1)}},TF=1e3;function EF(e){return e===void 0||!Number.isFinite(e)||e<=0?TF:Math.max(500,Math.round(e*1e3*2+200))}var DF={iceLite:!1,useTcp:!1,useIpv4:!0,useIpv6:!0};function OF(e){if(![`host`,`relay`,`srflx`].includes(e.type))throw Error(`Unexpected candidate type "${e.type}"`);return e}function kF(e,t){return e.sort((e,n)=>AF(e.localCandidate,e.remoteCandidate,t)-AF(n.localCandidate,n.remoteCandidate,t)).reverse()}function AF(e,t,n){let r=n&&e.priority||t.priority,i=n&&t.priority||e.priority;return 1*Math.min(r,i)+2*Math.max(r,i)+ +(r>i)}async function jF(e,t){let n=new _P(1,0);try{let[r]=await e.request(n,t),i=e.localCandidate;if(!i)throw Error(`not exist`);return new lF(yF(`srflx`,i.transport,i.host),i.component,i.transport,bF(`srflx`,{transport:i.transport,tcptype:i.tcptype}),r.getAttributeValue(`XOR-MAPPED-ADDRESS`)[0],r.getAttributeValue(`XOR-MAPPED-ADDRESS`)[1],`srflx`,i.host,i.port,i.tcptype)}catch(e){CF(`error serverReflexiveCandidate`,e)}}function MF(e){return e&&Number.isNaN(e[1])?[e[0],443]:e}function NF(e,t,n={},r){let i=[`ipsec`,`tun`,`utun`,`tap`],a=[`vmnet`,`veth`],{useLinkLocalAddress:o}=n,s=Object.keys(e).map(n=>{for(let e of[...i,...a])if(n.startsWith(e))return{nic:n,addresses:[]};return{nic:n,addresses:(e[n]??[]).filter(e=>zk(e.family)===t&&!e.internal&&(o?!0:!r(e))).map(e=>e.address)}}).filter(e=>!!e);return s.sort((e,t)=>e.nic.localeCompare(t.nic)),Object.values(s).flatMap(e=>e.addresses)}var PF=Bk(`werift-ice : packages/ice/src/utils.ts`);function FF(e){return zk(e.family)===4&&e.address?.startsWith(`169.254.`)||zk(e.family)===6&&e.address?.startsWith(`fe80::`)}function IF(e,{useLinkLocalAddress:t}={}){let n=m.networkInterfaces();return PF(n),NF(n,e,{useLinkLocalAddress:t},FF)}function LF(e,t,n={}){let r=[];return e&&r.push(...IF(4,n)),t&&r.push(...IF(6,n)),r}var RF=Bk(`werift-ice : packages/ice/src/ice.ts : log`),zF=class{constructor(e,t){this._iceControlling=e,this.options={...DF,...t},this.iceLite&&(this._iceControlling=!1);let{stunServer:n,turnServer:r}=this.options;this.stunServer=MF(n)??[`stun.l.google.com`,19302],this.turnServer=MF(r),this.restart(),RF(`new Connection`,this.options)}localUsername=HP(4);localPassword=HP(22);remoteIsLite=!1;remotePassword=``;remoteUsername=``;checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=c(8).readBigUInt64BE(0);state=`new`;lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new WP;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;consentFresh=!1;consentSessionId=0;consentExpiryTimer;consentRequestAbort;onData=new $;stateChanged=new $;onIceCandidate=new $;get iceControlling(){return this._iceControlling}set iceControlling(e){this.iceLite&&(e=!1),!this.nominated&&this.applyIceControlling(e)}get iceLite(){return this.options.iceLite}async restart(){this.generation++,this.localUsername=HP(4),this.localPassword=HP(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 WP,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let e of this.protocols)e.localCandidate&&(e.localCandidate.refreshId(),e.localCandidate.generation=this.generation,e.localCandidate.ufrag=this.localUsername);this.stopConsentLifecycle()}resetNominatedPair(){RF(`resetNominatedPair`),this.nominated=void 0,this.nominating=!1,this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:n}){RF(`setRemoteParams`,{iceLite:e,usernameFragment:t,password:n}),this.remoteIsLite=e,this.remoteUsername=t,this.remotePassword=n}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;for(let e of this.protocols)e.localCandidate&&(e.localCandidate.generation=this.generation,e.localCandidate.ufrag=this.localUsername,this.appendLocalCandidate(e.localCandidate));let e=LF(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:t}=this.options;if(t){let n=e.filter(e=>Object.values(t).includes(e));n.length&&(e=n)}this.options.additionalHostAddresses&&(e=Array.from(new Set([...this.options.additionalHostAddresses,...e])));let n=this.getCandidatePromises(e,5);await Promise.allSettled(n),this.localCandidatesEnd=!0}this.setState(`completed`)}appendLocalCandidate(e){this.localCandidates.push(e),this.onIceCandidate.execute(e)}ensureProtocol(e){e.onRequestReceived.subscribe((t,n,r)=>{if(t.messageMethod!==1){this.respondError(t,n,e,[400,`Bad Request`]);return}let{remoteUsername:i}=VF(t.getAttributeValue(`USERNAME`)),a=this.userHistory[i]??this.localPassword,{iceControlling:o}=this;if(o&&t.attributesKeys.includes(`ICE-CONTROLLING`)){if(this.tieBreaker>=t.getAttributeValue(`ICE-CONTROLLING`)){this.respondError(t,n,e,[487,`Role Conflict`]);return}this.switchRole(!1)}else if(!o&&t.attributesKeys.includes(`ICE-CONTROLLED`)){if(this.iceLite||this.tieBreaker<t.getAttributeValue(`ICE-CONTROLLED`)){this.respondError(t,n,e,[487,`Role Conflict`]);return}this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(t,n,e))return;let s=new _P(1,256,t.transactionId);s.setAttribute(`XOR-MAPPED-ADDRESS`,n).addMessageIntegrity(Buffer.from(a,`utf8`)).addFingerprint(),e.sendStun(s,n).catch(e=>{RF(`sendStun error`,e)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([t,n,e]):this.checkIncoming(t,n,e)}),e.onDataReceived.subscribe(t=>{try{let n=this.nominated;n&&n.protocol===e&&(n.packetsReceived++,n.bytesReceived+=t.length),this.onData.execute(t)}catch(e){RF(`dataReceived`,e)}})}getCandidatePromises(e,t=5){let n=[],{stunServer:r,turnServer:i}=this,{turnUsername:a,turnPassword:o}=this.options,s=this.iceLite,c=!s&&this.options.forceTurn&&i&&a&&o;e=e.filter(e=>!this.protocols.find(t=>t.localIp===e));let l=c?[]:e.map(async e=>{let t=new BP;this.ensureProtocol(t);try{await t.connectionMade(w(e),this.options.portRange,this.options.interfaceAddresses),t.localIp=e,this.protocols.push(t),RF(`protocol`,t.localIp);let n=[e,t.getExtraInfo()[1]];return t.localCandidate=new lF(yF(`host`,`udp`,n[0]),1,`udp`,bF(`host`,{transport:`udp`}),n[0],n[1],`host`,void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(t),this.appendLocalCandidate(t.localCandidate),t}catch(e){RF(`error protocol STUN`,e)}});if(c||n.push(...l.map(e=>e.then(e=>e?.localCandidate))),!c&&this.options.useTcp){let t=e.map(async e=>{let t=new RP;if(this.ensureProtocol(t),await t.connectionMade(e,this.options.portRange),t.localIp=e,t.localCandidate=new lF(yF(`host`,`tcp`,e),1,`tcp`,bF(`host`,{transport:`tcp`,tcptype:`passive`}),e,t.listeningPort,`host`,void 0,void 0,`passive`,this.generation,this.localUsername),this.protocols.push(t),this.appendLocalCandidate(t.localCandidate),!s){let t=new LP;this.ensureProtocol(t),await t.connectionMade(e),t.localIp=e,t.localCandidate=new lF(yF(`host`,`tcp`,e),1,`tcp`,bF(`host`,{transport:`tcp`,tcptype:`active`}),e,9,`host`,void 0,void 0,`active`,this.generation,this.localUsername),this.protocols.push(t),this.pairLocalProtocol(t),this.appendLocalCandidate(t.localCandidate)}});n.push(...t)}if(!s&&!c&&r){let e=l.map(async e=>{let n=await e;if(n)return new Promise(async(e,i)=>{let a=setTimeout(i,t*1e3);if(n.localCandidate?.host&&w(n.localCandidate?.host)){let t=await jF(n,r).catch(e=>{RF(`error`,e)});t&&this.appendLocalCandidate(t),clearTimeout(a),e(t)}else clearTimeout(a),e()}).catch(e=>{RF(`query STUN server`,e)})});n.push(...e)}if(!s&&i&&a&&o){let e=(async()=>{let e=this.options.turnTransport??`udp`,t=await sF({address:i,username:a,password:o},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:e,tlsOptions:this.options.turnTlsOptions}).catch(async t=>{if(e===`udp`)return await sF({address:i,username:a,password:o},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:`tcp`});throw t});this.ensureProtocol(t),this.protocols.push(t);let n=t.turn.relayedAddress,r=t.turn.mappedAddress;return RF(`turn candidateAddress`,n),t.localCandidate=new lF(yF(`relay`,`udp`,n[0]),1,`udp`,bF(`relay`),n[0],n[1],`relay`,r[0],r[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(t.localCandidate),t.localCandidate})().catch(e=>{RF(`query TURN server`,e)});n.push(e)}return n}async connect(){if(RF(`start connect ice`),!this.localCandidatesEnd&&!this.localCandidatesStart)throw Error(`Local candidates gathering was not performed`);if(!this.remoteUsername||!this.remotePassword)throw Error(`Remote username or password is missing`);for(let e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList(),this.iceLite||this.unfreezeInitial(),RF(`earlyChecks`,this.localPassword,this.earlyChecks.length);for(let e of this.earlyChecks)this.checkIncoming(...e);if(this.earlyChecks=[],this.earlyChecksDone=!0,this.iceLite){if(!this.nominated){let e=2;for(;!this.checkListDone&&this.state!==`closed`&&(e=await this.checkListState.get(),RF(`checkListState`,e),e!==1););if(e!==1&&!this.nominated)throw Error(`ICE negotiation failed`)}this.setState(`connected`);return}for(;this.state!==`closed`&&this.schedulingChecks();)await O.setTimeout(20);let e=2;for(;this.checkList.length>0&&e===2;)e=await this.checkListState.get(),RF(`checkListState`,e);for(let e of this.checkList)e.handle?.resolve?.();if(e!==1)throw Error(`ICE negotiation failed`);this.queryConsent(),this.setState(`connected`)}unfreezeInitial(){let[e]=this.checkList;if(!e)return;e.state===0&&e.updateState(1);let t=new Set(e.localCandidate.foundation);for(let n of this.checkList)n.component===e.component&&!t.has(n.localCandidate.foundation)&&n.state===0&&(n.updateState(1),t.add(n.localCandidate.foundation))}schedulingChecks(){{let e=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===BP.type)).find(e=>e.state===1);if(e)return e.handle=this.checkStart(e),!0}{let e=this.checkList.find(e=>e.state===0);if(e)return e.handle=this.checkStart(e),!0}return!this.remoteCandidatesEnd&&!this.checkListDone}stopConsentLifecycle(){this.consentSessionId++,this.consentFresh=!1,this.consentExpiryTimer!==void 0&&(clearTimeout(this.consentExpiryTimer),this.consentExpiryTimer=void 0),this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0;let e=this.queryConsentHandle;this.queryConsentHandle=void 0,e?.resolve?.()}shouldNominateConsentRequest(e){return this.iceControlling&&this.remoteIsLite&&this.nominated?.id===e.id}canSendApplicationData(){return!this.nominated||this.state===`closed`||this.state===`failed`?!1:this.iceLite?!0:this.consentFresh}abortableDelay(e,t){return new Promise((n,r)=>{if(t.aborted){r(new DOMException(`The operation was aborted`,`AbortError`));return}let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`The operation was aborted`,`AbortError`))};t.addEventListener(`abort`,a,{once:!0})})}queryConsent=()=>{if(this.iceLite)return;this.stopConsentLifecycle();let e=this.consentSessionId;this.consentFresh=!0;let t=GP(async(n,r,i)=>{let a=!1,o=new AbortController,s=()=>{this.consentExpiryTimer!==void 0&&(clearTimeout(this.consentExpiryTimer),this.consentExpiryTimer=void 0)},c=()=>{a||e!==this.consentSessionId||(s(),this.consentExpiryTimer=setTimeout(()=>{this.consentExpiryTimer=void 0,!(a||e!==this.consentSessionId)&&this.state!==`closed`&&this.state!==`failed`&&(RF(`Consent to send expired`),this.consentFresh=!1,this.consentSessionId++,this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0,this.queryConsentHandle===t&&(this.queryConsentHandle=void 0),a=!0,o.abort(),this.setState(`failed`))},3e4))};i.once(()=>{a=!0,e===this.consentSessionId&&(s(),this.consentRequestAbort?.abort(),this.consentRequestAbort=void 0),o.abort(),this.queryConsentHandle===t&&(this.queryConsentHandle=void 0)}),c();let l=()=>5*(.8+.4*Math.random())*1e3,u=Date.now()+l(),d=()=>this.state===`closed`||this.state===`failed`;try{for(;!d()&&!a&&e===this.consentSessionId&&(await this.abortableDelay(Math.max(0,u-Date.now()),o.signal),!(a||d()||e!==this.consentSessionId));){u=Date.now()+l();let t=this.nominated;if(!t)break;let n=t.id,r=this.generation,i=this.remotePassword,{localUsername:o,remoteUsername:s,iceControlling:d}=this,f=this.buildRequest({nominate:this.shouldNominateConsentRequest(t),localUsername:o,remoteUsername:s,iceControlling:d,localCandidate:t.localCandidate});this.consentRequestAbort?.abort();let p=new AbortController;this.consentRequestAbort=p,t.consentRequestsSent++,t.requestsSent++;let m=EF(t.rtt),h=performance.now();t.protocol.request(f,t.remoteAddr,Buffer.from(i,`utf8`),{retransmissions:0,responseTimeout:m,signal:p.signal,onRequestSent:e=>{e>0&&t.retransmissionsSent++}}).then(()=>{if(e!==this.consentSessionId||a)return;let o=this.state;if(o===`closed`||o===`failed`||this.nominated?.id!==n||this.generation!==r||this.remotePassword!==i)return;let s=(performance.now()-h)/1e3;t.rtt=s,t.totalRoundTripTime+=s,t.roundTripTimeMeasurements++,t.responsesReceived++,this.consentFresh=!0,c(),o===`disconnected`&&this.setState(`connected`)}).catch(t=>{e===this.consentSessionId&&this.nominated?.id===n&&RF(`no stun response`,t)})}}catch{}finally{e===this.consentSessionId&&s()}});this.queryConsentHandle=t};async close(){this.setState(`closed`),this.stopConsentLifecycle(),this.checkList&&!this.checkListDone&&this.checkListState.put(new Promise(e=>{e(2)})),this.nominated=void 0;for(let e of this.protocols)e.close&&await e.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(e){this.state=e,this.stateChanged.execute(e)}async addRemoteCandidate(e){if(!e){this.remoteCandidatesEnd=!0;return}if(e.host.includes(`.local`))try{this.lookup||=new SF,e.host=await this.lookup.lookup(e.host)}catch{return}try{OF(e)}catch{return}RF(`addRemoteCandidate`,e),this._remoteCandidates.push(e),this.pairRemoteCandidate(e),this.sortCheckList()}send=async e=>{if(!this.canSendApplicationData())return;let t=this.nominated;await t.protocol.sendData(e,t.remoteAddr),t.packetsSent++,t.bytesSent+=e.length};getDefaultCandidate(){let[e]=this.localCandidates.sort((e,t)=>e.priority-t.priority);return e}set remoteCandidates(e){if(this.remoteCandidatesEnd)throw Error(`Cannot set remote candidates after end-of-candidates.`);this._remoteCandidates=[];for(let t of e){try{OF(t)}catch{continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){kF(this.checkList,this.iceControlling)}findPair(e,t){return this.checkList.find(n=>n.protocol===e&&n.remoteCandidate===t)}applyIceControlling(e){this._iceControlling=e;for(let t of this.checkList)t.iceControlling=e}switchRole(e){RF(`switch role`,e),this.iceLite&&(e=!1),this.applyIceControlling(e),this.sortCheckList()}checkComplete(e){if(e.handle=void 0,e.state===3){if(e.nominated&&(e.remoteCandidate.generation==null||e.remoteCandidate.generation===this.generation)&&this.nominated==null){RF(`nominated`,e.toJSON()),this.nominated=e,this.nominating=!1,this.pruneTcpConnections(e),!this.iceLite&&(this.state===`connected`||this.state===`completed`)&&this.queryConsent();for(let t of this.checkList)t.component===e.component&&[1,0].includes(t.state)&&t.updateState(4)}if(this.nominated){this.checkListDone||=(RF(`ICE completed`),this.checkListState.put(new Promise(e=>e(1))),!0);return}RF(`not completed`,e.toJSON());for(let t of this.checkList)t.localCandidate.foundation===e.localCandidate.foundation&&t.state===0&&t.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:t})=>!e.includes(t)))return}(this.iceControlling||!this.checkList.find(({state:e})=>e===3))&&(this.checkListDone||(RF(`ICE failed`),this.checkListState.put(new Promise(e=>{e(2)}))))}checkStart=e=>GP(async t=>{RF(`check start`,e.toJSON()),e.updateState(2);let n={},{remotePassword:r,remoteUsername:i,generation:a}=this,o=e.localCandidate.ufrag??this.localUsername,s=this.iceControlling&&!this.remoteIsLite,c=this.buildRequest({nominate:s,localUsername:o,remoteUsername:i,iceControlling:this.iceControlling,localCandidate:e.localCandidate}),l=performance.now();try{e.requestsSent++;let[t,s]=await e.protocol.request(c,e.remoteAddr,Buffer.from(r,`utf8`),e.localCandidate.transport.toLowerCase()===`tcp`?0:4,t=>{t>0&&e.retransmissionsSent++});e.responsesReceived++;let u=(performance.now()-l)/1e3;e.rtt=u,e.totalRoundTripTime+=u,e.roundTripTimeMeasurements++,RF(`response received`,c.toJSON(),t.toJSON(),s,{localUsername:o,remoteUsername:i,remotePassword:r,generation:a,rtt:u}),n.response=t,n.addr=s}catch(n){let s=n;if(RF(`failure case`,c.toJSON(),s.response?JSON.stringify(s.response.toJSON(),null,2):n,{localUsername:o,remoteUsername:i,remotePassword:r,generation:a},e.remoteAddr),s.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(e).awaitable,t();return}if(s.response?.getAttributeValue(`ERROR-CODE`)[0]===401){RF(`retry 401`,e.toJSON()),await this.checkStart(e).awaitable,t();return}RF(`checkStart CandidatePairState.FAILED`,e.toJSON()),e.updateState(4),this.checkComplete(e),t();return}if(n.addr[0]!==e.remoteAddr[0]||n.addr[1]!==e.remoteAddr[1]){e.updateState(4),this.checkComplete(e),t();return}if(s||e.remoteNominated)e.nominated=!0;else if(this.iceControlling&&!this.nominating){this.nominating=!0;let t=this.buildRequest({nominate:!0,localUsername:o,remoteUsername:i,iceControlling:this.iceControlling,localCandidate:e.localCandidate});try{e.requestsSent++,await e.protocol.request(t,e.remoteAddr,Buffer.from(this.remotePassword,`utf8`),e.localCandidate.transport.toLowerCase()===`tcp`?0:4,t=>{t>0&&e.retransmissionsSent++}),e.responsesReceived++}catch{e.updateState(4),this.checkComplete(e);return}e.nominated=!0}e.updateState(3),this.checkComplete(e),t()});addPair(e){this.checkList.push(e),this.sortCheckList()}checkIncoming(e,t,n){let{remoteUsername:r}=VF(e.getAttributeValue(`USERNAME`)),i,[a,o]=t;for(let e of this.remoteCandidates)if(e.host===a&&e.port===o){i=e;break}i||(i=new lF(HP(10),1,n.localCandidate?.transport??`udp`,e.getAttributeValue(`PRIORITY`),a,o,`prflx`,void 0,void 0,n.localCandidate?.transport===`tcp`?xF(n.localCandidate.tcptype):void 0,void 0,void 0),this._remoteCandidates.push(i));let s=this.findPair(n,i);if(s||(s=new wF(n,i,this.iceControlling),s.updateState(1),this.addPair(s)),s.noteIncomingRequest(e.transactionIdHex),s.requestsReceived++,s.responsesSent++,s.localCandidate.ufrag=r,RF(`Triggered Checks`,e.toJSON(),s.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),this.iceLite){e.attributesKeys.includes(`USE-CANDIDATE`)&&!this.iceControlling&&(s.remoteNominated=!0,s.nominated=!0,s.updateState(3),this.checkComplete(s));return}[1,4].includes(s.state)&&(s.handle=this.checkStart(s)),e.attributesKeys.includes(`USE-CANDIDATE`)&&!this.iceControlling&&(s.remoteNominated=!0,s.state===3&&(s.nominated=!0,this.checkComplete(s)))}tryPair(e,t){if(e.localCandidate?.canPairWith(t)&&(e.localCandidate.transport.toLowerCase()!==`tcp`||e.localCandidate.tcptype!==`passive`||t.type===`prflx`)&&!this.findPair(e,t)){let n=new wF(e,t,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(n))return;n.updateState(1),this.addPair(n)}}pairLocalProtocol(e){for(let t of this.remoteCandidates)this.tryPair(e,t)}pairRemoteCandidate=e=>{for(let t of this.protocols)this.tryPair(t,e)};buildRequest({nominate:e,remoteUsername:t,localUsername:n,iceControlling:r,localCandidate:i}){let a=BF({remoteUsername:t,localUsername:n}),o=new _P(1,0);return o.setAttribute(`USERNAME`,a).setAttribute(`PRIORITY`,bF(`prflx`,{transport:i?.transport,tcptype:i?.tcptype})),r?(o.setAttribute(`ICE-CONTROLLING`,this.tieBreaker),e&&o.setAttribute(`USE-CANDIDATE`,null)):o.setAttribute(`ICE-CONTROLLED`,this.tieBreaker),o}pruneTcpConnections(e){for(let t of this.protocols)t.localCandidate?.transport.toLowerCase()===`tcp`&&`pruneForSelection`in t&&typeof t.pruneForSelection==`function`&&t.pruneForSelection(t===e.protocol?e.remoteAddr:void 0)}respondError(e,t,n,r){let i=new _P(e.messageMethod,272,e.transactionId);i.setAttribute(`ERROR-CODE`,r).addMessageIntegrity(Buffer.from(this.localPassword,`utf8`)).addFingerprint(),n.sendStun(i,t).catch(e=>{RF(`sendStun error`,e)})}},BF=({remoteUsername:e,localUsername:t})=>`${e}:${t}`,VF=e=>{let[t,n]=e.split(`:`);return{remoteUsername:t,localUsername:n}};function HF(e){return e.map((e,t)=>[t,e])}function UF(e,t){let n=e.split(t);return[n[0],n.slice(1).join(t)]}var WF=class extends k{emit(e,...t){if(typeof e!=`string`)return super.emit(e,...t);if(t.length===0)return super.emit(e,new Event(e));let[n,...r]=t;if(n&&typeof n==`object`&&!(`type`in n))try{Object.defineProperty(n,"type",{configurable:!0,enumerable:!0,value:e})}catch{return super.emit(e,{type:e,...n},...r)}return super.emit(e,n,...r)}addEventListener=(e,t,n)=>{if(typeof n==`object`&&n?.once){this.once(e,t);return}this.addListener(e,t)};removeEventListener=(e,t)=>{this.removeListener(e,t)};dispatchEvent=e=>this.emit(e.type,e)},GF=Bk(`werift:packages/webrtc/src/dataChannel.ts`);function KF(e){return Buffer.isBuffer(e)?e.length:Buffer.byteLength(e)}var qF=class extends WF{constructor(e,t,n=!0){if(super(),this.sctp=e,this.parameters=t,this.sendOpen=n,this.id=this.parameters.id,t.negotiated){if(this.id==null||this.id<0||this.id>65534)throw Error(`ID must be in range 0-65534 if data channel is negotiated out-of-band`);this.sctp.dataChannelAddNegotiated(this)}else n&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}statsId=l().toString();stateChange=new $;stateChanged=new $;onMessage=new $;error=new $;bufferedAmountLow=new $;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??null}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime??null}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(e){if(e<0||e>4294967295)throw Error(`bufferedAmountLowThreshold must be in range 0 - 4294967295`);this._bufferedAmountLowThreshold=e}setId(e){this.id=e}setReadyState(e){if(e!==this.readyState){switch(this.readyState=e,this.stateChange.execute(e),this.stateChanged.execute(e),e){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()}GF(`change state`,e)}}addBufferedAmount(e){let t=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+e<=this.bufferedAmountLowThreshold;this.bufferedAmount+=e,t&&(this.bufferedAmountLow.execute(),this.emit(`bufferedamountlow`))}send(e){let t=this.sctp.datachannelSend(this,e);this.messagesSent++,this.bytesSent+=t}close(){this.sctp.dataChannelClose(this)}},JF=class{label=``;maxPacketLifeTime;maxRetransmits;ordered=!0;protocol=``;negotiated=!1;id;constructor(e={}){Object.assign(this,e)}},YF=()=>({type:`nack`}),XF=()=>({type:`nack`,parameter:`pli`}),ZF=()=>({type:`goog-remb`}),QF=()=>({type:`transport-cc`}),$F=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction=`all`;constructor(e){Object.assign(this,e)}get name(){return this.mimeType.split(`/`)[1]}get contentType(){return this.mimeType.split(`/`)[0]}get str(){let e=`${this.name}/${this.clockRate}`;return this.channels===2&&(e+=`/2`),e}},eI=class{id;uri;constructor(e){Object.assign(this,e)}},tI=class{type;parameter;constructor(e={}){Object.assign(this,e)}},nI=class{ssrc;constructor(e={}){Object.assign(this,e)}},rI=class{ssrc;payloadType;rtx;constructor(e){Object.assign(this,e)}},iI=class{rid;direction;constructor(e){Object.assign(this,e)}},aI=(e={})=>new $F({mimeType:`video/h264`,clockRate:9e4,rtcpFeedback:[YF(),XF(),ZF()],parameters:`profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1`,...e}),oI=(e={})=>new $F({mimeType:`video/VP8`,clockRate:9e4,rtcpFeedback:[YF(),XF(),ZF()],...e}),sI=(e={})=>new $F({mimeType:`video/VP9`,clockRate:9e4,rtcpFeedback:[YF(),XF(),ZF()],...e}),cI=(e={})=>new $F({mimeType:`video/AV1X`,clockRate:9e4,rtcpFeedback:[YF(),XF(),ZF()],...e}),lI=(e={})=>new $F({mimeType:`audio/OPUS`,clockRate:48e3,channels:2,...e}),uI=(e={})=>new $F({mimeType:`audio/PCMU`,clockRate:8e3,channels:1,payloadType:0,...e}),dI=[cI(),sI(),oI(),aI(),lI(),uI()].map(e=>e.mimeType);dI.filter(e=>e.toLowerCase().startsWith(`video/`)),dI.filter(e=>e.toLowerCase().startsWith(`audio/`));var fI=2,pI=3,mI=0,hI=50,gI=51,_I=53,vI=56,yI=57,bI=`0.0.0.0`,xI=9,SI={auto:`actpass`,client:`active`,server:`passive`},CI=Object.keys(SI).reduce((e,t)=>{let n=SI[t];return e[n]=t,e},{}),wI=[`apt`,`max-fr`,`max-fs`,`maxplaybackrate`,`minptime`,`stereo`,`useinbandfec`],TI=[`cname`,`msid`,`mslabel`,`label`],EI={SRTP_AES128_CM_HMAC_SHA1_80:1,SRTP_AEAD_AES_128_GCM:7},DI=[`sendonly`,`sendrecv`],OI=[`sendrecv`,`recvonly`],kI=class extends Map{constructor(e){if(super(),e)for(let t of e)this.set(t.id,t)}};function AI(e,...t){return`${e}_${t.filter(e=>e!==void 0).join(`_`)}`}function jI(e,t,n){return AI(`codec`,e,t,n)}function MI(){return performance.timeOrigin+performance.now()}function NI(e){let t=[];for(let[n,r]of Object.entries(e))if(n!==`id`){if(n.endsWith(`Id`)){typeof r==`string`&&t.push(r);continue}if(n.endsWith(`Ids`)&&Array.isArray(r))for(let e of r)typeof e==`string`&&t.push(e)}return t}function PI(e,t){let n=new Map;for(let t of e)n.set(t.id,t);if(!t)return new kI([...n.values()]);let r=new Set,i=[...new Set(Array.from(t))];for(;i.length>0;){let e=i.shift();if(!e||r.has(e))continue;let t=n.get(e);t&&(r.add(e),i.push(...NI(t)))}return new kI([...r].map(e=>n.get(e)).filter(e=>!!e))}var FI=class{constructor(e,t,n,r,i){this.kind=e,this.receiver=n,this.sender=r,this._direction=i,t&&this.setDtlsTransport(t)}id=l().toString();onTrack=new $;mid=null;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(e){this._codecs=e}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}set direction(e){this.setDirection(e)}setDirection(e){this._direction=e,this._currentDirection&&this._currentDirection!==`stopped`&&DI.includes(this._currentDirection)&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection??null}setCurrentDirection(e){this._currentDirection=e}setDtlsTransport(e){this.receiver.setDtlsTransport(e),this.sender.setDtlsTransport(e)}get msid(){return this.msids[0]}get msids(){return this.sender.streamIds.map(e=>`${e} ${this.sender.trackId}`)}addTrack(e){this.receiver.addTrack(e)&&this.onTrack.execute(e,this)}stop(){this.stopping||=!0}forceStop(){this.stopped||(this.stopping=!0,this.stopped=!0,this.setCurrentDirection(`stopped`),this.receiver.stop(),this.sender.stop())}getPayloadType(e){return this.codecs.find(t=>t.mimeType.toLowerCase().includes(e.toLowerCase()))?.payloadType}getCodecStats(){let e=MI();return this.collectCodecStats(e)}collectCodecStats(e){let t=[];if(!this.dtlsTransport)return t;let n=AI(`transport`,this.dtlsTransport.id);for(let r of this.codecs){let i={type:`codec`,id:jI(n,r.payloadType,this.id),timestamp:e,payloadType:r.payloadType,transportId:n,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,sdpFmtpLine:r.parameters};t.push(i)}return t}},II=[`inactive`,`sendonly`,`recvonly`,`sendrecv`],LI=class extends WF{uuid=l().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new $;onReceiveRtcp=new $;onSourceChanged=new $;stopped=!1;muted=!0;constructor(e){super(),Object.assign(this,e),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=e=>{if(this.remote)throw Error(`this is remoteTrack`);if(this.stopped)return;let t=Buffer.isBuffer(e)?PM.deSerialize(e):e;t.header.payloadType=this.codec?.payloadType??t.header.payloadType,this.onReceiveRtp.execute(t)}},RI=class{id;tracks=[];constructor(e={}){Array.isArray(e)?this.tracks=e:Object.assign(this,e),this.id??=l().toString()}addTrack(e){e.streamId=this.id,this.tracks.push(e)}removeTrack(e){this.tracks=this.tracks.filter(t=>t!==e),e.streamId===this.id&&(e.streamId=void 0)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(e=>e.kind===`audio`)}getVideoTracks(){return this.tracks.filter(e=>e.kind===`video`)}},zI=Bk(`werift:packages/webrtc/src/utils.ts`);function BI(e,t){return(e=>e.match(/(.{2})/g).join(`:`))((e=>e.toUpperCase())(a(t).update(e).digest(`hex`)))}var VI={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`};function HI(e){return VI[e.trim().toLowerCase()]}function UI(e){return e.replace(/[^0-9a-f]/gi,``).toLowerCase()}function WI(e){let t=e[0];return t>19&&t<64}var GI=(e,t)=>II[II.indexOf(e)&II.indexOf(t)];function KI(e){return e===`sendonly`?`recvonly`:e===`recvonly`?`sendonly`:e}var qI=Date.now,JI=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,YI=()=>JI+process.hrtime.bigint()/1000n,XI=()=>Date.now()/1e3,ZI=()=>{let[e,t]=((A.timeOrigin+A.now()-Date.UTC(1900,0,1))/1e3).toString().split(`.`).map(Number);return fk([4,4],[e,t]).readBigUInt64BE()},QI=e=>{let[t,n]=mk(fk([8],[e]),[4,4]);return t*1e3+n+Date.UTC(1900,0,1)},$I=e=>{let[,t,n]=mk(fk([8],[e]),[2,2,2,2]);return fk([2,2],[t,n]).readUInt32BE()};function eL(e){let t={};for(let n of e){let e=Array.isArray(n.urls)?n.urls:[n.urls];for(let r of e){let e=nL(r);e&&(!t.stunServer&&e.kind===`stun`&&(t.stunServer=e.address),!t.turnServer&&e.kind===`turn`&&(t.turnServer=e.address,t.turnTransport=e.transport,t.turnUsername=n.username,t.turnPassword=n.credential))}}return zI(`iceOptions`,t),t}function tL({configuredTurnTransport:e,forceTurnTCP:t,parsedTurnTransport:n}){if(n)return n;if(e)return e;if(t)return`tcp`}function nL(e){let t=/^(stun|stuns|turn|turns):(.+)$/i.exec(e.trim());if(!t)return;let[,n,r]=t,i=n.toLowerCase(),[a]=r.split(`?`,1),[,o=``]=r.split(`?`),s=aL(a,iL(i));if(!s)return;if(i===`stun`||i===`stuns`)return{kind:`stun`,address:s};let c=rL({scheme:i,transportParam:new URLSearchParams(o).get(`transport`)});if(c!==`invalid`)return{kind:`turn`,address:s,transport:c}}function rL({scheme:e,transportParam:t}){return t==null?e===`turns`?`tls`:void 0:t===`udp`?e===`turns`?`invalid`:`udp`:t===`tcp`?e===`turns`?`tls`:`tcp`:`invalid`}function iL(e){return e===`stuns`||e===`turns`?5349:3478}function aL(e,t){let n=e.startsWith(`//`)?e.slice(2):e;if(!n)return;if(n.startsWith(`[`)){let e=n.indexOf(`]`);return e===-1?void 0:[n.slice(1,e),oL(n.slice(e+1),t)]}let r=n.indexOf(`:`),i=n.lastIndexOf(`:`);return r!==-1&&r===i?[n.slice(0,r),oL(n.slice(r+1),t)]:[n,t]}function oL(e,t){let n=e.startsWith(`:`)?e.slice(1):e,r=Number.parseInt(n,10);return Number.isFinite(r)?r:t}yA.createSelfSignedCertificateWithKey;var sL=(e,t)=>{if(!e||typeof e!=`object`)return typeof t==`object`&&t?t:e;if(!t||typeof t!=`object`)return t??e;for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];r!=null&&(e[n]=r)}return e},cL=Bk(`werift:packages/webrtc/src/media/receiver/nack.ts`),lL=150,uL=class{constructor(e){this.receiver=e}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new $;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(e){return this._lost[e]}setLost(e,t){this._lost[e]=t,!(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(e){cL(`failed to send nack`,e)}},5))}removeLost(e){delete this._lost[e]}addPacket(e){let{sequenceNumber:t,ssrc:n}=e.header;if(this.mediaSourceSsrc=n,this.newEstSeqNum===0){this.newEstSeqNum=t;return}if(this.getLost(t)){this.removeLost(t);return}if(t===Ak(this.newEstSeqNum,1))this.newEstSeqNum=t;else if(t>Ak(this.newEstSeqNum,1)){for(let e=Ak(this.newEstSeqNum,1);e<t;e=Ak(e,1))this.setLost(e,1);this.newEstSeqNum=t,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>lL&&(this._lost=Object.entries(this._lost).slice(-lL).reduce((e,[t,n])=>(e[t]=n,e),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(e=>{if(this._lost[e]++>this.retryCount)return this.removeLost(e),e})}sendNack=()=>new Promise((e,t)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let n=new Wj({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),r=new Qj({feedback:n});this.receiver.dtlsTransport.sendRtcp([r]).then(e).catch(t),this.updateRetryCount(),this.onPacketLost.execute(n)}})},dL=Bk(`werift:packages/webrtc/media/receiver/receiverTwcc`),fL=class{constructor(e,t,n){this.dtlsTransport=e,this.rtcpSsrc=t,this.mediaSourceSsrc=n,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(e){this.extensionInfo[e]={tsn:e,timestamp:YI()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await E(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let e=Object.values(this.extensionInfo).sort((e,t)=>e.tsn-t.tsn),t=e[0].tsn,n=e.slice(-1)[0].tsn,r=[],i=e[0].tsn,a=Ak(n-t,1),o,s,c=[];for(let e=t;e<=n;e++){let t=this.extensionInfo[e]?.timestamp;if(t){this.lastTimestamp||=t,o||=this.lastTimestamp;let i=t-this.lastTimestamp;this.lastTimestamp=t;let a=new Yj({delta:Number(i)});a.parseDelta(),c.push(a),s!=null&&s.status!==a.type&&(r.push(new qj({packetStatus:s.status,runLength:e-s.minTSN})),s={minTSN:e,status:a.type}),e===n&&(s==null?r.push(new qj({packetStatus:a.type,runLength:1})):r.push(new qj({packetStatus:s.status,runLength:e-s.minTSN+1}))),s??={minTSN:e,status:a.type}}}if(!o)return;let l=new Qj({feedback:new Kj({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:i,packetStatusCount:a,referenceTime:Mk(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:r})});this.dtlsTransport.sendRtcp([l]).catch(e=>{dL(e)}),this.extensionInfo={},this.fbPktCount=kk(this.fbPktCount,1)}},pL=class{base_seq;max_seq;cycles=0;packets_received=0;bytesReceived=0;headerBytesReceived=0;lastPacketReceivedTimestamp;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(e){this.clockRate=e}add(e,t=Date.now()/1e3){let n=this.max_seq==null||Nk(e.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.bytesReceived+=e.payload.length,this.headerBytesReceived+=e.header.serializeSize,this.lastPacketReceivedTimestamp=MI(),this.base_seq??=e.header.sequenceNumber,n){let n=Ik(t*this.clockRate);if(this.max_seq!=null&&e.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=e.header.sequenceNumber,e.header.timestamp!==this.last_timestamp&&this.packets_received>1){let t=Math.abs(n-(this.last_arrival??0)-(e.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=t-(this.jitter_q4+8>>4)}this.last_arrival=n,this.last_timestamp=e.header.timestamp}}get fraction_lost(){let e=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let t=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let n=e-t;return e==0||n<=0?0:Math.floor((n<<8)/e)}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 e=this.packets_expected-this.packets_received;return e<0?0:e}},mL=Bk(`werift:packages/webrtc/src/transport/dtls.ts`);function hL(e){if(e){if(e.major===254&&e.minor===253)return`DTLS 1.2`;if(e.major===254&&e.minor===255)return`DTLS 1.0`}}function gL(e){switch(e){case 1:return`AES_CM_128_HMAC_SHA1_80`;case 7:return`AEAD_AES_128_GCM`;default:return}}var _L=class e{constructor(t,n,r,i=[]){this.config=t,this.iceTransport=n,this.localCertificate=r,this.srtpProfiles=i,this.localCertificate??=e.localCertificate}id=l().toString();state=`new`;role=`auto`;srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new $;onRtcp=new $;onRtp=new $;events=new WF;onstatechange;static localCertificate;static localCertificatePromise;remoteParameters;addEventListener=(e,t,n)=>{this.events.addEventListener(e,t,n)};removeEventListener=(e,t)=>{this.events.removeEventListener(e,t)};dispatchEvent=e=>this.events.dispatchEvent(e);get localParameters(){return new bL(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){return this.localCertificate?this.localCertificate:(this.localCertificatePromise||=(async()=>{let{certPem:e,keyPem:t,signatureHash:n}=await yA.createSelfSignedCertificateWithKey({signature:qk.ecdsa_3,hash:Jk.sha256_4},Zk.secp256r1_23);return this.localCertificate=new vL(t,e,n),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let t=xL([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),n=e.role===`auto`&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new bL(t,n)}async start(){if(this.state!==`new`)throw Error(`state must be new`);if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw Error(`remote fingerprint not exist`);this.role===`auto`&&(this.role=this.iceTransport.role===`controlling`?`server`:`client`),this.setState(`connecting`),await new Promise(async(e,t)=>{this.dtls=this.role===`server`?new IN({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:TL(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):new DN({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:TL(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0}),this.dtls.onData.subscribe(e=>{this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random()||this.dataReceiver(e)}),this.dtls.onClose.subscribe(()=>{this.state!==`failed`&&this.setState(`closed`)}),this.dtls.onConnect.once(e),this.dtls.onError.once(e=>{this.setState(`failed`),mL(`dtls failed`,e),t(e)}),this.dtls instanceof DN&&(await E(100),this.dtls.connect().catch(e=>{this.setState(`failed`),mL(`dtls connect failed`,e),t(e)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState(`failed`),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState(`connected`),mL(`dtls connected`)}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw Error(`remote fingerprint not exist`);let e=this.dtls?.remoteCertificate;if(!e)throw Error(`remote certificate not available`);let t=this.remoteParameters.fingerprints.flatMap(({algorithm:e,value:t})=>{let n=HI(e);if(!n)return[];let r=UI(t);if(!r)throw Error(`remote fingerprint value is empty`);return[{normalizedAlgorithm:n,normalizedValue:r}]});if(t.length===0)throw Error(`no supported remote fingerprint algorithms`);let n=CL(t),r=t.filter(({normalizedAlgorithm:e})=>e===n),i=r.reduce((t,{normalizedAlgorithm:n})=>(t.has(n)||t.set(n,UI(BI(e,n))),t),new Map);if(!r.some(({normalizedAlgorithm:e,normalizedValue:t})=>i.get(e)===t))throw Error(`remote certificate fingerprint mismatch`)}updateSrtpSession(){if(!this.dtls)throw Error();let e=this.dtls.srtp.srtpProfile;if(!e)throw Error(`need srtpProfile`);mL(`selected SRTP Profile`,e);let{localKey:t,localSalt:n,remoteKey:r,remoteSalt:i}=this.dtls.extractSessionKeys(Aj(e),jj(e)),a={keys:{localMasterKey:t,localMasterSalt:n,remoteMasterKey:r,remoteMasterSalt:i},profile:e};this.srtp=new cN(a),this.srtcp=new oN(a)}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())&&Pj(e)){if(this.bytesReceived+=e.length,this.packetsReceived++,cM(e)){let t;try{t=this.srtcp.decrypt(e)}catch(e){if(e instanceof RM){mL(`dropping invalid SRTCP packet`,e);return}throw e}let n;try{n=sM.deSerialize(t)}catch(e){mL(`dropping malformed SRTCP packet`,e);return}for(let e of n)try{this.onRtcp.execute(e)}catch(e){mL(`RTCP error`,e)}}else{let t;try{t=this.srtp.decrypt(e)}catch(e){if(e instanceof RM){mL(`dropping invalid SRTP packet`,e);return}throw e}let n;try{n=PM.deSerialize(t)}catch(e){mL(`dropping malformed SRTP packet`,e);return}try{this.onRtp.execute(n)}catch(e){mL(`RTP error`,e)}}}}))}sendData=async e=>{if(!(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random())){if(!this.dtls)throw Error(`dtls not established`);await this.dtls.send(e)}};async sendRtp(e,t){try{let n=this.srtp.encrypt(e,t);return this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random()?n.length:(this.bytesSent+=n.length,this.packetsSent++,await this.iceTransport.connection.send(n).catch(()=>{}),n.length)}catch(e){return mL(`failed to send`,e),0}}async sendRtcp(e){let t=Buffer.concat(e.map(e=>e.serialize())),n=this.srtcp.encrypt(t);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,t=!0){e!=this.state&&(this.state=e,this.onStateChange.execute(e),t&&(this.onstatechange?.(),this.events.emit(`statechange`)))}async stop(){this.setState(`closed`,!1),await this.iceTransport.stop()}async getStats(e=MI()){let t=[],n=AI(`transport`,this.id),r={type:`transport`,id:n,timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,iceRole:this.iceTransport.role===`unknown`?void 0:this.iceTransport.role,iceLocalUsernameFragment:this.iceTransport.localParameters.usernameFragment,selectedCandidatePairId:this.iceTransport.connection.nominated?AI(`candidate-pair`,this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?AI(`certificate`,this.id,`local`):void 0,remoteCertificateId:this.dtls?.remoteCertificate?AI(`certificate`,this.id,`remote`):void 0,dtlsRole:this.role===`auto`?void 0:this.role,tlsVersion:hL(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:gL(this.dtls?.srtp.srtpProfile),iceRestarts:this.iceTransport.iceRestarts};if(t.push(r),this.localCertificate){let n=this.localCertificate.getFingerprints();if(n.length>0){let r={type:`certificate`,id:AI(`certificate`,this.id,`local`),timestamp:e,fingerprint:n[0].value,fingerprintAlgorithm:n[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString(`base64`)};t.push(r)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0&&this.dtls?.remoteCertificate){let n={type:`certificate`,id:AI(`certificate`,this.id,`remote`),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:Buffer.from(this.dtls.remoteCertificate).toString(`base64`)};t.push(n)}let i=await this.iceTransport.getStats(e,n);return t.push(...i),t}},vL=class{constructor(e,t,n){this.certPem=t,this.signatureHash=n;let r=Gd.Certificate.fromPEM(Buffer.from(t));this.publicKey=r.publicKey.toPEM(),this.privateKey=Gd.PrivateKey.fromPEM(Buffer.from(e)).toPEM()}publicKey;privateKey;getFingerprints(){return[new yL(`sha-256`,BI(Gd.Certificate.fromPEM(Buffer.from(this.certPem)).raw,`sha256`))]}},yL=class{constructor(e,t){this.algorithm=e,this.value=t}},bL=class{constructor(e=[],t){this.fingerprints=e,this.role=t}},xL=e=>{let t=new Set;return e.filter(({algorithm:e,value:n})=>{let r=`${HI(e)??e.trim().toLowerCase()}:${UI(n)}`;return!t.has(r)&&(t.add(r),!0)})},SL=[`sha512`,`sha384`,`sha256`,`sha224`,`sha1`],CL=e=>SL.find(t=>e.some(({normalizedAlgorithm:e})=>e===t))??e[0].normalizedAlgorithm,wL=class{constructor(e){this.ice=e,e.onData.subscribe(e=>{WI(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type=`ice`;send=e=>this.ice.send(e);async close(){this.closed=!0,this.ice.close()}},TL=e=>new wL(e),EL=Bk(`werift:packages/webrtc/src/transport/ice.ts`);function DL(e){switch(e){case 0:return`frozen`;case 1:return`waiting`;case 2:return`in-progress`;case 3:return`succeeded`;case 4:return`failed`;default:return`failed`}}var OL=class{constructor(e){this.iceGather=e,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)},this.iceGather.onGatheringStateChange.subscribe(()=>{this.ongatheringstatechange?.(),this.events.emit(`gatheringstatechange`)})}id=l().toString();connection;state=`new`;component=`rtp`;iceRestarts=0;waitStart;renominating=!1;events=new WF;onstatechange;ongatheringstatechange;onStateChange=new $;onIceCandidate=new $;onNegotiationNeeded=new $;addEventListener=(e,t,n)=>{this.events.addEventListener(e,t,n)};removeEventListener=(e,t)=>{this.events.removeEventListener(e,t)};dispatchEvent=e=>this.events.dispatchEvent(e);get role(){return!this.connection.remoteUsername||!this.connection.remotePassword?`unknown`:this.connection.iceControlling?`controlling`:`controlled`}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}getRemoteCandidates(){return this.connection.remoteCandidates.filter(e=>e.type!==`prflx`).map(e=>AL(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>AL(e).toJSON())}getSelectedCandidatePair(){let e=this.connection.candidatePairs.find(e=>e.nominated)??this.connection.candidatePairs.find(e=>e.state===3);return e?{local:AL(e.localCandidate).toJSON(),remote:AL(e.remoteCandidate).toJSON()}:null}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){return!this.connection.remoteUsername||!this.connection.remotePassword?null:new PL({iceLite:this.connection.remoteIsLite,password:this.connection.remotePassword,usernameFragment:this.connection.remoteUsername})}setState(e,t=!0){e!==this.state&&(this.state=e,this.onStateChange.execute(e),t&&(this.onstatechange?.(),this.events.emit(`statechange`)))}gather(){return this.iceGather.gather()}addRemoteCandidate=e=>{if(!this.connection.remoteCandidatesEnd)return e?this.connection.addRemoteCandidate(jL(e)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(e,t=!1){t&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==e.usernameFragment||this.connection.remotePassword!==e.password)&&(this.renominating?(EL(`renomination`,e),this.connection.resetNominatedPair(),this.renominating=!1):(EL(`restart`,e),this.restart())),this.connection.setRemoteParams(e)}restart(){this.iceRestarts++,this.connection.restart(),this.setState(`new`),this.iceGather.gatheringState=`new`,this.waitStart=void 0,this.onNegotiationNeeded.execute()}async start(){if(this.state===`closed`)throw Error(`RTCIceTransport is closed`);if(!this.connection.remotePassword||!this.connection.remoteUsername)throw Error(`remoteParams missing`);this.waitStart&&await this.waitStart.asPromise(),this.waitStart=new $,this.setState(`checking`);try{await this.connection.connect()}catch(e){throw this.setState(`failed`),e}this.waitStart.execute(),this.waitStart.complete(),this.waitStart=void 0}async stop(){this.state!==`closed`&&(this.setState(`closed`,!1),await this.connection.close()),this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(e=MI(),t=AI(`transport`,this.id)){let n=[];for(let r of this.connection.localCandidates){let i={type:`local-candidate`,id:AI(`local-candidate`,r.id),timestamp:e,transportId:t,address:r.host,port:r.port,protocol:r.transport,candidateType:r.type,priority:r.priority,foundation:r.foundation,relatedAddress:r.relatedAddress,relatedPort:r.relatedPort,usernameFragment:r.ufrag,tcpType:r.tcptype};n.push(i)}for(let r of this.connection.remoteCandidates){let i={type:`remote-candidate`,id:AI(`remote-candidate`,r.id),timestamp:e,transportId:t,address:r.host,port:r.port,protocol:r.transport,candidateType:r.type,priority:r.priority,foundation:r.foundation,relatedAddress:r.relatedAddress,relatedPort:r.relatedPort,usernameFragment:r.ufrag,tcpType:r.tcptype};n.push(i)}let r=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(e=>e.nominated),...this.connection.candidatePairs.filter(e=>!e.nominated)]:[];for(let i of r){let r={type:`candidate-pair`,id:AI(`candidate-pair`,i.id),timestamp:e,transportId:t,localCandidateId:AI(`local-candidate`,i.localCandidate.id),remoteCandidateId:AI(`remote-candidate`,i.remoteCandidate.id),state:DL(i.state),nominated:i.nominated,packetsSent:i.packetsSent,packetsReceived:i.packetsReceived,bytesSent:i.bytesSent,bytesReceived:i.bytesReceived,currentRoundTripTime:i.rtt,totalRoundTripTime:i.totalRoundTripTime,roundTripTimeMeasurements:i.roundTripTimeMeasurements,requestsReceived:i.requestsReceived,requestsSent:i.requestsSent,responsesReceived:i.responsesReceived,responsesSent:i.responsesSent,retransmissionsReceived:i.retransmissionsReceived,retransmissionsSent:i.retransmissionsSent,consentRequestsSent:i.consentRequestsSent};n.push(r)}return n}},kL=class{constructor(e={}){this.options=e,this.connection=new zF(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(AL(e))})}onIceCandidate=()=>{};gatheringState=`new`;connection;onGatheringStateChange=new $;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(AL)}get localParameters(){return new PL({iceLite:this.connection.iceLite,usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(e){e!==this.gatheringState&&(this.gatheringState=e,this.onGatheringStateChange.execute(e))}};function AL(e){let t=new NL(e.component,e.foundation,e.host,e.port,e.priority,e.transport,e.type,e.generation,e.ufrag);return t.relatedAddress=e.relatedAddress,t.relatedPort=e.relatedPort,t.tcpType=e.tcptype,t}function jL(e){return new lF(e.foundation,e.component,e.protocol,e.priority,e.ip,e.port,e.type,e.relatedAddress,e.relatedPort,e.tcpType,e.generation,e.ufrag)}var ML=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(e){Object.assign(this,e)}static fromSdp(e){return AL(lF.fromSdp(e)).toJSON()}static isThis(e){if(typeof e?.candidate==`string`)return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},NL=class{constructor(e,t,n,r,i,a,o,s,c){this.component=e,this.foundation=t,this.ip=n,this.port=r,this.priority=i,this.protocol=a,this.type=o,this.generation=s,this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new ML({candidate:ZR(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate)throw Error(`candidate is required`);let t=tz(e.candidate.startsWith(`candidate:`)?e.candidate.slice(10):e.candidate);return t.sdpMLineIndex=e.sdpMLineIndex??void 0,t.sdpMid=e.sdpMid??void 0,t}catch{}}},PL=class{iceLite=!1;usernameFragment;password;constructor(e={}){Object.assign(this,e)}},FL=class e{constructor(e=0,t=Buffer.from(``)){this.flags=e,this._body=t}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return e.type}get bytes(){if(!this.body)throw 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(tR(this.body.length))].map(()=>Buffer.from(`\0`))])}},IL=class extends FL{constructor(e=0,t){super(e,t),this.flags=e,t?(this.initiateTag=t.readUInt32BE(0),this.advertisedRwnd=t.readUInt32BE(4),this.outboundStreams=t.readUInt16BE(8),this.inboundStreams=t.readUInt16BE(10),this.initialTsn=t.readUInt32BE(12),this.params=rR(t.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 e=Buffer.alloc(16);return e.writeUInt32BE(this.initiateTag,0),e.writeUInt32BE(this.advertisedRwnd,4),e.writeUInt16BE(this.outboundStreams,8),e.writeUInt16BE(this.inboundStreams,10),e.writeUInt32BE(this.initialTsn,12),Buffer.concat([e,nR(this.params)])}},LL=class e extends IL{static type=1;get type(){return e.type}},RL=class e extends IL{static type=2;get type(){return e.type}},zL=class e extends IL{static type=130;get type(){return e.type}},BL=class e extends FL{constructor(e=0,t){if(super(e,t),this.flags=e,t){this.cumulativeTsn=t.readUInt32BE(0);let e=4;for(;e<t.length;)this.streams.push([t.readUInt16BE(e),t.readUInt16BE(e+2)]),e+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return e.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([e,t])=>{let n=Buffer.alloc(4);return n.writeUInt16BE(e,0),n.writeUInt16BE(t,2),n})])}},VL=class e extends FL{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.tsn=t.readUInt32BE(0),this.streamId=t.readUInt16BE(4),this.streamSeqNum=t.readUInt16BE(6),this.protocol=t.readUInt32BE(8),this.userData=t.slice(12))}static type=0;get type(){return e.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,t=Buffer.alloc(16);t.writeUInt8(this.type,0),t.writeUInt8(this.flags,1),t.writeUInt16BE(e,2),t.writeUInt32BE(this.tsn,4),t.writeUInt16BE(this.streamId,8),t.writeUInt16BE(this.streamSeqNum,10),t.writeUInt32BE(this.protocol,12);let n=Buffer.concat([t,this.userData]);return e%4&&(n=Buffer.concat([n,...[...Array(tR(e))].map(()=>Buffer.from(`\0`))])),n}},HL=class e extends FL{static type=10;get type(){return e.type}},UL=class e extends FL{static type=11;get type(){return e.type}},WL=class extends FL{constructor(e=0,t=void 0){super(e,t),this.flags=e,t&&(this.params=rR(t))}params=[];get body(){return nR(this.params)}},GL=class e extends WL{static type=6;get type(){return e.type}},KL=class e extends WL{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 e.type}get descriptions(){return this.params.map(([t,n])=>({name:(Object.entries(e.CODE).find(([,e])=>e===t)||[])[0],body:n}))}},qL=class e extends WL{static type=4;get type(){return e.type}},JL=class e extends WL{static type=5;get type(){return e.type}},YL=class e extends WL{static type=130;get type(){return e.type}},XL=class e extends FL{constructor(e=0,t){if(super(e,t),this.flags=e,t){this.cumulativeTsn=t.readUInt32BE(0),this.advertisedRwnd=t.readUInt32BE(4);let e=t.readUInt16BE(8),n=t.readUInt16BE(10),r=12;[...Array(e)].forEach(()=>{this.gaps.push([t.readUInt16BE(r),t.readUInt16BE(r+2)]),r+=4}),[...Array(n)].forEach(()=>{this.duplicates.push(t.readUInt32BE(r)),r+=4})}}static type=3;get type(){return e.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),t=Buffer.alloc(16);t.writeUInt8(this.type,0),t.writeUInt8(this.flags,1),t.writeUInt16BE(e,2),t.writeUInt32BE(this.cumulativeTsn,4),t.writeUInt32BE(this.advertisedRwnd,8),t.writeUInt16BE(this.gaps.length,12),t.writeUInt16BE(this.duplicates.length,14);let n=Buffer.concat([t,...this.gaps.map(e=>{let t=Buffer.alloc(4);return t.writeUInt16BE(e[0],0),t.writeUInt16BE(e[1],2),t})]);return n=Buffer.concat([n,...this.duplicates.map(e=>{let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t})]),n}},ZL=class e extends FL{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.cumulativeTsn=t.readUInt32BE(0))}static type=7;get type(){return e.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},QL=class e extends FL{static type=8;get type(){return e.type}},$L=class e extends FL{static type=14;get type(){return e.type}},eR=[VL,LL,RL,XL,qL,JL,GL,ZL,QL,KL,HL,UL,$L,YL,BL].reduce((e,t)=>(e[t.type]=t,e),{});function tR(e){let t=e%4;return t?4-t:0}function nR(e){let t=Buffer.from(``),n=Buffer.from(``);return e.forEach(([e,r])=>{let i=r.length+4,a=Buffer.alloc(4);a.writeUInt16BE(e,0),a.writeUInt16BE(i,2),t=Buffer.concat([t,n,a,r]),n=Buffer.concat([...Array(tR(i))].map(()=>Buffer.from(`\0`)))}),t}function rR(e){let t=[],n=0;for(;n<=e.length-4;){let r=e.readUInt16BE(n),i=e.readUInt16BE(n+2);t.push([r,e.slice(n+4,n+i)]),n+=i+tR(i)}return t}function iR(e){if(e.length<12)throw Error(`SCTP packet length is less than 12 bytes`);let t=e.readUInt16BE(0),n=e.readUInt16BE(2),r=e.readUInt32BE(4);if(e.readUInt32LE(8)!==Ok(Buffer.concat([e.slice(0,8),Buffer.from(`\0\0\0\0`),e.slice(12)])))throw Error(`SCTP packet has invalid checksum`);let i=[],a=12;for(;a+4<=e.length;){let t=e.readUInt8(a),n=e.readUInt8(a+1),r=e.readUInt16BE(a+2),o=e.slice(a+4,a+r),s=eR[t.toString()];if(s)i.push(new s(n,o));else throw Error(`unknown`);a+=r+tR(r)}return[t,n,r,i]}function aR(e,t,n,r){let i=Buffer.alloc(8);i.writeUInt16BE(e,0),i.writeUInt16BE(t,2),i.writeUInt32BE(n,4);let a=r.bytes,o=Ok(Buffer.concat([i,Buffer.from(`\0\0\0\0`),a])),s=Buffer.alloc(4);return s.writeUInt32LE(o,0),Buffer.concat([i,s,a])}function oR(e){return e.map((e,t)=>[t,e])}function sR(e){return e.reduce((e,t)=>(e[t]=new $,e),{})}var cR=class e{constructor(e,t,n,r){this.requestSequence=e,this.responseSequence=t,this.lastTsn=n,this.streams=r}static type=13;get type(){return e.type}get bytes(){let e=Buffer.allocUnsafe(12);return e.writeUInt32BE(this.requestSequence,0),e.writeUInt32BE(this.responseSequence,4),e.writeUInt32BE(this.lastTsn,8),Buffer.concat([e,...this.streams.map(e=>{let t=Buffer.allocUnsafe(2);return t.writeUInt16BE(e,0),t})])}static parse(t){let n=t.readUInt32BE(0),r=t.readUInt32BE(4),i=t.readUInt32BE(8),a=[];for(let e=12;e<t.length;e+=2)a.push(t.readUInt16BE(e));return new e(n,r,i,a)}},lR=class e{constructor(e,t){this.requestSequence=e,this.newStreams=t}static type=17;get type(){return e.type}get bytes(){let e=Buffer.allocUnsafe(8);return e.writeUInt32BE(this.requestSequence,0),e.writeUInt16BE(this.newStreams,4),e.writeUInt16BE(0,6),e}static parse(t){let n=t.readUInt32BE(0),r=t.readUInt16BE(4);return new e(n,r)}},uR={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},dR=class e{constructor(e,t){this.responseSequence=e,this.result=t}static type=16;get type(){return e.type}get bytes(){let e=Buffer.allocUnsafe(8);return e.writeUInt32BE(this.responseSequence,0),e.writeUInt32BE(this.result,4),e}static parse(t){let n=t.readUInt32BE(0),r=t.readUInt32BE(4);return new e(n,r)}},fR={13:cR,16:dR,17:lR},pR=Bk(`werift/sctp/sctp`),mR=24,hR=60,gR=65535,_R=1200,vR=1,yR=2,bR=4,xR=10,SR=8,CR=1/8,wR=1/4,TR=3,ER=1,DR=60,OR=2**32,kR=200,AR=30,jR=135,MR=7,NR=32776,PR=49152,FR=[`new`,`closed`,`connected`,`connecting`],IR=class e{constructor(e,t=5e3){this.transport=e,this.port=t,this.localPort=this.port,this.transport.onData=e=>{this.handleData(e)}}flush=new $;stateChanged=sR(FR);onReconfigStreams=new $;onReceive=new $;onSackReceived=async()=>{};associationState=1;started=!1;state=`new`;isServer=!0;isStopping=!1;isClosed=!1;hmacKey=c(16);localPartialReliability=!0;localPort;localVerificationTag=ck();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1048576;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=gR;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*_R;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=gR;localTsn=Number(ck());lastSackedTsn=zR(this.localTsn);advancedPeerAckTsn=zR(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=TR;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=AR;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(t,n=5e3){let r=new e(t,n);return r.isServer=!1,r}static server(t,n=5e3){let r=new e(t,n);return r.isServer=!0,r}async handleData(e){if(this.isStopped)return;let t,[,,n,r]=iR(e);if(r.filter(e=>e.type===LL.type).length>0){if(r.length!=1)throw Error();t=0}else t=this.localVerificationTag;if(n===t){this.sackHasNewDataInPacket=!1;for(let e of r)await this.receiveChunk(e);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),void 0),await this.sendSack();return}this.sackTimeout||=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch(e=>{pR(`send delayed sack failed`,e.message)})},kR)}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],t;[...this.sackMisOrdered].sort().forEach(n=>{let r=(n-this.lastReceivedTsn)%OR;n===t?e[e.length-1][1]=r:e.push([r,r]),t=BR(n)});let n=new XL(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(e=>{pR(`send sack failed`,e.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case VL.type:this.receiveDataChunk(e);break;case LL.type:{if(!this.isServer)return;let t=e;pR(`receive init`,t),this.lastReceivedTsn=zR(t.initialTsn),this.reconfigResponseSeq=zR(t.initialTsn),this.remoteVerificationTag=t.initiateTag,this.ssthresh=t.advertisedRwnd,this.peerAdvertisedRwnd=t.advertisedRwnd,this.getExtensions(t.params),this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);let n=new RL;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 r=Math.floor(Date.now()/1e3),i=Buffer.allocUnsafe(4);i.writeUInt32BE(r,0);let a=i;a=Buffer.concat([a,o(`sha1`,this.hmacKey).update(a).digest()]),n.params.push([MR,a]),pR(`send initAck`,n),await this.sendChunk(n).catch(e=>{pR(`send initAck failed`,e.message)})}break;case RL.type:{if(this.associationState!=2)return;let t=e;this.timer1Cancel(),this.lastReceivedTsn=zR(t.initialTsn),this.reconfigResponseSeq=zR(t.initialTsn),this.remoteVerificationTag=t.initiateTag,this.ssthresh=t.advertisedRwnd,this.peerAdvertisedRwnd=t.advertisedRwnd,this.getExtensions(t.params),this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);let n=new HL;for(let[e,r]of t.params)if(e===MR){n.body=r;break}await this.sendChunk(n).catch(e=>{pR(`send echo failed`,e.message)}),this.timer1Start(n),this.setState(3)}break;case XL.type:await this.receiveSackChunk(e);break;case qL.type:{let t=new JL;t.params=e.params,await this.sendChunk(t).catch(e=>{pR(`send heartbeat ack failed`,e.message)})}break;case GL.type:this.setState(1);break;case ZL.type:{this.timer2Cancel(),this.setState(7);let e=new QL;await this.sendChunk(e).catch(e=>{pR(`send shutdown ack failed`,e.message)}),this.t2Start(e),this.setState(6)}break;case KL.type:pR(`ErrorChunk`,e.descriptions);break;case HL.type:{if(!this.isServer)return;let t=e.body,n=o(`sha1`,this.hmacKey).update(t.slice(0,4)).digest();if(t?.length!=mR||!t.slice(4).equals(n)){pR(`x State cookie is invalid`);return}let r=Math.floor(Date.now()/1e3),i=t.readUInt32BE(0);if(i<r-hR||i>r){let e=new KL(0,void 0);e.params.push([KL.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(`\0`)))]),await this.sendChunk(e).catch(e=>{pR(`send errorChunk failed`,e.message)});return}let a=new UL;await this.sendChunk(a).catch(e=>{pR(`send cookieAck failed`,e.message)}),this.setState(4)}break;case UL.type:if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4);break;case $L.type:if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1);break;case YL.type:{if(this.associationState!=4)return;let t=e;for(let[e,n]of t.params){let t=fR[e];t&&await this.receiveReconfigParam(t.parse(n))}}break;case BL.type:this.receiveForwardTsnChunk(e)}}getExtensions(e){for(let[t,n]of e)t===PR?this.remotePartialReliability=!0:t===NR&&(this.remoteExtensions=[...n])}async receiveReconfigParam(e){switch(pR(`receiveReconfigParam`,fR[e.type]),e.type){case cR.type:{let t=e,n=new dR(t.requestSequence,uR.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence,await this.sendReconfigParam(n),await Promise.all(t.streams.map(async e=>{delete this.inboundStreams[e],this.outboundStreamSeq[e]&&(this.reconfigQueue.includes(e)||this.reconfigQueue.push(e))})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(t.streams)}break;case dR.type:{let t=e;if(t.result!==uR.ReconfigResultSuccessPerformed)pR(`OutgoingSSNResetRequestParam failed`,Object.keys(uR).find(e=>uR[e]===t.result));else if(t.responseSequence===this.reconfigRequest?.requestSequence){let e=this.reconfigRequest.streams.map(e=>(delete this.outboundStreamSeq[e],e));this.onReconfigStreams.execute(e),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=TR,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case lR.type:{let t=e;this._inboundStreamsCount+=t.newStreams;let n=new dR(t.requestSequence,1);this.reconfigResponseSeq=t.requestSequence,await this.sendReconfigParam(n)}}}receiveDataChunk(e){if(this.sackNeeded=!0,this.markReceived(e.tsn)){this.sackImmediate=!0;return}this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(e.flags&vR)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let t=this.getInboundStream(e.streamId);t.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let e of t.popMessages())this.advertisedRwnd+=e[2].length,this.receive(...e)}async receiveSackChunk(e){if(Pk(this.lastSackedTsn,e.cumulativeTsn))return;let t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let n=this.flightSize>=this.cwnd,r=0,i=0;for(;this.sentQueue.length>0&&Fk(this.lastSackedTsn,this.sentQueue[0].tsn);){let e=this.sentQueue.shift();r++,e?.acked||(i+=e.bookSize,this.flightSizeDecrease(e)),r===1&&e.sentCount===1&&this.updateRto(t-e.sentTime)}this.sentQueue.length||(this.sentQueue=[]);let a=!1;if(e.gaps.length>0){let t=new Set,n;e.gaps.forEach(r=>{for(let i=r[0];i<r[1]+1;i++)n=(e.cumulativeTsn+i)%OR,t.add(n)});let r=e.cumulativeTsn;for(let e of this.sentQueue){if(Pk(e.tsn,n))break;t.has(e.tsn)&&!e.acked&&(i+=e.bookSize,e.acked=!0,this.flightSizeDecrease(e),r=e.tsn)}for(let e of this.sentQueue){if(Pk(e.tsn,r))break;t.has(e.tsn)||(e.misses++,e.misses===3&&(e.misses=0,this.maybeAbandon(e)||(e.retransmit=!0),e.acked=!1,this.flightSizeDecrease(e),a=!0))}}this.fastRecoveryExit===void 0?(r&&n&&(this.cwnd<=this.ssthresh?this.cwnd+=Math.min(i,_R):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=_R))),a&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*_R),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):Fk(e.cumulativeTsn,this.fastRecoveryExit)&&(this.fastRecoveryExit=void 0),this.sentQueue.length===0?this.timer3Cancel():r>0&&this.timer3Restart(),this.peerAdvertisedRwnd=e.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(e){if(this.sackNeeded=!0,this.sackImmediate=!0,Fk(this.lastReceivedTsn,e.cumulativeTsn))return;let t=e=>Pk(e,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let e of[...this.sackMisOrdered].sort())if(e===BR(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;this.sackDuplicates=this.sackDuplicates.filter(t),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let[t,n]of e.streams){let e=this.getInboundStream(t);e.streamSequenceNumber=Ak(n,1);for(let t of e.popMessages())this.advertisedRwnd+=t[2].length,this.receive(...t)}Object.values(this.inboundStreams).forEach(e=>{this.advertisedRwnd+=e.pruneChunks(this.lastReceivedTsn)})}updateRto(e){this.srtt?(this.rttvar=(1-wR)*this.rttvar+wR*Math.abs(this.srtt-e),this.srtt=(1-CR)*this.srtt+CR*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(ER,Math.min(this.srtt+4*this.rttvar,DR))}receive(e,t,n){this.onReceive.execute(e,t,n)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new LR),this.inboundStreams[e]}markReceived(e){if(Fk(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e))return this.sackDuplicates.push(e),!0;this.sackMisOrdered.add(e);for(let e of[...this.sackMisOrdered].sort())if(e===BR(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;let t=e=>Pk(e,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(t),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t)),!1}send=async(e,t,n,{expiry:r,maxRetransmits:i,ordered:a}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let o=a&&this.outboundStreamSeq[e]||0,s=Math.ceil(n.length/_R),c=0,l=[];for(let u=0;u<s;u++){let d=new VL(0,void 0);d.flags=0,a||(d.flags=bR),u===0&&(d.flags|=yR),u===s-1&&(d.flags|=vR),d.tsn=this.localTsn,d.streamId=e,d.streamSeqNum=o,d.protocol=t,d.userData=n.slice(c,c+_R),d.bookSize=d.userData.length,d.expiry=r,d.maxRetransmits=i,c+=_R,this.localTsn=BR(this.localTsn),l.push(d)}for(l.forEach(e=>{this.outboundQueue.push(e)}),a&&(this.outboundStreamSeq[e]=Ak(o,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(e=>{pR(`send forwardTsn failed`,e.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit==null?4*_R:2*_R,t=Math.min(this.flightSize+e,this.cwnd),n=!0;for(let e of this.sentQueue){if(e.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=t)break;this.flightSizeIncrease(e),e.misses=0,e.retransmit=!1,e.sentCount++,await this.sendChunk(e).catch(e=>{pR(`send data failed`,e.message)}),n&&this.timer3Restart()}n=!1}for(;this.outboundQueue.length>0&&this.flightSize<t&&this.peerRwnd>0;){let e=this.outboundQueue.shift();if(!e)break;if(e.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(e);break}this.sentQueue.push(e),this.flightSizeIncrease(e),e.sentCount++,e.sentTime=Date.now()/1e3,await this.sendChunk(e).catch(e=>{pR(`send data outboundQueue failed`,e.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)],t=e.slice(0,jR);this.reconfigQueue=e.slice(jR);let n=new cR(this.reconfigRequestSeq,this.reconfigResponseSeq,zR(this.localTsn),t);this.reconfigRequestSeq=BR(this.reconfigRequestSeq),this.reconfigRequest=n,await this.sendReconfigParam(n),this.timerReconfigHandleStart()}}async sendReconfigParam(e){pR(`sendReconfigParam`,e);let t=new YL;t.params.push([e.type,e.bytes]),await this.sendChunk(t).catch(e=>{pR(`send reconfig failed`,e.message)})}async sendResetRequest(e){pR(`sendResetRequest`,e);let t=new VL(0,void 0);t.streamId=e,this.outboundQueue.push(t),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 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>SR)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{pR(`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 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>xR)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{pR(`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 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*_R),this.cwnd=_R,this.transmit())};timer3Cancel(){this.timer3Handle&&=(clearTimeout(this.timer3Handle),void 0)}timerReconfigHandleStart(){this.isStopped||(this.timerReconfigHandle||=(pR(`timerReconfigHandleStart`,{rto:this.rto}),this.timerReconfigFailures=0,setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)))}timerReconfigHandleExpired=async()=>{if(!this.isStopped){if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>xR)pR(`timerReconfigFailures`,this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(pR(`timerReconfigHandleExpired`,this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(pR(`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),void 0)}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState===4){if(this.flightSize===0&&this.outboundQueue.length===0){let e=new qL,t=Buffer.allocUnsafe(4);t.writeUInt32BE(Math.floor(Date.now()/1e3),0),e.params.push([1,t]),await this.sendChunk(e).catch(e=>{pR(`send heartbeat failed`,e.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw Error(`heartbeat interval must be > 0`);this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){Pk(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,t={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let n=this.sentQueue.shift();this.advancedPeerAckTsn=n.tsn,e++,n.flags&bR||(t[n.streamId]=n.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new BL(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(t).map(([e,t])=>[Number(e),t]))}maybeAbandon(e){if(e.abandoned)return!0;if(!(e.maxRetransmits&&e.maxRetransmits<e.sentCount||e.expiry&&e.expiry<Date.now()/1e3))return!1;let t=this.sentQueue.findIndex(t=>t.type===e.type);for(let e=t;e>=0;e--){let t=this.sentQueue[e];if(t.abandoned=!0,t.retransmit=!1,t.flags&vR)break}for(let e=t;e<this.sentQueue.length;e++){let t=this.sentQueue[e];if(t.abandoned=!0,t.retransmit=!1,t.flags&vR)break}return!0}static getCapabilities(){return new RR(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 LL;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),pR(`send init`,e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(e){pR(`send init failed`,e.message)}}setExtensions(e){let t=[];this.localPartialReliability&&(e.push([PR,Buffer.from(``)]),t.push(BL.type)),t.push(zL.type),e.push([NR,Buffer.from(t)])}async sendChunk(e){if(this.state===`closed`)return;if(this.remotePort===void 0)throw Error(`invalid remote port`);let t=aR(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}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),void 0),this.setConnectionState(`closed`),this.removeAllListeners())}setConnectionState(e){this.state=e,pR(`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),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 GL;await this.sendChunk(e).catch(e=>{pR(`send abort failed`,e.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},LR=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(e){if(this.reassembly.length===0||Pk(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(let[t,n]of oR(this.reassembly)){if(n.tsn===e.tsn)throw Error(`duplicate chunk in reassembly`);if(Pk(n.tsn,e.tsn)){this.reassembly.splice(t,0,e);break}}}*popMessages(){let e=0,t,n,r;for(;e<this.reassembly.length;){let i=this.reassembly[e];if(t===void 0){if(r=!(i.flags&bR),!(i.flags&yR)){if(r)break;e++;continue}if(r&&Nk(i.streamSeqNum,this.streamSequenceNumber))break;n=i.tsn,t=e}else if(i.tsn!==n){if(r)break;t=void 0,e++;continue}if(i.flags&vR){let n=this.reassembly.slice(t,e+1).map(e=>e.userData).reduce((e,t)=>(e.push(t),e.push(Buffer.from(``)),e),[]);n.pop();let a=Buffer.concat(n);this.reassembly=[...this.reassembly.slice(0,t),...this.reassembly.slice(e+1)],r&&i.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=Ak(this.streamSequenceNumber,1)),e=t,yield[i.streamId,i.protocol,a]}else e++;n=BR(n)}}pruneChunks(e){let t=-1,n=0;for(let[r,i]of this.reassembly.entries())if(Fk(e,i.tsn))t=r,n+=i.userData.length;else break;return this.reassembly=this.reassembly.slice(t+1),n}},RR=class{constructor(e){this.maxMessageSize=e}};function zR(e){return(e-1)%OR}function BR(e){return(e+1)%OR}var VR=Bk(`werift:packages/webrtc/src/transport/sctp.ts`),HR=65536,UR=class e{constructor(e=5e3,t=HR){this.port=e,this.maxMessageSize=t}dtlsTransport;sctp;onDataChannel=new $;id=l().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=HR;dataChannelQueue=[];dataChannelId;eventDisposer=[];get transport(){return this.dtlsTransport}setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(e=>e()),this.dtlsTransport=e,this.sctp=new IR(new GR(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(e=>{e.forEach(e=>{let t=this.dataChannels[e];t&&(t.setReadyState(`closing`),t.setReadyState(`closed`),delete this.dataChannels[e])})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(e=>{e.negotiated&&e.readyState!==`open`&&e.setReadyState(`open`)}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(e=>{e.setReadyState(`closed`)}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(e=>{e===`closed`&&this.sctp.setState(1)})].map(e=>e.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(t=>t.label===e)}datachannelReceive=async(e,t,n)=>{if(t===hI&&n.length>0)switch(VR(`DCEP`,e,t,n),n[0]){case pI:{if(n.length<12){VR(`DATA_CHANNEL_OPEN data.length not enough`);return}if(Object.keys(this.dataChannels).includes(e.toString()))VR(`datachannel already opened`,`retransmit ack`);else{let t=n.readUInt8(1),r=n.readUInt32BE(4),i=n.readUInt16BE(8),a=n.readUInt16BE(10),o=12,s=n.slice(o,o+i).toString(`utf8`);o+=i;let c=n.slice(o,o+a).toString(`utf8`);VR(`DATA_CHANNEL_OPEN`,{channelType:t,reliability:r,streamId:e,label:s,protocol:c});let l=(t&3)==1?r:void 0,u=(t&3)==2?r:void 0,d=new JF({label:s,ordered:!(t&128),maxPacketLifeTime:u,maxRetransmits:l,protocol:c,id:e}),f=new qF(this,d,!1);f.isCreatedByRemote=!0,this.dataChannels[e]=f,this.onDataChannel.execute(f),f.setReadyState(`open`)}let t=this.dataChannels[e],r=Buffer.allocUnsafe(1);r.writeUInt8(fI,0),this.dataChannelQueue.push([t,hI,r]),await this.dataChannelFlush()}break;case fI:{VR(`DATA_CHANNEL_ACK`,e,t);let n=this.dataChannels[e];if(!n)throw Error(`channel not found`);n.setReadyState(`open`)}}else{let r=this.dataChannels[e];if(r){let e=(()=>{switch(t){case gI:return n.toString(`utf8`);case vI:return``;case _I:return n;case yI:return Buffer.from([]);default:throw Error()}})();r.messagesReceived++,r.bytesReceived+=n.length,r.onMessage.execute(e),r.emit(`message`,{data:e}),r.onmessage&&r.onmessage({data:e})}}};dataChannelAddNegotiated(e){if(e.id==null||this.dataChannels[e.id])throw Error();this.dataChannels[e.id]=e,this.sctp.associationState===4&&e.setReadyState(`open`)}dataChannelOpen(e){if(e.id!==void 0){if(this.dataChannels[e.id])throw Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let t=mI,n=0;e.ordered||(t=128),e.maxRetransmits===null?e.maxPacketLifeTime!==null&&(t|=2,n=e.maxPacketLifeTime):(t|=1,n=e.maxRetransmits);let r=Buffer.allocUnsafe(12);r.writeUInt8(pI,0),r.writeUInt8(t,1),r.writeUInt16BE(0,2),r.writeUInt32BE(n,4),r.writeUInt16BE(e.label.length,8),r.writeUInt16BE(e.protocol.length,10);let i=Buffer.concat([r,Buffer.from(e.label,`utf8`),Buffer.from(e.protocol,`utf8`)]);this.dataChannelQueue.push([e,hI,i]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,t,n]=this.dataChannelQueue.shift(),r=e.id;if(r===void 0){for(r=this.dataChannelId;Object.keys(this.dataChannels).includes(r.toString());)r+=2;this.dataChannels[r]=e,e.setId(r)}if(t===hI)await this.sctp.send(r,t,n,{ordered:!0});else{let i=e.maxPacketLifeTime===null?void 0:Date.now()+e.maxPacketLifeTime/1e3;await this.sctp.send(r,t,n,{expiry:i,maxRetransmits:e.maxRetransmits??void 0,ordered:e.ordered}),e.addBufferedAmount(-n.length)}}this.dataChannelQueue=[]}}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,t)=>{let n=Buffer.isBuffer(t)?t:Buffer.from(t),r=KF(t);return this.assertSendableMessageSize(r),e.addBufferedAmount(r),this.dataChannelQueue.push(typeof t==`string`?[e,gI,n]:[e,_I,n]),this.sctp.associationState!==4&&VR(`sctp not established`,this.sctp.associationState),this.dataChannelFlush(),r};getCapabilities(){return e.getCapabilities(this.maxMessageSize)}static getCapabilities(e=HR){return new WR(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??65536}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.dataChannelId=+!this.isServer,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(t=>t[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id),e.id!==void 0&&delete this.dataChannels[e.id],e.setReadyState(`closed`)))}},WR=class{constructor(e){this.maxMessageSize=e}},GR=class{constructor(e){this.dtls=e}set onData(e){this.dtls.dataReceiver=e}send=e=>this.dtls.sendData(e);close(){}},KR=class e{version=0;origin;name=`-`;time=`0 0`;host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];cachedJson;static parse(t){let[n,r]=QR(t),i=new e;n.forEach(e=>{if(e.startsWith(`v=`))i.version=Number.parseInt(e.slice(2),10);else if(e.startsWith(`o=`))i.origin=e.slice(2);else if(e.startsWith(`s=`))i.name=e.slice(2);else if(e.startsWith(`c=`))i.host=YR(e.slice(2));else if(e.startsWith(`t=`))i.time=e.slice(2);else if(e.startsWith(`a=`)){let[t,n]=$R(e);switch(t){case`fingerprint`:{let[e,t]=n?.split(` `)||[];i.dtlsFingerprints.push(new yL(e,t))}break;case`ice-lite`:i.iceLite=!0;break;case`ice-options`:i.iceOptions=n;break;case`ice-pwd`:i.icePassword=n;break;case`ice-ufrag`:i.iceUsernameFragment=n;break;case`group`:ez(i.group,n);break;case`msid-semantic`:ez(i.msidSemantic,n);break;case`setup`:i.dtlsRole=CI[n];break;case`extmap-allow-mixed`:i.extMapAllowMixed=!0}}});let a=i.group.find(e=>e.semantic===`BUNDLE`);return r.forEach(e=>{let t=e[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!t)throw Error(`m line not found`);let n=t[1],r=t[4].split(` `),o=[`audio`,`video`].includes(n)?r.map(e=>Number(e)):void 0,s=new qR(n,Number.parseInt(t[2]),t[3],o||r);if(s.dtlsParams=new bL([...i.dtlsFingerprints],i.dtlsRole),s.iceParams=new PL({iceLite:i.iceLite,usernameFragment:i.iceUsernameFragment,password:i.icePassword}),s.iceOptions=i.iceOptions,i.media.push(s),e.slice(1).forEach(e=>{if(e.startsWith(`c=`))s.host=YR(e.slice(2));else if(e.startsWith(`a=`)){let[t,n]=$R(e);switch(t){case`candidate`:if(!n)throw Error();s.iceCandidates.push(tz(n));break;case`end-of-candidates`:s.iceCandidatesComplete=!0;break;case`extmap`:{let[e,t]=n.split(` `);e.includes(`/`)&&([e]=e.split(`/`)),s.rtp.headerExtensions.push(new eI({id:Number.parseInt(e),uri:t}))}break;case`fingerprint`:{if(!n)throw Error();let[e,t]=n.split(` `);s.dtlsParams?.fingerprints.push(new yL(e,t))}break;case`ice-options`:s.iceOptions=n;break;case`ice-pwd`:s.iceParams.password=n;break;case`ice-ufrag`:s.iceParams.usernameFragment=n;break;case`ice-lite`:s.iceParams.iceLite=!0;break;case`max-message-size`:s.sctpCapabilities=new WR(Number.parseInt(n,10));break;case`mid`:s.rtp.muxId=n;break;case`msid`:s.msids.push(n);break;case`rtcp`:{let[e,t]=UF(n,` `);s.rtcpPort=Number.parseInt(e),s.rtcpHost=YR(t)}break;case`rtcp-mux`:s.rtcpMux=!0;break;case`setup`:s.dtlsParams.role=CI[n];break;case`recvonly`:case`sendonly`:case`sendrecv`:case`inactive`:s.direction=t;break;case`rtpmap`:{let[e,t]=UF(n,` `),[r,i,a]=t.split(`/`),o;s.kind===`audio`&&(o=a?Number.parseInt(a):1);let c=new $F({mimeType:s.kind+`/`+r,channels:o,clockRate:Number.parseInt(i),payloadType:Number.parseInt(e)});s.rtp.codecs.push(c)}break;case`sctpmap`:{if(!n)throw Error();let[e,t]=UF(n,` `);s.sctpMap[Number.parseInt(e)]=t,s.sctpPort=Number.parseInt(e)}break;case`sctp-port`:if(!n)throw Error();s.sctpPort=Number.parseInt(n);break;case`ssrc`:{let[e,t]=UF(n,` `),r=Number.parseInt(e),[i,a]=UF(t,`:`),o=s.ssrc.find(e=>e.ssrc===r);o||(o=new az({ssrc:r}),s.ssrc.push(o)),TI.includes(i)&&(o[i]=a)}break;case`ssrc-group`:ez(s.ssrcGroup,n);break;case`rid`:{let[e,t]=UF(n,` `);s.simulcastParameters.push(new iI({rid:e,direction:t}))}}}}),(!s.iceParams.usernameFragment||!s.iceParams.password)&&s.rtp.muxId&&a&&a.items.includes(s.rtp.muxId))for(let e=0;e<a.items.length;e++){if(!a.items.includes(e.toString()))continue;let t=i.media[e];if(t.iceParams?.usernameFragment&&t.iceParams.password){s.iceParams={...t.iceParams};break}}s.dtlsParams.role||(s.dtlsParams=void 0);let c=e=>s.rtp.codecs.find(t=>t.payloadType===e);e.slice(1).forEach(e=>{if(e.startsWith(`a=`)){let[t,n]=$R(e);if(t===`fmtp`){let[e,t]=UF(n,` `),r=c(Number(e));r.parameters=t}else if(t===`rtcp-fb`){let[e,t,r]=n.split(` `);s.rtp.codecs.forEach(n=>{[`*`,n.payloadType.toString()].includes(e)&&n.rtcpFeedback.push(new tI({type:t,parameter:r}))})}}})}),i}webrtcTrackId(e){if(e.msid?.includes(` `)){let t=e.msid.split(` `);for(let e of this.msidSemantic)if(e.semantic===`WMS`&&(e.items.includes(t[0])||e.items.includes(`*`)))return t[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${XR(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(t=>e.push(`a=group:${t.str}`)),this.extMapAllowMixed&&e.push(`a=extmap-allow-mixed`),this.msidSemantic.forEach(t=>e.push(`a=msid-semantic:${t.str}`));let t=this.media.map(e=>e.toString()).join(``);return e.join(`\r
|
|
140
140
|
`)+`\r
|
|
141
|
-
`+t}toJSON(){let e=this.string;return(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type)&&(this.cachedJson=new
|
|
141
|
+
`+t}toJSON(){let e=this.string;return(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type)&&(this.cachedJson=new nz(e,this.type)),this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}},qR=class{constructor(e,t,n,r){this.kind=e,this.port=t,this.profile=n,this.fmt=r}host;direction;msids=[];rtcpPort;rtcpHost;rtcpMux=!1;ssrc=[];ssrcGroup=[];rtp={codecs:[],headerExtensions:[]};sctpCapabilities;sctpMap={};sctpPort;dtlsParams;iceParams;iceCandidates=[];iceCandidatesComplete=!1;iceOptions;simulcastParameters=[];get msid(){return this.msids[0]}set msid(e){this.msids=e?[e]:[]}toString(){let e=[];if(e.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(e=>e.toString()).join(` `)}`),this.host&&e.push(`c=${XR(this.host)}`),this.iceCandidates.forEach(t=>{e.push(`a=candidate:${ZR(t)}`)}),this.iceCandidatesComplete&&e.push(`a=end-of-candidates`),this.iceParams?.usernameFragment&&e.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`),this.iceParams?.password&&e.push(`a=ice-pwd:${this.iceParams.password}`),this.iceParams?.iceLite&&e.push(`a=ice-lite`),this.iceOptions&&e.push(`a=ice-options:${this.iceOptions}`),this.dtlsParams&&(this.dtlsParams.fingerprints.forEach(t=>{e.push(`a=fingerprint:${t.algorithm} ${t.value}`)}),e.push(`a=setup:${SI[this.dtlsParams.role]}`)),this.direction&&e.push(`a=${this.direction}`),this.rtp.muxId&&e.push(`a=mid:${this.rtp.muxId}`),this.msids.forEach(t=>e.push(`a=msid:${t}`)),this.rtcpPort&&this.rtcpHost&&(e.push(`a=rtcp:${this.rtcpPort} ${XR(this.rtcpHost)}`),this.rtcpMux&&e.push(`a=rtcp-mux`)),this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)}),this.ssrc.forEach(t=>{TI.forEach(n=>{let r=t[n];r!==void 0&&e.push(`a=ssrc:${t.ssrc} ${n}:${r}`)})}),this.rtp.codecs.forEach(t=>{e.push(`a=rtpmap:${t.payloadType} ${t.str}`),t.rtcpFeedback.forEach(n=>{let r=n.type;n.parameter&&(r+=` ${n.parameter}`),e.push(`a=rtcp-fb:${t.payloadType} ${r}`)}),t.parameters&&e.push(`a=fmtp:${t.payloadType} ${t.parameters}`)}),Object.keys(this.sctpMap).forEach(t=>{let n=this.sctpMap[Number(t)];e.push(`a=sctpmap:${t} ${n}`)}),this.sctpPort&&e.push(`a=sctp-port:${this.sctpPort}`),this.sctpCapabilities&&e.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`),this.rtp.headerExtensions.forEach(t=>e.push(`a=extmap:${t.id} ${t.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach(t=>{e.push(`a=rid:${t.rid} ${t.direction}`)});let t=`a=simulcast:`,n=this.simulcastParameters.filter(e=>e.direction===`recv`);n.length&&(t+=`recv ${n.map(e=>e.rid).join(`;`)} `);let r=this.simulcastParameters.filter(e=>e.direction===`send`);r.length&&(t+=`send ${r.map(e=>e.rid).join(`;`)}`),e.push(t)}return e.join(`\r
|
|
142
142
|
`)+`\r
|
|
143
|
-
`}},
|
|
143
|
+
`}},JR=class{constructor(e,t){this.semantic=e,this.items=t}get str(){return`${this.semantic} ${this.items.join(` `)}`}};function YR(e){let t=e.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!t)throw Error(`exception`);return t[2]}function XR(e){return`IN IP${w(e)?4:6} ${e}`}function ZR(e){let t=`${e.foundation} ${e.component} ${e.protocol} ${e.priority} ${e.ip} ${e.port} typ ${e.type}`;return e.relatedAddress!=null&&(t+=` raddr ${e.relatedAddress}`),e.relatedPort!=null&&(t+=` rport ${e.relatedPort}`),e.tcpType!=null&&(t+=` tcptype ${e.tcpType}`),e.generation!=null&&(t+=` generation ${e.generation}`),e.ufrag!=null&&(t+=` ufrag ${e.ufrag}`),t}function QR(e){let t=[],n=[],r=e.split(`\r
|
|
144
144
|
`);return r.length===1&&(r=e.split(`
|
|
145
|
-
`)),r.forEach(e=>{e.startsWith(`m=`)?n.push([e]):n.length>0?n[n.length-1].push(e):t.push(e)}),[t,n]}function bj(e){if(e.includes(`:`)){let t=uO(e.slice(2),`:`);return[t[0],t[1]]}return[e.slice(2),void 0]}function xj(e,t,n=e=>e.toString()){let r=t.split(` `);r.length>0&&e.push(new hj(r[0],r.slice(1).map(n)))}function Sj(e){return Zk(AD.fromSdp(e))}var Cj=class{sdp;type;constructor(e,t){Object.defineProperties(this,{sdp:{configurable:!0,enumerable:!0,value:e,writable:!1},type:{configurable:!0,enumerable:!0,value:t,writable:!1}})}static isThis(e){if(typeof e?.sdp==`string`)return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};function wj(e,t){t.origin=`- ${c(8).readBigUInt64BE(0).toString().slice(0,8)} 0 IN IP4 0.0.0.0`,t.msidSemantic.push(new hj(`WMS`,[`*`])),t.type=e}function Tj(e){let t={};return e.split(`;`).forEach(e=>{if(e.includes(`=`)){let[n,r]=uO(e,`=`);GO.includes(n)?t[n]=Number(r):t[n]=r}else if(e.includes(`:`)){let[n,r]=e.split(`:`);t[n]=Number.isNaN(Number(r))?r:Number(r)}else t[e]=void 0}),t}var Ej=class{ssrc;cname;msid;msLabel;label;constructor(e){Object.assign(this,e)}},Dj=sS(`werift:packages/webrtc/src/media/rtpReceiver.ts`),Oj=class{constructor(e,t,n){this.config=e,this.kind=t,this.rtcpSsrc=n,this.defaultTrack=new ik({kind:t,remote:!0}),this.onPacketLost.subscribe(e=>{this.nackCountBySsrc[e.mediaSourceSsrc]=(this.nackCountBySsrc[e.mediaSourceSsrc]??0)+1})}codecs={};defaultTrack;get codecArray(){return Object.values(this.codecs).sort((e,t)=>e.payloadType-t.payloadType)}ssrcByRtx={};nack=new jk(this);audioRedHandler=new qw;type=`receiver`;uuid=l().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new $;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteStreamIds=[];remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};senderReportsReceivedBySsrc={};remoteTimestampsBySsrc={};remotePacketCountBySsrc={};remoteOctetCountBySsrc={};nackCountBySsrc={};pliCountBySsrc={};get transport(){return this.dtlsTransport??null}setDtlsTransport(e){this.dtlsTransport=e}get track(){return this.tracks[0]??this.defaultTrack}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===`nack`)}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===yO().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===_O().type)}prepareReceive(e){e.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),e.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(e){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new Nk(this.dtlsTransport,this.rtcpSsrc,e))}addTrack(e){return!this.tracks.find(t=>{if(t.rid)return t.rid===e.rid;if(t.ssrc)return t.ssrc===e.ssrc})&&(this.tracks.push(e),e.ssrc&&(this.trackBySSRC[e.ssrc]=e),e.rid&&(this.trackByRID[e.rid]=e),!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 E(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let e=Object.entries(this.remoteStreams).map(([e,t])=>{let n=0,r=0;if(this.lastSRtimestamp[e]){n=this.lastSRtimestamp[e];let t=_k()-this.receiveLastSRTimestamp[e];t>0&&t<65536&&(r=rS(t*65536))}return new lw({ssrc:Number(e),fractionLost:t.fraction_lost,packetsLost:t.packets_lost,highestSequence:t.max_seq,jitter:t.jitter,lsr:n,dlsr:r})}),t=new cw({ssrc:this.rtcpSsrc,reports:e});try{this.config.debug.receiverReportDelay&&await E(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([t])}catch(e){Dj(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}getInboundRtpStatsId(e){return ZO(`inbound-rtp`,e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return ZO(`remote-outbound-rtp`,e.id??e.uuid)}getStatsRootIds(e){return this.tracks.filter(t=>!e||t===e).filter(e=>e.ssrc).map(e=>this.getInboundRtpStatsId(e))}collectStats(e){let t=[],n=this.dtlsTransport?ZO(`transport`,this.dtlsTransport.id):void 0,r=this.codecArray[0],i=new Set;for(let a of this.tracks){if(!a.ssrc)continue;let o=this.remoteStreams[a.ssrc],s=this.remoteTimestampsBySsrc[a.ssrc]!==void 0,c=this.lastSRtimestamp[a.ssrc]!==void 0||s?this.getRemoteOutboundRtpStatsId(a):void 0,l=r&&n?QO(n,r.payloadType,a.id??a.uuid):void 0;if(r&&n&&l&&!i.has(l)){i.add(l);let a={type:`codec`,id:l,timestamp:e,payloadType:r.payloadType,transportId:n,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,sdpFmtpLine:r.parameters};t.push(a)}let u={type:`inbound-rtp`,id:this.getInboundRtpStatsId(a),timestamp:e,ssrc:a.ssrc,kind:this.kind,transportId:n,codecId:l,mid:this.sdesMid,trackIdentifier:a.id??a.uuid,packetsReceived:o?.packets_received??0,bytesReceived:o?.bytesReceived??0,headerBytesReceived:o?.headerBytesReceived??0,packetsLost:o?.packets_lost??0,jitter:o?.clockRate?o.jitter/o.clockRate:void 0,lastPacketReceivedTimestamp:o?.lastPacketReceivedTimestamp,remoteId:c,nackCount:this.nackCountBySsrc[a.ssrc]||void 0,pliCount:this.pliCountBySsrc[a.ssrc]||void 0};if(t.push(u),c){let r={type:`remote-outbound-rtp`,id:this.getRemoteOutboundRtpStatsId(a),timestamp:e,ssrc:a.ssrc,kind:this.kind,transportId:n,codecId:u.codecId,localId:u.id,remoteTimestamp:this.remoteTimestampsBySsrc[a.ssrc],reportsSent:this.senderReportsReceivedBySsrc[a.ssrc]??0,packetsSent:this.remotePacketCountBySsrc[a.ssrc],bytesSent:this.remoteOctetCountBySsrc[a.ssrc]};t.push(r)}}return t}async getStats(){let e=$O(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),tk(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){Dj(`pli not supported`,{mediaSsrc:e});return}if(this.stopped)return;Dj(`sendRtcpPLI`,{mediaSsrc:e});let t=new sw({feedback:new iw({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1,await this.dtlsTransport.sendRtcp([t])}catch(e){Dj(e)}}handleRtcpPacket(e){switch(e.type){case ww.type:{let t=e;this.lastSRtimestamp[t.ssrc]=bk(t.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[t.ssrc]=_k(),this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1,this.remoteTimestampsBySsrc[t.ssrc]=yk(t.senderInfo.ntpTimestamp),this.remotePacketCountBySsrc[t.ssrc]=t.senderInfo.packetCount,this.remoteOctetCountBySsrc[t.ssrc]=t.senderInfo.octetCount;let n=this.trackBySSRC[e.ssrc];n&&n.onReceiveRtcp.execute(e)}}this.onRtcp.execute(e)}handleRtpBySsrc=(e,t)=>{let n=this.trackBySSRC[e.header.ssrc];this.handleRTP(e,t,n)};handleRtpByRid=(e,t,n)=>{let r=this.trackByRID[t];this.trackBySSRC[e.header.ssrc]||(this.trackBySSRC[e.header.ssrc]=r),this.handleRTP(e,n,r)};handleRTP(e,t,n){if(this.stopped)return;let r=this.codecs[e.header.payloadType];if(!r)return;if(this.remoteStreams[e.header.ssrc]=this.remoteStreams[e.header.ssrc]??new Pk(r.clockRate),this.remoteStreams[e.header.ssrc].add(e),this.receiverTWCC){let e=t[Aw.transportWideCC];if(!e==null)throw Error(`undefined`);this.receiverTWCC.handleTWCC(e)}else this.twccEnabled&&this.setupTWCC(e.header.ssrc);if(r.name.toLowerCase()===`rtx`){let t=this.ssrcByRtx[e.header.ssrc],i=Tj(r.parameters??``),a=this.codecs[i.apt];if(e.payload.length<2)return;e=nT(e,a.payloadType,t),n=this.trackBySSRC[t]}let i;if(!(r.name.toLowerCase()===`red`&&(i=Uw.deSerialize(e.payload),!Object.keys(this.codecs).includes(i.header.fields[0].blockPT.toString())))){if(n?.kind===`video`&&this.nackEnabled&&this.nack.addPacket(e),n){if(i){if(n.kind===`audio`){let r=this.audioRedHandler.push(i,e);for(let e of r)n.onReceiveRtp.execute(e.clone(),t)}}else n.onReceiveRtp.execute(e.clone(),t)}this.runRtcp()}}},kj=sS(`werift:packages/webrtc/src/media/router.ts`),Aj=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){kj(`registerRtpReceiver`,t),this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){kj(`registerRtpReceiverBySsrc`,t),t.encodings.filter(e=>e.ssrc!=null).forEach((n,r)=>{this.registerRtpReceiver(e.receiver,n.ssrc),e.addTrack(new ik({ssrc:n.ssrc,kind:e.kind,id:e.sender.trackId,remote:!0,codec:t.codecs[r]})),n.rtx&&this.registerRtpReceiver(e.receiver,n.rtx.ssrc)}),t.headerExtensions.forEach(e=>{this.extIdUriMap[e.id]=e.uri})}registerRtpReceiverByRid(e,t,n){let[r]=n.codecs;kj(`registerRtpReceiverByRid`,t),e.addTrack(new ik({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:!0,codec:r})),this.ridTable[t.rid]=e.receiver}routeRtp=e=>{let t=jw(e.header.extensions,this.extIdUriMap),n=this.ssrcTable[e.header.ssrc],r=t[Aw.sdesRTPStreamID];if(typeof r==`string`?(n=this.ridTable[r],n.latestRid=r,n.handleRtpByRid(e,r,t)):n?n.handleRtpBySsrc(e,t):(n=Object.values(this.ridTable).filter(e=>e instanceof Oj).find(t=>t.trackBySSRC[e.header.ssrc]),n&&(kj(`simulcast register receiver by ssrc`,e.header.ssrc),this.registerRtpReceiver(n,e.header.ssrc),n.handleRtpBySsrc(e,t))),!n){kj(`ssrcReceiver not found`);return}let i=t[Aw.sdesMid];typeof i==`string`&&(n.sdesMid=i);let a=t[Aw.repairedRtpStreamId];typeof a==`string`&&(n.latestRepairedRid=a)};routeRtcp=e=>{let t=[];switch(e.type){case ww.type:e=e,t.push(this.ssrcTable[e.ssrc]);break;case cw.type:e=e,e.reports.forEach(e=>{t.push(this.ssrcTable[e.ssrc])});break;case bw.type:break;case yw.type:{let n=e;n.feedback&&t.push(this.ssrcTable[n.feedback.mediaSourceSsrc])}break;case sw.type:{let n=e;switch(n.feedback.count){case aw.count:{let e=n.feedback;t.push(this.ssrcTable[e.ssrcFeedbacks[0]])}break;default:t.push(this.ssrcTable[n.feedback.senderSsrc]||this.ssrcTable[n.feedback.mediaSsrc])}}}t.filter(e=>e).forEach(t=>t.handleRtcpPacket(e))}},jj=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(e,t,n){this.numPackets===0?(this.firstPacketSentAtMs=t,this.firstPacketReceivedAtMs=n,this.lastPacketSentAtMs=t,this.lastPacketReceivedAtMs=n):(t<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=t),n<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=n),t>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=t),n>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=n)),this.numPackets++,this.totalSize+=e}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let e=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs;return ew(this.totalSize/e*8*1e3)}get sendBitrate(){let e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;return ew(this.totalSize/e*8*1e3)}},Mj=20,Nj=10,Pj=class{congestion=!1;onAvailableBitrate=new $;onCongestion=new $;onCongestionScore=new $;congestionCounter=0;cumulativeResult=new jj;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(e){this._congestionScore=e,this.onCongestionScore.execute(e)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(e){this._availableBitrate=e,this.onAvailableBitrate.execute(e)}constructor(){}receiveTWCC(e){let t=mk()-this.cumulativeResult.firstPacketSentAtMs;t>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<Mj?this.congestionCounter++:this.congestionScore<Nj&&this.congestionScore++,this.congestionCounter>=Mj&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let t of e.packetResults){if(!t.received)continue;let e=t.sequenceNumber,n=this.sentInfos[e];n&&t.receivedAtMs&&this.cumulativeResult.addPacket(n.size,n.sendingAtMs,t.receivedAtMs)}if(t>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-Mj){let e=ew(Mj/2)+1,t=e-(e-(ew(Mj/4)+1))/10*this.congestionScore;this.congestionCounter-=t}this.congestionCounter<=-Mj&&(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(e){Object.keys(e).map(e=>Number(e)).sort().filter(t=>t<e.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[e.wideSeq]=e}},Fj=sS(`werift:packages/webrtc/src/media/rtpSender.ts`),Ij=128,Lj=.85,Rj=class{constructor(e){this.trackOrKind=e,this.kind=typeof this.trackOrKind==`string`?this.trackOrKind:this.trackOrKind.kind,typeof e!=`string`&&this.registerTrack(e)}type=`sender`;kind;ssrc=c(4).readUInt32BE(0);rtxSsrc=c(4).readUInt32BE(0);trackId=l().toString();onReady=new $;onRtcp=new $;onPictureLossIndication=new $;onGenericNack=new $;senderBWE=new Pj;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=Ox();redRedundantPayloadType;_redDistance=2;redEncoder=new Gw(this._redDistance);headerExtensions=[];disposeTrack;sendEncodings=[{}];lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;headerBytesSent=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;retransmittedPacketsSent=0;retransmittedBytesSent=0;nackCount=0;pliCount=0;firCount=0;remotePacketsLost;remoteFractionLost;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpCache=[];codec;dtlsTransport;dtlsDisposer=[];track=null;streamIds=[];stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;get transport(){return this.dtlsTransport??null}get streamId(){return this.streamIds[0]}set streamId(e){this.streamIds=e?[e]:[]}setDtlsTransport(e){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=e,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e===`connected`&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(e){this._redDistance=e,this.redEncoder.distance=e}prepareSend(e){this.cname=e.rtcp?.cname,this.mid=e.muxId,this.headerExtensions=e.headerExtensions,this.rtpStreamId=e.rtpStreamId,this.repairedRtpStreamId=e.repairedRtpStreamId,this.codec=e.codecs[0],this.track&&(this.track.codec=this.codec),e.codecs.forEach(e=>{let t=Tj(e.parameters??``);e.name.toLowerCase()===`rtx`&&t.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()===`red`&&(this.redRedundantPayloadType=Number((e.parameters??``).split(`/`)[0]))})}registerTrack(e){if(e.stopped)throw Error(`track is ended`);this.disposeTrack&&this.disposeTrack(),e.id=this.trackId;let{unSubscribe:t}=e.onReceiveRtp.subscribe(async e=>{await this.sendRtp(e)});this.track=e,this.disposeTrack=t,this.codec&&(e.codec=this.codec),e.onSourceChanged.subscribe(e=>{this.replaceRTP(e)})}setStreams(e=[]){this.streamIds=[...new Set(e.map(e=>e.id))]}setSendEncodings(e=[]){this.sendEncodings=e.length>0?e.map(e=>({...e})):[{}]}async replaceTrack(e){if(e===null){this.disposeTrack&&this.disposeTrack(),this.track=null;return}if(e.stopped)throw Error(`track is ended`);if(this.sequenceNumber!=null){let t=e.header||(await e.onReceiveRtp.asPromise())[0].header;this.replaceRTP(t)}this.registerTrack(e),Fj(`replaceTrack`,`ssrc`,e.ssrc,`rid`,e.rid)}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack&&this.disposeTrack(),this.track=null}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await E(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let e=[new ww({ssrc:this.ssrc,senderInfo:new Tw({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=bk(this.ntpTimestamp),this.lastSentSRTimestamp=_k(),this.cname&&e.push(new bw({chunks:[new xw({source:this.ssrc,items:[new Sw({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(e)}catch(e){Fj(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:e,timestamp:t},n=!1){this.sequenceNumber!=null&&(this.seqOffset=Zx(this.sequenceNumber,-e),n&&(this.seqOffset=Zx(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=Qx(this.timestamp,-t),n&&(this.timestampOffset=Zx(this.timestampOffset,1))),this.rtpCache=[],Fj(`replaceRTP`,this.sequenceNumber,e,this.seqOffset)}async sendRtp(e){if(this.dtlsTransport.state!==`connected`||!this.codec)return;e=Buffer.isBuffer(e)?tT.deSerialize(e):e;let{header:t,payload:n}=e;t.ssrc=this.ssrc,t.payloadType=this.codec.payloadType,t.timestamp=Qx(t.timestamp,this.timestampOffset),t.sequenceNumber=Zx(t.sequenceNumber,this.seqOffset),this.timestamp=t.timestamp,this.sequenceNumber=t.sequenceNumber;let r=vk(),i=[...t.extensions];t.extensions=this.headerExtensions.map(e=>{let t=(()=>{switch(e.uri){case Aw.sdesMid:return this.mid?Mw(this.mid):void 0;case Aw.sdesRTPStreamID:return this.rtpStreamId?Nw(this.rtpStreamId):void 0;case Aw.repairedRtpStreamId:return this.repairedRtpStreamId?Pw(this.repairedRtpStreamId):void 0;case Aw.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Zx(this.dtlsTransport.transportSequenceNumber,1),Fw(this.dtlsTransport.transportSequenceNumber);case Aw.absSendTime:return Iw(r)}})();if(t)return{id:e.id,payload:t}}).filter(e=>e);for(let e of i){let n=t.extensions.find(t=>t.id===e.id);n?n.payload=e.payload:t.extensions.push(e)}t.extensions=t.extensions.sort((e,t)=>e.id-t.id),this.ntpTimestamp=r,this.rtpTimestamp=t.timestamp,this.octetCount+=n.length,this.headerBytesSent+=t.serializeSize,this.packetCount=Qx(this.packetCount,1),this.rtpCache[t.sequenceNumber%Ij]=e;let a=n;this.redRedundantPayloadType&&(this.redEncoder.push({block:a,timestamp:t.timestamp,blockPT:this.redRedundantPayloadType}),a=this.redEncoder.build().serialize());let o=await this.dtlsTransport.sendRtp(a,t);this.runRtcp();let s=mk(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:s,sentAtMs:s};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(e){switch(e.type){case ww.type:case cw.type:e.reports.filter(e=>e.ssrc===this.ssrc).forEach(e=>{if(this.remotePacketsLost=e.packetsLost,this.remoteFractionLost=e.fractionLost/256,this.lastSRtimestamp===e.lsr&&e.dlsr&&this.lastSentSRTimestamp){let t=_k()-this.lastSentSRTimestamp-e.dlsr/65536;this.totalRoundTripTime+=t,this.roundTripTimeMeasurements++,this.rtt=this.rtt===void 0?t:Lj*this.rtt+(1-Lj)*t}});break;case yw.type:{let t=e;switch(t.feedback.count){case pw.count:{let e=t.feedback;this.senderBWE.receiveTWCC(e)}break;case dw.count:{let e=t.feedback;this.nackCount++,e.lost.forEach(async e=>{let t=this.rtpCache[e%Ij];t&&t.header.sequenceNumber!==e&&(t=void 0),t&&(this.rtxPayloadType!=null&&(t=rT(t,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Zx(this.rtxSequenceNumber,1)),this.retransmittedPacketsSent++,this.retransmittedBytesSent+=t.payload.length,this.headerBytesSent+=t.header.serializeSize,await this.dtlsTransport.sendRtp(t.payload,t.header))}),this.onGenericNack.execute(e)}}}break;case sw.type:{let t=e;switch(t.feedback.count){case aw.count:{let e=t.feedback;this.receiverEstimatedMaxBitrate=e.bitrate}break;case iw.count:this.pliCount++,this.onPictureLossIndication.execute()}}}this.onRtcp.execute(e)}getParameters(){return{encodings:this.sendEncodings.map(e=>({...e}))}}setParameters(e){e.encodings&&this.setSendEncodings(e.encodings)}get outboundRtpStatsId(){return ZO(`outbound-rtp`,this.trackId)}get mediaSourceStatsId(){return ZO(`media-source`,this.trackId)}get remoteInboundRtpStatsId(){return ZO(`remote-inbound-rtp`,this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){let t=[],n=this.dtlsTransport?ZO(`transport`,this.dtlsTransport.id):void 0,r=this.codec&&n?QO(n,this.codec.payloadType,this.trackId):void 0,i={type:`outbound-rtp`,id:this.outboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:n,codecId:r,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,headerBytesSent:this.headerBytesSent,retransmittedPacketsSent:this.retransmittedPacketsSent||void 0,retransmittedBytesSent:this.retransmittedBytesSent||void 0,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0,mediaSourceId:this.track?this.mediaSourceStatsId:void 0,remoteId:this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0?this.remoteInboundRtpStatsId:void 0,nackCount:this.nackCount||void 0,pliCount:this.pliCount||void 0,firCount:this.firCount||void 0};if(t.push(i),this.track){let n={type:`media-source`,id:this.mediaSourceStatsId,timestamp:e,trackIdentifier:this.track.id??this.trackId,kind:this.kind};t.push(n)}if(this.codec&&n){let i={type:`codec`,id:r,timestamp:e,payloadType:this.codec.payloadType,transportId:n,mimeType:this.codec.mimeType,clockRate:this.codec.clockRate,channels:this.codec.channels,sdpFmtpLine:this.codec.parameters};t.push(i)}if(this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0){let r={type:`remote-inbound-rtp`,id:this.remoteInboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:n,codecId:i.codecId,localId:i.id,roundTripTime:this.rtt,totalRoundTripTime:this.totalRoundTripTime,roundTripTimeMeasurements:this.roundTripTimeMeasurements,packetsLost:this.remotePacketsLost,fractionLost:this.remoteFractionLost};t.push(r)}return t}async getStats(){let e=$O(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),tk(t,this.getStatsRootIds())}};function zj(e,t=e){return new DOMException(t,e)}function Bj(e){return TypeError(e)}var Vj=sS(`werift:packages/webrtc/src/transport/sctpManager.ts`),Hj=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new $;constructor(){}createSctpTransport(e){let t=new uj(5e3,e);return t.mid=void 0,t.onDataChannel.subscribe(e=>{this.dataChannelsOpened++,this.dataChannels.push(e),this.onDataChannel.execute(e)}),this.sctpTransport=t,t}createDataChannel(e,t={}){let n=Uj(t.maxPacketLifeTime,`maxPacketLifeTime`),r=Uj(t.maxRetransmits,`maxRetransmits`),i={protocol:``,ordered:!0,negotiated:!1,...t,maxPacketLifeTime:n,maxRetransmits:r};if(i.maxPacketLifeTime!=null&&i.maxRetransmits!=null)throw Bj(`maxPacketLifeTime and maxRetransmits cannot both be set`);this.sctpTransport||=this.createSctpTransport();let a=new hO({id:i.id,label:e,maxPacketLifeTime:i.maxPacketLifeTime,maxRetransmits:i.maxRetransmits,negotiated:i.negotiated,ordered:i.ordered,protocol:i.protocol}),o=new mO(this.sctpTransport,a);return this.dataChannelsOpened++,this.dataChannels.push(o),o.stateChange.subscribe(e=>{if(e===`closed`){this.dataChannelsClosed++;let e=this.dataChannels.indexOf(o);e!==-1&&this.dataChannels.splice(e,1)}}),o}async connectSctp(){this.sctpTransport&&this.sctpRemotePort&&(await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),Vj(`sctp connected`))}setRemoteSCTP(e,t){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(e.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=e.sctpPort,!this.sctpRemotePort)throw Error(`sctpRemotePort not exist`);this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=t,this.sctpTransport.mid||(this.sctpTransport.mid=e.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(e=$O()){let t=[];for(let n of this.dataChannels){let r={type:`data-channel`,id:ZO(`data-channel`,n.id??n.statsId),timestamp:e,label:n.label,protocol:n.protocol,dataChannelIdentifier:n.id??void 0,state:n.readyState,messagesSent:n.messagesSent||0,bytesSent:n.bytesSent||0,messagesReceived:n.messagesReceived||0,bytesReceived:n.bytesReceived||0};t.push(r)}return t}};function Uj(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw Bj(`${t} must be an unsigned short`);return n}var Wj=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:e,midSuffix:t,bundlePolicy:n}){this.cname=e,this.midSuffix=t??!1,this.bundlePolicy=n}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?.(e=>e.direction===`inactive`)}createMediaDescriptionForTransceiver(e,t){let n=new mj(e.kind,9,`UDP/TLS/RTP/SAVPF`,e.codecs.map(e=>e.payloadType));return n.direction=t,n.msids=e.msids,n.rtp={codecs:e.codecs,headerExtensions:e.headerExtensions,muxId:e.mid??void 0},n.rtcpHost=`0.0.0.0`,n.rtcpPort=9,n.rtcpMux=!0,n.ssrc=[new Ej({ssrc:e.sender.ssrc,cname:this.cname})],e.options.simulcast&&(n.simulcastParameters=e.options.simulcast.map(e=>new TO(e))),n.rtp.codecs.find(e=>e.name.toLowerCase()===`rtx`)&&(n.ssrc.push(new Ej({ssrc:e.sender.rtxSsrc,cname:this.cname})),n.ssrcGroup=[new hj(`FID`,[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]),this.addTransportDescription(n,e.dtlsTransport),n}createMediaDescriptionForSctp(e){let t=new mj(`application`,HO,`UDP/DTLS/SCTP`,[`webrtc-datachannel`]);return t.sctpPort=e.port,t.rtp.muxId=e.mid,t.sctpCapabilities=e.getCapabilities(),this.addTransportDescription(t,e.dtlsTransport),t}addTransportDescription(e,t){let n=t.iceTransport;e.iceCandidates=n.localCandidates,e.iceCandidatesComplete=n.gatheringState===`complete`,e.iceParams=n.localParameters,e.iceOptions=`trickle`,e.host=VO,e.port=HO,e.direction===`inactive`&&(e.port=0,e.msids=[]),e.dtlsParams||(e.dtlsParams=t.localParameters,e.dtlsParams.fingerprints||(e.dtlsParams.fingerprints=t.localParameters.fingerprints))}allocateMid(e=``){let t=``;for(let n=0;t=(n++).toString()+e,this.seenMid.has(t););return this.seenMid.add(t),t}parseSdp({sdp:e,isLocal:t,signalingState:n,type:r}){let i=pj.parse(e);return this.validateDescription({description:i,isLocal:t,signalingState:n,type:r}),i.type=r,i}validateDescription({description:e,isLocal:t,signalingState:n,type:r}){if(t){if(r===`offer`){if(![`stable`,`have-local-offer`].includes(n))throw zj(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-remote-offer`,`have-local-pranswer`].includes(n))throw zj(`InvalidStateError`,`Cannot handle answer in signaling state`)}else if(r===`offer`){if(![`stable`,`have-remote-offer`,`have-local-offer`].includes(n))throw zj(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-local-offer`,`have-remote-pranswer`].includes(n))throw zj(`InvalidStateError`,`Cannot handle answer in signaling state`)}buildOfferSdp(e,t){let n=new pj;wj(`offer`,n),(this.currentLocalDescription?.media??[]).forEach((r,i)=>{let a=r.rtp.muxId;if(a){if(r.kind===`application`){if(!t)throw Error(`sctpTransport not found`);t.mLineIndex=i,n.media.push(this.createMediaDescriptionForSctp(t))}else{let t=e.find(e=>e.mid===a);if(!t){if(r.direction===`inactive`){n.media.push(r);return}throw Error(`transceiver not found`)}t.mLineIndex=i,n.media.push(this.createMediaDescriptionForTransceiver(t,t.direction))}}});for(let t of e.filter(e=>!n.media.find(t=>t.rtp.muxId===e.mid))){t.mid??=this.allocateMid(this.midSuffix?`av`:``);let e=this.createMediaDescriptionForTransceiver(t,t.direction);t.mLineIndex===void 0?(t.mLineIndex=n.media.length,n.media.push(e)):n.media[t.mLineIndex]=e}if(t&&!n.media.find(e=>e.kind===`application`)&&(t.mLineIndex=n.media.length,t.mid??=this.allocateMid(this.midSuffix?`dc`:``),n.media.push(this.createMediaDescriptionForSctp(t))),this.bundlePolicy!==`disable`){let e=n.media.map(e=>e.rtp.muxId).filter(e=>e);if(e.length){let t=new hj(`BUNDLE`,e);n.group.push(t)}}return n}buildAnswerSdp({transceivers:e,sctpTransport:t,signalingState:n}){if(![`have-remote-offer`,`have-local-pranswer`].includes(n))throw Error(`createAnswer failed`);if(!this._remoteDescription)throw Error(`wrong state`);let r=new pj;wj(`answer`,r);for(let n of this._remoteDescription.media){let i,a;if([`audio`,`video`].includes(n.kind)){let t=e.find(e=>e.mid===n.rtp.muxId);if(!t)throw Error(`Transceiver with mid=${n.rtp.muxId} not found`);a=this.createMediaDescriptionForTransceiver(t,fk(t.direction,t.offerDirection)),i=t.dtlsTransport}else if(n.kind===`application`){if(!t||!t.mid)throw Error(`sctpTransport not found`);a=this.createMediaDescriptionForSctp(t),i=t.dtlsTransport}else throw Error(`invalid kind`);a.dtlsParams&&(i.role===`auto`?a.dtlsParams.role=`client`:a.dtlsParams.role=i.role),n.simulcastParameters&&n.simulcastParameters.length>0&&(a.simulcastParameters=n.simulcastParameters.map(e=>({...e,direction:e.direction===`send`?`recv`:`send`}))),r.media.push(a)}if(this.bundlePolicy!==`disable`){let e=new hj(`BUNDLE`,[]);for(let t of r.media)t.rtp.muxId&&e.items.push(t.rtp.muxId);r.group.push(e)}return r}setLocalDescription(e){if(e.type===`offer`||e.type===`pranswer`){this.pendingLocalDescription=e;return}this.currentLocalDescription=e,this.pendingRemoteDescription&&(this.currentRemoteDescription=this.pendingRemoteDescription),this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0}setRemoteDescription(e,t){if(!e.type)throw Error(`invalid sessionDescription`);if(e.type===`rollback`){if(![`have-remote-offer`,`have-local-pranswer`].includes(t))throw zj(`InvalidStateError`,`Cannot rollback remote description in signaling state`);this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0;return}if(!e.sdp)throw Error(`invalid sessionDescription`);let n=this.parseSdp({sdp:e.sdp,isLocal:!1,signalingState:t,type:e.type});return n.type===`offer`||n.type===`pranswer`?this.pendingRemoteDescription=n:(this.pendingLocalDescription&&(this.currentLocalDescription=this.pendingLocalDescription),this.currentRemoteDescription=n,this.pendingRemoteDescription=void 0,this.pendingLocalDescription=void 0),n}rollbackLocalDescription(e){if(![`have-local-offer`,`have-local-pranswer`].includes(e))throw zj(`InvalidStateError`,`Cannot rollback local description in signaling state`);this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0}registerMid(e){this.seenMid.add(e)}get remoteIsBundled(){let e=this._remoteDescription;if(e)return e.group.find(e=>e.semantic===`BUNDLE`&&this.bundlePolicy!==`disable`)}setLocal(e,t,n){let r=new Map(t.map(e=>[e?.mLineIndex,e])),i=t.find(e=>e?.dtlsTransport)?.dtlsTransport??n?.dtlsTransport;e.media.filter(e=>[`audio`,`video`].includes(e.kind)).forEach((e,n)=>{let a=(r.get(n)??t[n])?.dtlsTransport??i;if(!a)throw Error(`dtls transport not found for media index ${n}`);this.addTransportDescription(e,a)});let a=e.media.find(e=>e.kind===`application`);n&&a&&this.addTransportDescription(a,n.dtlsTransport),this.setLocalDescription(e)}},Gj=sS(`werift:packages/webrtc/src/transport/secureTransportManager.ts`),Kj=class{connectionState=`new`;iceConnectionState=`new`;iceGatheringState=`new`;certificate;iceGatheringStateChange=new $;iceConnectionStateChange=new $;onIceCandidate=new $;connectionStateChange=new $;config;transceiverManager;sctpManager;constructor({config:e,transceiverManager:t,sctpManager:n}){if(this.config=e,this.transceiverManager=t,this.sctpManager=n,this.config.dtls){let{keys:e}=this.config.dtls;this.config.certificates[0]?this.certificate=this.config.certificates[0]:e&&this.setupCertificate(e)}}get dtlsTransports(){return[...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport].filter(e=>e!=null).reduce((e,t)=>(e.map(e=>e.id).includes(t.id)||e.push(t),e),[])}get iceTransports(){return this.dtlsTransports.map(e=>e.iceTransport)}setupCertificate(e){this.certificate=new zk(e.keyPem,e.certPem,e.signatureHash)}createTransport(){let e=this.iceTransports.find(e=>e.state!==`closed`),t=xk(this.config.iceServers),n=Sk({parsedTurnTransport:t.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP}),r=new Xk({...t,iceLite:this.config.iceLite,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,useTcp:this.config.iceUseTcp,turnTransport:n,turnTlsOptions:this.config.turnTlsOptions,useLinkLocalAddress:this.config.iceUseLinkLocalAddress});e&&(r.connection.localUsername=e.connection.localUsername,r.connection.localPassword=e.connection.localPassword),r.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let i=new Yk(r);return i.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new Rk(this.config,i,this.certificate,qj)}handleNewIceCandidate({candidate:e,media:t,remoteIsBundled:n,transceiver:r,sctpTransport:i,bundlePolicy:a}){return a===`max-bundle`||n?(e.sdpMLineIndex=0,t&&(e.sdpMid=t.rtp.muxId)):(r&&(e.sdpMLineIndex=r.mLineIndex,e.sdpMid=r.mid??void 0),i&&(e.sdpMLineIndex=i.mLineIndex,e.sdpMid=i.mid)),e.foundation&&!e.foundation.startsWith(`candidate:`)&&(e.foundation=`candidate:`+e.foundation),this.onIceCandidate.execute(e),e}async addIceCandidate(e,t){let n=t?.candidate,r=t?.sdpMid,i=t?.sdpMLineIndex,a=t?.usernameFragment,o=t==null||n==null||n===``,s=this.resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:o,sdpMid:r,sdpMLineIndex:i,usernameFragment:a});if(o){let t=s.map(t=>this.getTransportByMLineIndex(e,t)).filter(e=>!!e).reduce((e,t)=>(e.find(({id:e})=>e===t.id)||e.push(t),e),[]);return await Promise.all(t.map(e=>e.addRemoteCandidate(void 0))),{kind:`end-of-candidates`,mediaIndices:s}}let c=eA.fromJSON(t);if(!c)throw zj(`OperationError`,`Failed to parse ICE candidate`);let l=s[0],u=e.media[l];if(!u)throw zj(`OperationError`,`ICE media section not found`);c.sdpMid=u.rtp.muxId??void 0,c.sdpMLineIndex=l;let d=this.getTransportByMLineIndex(e,l);if(!d)throw zj(`OperationError`,`ICE transport not found for candidate`);return await d.addRemoteCandidate(c),{kind:`candidate`,candidate:c,mediaIndices:[l]}}resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:t,sdpMid:n,sdpMLineIndex:r,usernameFragment:i}){let a;if(typeof n==`string`){let t=e.media.findIndex(e=>e.rtp.muxId===n);if(t<0)throw zj(`OperationError`,`Media section for sdpMid was not found`);a=[t]}else if(typeof r==`number`){if(r<0||r>=e.media.length)throw zj(`OperationError`,`Media section for sdpMLineIndex was not found`);a=[r]}else if(t)a=e.media.map((e,t)=>t);else throw Bj(`sdpMid or sdpMLineIndex must be provided with a candidate`);if(typeof i==`string`){let t=a.filter(t=>e.media[t]?.iceParams?.usernameFragment===i);if(t.length===0)throw zj(`OperationError`,`No media section matched the ICE usernameFragment`);a=t}return a}getTransportByMid(e){if(!e)return;let t,n=this.transceiverManager.getTransceivers().find(t=>t.mid===e);return n?t=n.dtlsTransport.iceTransport:!t&&this.sctpManager.sctpTransport?.mid===e&&(t=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),t}getTransportByMLineIndex(e,t){let n=e.media[t];if(n)return this.getTransportByMid(n.rtp.muxId)}restartIce(){for(let e of this.iceTransports)e.restart()}setLocalRole({type:e,role:t}){for(let n of this.dtlsTransports){let r=n.iceTransport;r.connection.iceLite?r.connection.iceControlling=!1:r.connection.remoteIsLite||e===`offer`?r.connection.iceControlling=!0:r.connection.iceControlling=!1,e===`answer`&&t&&(n.role=t)}}updateIceGatheringState(){let e=this.iceTransports;function t(...t){return e.filter(e=>t.includes(e.gatheringState)).length===e.length}let n;n=e.length&&t(`complete`)?`complete`:!e.length||t(`new`,`complete`)?`new`:e.map(e=>e.gatheringState).includes(`gathering`)?`gathering`:`new`,this.iceGatheringState!==n&&(this.iceGatheringState=n,this.iceGatheringStateChange.execute(n))}updateIceConnectionState(){let e=this.iceTransports,t;function n(...t){return e.filter(e=>t.includes(e.state)).length===e.length}function r(...t){return e.some(e=>t.includes(e.state))}t=this.connectionState===`closed`?`closed`:r(`failed`)?`failed`:r(`disconnected`)?`disconnected`:n(`new`,`closed`)?`new`:r(`new`,`checking`)?`checking`:n(`completed`,`closed`)?`completed`:n(`connected`,`completed`,`closed`)?`connected`:`new`,this.iceConnectionState!==t&&(Gj(`iceConnectionStateChange`,t),this.iceConnectionState=t,this.iceConnectionStateChange.execute(t),t===`failed`&&this.connectionState!==`closed`?this.setConnectionState(`failed`):t===`disconnected`&&this.connectionState===`connected`&&this.setConnectionState(`disconnected`))}async gatherCandidates(e){let t=this.iceTransports.find(e=>e.state===`connected`||e.state===`completed`);e&&t?Gj(`skipping ICE gathering for bundled connection`):await Promise.allSettled(this.iceTransports.map(e=>e.gather())).catch(e=>{Gj(`gatherCandidates failed`,e)})}setConnectionState(e){this.connectionState!==e&&(Gj(`connectionStateChange`,e),this.connectionState=e,this.connectionStateChange.execute(e))}async getStats(e){let t=[];for(let n of this.dtlsTransports){let r=await n.getStats(e);r&&t.push(...r)}return t}async ensureCerts(){this.certificate||=await Rk.SetupCertificate();for(let e of this.dtlsTransports)e.localCertificate=this.certificate}async close(){this.setConnectionState(`closed`),await Promise.allSettled([...this.dtlsTransports.map(e=>e.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},qj=[qO.SRTP_AEAD_AES_128_GCM,qO.SRTP_AES128_CM_HMAC_SHA1_80],Jj=sS(`werift:packages/webrtc/src/peerConnection.ts`),Yj=class extends dO{id=l().toString();cname=l().toString();config=Zj();signalingState=`stable`;negotiationneeded=!1;needRestart=!1;router=new Aj;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;lastCreatedAnswer;lastCreatedOffer;pendingRemoteCandidates=[];iceGatheringStateChange=new $;iceConnectionStateChange=new $;signalingStateChange=new $;connectionStateChange=new $;onDataChannel=new $;onRemoteTransceiverAdded=new $;onTransceiverAdded=new $;onIceCandidate=new $;onNegotiationneeded=new $;onTrack=new $;eventHandlers={};get ondatachannel(){return this.eventHandlers.ondatachannel??null}set ondatachannel(e){this.eventHandlers.ondatachannel=e??void 0}get onicecandidate(){return this.eventHandlers.onicecandidate??null}set onicecandidate(e){this.eventHandlers.onicecandidate=e??void 0}get onicecandidateerror(){return this.eventHandlers.onicecandidateerror??null}set onicecandidateerror(e){this.eventHandlers.onicecandidateerror=e??void 0}get onicegatheringstatechange(){return this.eventHandlers.onicegatheringstatechange??null}set onicegatheringstatechange(e){this.eventHandlers.onicegatheringstatechange=e??void 0}get onnegotiationneeded(){return this.eventHandlers.onnegotiationneeded??null}set onnegotiationneeded(e){this.eventHandlers.onnegotiationneeded=e??void 0}get onsignalingstatechange(){return this.eventHandlers.onsignalingstatechange??null}set onsignalingstatechange(e){this.eventHandlers.onsignalingstatechange=e??void 0}get ontrack(){return this.eventHandlers.ontrack??null}set ontrack(e){this.eventHandlers.ontrack=e??void 0}get onconnectionstatechange(){return this.eventHandlers.onconnectionstatechange??null}set onconnectionstatechange(e){this.eventHandlers.onconnectionstatechange=e??void 0}get oniceconnectionstatechange(){return this.eventHandlers.oniceconnectionstatechange??null}set oniceconnectionstatechange(e){this.eventHandlers.oniceconnectionstatechange=e??void 0}constructor(e={}){super(),this.setConfiguration(e),this.sdpManager=new Wj({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new iM(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:e,streams:t,transceiver:n})=>{let r=new nM({track:e,streams:t,transceiver:n,receiver:n.receiver});this.onTrack.execute(e),this.emit(`track`,r),this.ontrack&&this.ontrack(r)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new Hj,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let t={type:`datachannel`,channel:e};this.ondatachannel?.(t),this.emit(`datachannel`,t)}),this.secureManager=new Kj({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.secureManager.iceGatheringStateChange.subscribe(e=>{this.iceGatheringStateChange.execute(e),this.onicegatheringstatechange?.(new globalThis.Event(`icegatheringstatechange`)),this.emit(`icegatheringstatechange`)}),this.secureManager.iceConnectionStateChange.subscribe(e=>{e===`closed`&&this.close(),this.iceConnectionStateChange.execute(e),this.oniceconnectionstatechange?.(),this.emit(`iceconnectionstatechange`)}),this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e),this.onconnectionstatechange?.(),this.emit(`connectionstatechange`)}),this.secureManager.onIceCandidate.subscribe(e=>{let t=e?e.toJSON():void 0;this.onIceCandidate.execute(t);let n={type:`icecandidate`,candidate:t};this.onicecandidate?.(n),this.emit(`icecandidate`,n)})}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 sctp(){return this.sctpTransport??null}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??null}get currentLocalDescription(){return this.sdpManager.currentLocalDescription?.toJSON()??null}get pendingLocalDescription(){return this.sdpManager.pendingLocalDescription?.toJSON()??null}get remoteDescription(){return this.sdpManager.remoteDescription??null}get currentRemoteDescription(){return this.sdpManager.currentRemoteDescription?.toJSON()??null}get pendingRemoteDescription(){return this.sdpManager.pendingRemoteDescription?.toJSON()??null}get canTrickleIceCandidates(){let e=this.sdpManager._remoteDescription;return e?[e.iceOptions,...e.media.map(e=>e.iceOptions)].filter(e=>!!e).join(` `).split(/\s+/).includes(`trickle`):null}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(e){let t=Qj(e),n=!!this.sdpManager;if(t.rtcpMuxPolicy&&t.rtcpMuxPolicy!==`require`)throw Error(`rtcpMuxPolicy must be require`);if(t.iceCandidatePoolSize!==void 0&&(!Number.isInteger(t.iceCandidatePoolSize)||t.iceCandidatePoolSize<0))throw Error(`iceCandidatePoolSize must be a non-negative integer`);if(n&&t.bundlePolicy!==void 0&&t.bundlePolicy!==this.config.bundlePolicy)throw Error(`bundlePolicy cannot be changed`);if(n&&t.rtcpMuxPolicy!==void 0&&t.rtcpMuxPolicy!==this.config.rtcpMuxPolicy)throw Error(`rtcpMuxPolicy cannot be changed`);if(n&&t.certificates!==void 0&&!eM(t.certificates,this.config.certificates))throw Error(`certificates cannot be changed`);if(n&&t.iceCandidatePoolSize!==void 0&&this.localDescription&&t.iceCandidatePoolSize!==this.config.iceCandidatePoolSize)throw Error(`iceCandidatePoolSize cannot be changed after setLocalDescription`);if((t.iceCandidatePoolSize??0)>0)throw Error(`iceCandidatePoolSize > 0 is not supported`);if(Ok(this.config,t),this.config.icePortRange){let[e,t]=this.config.icePortRange;if(e===t)throw Error(`should not be same value`);if(e>=t)throw Error(`The min must be less than max`)}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw Error(`maxMessageSize must be a non-negative integer`);this.sctpManager?.sctpTransport&&(this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize);for(let[e,t]of lO([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(t.payloadType==null)switch(t.payloadType=96+e,t.name.toLowerCase()){case`rtx`:t.parameters=`apt=${t.payloadType-1}`;break;case`red`:if(t.contentType===`audio`){let e=t.payloadType+1;t.parameters=`${e}/${e}`,t.payloadType=63}}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,t)=>{e.id=1+t})}getConfiguration(){return tM(this.config)}async createOffer({iceRestart:e}={}){(e||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let e of this.transceiverManager.getTransceivers())e.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(e),e.headerExtensions.length===0&&(e.headerExtensions=this.config.headerExtensions[e.kind]??[]);let t=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON();return this.lastCreatedOffer=t,t}createSctpTransport(){let e=this.sctpManager.createSctpTransport(this.config.maxMessageSize),t=this.findOrCreateTransport();return e.setDtlsTransport(t),e}createDataChannel(e,t={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let n=this.sctpManager.createDataChannel(e,t);if(!n.sctp.dtlsTransport){let e=this.findOrCreateTransport();n.sctp.setDtlsTransport(e)}return n}removeTrack(e){if(this.isClosed)throw zj(`InvalidStateError`,`peer closed`);this.transceiverManager.removeTrack(e),this.needNegotiation()}needNegotiation=async()=>{this.invalidateLastCreatedDescriptions(),this.shouldNegotiationneeded=!0,!(this.negotiationneeded||this.signalingState!==`stable`)&&(this.shouldNegotiationneeded=!1,setImmediate(()=>{this.negotiationneeded=!0,this.onNegotiationneeded.execute(),this.onnegotiationneeded&&this.onnegotiationneeded(new globalThis.Event(`negotiationneeded`)),this.emit(`negotiationneeded`)}))};invalidateLastCreatedDescriptions(){this.lastCreatedAnswer=void 0,this.lastCreatedOffer=void 0}async waitForPendingDescriptionTask(){this.assertNotClosed(),await Promise.resolve(),this.isClosed&&await new Promise(()=>void 0)}findOrCreateTransport(){let e=this.dtlsTransports.find(e=>e.state!==`closed`);if(e?.iceTransport,(this.sdpManager.bundlePolicy===`max-bundle`||this.sdpManager.bundlePolicy!==`disable`&&this.remoteIsBundled)&&e)return e;let t=this.secureManager.createTransport();t.onRtp.subscribe(e=>{this.router.routeRtp(e)}),t.onRtcp.subscribe(e=>{this.router.routeRtcp(e)});let n=t.iceTransport;return n.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),n.onIceCandidate.subscribe(e=>{if(!this.localDescription){Jj(`localDescription not found when ice candidate was gathered`);return}if(!e){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){Jj(`localDescription not found when ice candidate was gathered`);return}this.secureManager.handleNewIceCandidate({candidate:e,bundlePolicy:this.sdpManager.bundlePolicy,remoteIsBundled:!!this.sdpManager.remoteIsBundled,media:this._localDescription.media[0],transceiver:this.transceiverManager.getTransceivers().find(e=>e?.dtlsTransport?.iceTransport.id===n.id),sctpTransport:this.sctpTransport?.dtlsTransport.iceTransport.id===n.id?this.sctpTransport:void 0})}),t}async setLocalDescription(e){let t=[`stable`,`have-local-offer`,`have-remote-pranswer`];if(await this.waitForPendingDescriptionTask(),e?.type===`rollback`){this.sdpManager.rollbackLocalDescription(this.signalingState),this.setSignalingState(`stable`),this.shouldNegotiationneeded&&this.needNegotiation(),this.invalidateLastCreatedDescriptions();return}let n=!e?.type||!e.sdp||e.sdp.length===0?e?.type===`offer`?this.lastCreatedOffer??await this.createOffer():e?.type===`answer`||e?.type===`pranswer`?this.lastCreatedAnswer??await this.createAnswer():t.includes(this.signalingState)?this.lastCreatedOffer??await this.createOffer():this.lastCreatedAnswer??await this.createAnswer():void 0;if(e={type:e?.type??n.type,sdp:e?.sdp&&e.sdp.length>0?e.sdp:n.sdp},e.type===`offer`&&this.lastCreatedOffer&&e.sdp!==this.lastCreatedOffer.sdp)throw zj(`InvalidModificationError`,`setLocalDescription must use the latest created offer`);let r=e.type,i=e.sdp,a=this.sdpManager.parseSdp({sdp:i,isLocal:!0,signalingState:this.signalingState,type:r});a.type===`offer`?this.setSignalingState(`have-local-offer`):a.type===`answer`?this.setSignalingState(`stable`):a.type===`pranswer`&&this.setSignalingState(`have-local-pranswer`);for(let[e,t]of lO(a.media)){let n=t.rtp.muxId;if(this.sdpManager.registerMid(n),[`audio`,`video`].includes(t.kind)){let t=this.transceiverManager.getTransceiverByMLineIndex(e);t&&(t.mid=n)}t.kind===`application`&&this.sctpTransport&&(this.sctpTransport.mid=n)}let o=a.media.find(e=>e.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:a.type===`offer`?`offer`:`answer`,role:o}),[`answer`,`pranswer`].includes(a.type))for(let e of this.transceiverManager.getTransceivers()){let t=fk(e.direction,e.offerDirection);e.setCurrentDirection(t)}return this.sdpManager.setLocal(a,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(e=>{Jj(`gatherCandidates failed`,e)}),a.type===`answer`&&this.connect().catch(e=>{Jj(`connect failed`,e),this.secureManager.setConnectionState(`failed`)}),this.sdpManager.setLocal(a,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),this.invalidateLastCreatedDescriptions(),a}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(e={}){if(this.isClosed)throw zj(`InvalidStateError`,`is closed`);if(!this.remoteDescription||!this.sdpManager._remoteDescription){this.pendingRemoteCandidates.push(e);return}await this.applyRemoteIceCandidate(e)}async applyRemoteIceCandidate(e){let t=this.sdpManager._remoteDescription;if(!t)return;let n=await this.secureManager.addIceCandidate(t,e),r=this.sdpManager._remoteDescription;if(r&&n){if(n.kind===`end-of-candidates`){for(let e of n.mediaIndices){let t=r.media[e];t&&(t.iceCandidatesComplete=!0)}return}for(let e of n.mediaIndices){let t=r.media[e];t&&t.iceCandidates.push(n.candidate)}}}async flushPendingRemoteCandidates(){for(;this.pendingRemoteCandidates.length>0&&this.remoteDescription&&this.sdpManager._remoteDescription;){let e=this.pendingRemoteCandidates.shift();await this.applyRemoteIceCandidate(e??null)}}async connect(){Jj(`start connect`),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:t}=e;t.state!==`connected`&&(this.secureManager.setConnectionState(`connecting`),await t.start().catch(e=>{throw Jj(`iceTransport.start failed`,e),e}),e.state!==`connected`&&(await e.start().catch(e=>{throw Jj(`dtlsTransport.start failed`,e),e}),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(e){e instanceof pj&&(e=e.toSdp()),await this.waitForPendingDescriptionTask(),e.type===`offer`&&[`have-local-offer`,`have-local-pranswer`].includes(this.signalingState)&&(this.sdpManager.rollbackLocalDescription(this.signalingState),this.shouldNegotiationneeded=!0,this.setSignalingState(`stable`),await Promise.resolve());let t=this.sdpManager.setRemoteDescription(e,this.signalingState);if(!t){this.setSignalingState(`stable`),this.shouldNegotiationneeded&&this.needNegotiation(),this.invalidateLastCreatedDescriptions();return}let n,r=(e,t)=>e.kind===t.kind&&[null,t.rtp.muxId].includes(e.mid),i=t.media.map((i,a)=>{let o;if([`audio`,`video`].includes(i.kind)){let s=this.transceiverManager.getTransceivers().find(e=>r(e,i));if(!s)s=this.addTransceiver(i.kind,{direction:`recvonly`}),s.mid=i.rtp.muxId??null,this.onRemoteTransceiverAdded.execute(s);else if(s.direction===`inactive`&&s.stopping){s.stopped=!0,e.type===`answer`&&s.setCurrentDirection(`inactive`);return}this.sdpManager.remoteIsBundled&&(n?s.setDtlsTransport(n):n=s.dtlsTransport),o=s.dtlsTransport,this.transceiverManager.setRemoteRTP(s,i,t.type,a)}else if(i.kind===`application`){let e=this.sctpTransport;e||(e=this.createSctpTransport(),e.mid=i.rtp.muxId),this.sdpManager.remoteIsBundled&&(n?e.setDtlsTransport(n):n=e.dtlsTransport),o=e.dtlsTransport,this.sctpManager.setRemoteSCTP(i,a)}else throw Error(`invalid media kind`);let s=o.iceTransport;if(i.iceParams){let e=!!this.sdpManager.inactiveRemoteMedia;s.setRemoteParams(i.iceParams,e),i.iceParams.iceLite&&!s.connection.iceLite&&(s.connection.iceControlling=!0)}return i.dtlsParams&&o.setRemoteParams(i.dtlsParams),i.iceCandidates.forEach(s.addRemoteCandidate),i.iceCandidatesComplete&&s.addRemoteCandidate(void 0),t.type===`answer`&&i.dtlsParams?.role&&(o.role=i.dtlsParams.role===`client`?`server`:`client`),s});i=i.filter(e=>!!e);let a=this.transceiverManager.getTransceivers().filter(e=>t.media.find(t=>r(e,t))==null);if(e.type===`answer`)for(let e of a)e.stop(),e.stopped=!0;t.type===`offer`?this.setSignalingState(`have-remote-offer`):t.type===`answer`?this.setSignalingState(`stable`):t.type===`pranswer`&&this.setSignalingState(`have-remote-pranswer`),await this.flushPendingRemoteCandidates(),t.type===`answer`&&(Jj(`caller start connect`),this.connect().catch(e=>{Jj(`connect failed`,e),this.secureManager.setConnectionState(`failed`)})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation(),this.invalidateLastCreatedDescriptions()}addTransceiver(e,t={}){let n=this.findOrCreateTransport(),r=this.transceiverManager.addTransceiver(e,n,t);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),r}addTrack(e,...t){if(this.isClosed)throw zj(`InvalidStateError`,`is closed`);let n=this.transceiverManager.addTrack(e,t);if(!n.dtlsTransport){let e=this.findOrCreateTransport();n.setDtlsTransport(e)}return this.needNegotiation(),n.sender}async createAnswer(){this.assertNotClosed(),await this.secureManager.ensureCerts();let e=this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON();return this.lastCreatedAnswer=e,e}assertNotClosed(){if(this.isClosed)throw zj(`InvalidStateError`,`RTCPeerConnection is closed`)}setSignalingState(e){this.signalingState!==e&&(Jj(`signalingStateChange`,e),this.signalingState=e,this.signalingStateChange.execute(e),this.onsignalingstatechange&&this.onsignalingstatechange(new globalThis.Event(`signalingstatechange`)),this.emit(`signalingstatechange`))}createPeerConnectionStats(e){return{type:`peer-connection`,id:ZO(`peer-connection`,this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){let t=$O(),n=[];e||n.push(this.createPeerConnectionStats(t)),n.push(...this.transceiverManager.collectStats(t));let r=await this.secureManager.getStats(t);if(n.push(...r),!e&&this.sctpTransport){let e=await this.sctpManager.getStats(t);e&&n.push(...e)}return e?tk(n,this.transceiverManager.getStatsRootIds(e)):tk(n)}async close(){this.isClosed||(this.isClosed=!0,this.pendingRemoteCandidates.length=0,this.setSignalingState(`closed`),this.transceiverManager.close(),await this.secureManager.close(),await this.sctpManager.close(),this.completePeerEvents(),Jj(`peerConnection closed`))}completePeerEvents(){let e=[this.onDataChannel,this.iceGatheringStateChange,this.iceConnectionStateChange,this.signalingStateChange,this.connectionStateChange,this.onTransceiverAdded,this.onRemoteTransceiverAdded,this.onIceCandidate,this.onNegotiationneeded];for(let t of e)t.ended||t.complete()}},Xj=(e,t)=>e.find(e=>e.mimeType.toLowerCase()===t.mimeType.toLowerCase())?t:void 0;function Zj(){return{codecs:{audio:[AO(),jO()],video:[DO()]},headerExtensions:{audio:[],video:[]},iceTransportPolicy:`all`,iceLite:!1,iceServers:[{urls:`stun:stun.l.google.com:19302`}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceUseTcp:!1,turnTransport:void 0,turnTlsOptions:void 0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:`max-compat`,rtcpMuxPolicy:`require`,iceCandidatePoolSize:0,certificates:[],debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:lj}}Zj();function Qj(e){let t=Object(e??{}),n={...t};if(t.bundlePolicy===`balanced`&&(n.bundlePolicy=`max-compat`),`certificates`in t){if(t.certificates===void 0)n.certificates=void 0;else if(!Array.isArray(t.certificates)||t.certificates.some(e=>e==null))throw Bj(`certificates must be an array of RTCCertificate`);else n.certificates=[...t.certificates]}return`iceCandidatePoolSize`in t&&(n.iceCandidatePoolSize=$j(t.iceCandidatePoolSize,`iceCandidatePoolSize`)),n}function $j(e,t){let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw Bj(`${t} must be an unsigned short`);return n}function eM(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function tM(e){return{...e,codecs:{audio:e.codecs.audio?[...e.codecs.audio]:void 0,video:e.codecs.video?[...e.codecs.video]:void 0},headerExtensions:{audio:e.headerExtensions.audio?[...e.headerExtensions.audio]:void 0,video:e.headerExtensions.video?[...e.headerExtensions.video]:void 0},iceServers:e.iceServers.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),icePortRange:e.icePortRange?[...e.icePortRange]:void 0,iceAdditionalHostAddresses:e.iceAdditionalHostAddresses?[...e.iceAdditionalHostAddresses]:void 0,dtls:{...e.dtls},certificates:[...e.certificates],debug:{...e.debug}}}var nM=class{type=`track`;track;streams;transceiver;receiver;constructor(e){this.track=e.track,this.streams=[...e.streams],this.transceiver=e.transceiver,this.receiver=e.receiver}},rM=sS(`werift:packages/webrtc/src/media/rtpTransceiverManager.ts`),iM=class{constructor(e,t,n){this.cname=e,this.config=t,this.router=n}transceivers=[];onTransceiverAdded=new $;onRemoteTransceiverAdded=new $;onTrack=new $;onNegotiationNeeded=new $;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(e=>e.sender)}getReceivers(){return this.getTransceivers().map(e=>e.receiver)}getTransceiverByMLineIndex(e){return this.transceivers.find(t=>t.mLineIndex===e)}pushTransceiver(e){this.transceivers.push(e)}replaceTransceiver(e,t){this.transceivers[t]=e}addTransceiver(e,t,n={}){let r=typeof e==`string`?e:e.kind,i=n.direction||`sendrecv`,a=new Rj(e),o=new nk(r,t,new Oj(this.config,r,a.ssrc),a,i);o.options=n,o.sender.setStreams(n.streams??[]),o.sender.setSendEncodings((n.sendEncodings??[]).map(e=>({...e}))),this.router.registerRtpSender(o.sender);let s=this.transceivers.findIndex(e=>e.currentDirection===`inactive`&&!e.usedForSender),c=this.transceivers.find(e=>e.currentDirection===`inactive`&&!e.usedForSender);return s>-1&&c?(this.replaceTransceiver(o,s),o.mLineIndex=c.mLineIndex,o.mid=c.mid,c.setCurrentDirection(void 0)):this.pushTransceiver(o),this.onTransceiverAdded.execute(o),o}addTrack(e,t=[]){if(this.getSenders().find(t=>t.track?.uuid===e.uuid))throw zj(`InvalidAccessError`,`Track already added`);let n=this.transceivers.find(t=>t.sender.track==null&&t.kind===e.kind&&JO.includes(t.direction)===!0);if(n){let r=n.sender;return r.setStreams(t),r.registerTrack(e),n.options={...n.options,streams:t},n}let r=this.transceivers.find(t=>t.sender.track==null&&t.kind===e.kind&&JO.includes(t.direction)===!1&&!t.usedForSender);if(r){let n=r.sender;switch(n.setStreams(t),n.registerTrack(e),r.options={...r.options,streams:t},r.direction){case`recvonly`:r.setDirection(`sendrecv`);break;case`inactive`:r.setDirection(`sendonly`)}return r}return this.addTransceiver(e,void 0,{direction:`sendrecv`,streams:t})}removeTrack(e){if(!this.getSenders().find(({ssrc:t})=>e.ssrc===t))throw zj(`InvalidAccessError`,`Sender does not exist`);let t=this.transceivers.find(({sender:{ssrc:t}})=>e.ssrc===t);if(!t)throw Error(`No matching transceiver found`);if(!(t.stopping||t.stopped)){if(e.stop(),[`recvonly`,`inactive`].includes(t.currentDirection??``)){this.onNegotiationNeeded.execute();return}t.direction===`sendrecv`?t.setDirection(`recvonly`):(t.direction===`sendonly`||t.direction===`recvonly`)&&t.setDirection(`inactive`)}}assignTransceiverCodecs(e){e.codecs=this.config.codecs[e.kind].filter(t=>{switch(t.direction){case`recvonly`:return!!YO.includes(e.direction);case`sendonly`:return!!JO.includes(e.direction);case`sendrecv`:return!![`sendrecv`,`recvonly`,`sendonly`].includes(e.direction);case`all`:return!0;default:return!1}})}getLocalRtpParams(e){if(e.mid==null)throw Error(`mid not assigned`);return{codecs:e.codecs,muxId:e.mid,headerExtensions:e.headerExtensions,rtcp:{cname:this.cname,ssrc:e.sender.ssrc,mux:!0}}}getRemoteRtpParams(e,t){return{muxId:e.rtp.muxId,rtcp:e.rtp.rtcp,codecs:t.codecs,headerExtensions:t.headerExtensions,encodings:Object.values(t.codecs.reduce((t,n)=>{if(n.name.toLowerCase()===`rtx`){let r=t[Tj(n.parameters??``).apt];return r&&e.ssrc.length===2&&(r.rtx=new CO({ssrc:e.ssrc[1].ssrc})),t}return t[n.payloadType]=new wO({ssrc:e.ssrc[0]?.ssrc,payloadType:n.payloadType}),t},{}))}}setRemoteRTP(e,t,n,r){if(e.mid||=t.rtp.muxId??null,e.mLineIndex=r,e.codecs=t.rtp.codecs.filter(e=>{let n=this.config.codecs[t.kind]||[],r=Xj(n,e);if(!r)return!1;if(r?.name.toLowerCase()===`rtx`){let e=Tj(r.parameters??``).apt,i=t.rtp.codecs.find(t=>t.payloadType===e);return i?!!Xj(n,i):!1}return!0}),rM(`negotiated codecs`,e.codecs),e.codecs.length===0)throw Error(`negotiate codecs failed.`);e.headerExtensions=t.rtp.headerExtensions.filter(e=>(this.config.headerExtensions[t.kind]||[]).find(t=>t.uri===e.uri));let i=t.direction??`inactive`,a=pk(i);[`answer`,`pranswer`].includes(n)?e.setCurrentDirection(a):e.offerDirection=a;let o=this.getLocalRtpParams(e);if(e.sender.prepareSend(o),[`recvonly`,`sendrecv`].includes(e.direction)){let n=this.getRemoteRtpParams(t,e);for(let r of t.simulcastParameters)this.router.registerRtpReceiverByRid(e,r,n);e.receiver.prepareReceive(n),this.router.registerRtpReceiverBySsrc(e,n)}if(t.port!==0&&[`sendonly`,`sendrecv`].includes(i)){let n=[...new Set(t.msids.map(e=>e.split(` `)[0]))],r=t.msids[0]?.split(` `)[1];e.receiver.remoteStreamId=n[0],e.receiver.remoteStreamIds=n,e.receiver.remoteTrackId=r,this.onTrack.execute({track:e.receiver.track,transceiver:e,streams:n.map(t=>new ak({id:t,tracks:[e.receiver.track]}))})}t.ssrc[0]?.ssrc&&e.receiver.setupTWCC(t.ssrc[0].ssrc)}collectStats(e){let t=[];for(let n of this.transceivers){n.sender&&t.push(...n.sender.collectStats(e)),n.receiver&&t.push(...n.receiver.collectStats(e));let r=n.collectCodecStats(e);r&&t.push(...r)}return t}getStatsRootIds(e){if(!e)return[];let t=[];for(let n of this.transceivers)n.sender.track===e&&t.push(...n.sender.getStatsRootIds()),n.receiver.tracks.includes(e)&&t.push(...n.receiver.getStatsRootIds(e));return t}close(){for(let e of this.transceivers)e.forceStop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}};function aM(e){return new Proxy(e,{get(e,t){if(t===`send`)return t=>e.send(typeof t==`string`?t:Buffer.from(t));let n=Reflect.get(e,t,e);return typeof n==`function`?n.bind(e):n},set(e,t,n){return t===`onmessage`&&n?(e.onmessage=e=>n({data:typeof e.data==`string`?e.data:Uint8Array.from(e.data).buffer}),!0):Reflect.set(e,t,n,e)}})}function oM(){let e=new Set,t=new WeakMap,n=!1,r=!1,i;function a(n){let a=t.get(n);if(a)return a;let o=n.close();return t.set(n,o),o.then(()=>e.delete(n),t=>{r||(i=t),r=!0,e.delete(n)}),o}return{createPeerConnection(t){if(n)throw Error(`Native room transport is closed`);let r=new Yj({iceServers:t.iceServers?.map(e=>({urls:e.urls})),bundlePolicy:t.bundlePolicy});return e.add(r),new Proxy(r,{get(e,t){if(t===`close`)return()=>a(e);if(t===`createDataChannel`)return(...t)=>aM(e.createDataChannel(...t));let n=Reflect.get(e,t,e);return typeof n==`function`?n.bind(e):n},set(e,t,n){return t===`ondatachannel`&&n?(e.ondatachannel=e=>n({channel:aM(e.channel)}),!0):Reflect.set(e,t,n,e)}})},async close(){if(n=!0,await Promise.allSettled([...e].map(a)),r)throw i}}}function sM(e){return Qn(e)}function cM(e){if(typeof e!=`string`)throw TypeError(`Stadium source must be a string`);let t=Cn(e);return Object.freeze({name:t.name,canBeStored:t.canBeStored,warnings:Object.freeze([...t.warnings])})}async function lM(e,n={}){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Room configuration must be an object`);let{serviceOrigin:r,apiKey:i,...a}=e;if(typeof i!=`string`||!/^b2d_[0-9a-f]{64}$/.test(i))throw TypeError(`A valid API key is required.`);n.signal?.throwIfAborted();let o=kn(r??`https://ball2d.com`),s=Fr(a),c=oM(),l=crypto.randomUUID(),u=new AbortController,d,f,p=e=>{u.abort(Error(e));try{let t=f?.onError?.(e);t instanceof Promise&&t.catch(()=>{})}catch{}f?.close()},m,h,g=new Promise((e,t)=>{m=e,h=t});g.catch(()=>{});try{let e=await Pr.create(s,{network:{serviceOrigin:o,signalingResume:!0,createWebSocket:e=>new WebSocket(e),createPeerConnection:c.createPeerConnection},request:async(e,t)=>{let n=new URL(e);if(n.origin===o&&n.pathname===re.rooms&&t?.method===`POST`){let e=new Headers(t.headers);e.set(`Authorization`,`Bearer ${i}`),e.set(`Idempotency-Key`,l);let n=performance.now(),r=await fetch(new URL(re.sdkRooms,o),{...t,headers:e,redirect:`error`});if(r.status===401)throw await r.body?.cancel(),Error(`API key is invalid, expired or revoked. Create a key from your Ball2D account.`);if(r.ok){let e=await r.clone().json();d=new ae(o,i,e.id,e.lease,n,p)}return r}return fetch(e,t)},loadEngine:async e=>Dn.create(await t(new URL(`./core.wasm`,import.meta.url),{signal:e})),loadStadium:Pn(async e=>new Response(await t(new URL(`.${e}`,import.meta.url),`utf8`)))},AbortSignal.any([u.signal,...n.signal?[n.signal]:[]]));if(f=e,n.signal?.throwIfAborted(),!d)throw Error(`Missing room authorization`);u.signal.throwIfAborted();let r=()=>{queueMicrotask(()=>{Promise.allSettled([c.close(),d?.stop()]).then(e=>{let t=e.find(e=>e.status===`rejected`);t?.status===`rejected`?h(t.reason):m()})})};return e.signal.addEventListener(`abort`,r,{once:!0}),e.signal.aborted?r():d.start(),Rr(e,g)}catch(e){let t=(await Promise.allSettled([()=>f?.close(),()=>d?.stop(),()=>c.close()].map(e=>Promise.resolve().then(e)))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);throw t.length?AggregateError([e,...t],`Room creation and cleanup failed`,{cause:e}):e}}export{lM as createRoom,sM as readReplay,cM as validateStadium};
|
|
145
|
+
`)),r.forEach(e=>{e.startsWith(`m=`)?n.push([e]):n.length>0?n[n.length-1].push(e):t.push(e)}),[t,n]}function $R(e){if(e.includes(`:`)){let t=UF(e.slice(2),`:`);return[t[0],t[1]]}return[e.slice(2),void 0]}function ez(e,t,n=e=>e.toString()){let r=t.split(` `);r.length>0&&e.push(new JR(r[0],r.slice(1).map(n)))}function tz(e){return AL(lF.fromSdp(e))}var nz=class{sdp;type;constructor(e,t){Object.defineProperties(this,{sdp:{configurable:!0,enumerable:!0,value:e,writable:!1},type:{configurable:!0,enumerable:!0,value:t,writable:!1}})}static isThis(e){if(typeof e?.sdp==`string`)return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};function rz(e,t){t.origin=`- ${c(8).readBigUInt64BE(0).toString().slice(0,8)} 0 IN IP4 0.0.0.0`,t.msidSemantic.push(new JR(`WMS`,[`*`])),t.type=e}function iz(e){let t={};return e.split(`;`).forEach(e=>{if(e.includes(`=`)){let[n,r]=UF(e,`=`);wI.includes(n)?t[n]=Number(r):t[n]=r}else if(e.includes(`:`)){let[n,r]=e.split(`:`);t[n]=Number.isNaN(Number(r))?r:Number(r)}else t[e]=void 0}),t}var az=class{ssrc;cname;msid;msLabel;label;constructor(e){Object.assign(this,e)}},oz=Bk(`werift:packages/webrtc/src/media/rtpReceiver.ts`),sz=class{constructor(e,t,n){this.config=e,this.kind=t,this.rtcpSsrc=n,this.defaultTrack=new LI({kind:t,remote:!0}),this.onPacketLost.subscribe(e=>{this.nackCountBySsrc[e.mediaSourceSsrc]=(this.nackCountBySsrc[e.mediaSourceSsrc]??0)+1})}codecs={};defaultTrack;get codecArray(){return Object.values(this.codecs).sort((e,t)=>e.payloadType-t.payloadType)}ssrcByRtx={};nack=new uL(this);audioRedHandler=new EM;type=`receiver`;uuid=l().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new $;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteStreamIds=[];remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};senderReportsReceivedBySsrc={};remoteTimestampsBySsrc={};remotePacketCountBySsrc={};remoteOctetCountBySsrc={};nackCountBySsrc={};pliCountBySsrc={};get transport(){return this.dtlsTransport??null}setDtlsTransport(e){this.dtlsTransport=e}get track(){return this.tracks[0]??this.defaultTrack}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===`nack`)}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===QF().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===XF().type)}prepareReceive(e){e.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),e.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(e){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new fL(this.dtlsTransport,this.rtcpSsrc,e))}addTrack(e){return!this.tracks.find(t=>{if(t.rid)return t.rid===e.rid;if(t.ssrc)return t.ssrc===e.ssrc})&&(this.tracks.push(e),e.ssrc&&(this.trackBySSRC[e.ssrc]=e),e.rid&&(this.trackByRID[e.rid]=e),!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 E(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let e=Object.entries(this.remoteStreams).map(([e,t])=>{let n=0,r=0;if(this.lastSRtimestamp[e]){n=this.lastSRtimestamp[e];let t=XI()-this.receiveLastSRTimestamp[e];t>0&&t<65536&&(r=Ik(t*65536))}return new Hj({ssrc:Number(e),fractionLost:t.fraction_lost,packetsLost:t.packets_lost,highestSequence:t.max_seq,jitter:t.jitter,lsr:n,dlsr:r})}),t=new Vj({ssrc:this.rtcpSsrc,reports:e});try{this.config.debug.receiverReportDelay&&await E(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([t])}catch(e){oz(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}getInboundRtpStatsId(e){return AI(`inbound-rtp`,e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return AI(`remote-outbound-rtp`,e.id??e.uuid)}getStatsRootIds(e){return this.tracks.filter(t=>!e||t===e).filter(e=>e.ssrc).map(e=>this.getInboundRtpStatsId(e))}collectStats(e){let t=[],n=this.dtlsTransport?AI(`transport`,this.dtlsTransport.id):void 0,r=this.codecArray[0],i=new Set;for(let a of this.tracks){if(!a.ssrc)continue;let o=this.remoteStreams[a.ssrc],s=this.remoteTimestampsBySsrc[a.ssrc]!==void 0,c=this.lastSRtimestamp[a.ssrc]!==void 0||s?this.getRemoteOutboundRtpStatsId(a):void 0,l=r&&n?jI(n,r.payloadType,a.id??a.uuid):void 0;if(r&&n&&l&&!i.has(l)){i.add(l);let a={type:`codec`,id:l,timestamp:e,payloadType:r.payloadType,transportId:n,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,sdpFmtpLine:r.parameters};t.push(a)}let u={type:`inbound-rtp`,id:this.getInboundRtpStatsId(a),timestamp:e,ssrc:a.ssrc,kind:this.kind,transportId:n,codecId:l,mid:this.sdesMid,trackIdentifier:a.id??a.uuid,packetsReceived:o?.packets_received??0,bytesReceived:o?.bytesReceived??0,headerBytesReceived:o?.headerBytesReceived??0,packetsLost:o?.packets_lost??0,jitter:o?.clockRate?o.jitter/o.clockRate:void 0,lastPacketReceivedTimestamp:o?.lastPacketReceivedTimestamp,remoteId:c,nackCount:this.nackCountBySsrc[a.ssrc]||void 0,pliCount:this.pliCountBySsrc[a.ssrc]||void 0};if(t.push(u),c){let r={type:`remote-outbound-rtp`,id:this.getRemoteOutboundRtpStatsId(a),timestamp:e,ssrc:a.ssrc,kind:this.kind,transportId:n,codecId:u.codecId,localId:u.id,remoteTimestamp:this.remoteTimestampsBySsrc[a.ssrc],reportsSent:this.senderReportsReceivedBySsrc[a.ssrc]??0,packetsSent:this.remotePacketCountBySsrc[a.ssrc],bytesSent:this.remoteOctetCountBySsrc[a.ssrc]};t.push(r)}}return t}async getStats(){let e=MI(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),PI(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){oz(`pli not supported`,{mediaSsrc:e});return}if(this.stopped)return;oz(`sendRtcpPLI`,{mediaSsrc:e});let t=new Bj({feedback:new Lj({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1,await this.dtlsTransport.sendRtcp([t])}catch(e){oz(e)}}handleRtcpPacket(e){switch(e.type){case rM.type:{let t=e;this.lastSRtimestamp[t.ssrc]=$I(t.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[t.ssrc]=XI(),this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1,this.remoteTimestampsBySsrc[t.ssrc]=QI(t.senderInfo.ntpTimestamp),this.remotePacketCountBySsrc[t.ssrc]=t.senderInfo.packetCount,this.remoteOctetCountBySsrc[t.ssrc]=t.senderInfo.octetCount;let n=this.trackBySSRC[e.ssrc];n&&n.onReceiveRtcp.execute(e)}}this.onRtcp.execute(e)}handleRtpBySsrc=(e,t)=>{let n=this.trackBySSRC[e.header.ssrc];this.handleRTP(e,t,n)};handleRtpByRid=(e,t,n)=>{let r=this.trackByRID[t];this.trackBySSRC[e.header.ssrc]||(this.trackBySSRC[e.header.ssrc]=r),this.handleRTP(e,n,r)};handleRTP(e,t,n){if(this.stopped)return;let r=this.codecs[e.header.payloadType];if(!r)return;if(this.remoteStreams[e.header.ssrc]=this.remoteStreams[e.header.ssrc]??new pL(r.clockRate),this.remoteStreams[e.header.ssrc].add(e),this.receiverTWCC){let e=t[lM.transportWideCC];if(!e==null)throw Error(`undefined`);this.receiverTWCC.handleTWCC(e)}else this.twccEnabled&&this.setupTWCC(e.header.ssrc);if(r.name.toLowerCase()===`rtx`){let t=this.ssrcByRtx[e.header.ssrc],i=iz(r.parameters??``),a=this.codecs[i.apt];if(e.payload.length<2)return;e=FM(e,a.payloadType,t),n=this.trackBySSRC[t]}let i;if(!(r.name.toLowerCase()===`red`&&(i=SM.deSerialize(e.payload),!Object.keys(this.codecs).includes(i.header.fields[0].blockPT.toString())))){if(n?.kind===`video`&&this.nackEnabled&&this.nack.addPacket(e),n){if(i){if(n.kind===`audio`){let r=this.audioRedHandler.push(i,e);for(let e of r)n.onReceiveRtp.execute(e.clone(),t)}}else n.onReceiveRtp.execute(e.clone(),t)}this.runRtcp()}}},cz=Bk(`werift:packages/webrtc/src/media/router.ts`),lz=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){cz(`registerRtpReceiver`,t),this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){cz(`registerRtpReceiverBySsrc`,t),t.encodings.filter(e=>e.ssrc!=null).forEach((n,r)=>{this.registerRtpReceiver(e.receiver,n.ssrc),e.addTrack(new LI({ssrc:n.ssrc,kind:e.kind,id:e.sender.trackId,remote:!0,codec:t.codecs[r]})),n.rtx&&this.registerRtpReceiver(e.receiver,n.rtx.ssrc)}),t.headerExtensions.forEach(e=>{this.extIdUriMap[e.id]=e.uri})}registerRtpReceiverByRid(e,t,n){let[r]=n.codecs;cz(`registerRtpReceiverByRid`,t),e.addTrack(new LI({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:!0,codec:r})),this.ridTable[t.rid]=e.receiver}routeRtp=e=>{let t=uM(e.header.extensions,this.extIdUriMap),n=this.ssrcTable[e.header.ssrc],r=t[lM.sdesRTPStreamID];if(typeof r==`string`?(n=this.ridTable[r],n.latestRid=r,n.handleRtpByRid(e,r,t)):n?n.handleRtpBySsrc(e,t):(n=Object.values(this.ridTable).filter(e=>e instanceof sz).find(t=>t.trackBySSRC[e.header.ssrc]),n&&(cz(`simulcast register receiver by ssrc`,e.header.ssrc),this.registerRtpReceiver(n,e.header.ssrc),n.handleRtpBySsrc(e,t))),!n){cz(`ssrcReceiver not found`);return}let i=t[lM.sdesMid];typeof i==`string`&&(n.sdesMid=i);let a=t[lM.repairedRtpStreamId];typeof a==`string`&&(n.latestRepairedRid=a)};routeRtcp=e=>{let t=[];switch(e.type){case rM.type:e=e,t.push(this.ssrcTable[e.ssrc]);break;case Vj.type:e=e,e.reports.forEach(e=>{t.push(this.ssrcTable[e.ssrc])});break;case $j.type:break;case Qj.type:{let n=e;n.feedback&&t.push(this.ssrcTable[n.feedback.mediaSourceSsrc])}break;case Bj.type:{let n=e;switch(n.feedback.count){case Rj.count:{let e=n.feedback;t.push(this.ssrcTable[e.ssrcFeedbacks[0]])}break;default:t.push(this.ssrcTable[n.feedback.senderSsrc]||this.ssrcTable[n.feedback.mediaSsrc])}}}t.filter(e=>e).forEach(t=>t.handleRtcpPacket(e))}},uz=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(e,t,n){this.numPackets===0?(this.firstPacketSentAtMs=t,this.firstPacketReceivedAtMs=n,this.lastPacketSentAtMs=t,this.lastPacketReceivedAtMs=n):(t<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=t),n<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=n),t>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=t),n>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=n)),this.numPackets++,this.totalSize+=e}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let e=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs;return Nj(this.totalSize/e*8*1e3)}get sendBitrate(){let e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;return Nj(this.totalSize/e*8*1e3)}},dz=20,fz=10,pz=class{congestion=!1;onAvailableBitrate=new $;onCongestion=new $;onCongestionScore=new $;congestionCounter=0;cumulativeResult=new uz;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(e){this._congestionScore=e,this.onCongestionScore.execute(e)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(e){this._availableBitrate=e,this.onAvailableBitrate.execute(e)}constructor(){}receiveTWCC(e){let t=qI()-this.cumulativeResult.firstPacketSentAtMs;t>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<dz?this.congestionCounter++:this.congestionScore<fz&&this.congestionScore++,this.congestionCounter>=dz&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let t of e.packetResults){if(!t.received)continue;let e=t.sequenceNumber,n=this.sentInfos[e];n&&t.receivedAtMs&&this.cumulativeResult.addPacket(n.size,n.sendingAtMs,t.receivedAtMs)}if(t>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-dz){let e=Nj(dz/2)+1,t=e-(e-(Nj(dz/4)+1))/10*this.congestionScore;this.congestionCounter-=t}this.congestionCounter<=-dz&&(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(e){Object.keys(e).map(e=>Number(e)).sort().filter(t=>t<e.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[e.wideSeq]=e}},mz=Bk(`werift:packages/webrtc/src/media/rtpSender.ts`),hz=128,gz=.85,_z=class{constructor(e){this.trackOrKind=e,this.kind=typeof this.trackOrKind==`string`?this.trackOrKind:this.trackOrKind.kind,typeof e!=`string`&&this.registerTrack(e)}type=`sender`;kind;ssrc=c(4).readUInt32BE(0);rtxSsrc=c(4).readUInt32BE(0);trackId=l().toString();onReady=new $;onRtcp=new $;onPictureLossIndication=new $;onGenericNack=new $;senderBWE=new pz;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=sk();redRedundantPayloadType;_redDistance=2;redEncoder=new wM(this._redDistance);headerExtensions=[];disposeTrack;sendEncodings=[{}];lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;headerBytesSent=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;retransmittedPacketsSent=0;retransmittedBytesSent=0;nackCount=0;pliCount=0;firCount=0;remotePacketsLost;remoteFractionLost;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpCache=[];codec;dtlsTransport;dtlsDisposer=[];track=null;streamIds=[];stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;get transport(){return this.dtlsTransport??null}get streamId(){return this.streamIds[0]}set streamId(e){this.streamIds=e?[e]:[]}setDtlsTransport(e){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=e,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e===`connected`&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(e){this._redDistance=e,this.redEncoder.distance=e}prepareSend(e){this.cname=e.rtcp?.cname,this.mid=e.muxId,this.headerExtensions=e.headerExtensions,this.rtpStreamId=e.rtpStreamId,this.repairedRtpStreamId=e.repairedRtpStreamId,this.codec=e.codecs[0],this.track&&(this.track.codec=this.codec),e.codecs.forEach(e=>{let t=iz(e.parameters??``);e.name.toLowerCase()===`rtx`&&t.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()===`red`&&(this.redRedundantPayloadType=Number((e.parameters??``).split(`/`)[0]))})}registerTrack(e){if(e.stopped)throw Error(`track is ended`);this.disposeTrack&&this.disposeTrack(),e.id=this.trackId;let{unSubscribe:t}=e.onReceiveRtp.subscribe(async e=>{await this.sendRtp(e)});this.track=e,this.disposeTrack=t,this.codec&&(e.codec=this.codec),e.onSourceChanged.subscribe(e=>{this.replaceRTP(e)})}setStreams(e=[]){this.streamIds=[...new Set(e.map(e=>e.id))]}setSendEncodings(e=[]){this.sendEncodings=e.length>0?e.map(e=>({...e})):[{}]}async replaceTrack(e){if(e===null){this.disposeTrack&&this.disposeTrack(),this.track=null;return}if(e.stopped)throw Error(`track is ended`);if(this.sequenceNumber!=null){let t=e.header||(await e.onReceiveRtp.asPromise())[0].header;this.replaceRTP(t)}this.registerTrack(e),mz(`replaceTrack`,`ssrc`,e.ssrc,`rid`,e.rid)}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack&&this.disposeTrack(),this.track=null}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await E(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let e=[new rM({ssrc:this.ssrc,senderInfo:new iM({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=$I(this.ntpTimestamp),this.lastSentSRTimestamp=XI(),this.cname&&e.push(new $j({chunks:[new eM({source:this.ssrc,items:[new tM({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(e)}catch(e){mz(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:e,timestamp:t},n=!1){this.sequenceNumber!=null&&(this.seqOffset=Ak(this.sequenceNumber,-e),n&&(this.seqOffset=Ak(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=jk(this.timestamp,-t),n&&(this.timestampOffset=Ak(this.timestampOffset,1))),this.rtpCache=[],mz(`replaceRTP`,this.sequenceNumber,e,this.seqOffset)}async sendRtp(e){if(this.dtlsTransport.state!==`connected`||!this.codec)return;e=Buffer.isBuffer(e)?PM.deSerialize(e):e;let{header:t,payload:n}=e;t.ssrc=this.ssrc,t.payloadType=this.codec.payloadType,t.timestamp=jk(t.timestamp,this.timestampOffset),t.sequenceNumber=Ak(t.sequenceNumber,this.seqOffset),this.timestamp=t.timestamp,this.sequenceNumber=t.sequenceNumber;let r=ZI(),i=[...t.extensions];t.extensions=this.headerExtensions.map(e=>{let t=(()=>{switch(e.uri){case lM.sdesMid:return this.mid?dM(this.mid):void 0;case lM.sdesRTPStreamID:return this.rtpStreamId?fM(this.rtpStreamId):void 0;case lM.repairedRtpStreamId:return this.repairedRtpStreamId?pM(this.repairedRtpStreamId):void 0;case lM.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Ak(this.dtlsTransport.transportSequenceNumber,1),mM(this.dtlsTransport.transportSequenceNumber);case lM.absSendTime:return hM(r)}})();if(t)return{id:e.id,payload:t}}).filter(e=>e);for(let e of i){let n=t.extensions.find(t=>t.id===e.id);n?n.payload=e.payload:t.extensions.push(e)}t.extensions=t.extensions.sort((e,t)=>e.id-t.id),this.ntpTimestamp=r,this.rtpTimestamp=t.timestamp,this.octetCount+=n.length,this.headerBytesSent+=t.serializeSize,this.packetCount=jk(this.packetCount,1),this.rtpCache[t.sequenceNumber%hz]=e;let a=n;this.redRedundantPayloadType&&(this.redEncoder.push({block:a,timestamp:t.timestamp,blockPT:this.redRedundantPayloadType}),a=this.redEncoder.build().serialize());let o=await this.dtlsTransport.sendRtp(a,t);this.runRtcp();let s=qI(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:s,sentAtMs:s};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(e){switch(e.type){case rM.type:case Vj.type:e.reports.filter(e=>e.ssrc===this.ssrc).forEach(e=>{if(this.remotePacketsLost=e.packetsLost,this.remoteFractionLost=e.fractionLost/256,this.lastSRtimestamp===e.lsr&&e.dlsr&&this.lastSentSRTimestamp){let t=XI()-this.lastSentSRTimestamp-e.dlsr/65536;this.totalRoundTripTime+=t,this.roundTripTimeMeasurements++,this.rtt=this.rtt===void 0?t:gz*this.rtt+(1-gz)*t}});break;case Qj.type:{let t=e;switch(t.feedback.count){case Kj.count:{let e=t.feedback;this.senderBWE.receiveTWCC(e)}break;case Wj.count:{let e=t.feedback;this.nackCount++,e.lost.forEach(async e=>{let t=this.rtpCache[e%hz];t&&t.header.sequenceNumber!==e&&(t=void 0),t&&(this.rtxPayloadType!=null&&(t=IM(t,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Ak(this.rtxSequenceNumber,1)),this.retransmittedPacketsSent++,this.retransmittedBytesSent+=t.payload.length,this.headerBytesSent+=t.header.serializeSize,await this.dtlsTransport.sendRtp(t.payload,t.header))}),this.onGenericNack.execute(e)}}}break;case Bj.type:{let t=e;switch(t.feedback.count){case Rj.count:{let e=t.feedback;this.receiverEstimatedMaxBitrate=e.bitrate}break;case Lj.count:this.pliCount++,this.onPictureLossIndication.execute()}}}this.onRtcp.execute(e)}getParameters(){return{encodings:this.sendEncodings.map(e=>({...e}))}}setParameters(e){e.encodings&&this.setSendEncodings(e.encodings)}get outboundRtpStatsId(){return AI(`outbound-rtp`,this.trackId)}get mediaSourceStatsId(){return AI(`media-source`,this.trackId)}get remoteInboundRtpStatsId(){return AI(`remote-inbound-rtp`,this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){let t=[],n=this.dtlsTransport?AI(`transport`,this.dtlsTransport.id):void 0,r=this.codec&&n?jI(n,this.codec.payloadType,this.trackId):void 0,i={type:`outbound-rtp`,id:this.outboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:n,codecId:r,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,headerBytesSent:this.headerBytesSent,retransmittedPacketsSent:this.retransmittedPacketsSent||void 0,retransmittedBytesSent:this.retransmittedBytesSent||void 0,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0,mediaSourceId:this.track?this.mediaSourceStatsId:void 0,remoteId:this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0?this.remoteInboundRtpStatsId:void 0,nackCount:this.nackCount||void 0,pliCount:this.pliCount||void 0,firCount:this.firCount||void 0};if(t.push(i),this.track){let n={type:`media-source`,id:this.mediaSourceStatsId,timestamp:e,trackIdentifier:this.track.id??this.trackId,kind:this.kind};t.push(n)}if(this.codec&&n){let i={type:`codec`,id:r,timestamp:e,payloadType:this.codec.payloadType,transportId:n,mimeType:this.codec.mimeType,clockRate:this.codec.clockRate,channels:this.codec.channels,sdpFmtpLine:this.codec.parameters};t.push(i)}if(this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0){let r={type:`remote-inbound-rtp`,id:this.remoteInboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:n,codecId:i.codecId,localId:i.id,roundTripTime:this.rtt,totalRoundTripTime:this.totalRoundTripTime,roundTripTimeMeasurements:this.roundTripTimeMeasurements,packetsLost:this.remotePacketsLost,fractionLost:this.remoteFractionLost};t.push(r)}return t}async getStats(){let e=MI(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),PI(t,this.getStatsRootIds())}};function vz(e,t=e){return new DOMException(t,e)}function yz(e){return TypeError(e)}var bz=Bk(`werift:packages/webrtc/src/transport/sctpManager.ts`),xz=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new $;constructor(){}createSctpTransport(e){let t=new UR(5e3,e);return t.mid=void 0,t.onDataChannel.subscribe(e=>{this.dataChannelsOpened++,this.dataChannels.push(e),this.onDataChannel.execute(e)}),this.sctpTransport=t,t}createDataChannel(e,t={}){let n=Sz(t.maxPacketLifeTime,`maxPacketLifeTime`),r=Sz(t.maxRetransmits,`maxRetransmits`),i={protocol:``,ordered:!0,negotiated:!1,...t,maxPacketLifeTime:n,maxRetransmits:r};if(i.maxPacketLifeTime!=null&&i.maxRetransmits!=null)throw yz(`maxPacketLifeTime and maxRetransmits cannot both be set`);this.sctpTransport||=this.createSctpTransport();let a=new JF({id:i.id,label:e,maxPacketLifeTime:i.maxPacketLifeTime,maxRetransmits:i.maxRetransmits,negotiated:i.negotiated,ordered:i.ordered,protocol:i.protocol}),o=new qF(this.sctpTransport,a);return this.dataChannelsOpened++,this.dataChannels.push(o),o.stateChange.subscribe(e=>{if(e===`closed`){this.dataChannelsClosed++;let e=this.dataChannels.indexOf(o);e!==-1&&this.dataChannels.splice(e,1)}}),o}async connectSctp(){this.sctpTransport&&this.sctpRemotePort&&(await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),bz(`sctp connected`))}setRemoteSCTP(e,t){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(e.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=e.sctpPort,!this.sctpRemotePort)throw Error(`sctpRemotePort not exist`);this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=t,this.sctpTransport.mid||(this.sctpTransport.mid=e.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(e=MI()){let t=[];for(let n of this.dataChannels){let r={type:`data-channel`,id:AI(`data-channel`,n.id??n.statsId),timestamp:e,label:n.label,protocol:n.protocol,dataChannelIdentifier:n.id??void 0,state:n.readyState,messagesSent:n.messagesSent||0,bytesSent:n.bytesSent||0,messagesReceived:n.messagesReceived||0,bytesReceived:n.bytesReceived||0};t.push(r)}return t}};function Sz(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw yz(`${t} must be an unsigned short`);return n}var Cz=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:e,midSuffix:t,bundlePolicy:n}){this.cname=e,this.midSuffix=t??!1,this.bundlePolicy=n}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?.(e=>e.direction===`inactive`)}createMediaDescriptionForTransceiver(e,t){let n=new qR(e.kind,9,`UDP/TLS/RTP/SAVPF`,e.codecs.map(e=>e.payloadType));return n.direction=t,n.msids=e.msids,n.rtp={codecs:e.codecs,headerExtensions:e.headerExtensions,muxId:e.mid??void 0},n.rtcpHost=`0.0.0.0`,n.rtcpPort=9,n.rtcpMux=!0,n.ssrc=[new az({ssrc:e.sender.ssrc,cname:this.cname})],e.options.simulcast&&(n.simulcastParameters=e.options.simulcast.map(e=>new iI(e))),n.rtp.codecs.find(e=>e.name.toLowerCase()===`rtx`)&&(n.ssrc.push(new az({ssrc:e.sender.rtxSsrc,cname:this.cname})),n.ssrcGroup=[new JR(`FID`,[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]),this.addTransportDescription(n,e.dtlsTransport),n}createMediaDescriptionForSctp(e){let t=new qR(`application`,xI,`UDP/DTLS/SCTP`,[`webrtc-datachannel`]);return t.sctpPort=e.port,t.rtp.muxId=e.mid,t.sctpCapabilities=e.getCapabilities(),this.addTransportDescription(t,e.dtlsTransport),t}addTransportDescription(e,t){let n=t.iceTransport;e.iceCandidates=n.localCandidates,e.iceCandidatesComplete=n.gatheringState===`complete`,e.iceParams=n.localParameters,e.iceOptions=`trickle`,e.host=bI,e.port=xI,e.direction===`inactive`&&(e.port=0,e.msids=[]),e.dtlsParams||(e.dtlsParams=t.localParameters,e.dtlsParams.fingerprints||(e.dtlsParams.fingerprints=t.localParameters.fingerprints))}allocateMid(e=``){let t=``;for(let n=0;t=(n++).toString()+e,this.seenMid.has(t););return this.seenMid.add(t),t}parseSdp({sdp:e,isLocal:t,signalingState:n,type:r}){let i=KR.parse(e);return this.validateDescription({description:i,isLocal:t,signalingState:n,type:r}),i.type=r,i}validateDescription({description:e,isLocal:t,signalingState:n,type:r}){if(t){if(r===`offer`){if(![`stable`,`have-local-offer`].includes(n))throw vz(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-remote-offer`,`have-local-pranswer`].includes(n))throw vz(`InvalidStateError`,`Cannot handle answer in signaling state`)}else if(r===`offer`){if(![`stable`,`have-remote-offer`,`have-local-offer`].includes(n))throw vz(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-local-offer`,`have-remote-pranswer`].includes(n))throw vz(`InvalidStateError`,`Cannot handle answer in signaling state`)}buildOfferSdp(e,t){let n=new KR;rz(`offer`,n),(this.currentLocalDescription?.media??[]).forEach((r,i)=>{let a=r.rtp.muxId;if(a){if(r.kind===`application`){if(!t)throw Error(`sctpTransport not found`);t.mLineIndex=i,n.media.push(this.createMediaDescriptionForSctp(t))}else{let t=e.find(e=>e.mid===a);if(!t){if(r.direction===`inactive`){n.media.push(r);return}throw Error(`transceiver not found`)}t.mLineIndex=i,n.media.push(this.createMediaDescriptionForTransceiver(t,t.direction))}}});for(let t of e.filter(e=>!n.media.find(t=>t.rtp.muxId===e.mid))){t.mid??=this.allocateMid(this.midSuffix?`av`:``);let e=this.createMediaDescriptionForTransceiver(t,t.direction);t.mLineIndex===void 0?(t.mLineIndex=n.media.length,n.media.push(e)):n.media[t.mLineIndex]=e}if(t&&!n.media.find(e=>e.kind===`application`)&&(t.mLineIndex=n.media.length,t.mid??=this.allocateMid(this.midSuffix?`dc`:``),n.media.push(this.createMediaDescriptionForSctp(t))),this.bundlePolicy!==`disable`){let e=n.media.map(e=>e.rtp.muxId).filter(e=>e);if(e.length){let t=new JR(`BUNDLE`,e);n.group.push(t)}}return n}buildAnswerSdp({transceivers:e,sctpTransport:t,signalingState:n}){if(![`have-remote-offer`,`have-local-pranswer`].includes(n))throw Error(`createAnswer failed`);if(!this._remoteDescription)throw Error(`wrong state`);let r=new KR;rz(`answer`,r);for(let n of this._remoteDescription.media){let i,a;if([`audio`,`video`].includes(n.kind)){let t=e.find(e=>e.mid===n.rtp.muxId);if(!t)throw Error(`Transceiver with mid=${n.rtp.muxId} not found`);a=this.createMediaDescriptionForTransceiver(t,GI(t.direction,t.offerDirection)),i=t.dtlsTransport}else if(n.kind===`application`){if(!t||!t.mid)throw Error(`sctpTransport not found`);a=this.createMediaDescriptionForSctp(t),i=t.dtlsTransport}else throw Error(`invalid kind`);a.dtlsParams&&(i.role===`auto`?a.dtlsParams.role=`client`:a.dtlsParams.role=i.role),n.simulcastParameters&&n.simulcastParameters.length>0&&(a.simulcastParameters=n.simulcastParameters.map(e=>({...e,direction:e.direction===`send`?`recv`:`send`}))),r.media.push(a)}if(this.bundlePolicy!==`disable`){let e=new JR(`BUNDLE`,[]);for(let t of r.media)t.rtp.muxId&&e.items.push(t.rtp.muxId);r.group.push(e)}return r}setLocalDescription(e){if(e.type===`offer`||e.type===`pranswer`){this.pendingLocalDescription=e;return}this.currentLocalDescription=e,this.pendingRemoteDescription&&(this.currentRemoteDescription=this.pendingRemoteDescription),this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0}setRemoteDescription(e,t){if(!e.type)throw Error(`invalid sessionDescription`);if(e.type===`rollback`){if(![`have-remote-offer`,`have-local-pranswer`].includes(t))throw vz(`InvalidStateError`,`Cannot rollback remote description in signaling state`);this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0;return}if(!e.sdp)throw Error(`invalid sessionDescription`);let n=this.parseSdp({sdp:e.sdp,isLocal:!1,signalingState:t,type:e.type});return n.type===`offer`||n.type===`pranswer`?this.pendingRemoteDescription=n:(this.pendingLocalDescription&&(this.currentLocalDescription=this.pendingLocalDescription),this.currentRemoteDescription=n,this.pendingRemoteDescription=void 0,this.pendingLocalDescription=void 0),n}rollbackLocalDescription(e){if(![`have-local-offer`,`have-local-pranswer`].includes(e))throw vz(`InvalidStateError`,`Cannot rollback local description in signaling state`);this.pendingLocalDescription=void 0,this.pendingRemoteDescription=void 0}registerMid(e){this.seenMid.add(e)}get remoteIsBundled(){let e=this._remoteDescription;if(e)return e.group.find(e=>e.semantic===`BUNDLE`&&this.bundlePolicy!==`disable`)}setLocal(e,t,n){let r=new Map(t.map(e=>[e?.mLineIndex,e])),i=t.find(e=>e?.dtlsTransport)?.dtlsTransport??n?.dtlsTransport;e.media.filter(e=>[`audio`,`video`].includes(e.kind)).forEach((e,n)=>{let a=(r.get(n)??t[n])?.dtlsTransport??i;if(!a)throw Error(`dtls transport not found for media index ${n}`);this.addTransportDescription(e,a)});let a=e.media.find(e=>e.kind===`application`);n&&a&&this.addTransportDescription(a,n.dtlsTransport),this.setLocalDescription(e)}},wz=Bk(`werift:packages/webrtc/src/transport/secureTransportManager.ts`),Tz=class{connectionState=`new`;iceConnectionState=`new`;iceGatheringState=`new`;certificate;iceGatheringStateChange=new $;iceConnectionStateChange=new $;onIceCandidate=new $;connectionStateChange=new $;config;transceiverManager;sctpManager;constructor({config:e,transceiverManager:t,sctpManager:n}){if(this.config=e,this.transceiverManager=t,this.sctpManager=n,this.config.dtls){let{keys:e}=this.config.dtls;this.config.certificates[0]?this.certificate=this.config.certificates[0]:e&&this.setupCertificate(e)}}get dtlsTransports(){return[...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport].filter(e=>e!=null).reduce((e,t)=>(e.map(e=>e.id).includes(t.id)||e.push(t),e),[])}get iceTransports(){return this.dtlsTransports.map(e=>e.iceTransport)}setupCertificate(e){this.certificate=new vL(e.keyPem,e.certPem,e.signatureHash)}createTransport(){let e=this.iceTransports.find(e=>e.state!==`closed`),t=eL(this.config.iceServers),n=tL({parsedTurnTransport:t.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP}),r=new kL({...t,iceLite:this.config.iceLite,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,useTcp:this.config.iceUseTcp,turnTransport:n,turnTlsOptions:this.config.turnTlsOptions,useLinkLocalAddress:this.config.iceUseLinkLocalAddress});e&&(r.connection.localUsername=e.connection.localUsername,r.connection.localPassword=e.connection.localPassword),r.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let i=new OL(r);return i.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new _L(this.config,i,this.certificate,Ez)}handleNewIceCandidate({candidate:e,media:t,remoteIsBundled:n,transceiver:r,sctpTransport:i,bundlePolicy:a}){return a===`max-bundle`||n?(e.sdpMLineIndex=0,t&&(e.sdpMid=t.rtp.muxId)):(r&&(e.sdpMLineIndex=r.mLineIndex,e.sdpMid=r.mid??void 0),i&&(e.sdpMLineIndex=i.mLineIndex,e.sdpMid=i.mid)),e.foundation&&!e.foundation.startsWith(`candidate:`)&&(e.foundation=`candidate:`+e.foundation),this.onIceCandidate.execute(e),e}async addIceCandidate(e,t){let n=t?.candidate,r=t?.sdpMid,i=t?.sdpMLineIndex,a=t?.usernameFragment,o=t==null||n==null||n===``,s=this.resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:o,sdpMid:r,sdpMLineIndex:i,usernameFragment:a});if(o){let t=s.map(t=>this.getTransportByMLineIndex(e,t)).filter(e=>!!e).reduce((e,t)=>(e.find(({id:e})=>e===t.id)||e.push(t),e),[]);return await Promise.all(t.map(e=>e.addRemoteCandidate(void 0))),{kind:`end-of-candidates`,mediaIndices:s}}let c=NL.fromJSON(t);if(!c)throw vz(`OperationError`,`Failed to parse ICE candidate`);let l=s[0],u=e.media[l];if(!u)throw vz(`OperationError`,`ICE media section not found`);c.sdpMid=u.rtp.muxId??void 0,c.sdpMLineIndex=l;let d=this.getTransportByMLineIndex(e,l);if(!d)throw vz(`OperationError`,`ICE transport not found for candidate`);return await d.addRemoteCandidate(c),{kind:`candidate`,candidate:c,mediaIndices:[l]}}resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:t,sdpMid:n,sdpMLineIndex:r,usernameFragment:i}){let a;if(typeof n==`string`){let t=e.media.findIndex(e=>e.rtp.muxId===n);if(t<0)throw vz(`OperationError`,`Media section for sdpMid was not found`);a=[t]}else if(typeof r==`number`){if(r<0||r>=e.media.length)throw vz(`OperationError`,`Media section for sdpMLineIndex was not found`);a=[r]}else if(t)a=e.media.map((e,t)=>t);else throw yz(`sdpMid or sdpMLineIndex must be provided with a candidate`);if(typeof i==`string`){let t=a.filter(t=>e.media[t]?.iceParams?.usernameFragment===i);if(t.length===0)throw vz(`OperationError`,`No media section matched the ICE usernameFragment`);a=t}return a}getTransportByMid(e){if(!e)return;let t,n=this.transceiverManager.getTransceivers().find(t=>t.mid===e);return n?t=n.dtlsTransport.iceTransport:!t&&this.sctpManager.sctpTransport?.mid===e&&(t=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),t}getTransportByMLineIndex(e,t){let n=e.media[t];if(n)return this.getTransportByMid(n.rtp.muxId)}restartIce(){for(let e of this.iceTransports)e.restart()}setLocalRole({type:e,role:t}){for(let n of this.dtlsTransports){let r=n.iceTransport;r.connection.iceLite?r.connection.iceControlling=!1:r.connection.remoteIsLite||e===`offer`?r.connection.iceControlling=!0:r.connection.iceControlling=!1,e===`answer`&&t&&(n.role=t)}}updateIceGatheringState(){let e=this.iceTransports;function t(...t){return e.filter(e=>t.includes(e.gatheringState)).length===e.length}let n;n=e.length&&t(`complete`)?`complete`:!e.length||t(`new`,`complete`)?`new`:e.map(e=>e.gatheringState).includes(`gathering`)?`gathering`:`new`,this.iceGatheringState!==n&&(this.iceGatheringState=n,this.iceGatheringStateChange.execute(n))}updateIceConnectionState(){let e=this.iceTransports,t;function n(...t){return e.filter(e=>t.includes(e.state)).length===e.length}function r(...t){return e.some(e=>t.includes(e.state))}t=this.connectionState===`closed`?`closed`:r(`failed`)?`failed`:r(`disconnected`)?`disconnected`:n(`new`,`closed`)?`new`:r(`new`,`checking`)?`checking`:n(`completed`,`closed`)?`completed`:n(`connected`,`completed`,`closed`)?`connected`:`new`,this.iceConnectionState!==t&&(wz(`iceConnectionStateChange`,t),this.iceConnectionState=t,this.iceConnectionStateChange.execute(t),t===`failed`&&this.connectionState!==`closed`?this.setConnectionState(`failed`):t===`disconnected`&&this.connectionState===`connected`&&this.setConnectionState(`disconnected`))}async gatherCandidates(e){let t=this.iceTransports.find(e=>e.state===`connected`||e.state===`completed`);e&&t?wz(`skipping ICE gathering for bundled connection`):await Promise.allSettled(this.iceTransports.map(e=>e.gather())).catch(e=>{wz(`gatherCandidates failed`,e)})}setConnectionState(e){this.connectionState!==e&&(wz(`connectionStateChange`,e),this.connectionState=e,this.connectionStateChange.execute(e))}async getStats(e){let t=[];for(let n of this.dtlsTransports){let r=await n.getStats(e);r&&t.push(...r)}return t}async ensureCerts(){this.certificate||=await _L.SetupCertificate();for(let e of this.dtlsTransports)e.localCertificate=this.certificate}async close(){this.setConnectionState(`closed`),await Promise.allSettled([...this.dtlsTransports.map(e=>e.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},Ez=[EI.SRTP_AEAD_AES_128_GCM,EI.SRTP_AES128_CM_HMAC_SHA1_80],Dz=Bk(`werift:packages/webrtc/src/peerConnection.ts`),Oz=class extends WF{id=l().toString();cname=l().toString();config=Az();signalingState=`stable`;negotiationneeded=!1;needRestart=!1;router=new lz;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;lastCreatedAnswer;lastCreatedOffer;pendingRemoteCandidates=[];iceGatheringStateChange=new $;iceConnectionStateChange=new $;signalingStateChange=new $;connectionStateChange=new $;onDataChannel=new $;onRemoteTransceiverAdded=new $;onTransceiverAdded=new $;onIceCandidate=new $;onNegotiationneeded=new $;onTrack=new $;eventHandlers={};get ondatachannel(){return this.eventHandlers.ondatachannel??null}set ondatachannel(e){this.eventHandlers.ondatachannel=e??void 0}get onicecandidate(){return this.eventHandlers.onicecandidate??null}set onicecandidate(e){this.eventHandlers.onicecandidate=e??void 0}get onicecandidateerror(){return this.eventHandlers.onicecandidateerror??null}set onicecandidateerror(e){this.eventHandlers.onicecandidateerror=e??void 0}get onicegatheringstatechange(){return this.eventHandlers.onicegatheringstatechange??null}set onicegatheringstatechange(e){this.eventHandlers.onicegatheringstatechange=e??void 0}get onnegotiationneeded(){return this.eventHandlers.onnegotiationneeded??null}set onnegotiationneeded(e){this.eventHandlers.onnegotiationneeded=e??void 0}get onsignalingstatechange(){return this.eventHandlers.onsignalingstatechange??null}set onsignalingstatechange(e){this.eventHandlers.onsignalingstatechange=e??void 0}get ontrack(){return this.eventHandlers.ontrack??null}set ontrack(e){this.eventHandlers.ontrack=e??void 0}get onconnectionstatechange(){return this.eventHandlers.onconnectionstatechange??null}set onconnectionstatechange(e){this.eventHandlers.onconnectionstatechange=e??void 0}get oniceconnectionstatechange(){return this.eventHandlers.oniceconnectionstatechange??null}set oniceconnectionstatechange(e){this.eventHandlers.oniceconnectionstatechange=e??void 0}constructor(e={}){super(),this.setConfiguration(e),this.sdpManager=new Cz({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new Lz(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:e,streams:t,transceiver:n})=>{let r=new Fz({track:e,streams:t,transceiver:n,receiver:n.receiver});this.onTrack.execute(e),this.emit(`track`,r),this.ontrack&&this.ontrack(r)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new xz,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let t={type:`datachannel`,channel:e};this.ondatachannel?.(t),this.emit(`datachannel`,t)}),this.secureManager=new Tz({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.secureManager.iceGatheringStateChange.subscribe(e=>{this.iceGatheringStateChange.execute(e),this.onicegatheringstatechange?.(new globalThis.Event(`icegatheringstatechange`)),this.emit(`icegatheringstatechange`)}),this.secureManager.iceConnectionStateChange.subscribe(e=>{e===`closed`&&this.close(),this.iceConnectionStateChange.execute(e),this.oniceconnectionstatechange?.(),this.emit(`iceconnectionstatechange`)}),this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e),this.onconnectionstatechange?.(),this.emit(`connectionstatechange`)}),this.secureManager.onIceCandidate.subscribe(e=>{let t=e?e.toJSON():void 0;this.onIceCandidate.execute(t);let n={type:`icecandidate`,candidate:t};this.onicecandidate?.(n),this.emit(`icecandidate`,n)})}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 sctp(){return this.sctpTransport??null}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??null}get currentLocalDescription(){return this.sdpManager.currentLocalDescription?.toJSON()??null}get pendingLocalDescription(){return this.sdpManager.pendingLocalDescription?.toJSON()??null}get remoteDescription(){return this.sdpManager.remoteDescription??null}get currentRemoteDescription(){return this.sdpManager.currentRemoteDescription?.toJSON()??null}get pendingRemoteDescription(){return this.sdpManager.pendingRemoteDescription?.toJSON()??null}get canTrickleIceCandidates(){let e=this.sdpManager._remoteDescription;return e?[e.iceOptions,...e.media.map(e=>e.iceOptions)].filter(e=>!!e).join(` `).split(/\s+/).includes(`trickle`):null}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(e){let t=jz(e),n=!!this.sdpManager;if(t.rtcpMuxPolicy&&t.rtcpMuxPolicy!==`require`)throw Error(`rtcpMuxPolicy must be require`);if(t.iceCandidatePoolSize!==void 0&&(!Number.isInteger(t.iceCandidatePoolSize)||t.iceCandidatePoolSize<0))throw Error(`iceCandidatePoolSize must be a non-negative integer`);if(n&&t.bundlePolicy!==void 0&&t.bundlePolicy!==this.config.bundlePolicy)throw Error(`bundlePolicy cannot be changed`);if(n&&t.rtcpMuxPolicy!==void 0&&t.rtcpMuxPolicy!==this.config.rtcpMuxPolicy)throw Error(`rtcpMuxPolicy cannot be changed`);if(n&&t.certificates!==void 0&&!Nz(t.certificates,this.config.certificates))throw Error(`certificates cannot be changed`);if(n&&t.iceCandidatePoolSize!==void 0&&this.localDescription&&t.iceCandidatePoolSize!==this.config.iceCandidatePoolSize)throw Error(`iceCandidatePoolSize cannot be changed after setLocalDescription`);if((t.iceCandidatePoolSize??0)>0)throw Error(`iceCandidatePoolSize > 0 is not supported`);if(sL(this.config,t),this.config.icePortRange){let[e,t]=this.config.icePortRange;if(e===t)throw Error(`should not be same value`);if(e>=t)throw Error(`The min must be less than max`)}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw Error(`maxMessageSize must be a non-negative integer`);this.sctpManager?.sctpTransport&&(this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize);for(let[e,t]of HF([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(t.payloadType==null)switch(t.payloadType=96+e,t.name.toLowerCase()){case`rtx`:t.parameters=`apt=${t.payloadType-1}`;break;case`red`:if(t.contentType===`audio`){let e=t.payloadType+1;t.parameters=`${e}/${e}`,t.payloadType=63}}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,t)=>{e.id=1+t})}getConfiguration(){return Pz(this.config)}async createOffer({iceRestart:e}={}){(e||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let e of this.transceiverManager.getTransceivers())e.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(e),e.headerExtensions.length===0&&(e.headerExtensions=this.config.headerExtensions[e.kind]??[]);let t=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON();return this.lastCreatedOffer=t,t}createSctpTransport(){let e=this.sctpManager.createSctpTransport(this.config.maxMessageSize),t=this.findOrCreateTransport();return e.setDtlsTransport(t),e}createDataChannel(e,t={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let n=this.sctpManager.createDataChannel(e,t);if(!n.sctp.dtlsTransport){let e=this.findOrCreateTransport();n.sctp.setDtlsTransport(e)}return n}removeTrack(e){if(this.isClosed)throw vz(`InvalidStateError`,`peer closed`);this.transceiverManager.removeTrack(e),this.needNegotiation()}needNegotiation=async()=>{this.invalidateLastCreatedDescriptions(),this.shouldNegotiationneeded=!0,!(this.negotiationneeded||this.signalingState!==`stable`)&&(this.shouldNegotiationneeded=!1,setImmediate(()=>{this.negotiationneeded=!0,this.onNegotiationneeded.execute(),this.onnegotiationneeded&&this.onnegotiationneeded(new globalThis.Event(`negotiationneeded`)),this.emit(`negotiationneeded`)}))};invalidateLastCreatedDescriptions(){this.lastCreatedAnswer=void 0,this.lastCreatedOffer=void 0}async waitForPendingDescriptionTask(){this.assertNotClosed(),await Promise.resolve(),this.isClosed&&await new Promise(()=>void 0)}findOrCreateTransport(){let e=this.dtlsTransports.find(e=>e.state!==`closed`);if(e?.iceTransport,(this.sdpManager.bundlePolicy===`max-bundle`||this.sdpManager.bundlePolicy!==`disable`&&this.remoteIsBundled)&&e)return e;let t=this.secureManager.createTransport();t.onRtp.subscribe(e=>{this.router.routeRtp(e)}),t.onRtcp.subscribe(e=>{this.router.routeRtcp(e)});let n=t.iceTransport;return n.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),n.onIceCandidate.subscribe(e=>{if(!this.localDescription){Dz(`localDescription not found when ice candidate was gathered`);return}if(!e){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){Dz(`localDescription not found when ice candidate was gathered`);return}this.secureManager.handleNewIceCandidate({candidate:e,bundlePolicy:this.sdpManager.bundlePolicy,remoteIsBundled:!!this.sdpManager.remoteIsBundled,media:this._localDescription.media[0],transceiver:this.transceiverManager.getTransceivers().find(e=>e?.dtlsTransport?.iceTransport.id===n.id),sctpTransport:this.sctpTransport?.dtlsTransport.iceTransport.id===n.id?this.sctpTransport:void 0})}),t}async setLocalDescription(e){let t=[`stable`,`have-local-offer`,`have-remote-pranswer`];if(await this.waitForPendingDescriptionTask(),e?.type===`rollback`){this.sdpManager.rollbackLocalDescription(this.signalingState),this.setSignalingState(`stable`),this.shouldNegotiationneeded&&this.needNegotiation(),this.invalidateLastCreatedDescriptions();return}let n=!e?.type||!e.sdp||e.sdp.length===0?e?.type===`offer`?this.lastCreatedOffer??await this.createOffer():e?.type===`answer`||e?.type===`pranswer`?this.lastCreatedAnswer??await this.createAnswer():t.includes(this.signalingState)?this.lastCreatedOffer??await this.createOffer():this.lastCreatedAnswer??await this.createAnswer():void 0;if(e={type:e?.type??n.type,sdp:e?.sdp&&e.sdp.length>0?e.sdp:n.sdp},e.type===`offer`&&this.lastCreatedOffer&&e.sdp!==this.lastCreatedOffer.sdp)throw vz(`InvalidModificationError`,`setLocalDescription must use the latest created offer`);let r=e.type,i=e.sdp,a=this.sdpManager.parseSdp({sdp:i,isLocal:!0,signalingState:this.signalingState,type:r});a.type===`offer`?this.setSignalingState(`have-local-offer`):a.type===`answer`?this.setSignalingState(`stable`):a.type===`pranswer`&&this.setSignalingState(`have-local-pranswer`);for(let[e,t]of HF(a.media)){let n=t.rtp.muxId;if(this.sdpManager.registerMid(n),[`audio`,`video`].includes(t.kind)){let t=this.transceiverManager.getTransceiverByMLineIndex(e);t&&(t.mid=n)}t.kind===`application`&&this.sctpTransport&&(this.sctpTransport.mid=n)}let o=a.media.find(e=>e.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:a.type===`offer`?`offer`:`answer`,role:o}),[`answer`,`pranswer`].includes(a.type))for(let e of this.transceiverManager.getTransceivers()){let t=GI(e.direction,e.offerDirection);e.setCurrentDirection(t)}return this.sdpManager.setLocal(a,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(e=>{Dz(`gatherCandidates failed`,e)}),a.type===`answer`&&this.connect().catch(e=>{Dz(`connect failed`,e),this.secureManager.setConnectionState(`failed`)}),this.sdpManager.setLocal(a,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),this.invalidateLastCreatedDescriptions(),a}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(e={}){if(this.isClosed)throw vz(`InvalidStateError`,`is closed`);if(!this.remoteDescription||!this.sdpManager._remoteDescription){this.pendingRemoteCandidates.push(e);return}await this.applyRemoteIceCandidate(e)}async applyRemoteIceCandidate(e){let t=this.sdpManager._remoteDescription;if(!t)return;let n=await this.secureManager.addIceCandidate(t,e),r=this.sdpManager._remoteDescription;if(r&&n){if(n.kind===`end-of-candidates`){for(let e of n.mediaIndices){let t=r.media[e];t&&(t.iceCandidatesComplete=!0)}return}for(let e of n.mediaIndices){let t=r.media[e];t&&t.iceCandidates.push(n.candidate)}}}async flushPendingRemoteCandidates(){for(;this.pendingRemoteCandidates.length>0&&this.remoteDescription&&this.sdpManager._remoteDescription;){let e=this.pendingRemoteCandidates.shift();await this.applyRemoteIceCandidate(e??null)}}async connect(){Dz(`start connect`),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:t}=e;t.state!==`connected`&&(this.secureManager.setConnectionState(`connecting`),await t.start().catch(e=>{throw Dz(`iceTransport.start failed`,e),e}),e.state!==`connected`&&(await e.start().catch(e=>{throw Dz(`dtlsTransport.start failed`,e),e}),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(e){e instanceof KR&&(e=e.toSdp()),await this.waitForPendingDescriptionTask(),e.type===`offer`&&[`have-local-offer`,`have-local-pranswer`].includes(this.signalingState)&&(this.sdpManager.rollbackLocalDescription(this.signalingState),this.shouldNegotiationneeded=!0,this.setSignalingState(`stable`),await Promise.resolve());let t=this.sdpManager.setRemoteDescription(e,this.signalingState);if(!t){this.setSignalingState(`stable`),this.shouldNegotiationneeded&&this.needNegotiation(),this.invalidateLastCreatedDescriptions();return}let n,r=(e,t)=>e.kind===t.kind&&[null,t.rtp.muxId].includes(e.mid),i=t.media.map((i,a)=>{let o;if([`audio`,`video`].includes(i.kind)){let s=this.transceiverManager.getTransceivers().find(e=>r(e,i));if(!s)s=this.addTransceiver(i.kind,{direction:`recvonly`}),s.mid=i.rtp.muxId??null,this.onRemoteTransceiverAdded.execute(s);else if(s.direction===`inactive`&&s.stopping){s.stopped=!0,e.type===`answer`&&s.setCurrentDirection(`inactive`);return}this.sdpManager.remoteIsBundled&&(n?s.setDtlsTransport(n):n=s.dtlsTransport),o=s.dtlsTransport,this.transceiverManager.setRemoteRTP(s,i,t.type,a)}else if(i.kind===`application`){let e=this.sctpTransport;e||(e=this.createSctpTransport(),e.mid=i.rtp.muxId),this.sdpManager.remoteIsBundled&&(n?e.setDtlsTransport(n):n=e.dtlsTransport),o=e.dtlsTransport,this.sctpManager.setRemoteSCTP(i,a)}else throw Error(`invalid media kind`);let s=o.iceTransport;if(i.iceParams){let e=!!this.sdpManager.inactiveRemoteMedia;s.setRemoteParams(i.iceParams,e),i.iceParams.iceLite&&!s.connection.iceLite&&(s.connection.iceControlling=!0)}return i.dtlsParams&&o.setRemoteParams(i.dtlsParams),i.iceCandidates.forEach(s.addRemoteCandidate),i.iceCandidatesComplete&&s.addRemoteCandidate(void 0),t.type===`answer`&&i.dtlsParams?.role&&(o.role=i.dtlsParams.role===`client`?`server`:`client`),s});i=i.filter(e=>!!e);let a=this.transceiverManager.getTransceivers().filter(e=>t.media.find(t=>r(e,t))==null);if(e.type===`answer`)for(let e of a)e.stop(),e.stopped=!0;t.type===`offer`?this.setSignalingState(`have-remote-offer`):t.type===`answer`?this.setSignalingState(`stable`):t.type===`pranswer`&&this.setSignalingState(`have-remote-pranswer`),await this.flushPendingRemoteCandidates(),t.type===`answer`&&(Dz(`caller start connect`),this.connect().catch(e=>{Dz(`connect failed`,e),this.secureManager.setConnectionState(`failed`)})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation(),this.invalidateLastCreatedDescriptions()}addTransceiver(e,t={}){let n=this.findOrCreateTransport(),r=this.transceiverManager.addTransceiver(e,n,t);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),r}addTrack(e,...t){if(this.isClosed)throw vz(`InvalidStateError`,`is closed`);let n=this.transceiverManager.addTrack(e,t);if(!n.dtlsTransport){let e=this.findOrCreateTransport();n.setDtlsTransport(e)}return this.needNegotiation(),n.sender}async createAnswer(){this.assertNotClosed(),await this.secureManager.ensureCerts();let e=this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON();return this.lastCreatedAnswer=e,e}assertNotClosed(){if(this.isClosed)throw vz(`InvalidStateError`,`RTCPeerConnection is closed`)}setSignalingState(e){this.signalingState!==e&&(Dz(`signalingStateChange`,e),this.signalingState=e,this.signalingStateChange.execute(e),this.onsignalingstatechange&&this.onsignalingstatechange(new globalThis.Event(`signalingstatechange`)),this.emit(`signalingstatechange`))}createPeerConnectionStats(e){return{type:`peer-connection`,id:AI(`peer-connection`,this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){let t=MI(),n=[];e||n.push(this.createPeerConnectionStats(t)),n.push(...this.transceiverManager.collectStats(t));let r=await this.secureManager.getStats(t);if(n.push(...r),!e&&this.sctpTransport){let e=await this.sctpManager.getStats(t);e&&n.push(...e)}return e?PI(n,this.transceiverManager.getStatsRootIds(e)):PI(n)}async close(){this.isClosed||(this.isClosed=!0,this.pendingRemoteCandidates.length=0,this.setSignalingState(`closed`),this.transceiverManager.close(),await this.secureManager.close(),await this.sctpManager.close(),this.completePeerEvents(),Dz(`peerConnection closed`))}completePeerEvents(){let e=[this.onDataChannel,this.iceGatheringStateChange,this.iceConnectionStateChange,this.signalingStateChange,this.connectionStateChange,this.onTransceiverAdded,this.onRemoteTransceiverAdded,this.onIceCandidate,this.onNegotiationneeded];for(let t of e)t.ended||t.complete()}},kz=(e,t)=>e.find(e=>e.mimeType.toLowerCase()===t.mimeType.toLowerCase())?t:void 0;function Az(){return{codecs:{audio:[lI(),uI()],video:[oI()]},headerExtensions:{audio:[],video:[]},iceTransportPolicy:`all`,iceLite:!1,iceServers:[{urls:`stun:stun.l.google.com:19302`}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceUseTcp:!1,turnTransport:void 0,turnTlsOptions:void 0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:`max-compat`,rtcpMuxPolicy:`require`,iceCandidatePoolSize:0,certificates:[],debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:HR}}Az();function jz(e){let t=Object(e??{}),n={...t};if(t.bundlePolicy===`balanced`&&(n.bundlePolicy=`max-compat`),`certificates`in t){if(t.certificates===void 0)n.certificates=void 0;else if(!Array.isArray(t.certificates)||t.certificates.some(e=>e==null))throw yz(`certificates must be an array of RTCCertificate`);else n.certificates=[...t.certificates]}return`iceCandidatePoolSize`in t&&(n.iceCandidatePoolSize=Mz(t.iceCandidatePoolSize,`iceCandidatePoolSize`)),n}function Mz(e,t){let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw yz(`${t} must be an unsigned short`);return n}function Nz(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Pz(e){return{...e,codecs:{audio:e.codecs.audio?[...e.codecs.audio]:void 0,video:e.codecs.video?[...e.codecs.video]:void 0},headerExtensions:{audio:e.headerExtensions.audio?[...e.headerExtensions.audio]:void 0,video:e.headerExtensions.video?[...e.headerExtensions.video]:void 0},iceServers:e.iceServers.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),icePortRange:e.icePortRange?[...e.icePortRange]:void 0,iceAdditionalHostAddresses:e.iceAdditionalHostAddresses?[...e.iceAdditionalHostAddresses]:void 0,dtls:{...e.dtls},certificates:[...e.certificates],debug:{...e.debug}}}var Fz=class{type=`track`;track;streams;transceiver;receiver;constructor(e){this.track=e.track,this.streams=[...e.streams],this.transceiver=e.transceiver,this.receiver=e.receiver}},Iz=Bk(`werift:packages/webrtc/src/media/rtpTransceiverManager.ts`),Lz=class{constructor(e,t,n){this.cname=e,this.config=t,this.router=n}transceivers=[];onTransceiverAdded=new $;onRemoteTransceiverAdded=new $;onTrack=new $;onNegotiationNeeded=new $;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(e=>e.sender)}getReceivers(){return this.getTransceivers().map(e=>e.receiver)}getTransceiverByMLineIndex(e){return this.transceivers.find(t=>t.mLineIndex===e)}pushTransceiver(e){this.transceivers.push(e)}replaceTransceiver(e,t){this.transceivers[t]=e}addTransceiver(e,t,n={}){let r=typeof e==`string`?e:e.kind,i=n.direction||`sendrecv`,a=new _z(e),o=new FI(r,t,new sz(this.config,r,a.ssrc),a,i);o.options=n,o.sender.setStreams(n.streams??[]),o.sender.setSendEncodings((n.sendEncodings??[]).map(e=>({...e}))),this.router.registerRtpSender(o.sender);let s=this.transceivers.findIndex(e=>e.currentDirection===`inactive`&&!e.usedForSender),c=this.transceivers.find(e=>e.currentDirection===`inactive`&&!e.usedForSender);return s>-1&&c?(this.replaceTransceiver(o,s),o.mLineIndex=c.mLineIndex,o.mid=c.mid,c.setCurrentDirection(void 0)):this.pushTransceiver(o),this.onTransceiverAdded.execute(o),o}addTrack(e,t=[]){if(this.getSenders().find(t=>t.track?.uuid===e.uuid))throw vz(`InvalidAccessError`,`Track already added`);let n=this.transceivers.find(t=>t.sender.track==null&&t.kind===e.kind&&DI.includes(t.direction)===!0);if(n){let r=n.sender;return r.setStreams(t),r.registerTrack(e),n.options={...n.options,streams:t},n}let r=this.transceivers.find(t=>t.sender.track==null&&t.kind===e.kind&&DI.includes(t.direction)===!1&&!t.usedForSender);if(r){let n=r.sender;switch(n.setStreams(t),n.registerTrack(e),r.options={...r.options,streams:t},r.direction){case`recvonly`:r.setDirection(`sendrecv`);break;case`inactive`:r.setDirection(`sendonly`)}return r}return this.addTransceiver(e,void 0,{direction:`sendrecv`,streams:t})}removeTrack(e){if(!this.getSenders().find(({ssrc:t})=>e.ssrc===t))throw vz(`InvalidAccessError`,`Sender does not exist`);let t=this.transceivers.find(({sender:{ssrc:t}})=>e.ssrc===t);if(!t)throw Error(`No matching transceiver found`);if(!(t.stopping||t.stopped)){if(e.stop(),[`recvonly`,`inactive`].includes(t.currentDirection??``)){this.onNegotiationNeeded.execute();return}t.direction===`sendrecv`?t.setDirection(`recvonly`):(t.direction===`sendonly`||t.direction===`recvonly`)&&t.setDirection(`inactive`)}}assignTransceiverCodecs(e){e.codecs=this.config.codecs[e.kind].filter(t=>{switch(t.direction){case`recvonly`:return!!OI.includes(e.direction);case`sendonly`:return!!DI.includes(e.direction);case`sendrecv`:return!![`sendrecv`,`recvonly`,`sendonly`].includes(e.direction);case`all`:return!0;default:return!1}})}getLocalRtpParams(e){if(e.mid==null)throw Error(`mid not assigned`);return{codecs:e.codecs,muxId:e.mid,headerExtensions:e.headerExtensions,rtcp:{cname:this.cname,ssrc:e.sender.ssrc,mux:!0}}}getRemoteRtpParams(e,t){return{muxId:e.rtp.muxId,rtcp:e.rtp.rtcp,codecs:t.codecs,headerExtensions:t.headerExtensions,encodings:Object.values(t.codecs.reduce((t,n)=>{if(n.name.toLowerCase()===`rtx`){let r=t[iz(n.parameters??``).apt];return r&&e.ssrc.length===2&&(r.rtx=new nI({ssrc:e.ssrc[1].ssrc})),t}return t[n.payloadType]=new rI({ssrc:e.ssrc[0]?.ssrc,payloadType:n.payloadType}),t},{}))}}setRemoteRTP(e,t,n,r){if(e.mid||=t.rtp.muxId??null,e.mLineIndex=r,e.codecs=t.rtp.codecs.filter(e=>{let n=this.config.codecs[t.kind]||[],r=kz(n,e);if(!r)return!1;if(r?.name.toLowerCase()===`rtx`){let e=iz(r.parameters??``).apt,i=t.rtp.codecs.find(t=>t.payloadType===e);return i?!!kz(n,i):!1}return!0}),Iz(`negotiated codecs`,e.codecs),e.codecs.length===0)throw Error(`negotiate codecs failed.`);e.headerExtensions=t.rtp.headerExtensions.filter(e=>(this.config.headerExtensions[t.kind]||[]).find(t=>t.uri===e.uri));let i=t.direction??`inactive`,a=KI(i);[`answer`,`pranswer`].includes(n)?e.setCurrentDirection(a):e.offerDirection=a;let o=this.getLocalRtpParams(e);if(e.sender.prepareSend(o),[`recvonly`,`sendrecv`].includes(e.direction)){let n=this.getRemoteRtpParams(t,e);for(let r of t.simulcastParameters)this.router.registerRtpReceiverByRid(e,r,n);e.receiver.prepareReceive(n),this.router.registerRtpReceiverBySsrc(e,n)}if(t.port!==0&&[`sendonly`,`sendrecv`].includes(i)){let n=[...new Set(t.msids.map(e=>e.split(` `)[0]))],r=t.msids[0]?.split(` `)[1];e.receiver.remoteStreamId=n[0],e.receiver.remoteStreamIds=n,e.receiver.remoteTrackId=r,this.onTrack.execute({track:e.receiver.track,transceiver:e,streams:n.map(t=>new RI({id:t,tracks:[e.receiver.track]}))})}t.ssrc[0]?.ssrc&&e.receiver.setupTWCC(t.ssrc[0].ssrc)}collectStats(e){let t=[];for(let n of this.transceivers){n.sender&&t.push(...n.sender.collectStats(e)),n.receiver&&t.push(...n.receiver.collectStats(e));let r=n.collectCodecStats(e);r&&t.push(...r)}return t}getStatsRootIds(e){if(!e)return[];let t=[];for(let n of this.transceivers)n.sender.track===e&&t.push(...n.sender.getStatsRootIds()),n.receiver.tracks.includes(e)&&t.push(...n.receiver.getStatsRootIds(e));return t}close(){for(let e of this.transceivers)e.forceStop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}},Rz={encode:e=>typeof e==`string`?e:Buffer.from(e),decode:e=>typeof e==`string`?e:Uint8Array.from(e).buffer};function zz(){let e=new Set,t=new WeakMap,n=!1,r=!1,i;function a(n){let a=t.get(n);if(a)return a;let o=n.close();return t.set(n,o),o.then(()=>e.delete(n),t=>{r||(i=t),r=!0,e.delete(n)}),o}return{createPeerConnection(t){if(n)throw Error(`Native room transport is closed`);let r=new Oz({iceServers:t.iceServers?.map(e=>({urls:e.urls})),bundlePolicy:t.bundlePolicy});return e.add(r),Aa(r,Rz,()=>a(r))},async close(){if(n=!0,await Promise.allSettled([...e].map(a)),r)throw i}}}function Bz(e){let t=Ea(e),n=new URL(t);if(n.protocol===`http:`&&![`localhost`,`127.0.0.1`,`[::1]`].includes(n.hostname))throw TypeError(`Native API keys require HTTPS except for loopback services.`);return t}async function Vz(e,n={}){let r=new URL(`.`,import.meta.url);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Room configuration must be an object`);let{serviceOrigin:i,apiKey:a,...o}=e;if(typeof a!=`string`||!/^b2d_[0-9a-f]{64}$/.test(a))throw TypeError(`A valid API key is required.`);n.signal?.throwIfAborted();let s=Bz(i??`https://ball2d.com`),c=vd(o),l=zz(),u=crypto.randomUUID(),d,f,p,m,h=new Promise((e,t)=>{p=e,m=t});h.catch(()=>{});try{let e=await _d.create(c,{network:{serviceOrigin:s,createWebSocket:e=>new WebSocket(e),createPeerConnection:l.createPeerConnection},request:async(e,t)=>{let n=new URL(e);if(n.origin===s&&n.pathname===ie.rooms&&t?.method===`POST`){let e=new Headers(t.headers);e.set(`Authorization`,`Bearer ${a}`),e.set(`Idempotency-Key`,u);let n=performance.now(),r=await fetch(new URL(ie.sdkRooms,s),{...t,headers:e,redirect:`error`});if(r.status===401)throw await r.body?.cancel(),new qu(`API key is invalid, expired or revoked. Create a key from your Ball2D account.`,401);if(r.ok){let e=await r.clone().json();d=new Qe(s,a,e.id,e.lease,n)}return r}return fetch(e,t)},loadEngine:async e=>ci.create(await t(new URL(`core.wasm`,r),{signal:e})),loadStadium:Ba(async e=>new Response(await t(new URL(`.${e}`,r),`utf8`)))},n.signal,n.matchXgTrust);if(f=e,n.signal?.throwIfAborted(),!d)throw Error(`Missing room authorization`);let i=()=>{queueMicrotask(()=>{Promise.allSettled([l.close(),d?.stop()]).then(e=>{let t=e.find(e=>e.status===`rejected`);t?.status===`rejected`?m(t.reason):p()})})};return e.signal.addEventListener(`abort`,i,{once:!0}),e.signal.aborted&&i(),{host:e,closed:h}}catch(e){let t=(await Promise.allSettled([()=>f?.close(),()=>d?.stop(),()=>l.close()].map(e=>Promise.resolve().then(e)))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);throw t.length?AggregateError([e,...t],`Room creation and cleanup failed`,{cause:e}):e}}var Hz=class{onError;pending=[];active;scheduled=!1;closed=!1;constructor(e=()=>{}){this.onError=e}enqueue(e){let t=new Promise((t,n)=>{if(this.closed){n(Error(`Room is closed`));return}if(this.pending.length>=256){n(Error(`Room command queue is full`));return}this.pending.push({run:e,resolve:e=>t(e),reject:n}),this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.drain()}))});return t.catch(e=>{if(!this.closed)try{this.onError(e)}catch{}}),t}async drain(){for(;!this.closed&&this.pending.length;){let e=this.pending.shift();if(!e)break;this.active=e;try{e.resolve(await e.run())}catch(t){e.reject(t)}this.active=void 0}this.scheduled=!1}close(){if(this.closed)return;this.closed=!0;let e=Error(`Room is closed`);this.active?.reject(e);for(let t of this.pending.splice(0))t.reject(e)}},Uz=`sendChat.sendAnnouncement.setPlayerAdmin.setPlayerMuted.setPlayerTeam.kickPlayer.clearBan.clearBans.setScoreLimit.setTimeLimit.setCustomStadium.setDefaultStadium.setTeamsLock.setTeamColors.startGame.stopGame.pauseGame.setPassword.setRequireVerification.reorderPlayers.setKickRateLimit.setPlayerAvatar.setDiscProperties.setPlayerDiscProperties.setMatchXgConfig.setCommentaryPolicy.setMatchIntelligencePolicy.setMatchIntelligenceRoles.setPlayerCommentaryContext.setCommentaryGeometry.setCommentaryCatalog.setAtmospherePolicy.setAtmospherePack`.split(`.`);function Wz(e,t){let n=Object.create(null);t&&Object.defineProperty(n,"closed",{enumerable:!0,value:t});let r=new Hz(t=>{let n=e.onError?.(String(t));n instanceof Promise&&n.catch(()=>{})});e.signal.addEventListener(`abort`,()=>r.close(),{once:!0}),e.signal.aborted&&r.close();for(let t of Uz)Object.defineProperty(n,t,{enumerable:!0,value:(...n)=>{try{let i=structuredClone(n);return(t===`setScoreLimit`||t===`setTimeLimit`)&&typeof i[0]==`number`&&Number.isInteger(i[0])&&(i[0]=Math.max(0,Math.min(99,i[0]))),r.enqueue(()=>Reflect.apply(e[t],e,i))}catch(e){return r.enqueue(()=>{throw e})}}});for(let t of[`getPlayer`,`getPlayerList`,`getScores`,`getBallPosition`,`getDiscCount`,`getDiscProperties`,`getPlayerDiscProperties`,`getState`,`getMatchXgStatus`,`getCommentaryPolicy`,`getMatchIntelligencePolicy`,`getMatchIntelligenceRoles`,`getMatchIntelligenceSnapshot`,`getPlayerCommentaryContext`,`getCommentaryGeometry`,`getCommentaryCatalog`,`getAtmospherePolicy`,`getAtmospherePack`,`startRecording`,`stopRecording`])Object.defineProperty(n,t,{enumerable:!0,value:e[t].bind(e)});for(let t of[`roomId`,`roomLink`,`roomName`,`lastRecording`,`requireVerification`,`CollisionFlags`,`signal`])Object.defineProperty(n,t,{enumerable:!0,get:()=>e[t]});for(let t of`onRoomLink.onMatchKickEstimate.onMatchFact.onMatchIntelligenceEvent.onMatchObservation.onPlayerJoin.onPlayerLeave.onPlayerChat.onPlayerDirectChat.onPlayerTeamChange.onPlayerAdminChange.onPlayerMuteChange.onPlayerKicked.onPlayerActivity.onPlayerInput.onPlayerBallKick.onTeamGoal.onTeamVictory.onGameVictory.onGameStart.onGameStop.onGameTick.onGamePause.onGameUnpause.onGamePauseChange.onPositionsReset.onStadiumChange.onTeamsLockChange.onKickRateLimitSet.onRecordingComplete.onError`.split(`.`)){let r;Object.defineProperty(n,t,{enumerable:!0,get:()=>r,set:i=>{if(i!=null&&typeof i!=`function`)throw Error(`Callback must be a function`);r=i,Reflect.set(e,t,i==null?void 0:(...e)=>Reflect.apply(i,n,e))}})}return Object.defineProperty(n,"close",{enumerable:!0,value:()=>{r.close(),e.close()}}),Object.preventExtensions(n)}function Gz(e){return ul(e)}function Kz(e){if(typeof e!=`string`)throw TypeError(`Stadium source must be a string`);let t=Or(e);return Object.freeze({name:t.name,canBeStored:t.canBeStored,warnings:Object.freeze([...t.warnings])})}async function qz(e,t={}){let{host:n,closed:r}=await Vz(e,t);return Wz(n,r)}export{qu as RoomAdmissionError,qz as createRoom,Gz as readReplay,Kz as validateStadium};
|