ball2d 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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);function ne(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 re=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=ne(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(`/api/sdk/rooms/${this.roomId}/lease`,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=ne(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(`/api/sdk/rooms/${this.roomId}/lease`,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)}},ie=n(`/`),ae;try{ae=ie(`worker_threads`),ae.Worker,ae.isMarkedAsUntransferable}catch{}var oe=Uint8Array,se=Uint16Array,ce=Int32Array,le=new oe([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]),ue=new oe([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]),de=new oe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),fe=function(e,t){for(var n=new se(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new ce(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}},ae=fe(le,2),pe=ae.b,me=ae.r;pe[28]=258,me[258]=28;for(var he=fe(ue,0),ge=he.b,_e=he.r,ve=new se(32768),ye=0;ye<32768;++ye){var be=(ye&43690)>>1|(ye&21845)<<1;be=(be&52428)>>2|(be&13107)<<2,be=(be&61680)>>4|(be&3855)<<4,ve[ye]=((be&65280)>>8|(be&255)<<8)>>1}for(var xe=(function(e,t,n){for(var r=e.length,i=0,a=new se(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new se(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new se(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[ve[d]>>c]=l}else for(s=new se(r),i=0;i<r;++i)e[i]&&(s[i]=ve[o[e[i]-1]++]>>15-e[i]);return s}),Se=new oe(288),ye=0;ye<144;++ye)Se[ye]=8;for(var ye=144;ye<256;++ye)Se[ye]=9;for(var ye=256;ye<280;++ye)Se[ye]=7;for(var ye=280;ye<288;++ye)Se[ye]=8;for(var Ce=new oe(32),ye=0;ye<32;++ye)Ce[ye]=5;var we=xe(Se,9,0),Te=xe(Se,9,1),Ee=xe(Ce,5,0),De=xe(Ce,5,1),Oe=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ke=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Ae=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},je=function(e){return(e+7)/8|0},Me=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new oe(e.subarray(t,n))},Ne=[`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`],Pe=function(e,t,n){var r=Error(t||Ne[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Pe),!n)throw r;return r},Fe=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new oe(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new oe(i*3));var l=function(e){var t=n.length;if(e>t){var r=new oe(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=ke(e,d,1);var v=ke(e,d+1,3);if(d+=3,!v){var y=je(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&Pe(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=Te,m=De,h=9,g=5;else if(v==2){var S=ke(e,d,31)+257,C=ke(e,d+10,15)+4,w=S+ke(e,d+5,31)+1;d+=14;for(var T=new oe(w),E=new oe(19),D=0;D<C;++D)E[de[D]]=ke(e,d+D*3,7);d+=C*3;for(var O=Oe(E),k=(1<<O)-1,A=xe(E,O,1),D=0;D<w;){var j=A[ke(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+ke(e,d,3),d+=2,M=T[D-1]):y==17?(N=3+ke(e,d,7),d+=3):y==18&&(N=11+ke(e,d,127),d+=7);N--;)T[D++]=M}}var P=T.subarray(0,S),F=T.subarray(S);h=Oe(P),g=Oe(F),p=xe(P,h,1),m=xe(F,g,1)}else Pe(1);if(d>_){c&&Pe(0);break}}s&&l(f+131072);for(var I=(1<<h)-1,L=(1<<g)-1,R=d;;R=d){var M=p[Ae(e,d)&I],z=M>>4;if(d+=M&15,d>_){c&&Pe(0);break}if(M||Pe(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=le[D];B=ke(e,d,(1<<V)-1)+pe[D],d+=V}var ee=m[Ae(e,d)&L],te=ee>>4;ee||Pe(3),d+=ee&15;var F=ge[te];if(te>3){var V=ue[te];F+=Ae(e,d)&(1<<V)-1,d+=V}if(d>_){c&&Pe(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&&Pe(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?Me(n,0,f):n.subarray(0,f)},Ie=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},Le=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},Re=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:Ge,l:0};if(i==1){var o=new oe(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 se(f+1),m=ze(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 oe(p),l:m}},ze=function(e,t,n){return e.s==-1?Math.max(ze(e.l,t,n+1),ze(e.r,t,n+1)):t[e.s]=n},Be=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new se(++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}},Ve=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},He=function(e,t,n){var r=n.length,i=je(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},Ue=function(e,t,n,r,i,a,o,s,c,l,u){Ie(t,u++,n),++i[256];for(var d=Re(i,15),f=d.t,p=d.l,m=Re(a,15),h=m.t,g=m.l,_=Be(f),v=_.c,y=_.n,b=Be(h),x=b.c,S=b.n,C=new se(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=Re(C,7),E=T.t,D=T.l,O=19;O>4&&!E[de[O-1]];--O);var k=l+5<<3,A=Ve(i,Se)+Ve(a,Ce)+o,j=Ve(i,f)+Ve(a,h)+o+14+3*O+Ve(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&k<=A&&k<=j)return He(t,u,e.subarray(c,c+l));var M,N,P,F;if(Ie(t,u,1+(j<A)),u+=2,j<A){M=xe(f,p,0),N=f,P=xe(h,g,0),F=h;var I=xe(E,D,0);Ie(t,u,y-257),Ie(t,u+5,S-1),Ie(t,u+10,O-4),u+=14;for(var w=0;w<O;++w)Ie(t,u+3*w,E[de[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;Ie(t,u,I[B]),u+=E[B],B>15&&(Ie(t,u,z[w]>>5&127),u+=z[w]>>12)}}else M=we,N=Se,P=Ee,F=Ce;for(var w=0;w<s;++w){var V=r[w];if(V>255){var B=V>>18&31;Le(t,u,M[B+257]),u+=N[B+257],B>7&&(Ie(t,u,V>>23&31),u+=le[B]);var ee=V&31;Le(t,u,P[ee]),u+=F[ee],ee>3&&(Le(t,u,V>>5&8191),u+=ue[ee])}else Le(t,u,M[V]),u+=N[V]}return Le(t,u,M[256]),u+N[256]},We=new ce([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ge=new oe(0),Ke=function(e,t,n,r,i,a){var o=a.z||e.length,s=new oe(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=We[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new se(32768),g=a.h||new se(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new ce(25e3),x=new se(288),S=new se(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=Ue(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|me[P]<<18|_e[F];var ie=me[P]&31,ae=_e[F]&31;w+=le[ie]+ue[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=Ue(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 de=T+65535;de>=o&&(c[u/8|0]=l,de=o),u=He(c,u+1,e.subarray(T,de))}a.i=o}return Me(s,0,r+je(u)+i)},qe=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new oe(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return Ke(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 Je(e,t){return qe(e,t||{},0,0)}var Ye=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 oe(32768),this.p=new oe(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||Pe(5),this.d&&Pe(4),!this.p.length)this.p=e;else if(e.length){var t=new oe(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=Fe(this.p,this.s,this.o);this.ondata(Me(n,t,this.s.b),this.d),this.o=Me(n,this.s.b-32768),this.s.b=this.o.length,this.p=Me(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),Xe=typeof TextDecoder<`u`&&new TextDecoder;try{Xe.decode(Ge,{stream:!0})}catch{}var Ze=5389,Qe=(e,t,n)=>Number.isInteger(e)&&e>=t&&e<=n,$e=e=>Number.isFinite(e)&&e>=1&&e<=1e5,et=class{core;enabled=!1;constructor(e){if(this.core=e,e.surface_state_capacity()!==5389)throw Error(`Unsupported surface state version`)}configure(e){if(!Qe(e.seed,0,4294967295)||!$e(e.halfWidth)||!$e(e.halfHeight)||!Qe(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(!Qe(e.rainMilliMmH,0,2e5)||!Qe(e.temperatureMilliC,-3e4,6e4)||!Qe(e.humidityPermille,0,1e3)||!Qe(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=>Qe(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,Ze)}},tt=131072,nt=49152,rt=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});var it=(e,t)=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=t;function at(e,t){if(!it(t,65535)||!it(e.tick,4294967295)||!Array.isArray(e.surface)||e.surface.length!==5389)throw Error(`Invalid terrain snapshot`);let n=rt.encode(JSON.stringify(e));if(n.length>tt)throw Error(`Terrain snapshot exceeds size limit`);let r=Je(n,{level:1});if(r.length>nt)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 ot(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 st=new Set([`noPlayer`,`playerName`,`roomName`,`maxPlayers`,`password`,`public`,`stadium`]);function ct(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(!st.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 lt(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 ut(e){let t=lt(e);if(!t)throw Error(`Invalid room code`);return`/r/${t}`}function dt(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 ft(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:dt(e.angle,e.textColor,e.colors))}var pt=[`normal`,`bold`,`italic`,`small`,`small-bold`,`small-italic`];function mt(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&&!pt.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 ht(e){return e===null||typeof e==`string`&&Array.from(e).length<=2&&!/[\p{Cc}\p{Cf}]/u.test(e)}var gt=[[`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 _t(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid disc property update`);let t=e,n={};for(let e=0;e<gt.length;e++){let[r,,i,a]=gt[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 vt=`edb227eac070ad86a151`,yt={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]/},bt={isSpaceSeparator(e){return typeof e==`string`&&yt.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||yt.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===`‍`||yt.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)}},xt,St,Ct,wt,Tt,Et,Dt,Ot,kt,At=function(e,t){xt=String(e),St=`start`,Ct=[],wt=0,Tt=1,Et=0,Dt=void 0,Ot=void 0,kt=void 0;do Dt=Lt(),Gt[St]();while(Dt.type!==`eof`);return typeof t==`function`?jt({"":kt},``,t):kt};function jt(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=jt(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=jt(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 Mt,Nt,Pt,Ft,It;function Lt(){for(Mt=`default`,Nt=``,Pt=!1,Ft=1;;){It=Rt();let e=zt[Mt]();if(e)return e}}function Rt(){if(xt[wt])return String.fromCodePoint(xt.codePointAt(wt))}function H(){let e=Rt();return e===`
2
- `?(Tt++,Et=0):e?Et+=e.length:Et++,e&&(wt+=e.length),e}var zt={default(){switch(It){case` `:case`\v`:case`\f`:case` `:case`\xA0`:case``:case`
3
- `:case`\r`:case`\u2028`:case`\u2029`:H();return;case`/`:H(),Mt=`comment`;return;case void 0:return H(),Bt(`eof`)}if(bt.isSpaceSeparator(It)){H();return}return zt[St]()},comment(){switch(It){case`*`:H(),Mt=`multiLineComment`;return;case`/`:H(),Mt=`singleLineComment`;return}throw Jt(H())},multiLineComment(){switch(It){case`*`:H(),Mt=`multiLineCommentAsterisk`;return;case void 0:throw Jt(H())}H()},multiLineCommentAsterisk(){switch(It){case`*`:H();return;case`/`:H(),Mt=`default`;return;case void 0:throw Jt(H())}H(),Mt=`multiLineComment`},singleLineComment(){switch(It){case`
4
- `:case`\r`:case`\u2028`:case`\u2029`:H(),Mt=`default`;return;case void 0:return H(),Bt(`eof`)}H()},value(){switch(It){case`{`:case`[`:return Bt(`punctuator`,H());case`n`:return H(),Vt(`ull`),Bt(`null`,null);case`t`:return H(),Vt(`rue`),Bt(`boolean`,!0);case`f`:return H(),Vt(`alse`),Bt(`boolean`,!1);case`-`:case`+`:H()===`-`&&(Ft=-1),Mt=`sign`;return;case`.`:Nt=H(),Mt=`decimalPointLeading`;return;case`0`:Nt=H(),Mt=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Nt=H(),Mt=`decimalInteger`;return;case`I`:return H(),Vt(`nfinity`),Bt(`numeric`,1/0);case`N`:return H(),Vt(`aN`),Bt(`numeric`,NaN);case`"`:case`'`:Pt=H()===`"`,Nt=``,Mt=`string`;return}throw Jt(H())},identifierNameStartEscape(){if(It!==`u`)throw Jt(H());H();let e=Wt();switch(e){case`$`:case`_`:break;default:if(!bt.isIdStartChar(e))throw Xt()}Nt+=e,Mt=`identifierName`},identifierName(){switch(It){case`$`:case`_`:case`‌`:case`‍`:Nt+=H();return;case`\\`:H(),Mt=`identifierNameEscape`;return}if(bt.isIdContinueChar(It)){Nt+=H();return}return Bt(`identifier`,Nt)},identifierNameEscape(){if(It!==`u`)throw Jt(H());H();let e=Wt();switch(e){case`$`:case`_`:case`‌`:case`‍`:break;default:if(!bt.isIdContinueChar(e))throw Xt()}Nt+=e,Mt=`identifierName`},sign(){switch(It){case`.`:Nt=H(),Mt=`decimalPointLeading`;return;case`0`:Nt=H(),Mt=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Nt=H(),Mt=`decimalInteger`;return;case`I`:return H(),Vt(`nfinity`),Bt(`numeric`,Ft*(1/0));case`N`:return H(),Vt(`aN`),Bt(`numeric`,NaN)}throw Jt(H())},zero(){switch(It){case`.`:Nt+=H(),Mt=`decimalPoint`;return;case`e`:case`E`:Nt+=H(),Mt=`decimalExponent`;return;case`x`:case`X`:Nt+=H(),Mt=`hexadecimal`;return}return Bt(`numeric`,Ft*0)},decimalInteger(){switch(It){case`.`:Nt+=H(),Mt=`decimalPoint`;return;case`e`:case`E`:Nt+=H(),Mt=`decimalExponent`;return}if(bt.isDigit(It)){Nt+=H();return}return Bt(`numeric`,Ft*Number(Nt))},decimalPointLeading(){if(bt.isDigit(It)){Nt+=H(),Mt=`decimalFraction`;return}throw Jt(H())},decimalPoint(){switch(It){case`e`:case`E`:Nt+=H(),Mt=`decimalExponent`;return}if(bt.isDigit(It)){Nt+=H(),Mt=`decimalFraction`;return}return Bt(`numeric`,Ft*Number(Nt))},decimalFraction(){switch(It){case`e`:case`E`:Nt+=H(),Mt=`decimalExponent`;return}if(bt.isDigit(It)){Nt+=H();return}return Bt(`numeric`,Ft*Number(Nt))},decimalExponent(){switch(It){case`+`:case`-`:Nt+=H(),Mt=`decimalExponentSign`;return}if(bt.isDigit(It)){Nt+=H(),Mt=`decimalExponentInteger`;return}throw Jt(H())},decimalExponentSign(){if(bt.isDigit(It)){Nt+=H(),Mt=`decimalExponentInteger`;return}throw Jt(H())},decimalExponentInteger(){if(bt.isDigit(It)){Nt+=H();return}return Bt(`numeric`,Ft*Number(Nt))},hexadecimal(){if(bt.isHexDigit(It)){Nt+=H(),Mt=`hexadecimalInteger`;return}throw Jt(H())},hexadecimalInteger(){if(bt.isHexDigit(It)){Nt+=H();return}return Bt(`numeric`,Ft*Number(Nt))},string(){switch(It){case`\\`:H(),Nt+=Ht();return;case`"`:if(Pt)return H(),Bt(`string`,Nt);Nt+=H();return;case`'`:if(!Pt)return H(),Bt(`string`,Nt);Nt+=H();return;case`
5
- `:case`\r`:throw Jt(H());case`\u2028`:case`\u2029`:Zt(It);break;case void 0:throw Jt(H())}Nt+=H()},start(){switch(It){case`{`:case`[`:return Bt(`punctuator`,H())}Mt=`value`},beforePropertyName(){switch(It){case`$`:case`_`:Nt=H(),Mt=`identifierName`;return;case`\\`:H(),Mt=`identifierNameStartEscape`;return;case`}`:return Bt(`punctuator`,H());case`"`:case`'`:Pt=H()===`"`,Mt=`string`;return}if(bt.isIdStartChar(It)){Nt+=H(),Mt=`identifierName`;return}throw Jt(H())},afterPropertyName(){if(It===`:`)return Bt(`punctuator`,H());throw Jt(H())},beforePropertyValue(){Mt=`value`},afterPropertyValue(){switch(It){case`,`:case`}`:return Bt(`punctuator`,H())}throw Jt(H())},beforeArrayValue(){if(It===`]`)return Bt(`punctuator`,H());Mt=`value`},afterArrayValue(){switch(It){case`,`:case`]`:return Bt(`punctuator`,H())}throw Jt(H())},end(){throw Jt(H())}};function Bt(e,t){return{type:e,value:t,line:Tt,column:Et}}function Vt(e){for(let t of e){if(Rt()!==t)throw Jt(H());H()}}function Ht(){switch(Rt()){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(),bt.isDigit(Rt()))throw Jt(H());return`\0`;case`x`:return H(),Ut();case`u`:return H(),Wt();case`
7
- `:case`\u2028`:case`\u2029`:return H(),``;case`\r`:return H(),Rt()===`
8
- `&&H(),``;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:throw Jt(H());case void 0:throw Jt(H())}return H()}function Ut(){let e=``,t=Rt();if(!bt.isHexDigit(t)||(e+=H(),t=Rt(),!bt.isHexDigit(t)))throw Jt(H());return e+=H(),String.fromCodePoint(parseInt(e,16))}function Wt(){let e=``,t=4;for(;t-->0;){let t=Rt();if(!bt.isHexDigit(t))throw Jt(H());e+=H()}return String.fromCodePoint(parseInt(e,16))}var Gt={start(){if(Dt.type===`eof`)throw Yt();Kt()},beforePropertyName(){switch(Dt.type){case`identifier`:case`string`:Ot=Dt.value,St=`afterPropertyName`;return;case`punctuator`:qt();return;case`eof`:throw Yt()}},afterPropertyName(){if(Dt.type===`eof`)throw Yt();St=`beforePropertyValue`},beforePropertyValue(){if(Dt.type===`eof`)throw Yt();Kt()},beforeArrayValue(){if(Dt.type===`eof`)throw Yt();if(Dt.type===`punctuator`&&Dt.value===`]`){qt();return}Kt()},afterPropertyValue(){if(Dt.type===`eof`)throw Yt();switch(Dt.value){case`,`:St=`beforePropertyName`;return;case`}`:qt()}},afterArrayValue(){if(Dt.type===`eof`)throw Yt();switch(Dt.value){case`,`:St=`beforeArrayValue`;return;case`]`:qt()}},end(){}};function Kt(){let e;switch(Dt.type){case`punctuator`:switch(Dt.value){case`{`:e={};break;case`[`:e=[]}break;case`null`:case`boolean`:case`numeric`:case`string`:e=Dt.value}if(kt===void 0)kt=e;else{let t=Ct[Ct.length-1];Array.isArray(t)?t.push(e):Object.defineProperty(t,Ot,{value:e,writable:!0,enumerable:!0,configurable:!0})}if(typeof e==`object`&&e)Ct.push(e),St=Array.isArray(e)?`beforeArrayValue`:`beforePropertyName`;else{let e=Ct[Ct.length-1];St=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}}function qt(){Ct.pop();let e=Ct[Ct.length-1];St=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}function Jt(e){return $t(e===void 0?`JSON5: invalid end of input at ${Tt}:${Et}`:`JSON5: invalid character '${Qt(e)}' at ${Tt}:${Et}`)}function Yt(){return $t(`JSON5: invalid end of input at ${Tt}:${Et}`)}function Xt(){return Et-=5,$t(`JSON5: invalid identifier character at ${Tt}:${Et}`)}function Zt(e){console.warn(`JSON5: '${Qt(e)}' in strings is not valid ECMAScript; consider escaping`)}function Qt(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 $t(e){let t=SyntaxError(e);return t.lineNumber=Tt,t.columnNumber=Et,t}var en={parse:At,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(bt.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=`,
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
+ `?(Ft++,It=0):e?It+=e.length:It++,e&&(Pt+=e.length),e}var Yt={default(){switch(Kt){case` `:case`\v`:case`\f`:case` `:case`\xA0`:case``:case`
3
+ `:case`\r`:case`\u2028`:case`\u2029`:H();return;case`/`:H(),Ht=`comment`;return;case void 0:return H(),Xt(`eof`)}if(At.isSpaceSeparator(Kt)){H();return}return Yt[Mt]()},comment(){switch(Kt){case`*`:H(),Ht=`multiLineComment`;return;case`/`:H(),Ht=`singleLineComment`;return}throw an(H())},multiLineComment(){switch(Kt){case`*`:H(),Ht=`multiLineCommentAsterisk`;return;case void 0:throw an(H())}H()},multiLineCommentAsterisk(){switch(Kt){case`*`:H();return;case`/`:H(),Ht=`default`;return;case void 0:throw an(H())}H(),Ht=`multiLineComment`},singleLineComment(){switch(Kt){case`
4
+ `:case`\r`:case`\u2028`:case`\u2029`:H(),Ht=`default`;return;case void 0:return H(),Xt(`eof`)}H()},value(){switch(Kt){case`{`:case`[`:return Xt(`punctuator`,H());case`n`:return H(),Zt(`ull`),Xt(`null`,null);case`t`:return H(),Zt(`rue`),Xt(`boolean`,!0);case`f`:return H(),Zt(`alse`),Xt(`boolean`,!1);case`-`:case`+`:H()===`-`&&(Gt=-1),Ht=`sign`;return;case`.`:Ut=H(),Ht=`decimalPointLeading`;return;case`0`:Ut=H(),Ht=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Ut=H(),Ht=`decimalInteger`;return;case`I`:return H(),Zt(`nfinity`),Xt(`numeric`,1/0);case`N`:return H(),Zt(`aN`),Xt(`numeric`,NaN);case`"`:case`'`:Wt=H()===`"`,Ut=``,Ht=`string`;return}throw an(H())},identifierNameStartEscape(){if(Kt!==`u`)throw an(H());H();let e=en();switch(e){case`$`:case`_`:break;default:if(!At.isIdStartChar(e))throw sn()}Ut+=e,Ht=`identifierName`},identifierName(){switch(Kt){case`$`:case`_`:case`‌`:case`‍`:Ut+=H();return;case`\\`:H(),Ht=`identifierNameEscape`;return}if(At.isIdContinueChar(Kt)){Ut+=H();return}return Xt(`identifier`,Ut)},identifierNameEscape(){if(Kt!==`u`)throw an(H());H();let e=en();switch(e){case`$`:case`_`:case`‌`:case`‍`:break;default:if(!At.isIdContinueChar(e))throw sn()}Ut+=e,Ht=`identifierName`},sign(){switch(Kt){case`.`:Ut=H(),Ht=`decimalPointLeading`;return;case`0`:Ut=H(),Ht=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Ut=H(),Ht=`decimalInteger`;return;case`I`:return H(),Zt(`nfinity`),Xt(`numeric`,Gt*(1/0));case`N`:return H(),Zt(`aN`),Xt(`numeric`,NaN)}throw an(H())},zero(){switch(Kt){case`.`:Ut+=H(),Ht=`decimalPoint`;return;case`e`:case`E`:Ut+=H(),Ht=`decimalExponent`;return;case`x`:case`X`:Ut+=H(),Ht=`hexadecimal`;return}return Xt(`numeric`,Gt*0)},decimalInteger(){switch(Kt){case`.`:Ut+=H(),Ht=`decimalPoint`;return;case`e`:case`E`:Ut+=H(),Ht=`decimalExponent`;return}if(At.isDigit(Kt)){Ut+=H();return}return Xt(`numeric`,Gt*Number(Ut))},decimalPointLeading(){if(At.isDigit(Kt)){Ut+=H(),Ht=`decimalFraction`;return}throw an(H())},decimalPoint(){switch(Kt){case`e`:case`E`:Ut+=H(),Ht=`decimalExponent`;return}if(At.isDigit(Kt)){Ut+=H(),Ht=`decimalFraction`;return}return Xt(`numeric`,Gt*Number(Ut))},decimalFraction(){switch(Kt){case`e`:case`E`:Ut+=H(),Ht=`decimalExponent`;return}if(At.isDigit(Kt)){Ut+=H();return}return Xt(`numeric`,Gt*Number(Ut))},decimalExponent(){switch(Kt){case`+`:case`-`:Ut+=H(),Ht=`decimalExponentSign`;return}if(At.isDigit(Kt)){Ut+=H(),Ht=`decimalExponentInteger`;return}throw an(H())},decimalExponentSign(){if(At.isDigit(Kt)){Ut+=H(),Ht=`decimalExponentInteger`;return}throw an(H())},decimalExponentInteger(){if(At.isDigit(Kt)){Ut+=H();return}return Xt(`numeric`,Gt*Number(Ut))},hexadecimal(){if(At.isHexDigit(Kt)){Ut+=H(),Ht=`hexadecimalInteger`;return}throw an(H())},hexadecimalInteger(){if(At.isHexDigit(Kt)){Ut+=H();return}return Xt(`numeric`,Gt*Number(Ut))},string(){switch(Kt){case`\\`:H(),Ut+=Qt();return;case`"`:if(Wt)return H(),Xt(`string`,Ut);Ut+=H();return;case`'`:if(!Wt)return H(),Xt(`string`,Ut);Ut+=H();return;case`
5
+ `:case`\r`:throw an(H());case`\u2028`:case`\u2029`:cn(Kt);break;case void 0:throw an(H())}Ut+=H()},start(){switch(Kt){case`{`:case`[`:return Xt(`punctuator`,H())}Ht=`value`},beforePropertyName(){switch(Kt){case`$`:case`_`:Ut=H(),Ht=`identifierName`;return;case`\\`:H(),Ht=`identifierNameStartEscape`;return;case`}`:return Xt(`punctuator`,H());case`"`:case`'`:Wt=H()===`"`,Ht=`string`;return}if(At.isIdStartChar(Kt)){Ut+=H(),Ht=`identifierName`;return}throw an(H())},afterPropertyName(){if(Kt===`:`)return Xt(`punctuator`,H());throw an(H())},beforePropertyValue(){Ht=`value`},afterPropertyValue(){switch(Kt){case`,`:case`}`:return Xt(`punctuator`,H())}throw an(H())},beforeArrayValue(){if(Kt===`]`)return Xt(`punctuator`,H());Ht=`value`},afterArrayValue(){switch(Kt){case`,`:case`]`:return Xt(`punctuator`,H())}throw an(H())},end(){throw an(H())}};function Xt(e,t){return{type:e,value:t,line:Ft,column:It}}function Zt(e){for(let t of e){if(Jt()!==t)throw an(H());H()}}function Qt(){switch(Jt()){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(),At.isDigit(Jt()))throw an(H());return`\0`;case`x`:return H(),$t();case`u`:return H(),en();case`
7
+ `:case`\u2028`:case`\u2029`:return H(),``;case`\r`:return H(),Jt()===`
8
+ `&&H(),``;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:throw an(H());case void 0:throw an(H())}return H()}function $t(){let e=``,t=Jt();if(!At.isHexDigit(t)||(e+=H(),t=Jt(),!At.isHexDigit(t)))throw an(H());return e+=H(),String.fromCodePoint(parseInt(e,16))}function en(){let e=``,t=4;for(;t-->0;){let t=Jt();if(!At.isHexDigit(t))throw an(H());e+=H()}return String.fromCodePoint(parseInt(e,16))}var tn={start(){if(Lt.type===`eof`)throw on();nn()},beforePropertyName(){switch(Lt.type){case`identifier`:case`string`:Rt=Lt.value,Mt=`afterPropertyName`;return;case`punctuator`:rn();return;case`eof`:throw on()}},afterPropertyName(){if(Lt.type===`eof`)throw on();Mt=`beforePropertyValue`},beforePropertyValue(){if(Lt.type===`eof`)throw on();nn()},beforeArrayValue(){if(Lt.type===`eof`)throw on();if(Lt.type===`punctuator`&&Lt.value===`]`){rn();return}nn()},afterPropertyValue(){if(Lt.type===`eof`)throw on();switch(Lt.value){case`,`:Mt=`beforePropertyName`;return;case`}`:rn()}},afterArrayValue(){if(Lt.type===`eof`)throw on();switch(Lt.value){case`,`:Mt=`beforeArrayValue`;return;case`]`:rn()}},end(){}};function nn(){let e;switch(Lt.type){case`punctuator`:switch(Lt.value){case`{`:e={};break;case`[`:e=[]}break;case`null`:case`boolean`:case`numeric`:case`string`:e=Lt.value}if(zt===void 0)zt=e;else{let t=Nt[Nt.length-1];Array.isArray(t)?t.push(e):Object.defineProperty(t,Rt,{value:e,writable:!0,enumerable:!0,configurable:!0})}if(typeof e==`object`&&e)Nt.push(e),Mt=Array.isArray(e)?`beforeArrayValue`:`beforePropertyName`;else{let e=Nt[Nt.length-1];Mt=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}}function rn(){Nt.pop();let e=Nt[Nt.length-1];Mt=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}function an(e){return un(e===void 0?`JSON5: invalid end of input at ${Ft}:${It}`:`JSON5: invalid character '${ln(e)}' at ${Ft}:${It}`)}function on(){return un(`JSON5: invalid end of input at ${Ft}:${It}`)}function sn(){return It-=5,un(`JSON5: invalid identifier character at ${Ft}:${It}`)}function cn(e){console.warn(`JSON5: '${ln(e)}' in strings is not valid ECMAScript; consider escaping`)}function ln(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 un(e){let t=SyntaxError(e);return t.lineNumber=Ft,t.columnNumber=It,t}var dn={parse:Bt,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(At.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(!bt.isIdStartChar(t))return u(e,!0);for(let n=t.length;n<e.length;n++)if(!bt.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=`,
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(!At.isIdStartChar(t))return u(e,!0);for(let n=t.length;n<e.length;n++)if(!At.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}}},tn={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},nn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Expected an object`);return e},rn=(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},an=(e,t=[0,0])=>{if(e===void 0)return[...t];if(!Array.isArray(e)||e.length!==2)throw Error(`Expected [x, y]`);return[rn(e[0],0),rn(e[1],0)]},on=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.length>t)throw Error(`Array limit: ${t}`);return e};function sn(e,t){return e===void 0?t:typeof e==`number`?rn(e,t,-2147483648,4294967295)|0:on(e,16).reduce((e,t)=>{if(typeof t!=`string`||!Object.hasOwn(tn,t))throw Error(`Unknown collision flag`);return e|tn[t]},0)}function cn(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(rn(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 ln=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(` `))])),un=new Set([`vertexes`,`segments`,`discs`,`planes`,`goals`,`joints`,`playerPhysics`].flatMap(e=>[...ln[e]]));function dn(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,ln.root,`$`),r(e.bg,ln.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,ln[t],`$.`+t+`[`+n+`]`))}if(r(e.ballPhysics,ln.discs,`$.ballPhysics`),r(e.playerPhysics,ln.playerPhysics,`$.playerPhysics`),e.traits&&typeof e.traits==`object`&&!Array.isArray(e.traits))for(let[t,i]of Object.entries(e.traits))r(i,un,n(`$.traits`,t));return t}function fn(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 pn(e){if(new TextEncoder().encode(e).length>262144)throw Error(`Stadium exceeds 256 KB`);let t=nn(en.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?{}:nn(t.traits),i=e=>{let t=nn(e);if(t.trait===void 0)return t;if(typeof t.trait!=`string`||!Object.hasOwn(r,t.trait))throw Error(`Unknown trait`);return{...nn(r[t.trait]),...t}},a=(e,t=!1)=>({pos:an(e.pos),speed:an(e.speed),gravity:an(e.gravity),radius:rn(e.radius,10,.5,100),invMass:rn(e.invMass,1,0,8192),damping:rn(e.damping,.99,0,8192),bCoef:rn(e.bCoef,.5,-1,8192),cGroup:sn(e.cGroup,t?193:63),cMask:sn(e.cMask,63),color:cn(e.color)}),o=on(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=on(t.vertexes,1024).map(e=>i(e)),c=[],l=[],u=dn(t);for(let e of s)c.push({a:[rn(e.x,0),rn(e.y,0)],b:[rn(e.x,0),rn(e.y,0)],bCoef:rn(e.bCoef,1,-1,8192),cGroup:sn(e.cGroup,32),cMask:sn(e.cMask,63),bias:0,color:`transparent`,vis:!1});let d=[...c];for(let e of on(t.segments,1024)){let t=i(e),n=rn(t.v0,-1,0,s.length-1),r=rn(t.v1,-1,0,s.length-1);if(!Number.isInteger(n)||!Number.isInteger(r))throw Error(`Vertex indices must be integers`);let a=[rn(s[n].x,0),rn(s[n].y,0)],o=[rn(s[r].x,0),rn(s[r].y,0)],u={bCoef:rn(t.bCoef,1,-1,8192),cGroup:sn(t.cGroup,32),cMask:sn(t.cMask,63),bias:rn(t.bias,0,-100,100),color:cn(t.color,`000000`),vis:t.vis!==!1},f=t.curveF===void 0?rn(t.curve,0,-359,359):2*Math.atan2(1,rn(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:rn(f.acceleration,.1,-8192,8192),kickingAcceleration:rn(f.kickingAcceleration,.07,-8192,8192),kickingDamping:rn(f.kickingDamping,.96,0,8192),kickStrength:rn(f.kickStrength,5,-8192,8192),kickback:rn(f.kickback,0,-8192,8192)};fn(n,o.length,c.length,on(t.planes,64).length+on(t.joints,128).length,Math.min(p.radius,...o.map(e=>e.radius)));let m=t.bg===void 0?{}:nn(t.bg);return{version:1,physicsMode:n,name:typeof t.name==`string`?t.name.slice(0,64):`Untitled stadium`,canBeStored:t.canBeStored!==!1,width:rn(t.width,520,100,2048),height:rn(t.height,300,80,2048),maxViewWidth:rn(t.maxViewWidth,0,0,4096),cameraFollow:t.cameraFollow===`player`?`player`:`ball`,bg:{type:m.type===`grass`?`grass`:m.type===`hockey`?`hockey`:`none`,cornerRadius:rn(m.cornerRadius,0,0,500),goalLine:rn(m.goalLine,0,0,2048),width:rn(m.width,0,0,2048),height:rn(m.height,0,0,2048),color:cn(m.color,`718C5A`),kickOffRadius:rn(m.kickOffRadius,0,0,500)},discs:o,segments:c,arcs:l,colliders:d,player:p,spawnDistance:rn(t.spawnDistance,200,0,1500),kickOffReset:t.kickOffReset===`full`?`full`:`partial`,redSpawnPoints:on(t.redSpawnPoints,32).map(e=>an(e)),blueSpawnPoints:on(t.blueSpawnPoints,32).map(e=>an(e)),warnings:u,planes:on(t.planes,64).map(e=>{let t=i(e),n=an(t.normal);if(Math.hypot(...n)<1e-6)throw Error(`Plane normal is zero`);return{normal:n,dist:rn(t.dist,0),bCoef:rn(t.bCoef,1,-1,8192),cGroup:sn(t.cGroup,32),cMask:sn(t.cMask,63)}}),goals:on(t.goals,16).map(e=>{let t=i(e);if(t.team!==`red`&&t.team!==`blue`)throw Error(`Invalid goal team`);let n=an(t.p0),r=an(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:on(t.joints,128).map(e=>{let t=i(e),n=rn(t.d0,-1,0,o.length-1),r=rn(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]:an(t.length);return{d0:n,d1:r,min:rn(s[0],0,0),max:rn(s[1],0,0),strength:t.strength===void 0||t.strength===`rigid`?`rigid`:rn(t.strength,0,-8192,8192),color:cn(t.color,`000000`)}})}}function mn(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 hn=`ball2d-core/1/${vt}`,gn=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=_n(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 et(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=edb227eac070ad86a151`,{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=pn(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<32;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>=32)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=_t(t),i=!1;for(let[t,a]of gt){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]));fn(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 gt){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<32;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<32;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]);fn(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 _n(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 vn(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 yn(){return{serviceOrigin:location.origin,signalingResume:!0,createWebSocket:e=>new WebSocket(e),createPeerConnection:e=>new RTCPeerConnection(e)}}var bn=[[`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 xn(e){let t=new Map;return async n=>{let r=bn.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 pn(n),n})(),t.set(r[0],i),i.catch(()=>t.delete(r[0]))),i}}function Sn(){let e=yn(),t=(e,t)=>fetch(e,t);return{network:e,request:t,loadEngine:e=>gn.create(void 0,e),loadStadium:xn(n=>t(new URL(n,e.serviceOrigin)))}}var Cn={message:{burst:240,perSecond:160},action:{burst:12,perSecond:6},chat:{burst:4,perSecond:1}},wn=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}=Cn[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()}},Tn=33554432,En=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});function Dn(e){let t=2166136261;for(let n of e)t=Math.imul(t^n,16777619);return t>>>0}function On(e){if(e.length>33554432)throw Error(`Replay exceeds 32 MB`);let t=Je(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,Dn(e),!0),n.set(t,16),n}function kn(e){if(typeof e==`string`){if(En.encode(e).length>33554432)throw Error(`Replay exceeds 32 MB`);return En.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 Ye((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||Dn(i)!==n.getUint32(12,!0))throw Error(`Compressed replay integrity failure`);return i}var An=[`input`,`team`,`start`,`stop`,`pause`,`scoreLimit`,`timeLimit`,`kickRate`,`join`,`disc`,`surface`],jn=new TextEncoder,Mn=new TextDecoder(`utf-8`,{fatal:!0});function Nn(e){return On(Pn(e))}function Pn(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=jn.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(Tn,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=An.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=_t(e.properties),n=0;gt.forEach(([e],r)=>{t[e]!==void 0&&(n|=1<<r)}),p(n);for(let[e]of gt){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 Fn(e){let t=kn(e);if(t[0]!==66||t[1]!==50||t[2]!==68||t[3]!==80)return JSON.parse(Mn.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(Mn.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=An[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={};gt.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:_t(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 In(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 Ln(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`: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 Rn=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:hn,stadium:e.source,initial:r,commands:[],checkpoints:[],roster:t.map(e=>({...e,tick:r.tick})),styles:[{tick:r.tick,teams:ft(n)}],orders:[{tick:r.tick,slots:[...this.playerOrder]}],end:r.tick,finalHash:In(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:ft(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:_t(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:In(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=In(e.snapshot()),Pn(this.replay)}finish(e){return this.replay.end=e.tick,this.replay.finalHash=In(e.snapshot()),new Blob([Nn(this.replay)],{type:`application/x-ball2d-replay`})}};async function zn(e){if(e.size>33554432)throw Error(`Replay exceeds 32 MB`);return Bn(await e.arrayBuffer())}function Bn(e){let t=Fn(e);if(t.magic!==`B2DR`||t.version!==1||t.engine!==hn)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=_t(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&&!ht(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=ft(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 Vn=e=>Number.isSafeInteger(e)&&e>0&&e<=9e4,Hn=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,!Vn(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&&!Vn(t)||this.checkExpiry()||this.checkAttemptTimeout())return!1;t!==void 0&&(this.membershipDeadline=Math.min(this.membershipDeadline,this.io.now()+t));let n={attemptId:this.attemptId,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(n),!0}heartbeat(e,t){return e!==this.currentEpoch||this.state!==`admitted`||!Vn(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;this.state=`connecting`;let e=++this.currentEpoch;this.phaseDeadline=this.io.now()+5e3,this.arm();let t;try{t=this.io.createAttempt({attemptId:this.attemptId,epoch:e},{opened:()=>{e!==this.currentEpoch||this.state!==`connecting`||this.checkExpiry()||this.checkAttemptTimeout()||(this.state=`awaiting-ack`)},closed:()=>this.disconnected(e)})}catch{e===this.currentEpoch&&this.disconnected(e);return}if(e===this.currentEpoch&&(this.state===`connecting`||this.state===`awaiting-ack`||this.state===`admitted`))this.transport=t;else try{t.close()}catch{}}};function Un(e,t){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}var Wn=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),Gn=e=>typeof e==`string`&&/^[0-9a-f]{64}$/.test(e),Kn=(e,t)=>Number.isSafeInteger(e)&&e>=t,qn=e=>Kn(e,1)&&e<=9e4,Jn=e=>e===`host`||e===`guest`;function Yn(e){return!Un(e,[`version`,`roomGeneration`,`secret`,`connectionEpoch`,`membershipValidForMs`])||e.version!==2||!Wn(e.roomGeneration)||!Gn(e.secret)||!Kn(e.connectionEpoch,1)||!qn(e.membershipValidForMs)?null:{version:2,roomGeneration:e.roomGeneration,secret:e.secret,connectionEpoch:e.connectionEpoch,membershipValidForMs:e.membershipValidForMs}}function Xn(e){if(!Un(e,[`type`,`version`,`roomGeneration`,`attemptId`,`id`,`hostId`,`role`,`connectionEpoch`,`membershipValidForMs`,`rosterRevision`,`members`,`requireVerification`,`locked`])||e.type!==`resumed`||e.version!==2||!Wn(e.roomGeneration)||!Wn(e.attemptId)||!Wn(e.id)||!Wn(e.hostId)||!Jn(e.role)||!Kn(e.connectionEpoch,1)||!qn(e.membershipValidForMs)||!Kn(e.rosterRevision,0)||typeof e.requireVerification!=`boolean`||typeof e.locked!=`boolean`||!Array.isArray(e.members)||e.members.length<1||e.members.length>33)return null;let t=Qn(e.members,e.hostId);return!t||!t.some(t=>t.id===e.id&&t.role===e.role&&t.attached&&t.connectionEpoch===e.connectionEpoch)?null:{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}}function Zn(e){if(!Un(e,[`type`,`id`,`hostId`,`role`,`resumeGrant`,`rosterRevision`,`members`,`requireVerification`,`locked`])||e.type!==`ready`)return null;let t=Yn(e.resumeGrant);if(!t)return null;let n=Xn({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 Qn(e,t){if(!Array.isArray(e)||e.length<1||e.length>33)return null;let n=[],r=new Set;for(let t of e){if(!Un(t,[`id`,`role`,`attached`,`connectionEpoch`])||!Wn(t.id)||!Jn(t.role)||typeof t.attached!=`boolean`||!Kn(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 $n(e){if(!Un(e,[`type`,`roomGeneration`,`hostId`,`rosterRevision`,`members`])||e.type!==`roster`||!Wn(e.roomGeneration)||!Wn(e.hostId)||!Kn(e.rosterRevision,0))return null;let t=Qn(e.members,e.hostId);return t?{type:`roster`,roomGeneration:e.roomGeneration,hostId:e.hostId,rosterRevision:e.rosterRevision,members:t}:null}function er(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 tr=524288,nr=16384,rr=12;function ir(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>tr)throw Error(`Control message exceeds 512 KB`);if(r.length<=nr)return[n];let i=Math.ceil(r.length/nr),a=[];for(let e=0;e<i;e++){let n=r.subarray(e*nr,(e+1)*nr),o=new ArrayBuffer(rr+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,rr).set(n),a.push(o)}return a}var ar=class{partial;push(e,t=performance.now()){if(typeof e==`string`){if(this.partial||new TextEncoder().encode(e).length>nr)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-rr,o.bytes>tr)throw Error(`Control size limit`);if(o.parts.push(new Uint8Array(e.slice(rr))),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))}},or=class extends Error{},sr=1,cr=e=>typeof e==`string`&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(e),lr=e=>Number.isSafeInteger(e)&&e>0,ur=e=>e?.match(/(?:^|\r?\n)a=ice-ufrag:([^\s]+)/)?.[1],dr=e=>e.usernameFragment??e.candidate?.match(/(?:^| )ufrag ([^ ]+)/)?.[1],fr=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;let t=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)))};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===sr&&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!==sr?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!==sr?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 or(e):Error(e)))}updateBan(e,t){return this.closed||!this.host||!this.signalingAdmitted||this.ws.readyState!==sr?Promise.reject(Error(`An active room-owner connection is required.`)):this.banRequest?Promise.reject(Error(`A ban operation is already pending.`)):new Promise((n,r)=>{let i=++this.banSequence,a=setTimeout(()=>this.rejectBan(`Ban operation was not confirmed.`),1e4);this.banRequest={id:i,resolve:n,reject:r,timer:a};try{this.signal({type:e,id:t,requestId:i})}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=yn()){this.room=e,this.credentials=t,this.hooks=n,this.runtime=r;let i=new URL(`/api/rooms/${encodeURIComponent(e)}/signal`,vn(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===sr&&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(`Direct connection failed. This network pair may require a relay; this game does not use TURN.`),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.`),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.`)}))},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…`);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.`)}},e.onerror=()=>{i()&&this.hooks.status(`Room service is unavailable.`)}}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 Hn({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(`/api/rooms/${encodeURIComponent(this.room)}/signal`,vn(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(),this.recovery?.status===`awaiting-ack`&&(this.requestSentAt=performance.now(),r.send(JSON.stringify({type:`resume`,version:2,roomGeneration:this.resumeGrant.roomGeneration,peerId:this.id,secret:this.resumeGrant.secret,attemptId:e.attemptId,expectedEpoch:this.resumeGrant.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===sr&&this.ws.send(JSON.stringify(e))}async message(e,t=this.socketSerial){if(this.closed||t!==this.socketSerial)return;if(e.type===`resumed`){let n=Xn(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.`);return}if(e.type===`heartbeat`&&this.resumeGrant&&this.recovery){let t=this.heartbeatRequest;if(!t||e.requestId!==t.id||e.connectionEpoch!==this.resumeGrant.connectionEpoch||!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=$n(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||!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!==sr)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.`);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=Zn(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(!cr(e.id)||!lr(e.connectionEpoch)||!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&&(!cr(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(e.signal.type===`offer`){if(this.host||!ur(e.signal.sdp))return;n.negotiationId!==e.negotiationId&&(n.candidates=[]),this.beginNegotiation(n,e.negotiationId),n.remoteIceUfrag=ur(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(!ur(e.signal.sdp))return;n.remoteIceUfrag=ur(e.signal.sdp)}}let r=n.negotiationId,i=()=>this.current(n)&&t===this.socketSerial&&this.signalingAdmitted&&n.negotiationId===r&&this.negotiationCurrent(n);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}),!i()||(await this.flushCandidates(n,i),!i()))return;let t=await n.pc.createAnswer();if(!i()||(n.localIceUfrag=ur(t.sdp),await n.pc.setLocalDescription(t),!i()))return;this.peerSignal(n,{type:`answer`,sdp:n.pc.localDescription.sdp})}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}),!i())return;await this.flushCandidates(n,i),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{i()&&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.`)})}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?{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=ur(a.sdp),await n.pc.setLocalDescription(a),i()&&this.peerSignal(n,{type:`offer`,sdp:n.pc.localDescription.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.`)}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!==sr)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=ur(e.sdp),await t.pc.setLocalDescription(e),!i())?!1:(this.peerSignal(t,{type:`offer`,sdp:t.pc.localDescription.sdp}),!0)}catch{return!this.closed&&this.peers.get(e)===t&&this.hooks.status(`Direct connection recovery is still pending.`),!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.`),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…`)))};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.`),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.`),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 ar,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.`),this.remove(e.id)}}}}admit(e){clearTimeout(e.admissionTimer),e.admissionTimer=void 0}control(e,t){if(e.control?.readyState!==`open`)return;let n=ir(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=er(t.values()))}catch{e.rtt=null}}))}finally{this.pollingStats=!1}}}remove(e,t=!0){let n=this.peers.get(e);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.host||this.close(),this.hooks.leave(e),this.host||this.hooks.ended?.(`The host connection ended.`))}close(){if(!this.closed){this.resumeGrant&&this.signalingAdmitted&&this.ws.readyState===sr&&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()}}};function pr(e,t){return e!==t&&e-t>>>0<2147483648}function mr(e){if(e.byteLength!==14)throw Error(`Input length`);let t=new DataView(e);if(t.getUint8(0)!==1||t.getUint8(1)!==5||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 hr(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,5),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 gr=Object.freeze({...tn}),_r=class e{runtime;engine;network;roomId=``;roomLink=``;roomName=``;epoch=0;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 wn;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=Sn(),r){let i=vn(n.network.serviceOrigin);if(t=ct(t),t.noPlayer!==void 0&&typeof t.noPlayer!=`boolean`)throw Error(`Invalid noPlayer setting`);let a=t.noPlayer===!1,o=t.playerName??`Host`;if(a&&(typeof o!=`string`||!o.trim()||o.length>24))throw Error(`Invalid host player name`);let s=ot(r),c;try{s.signal.throwIfAborted();let r=await s.run(n.loadEngine(s.signal));r.load(t.stadium??mn()),c=new e(r,n);let l=c,u=await s.run(n.request(new URL(`/api/rooms`,i),{signal:s.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:a})}));if(!u.ok)throw Error(`Room creation failed (${u.status})`);let d=await s.run(u.json());l.roomId=d.id,l.roomName=t.roomName,l.roomLink=`${i}${ut(d.id)}`;let f;try{await s.run(new Promise((e,t)=>{f=setTimeout(()=>t(Error(`Signaling timed out`)),12e3),l.network=new fr(d.id,{hostToken:d.hostToken},{ready:(n,r)=>{if(!r){t(Error(`Host authority was not granted`));return}a&&(l.players.push({id:l.nextPlayerId++,slot:0,peerId:n,name:o.trim(),team:0,admin:!0}),l.engine.joinPlayer(0)),clearTimeout(f),e()},allowStadiumUpload:e=>!!l.players.find(t=>t.peerId===e.id)?.admin&&[`lobby`,`finished`].includes(l.engine.phase)&&l.traffic.allow(e.id,`message`),open:()=>{},control:(e,t)=>l.control(e,t),fast:(e,t)=>l.fast(e,t),leave:e=>l.leave(e),status:e=>l.report(e),ended:e=>{clearTimeout(f),t(Error(e)),l.close(),l.report(e)}},n.network)}))}catch(e){throw l.close(),e}finally{clearTimeout(f)}if(l.closed)throw Error(`Room closed during startup`);l.last=performance.now(),l.loop=setInterval(()=>l.advance(),1e3/60);let p=l.roomLink;return l.linkNotification=setTimeout(()=>{l.linkNotification=void 0,l.invoke(`onRoomLink`,l.onRoomLink,p)},0),c}catch(e){throw c?.close(),e}finally{s.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.recorder?.step(this.engine),this.engine.phase!==r&&this.state();let i=r===`goal`&&this.engine.phase===`playing`;r===`finished`&&this.engine.phase===`lobby`&&this.invoke(`onGameStop`,this.onGameStop,null);let a=this.engine.ballKicks.map(e=>{let t=this.players.find(t=>t.slot===e);return t?this.playerCopy(t):null}).filter(e=>!!e),o=r!==`finished`&&this.engine.phase===`finished`?this.getScores():null;o&&(this.invoke(`onTeamVictory`,this.onTeamVictory,{...o}),this.invoke(`onGameVictory`,this.onGameVictory,{...o}));for(let e of a)this.invoke(`onPlayerBallKick`,this.onPlayerBallKick,e);if(this.engine.red>t&&this.invoke(`onTeamGoal`,this.onTeamGoal,1),this.engine.blue>n&&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=at(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 hr(e,this.inputs.get(t.id)?.seq??0,this.epoch))this.network.fast(t,n)}this.accumulator-=1e3/60}}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!==hn||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`,epoch:this.epoch,roomName:this.roomName,engine:hn,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`&&ht(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`&&(!this.locked||r.admin)&&[0,1,2].includes(Number(n.team))){let e=n.slot===void 0?r:this.players.find(e=>e.slot===n.slot);e&&(e===r||r.admin)&&this.changeTeam(e.id,Number(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);e&&e!==r&&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`&&(!t||t===r||t.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}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:dt(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=Number(n.score),t=Number(n.minutes);if(Number.isInteger(e)&&e>=0&&e<=99&&Number.isInteger(t)&&t>=0&&t<=99&&(n.kickRate===void 0||Number.isInteger(n.kickRate)&&Number(n.kickRate)>=0&&Number(n.kickRate)<=6619135)){if(this.setScoreLimit(e),this.setTimeLimit(t),this.changeTeamsLock(!!n.locked,this.playerCopy(r)),this.closed)return;if(n.kickRate!==void 0&&n.kickRate!==this.engine.kickRate){let e=Number(n.kickRate);this.changeKickRateLimit(e&255,e>>>8&255,e>>>16,this.playerCopy(r))}}}if(n.action===`kick`&&typeof n.slot==`number`&&n.slot!==r.slot){let e=this.players.find(e=>e.slot===n.slot);e&&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=mr(t);if(r.epoch!==this.epoch)return;let i=this.inputs.get(e.id);(!i||pr(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`);Ln(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){this.changeTeamColors(e,dt(t,n,r))}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(!ht(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)}catch(t){throw t instanceof or&&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=mt(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=_n(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;pn(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 gr}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=_t(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`);Ln(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 Rn(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 vr(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 ct({...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 yr=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();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)}},br=`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 xr(e,t){let n=Object.create(null);t&&Object.defineProperty(n,"closed",{enumerable:!0,value:t});let r=new yr(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 br)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 Sr=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`:``)}})),Cr=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=Sr(),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})),wr=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=Cr()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Tr=z({createSupportsColor:()=>Ar,default:()=>Nr});function Er(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 Dr(){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 Or(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function kr(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Dr();r!==void 0&&(Mr=r);let i=n?Mr:r;if(i===0)return 0;if(n){if(Er(`color=16m`)||Er(`color=full`)||Er(`color=truecolor`))return 3;if(Er(`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 Ar(e,t={}){return Or(kr(e,{streamIsTTY:e&&e.isTTY,...t}))}var jr,Mr,Nr,Pr=L((()=>{({env:jr}=p),Er(`no-color`)||Er(`no-colors`)||Er(`color=false`)||Er(`color=never`)?Mr=0:(Er(`color`)||Er(`colors`)||Er(`color=true`)||Er(`color=always`))&&(Mr=1),Nr={stdout:Ar({isTTY:g.isatty(1)}),stderr:Ar({isTTY:g.isatty(2)})}})),Fr=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=(Pr(),ee(Tr));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}}},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(`
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=Cr()(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)}})),Ir=R(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?wr():Fr()})),Lr=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`)})),Rr=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||{})})),zr=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}}})),Br=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=Br()(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)}})),$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(`
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}})),Vr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=zr(),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}})),Hr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferVisitor=zr().BufferVisitor,e.PEM=Br().PEM;var t=Vr();e.ASN1=t.ASN1,e.Class=t.Class,e.Tag=t.Tag,e.BitString=t.BitString})),Ur=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=te(`crypto`),r=Rr(),i=Hr(),a=Lr();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))})})),Wr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=te(`crypto`),r=Hr(),i=Lr(),a=Ur(),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}})),Gr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Lr();e.bytesFromIP=t.bytesFromIP,e.bytesToIP=t.bytesToIP,e.getOID=t.getOID,e.getOIDName=t.getOIDName;var n=Ur();e.PublicKey=n.PublicKey,e.PrivateKey=n.PrivateKey,e.RSAPublicKey=n.RSAPublicKey,e.RSAPrivateKey=n.RSAPrivateKey;var r=Wr();e.Certificate=r.Certificate,e.DistinguishedName=r.DistinguishedName})),Kr=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||={})})),qr=V(Ir(),1),Jr=Gr();Kr();var Yr=`[object ArrayBuffer]`,U=class e{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Yr}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}},Xr=`string`,Zr=/^[0-9a-f\s]+$/i,Qr=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,$r=/^[a-zA-Z0-9-_]+$/,ei=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))}},ti=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}},ni=class e{static isHex(e){return typeof e===Xr&&Zr.test(e)}static isBase64(e){return typeof e===Xr&&Qr.test(e)}static isBase64Url(e){return typeof e===Xr&&$r.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 ti.toString(n,!0);case`utf16`:case`utf16be`:return ti.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 ti.fromString(e,!0);case`utf16`:case`utf16be`:return ti.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 ei.fromString(t);case`utf16`:case`utf16be`:return ti.fromString(t);case`utf16le`:case`usc2`:return ti.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 ei.toString(t);case`utf16`:case`utf16be`:return ti.toString(t);case`utf16le`:case`usc2`:return ti.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 ti.toString(e,t)}static FromUtf16String(e,t=!1){return ti.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,``)||``}};ni.DEFAULT_UTF8_ENCODING=`utf8`;function ri(...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 ii(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 ai(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 oi(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 si(...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 ci(){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=ai(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,ai(a,8)-r}function li(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=oi(n-t,8,r),i=new Uint8Array(e);return i[0]|=128,e}let i=oi(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 ui(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 di(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 fi=z({Any:()=>Fo,BaseBlock:()=>Bi,BaseStringBlock:()=>Hi,BitString:()=>Sa,BmpString:()=>Qa,Boolean:()=>ga,CharacterString:()=>bo,Choice:()=>Io,Constructed:()=>ca,DATE:()=>Eo,DEFAULT_MAX_CONTENT_LENGTH:()=>qi,DEFAULT_MAX_DEPTH:()=>100,DEFAULT_MAX_NODES:()=>Ki,DateTime:()=>Ao,Duration:()=>Mo,EndOfContent:()=>da,Enumerated:()=>ja,GeneralString:()=>vo,GeneralizedTime:()=>wo,GraphicString:()=>mo,HexBlock:()=>Fi,IA5String:()=>fo,Integer:()=>ka,Null:()=>pa,NumericString:()=>ro,ObjectIdentifier:()=>Fa,OctetString:()=>ya,Primitive:()=>Gi,PrintableString:()=>ao,RawData:()=>Ro,RelativeObjectIdentifier:()=>za,Repeated:()=>Lo,Sequence:()=>Va,Set:()=>Ua,TIME:()=>Po,TeletexString:()=>so,TimeOfDay:()=>Oo,UTCTime:()=>So,UniversalString:()=>to,Utf8String:()=>Ya,ValueBlock:()=>Li,VideotexString:()=>lo,ViewWriter:()=>gi,VisibleString:()=>go,compareSchema:()=>zo,fromBER:()=>ia,verifySchema:()=>Bo});function pi(){if(typeof BigInt>`u`)throw Error(`BigInt is not defined. Your environment doesn't implement BigInt.`)}function mi(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 hi(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 gi=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return mi(this.items)}},_i=[new Uint8Array([1])],vi=`0123456789`,yi=`name`,bi=`valueHexView`,xi=`isHexOnly`,Si=`idBlock`,Ci=`tagClass`,wi=`tagNumber`,Ti=`isConstructed`,Ei=`fromBER`,Di=`toBER`,Oi=`local`,ki=``,Ai=new ArrayBuffer(0),ji=new Uint8Array,Mi=`EndOfContent`,Ni=`OCTET STRING`,Pi=`BIT STRING`;function Fi(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(!hi(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`,Ai)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ni.ToHex(this.valueHexView)}}};return t.NAME=`hexBlock`,t}var Ii=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:ni.ToHex(this.valueBeforeDecodeView)}}};Ii.NAME=`baseBlock`;var Li=class extends Ii{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'`)}};Li.NAME=`valueBlock`;var Ri=class extends Fi(Ii){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`,Ai}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=oi(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(!hi(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=ai(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}}};Ri.NAME=`identificationBlock`;var zi=class extends Ii{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(!hi(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=ai(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=oi(this.length,8);if(r.byteLength>127)return this.error=`Too big length`,Ai;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}}};zi.NAME=`lengthBlock`;var W={},Bi=class extends Ii{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 Ri(r),this.lenBlock=new zi(r),this.valueBlock=i?new i(r):new Li(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 gi;t||Vi(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?Ai: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():ni.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${ni.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&ui(this.toBER(),e.toBER())}};Bi.NAME=`BaseBlock`;function Vi(e){if(e instanceof W.Constructed)for(let t of e.valueBlock.value)Vi(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock?.isIndefiniteForm}var Hi=class extends Bi{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}'`}};Hi.NAME=`BaseStringBlock`;var Ui=class extends Fi(Li){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Ui.NAME=`PrimitiveValueBlock`;var Wi,Gi=class extends Bi{constructor(e={}){super(e,Ui),this.idBlock.isConstructed=!1}};Wi=Gi,W.Primitive=Wi,Gi.NAME=`PRIMITIVE`;var Ki=1e4,qi=16777216,Ji=`Maximum ASN.1 nesting depth exceeded`,Yi=`Maximum ASN.1 node count exceeded`,Xi=`Maximum ASN.1 content length exceeded`;function Zi(e={}){return{depth:0,maxDepth:e.maxDepth??100,nodesCount:0,maxNodes:e.maxNodes??Ki,maxContentLength:e.maxContentLength??qi}}function Qi(e){let t=new Bi({},Li);return t.error=e,{offset:-1,result:t}}function $i(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return Yi}function ea(e,t){if(e>t.maxContentLength)return Xi}function ta(e,t,n,r){let i=r.depth+1;if(i>r.maxDepth)return Qi(Ji);r.depth=i;try{return ra(e,t,n,r)}finally{--r.depth}}function na(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 ra(e,t=0,n=e.length,r=Zi()){let i=t,a=new Bi({},Li),o=new Ii;if(!hi(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=$i(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=ea(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=Bi;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=na(a,d),c=a.fromBER(e,t,l,r),a.valueBeforeDecodeView=e.subarray(i,i+a.blockLength),{offset:c,result:a}}function ia(e,t={}){if(!e.byteLength){let e=new Bi({},Li);return e.error=`Input buffer has zero length`,{offset:-1,result:e}}return ra(U.toUint8Array(e).slice(),0,e.byteLength,Zi(t))}function aa(e,t){return e?1:t}var oa=class extends Li{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??Zi();if(!hi(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(;aa(this.isIndefiniteForm,n)>0;){let e=ta(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===Mi)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Mi?this.value.pop():this.warnings.push(`No EndOfContent block encoded`)),o}toBER(e,t){let n=t||new gi;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,n);return t?Ai:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};oa.NAME=`ConstructedValueBlock`;var sa,ca=class extends Bi{constructor(e={}){super(e,oa),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}})),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(`
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} :`}};sa=ca,W.Constructed=sa,ca.NAME=`CONSTRUCTED`;var la=class extends Li{fromBER(e,t,n){return t}toBER(e){return Ai}};la.override=`EndOfContentValueBlock`;var ua,da=class extends Bi{constructor(e={}){super(e,la),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};ua=da,W.EndOfContent=ua,da.NAME=Mi;var fa,pa=class extends Bi{constructor(e={}){super(e,Li),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}`}};fa=pa,W.Null=fa,pa.NAME=`NULL`;var ma=class extends Fi(Li){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 hi(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,ci.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ma.NAME=`BooleanValueBlock`;var ha,ga=class extends Bi{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,ma),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};ha=ga,W.Boolean=ha,ga.NAME=`BOOLEAN`;var _a=class extends Fi(oa){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=oa.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===Mi){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only`,-1}if(t!==Ni)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?oa.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};_a.NAME=`OctetStringValueBlock`;var va,ya=class extends Bi{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},_a),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??Zi(),t=ta(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?ca.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${ni.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 va&&e.push(t.valueBlock.valueHexView);return U.concat(e)}};va=ya,W.OctetString=va,ya.NAME=Ni;var ba=class extends Fi(oa){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=oa.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===Mi){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only`,-1}if(t!==Pi)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(!hi(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??Zi(),i=ta(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 oa.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}}};ba.NAME=`BitStringValueBlock`;var xa,Sa=class extends Bi{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},ba),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 ca.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)}`}}};xa=Sa,W.BitString=xa,Sa.NAME=Pi;var Ca;function wa(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=si(new Uint8Array([l%10]),a);break;default:a[o-d]=l%10}}return n[0]>0&&(a=si(n,a)),a}function Ta(e){if(e>=_i.length)for(let t=_i.length;t<=e;t++){let e=new Uint8Array([0]),n=_i[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=si(e,n)),_i.push(n)}return _i[e]}function Ea(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 Da=class extends Fi(Li){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=ci.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(li(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=Ea(Ta(n),t),a=`-`;break;default:t=wa(t,Ta(n))}n++,r>>=1}}for(let e=0;e<t.length;e++)t[e]&&(o=!0),o&&(a+=vi.charAt(t[e]));return o===!1&&(a+=vi.charAt(0)),a}};Ca=Da,Da.NAME=`IntegerValueBlock`,Object.defineProperty(Ca.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Oa,ka=class extends Bi{constructor(e={}){super(e,Da),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return pi(),BigInt(this.valueBlock.toString())}static fromBigInt(e){pi();let t=BigInt(e),n=new gi,r=t.toString(16).replace(/^-/,``),i=new Uint8Array(ni.FromHex(r));if(t<0){let e=new Uint8Array(i.length+(i[0]&128?1:0));e[0]|=128;let r=BigInt(`0x${ni.ToHex(e)}`)+t,a=U.toUint8Array(ni.FromHex(r.toString(16)));a[0]|=128,n.write(a)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new Oa({valueHex:n.final()})}convertToDER(){let e=new Oa({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Oa({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Oa=ka,W.Integer=Oa,ka.NAME=`INTEGER`;var Aa,ja=class extends ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Aa=ja,W.Enumerated=Aa,ja.NAME=`ENUMERATED`;var Ma=class extends Fi(Li){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(!hi(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=ai(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}set valueBigInt(e){pi();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=oi(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,Ai;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=ni.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}}};Ma.NAME=`sidBlock`;var Na=class extends Li{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 Ma;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,Ai;t.push(r)}return mi(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 Ma;if(r>2**53-1)pi(),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}};Na.NAME=`ObjectIdentifierValueBlock`;var Pa,Fa=class extends Bi{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Na),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Pa=Fa,W.ObjectIdentifier=Pa,Fa.NAME=`OBJECT IDENTIFIER`;var Ia=class extends Fi(Ii){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(!hi(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=ai(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=oi(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,Ai;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?ni.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ia.NAME=`relativeSidBlock`;var La=class extends Li{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 Ia;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,Ai;n.push(r)}return mi(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 Ia;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}};La.NAME=`RelativeObjectIdentifierValueBlock`;var Ra,za=class extends Bi{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,La),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Ra=za,W.RelativeObjectIdentifier=Ra,za.NAME=`RelativeObjectIdentifier`;var Ba,Va=class extends ca{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Ba=Va,W.Sequence=Ba,Va.NAME=`SEQUENCE`;var Ha,Ua=class extends ca{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Ha=Ua,W.Set=Ha,Ua.NAME=`SET`;var Wa=class extends Fi(Li){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ki}toJSON(){return{...super.toJSON(),value:this.value}}};Wa.NAME=`StringValueBlock`;var Ga=class extends Wa{};Ga.NAME=`SimpleStringValueBlock`;var Ka=class extends Hi{constructor({...e}={}){super(e,Ga)}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}};Ka.NAME=`SIMPLE STRING`;var qa=class extends Ka{fromBuffer(e){this.valueBlock.valueHexView=U.toUint8Array(e);try{this.valueBlock.value=ni.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ni.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ni.FromUtf8String(e)),this.valueBlock.value=e}};qa.NAME=`Utf8StringValueBlock`;var Ja,Ya=class extends qa{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Ja=Ya,W.Utf8String=Ja,Ya.NAME=`UTF8String`;var Xa=class extends Ka{fromBuffer(e){this.valueBlock.value=ni.ToUtf16String(e),this.valueBlock.valueHexView=U.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ni.FromUtf16String(e))}};Xa.NAME=`BmpStringValueBlock`;var Za,Qa=class extends Xa{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Za=Qa,W.BmpString=Za,Qa.NAME=`BMPString`;var $a=class extends Ka{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=oi(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}};$a.NAME=`UniversalStringValueBlock`;var eo,to=class extends $a{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};eo=to,W.UniversalString=eo,to.NAME=`UniversalString`;var no,ro=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};no=ro,W.NumericString=no,ro.NAME=`NumericString`;var io,ao=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};io=ao,W.PrintableString=io,ao.NAME=`PrintableString`;var oo,so=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};oo=so,W.TeletexString=oo,so.NAME=`TeletexString`;var co,lo=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};co=lo,W.VideotexString=co,lo.NAME=`VideotexString`;var uo,fo=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};uo=fo,W.IA5String=uo,fo.NAME=`IA5String`;var po,mo=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};po=mo,W.GraphicString=po,mo.NAME=`GraphicString`;var ho,go=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};ho=go,W.VisibleString=ho,go.NAME=`VisibleString`;var _o,vo=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};_o=vo,W.GeneralString=_o,vo.NAME=`GeneralString`;var yo,bo=class extends Ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};yo=bo,W.CharacterString=yo,bo.NAME=`CharacterString`;var xo,So=class extends go{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]=di(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=di(this.month,2),e[2]=di(this.day,2),e[3]=di(this.hour,2),e[4]=di(this.minute,2),e[5]=di(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}}};xo=So,W.UTCTime=xo,So.NAME=`UTCTime`;var Co,wo=class extends So{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(di(this.year,4)),e.push(di(this.month,2)),e.push(di(this.day,2)),e.push(di(this.hour,2)),e.push(di(this.minute,2)),e.push(di(this.second,2)),this.millisecond!==0&&(e.push(`.`),e.push(di(this.millisecond,3))),e.push(`Z`),e.join(``)}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Co=wo,W.GeneralizedTime=Co,wo.NAME=`GeneralizedTime`;var To,Eo=class extends Ya{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};To=Eo,W.DATE=To,Eo.NAME=`DATE`;var Do,Oo=class extends Ya{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Do=Oo,W.TimeOfDay=Do,Oo.NAME=`TimeOfDay`;var ko,Ao=class extends Ya{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};ko=Ao,W.DateTime=ko,Ao.NAME=`DateTime`;var jo,Mo=class extends Ya{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};jo=Mo,W.Duration=jo,Mo.NAME=`Duration`;var No,Po=class extends Ya{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};No=Po,W.TIME=No,Po.NAME=`TIME`;var Fo=class{constructor({name:e=ki,optional:t=!1}={}){this.name=e,this.optional=t}},Io=class extends Fo{constructor({value:e=[],...t}={}){super(t),this.value=e}},Lo=class extends Fo{constructor({value:e=new Fo,local:t=!1,...n}={}){super(n),this.value=e,this.local=t}},Ro=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 zo(e,t,n){if(n instanceof Io){for(let r of n.value)if(zo(e,t,r).verified)return{verified:!0,result:e};{let e={verified:!1,result:{error:`Wrong values for Choice type`}};return n.hasOwnProperty(yi)&&(e.name=n.name),e}}if(n instanceof Fo)return n.hasOwnProperty(yi)&&(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)||!(Si in n)||!(Ei in n.idBlock)||!(Di 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(Ci)===!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(wi)===!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(Ti)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(xi 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(!(bi 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 Lo&&(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 Lo){if(i=zo(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(yi in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let r={};r=Oi 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=zo(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&&bi in t.valueBlock){let r=ra(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 zo(e,r.result,n.primitiveSchema)}return{verified:!0,result:e}}function Bo(e,t){if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 schema type`}};let n=ra(U.toUint8Array(e));return n.offset===-1?{verified:!1,result:n.result}:zo(n.result,n.result,t)}var Vo=`[object ArrayBuffer]`,Ho=`[object SharedArrayBuffer]`;function Uo(e){return Object.prototype.toString.call(e)}function Wo(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`&&qo(t.buffer)}function Go(e){return Uo(e)===Vo}function Ko(e){return typeof SharedArrayBuffer<`u`&&Uo(e)===Ho}function qo(e){return Go(e)||Ko(e)}function Jo(e){return Wo(e)}function Yo(e){return qo(e)||Jo(e)}function Xo(e){if(!Yo(e))throw TypeError(`Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView`)}function Zo(e){return Xo(e),qo(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Qo(e){if(Xo(e),Go(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(Zo(e)),t}function $o(e,t,n={}){let r=Zo(e),i=Zo(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 es(e){let t=Zo(e),n=``;for(let e of t)n+=String.fromCharCode(e);return n}function ts(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function ns(e){return typeof e==`string`}var rs=/^[0-9a-f]$/i,is=[` `,` `,`
27
- `,`\r`,`:`,`-`,`.`];function as(e){return e.separators===`none`?[]:!e.separators||e.separators===`common`?is:e.separators}function os(e){if(!e)throw TypeError(`Hex separators must be non-empty strings`)}function ss(e,t,n){for(let r of n)if(e.startsWith(r,t))return r}function cs(e){let t=/[A-F]/.test(e),n=/[a-f]/.test(e);return t&&!n?`upper`:`lower`}function ls(e){let t=/\r\n|\n/.exec(e);if(t)return t[0]===`\r
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 Ss(e){return e.separators===`none`?[]:!e.separators||e.separators===`common`?xs:e.separators}function Cs(e){if(!e)throw TypeError(`Hex separators must be non-empty strings`)}function ws(e,t,n){for(let r of n)if(e.startsWith(r,t))return r}function Ts(e){let t=/[A-F]/.test(e),n=/[a-f]/.test(e);return t&&!n?`upper`:`lower`}function Es(e){let t=/\r\n|\n/.exec(e);if(t)return t[0]===`\r
28
28
  `?`\r
29
29
  `:`
30
- `}function us(e){return e.replace(/[^0-9a-f]/gi,``)}function ds(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 fs(e){let t=e.trim(),n=/^0x/i.test(t)?`0x`:``,r=n?t.slice(2):t,i=ls(r),a=r.split(/\r\n|\n/).filter(e=>e.length>0),o=ds(a[0]?.trim()??``),s={case:cs(t),prefix:n};if(o&&(s.group=o),i&&a.length>1){let e=us(a[0]??``).length/2;e>0&&a.slice(0,-1).every(t=>us(t).length/2===e)&&(s.line={bytesPerLine:e,separator:i})}return s}function ps(e,t){let n=t.allowPrefix??!0,r=[...as(t)].sort((e,t)=>t.length-e.length);for(let e of r)os(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(rs.test(n)){a+=n,o=!1,e+=1;continue}let s=ss(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 ms(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 hs(e,t={}){return ps(e,t)}function gs(e,t={}){if(typeof e!=`string`)return!1;try{return hs(e,t),!0}catch{return!1}}function _s(e,t={}){let n=Zo(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(ms(i.slice(n,n+e),t.group));a=r.join(n)}else a=ms(i,t.group);return`${t.prefix??``}${a}`}function vs(e,t={}){let n=hs(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 ys(e,t={}){let n=hs(e,t);return{bytes:vs(n),format:fs(e),normalized:n}}function bs(e,t){return _s(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 xs(e){return new TextEncoder().encode(e)}function Ss(e){return new TextDecoder(`utf-8`,{fatal:!1}).decode(Zo(e))}function Cs(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 ws(e,t={}){let n=Qo(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 Ts=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Es(){return globalThis.Buffer}function Ds(e){return e.replace(/[\n\r\t ]/g,``)}function Os(e){let t=e.length%4;return t?e+`=`.repeat(4-t):e}function ks(e){if(typeof e!=`string`)return!1;let t=Ds(e);return t===``||Ts.test(t)}function As(e,t){let n=Zo(e),r=Es();return r?r.from(n).toString(`base64`):btoa(es(n))}function js(e,t){let n=Ds(e);if(!ks(n))throw TypeError(`Input is not valid Base64 text`);let r=Es();return r?new Uint8Array(r.from(n,`base64`)):ts(atob(n))}var Ms={encode:As,decode:js,is:ks,normalize:Ds,pad:Os},Ns=/^[A-Za-z0-9_-]*$/;function Ps(e){return e.replace(/[\n\r\t ]/g,``)}function Fs(e){return typeof e==`string`&&Ns.test(Ps(e))}function Is(e,t){return Ms.encode(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}function Ls(e,t){let n=Ps(e);if(!Fs(n))throw TypeError(`Input is not valid Base64Url text`);return Ms.decode(Ms.pad(n.replace(/-/g,`+`).replace(/_/g,`/`)))}var Rs=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,zs=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function Bs(e){if(!Rs.test(e))throw TypeError(`Invalid PEM label '${e}'`)}function Vs(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Hs(e){let t=e.trim().replace(/\r\n/g,`
30
+ `}function Ds(e){return e.replace(/[^0-9a-f]/gi,``)}function Os(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 ks(e){let t=e.trim(),n=/^0x/i.test(t)?`0x`:``,r=n?t.slice(2):t,i=Es(r),a=r.split(/\r\n|\n/).filter(e=>e.length>0),o=Os(a[0]?.trim()??``),s={case:Ts(t),prefix:n};if(o&&(s.group=o),i&&a.length>1){let e=Ds(a[0]??``).length/2;e>0&&a.slice(0,-1).every(t=>Ds(t).length/2===e)&&(s.line={bytesPerLine:e,separator:i})}return s}function As(e,t){let n=t.allowPrefix??!0,r=[...Ss(t)].sort((e,t)=>t.length-e.length);for(let e of r)Cs(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(bs.test(n)){a+=n,o=!1,e+=1;continue}let s=ws(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 js(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 Ms(e,t={}){return As(e,t)}function Ns(e,t={}){if(typeof e!=`string`)return!1;try{return Ms(e,t),!0}catch{return!1}}function Ps(e,t={}){let n=ms(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(js(i.slice(n,n+e),t.group));a=r.join(n)}else a=js(i,t.group);return`${t.prefix??``}${a}`}function Fs(e,t={}){let n=Ms(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 Is(e,t={}){let n=Ms(e,t);return{bytes:Fs(n),format:ks(e),normalized:n}}function Ls(e,t){return Ps(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 Rs(e){return new TextEncoder().encode(e)}function zs(e){return new TextDecoder(`utf-8`,{fatal:!1}).decode(ms(e))}function Bs(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 Vs(e,t={}){let n=hs(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 Hs=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Us(){return globalThis.Buffer}function Ws(e){return e.replace(/[\n\r\t ]/g,``)}function Gs(e){let t=e.length%4;return t?e+`=`.repeat(4-t):e}function Ks(e){if(typeof e!=`string`)return!1;let t=Ws(e);return t===``||Hs.test(t)}function qs(e,t){let n=ms(e),r=Us();return r?r.from(n).toString(`base64`):btoa(_s(n))}function Js(e,t){let n=Ws(e);if(!Ks(n))throw TypeError(`Input is not valid Base64 text`);let r=Us();return r?new Uint8Array(r.from(n,`base64`)):vs(atob(n))}var Ys={encode:qs,decode:Js,is:Ks,normalize:Ws,pad:Gs},Xs=/^[A-Za-z0-9_-]*$/;function Zs(e){return e.replace(/[\n\r\t ]/g,``)}function Qs(e){return typeof e==`string`&&Xs.test(Zs(e))}function $s(e,t){return Ys.encode(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}function ec(e,t){let n=Zs(e);if(!Qs(n))throw TypeError(`Input is not valid Base64Url text`);return Ys.decode(Ys.pad(n.replace(/-/g,`+`).replace(/_/g,`/`)))}var tc=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,nc=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function rc(e){if(!tc.test(e))throw TypeError(`Invalid PEM label '${e}'`)}function ic(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ac(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 Us(e){return/\r\n/.test(e)?`\r
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 oc(e){return/\r\n/.test(e)?`\r
34
34
  `:`
35
- `}function Ws(e,t={}){let n=[],r=t.label,i;for(zs.lastIndex=0;i=zs.exec(e);){let e=i[1].trim();if(r&&e!==r)continue;Bs(e);let t=Hs(i[2]);n.push({label:e,data:Ms.decode(t.base64Text),headers:t.headers,lineLength:t.base64Lines[0]?.length??64,newline:Us(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 Gs(e,t,n={}){Bs(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(...Vs(Ms.encode(t),r)),a.push(`-----END ${e}-----`),`${a.join(i)}${i}`}function Ks(e,t={}){return Ws(e,t).map(({lineLength:e,newline:t,...n})=>n)}function qs(e,t){let[n]=Ks(e,{label:t,strict:!0});return n.data}function Js(e,t={}){let[n]=Ws(e,{...t,strict:!0}),r={label:n.label,headers:n.headers,lineLength:n.lineLength,newline:n.newline};return{bytes:n.data,format:r,normalized:Gs(n.label,n.data,r)}}function Ys(e,t){return Gs(t.label,e,t)}var Xs={name:`pem`,encode:(e,t)=>{if(!t?.label)throw TypeError(`PEM label is required`);return Gs(t.label,e,t)},decode:(e,t)=>qs(e,t?.label),format:Ys,is:e=>typeof e==`string`&&/-----BEGIN [^-]+-----/.test(e),parse:Js};function Zs(e){return e.trim().toLowerCase()}function Qs(e){return e instanceof Error?e:Error(String(e))}function $s(e,t,n){for(let t of[n.name,...n.aliases??[]])e.delete(Zs(t));t.delete(Zs(n.name))}function ec(e,t,n){let r=e[n];if(typeof r!=`function`)throw Error(`Converter '${t}' does not support ${n}()`);return r}function tc(e,t,n){let r=Zs(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 nc(e=[]){let t=new Map,n=new Set,r={register(e,r={}){if(!e.name||!Zs(e.name))throw TypeError(`Converter name is required`);let i=[...new Set([e.name,...e.aliases??[]].map(Zs))],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)$s(t,n,e);for(let n of i)t.set(n,e);return n.add(Zs(e.name)),this},unregister(e){let r=t.get(Zs(e));return r?($s(t,n,r),!0):!1},has(e){return t.has(Zs(e))},get(e){let n=t.get(Zs(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:Qs(e)}}},normalize(e,t,n){let r=this.get(e);return ec(r,e,`normalize`).call(r,t,n)},parse(e,t,n){let r=this.get(e);return ec(r,e,`parse`).call(r,t,n)},format(e,t,n){let r=this.get(e);return ec(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(Zs(e))),r=new Map;for(let t of n){let n=this.get(t),i=tc(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}nc([{name:`binary`,aliases:[`latin1`],encode:es,decode:ts,is:ns},{name:`hex`,encode:_s,decode:vs,format:bs,is:gs,normalize:hs,parse:ys},{name:`base64`,aliases:[`b64`],encode:As,decode:js,is:ks,normalize:Ds},{name:`base64url`,aliases:[`base64-url`,`b64url`],encode:Is,decode:Ls,is:Fs,normalize:Ps},{name:`utf8`,aliases:[`utf-8`],encode:e=>Ss(e),decode:e=>xs(e),is:e=>typeof e==`string`},{name:`utf16be`,aliases:[`utf16`,`utf-16`,`utf-16be`],encode:e=>ws(e),decode:e=>Cs(e),is:e=>typeof e==`string`},{name:`utf16le`,aliases:[`utf-16le`,`ucs2`,`usc2`],encode:e=>ws(e,{littleEndian:!0}),decode:e=>Cs(e,{littleEndian:!0}),is:e=>typeof e==`string`},Xs]);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 rc=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e){if(typeof e==`number`)this.fromNumber(e);else if(Yo(e))this.unusedBits=t,this.value=Qo(e);else throw TypeError(`Unsupported type of 'params' argument for BitString`)}}fromASN(e){if(!(e instanceof Sa))throw TypeError(`Argument 'asn' is not instance of ASN.1 BitString`);return this.unusedBits=e.valueBlock.unusedBits,this.value=Qo(e.valueBlock.valueHex),this}toASN(){return new Sa({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Sa({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}},ic=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){this.buffer=typeof e==`number`?new ArrayBuffer(e):Yo(e)?Qo(e):Array.isArray(e)?new Uint8Array(e).buffer:new ArrayBuffer(0)}fromASN(e){if(!(e instanceof ya))throw TypeError(`Argument 'asn' is not instance of ASN.1 OctetString`);return this.buffer=Qo(e.valueBlock.valueHex),this}toASN(){return new ya({valueHex:this.buffer})}toSchema(e){return new ya({name:e})}},ac={fromASN:e=>e instanceof pa?null:Qo(e.valueBeforeDecodeView),toASN:e=>{if(e===null)return new pa;let t=ia(e);if(t.result.error)throw Error(t.result.error);return t.result}},oc={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new ka({value:+e})},sc={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new ja({value:e})},cc={fromASN:e=>Qo(e.valueBlock.valueHexView),toASN:e=>new ka({valueHex:e})},lc={fromASN:e=>Qo(e.valueBlock.valueHexView),toASN:e=>new Sa({valueHex:e})},uc={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Fa({value:e})},dc={fromASN:e=>e.valueBlock.toString(),toASN:e=>new za({value:e})},fc={fromASN:e=>e.valueBlock.value,toASN:e=>new ga({value:e})},pc={fromASN:e=>Qo(e.valueBlock.valueHexView),toASN:e=>new ya({valueHex:e})},mc={fromASN:e=>new ic(e.getValue()),toASN:e=>e.toASN()};function hc(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var gc=hc(Ya),_c=hc(Qa),vc=hc(to),yc=hc(ro),bc=hc(ao),xc=hc(so),Sc=hc(lo),Cc=hc(fo),wc=hc(mo),Tc=hc(go),Ec=hc(vo),Dc=hc(bo),Oc={fromASN:e=>e.toDate(),toASN:e=>new So({valueDate:e})},kc={fromASN:e=>e.toDate(),toASN:e=>new wo({valueDate:e})},Ac={fromASN:()=>null,toASN:()=>new pa};function jc(e){switch(e){case K.Any:return ac;case K.BitString:return lc;case K.BmpString:return _c;case K.Boolean:return fc;case K.CharacterString:return Dc;case K.Enumerated:return sc;case K.GeneralString:return Ec;case K.GeneralizedTime:return kc;case K.GraphicString:return wc;case K.IA5String:return Cc;case K.Integer:return oc;case K.Null:return Ac;case K.NumericString:return yc;case K.ObjectIdentifier:return uc;case K.RelativeObjectIdentifier:return dc;case K.OctetString:return pc;case K.PrintableString:return bc;case K.TeletexString:return xc;case K.UTCTime:return Oc;case K.UniversalString:return vc;case K.Utf8String:return gc;case K.VideotexString:return Sc;case K.VisibleString:return Tc;default:return null}}function Mc(e){return typeof e==`function`&&e.prototype?e.prototype.toASN&&e.prototype.fromASN?!0:Mc(e.prototype):!!(e&&typeof e==`object`&&`toASN`in e&&`fromASN`in e)}function Nc(e){if(e){let t=Object.getPrototypeOf(e);return t?.prototype?.constructor===Array||Nc(t)}return!1}function Pc(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 Fc=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=fi[e];if(!t)throw Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:a})}else Mc(i.type)?o=new i.type().toSchema(a):i.optional?this.get(i.type).type===G.Choice?o=new Fo({name:a}):(o=this.create(i.type,!1),o.name=a):o=new Fo({name:a});let s=!!i.optional||i.defaultValue!==void 0;if(i.repeated&&(o.name=``,o=new(i.repeated===`set`?Ua:Va)({name:``,value:[new Lo({name:a,value:o})]})),i.context!==null&&i.context!==void 0){if(i.implicit){if(typeof i.type==`number`||Mc(i.type)){let e=i.repeated?ca:Gi;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 ca({name:e?``:a,optional:s,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}}else r.push(new ca({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 Va({value:r,name:``});case G.Set:return new Ua({value:r,name:``});case G.Choice:return new Io({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;Fc.has(t)?n=Fc.get(t):(n=Fc.createDefault(t),Fc.set(t,n)),Object.assign(n,e)},J=e=>(t,n)=>{let r;Fc.has(t.constructor)?r=Fc.get(t.constructor):(r=Fc.createDefault(t.constructor),Fc.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},Ic=class extends Error{schemas=[]},Lc=class{static parse(e,t,n){let r=ia(Qo(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(Mc(t))return new t().fromASN(e);let r=Fc.get(t);Fc.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 Nc(t)?this.handleArrayTypes(e,r,t,n):(this.processSchemaItems(r,o,s,n),s)}catch(e){throw e instanceof Ic&&e.schemas.push(t.name),e}}static handleChoiceTypes(e,t,n,r,i){if(e.constructor===ca&&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`&&Fc.has(a.type)){let t=Fc.get(a.type);if(t&&t.type===G.Sequence){let t=new Va;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===ca&&t.type!==G.Choice){let n=new ca({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=zo({},e,r);if(!t.verified)throw new Ic(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}{let t=zo({},e,r);if(!t.verified)throw new Ic(`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`&&Fc.has(e.type)&&Fc.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 Ic&&/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`||Mc(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??(Mc(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`?Va:Ua);i.valueBlock=e.valueBlock;let a=ia(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(Mc(n))e=new n().toSchema(``);else{let t=K[n],r=fi[t];if(!r)throw Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=a.valueBlock,a=ia(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 Ic&&/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=Fc.get(n);if(t.type===G.Sequence){let t=new Va;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 Ua;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}}return e}},Rc=class e{static serialize(e){return e instanceof Bi?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&typeof t==`object`&&Mc(t))return t.toASN();if(!(t&&typeof t==`object`))throw TypeError(`Parameter 1 should be type of Object.`);let n=t.constructor,r=Fc.get(n);Fc.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`&&Pc(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`||Mc(o.type))){let e={};e.valueHex=c instanceof pa?Qo(c.valueBeforeDecodeView):c.valueBlock.toBER(),i.push(new Gi({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},...e}))}else i.push(new ca({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:c.valueBlock.value}))}else i.push(new ca({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 Va({value:i});break;case G.Set:a=new Ua({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`?Va:Ua)({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`?Va:Ua)({value:t})}else i=this.toASN(r);return i}},zc=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 Rc.serialize(e)}static parse(e,t,n){return Lc.parse(e,t,n)}static toString(t,n){let r=ia(Yo(t)?Qo(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 Bc(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 Vc(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 Hc=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(_s(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}},Uc,Wc,Gc,Kc=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})],Kc.prototype,`teletexString`,void 0),X([J({type:K.PrintableString})],Kc.prototype,`printableString`,void 0),X([J({type:K.UniversalString})],Kc.prototype,`universalString`,void 0),X([J({type:K.Utf8String})],Kc.prototype,`utf8String`,void 0),X([J({type:K.BmpString})],Kc.prototype,`bmpString`,void 0),Kc=X([q({type:G.Choice})],Kc);var qc=class extends Kc{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?_s(this.anyValue):super.toString())}};X([J({type:K.IA5String})],qc.prototype,`ia5String`,void 0),X([J({type:K.Any})],qc.prototype,`anyValue`,void 0),qc=X([q({type:G.Choice})],qc);var Jc=class{type=``;value=new qc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Jc.prototype,`type`,void 0),X([J({type:qc})],Jc.prototype,`value`,void 0);var Yc=Uc=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Uc.prototype)}};Yc=Uc=X([q({type:G.Set,itemType:Jc})],Yc);var Xc=Wc=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Wc.prototype)}};Xc=Wc=X([q({type:G.Sequence,itemType:Yc})],Xc);var Zc=Gc=class extends Xc{constructor(e){super(e),Object.setPrototypeOf(this,Gc.prototype)}};Zc=Gc=X([q({type:G.Sequence})],Zc);var Qc={fromASN:e=>Hc.toString(pc.fromASN(e)),toASN:e=>pc.toASN(Hc.fromString(e))},$c=class{typeId=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],$c.prototype,`typeId`,void 0),X([J({type:K.Any,context:0})],$c.prototype,`value`,void 0);var el=class{nameAssigner;partyName=new Kc;constructor(e={}){Object.assign(this,e)}};X([J({type:Kc,optional:!0,context:0,implicit:!0})],el.prototype,`nameAssigner`,void 0),X([J({type:Kc,context:1,implicit:!0})],el.prototype,`partyName`,void 0);var tl=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};X([J({type:$c,context:0,implicit:!0})],tl.prototype,`otherName`,void 0),X([J({type:K.IA5String,context:1,implicit:!0})],tl.prototype,`rfc822Name`,void 0),X([J({type:K.IA5String,context:2,implicit:!0})],tl.prototype,`dNSName`,void 0),X([J({type:K.Any,context:3,implicit:!0})],tl.prototype,`x400Address`,void 0),X([J({type:Zc,context:4,implicit:!1})],tl.prototype,`directoryName`,void 0),X([J({type:el,context:5})],tl.prototype,`ediPartyName`,void 0),X([J({type:K.IA5String,context:6,implicit:!0})],tl.prototype,`uniformResourceIdentifier`,void 0),X([J({type:K.OctetString,context:7,implicit:!0,converter:Qc})],tl.prototype,`iPAddress`,void 0),X([J({type:K.ObjectIdentifier,context:8,implicit:!0})],tl.prototype,`registeredID`,void 0),tl=X([q({type:G.Choice})],tl);var nl=`1.3.6.1.5.5.7`,rl=`${nl}.1`,il=`${nl}.2`,al=`${nl}.3`,ol=`${nl}.48`;`${il}`,`${il}`;var sl=`${ol}.1`,cl=`${ol}.2`,ll=`${ol}.3`,ul=`${ol}.5`,dl=`2.5.29`,fl,pl=`${rl}.1`,ml=class{accessMethod=``;accessLocation=new tl;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ml.prototype,`accessMethod`,void 0),X([J({type:tl})],ml.prototype,`accessLocation`,void 0);var hl=fl=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,fl.prototype)}};hl=fl=X([q({type:G.Sequence,itemType:ml})],hl);var gl=`${dl}.35`,_l=class extends ic{},vl=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};X([J({type:_l,context:0,optional:!0,implicit:!0})],vl.prototype,`keyIdentifier`,void 0),X([J({type:tl,context:1,optional:!0,implicit:!0,repeated:`sequence`})],vl.prototype,`authorityCertIssuer`,void 0),X([J({type:K.Integer,context:2,optional:!0,implicit:!0,converter:cc})],vl.prototype,`authorityCertSerialNumber`,void 0);var yl=`${dl}.19`,bl=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Boolean,defaultValue:!1})],bl.prototype,`cA`,void 0),X([J({type:K.Integer,optional:!0})],bl.prototype,`pathLenConstraint`,void 0);var xl,Sl=xl=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,xl.prototype)}};Sl=xl=X([q({type:G.Sequence,itemType:tl})],Sl);var Cl;`${dl}`;var wl=Cl=class extends Sl{constructor(e){super(e),Object.setPrototypeOf(this,Cl.prototype)}};wl=Cl=X([q({type:G.Sequence})],wl);var Tl,El=`${dl}.32`;`${El}`;var Dl=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})],Dl.prototype,`ia5String`,void 0),X([J({type:K.VisibleString})],Dl.prototype,`visibleString`,void 0),X([J({type:K.BmpString})],Dl.prototype,`bmpString`,void 0),X([J({type:K.Utf8String})],Dl.prototype,`utf8String`,void 0),Dl=X([q({type:G.Choice})],Dl);var Ol=class{organization=new Dl;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};X([J({type:Dl})],Ol.prototype,`organization`,void 0),X([J({type:K.Integer,repeated:`sequence`})],Ol.prototype,`noticeNumbers`,void 0);var kl=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};X([J({type:Ol,optional:!0})],kl.prototype,`noticeRef`,void 0),X([J({type:Dl,optional:!0})],kl.prototype,`explicitText`,void 0);var Al=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};X([J({type:K.IA5String})],Al.prototype,`cPSuri`,void 0),X([J({type:kl})],Al.prototype,`userNotice`,void 0),Al=X([q({type:G.Choice})],Al);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 Ml=class{policyIdentifier=``;policyQualifiers;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Ml.prototype,`policyIdentifier`,void 0),X([J({type:jl,repeated:`sequence`,optional:!0})],Ml.prototype,`policyQualifiers`,void 0);var Nl=Tl=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Tl.prototype)}};Nl=Tl=X([q({type:G.Sequence,itemType:Ml})],Nl),`${dl}`;var Pl=class{value;constructor(e=0){this.value=e}};X([J({type:K.Integer})],Pl.prototype,`value`,void 0),Pl=X([q({type:G.Choice})],Pl),`${dl}`;var Fl=class extends Pl{};Fl=X([q({type:G.Choice})],Fl);var Il,Ll=`${dl}.31`,Rl;(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`})(Rl||={});var zl=class extends rc{toJSON(){let e=[],t=this.toNumber();return t&Rl.aACompromise&&e.push(`aACompromise`),t&Rl.affiliationChanged&&e.push(`affiliationChanged`),t&Rl.cACompromise&&e.push(`cACompromise`),t&Rl.certificateHold&&e.push(`certificateHold`),t&Rl.cessationOfOperation&&e.push(`cessationOfOperation`),t&Rl.keyCompromise&&e.push(`keyCompromise`),t&Rl.privilegeWithdrawn&&e.push(`privilegeWithdrawn`),t&Rl.superseded&&e.push(`superseded`),t&Rl.unused&&e.push(`unused`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},Bl=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:tl,context:0,repeated:`sequence`,implicit:!0})],Bl.prototype,`fullName`,void 0),X([J({type:Yc,context:1,implicit:!0})],Bl.prototype,`nameRelativeToCRLIssuer`,void 0),Bl=X([q({type:G.Choice})],Bl);var Vl=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:Bl,context:0,optional:!0})],Vl.prototype,`distributionPoint`,void 0),X([J({type:zl,context:1,optional:!0,implicit:!0})],Vl.prototype,`reasons`,void 0),X([J({type:tl,context:2,optional:!0,repeated:`sequence`,implicit:!0})],Vl.prototype,`cRLIssuer`,void 0);var Hl=Il=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Il.prototype)}};Hl=Il=X([q({type:G.Sequence,itemType:Vl})],Hl);var Ul;`${dl}`;var Wl=Ul=class extends Hl{constructor(e){super(e),Object.setPrototypeOf(this,Ul.prototype)}};Wl=Ul=X([q({type:G.Sequence,itemType:Vl})],Wl),`${dl}`;var Gl=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:Bl,context:0,optional:!0})],Gl.prototype,`distributionPoint`,void 0),X([J({type:K.Boolean,context:1,defaultValue:Gl.ONLY,implicit:!0})],Gl.prototype,`onlyContainsUserCerts`,void 0),X([J({type:K.Boolean,context:2,defaultValue:Gl.ONLY,implicit:!0})],Gl.prototype,`onlyContainsCACerts`,void 0),X([J({type:zl,context:3,optional:!0,implicit:!0})],Gl.prototype,`onlySomeReasons`,void 0),X([J({type:K.Boolean,context:4,defaultValue:Gl.ONLY,implicit:!0})],Gl.prototype,`indirectCRL`,void 0),X([J({type:K.Boolean,context:5,defaultValue:Gl.ONLY,implicit:!0})],Gl.prototype,`onlyContainsAttributeCerts`,void 0),`${dl}`;var Kl;(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`})(Kl||={});var ql=class{reason=Kl.unspecified;constructor(e=Kl.unspecified){this.reason=e}toJSON(){return Kl[this.reason]}toString(){return this.toJSON()}};X([J({type:K.Enumerated})],ql.prototype,`reason`,void 0),ql=X([q({type:G.Choice})],ql);var Jl,Yl=`${dl}.37`,Xl=Jl=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Jl.prototype)}};Xl=Jl=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],Xl),`${Yl}`;var Zl=`${al}.1`,Ql=`${al}.2`,$l=`${al}.3`,eu=`${al}.4`,tu=`${al}.8`,nu=`${al}.9`;`${dl}`;var ru=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};X([J({type:K.Integer,converter:cc})],ru.prototype,`value`,void 0),ru=X([q({type:G.Choice})],ru),`${dl}`;var iu=class{value=new Date;constructor(e){e&&(this.value=e)}};X([J({type:K.GeneralizedTime})],iu.prototype,`value`,void 0),iu=X([q({type:G.Choice})],iu);var au,ou=`${dl}.18`,su=au=class extends Sl{constructor(e){super(e),Object.setPrototypeOf(this,au.prototype)}};su=au=X([q({type:G.Sequence})],su);var cu=`${dl}.15`,lu;(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`})(lu||={});var uu=class extends rc{toJSON(){let e=this.toNumber(),t=[];return e&lu.cRLSign&&t.push(`crlSign`),e&lu.dataEncipherment&&t.push(`dataEncipherment`),e&lu.decipherOnly&&t.push(`decipherOnly`),e&lu.digitalSignature&&t.push(`digitalSignature`),e&lu.encipherOnly&&t.push(`encipherOnly`),e&lu.keyAgreement&&t.push(`keyAgreement`),e&lu.keyCertSign&&t.push(`keyCertSign`),e&lu.keyEncipherment&&t.push(`keyEncipherment`),e&lu.nonRepudiation&&t.push(`nonRepudiation`),t}toString(){return`[${this.toJSON().join(`, `)}]`}},du;`${dl}`;var fu=class{base=new tl;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};X([J({type:tl})],fu.prototype,`base`,void 0),X([J({type:K.Integer,context:0,defaultValue:0,implicit:!0})],fu.prototype,`minimum`,void 0),X([J({type:K.Integer,context:1,optional:!0,implicit:!0})],fu.prototype,`maximum`,void 0);var pu=du=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,du.prototype)}};pu=du=X([q({type:G.Sequence,itemType:fu})],pu);var mu=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};X([J({type:pu,context:0,optional:!0,implicit:!0})],mu.prototype,`permittedSubtrees`,void 0),X([J({type:pu,context:1,optional:!0,implicit:!0})],mu.prototype,`excludedSubtrees`,void 0),`${dl}`;var hu=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,implicit:!0,optional:!0,converter:cc})],hu.prototype,`requireExplicitPolicy`,void 0),X([J({type:K.Integer,context:1,implicit:!0,optional:!0,converter:cc})],hu.prototype,`inhibitPolicyMapping`,void 0);var gu;`${dl}`;var _u=class{issuerDomainPolicy=``;subjectDomainPolicy=``;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],_u.prototype,`issuerDomainPolicy`,void 0),X([J({type:K.ObjectIdentifier})],_u.prototype,`subjectDomainPolicy`,void 0);var vu=gu=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,gu.prototype)}};vu=gu=X([q({type:G.Sequence,itemType:_u})],vu);var yu,bu=`${dl}.17`,xu=yu=class extends Sl{constructor(e){super(e),Object.setPrototypeOf(this,yu.prototype)}};xu=yu=X([q({type:G.Sequence})],xu);var Su=class{type=``;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Su.prototype,`type`,void 0),X([J({type:K.Any,repeated:`set`})],Su.prototype,`values`,void 0);var Cu;`${dl}`;var wu=Cu=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Cu.prototype)}};wu=Cu=X([q({type:G.Sequence,itemType:Su})],wu);var Tu=`${dl}.14`,Eu=class extends _l{};`${dl}`;var Du=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime,context:0,implicit:!0,optional:!0})],Du.prototype,`notBefore`,void 0),X([J({type:K.GeneralizedTime,context:1,implicit:!0,optional:!0})],Du.prototype,`notAfter`,void 0);var Ou;(function(e){e[e.keyUpdateAllowed=1]=`keyUpdateAllowed`,e[e.newExtensions=2]=`newExtensions`,e[e.pKIXCertificate=4]=`pKIXCertificate`})(Ou||={});var ku=class extends rc{toJSON(){let e=[],t=this.toNumber();return t&Ou.pKIXCertificate&&e.push(`pKIXCertificate`),t&Ou.newExtensions&&e.push(`newExtensions`),t&Ou.keyUpdateAllowed&&e.push(`keyUpdateAllowed`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},Au=class{entrustVers=``;entrustInfoFlags=new ku;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralString})],Au.prototype,`entrustVers`,void 0),X([J({type:ku})],Au.prototype,`entrustInfoFlags`,void 0);var ju;`${rl}`;var Mu=ju=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,ju.prototype)}};Mu=ju=X([q({type:G.Sequence,itemType:ml})],Mu);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&&$o(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 Nu=class{algorithm=new Z;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Nu.prototype,`algorithm`,void 0),X([J({type:K.BitString})],Nu.prototype,`subjectPublicKey`,void 0);var Pu=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})],Pu.prototype,`utcTime`,void 0),X([J({type:K.GeneralizedTime})],Pu.prototype,`generalTime`,void 0),Pu=X([q({type:G.Choice})],Pu);var Fu=class{notBefore=new Pu(new Date);notAfter=new Pu(new Date);constructor(e){e&&(this.notBefore=new Pu(e.notBefore),this.notAfter=new Pu(e.notAfter))}};X([J({type:Pu})],Fu.prototype,`notBefore`,void 0),X([J({type:Pu})],Fu.prototype,`notAfter`,void 0);var Iu,Lu=class e{static CRITICAL=!1;extnID=``;critical=e.CRITICAL;extnValue=new ic;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Lu.prototype,`extnID`,void 0),X([J({type:K.Boolean,defaultValue:Lu.CRITICAL})],Lu.prototype,`critical`,void 0),X([J({type:ic})],Lu.prototype,`extnValue`,void 0);var Ru=Iu=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Iu.prototype)}};Ru=Iu=X([q({type:G.Sequence,itemType:Lu})],Ru);var zu;(function(e){e[e.v1=0]=`v1`,e[e.v2=1]=`v2`,e[e.v3=2]=`v3`})(zu||={});var Bu=class{version=zu.v1;serialNumber=new ArrayBuffer(0);signature=new Z;issuer=new Zc;validity=new Fu;subject=new Zc;subjectPublicKeyInfo=new Nu;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,defaultValue:zu.v1})],Bu.prototype,`version`,void 0),X([J({type:K.Integer,converter:cc})],Bu.prototype,`serialNumber`,void 0),X([J({type:Z})],Bu.prototype,`signature`,void 0),X([J({type:Zc})],Bu.prototype,`issuer`,void 0),X([J({type:Fu})],Bu.prototype,`validity`,void 0),X([J({type:Zc})],Bu.prototype,`subject`,void 0),X([J({type:Nu})],Bu.prototype,`subjectPublicKeyInfo`,void 0),X([J({type:K.BitString,context:1,implicit:!0,optional:!0})],Bu.prototype,`issuerUniqueID`,void 0),X([J({type:K.BitString,context:2,implicit:!0,optional:!0})],Bu.prototype,`subjectUniqueID`,void 0),X([J({type:Ru,context:3,optional:!0})],Bu.prototype,`extensions`,void 0);var Vu=class{tbsCertificate=new Bu;tbsCertificateRaw;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Bu,raw:!0})],Vu.prototype,`tbsCertificate`,void 0),X([J({type:Z})],Vu.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Vu.prototype,`signatureValue`,void 0);var Hu=class{userCertificate=new ArrayBuffer(0);revocationDate=new Pu;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:cc})],Hu.prototype,`userCertificate`,void 0),X([J({type:Pu})],Hu.prototype,`revocationDate`,void 0),X([J({type:Lu,optional:!0,repeated:`sequence`})],Hu.prototype,`crlEntryExtensions`,void 0);var Uu=class{version;signature=new Z;issuer=new Zc;thisUpdate=new Pu;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],Uu.prototype,`version`,void 0),X([J({type:Z})],Uu.prototype,`signature`,void 0),X([J({type:Zc})],Uu.prototype,`issuer`,void 0),X([J({type:Pu})],Uu.prototype,`thisUpdate`,void 0),X([J({type:Pu,optional:!0})],Uu.prototype,`nextUpdate`,void 0),X([J({type:Hu,repeated:`sequence`,optional:!0})],Uu.prototype,`revokedCertificates`,void 0),X([J({type:Lu,optional:!0,context:0,repeated:`sequence`})],Uu.prototype,`crlExtensions`,void 0);var Wu=class{tbsCertList=new Uu;tbsCertListRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Uu,raw:!0})],Wu.prototype,`tbsCertList`,void 0),X([J({type:Z})],Wu.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Wu.prototype,`signature`,void 0);var Gu=class{issuer=new Zc;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Zc})],Gu.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:cc})],Gu.prototype,`serialNumber`,void 0);var Ku=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Eu,context:0,implicit:!0})],Ku.prototype,`subjectKeyIdentifier`,void 0),X([J({type:Gu})],Ku.prototype,`issuerAndSerialNumber`,void 0),Ku=X([q({type:G.Choice})],Ku);var qu;(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`})(qu||={});var Ju=class extends Z{};Ju=X([q({type:G.Sequence})],Ju);var Yu=class extends Z{};Yu=X([q({type:G.Sequence})],Yu);var Xu=class extends Z{};Xu=X([q({type:G.Sequence})],Xu);var Zu=class extends Z{};Zu=X([q({type:G.Sequence})],Zu);var Qu=class extends Z{};Qu=X([q({type:G.Sequence})],Qu);var $u=class extends Z{};$u=X([q({type:G.Sequence})],$u);var ed=class{attrType=``;attrValues=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ed.prototype,`attrType`,void 0),X([J({type:K.Any,repeated:`set`})],ed.prototype,`attrValues`,void 0);var td,nd=class{version=qu.v0;sid=new Ku;digestAlgorithm=new Ju;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Yu;signature=new ic;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],nd.prototype,`version`,void 0),X([J({type:Ku})],nd.prototype,`sid`,void 0),X([J({type:Ju})],nd.prototype,`digestAlgorithm`,void 0),X([J({type:ed,repeated:`set`,context:0,implicit:!0,optional:!0,raw:!0})],nd.prototype,`signedAttrs`,void 0),X([J({type:Yu})],nd.prototype,`signatureAlgorithm`,void 0),X([J({type:ic})],nd.prototype,`signature`,void 0),X([J({type:ed,repeated:`set`,context:1,implicit:!0,optional:!0})],nd.prototype,`unsignedAttrs`,void 0);var rd=td=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,td.prototype)}};rd=td=X([q({type:G.Set,itemType:nd})],rd);var id=class extends nd{};id=X([q({type:G.Sequence})],id);var ad=class extends Pu{};ad=X([q({type:G.Choice})],ad);var od=class{acIssuer=new tl;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};X([J({type:tl})],od.prototype,`acIssuer`,void 0),X([J({type:K.Integer})],od.prototype,`acSerial`,void 0),X([J({type:Su,repeated:`sequence`})],od.prototype,`attrs`,void 0);var sd,cd=sd=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,sd.prototype)}};cd=sd=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],cd);var ld=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],ld.prototype,`pathLenConstraint`,void 0),X([J({type:cd,implicit:!0,context:0,optional:!0})],ld.prototype,`permittedAttrs`,void 0),X([J({type:cd,implicit:!0,context:1,optional:!0})],ld.prototype,`excludedAttrs`,void 0),X([J({type:K.Boolean,defaultValue:!0})],ld.prototype,`permitUnSpecified`,void 0);var ud=class{issuer=new Sl;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Sl})],ud.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:cc})],ud.prototype,`serial`,void 0),X([J({type:K.BitString,optional:!0})],ud.prototype,`issuerUID`,void 0);var dd;(function(e){e[e.publicKey=0]=`publicKey`,e[e.publicKeyCert=1]=`publicKeyCert`,e[e.otherObjectTypes=2]=`otherObjectTypes`})(dd||={});var fd=class{digestedObjectType=dd.publicKey;otherObjectTypeID;digestAlgorithm=new Z;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Enumerated})],fd.prototype,`digestedObjectType`,void 0),X([J({type:K.ObjectIdentifier,optional:!0})],fd.prototype,`otherObjectTypeID`,void 0),X([J({type:Z})],fd.prototype,`digestAlgorithm`,void 0),X([J({type:K.BitString})],fd.prototype,`objectDigest`,void 0);var pd=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:Sl,optional:!0})],pd.prototype,`issuerName`,void 0),X([J({type:ud,context:0,implicit:!0,optional:!0})],pd.prototype,`baseCertificateID`,void 0),X([J({type:fd,context:1,implicit:!0,optional:!0})],pd.prototype,`objectDigestInfo`,void 0);var md=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};X([J({type:tl,repeated:`sequence`})],md.prototype,`v1Form`,void 0),X([J({type:pd,context:0,implicit:!0})],md.prototype,`v2Form`,void 0),md=X([q({type:G.Choice})],md);var hd=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime})],hd.prototype,`notBeforeTime`,void 0),X([J({type:K.GeneralizedTime})],hd.prototype,`notAfterTime`,void 0);var gd=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:ud,implicit:!0,context:0,optional:!0})],gd.prototype,`baseCertificateID`,void 0),X([J({type:Sl,implicit:!0,context:1,optional:!0})],gd.prototype,`entityName`,void 0),X([J({type:fd,implicit:!0,context:2,optional:!0})],gd.prototype,`objectDigestInfo`,void 0);var _d;(function(e){e[e.v2=1]=`v2`})(_d||={});var vd=class{version=_d.v2;holder=new gd;issuer=new md;signature=new Z;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new hd;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],vd.prototype,`version`,void 0),X([J({type:gd})],vd.prototype,`holder`,void 0),X([J({type:md})],vd.prototype,`issuer`,void 0),X([J({type:Z})],vd.prototype,`signature`,void 0),X([J({type:K.Integer,converter:cc})],vd.prototype,`serialNumber`,void 0),X([J({type:hd})],vd.prototype,`attrCertValidityPeriod`,void 0),X([J({type:Su,repeated:`sequence`})],vd.prototype,`attributes`,void 0),X([J({type:K.BitString,optional:!0})],vd.prototype,`issuerUniqueID`,void 0),X([J({type:Ru,optional:!0})],vd.prototype,`extensions`,void 0);var yd=class{acinfo=new vd;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:vd})],yd.prototype,`acinfo`,void 0),X([J({type:Z})],yd.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],yd.prototype,`signatureValue`,void 0);var bd;(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`})(bd||={});var xd=class extends rc{},Sd=class{type=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier,implicit:!0,context:0})],Sd.prototype,`type`,void 0),X([J({type:K.Any,implicit:!0,context:1})],Sd.prototype,`value`,void 0);var Cd=class{policyId=``;classList=new xd(bd.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Cd.prototype,`policyId`,void 0),X([J({type:xd,defaultValue:new xd(bd.unclassified)})],Cd.prototype,`classList`,void 0),X([J({type:Sd,repeated:`set`})],Cd.prototype,`securityCategories`,void 0);var wd=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};X([J({type:ic})],wd.prototype,`cotets`,void 0),X([J({type:K.ObjectIdentifier})],wd.prototype,`oid`,void 0),X([J({type:K.Utf8String})],wd.prototype,`string`,void 0);var Td=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:Sl,implicit:!0,context:0,optional:!0})],Td.prototype,`policyAuthority`,void 0),X([J({type:wd,repeated:`sequence`})],Td.prototype,`values`,void 0),`${rl}`,`${rl}`,`${rl}`,`${dl}`;var Ed=`${nl}.10`;`${Ed}`,`${Ed}`,`${Ed}`,`${Ed}`,`${Ed}`;var Dd=`2.5.4`;`${Dd}`;var Od,kd=class{targetCertificate=new ud;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:ud})],kd.prototype,`targetCertificate`,void 0),X([J({type:tl,optional:!0})],kd.prototype,`targetName`,void 0),X([J({type:fd,optional:!0})],kd.prototype,`certDigestInfo`,void 0);var Ad=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};X([J({type:tl,context:0,implicit:!0})],Ad.prototype,`targetName`,void 0),X([J({type:tl,context:1,implicit:!0})],Ad.prototype,`targetGroup`,void 0),X([J({type:kd,context:2,implicit:!0})],Ad.prototype,`targetCert`,void 0),Ad=X([q({type:G.Choice})],Ad);var jd=Od=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Od.prototype)}};jd=Od=X([q({type:G.Sequence,itemType:Ad})],jd);var Md,Nd=Md=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Md.prototype)}};Nd=Md=X([q({type:G.Sequence,itemType:jd})],Nd);var Pd=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};X([J({type:Sl,implicit:!0,context:0,optional:!0})],Pd.prototype,`roleAuthority`,void 0),X([J({type:tl,implicit:!0,context:1})],Pd.prototype,`roleName`,void 0);var Fd=class{service=new tl;ident=new tl;authInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:tl})],Fd.prototype,`service`,void 0),X([J({type:tl})],Fd.prototype,`ident`,void 0),X([J({type:ic,optional:!0})],Fd.prototype,`authInfo`,void 0);var Id,Ld=class{otherCertFormat=``;otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Ld.prototype,`otherCertFormat`,void 0),X([J({type:K.Any})],Ld.prototype,`otherCert`,void 0);var Rd=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};X([J({type:Vu})],Rd.prototype,`certificate`,void 0),X([J({type:yd,context:2,implicit:!0})],Rd.prototype,`v2AttrCert`,void 0),X([J({type:Ld,context:3,implicit:!0})],Rd.prototype,`other`,void 0),Rd=X([q({type:G.Choice})],Rd);var zd=Id=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Id.prototype)}};zd=Id=X([q({type:G.Set,itemType:Rd})],zd);var Bd=class{contentType=``;content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Bd.prototype,`contentType`,void 0),X([J({type:K.Any,context:0})],Bd.prototype,`content`,void 0);var Vd=class{single;any;constructor(e={}){Object.assign(this,e)}};X([J({type:ic})],Vd.prototype,`single`,void 0),X([J({type:K.Any})],Vd.prototype,`any`,void 0),Vd=X([q({type:G.Choice})],Vd);var Hd=class{eContentType=``;eContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Hd.prototype,`eContentType`,void 0),X([J({type:Vd,context:0,optional:!0})],Hd.prototype,`eContent`,void 0);var Ud=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};X([J({type:ic,context:0,implicit:!0,optional:!0})],Ud.prototype,`value`,void 0),X([J({type:ic,converter:mc,context:0,implicit:!0,optional:!0,repeated:`sequence`})],Ud.prototype,`constructedValue`,void 0),Ud=X([q({type:G.Choice})],Ud);var Wd=class{contentType=``;contentEncryptionAlgorithm=new Zu;encryptedContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Wd.prototype,`contentType`,void 0),X([J({type:Zu})],Wd.prototype,`contentEncryptionAlgorithm`,void 0),X([J({type:Ud,optional:!0})],Wd.prototype,`encryptedContent`,void 0);var Gd=class{keyAttrId=``;keyAttr;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Gd.prototype,`keyAttrId`,void 0),X([J({type:K.Any,optional:!0})],Gd.prototype,`keyAttr`,void 0);var Kd,qd=class{subjectKeyIdentifier=new Eu;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:Eu})],qd.prototype,`subjectKeyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],qd.prototype,`date`,void 0),X([J({type:Gd,optional:!0})],qd.prototype,`other`,void 0);var Jd=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:qd,context:0,implicit:!0,optional:!0})],Jd.prototype,`rKeyId`,void 0),X([J({type:Gu,optional:!0})],Jd.prototype,`issuerAndSerialNumber`,void 0),Jd=X([q({type:G.Choice})],Jd);var Yd=class{rid=new Jd;encryptedKey=new ic;constructor(e={}){Object.assign(this,e)}};X([J({type:Jd})],Yd.prototype,`rid`,void 0),X([J({type:ic})],Yd.prototype,`encryptedKey`,void 0);var Xd=Kd=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Kd.prototype)}};Xd=Kd=X([q({type:G.Sequence,itemType:Yd})],Xd);var Zd=class{algorithm=new Z;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Zd.prototype,`algorithm`,void 0),X([J({type:K.BitString})],Zd.prototype,`publicKey`,void 0);var Qd=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Eu,context:0,implicit:!0,optional:!0})],Qd.prototype,`subjectKeyIdentifier`,void 0),X([J({type:Zd,context:1,implicit:!0,optional:!0})],Qd.prototype,`originatorKey`,void 0),X([J({type:Gu,optional:!0})],Qd.prototype,`issuerAndSerialNumber`,void 0),Qd=X([q({type:G.Choice})],Qd);var $d=class{version=qu.v3;originator=new Qd;ukm;keyEncryptionAlgorithm=new Xu;recipientEncryptedKeys=new Xd;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],$d.prototype,`version`,void 0),X([J({type:Qd,context:0})],$d.prototype,`originator`,void 0),X([J({type:ic,context:1,optional:!0})],$d.prototype,`ukm`,void 0),X([J({type:Xu})],$d.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:Xd})],$d.prototype,`recipientEncryptedKeys`,void 0);var ef=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Eu,context:0,implicit:!0})],ef.prototype,`subjectKeyIdentifier`,void 0),X([J({type:Gu})],ef.prototype,`issuerAndSerialNumber`,void 0),ef=X([q({type:G.Choice})],ef);var tf=class{version=qu.v0;rid=new ef;keyEncryptionAlgorithm=new Xu;encryptedKey=new ic;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],tf.prototype,`version`,void 0),X([J({type:ef})],tf.prototype,`rid`,void 0),X([J({type:Xu})],tf.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:ic})],tf.prototype,`encryptedKey`,void 0);var nf=class{keyIdentifier=new ic;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:ic})],nf.prototype,`keyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],nf.prototype,`date`,void 0),X([J({type:Gd,optional:!0})],nf.prototype,`other`,void 0);var rf=class{version=qu.v4;kekid=new nf;keyEncryptionAlgorithm=new Xu;encryptedKey=new ic;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],rf.prototype,`version`,void 0),X([J({type:nf})],rf.prototype,`kekid`,void 0),X([J({type:Xu})],rf.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:ic})],rf.prototype,`encryptedKey`,void 0);var af=class{version=qu.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Xu;encryptedKey=new ic;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],af.prototype,`version`,void 0),X([J({type:$u,context:0,optional:!0})],af.prototype,`keyDerivationAlgorithm`,void 0),X([J({type:Xu})],af.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:ic})],af.prototype,`encryptedKey`,void 0);var of=class{oriType=``;oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],of.prototype,`oriType`,void 0),X([J({type:K.Any})],of.prototype,`oriValue`,void 0);var sf=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};X([J({type:tf,optional:!0})],sf.prototype,`ktri`,void 0),X([J({type:$d,context:1,implicit:!0,optional:!0})],sf.prototype,`kari`,void 0),X([J({type:rf,context:2,implicit:!0,optional:!0})],sf.prototype,`kekri`,void 0),X([J({type:af,context:3,implicit:!0,optional:!0})],sf.prototype,`pwri`,void 0),X([J({type:of,context:4,implicit:!0,optional:!0})],sf.prototype,`ori`,void 0),sf=X([q({type:G.Choice})],sf);var cf,lf=cf=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,cf.prototype)}};lf=cf=X([q({type:G.Set,itemType:sf})],lf);var uf,df=`${nl}.16`;`${df}`,`${df}`;var ff=class{otherRevInfoFormat=``;otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ff.prototype,`otherRevInfoFormat`,void 0),X([J({type:K.Any})],ff.prototype,`otherRevInfo`,void 0);var pf=class{other=new ff;constructor(e={}){Object.assign(this,e)}};X([J({type:ff,context:1,implicit:!0})],pf.prototype,`other`,void 0),pf=X([q({type:G.Choice})],pf);var mf=uf=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,uf.prototype)}};mf=uf=X([q({type:G.Set,itemType:pf})],mf);var hf=class{certs;crls;constructor(e={}){Object.assign(this,e)}};X([J({type:zd,context:0,implicit:!0,optional:!0})],hf.prototype,`certs`,void 0),X([J({type:mf,context:1,implicit:!0,optional:!0})],hf.prototype,`crls`,void 0);var gf,_f=gf=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,gf.prototype)}};_f=gf=X([q({type:G.Set,itemType:ed})],_f);var vf=class{version=qu.v0;originatorInfo;recipientInfos=new lf;encryptedContentInfo=new Wd;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],vf.prototype,`version`,void 0),X([J({type:hf,context:0,implicit:!0,optional:!0})],vf.prototype,`originatorInfo`,void 0),X([J({type:lf})],vf.prototype,`recipientInfos`,void 0),X([J({type:Wd})],vf.prototype,`encryptedContentInfo`,void 0),X([J({type:_f,context:1,implicit:!0,optional:!0})],vf.prototype,`unprotectedAttrs`,void 0);var yf=`1.2.840.113549.1.7.2`,bf,xf=bf=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,bf.prototype)}};xf=bf=X([q({type:G.Set,itemType:Ju})],xf);var Sf=class{version=qu.v0;digestAlgorithms=new xf;encapContentInfo=new Hd;certificates;crls;signerInfos=new rd;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Sf.prototype,`version`,void 0),X([J({type:xf})],Sf.prototype,`digestAlgorithms`,void 0),X([J({type:Hd})],Sf.prototype,`encapContentInfo`,void 0),X([J({type:zd,context:0,implicit:!0,optional:!0})],Sf.prototype,`certificates`,void 0),X([J({type:mf,context:1,implicit:!0,optional:!0})],Sf.prototype,`crls`,void 0),X([J({type:rd})],Sf.prototype,`signerInfos`,void 0);var Cf=`1.2.840.10045.2.1`,wf=`1.2.840.10045.4.1`,Tf=`1.2.840.10045.4.3.1`,Ef=`1.2.840.10045.4.3.2`,Df=`1.2.840.10045.4.3.3`,Of=`1.2.840.10045.4.3.4`,kf=`1.2.840.10045.3.1.7`,Af=`1.3.132.0.34`,jf=`1.3.132.0.35`;function Mf(e){return new Z({algorithm:e})}var Nf=Mf(wf);Mf(Tf);var Pf=Mf(Ef),Ff=Mf(Df),If=Mf(Of),Lf=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Lf.prototype,`fieldType`,void 0),X([J({type:K.Any})],Lf.prototype,`parameters`,void 0),Lf=X([q({type:G.Sequence})],Lf);var Rf=class extends ic{},zf=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};X([J({type:K.OctetString})],zf.prototype,`a`,void 0),X([J({type:K.OctetString})],zf.prototype,`b`,void 0),X([J({type:K.BitString,optional:!0})],zf.prototype,`seed`,void 0),zf=X([q({type:G.Sequence})],zf);var Bf;(function(e){e[e.ecpVer1=1]=`ecpVer1`})(Bf||={});var Vf=class{version=Bf.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Vf.prototype,`version`,void 0),X([J({type:Lf})],Vf.prototype,`fieldID`,void 0),X([J({type:zf})],Vf.prototype,`curve`,void 0),X([J({type:Rf})],Vf.prototype,`base`,void 0),X([J({type:K.Integer,converter:cc})],Vf.prototype,`order`,void 0),X([J({type:K.Integer,optional:!0})],Vf.prototype,`cofactor`,void 0),Vf=X([q({type:G.Sequence})],Vf);var Hf=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Hf.prototype,`namedCurve`,void 0),X([J({type:K.Null})],Hf.prototype,`implicitCurve`,void 0),X([J({type:Vf})],Hf.prototype,`specifiedCurve`,void 0),Hf=X([q({type:G.Choice})],Hf);var Uf=class{version=1;privateKey=new ic;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Uf.prototype,`version`,void 0),X([J({type:ic})],Uf.prototype,`privateKey`,void 0),X([J({type:Hf,context:0,optional:!0})],Uf.prototype,`parameters`,void 0),X([J({type:K.BitString,context:1,optional:!0})],Uf.prototype,`publicKey`,void 0);var Wf=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:cc})],Wf.prototype,`r`,void 0),X([J({type:K.Integer,converter:cc})],Wf.prototype,`s`,void 0);var Gf=`1.2.840.113549.1.1`,Kf=`${Gf}.1`,qf=`${Gf}.7`,Jf=`${Gf}.9`,Yf=`${Gf}.10`,Xf=`${Gf}.2`,Zf=`${Gf}.4`,Qf=`${Gf}.5`,$f=`${Gf}.14`,ep=`${Gf}.11`,tp=`${Gf}.12`,np=`${Gf}.13`,rp=`${Gf}.15`,ip=`${Gf}.16`,ap=`1.3.14.3.2.26`,op=`2.16.840.1.101.3.4.2.4`,sp=`2.16.840.1.101.3.4.2.1`,cp=`2.16.840.1.101.3.4.2.2`,lp=`2.16.840.1.101.3.4.2.3`,up=`2.16.840.1.101.3.4.2.5`,dp=`2.16.840.1.101.3.4.2.6`,fp=`1.2.840.113549.2.2`,pp=`1.2.840.113549.2.5`,mp=`${Gf}.8`;function hp(e){return new Z({algorithm:e,parameters:null})}hp(fp),hp(pp);var gp=hp(ap);hp(op),hp(sp),hp(cp),hp(lp),hp(up),hp(dp);var _p=new Z({algorithm:mp,parameters:Y.serialize(gp)}),vp=new Z({algorithm:Jf,parameters:Y.serialize(pc.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});hp(Kf),hp(Xf),hp(Zf),hp(Qf),hp(rp),hp(ip),hp(tp),hp(np),hp(rp),hp(ip);var yp=class{hashAlgorithm=new Z(gp);maskGenAlgorithm=new Z({algorithm:mp,parameters:Y.serialize(gp)});pSourceAlgorithm=new Z(vp);constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:gp})],yp.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:_p})],yp.prototype,`maskGenAlgorithm`,void 0),X([J({type:Z,context:2,defaultValue:vp})],yp.prototype,`pSourceAlgorithm`,void 0),new Z({algorithm:qf,parameters:Y.serialize(new yp)});var bp=class{hashAlgorithm=new Z(gp);maskGenAlgorithm=new Z({algorithm:mp,parameters:Y.serialize(gp)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:gp})],bp.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:_p})],bp.prototype,`maskGenAlgorithm`,void 0),X([J({type:K.Integer,context:2,defaultValue:20})],bp.prototype,`saltLength`,void 0),X([J({type:K.Integer,context:3,defaultValue:1})],bp.prototype,`trailerField`,void 0),new Z({algorithm:Yf,parameters:Y.serialize(new bp)});var xp=class{digestAlgorithm=new Z;digest=new ic;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],xp.prototype,`digestAlgorithm`,void 0),X([J({type:ic})],xp.prototype,`digest`,void 0);var Sp,Cp=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:cc})],Cp.prototype,`prime`,void 0),X([J({type:K.Integer,converter:cc})],Cp.prototype,`exponent`,void 0),X([J({type:K.Integer,converter:cc})],Cp.prototype,`coefficient`,void 0);var wp=Sp=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Sp.prototype)}};wp=Sp=X([q({type:G.Sequence,itemType:Cp})],wp);var Tp=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})],Tp.prototype,`version`,void 0),X([J({type:K.Integer,converter:cc})],Tp.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:cc})],Tp.prototype,`publicExponent`,void 0),X([J({type:K.Integer,converter:cc})],Tp.prototype,`privateExponent`,void 0),X([J({type:K.Integer,converter:cc})],Tp.prototype,`prime1`,void 0),X([J({type:K.Integer,converter:cc})],Tp.prototype,`prime2`,void 0),X([J({type:K.Integer,converter:cc})],Tp.prototype,`exponent1`,void 0),X([J({type:K.Integer,converter:cc})],Tp.prototype,`exponent2`,void 0),X([J({type:K.Integer,converter:cc})],Tp.prototype,`coefficient`,void 0),X([J({type:wp,optional:!0})],Tp.prototype,`otherPrimeInfos`,void 0);var Ep=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:cc})],Ep.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:cc})],Ep.prototype,`publicExponent`,void 0);var Dp;(function(e){e[e.Transient=0]=`Transient`,e[e.Singleton=1]=`Singleton`,e[e.ResolutionScoped=2]=`ResolutionScoped`,e[e.ContainerScoped=3]=`ContainerScoped`})(Dp||={});var Op=Dp,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 Ap(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 Mp(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 Np(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 Pp(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 Fp(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Pp(arguments[t]));return e}function Ip(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 Lp(e){return!!e.useClass}function Rp(e){return!!e.useFactory}var zp=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,Fp(t))}}),t},e}();function Bp(e){return typeof e==`string`||typeof e==`symbol`}function Vp(e){return typeof e==`object`&&`token`in e&&`multiple`in e}function Hp(e){return typeof e==`object`&&`token`in e&&`transform`in e}function Up(e){return typeof e==`function`||e instanceof zp}function Wp(e){return!!e.useToken}function Gp(e){return e.useValue!=null}function Kp(e){return Lp(e)||Gp(e)||Wp(e)||Rp(e)}var qp=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}(),Jp=function(e){Ap(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(qp),Yp=function(){function e(){this.scopedResolutions=new Map}return e}();function Xp(e,t){return e===null?`at position #`+t:`"`+e.split(`,`)[t].trim()+`" at position #`+t}function Zp(e,t,n){return n===void 0&&(n=` `),Fp([e],t.message.split(`
35
+ `}function sc(e,t={}){let n=[],r=t.label,i;for(nc.lastIndex=0;i=nc.exec(e);){let e=i[1].trim();if(r&&e!==r)continue;rc(e);let t=ac(i[2]);n.push({label:e,data:Ys.decode(t.base64Text),headers:t.headers,lineLength:t.base64Lines[0]?.length??64,newline:oc(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 cc(e,t,n={}){rc(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(...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(`
37
37
  `).map(function(e){return n+e})).join(`
38
- `)}function Qp(e,t,n){var r=Pp(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return Zp(`Cannot inject the dependency `+Xp(r===void 0?null:r,t)+` of "`+e.name+`" constructor. Reason:`,n)}function $p(e){return!(typeof e.dispose!=`function`||e.dispose.length>0)}var em=function(e){Ap(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(qp),tm=function(e){Ap(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(qp),nm=function(){function e(){this.preResolution=new em,this.postResolution=new tm}return e}(),rm=new Map,im=new(function(){function e(e){this.parent=e,this._registry=new Jp,this.interceptors=new nm,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,n){n===void 0&&(n={lifecycle:Op.Transient}),this.ensureNotDisposed();var r=Kp(t)?t:{useClass:t};if(Wp(r))for(var i=[e],a=r;a!=null;){var o=a.useToken;if(i.includes(o))throw Error(`Token registration cycle detected! `+Fp(i,[o]).join(` -> `));i.push(o);var s=this._registry.get(o);a=s&&Wp(s.provider)?s.provider:null}if((n.lifecycle===Op.Singleton||n.lifecycle==Op.ContainerScoped||n.lifecycle==Op.ResolutionScoped)&&(Gp(r)||Rp(r)))throw Error(`Cannot use lifecycle "`+Op[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(),Bp(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(),Bp(e)){if(Bp(t))return this.register(e,{useToken:t},{lifecycle:Op.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:Op.Singleton});throw Error(`Cannot register a type name as a singleton without a "to" token`)}var n=e;return t&&!Bp(t)&&(n=t),this.register(e,{useClass:n},{lifecycle:Op.Singleton})},e.prototype.resolve=function(e,t,n){t===void 0&&(t=new Yp),n===void 0&&(n=!1),this.ensureNotDisposed();var r=this.getRegistration(e);if(!r&&Bp(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(Up(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=Np(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=Np(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===Op.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var n=e.options.lifecycle===Op.Singleton,r=e.options.lifecycle===Op.ContainerScoped,i=n||r,a=Gp(e.provider)?e.provider.useValue:Wp(e.provider)?i?e.instance||=this.resolve(e.provider.useToken,t):this.resolve(e.provider.useToken,t):Lp(e.provider)?i?e.instance||=this.construct(e.provider.useClass,t):this.construct(e.provider.useClass,t):Rp(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t);return e.options.lifecycle===Op.ResolutionScoped&&t.scopedResolutions.set(e,a),a},e.prototype.resolveAll=function(e,t,n){var r=this;t===void 0&&(t=new Yp),n===void 0&&(n=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&Bp(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=Np(this._registry.entries()),r=n.next();!r.done;r=n.next()){var i=Pp(r.value,2),a=i[0],o=i[1];this._registry.setAll(a,o.filter(function(e){return!Gp(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=Np(this._registry.entries()),a=i.next();!a.done;a=i.next()){var o=Pp(a.value,2),s=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===Op.ContainerScoped})&&r._registry.setAll(s,c.map(function(e){return e.options.lifecycle===Op.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 Mp(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 zp)return e.createProxy(function(e){return n.resolve(e,t)});var r=(function(){var r=rm.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,Fp([void 0],i)))})();return $p(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 Vp(r)?Hp(r)?r.multiple?(a=n.resolve(r.transform)).transform.apply(a,Fp([n.resolveAll(r.token,new Yp,r.isOptional)],r.transformArgs)):(o=n.resolve(r.transform)).transform.apply(o,Fp([n.resolve(r.token,e,r.isOptional)],r.transformArgs)):r.multiple?n.resolveAll(r.token,new Yp,r.isOptional):n.resolve(r.token,e,r.isOptional):Hp(r)?(s=n.resolve(r.transform,e)).transform.apply(s,Fp([n.resolve(r.token,e)],r.transformArgs)):n.resolve(r,e)}catch(e){throw Error(Qp(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 am(e){return function(t){rm.set(t,Ip(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){im.register(e,t)}):im.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 om,sm=class{attrId=``;attrValues=[];constructor(e={}){Object.assign(e)}};X([J({type:K.ObjectIdentifier})],sm.prototype,`attrId`,void 0),X([J({type:K.Any,repeated:`set`})],sm.prototype,`attrValues`,void 0);var cm=om=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,om.prototype)}};cm=om=X([q({type:G.Sequence,itemType:sm})],cm);var lm,um=lm=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,lm.prototype)}};um=lm=X([q({type:G.Sequence,itemType:Bd})],um);var dm=`1.2.840.113549.1.12`,fm=`${dm}.1`;`${fm}`,`${fm}`,`${fm}`,`${fm}`,`${fm}`,`${fm}`;var pm=`${dm}.10.1`;`${pm}`,`${pm}`,`${pm}`,`${pm}`,`${pm}`,`${pm}`;var mm=`1.2.840.113549.1.9`,hm=class{certId=``;certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],hm.prototype,`certId`,void 0),X([J({type:K.Any,context:0})],hm.prototype,`certValue`,void 0);var gm=`${mm}.22`;`${gm}`,`${gm}`;var _m=class{crlId=``;crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],_m.prototype,`crlId`,void 0),X([J({type:K.Any,context:0})],_m.prototype,`crltValue`,void 0),`${mm}`;var vm=class extends ic{},ym=class{encryptionAlgorithm=new Z;encryptedData=new vm;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],ym.prototype,`encryptionAlgorithm`,void 0),X([J({type:vm})],ym.prototype,`encryptedData`,void 0);var bm,xm;(function(e){e[e.v1=0]=`v1`})(xm||={});var Sm=class extends ic{},Cm=bm=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,bm.prototype)}};Cm=bm=X([q({type:G.Sequence,itemType:Su})],Cm);var wm=class{version=xm.v1;privateKeyAlgorithm=new Z;privateKey=new Sm;attributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],wm.prototype,`version`,void 0),X([J({type:Z})],wm.prototype,`privateKeyAlgorithm`,void 0),X([J({type:Sm})],wm.prototype,`privateKey`,void 0),X([J({type:Cm,implicit:!0,context:0,optional:!0})],wm.prototype,`attributes`,void 0);var Tm=class extends wm{};Tm=X([q({type:G.Sequence})],Tm);var Em=class extends ym{};Em=X([q({type:G.Sequence})],Em);var Dm=class{secretTypeId=``;secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Dm.prototype,`secretTypeId`,void 0),X([J({type:K.Any,context:0})],Dm.prototype,`secretValue`,void 0);var Om=class{mac=new xp;macSalt=new ic;iterations=1;constructor(e={}){Object.assign(this,e)}};X([J({type:xp})],Om.prototype,`mac`,void 0),X([J({type:ic})],Om.prototype,`macSalt`,void 0),X([J({type:K.Integer,defaultValue:1})],Om.prototype,`iterations`,void 0);var km=class{version=3;authSafe=new Bd;macData=new Om;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],km.prototype,`version`,void 0),X([J({type:Bd})],km.prototype,`authSafe`,void 0),X([J({type:Om,optional:!0})],km.prototype,`macData`,void 0);var Am,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:sm,repeated:`set`,optional:!0})],jm.prototype,`bagAttributes`,void 0);var Mm=Am=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Am.prototype)}};Mm=Am=X([q({type:G.Sequence,itemType:jm})],Mm);var Nm,Pm,Fm,Im=`1.2.840.113549.1.9`;`${Im}`;var Lm=`${Im}.24`,Rm=`${Im}.25`,zm=`${Im}.26`,Bm=`${Im}.27`;`${Lm}`,`${Lm}`,`${Im}`,`${Im}`,`${Im}`,`${Im}`,`${Im}`,`${Im}`;var Vm=`${Im}.7`;`${Im}`,`${Im}`,`${Im}`;var Hm=`${Im}.14`;`${Im}`,`${Im}`,`${Im}`,`${Rm}`,`${Rm}`,`${Rm}`,`${Rm}`,`${Rm}`;var Um=`1.3.6.1.5.5.7.9`;`${Um}`,`${Um}`,`${Um}`,`${Um}`,`${Um}`,`${zm}`,`${zm}`,`${Bm}`,`${Bm}`,`${Im}`,`${Im}`,`${Im}`,`${Dd}`;var Wm=class extends Kc{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};X([J({type:K.IA5String})],Wm.prototype,`ia5String`,void 0),Wm=X([q({type:G.Choice})],Wm);var Gm=class extends Bd{};Gm=X([q({type:G.Sequence})],Gm);var Km=class extends km{};Km=X([q({type:G.Sequence})],Km);var qm=class extends ym{};qm=X([q({type:G.Sequence})],qm);var Jm=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.IA5String})],Jm.prototype,`value`,void 0),Jm=X([q({type:G.Choice})],Jm);var Ym=class extends Wm{};Ym=X([q({type:G.Choice})],Ym);var Xm=class extends Kc{};Xm=X([q({type:G.Choice})],Xm);var Zm=class{value;constructor(e=new Date){this.value=e}};X([J({type:K.GeneralizedTime})],Zm.prototype,`value`,void 0),Zm=X([q({type:G.Choice})],Zm);var Qm=class extends Kc{};Qm=X([q({type:G.Choice})],Qm);var $m=class{value;constructor(e=`M`){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],$m.prototype,`value`,void 0),$m=X([q({type:G.Choice})],$m);var eh=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],eh.prototype,`value`,void 0),eh=X([q({type:G.Choice})],eh);var th=class extends eh{};th=X([q({type:G.Choice})],th);var nh=class extends Kc{};nh=X([q({type:G.Choice})],nh);var rh=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.ObjectIdentifier})],rh.prototype,`value`,void 0),rh=X([q({type:G.Choice})],rh);var ih=class extends Pu{};ih=X([q({type:G.Choice})],ih);var ah=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};X([J({type:K.Integer})],ah.prototype,`value`,void 0),ah=X([q({type:G.Choice})],ah);var oh=class extends nd{};oh=X([q({type:G.Sequence})],oh);var sh=class extends Kc{};sh=X([q({type:G.Choice})],sh);var ch=Nm=class extends Ru{constructor(e){super(e),Object.setPrototypeOf(this,Nm.prototype)}};ch=Nm=X([q({type:G.Sequence})],ch);var lh=Pm=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Pm.prototype)}};lh=Pm=X([q({type:G.Set,itemType:ed})],lh);var uh=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.BmpString})],uh.prototype,`value`,void 0),uh=X([q({type:G.Choice})],uh);var dh=class extends Z{};dh=X([q({type:G.Sequence})],dh);var fh=Fm=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,Fm.prototype)}};fh=Fm=X([q({type:G.Sequence,itemType:dh})],fh);var ph,mh=ph=class extends zc{constructor(e){super(e),Object.setPrototypeOf(this,ph.prototype)}};mh=ph=X([q({type:G.Sequence,itemType:Su})],mh);var hh=class{version=0;subject=new Zc;subjectPKInfo=new Nu;attributes=new mh;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],hh.prototype,`version`,void 0),X([J({type:Zc})],hh.prototype,`subject`,void 0),X([J({type:Nu})],hh.prototype,`subjectPKInfo`,void 0),X([J({type:mh,implicit:!0,context:0,optional:!0})],hh.prototype,`attributes`,void 0);var gh=class{certificationRequestInfo=new hh;certificationRequestInfoRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:hh,raw:!0})],gh.prototype,`certificationRequestInfo`,void 0),X([J({type:Z})],gh.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],gh.prototype,`signature`,void 0);var _h=`crypto.algorithm`,vh=class{getAlgorithms(){return im.resolveAll(_h)}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}}},yh=`crypto.algorithmProvider`;im.registerSingleton(yh,vh);var bh,xh=`1.3.36.3.3.2.8.1.1`,Sh=`${xh}.1`,Ch=`${xh}.2`,wh=`${xh}.3`,Th=`${xh}.4`,Eh=`${xh}.5`,Dh=`${xh}.6`,Oh=`${xh}.7`,kh=`${xh}.8`,Ah=`${xh}.9`,jh=`${xh}.10`,Mh=`${xh}.11`,Nh=`${xh}.12`,Ph=`${xh}.13`,Fh=`${xh}.14`,Ih=`brainpoolP160r1`,Lh=`brainpoolP160t1`,Rh=`brainpoolP192r1`,zh=`brainpoolP192t1`,Bh=`brainpoolP224r1`,Vh=`brainpoolP224t1`,Hh=`brainpoolP256r1`,Uh=`brainpoolP256t1`,Wh=`brainpoolP320r1`,Gh=`brainpoolP320t1`,Kh=`brainpoolP384r1`,qh=`brainpoolP384t1`,Jh=`brainpoolP512r1`,Yh=`brainpoolP512t1`,Xh=`ECDSA`,Zh=bh=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case Xh.toLowerCase():if(`hash`in e)switch((typeof e.hash==`string`?e.hash:e.hash.name).toLowerCase()){case`sha-1`:return Nf;case`sha-256`:return Pf;case`sha-384`:return Ff;case`sha-512`:return If}else if(`namedCurve`in e){let t=``;switch(e.namedCurve){case`P-256`:t=kf;break;case`K-256`:t=bh.SECP256K1;break;case`P-384`:t=Af;break;case`P-521`:t=jf;break;case Ih:t=Sh;break;case Lh:t=Ch;break;case Rh:t=wh;break;case zh:t=Th;break;case Bh:t=Eh;break;case Vh:t=Dh;break;case Hh:t=Oh;break;case Uh:t=kh;break;case Wh:t=Ah;break;case Gh:t=jh;break;case Kh:t=Mh;break;case qh:t=Nh;break;case Jh:t=Ph;break;case Yh:t=Fh}if(t)return new Z({algorithm:Cf,parameters:Y.serialize(new Hf({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case wf:return{name:Xh,hash:{name:`SHA-1`}};case Ef:return{name:Xh,hash:{name:`SHA-256`}};case Df:return{name:Xh,hash:{name:`SHA-384`}};case Of:return{name:Xh,hash:{name:`SHA-512`}};case Cf:if(!e.parameters)throw TypeError(`Cannot get required parameters from EC algorithm`);switch(Y.parse(e.parameters,Hf).namedCurve){case kf:return{name:Xh,namedCurve:`P-256`};case bh.SECP256K1:return{name:Xh,namedCurve:`K-256`};case Af:return{name:Xh,namedCurve:`P-384`};case jf:return{name:Xh,namedCurve:`P-521`};case Sh:return{name:Xh,namedCurve:Ih};case Ch:return{name:Xh,namedCurve:Lh};case wh:return{name:Xh,namedCurve:Rh};case Th:return{name:Xh,namedCurve:zh};case Eh:return{name:Xh,namedCurve:Bh};case Dh:return{name:Xh,namedCurve:Vh};case Oh:return{name:Xh,namedCurve:Hh};case kh:return{name:Xh,namedCurve:Uh};case Ah:return{name:Xh,namedCurve:Wh};case jh:return{name:Xh,namedCurve:Gh};case Mh:return{name:Xh,namedCurve:Kh};case Nh:return{name:Xh,namedCurve:qh};case Ph:return{name:Xh,namedCurve:Jh};case Fh:return{name:Xh,namedCurve:Yh}}}return null}};Zh.SECP256K1=`1.3.132.0.10`,Zh=bh=X([am()],Zh),im.registerSingleton(_h,Zh);var Qh=Symbol(`name`),$h=Symbol(`value`),eg=class{constructor(e,t={},n=``){this[Qh]=e,this[$h]=n;for(let e in t)this[e]=t[e]}};eg.NAME=Qh,eg.VALUE=$h;var tg=class{static toTextObject(e){let t=new eg(`Algorithm Identifier`,{},ng.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Cf:{let n=new Zh().toWebAlgorithm(e);n&&`namedCurve`in n?t[`Named Curve`]=n.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}},ng=class{static toString(e){return this.items[e]||e}};ng.items={[ap]:`sha1`,[op]:`sha224`,[sp]:`sha256`,[cp]:`sha384`,[lp]:`sha512`,[Kf]:`rsaEncryption`,[Qf]:`sha1WithRSAEncryption`,[$f]:`sha224WithRSAEncryption`,[ep]:`sha256WithRSAEncryption`,[tp]:`sha384WithRSAEncryption`,[np]:`sha512WithRSAEncryption`,[Cf]:`ecPublicKey`,[wf]:`ecdsaWithSHA1`,[Tf]:`ecdsaWithSHA224`,[Ef]:`ecdsaWithSHA256`,[Df]:`ecdsaWithSHA384`,[Of]:`ecdsaWithSHA512`,[Zl]:`TLS WWW server authentication`,[Ql]:`TLS WWW client authentication`,[$l]:`Code Signing`,[eu]:`E-mail Protection`,[tu]:`Time Stamping`,[nu]:`OCSP Signing`,[yf]:`Signed Data`};var rg=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[eg.VALUE];a&&(i=` ${a}`),n.push(`${r}${e[eg.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[eg.NAME]=i,n.push(...this.serializeObj(e,t));else if(a instanceof eg)a[eg.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[eg.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)}};rg.oidSerializer=ng,rg.algorithmSerializer=tg;var ig,ag=class e{get rawData(){return Bc(this,ig,`f`)||Vc(this,ig,Y.serialize(this.asn),`f`),Bc(this,ig,`f`)}constructor(...e){ig.set(this,void 0),U.isBufferSource(e[0])?(this.asn=Y.parse(e[0],e[1]),Vc(this,ig,U.toArrayBuffer(e[0]),`f`),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(t){return t instanceof e&&ii(t.rawData,this.rawData)}toString(e=`text`){switch(e){case`asn`:return Y.toString(this.rawData);case`text`:return rg.serialize(this.toTextObject());case`hex`:return ni.ToHex(this.rawData);case`base64`:return ni.ToBase64(this.rawData);case`base64url`:return ni.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 eg(this.getTextName(),{},e)}};ig=new WeakMap,ag.NAME=`ASN`;var og=class e extends ag{constructor(...e){let t;t=U.isBufferSource(e[0])?U.toArrayBuffer(e[0]):Y.serialize(new Lu({extnID:e[0],critical:e[1],extnValue:new ic(U.toArrayBuffer(e[2]))})),super(t,Lu)}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[eg.NAME]===e.NAME&&(t[eg.NAME]=ng.toString(this.type)),t}},sg,cg=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[sg]=`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}};sg=Symbol.toStringTag,cg.DEFAULT=`default`;var lg=new cg,ug=/^[0-2](?:\.[1-9][0-9]*)+$/;function dg(e){return new RegExp(ug).test(e)}var fg=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 dg(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},pg=new fg;pg.register(`CN`,`2.5.4.3`),pg.register(`L`,`2.5.4.7`),pg.register(`ST`,`2.5.4.8`),pg.register(`O`,`2.5.4.10`),pg.register(`OU`,`2.5.4.11`),pg.register(`C`,`2.5.4.6`),pg.register(`DC`,`0.9.2342.19200300.100.1.25`),pg.register(`E`,`1.2.840.113549.1.9.1`),pg.register(`G`,`2.5.4.42`),pg.register(`I`,`2.5.4.43`),pg.register(`SN`,`2.5.4.4`),pg.register(`T`,`2.5.4.12`);function mg(e,t){return`\\${ni.ToHex(ni.FromUtf8String(t)).toUpperCase()}`}function hg(e){return e.replace(/([,+"\\<>;])/g,`\\$1`).replace(/^([ #])/,`\\$1`).replace(/([ ]$)/,`\\$1`).replace(/([\r\n\t])/,mg)}var gg=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 fg,this.asn=new Zc;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 Zc?e:U.isBufferSource(e)?Y.parse(e,Zc):this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||pg.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)||pg.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${ni.ToHex(e.value.anyValue)}`:hg(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?`#${ni.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(n)}return e}fromString(e){let t=new Zc,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 Yc([s])),i=o}return t}fromJSON(e){let t=new Zc;for(let n of e){let e=new Yc;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 Jc({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=ni.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]||lg.get()):t=e[0]||lg.get(),await t.subtle.digest(n,this.toArrayBuffer())}},_g=`Cannot initialize GeneralName from ASN.1 data.`,vg=`${_g} Unsupported string format in use.`,yg=`${_g} Value doesn't match to GUID regular expression.`,bg=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,xg=`1.3.6.1.4.1.311.25.1`,Sg=`1.3.6.1.4.1.311.20.2.3`,Cg=`email`,wg=`guid`,Tg=class extends ag{constructor(...e){let t;if(e.length===2)switch(e[0]){case`dn`:{let n=new gg(e[1]).toArrayBuffer(),r=Y.parse(n,Zc);t=new tl({directoryName:r});break}case`dns`:t=new tl({dNSName:e[1]});break;case Cg:t=new tl({rfc822Name:e[1]});break;case wg:{let n=new RegExp(bg,`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?ni.ToHex(new Uint8Array(ni.FromHex(e)).reverse()):e).join(``);t=new tl({otherName:new $c({typeId:xg,value:Y.serialize(new ic(ni.FromHex(r)))})});break}case`ip`:t=new tl({iPAddress:e[1]});break;case`id`:t=new tl({registeredID:e[1]});break;case`upn`:t=new tl({otherName:new $c({typeId:Sg,value:Y.serialize(gc.toASN(e[1]))})});break;case`url`:t=new tl({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],tl):e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=`dns`,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Cg,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 gg(e.directoryName).toString();else if(e.otherName!=null){if(e.otherName.typeId===xg){this.type=wg;let t=Y.parse(e.otherName.value,ic),n=new RegExp(bg,`i`).exec(ni.ToHex(t));if(!n)throw Error(yg);this.value=n.slice(1).map((e,t)=>t<3?ni.ToHex(new Uint8Array(ni.FromHex(e)).reverse()):e).join(`-`)}else if(e.otherName.typeId===Sg)this.type=`upn`,this.value=Y.parse(e.otherName.value,Kc).toString();else throw Error(vg)}else throw Error(vg)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case`dn`:case`dns`:case wg:case`ip`:case`id`:case`upn`:case`url`:e=this.type.toUpperCase();break;case Cg:e=`Email`;break;default:throw Error(`Unsupported GeneralName type`)}let t=this.value;return this.type===`id`&&(t=ng.toString(t)),new eg(e,void 0,t)}},Eg=class extends ag{constructor(e){let t;if(e instanceof Sl)t=e;else if(Array.isArray(e)){let n=[];for(let t of e)if(t instanceof tl)n.push(t);else{let e=Y.parse(new Tg(t.type,t.value).rawData,tl);n.push(e)}t=new Sl(n)}else if(U.isBufferSource(e))t=Y.parse(e,Sl);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 Tg(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[eg.NAME]];Array.isArray(r)||(r=[],e[n[eg.NAME]]=r),r.push(n)}return e}};Eg.NAME=`GeneralNames`;var Dg=`-{5}`,Og=`\\n`,kg=`${Dg}BEGIN (${`[^${Og}]+`}(?=${Dg}))${Dg}`,Ag=`${Dg}END \\1${Dg}`,jg=`\\n`,Mg=`${kg}${jg}(?:((?:${`[^:${Og}]+`}: ${`(?:[^${Og}]+${jg}(?: +[^${Og}]+${jg})*)`})+))?${jg}?(${`(?:[a-zA-Z0-9=+/]+${jg})+`})${Ag}`,Ng=class{static isPem(e){return typeof e==`string`&&new RegExp(Mg,`g`).test(e.replace(/\r/g,``))}static decodeWithHeaders(e){e=e.replace(/\r/g,``);let t=new RegExp(Mg,`g`),n=[],r=null;for(;r=t.exec(e);){let e=r[3].replace(RegExp(`[${Og}]+`,`g`),``),t={type:r[1],headers:[],rawData:ni.FromBase64(e)},i=r[2];if(i){let e=i.split(new RegExp(jg,`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=ni.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
- `)}};Ng.CertificateTag=`CERTIFICATE`,Ng.CrlTag=`CRL`,Ng.CertificateRequestTag=`CERTIFICATE REQUEST`,Ng.PublicKeyTag=`PUBLIC KEY`,Ng.PrivateKeyTag=`PRIVATE KEY`;var Pg=class e extends ag{static isAsnEncoded(e){return U.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(Ng.isPem(e))return Ng.decode(e)[0];if(ni.isHex(e))return ni.FromHex(e);if(ni.isBase64(e))return ni.FromBase64(e);if(ni.isBase64Url(e))return ni.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=ni.ToBinary(e);if(Ng.isPem(n))return Ng.decode(n)[0];if(ni.isHex(n))return ni.FromHex(n);if(ni.isBase64(n))return ni.FromBase64(n);if(ni.isBase64Url(n))return ni.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 Ng.encode(this.rawData,this.tag);default:return super.toString(e)}}},Fg=class e extends Pg{static async create(t,n=lg.get()){if(t instanceof e)return t;if(cg.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){Pg.isAsnEncoded(e)?super(e,Nu):super(e),this.tag=Ng.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]||lg.get()):t=e[0]||lg.get();let i=this.rawData,a=Y.parse(this.rawData,Nu);return a.algorithm.algorithm===Yf&&(i=Ig(a,i)),t.subtle.importKey(`spki`,i,r,!0,n)}onInit(e){let t=im.resolve(yh),n=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case Kf:{let t=Y.parse(e.subjectPublicKey,Ep),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]||lg.get()):t=e[0]||lg.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=lg.get()):t=e[0]:e.length===2?(n=e[0],t=e[1]):t=lg.get();let r=Y.parse(this.rawData,Nu);return await t.subtle.digest(n,r.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,Nu);switch(e.Algorithm=rg.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Cf:e[`EC Point`]=t.subjectPublicKey;break;case Kf:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function Ig(e,t){return e.algorithm=new Z({algorithm:Kf,parameters:null}),t=Y.serialize(e),t}var Lg=class e extends og{static async create(t,n=!1,r=lg.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let i=await(await Fg.create(t,r)).getKeyIdentifier(r);return new e(ni.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new vl({keyIdentifier:new _l(ni.FromHex(e[0]))});super(gl,e[1],Y.serialize(t))}else{let t=e[0],n=new vl({authorityCertIssuer:t.name instanceof Eg?Y.parse(t.name.rawData,Sl):t.name,authorityCertSerialNumber:ni.FromHex(t.serialNumber)});super(gl,e[1],Y.serialize(n))}}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,vl);t.keyIdentifier&&(this.keyId=ni.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?ni.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=Y.parse(this.value,vl);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new Eg(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};Lg.NAME=`Authority Key Identifier`;var Rg=class extends og{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,bl);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new bl({cA:e[0],pathLenConstraint:e[1]});super(yl,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}};Rg.NAME=`Basic Constraints`;var zg;(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`})(zg||={});var Bg=class extends og{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Xl);this.usages=t.map(e=>e)}else{let t=new Xl(e[0]);super(Yl,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.usages.map(e=>ng.toString(e)).join(`, `),e}};Bg.NAME=`Extended Key Usages`;var Vg;(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`})(Vg||={});var Hg=class extends og{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,uu);this.usages=t.toNumber()}else{let t=new uu(e[0]);super(cu,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,uu).toJSON().join(`, `),e}};Hg.NAME=`Key Usages`;var Ug=class e extends og{static async create(t,n=!1,r=lg.get()){let i=await(await Fg.create(t,r)).getKeyIdentifier(r);return new e(ni.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Eu);this.keyId=ni.ToHex(t)}else{let t=typeof e[0]==`string`?ni.FromHex(e[0]):e[0],n=new Eu(t);super(Tu,e[1],Y.serialize(n)),this.keyId=ni.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,Eu),e}};Ug.NAME=`Subject Key Identifier`;var Wg=class extends og{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(bu,e[1],new Eg(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,xu);this.names=new Eg(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};Wg.NAME=`Subject Alternative Name`;var Gg=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new og(e),n=this.items.get(t.type);return n?new n(e):t}};Gg.items=new Map;var Kg=class extends og{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Nl);this.policies=t.map(e=>e.policyIdentifier)}else{let t=e[0],n=e[1]??!1,r=new Nl(t.map(e=>new Ml({policyIdentifier:e})));super(El,n,Y.serialize(r)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new eg(``,{},ng.toString(e))),e}};Kg.NAME=`Certificate Policies`,Gg.register(El,Kg);var qg=class extends og{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 Vl({distributionPoint:new Bl({fullName:[new tl({uniformResourceIdentifier:e})]})})),n=new Hl(t);super(Ll,e[1],Y.serialize(n))}else{let t=new Hl(e[0]);super(Ll,e[1],Y.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Hl);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 Tg(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};qg.NAME=`CRL Distribution Points`;var Jg=class extends og{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof hl){let t=new hl(e[0]);super(pl,e[1],Y.serialize(t))}else{let t=e[0],n=new hl;Xg(n,t,sl,`ocsp`),Xg(n,t,cl,`caIssuers`),Xg(n,t,ll,`timeStamping`),Xg(n,t,ul,`caRepository`),super(pl,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,hl).forEach(e=>{switch(e.accessMethod){case sl:this.ocsp.push(new Tg(e.accessLocation));break;case cl:this.caIssuers.push(new Tg(e.accessLocation));break;case ll:this.timeStamping.push(new Tg(e.accessLocation));break;case ul:this.caRepository.push(new Tg(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Yg(e,`OCSP`,this.ocsp),this.caIssuers.length&&Yg(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&Yg(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&Yg(e,`CA Repository`,this.caRepository),e}};Jg.NAME=`Authority Info Access`;function Yg(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new eg(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[eg.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function Xg(e,t,n,r){let i=t[r];i&&(Array.isArray(i)?i:[i]).forEach(t=>{typeof t==`string`&&(t=new Tg(`url`,t)),e.push(new ml({accessMethod:n,accessLocation:Y.parse(t.rawData,tl)}))})}var Zg=class extends og{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(ou,e[1],new Eg(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Sl);this.names=new Eg(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};Zg.NAME=`Issuer Alternative Name`;var Qg=class e extends ag{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 Su({type:n,values:r}))}super(t,Su)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new eg(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[eg.NAME]===e.NAME&&(t[eg.NAME]=ng.toString(this.type)),t}};Qg.NAME=`Attribute`;var $g=class extends Qg{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=new sh({printableString:e[0]});super(Vm,[Y.serialize(t)])}this.password??=``}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],sh);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[eg.VALUE]=this.password,e}};$g.NAME=`Challenge Password`;var e_=class extends Qg{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=e[0],n=new Ru;for(let e of t)n.push(Y.parse(e.rawData,Lu));super(Hm,[Y.serialize(n)])}this.items??=[]}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],Ru);this.items=e.map(e=>Gg.create(Y.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[eg.NAME]]=n;return e}};e_.NAME=`Extensions`;var t_=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new Qg(e),n=this.items.get(t.type);return n?new n(e):t}};t_.items=new Map;var n_=`crypto.signatureFormatter`,r_=class{toAsnSignature(e,t){return U.toArrayBuffer(t)}toWebSignature(e,t){return U.toArrayBuffer(t)}},i_,a_=i_=class{static createPssParams(e,t){let n=i_.getHashAlgorithm(e);return n?new bp({hashAlgorithm:n,maskGenAlgorithm:new Z({algorithm:mp,parameters:Y.serialize(n)}),saltLength:t}):null}static getHashAlgorithm(e){let t=im.resolve(yh);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:Qf,parameters:null});case`sha-256`:return new Z({algorithm:ep,parameters:null});case`sha-384`:return new Z({algorithm:tp,parameters:null});case`sha-512`:return new Z({algorithm:np,parameters:null})}}else return new Z({algorithm:Kf,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=i_.createPssParams(e.hash,e.saltLength);if(!t)throw Error(`Cannot create PSS parameters`);return new Z({algorithm:Yf,parameters:Y.serialize(t)})}return new Z({algorithm:Yf,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Kf:return{name:`RSASSA-PKCS1-v1_5`};case Qf:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case ep:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case tp:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case np:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case Yf:if(e.parameters){let t=Y.parse(e.parameters,bp);return{name:`RSA-PSS`,hash:im.resolve(yh).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:`RSA-PSS`}}return null}};a_=i_=X([am()],a_),im.registerSingleton(_h,a_);var o_=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new Z({algorithm:ap});case`sha-256`:return new Z({algorithm:sp});case`sha-384`:return new Z({algorithm:cp});case`sha-512`:return new Z({algorithm:lp})}return null}toWebAlgorithm(e){switch(e.algorithm){case ap:return{name:`SHA-1`};case sp:return{name:`SHA-256`};case cp:return{name:`SHA-384`};case lp:return{name:`SHA-512`}}return null}};o_=X([am()],o_),im.registerSingleton(_h,o_);var s_=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 Wf,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,Wf),i=t.namedCurve,a=e.namedCurveSize.get(i)||e.defaultNamedCurveSize;return ri(this.addPadding(a,this.removePadding(r.r)),this.addPadding(a,this.removePadding(r.s)))}return null}};s_.namedCurveSize=new Map,s_.defaultNamedCurveSize=32;var c_=`1.3.101.110`,l_=`1.3.101.111`,u_=`1.3.101.112`,d_=`1.3.101.113`,f_=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=u_;break;case`x25519`:t=c_;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=u_;break;case`ed448`:t=d_}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=c_;break;case`x448`:t=l_}}return t?new Z({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case u_:return{name:`Ed25519`};case d_:return{name:`EdDSA`,namedCurve:`Ed448`};case c_:return{name:`X25519`};case l_:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}};f_=X([am()],f_),im.registerSingleton(_h,f_);var p_,m_,h_,g_,__,v_,y_,b_,x_=class extends Pg{get subjectName(){return Bc(this,m_,`f`)||Vc(this,m_,new gg(this.asn.certificationRequestInfo.subject),`f`),Bc(this,m_,`f`)}get subject(){return Bc(this,h_,`f`)||Vc(this,h_,this.subjectName.toString(),`f`),Bc(this,h_,`f`)}get signatureAlgorithm(){if(!Bc(this,g_,`f`)){let e=im.resolve(yh);Vc(this,g_,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return Bc(this,g_,`f`)}get signature(){return Bc(this,__,`f`)||Vc(this,__,this.asn.signature,`f`),Bc(this,__,`f`)}get publicKey(){return Bc(this,v_,`f`)||Vc(this,v_,new Fg(this.asn.certificationRequestInfo.subjectPKInfo),`f`),Bc(this,v_,`f`)}get attributes(){return Bc(this,y_,`f`)||Vc(this,y_,this.asn.certificationRequestInfo.attributes.map(e=>t_.create(Y.serialize(e))),`f`),Bc(this,y_,`f`)}get extensions(){if(!Bc(this,b_,`f`)){Vc(this,b_,[],`f`);let e=this.getAttribute(Hm);e instanceof e_&&Vc(this,b_,e.items,`f`)}return Bc(this,b_,`f`)}get tbs(){return Bc(this,p_,`f`)||Vc(this,p_,this.asn.certificationRequestInfoRaw||Y.serialize(this.asn.certificationRequestInfo),`f`),Bc(this,p_,`f`)}constructor(e){let t=Pg.isAsnEncoded(e)?[e,gh]:[e];super(t[0],t[1]),p_.set(this,void 0),m_.set(this,void 0),h_.set(this,void 0),g_.set(this,void 0),__.set(this,void 0),v_.set(this,void 0),y_.set(this,void 0),b_.set(this,void 0),this.tag=Ng.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=lg.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=im.resolveAll(n_).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,gh),n=t.certificationRequestInfo,r=new eg(``,{Version:`${zu[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new eg(``);for(let t of this.attributes){let n=t.toTextObject();e[n[eg.NAME]]=n}r.Attributes=e}return e.Data=r,e.Signature=new eg(``,{Algorithm:rg.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};p_=new WeakMap,m_=new WeakMap,h_=new WeakMap,g_=new WeakMap,__=new WeakMap,v_=new WeakMap,y_=new WeakMap,b_=new WeakMap,x_.NAME=`PKCS#10 Certificate Request`;var S_,C_,w_,T_,E_,D_,O_,k_,A_,j_,M_,N_,P_=class extends Pg{get publicKey(){return Bc(this,N_,`f`)||Vc(this,N_,new Fg(this.asn.tbsCertificate.subjectPublicKeyInfo),`f`),Bc(this,N_,`f`)}get serialNumber(){if(!Bc(this,C_,`f`)){let e=this.asn.tbsCertificate,t=new Uint8Array(e.serialNumber);t.length>1&&t[0]===0&&t[1]>127&&(t=t.slice(1)),Vc(this,C_,ni.ToHex(t),`f`)}return Bc(this,C_,`f`)}get subjectName(){return Bc(this,w_,`f`)||Vc(this,w_,new gg(this.asn.tbsCertificate.subject),`f`),Bc(this,w_,`f`)}get subject(){return Bc(this,T_,`f`)||Vc(this,T_,this.subjectName.toString(),`f`),Bc(this,T_,`f`)}get issuerName(){return Bc(this,E_,`f`)||Vc(this,E_,new gg(this.asn.tbsCertificate.issuer),`f`),Bc(this,E_,`f`)}get issuer(){return Bc(this,D_,`f`)||Vc(this,D_,this.issuerName.toString(),`f`),Bc(this,D_,`f`)}get notBefore(){if(!Bc(this,O_,`f`)){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw Error(`Cannot get 'notBefore' value`);Vc(this,O_,e,`f`)}return Bc(this,O_,`f`)}get notAfter(){if(!Bc(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`);Vc(this,k_,e,`f`)}return Bc(this,k_,`f`)}get signatureAlgorithm(){if(!Bc(this,A_,`f`)){let e=im.resolve(yh);Vc(this,A_,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return Bc(this,A_,`f`)}get signature(){return Bc(this,j_,`f`)||Vc(this,j_,this.asn.signatureValue,`f`),Bc(this,j_,`f`)}get extensions(){return Bc(this,M_,`f`)||(Vc(this,M_,[],`f`),this.asn.tbsCertificate.extensions&&Vc(this,M_,this.asn.tbsCertificate.extensions.map(e=>Gg.create(Y.serialize(e))),`f`)),Bc(this,M_,`f`)}get tbs(){return Bc(this,S_,`f`)||Vc(this,S_,this.asn.tbsCertificateRaw||Y.serialize(this.asn.tbsCertificate),`f`),Bc(this,S_,`f`)}constructor(e){let t=Pg.isAsnEncoded(e)?[e,Vu]:[e];super(t[0],t[1]),S_.set(this,void 0),C_.set(this,void 0),w_.set(this,void 0),T_.set(this,void 0),E_.set(this,void 0),D_.set(this,void 0),O_.set(this,void 0),k_.set(this,void 0),A_.set(this,void 0),j_.set(this,void 0),M_.set(this,void 0),N_.set(this,void 0),this.tag=Ng.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=lg.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 Fg)n={...i.algorithm,...this.signatureAlgorithm},r=await i.export(n,[`verify`],t);else if(U.isBufferSource(i)){let e=new Fg(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=im.resolveAll(n_).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??=lg.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=lg.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,Vu),n=t.tbsCertificate,r=new eg(``,{Version:`${zu[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":rg.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new eg(``,{"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 eg(``);for(let t of this.extensions){let n=t.toTextObject();e[n[eg.NAME]]=n}r.Extensions=e}return e.Data=r,e.Signature=new eg(``,{Algorithm:rg.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};S_=new WeakMap,C_=new WeakMap,w_=new WeakMap,T_=new WeakMap,E_=new WeakMap,D_=new WeakMap,O_=new WeakMap,k_=new WeakMap,A_=new WeakMap,j_=new WeakMap,M_=new WeakMap,N_=new WeakMap,P_.NAME=`Certificate`;function F_(e,t=lg.get()){let n=U.toUint8Array(ni.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 I_=class{static async createSelfSigned(e,t=lg.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=lg.get()){let n;n=e.publicKey instanceof Fg?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=F_(e.serialNumber,t),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),o=new Vu({tbsCertificate:new Bu({version:zu.v3,serialNumber:r,validity:new Fu({notBefore:i,notAfter:a}),extensions:new Ru(e.extensions?.map(e=>Y.parse(e.rawData,Lu))||[]),subjectPublicKeyInfo:Y.parse(n,Nu)})});if(e.subject){let t=e.subject instanceof gg?e.subject:new gg(e.subject);o.tbsCertificate.subject=Y.parse(t.toArrayBuffer(),Zc)}if(e.issuer){let t=e.issuer instanceof gg?e.issuer:new gg(e.issuer);o.tbsCertificate.issuer=Y.parse(t.toArrayBuffer(),Zc)}let s={hash:`SHA-256`},c=`signingKey`in e?{...s,...e.signingAlgorithm,...e.signingKey.algorithm}:{...s,...e.signingAlgorithm},l=im.resolve(yh);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=im.resolveAll(n_).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 P_(Y.serialize(o))}},L_;(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`})(L_||={}),Gg.register(yl,Rg),Gg.register(Yl,Bg),Gg.register(cu,Hg),Gg.register(Tu,Ug),Gg.register(gl,Lg),Gg.register(bu,Wg),Gg.register(Ll,qg),Gg.register(pl,Jg),Gg.register(ou,Zg),t_.register(Vm,$g),t_.register(Hm,e_),im.registerSingleton(n_,r_),im.registerSingleton(n_,s_),s_.namedCurveSize.set(`P-256`,32),s_.namedCurveSize.set(`K-256`,32),s_.namedCurveSize.set(`P-384`,48),s_.namedCurveSize.set(`P-521`,66);var R_=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})),z_=R(((e,t)=>{for(var n=te(`util`),r=R_(),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 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[_g.VALUE];a&&(i=` ${a}`),n.push(`${r}${e[_g.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[_g.NAME]=i,n.push(...this.serializeObj(e,t));else if(a instanceof _g)a[_g.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[_g.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)}};bg.oidSerializer=yg,bg.algorithmSerializer=vg;var xg,Sg=class e{get rawData(){return rl(this,xg,`f`)||il(this,xg,Y.serialize(this.asn),`f`),rl(this,xg,`f`)}constructor(...e){xg.set(this,void 0),U.isBufferSource(e[0])?(this.asn=Y.parse(e[0],e[1]),il(this,xg,U.toArrayBuffer(e[0]),`f`),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(t){return t instanceof e&&xi(t.rawData,this.rawData)}toString(e=`text`){switch(e){case`asn`:return Y.toString(this.rawData);case`text`:return bg.serialize(this.toTextObject());case`hex`:return yi.ToHex(this.rawData);case`base64`:return yi.ToBase64(this.rawData);case`base64url`:return yi.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 _g(this.getTextName(),{},e)}};xg=new WeakMap,Sg.NAME=`ASN`;var Cg=class e extends Sg{constructor(...e){let t;t=U.isBufferSource(e[0])?U.toArrayBuffer(e[0]):Y.serialize(new ed({extnID:e[0],critical:e[1],extnValue:new xc(U.toArrayBuffer(e[2]))})),super(t,ed)}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[_g.NAME]===e.NAME&&(t[_g.NAME]=yg.toString(this.type)),t}},wg,Tg=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[wg]=`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}};wg=Symbol.toStringTag,Tg.DEFAULT=`default`;var Eg=new Tg,Dg=/^[0-2](?:\.[1-9][0-9]*)+$/;function Og(e){return new RegExp(Dg).test(e)}var kg=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 Og(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},Ag=new kg;Ag.register(`CN`,`2.5.4.3`),Ag.register(`L`,`2.5.4.7`),Ag.register(`ST`,`2.5.4.8`),Ag.register(`O`,`2.5.4.10`),Ag.register(`OU`,`2.5.4.11`),Ag.register(`C`,`2.5.4.6`),Ag.register(`DC`,`0.9.2342.19200300.100.1.25`),Ag.register(`E`,`1.2.840.113549.1.9.1`),Ag.register(`G`,`2.5.4.42`),Ag.register(`I`,`2.5.4.43`),Ag.register(`SN`,`2.5.4.4`),Ag.register(`T`,`2.5.4.12`);function jg(e,t){return`\\${yi.ToHex(yi.FromUtf8String(t)).toUpperCase()}`}function Mg(e){return e.replace(/([,+"\\<>;])/g,`\\$1`).replace(/^([ #])/,`\\$1`).replace(/([ ]$)/,`\\$1`).replace(/([\r\n\t])/,jg)}var Ng=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 kg,this.asn=new ml;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 ml?e:U.isBufferSource(e)?Y.parse(e,ml):this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||Ag.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)||Ag.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${yi.ToHex(e.value.anyValue)}`:Mg(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?`#${yi.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(n)}return e}fromString(e){let t=new ml,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 fl([s])),i=o}return t}fromJSON(e){let t=new ml;for(let n of e){let e=new fl;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 dl({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=yi.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]||Eg.get()):t=e[0]||Eg.get(),await t.subtle.digest(n,this.toArrayBuffer())}},Pg=`Cannot initialize GeneralName from ASN.1 data.`,Fg=`${Pg} Unsupported string format in use.`,Ig=`${Pg} Value doesn't match to GUID regular expression.`,Lg=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Rg=`1.3.6.1.4.1.311.25.1`,zg=`1.3.6.1.4.1.311.20.2.3`,Bg=`email`,Vg=`guid`,Hg=class extends Sg{constructor(...e){let t;if(e.length===2)switch(e[0]){case`dn`:{let n=new Ng(e[1]).toArrayBuffer(),r=Y.parse(n,ml);t=new vl({directoryName:r});break}case`dns`:t=new vl({dNSName:e[1]});break;case Bg:t=new vl({rfc822Name:e[1]});break;case Vg:{let n=new RegExp(Lg,`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?yi.ToHex(new Uint8Array(yi.FromHex(e)).reverse()):e).join(``);t=new vl({otherName:new gl({typeId:Rg,value:Y.serialize(new xc(yi.FromHex(r)))})});break}case`ip`:t=new vl({iPAddress:e[1]});break;case`id`:t=new vl({registeredID:e[1]});break;case`upn`:t=new vl({otherName:new gl({typeId:zg,value:Y.serialize(Nc.toASN(e[1]))})});break;case`url`:t=new vl({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],vl):e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=`dns`,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Bg,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 Ng(e.directoryName).toString();else if(e.otherName!=null){if(e.otherName.typeId===Rg){this.type=Vg;let t=Y.parse(e.otherName.value,xc),n=new RegExp(Lg,`i`).exec(yi.ToHex(t));if(!n)throw Error(Ig);this.value=n.slice(1).map((e,t)=>t<3?yi.ToHex(new Uint8Array(yi.FromHex(e)).reverse()):e).join(`-`)}else if(e.otherName.typeId===zg)this.type=`upn`,this.value=Y.parse(e.otherName.value,ll).toString();else throw Error(Fg)}else throw Error(Fg)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case`dn`:case`dns`:case Vg:case`ip`:case`id`:case`upn`:case`url`:e=this.type.toUpperCase();break;case Bg:e=`Email`;break;default:throw Error(`Unsupported GeneralName type`)}let t=this.value;return this.type===`id`&&(t=yg.toString(t)),new _g(e,void 0,t)}},Ug=class extends Sg{constructor(e){let t;if(e instanceof zl)t=e;else if(Array.isArray(e)){let n=[];for(let t of e)if(t instanceof vl)n.push(t);else{let e=Y.parse(new Hg(t.type,t.value).rawData,vl);n.push(e)}t=new zl(n)}else if(U.isBufferSource(e))t=Y.parse(e,zl);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 Hg(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[_g.NAME]];Array.isArray(r)||(r=[],e[n[_g.NAME]]=r),r.push(n)}return e}};Ug.NAME=`GeneralNames`;var Wg=`-{5}`,Gg=`\\n`,Kg=`${Wg}BEGIN (${`[^${Gg}]+`}(?=${Wg}))${Wg}`,qg=`${Wg}END \\1${Wg}`,Jg=`\\n`,Yg=`${Kg}${Jg}(?:((?:${`[^:${Gg}]+`}: ${`(?:[^${Gg}]+${Jg}(?: +[^${Gg}]+${Jg})*)`})+))?${Jg}?(${`(?:[a-zA-Z0-9=+/]+${Jg})+`})${qg}`,Xg=class{static isPem(e){return typeof e==`string`&&new RegExp(Yg,`g`).test(e.replace(/\r/g,``))}static decodeWithHeaders(e){e=e.replace(/\r/g,``);let t=new RegExp(Yg,`g`),n=[],r=null;for(;r=t.exec(e);){let e=r[3].replace(RegExp(`[${Gg}]+`,`g`),``),t={type:r[1],headers:[],rawData:yi.FromBase64(e)},i=r[2];if(i){let e=i.split(new RegExp(Jg,`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=yi.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
+ `)}};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(`
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})),B_=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}}})),V_=R(((e,t)=>{var n=z_(),r=B_(),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(`
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})),rv=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}}})),iv=R(((e,t)=>{var n=nv(),r=rv(),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})),H_=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`}}})),U_=R(((e,t)=>{var{Transform:n}=te(`stream`),r=z_(),i=V_(),a=H_(),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(`
79
+ `),i.prototype[e]=t.toFunction()}),t.exports=i})),av=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`}}})),ov=R(((e,t)=>{var{Transform:n}=te(`stream`),r=nv(),i=iv(),a=av(),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})),W_=R(((e,t)=>{t.exports=function(e){return typeof e==`object`&&!!e&&Array.isArray(e)===!1}})),G_=R(((e,t)=>{var n=W_();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)}})),K_=R(((e,t)=>{t.exports={isType:n,isUserType:G_(),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)}})),q_=R(((e,t)=>{t.exports={skip:Symbol(`skip`),bytes:Symbol(`bytes`)}})),J_=R(((e,t)=>{var n=q_();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)}}})),Y_=R(((e,t)=>{var{isType:n,isUserType:r,isDecodeType:i}=K_(),a=U_(),o=q_(),s=J_();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.`)}})),X_=R(((e,t)=>{var{isUserType:n,isEncodeType:r,isType:i}=K_(),a=q_(),o=J_(),s=U_();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.")}})),Z_=R(((e,t)=>{var{isUserType:n,isType:r}=K_(),i=J_(),a=q_();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)}}})),Q_=R(((e,t)=>{var{decodeCommon:n}=Y_(),{encodeCommon:r}=X_(),{encodingLengthCommon:i}=Z_(),{isType:a,isUserType:o,isFunction:s}=K_(),c=J_();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}})),$_=R(((e,t)=>{var{isType:n,isFunction:r}=K_(),i=H_(),a=U_();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.`)}})),ev=R(((e,t)=>{var{isType:n}=K_();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}}})),tv=R(((e,t)=>{var{decodeCommon:n}=Y_(),{encodeCommon:r}=X_(),{encodingLengthCommon:i}=Z_(),{isType:a,isFunction:o}=K_(),s=q_(),c=J_();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)}}})),nv=R(((e,t)=>{var{isType:n}=K_(),r=H_();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}`)}})),rv=R(((e,t)=>{var n=z_();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})),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(`
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()}}})),iv=R(((e,t)=>{var{isType:n,isFunction:r,isUserType:i}=K_(),a=q_(),{decodeCommon:o}=Y_(),{encodeCommon:s}=X_(),{encodingLengthCommon:c}=Z_(),l=J_();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}}})),av=R(((e,t)=>{var n=q_(),{decodeCommon:r}=Y_(),i=J_();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}}})),ov=R(((e,t)=>{var n=z_(),r=H_(),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(`
125
+ `),{encodingLength:()=>e,encode:a.toFunction(),decode:i.toFunction()}}})),xv=R(((e,t)=>{var{isType:n,isFunction:r,isUserType:i}=lv(),a=uv(),{decodeCommon:o}=fv(),{encodeCommon:s}=pv(),{encodingLengthCommon:c}=mv(),l=dv();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}}})),Sv=R(((e,t)=>{var n=uv(),{decodeCommon:r}=fv(),i=dv();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}}})),Cv=R(((e,t)=>{var n=nv(),r=av(),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)}})),sv=R(((e,t)=>{var n=U_(),r=Q_(),i=$_(),a=ev(),o=tv(),s=nv(),c=rv(),l=iv(),u=av(),{encode:d}=X_(),{decode:f}=Y_(),{encodingLength:p}=Z_(),m=ov(),h=H_(),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}})),cv=V(Rr(),1),Q=sv(),lv=T&&typeof T==`object`&&`webcrypto`in T?T.webcrypto:T&&typeof T==`object`&&`randomBytes`in T?T:void 0;function uv(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function dv(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function fv(e,...t){if(!uv(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 pv(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.createHasher`);dv(e.outputLen),dv(e.blockLen)}function mv(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 hv(e,t){fv(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function gv(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _v(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function vv(e,t){return e<<32-t|e>>>t}var yv=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,bv=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function xv(e){if(fv(e),yv)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=bv[e[n]];return t}var Sv={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cv(e){if(e>=Sv._0&&e<=Sv._9)return e-Sv._0;if(e>=Sv.A&&e<=Sv.F)return e-(Sv.A-10);if(e>=Sv.a&&e<=Sv.f)return e-(Sv.a-10)}function wv(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(yv)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=Cv(e.charCodeAt(i)),a=Cv(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 Tv(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function Ev(e){return typeof e==`string`&&(e=Tv(e)),fv(e),e}function Dv(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];fv(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 Ov=class{};function kv(e){let t=t=>e().update(Ev(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Av(e=32){if(lv&&typeof lv.getRandomValues==`function`)return lv.getRandomValues(new Uint8Array(e));if(lv&&typeof lv.randomBytes==`function`)return Uint8Array.from(lv.randomBytes(e));throw Error(`crypto.getRandomValues must be defined`)}var jv=BigInt(0),Mv=BigInt(1);function Nv(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function Pv(e,t,n=``){let r=uv(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 Fv(e){let t=e.toString(16);return t.length&1?`0`+t:t}function Iv(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?jv:BigInt(`0x`+e)}function Lv(e){return Iv(xv(e))}function Rv(e){return fv(e),Iv(xv(Uint8Array.from(e).reverse()))}function zv(e,t){return wv(e.toString(16).padStart(t*2,`0`))}function Bv(e,t){return zv(e,t).reverse()}function Vv(e,t,n){let r;if(typeof t==`string`)try{r=wv(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(uv(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 Hv=e=>typeof e==`bigint`&&jv<=e;function Uv(e,t,n){return Hv(e)&&Hv(t)&&Hv(n)&&t<=e&&e<n}function Wv(e,t,n,r){if(!Uv(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function Gv(e){let t=0;for(;e>jv;e>>=Mv,t+=1);return t}var Kv=e=>(Mv<<BigInt(e))-Mv;function qv(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 Dv(...n)};return(e,t)=>{c(),u(e);let n;for(;!(n=t(d()));)u();return c(),n}}function Jv(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 Yv(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 Xv=BigInt(0),Zv=BigInt(1),Qv=BigInt(2),$v=BigInt(3),ey=BigInt(4),ty=BigInt(5),ny=BigInt(7),ry=BigInt(8),iy=BigInt(9),ay=BigInt(16);function oy(e,t){let n=e%t;return n>=Xv?n:t+n}function sy(e,t){if(e===Xv)throw Error(`invert: expected non-zero number`);if(t<=Xv)throw Error(`invert: expected positive modulus, got `+t);let n=oy(e,t),r=t,i=Xv,a=Zv,o=Zv,s=Xv;for(;n!==Xv;){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!==Zv)throw Error(`invert: does not exist`);return oy(i,t)}function cy(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function ly(e,t){let n=(e.ORDER+Zv)/ey,r=e.pow(t,n);return cy(e,r,t),r}function uy(e,t){let n=(e.ORDER-ty)/ry,r=e.mul(t,Qv),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,Qv),i),s=e.mul(a,e.sub(o,e.ONE));return cy(e,s,t),s}function dy(e){let t=by(e),n=fy(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+ny)/ay;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 cy(e,p,t),p}}function fy(e){if(e<$v)throw Error(`sqrt is not defined for small field`);let t=e-Zv,n=0;for(;t%Qv===Xv;)t/=Qv,n++;let r=Qv,i=by(e);for(;vy(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return ly;let a=i.pow(r,t),o=(t+Zv)/Qv;return function(e,r){if(e.is0(r))return r;if(vy(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=Zv<<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 py(e){return e%ey===$v?ly:e%ry===ty?uy:e%ay===iy?dy(e):fy(e)}var my=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function hy(e){return Jv(e,my.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function gy(e,t,n){if(n<Xv)throw Error(`invalid exponent, negatives unsupported`);if(n===Xv)return e.ONE;if(n===Zv)return t;let r=e.ONE,i=t;for(;n>Xv;)n&Zv&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Zv;return r}function _y(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 vy(e,t){let n=(e.ORDER-Zv)/Qv,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 yy(e,t){t!==void 0&&dv(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function by(e,t,n=!1,r={}){if(e<=Xv)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}=yy(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:Kv(c),ZERO:Xv,ONE:Zv,allowedLengths:s,create:t=>oy(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return Xv<=t&&t<e},is0:e=>e===Xv,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&Zv)===Zv,neg:t=>oy(-t,e),eql:(e,t)=>e===t,sqr:t=>oy(t*t,e),add:(t,n)=>oy(t+n,e),sub:(t,n)=>oy(t-n,e),mul:(t,n)=>oy(t*n,e),pow:(e,t)=>gy(d,e,t),div:(t,n)=>oy(t*sy(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>sy(t,e),sqrt:a||(t=>(u||=py(e),u(d,t))),toBytes:e=>n?Bv(e,l):zv(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?Rv(t):Lv(t);if(o&&(i=oy(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>_y(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function xy(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function Sy(e){let t=xy(e);return t+Math.ceil(t/2)}function Cy(e,t,n=!1){let r=e.length,i=xy(t),a=Sy(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=oy(n?Rv(e):Lv(e),t-Zv)+Zv;return n?Bv(o,i):zv(o,i)}function wy(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 Ty(e,t,n){return e&t^~e&n}function Ey(e,t,n){return e&t^e&n^t&n}var Dy=class extends Ov{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=_v(this.buffer)}update(e){mv(this),e=Ev(e),fv(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=_v(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){mv(this),hv(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,gv(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;wy(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=_v(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()}},Oy=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]),Ay=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),jy=BigInt(2**32-1),My=BigInt(32);function Ny(e,t=!1){return t?{h:Number(e&jy),l:Number(e>>My&jy)}:{h:Number(e>>My&jy)|0,l:Number(e&jy)|0}}function Py(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}=Ny(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var Fy=(e,t,n)=>e>>>n,Iy=(e,t,n)=>e<<32-n|t>>>n,Ly=(e,t,n)=>e>>>n|t<<32-n,Ry=(e,t,n)=>e<<32-n|t>>>n,zy=(e,t,n)=>e<<64-n|t>>>n-32,By=(e,t,n)=>e>>>n-32|t<<64-n;function Vy(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var Hy=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Uy=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Wy=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Gy=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Ky=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),qy=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,Jy=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]),Yy=new Uint32Array(64),Xy=class extends Dy{constructor(e=32){super(64,e,8,!1),this.A=Oy[0]|0,this.B=Oy[1]|0,this.C=Oy[2]|0,this.D=Oy[3]|0,this.E=Oy[4]|0,this.F=Oy[5]|0,this.G=Oy[6]|0,this.H=Oy[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)Yy[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Yy[e-15],n=Yy[e-2],r=vv(t,7)^vv(t,18)^t>>>3,i=vv(n,17)^vv(n,19)^n>>>10;Yy[e]=i+Yy[e-7]+r+Yy[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=vv(o,6)^vv(o,11)^vv(o,25),u=l+t+Ty(o,s,c)+Jy[e]+Yy[e]|0,d=(vv(n,2)^vv(n,13)^vv(n,22))+Ey(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(){gv(Yy)}destroy(){this.set(0,0,0,0,0,0,0,0),gv(this.buffer)}},Zy=Py(`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))),Qy=Zy[0],$y=Zy[1],eb=new Uint32Array(80),tb=new Uint32Array(80),nb=class extends Dy{constructor(e=64){super(128,e,16,!1),this.Ah=Ay[0]|0,this.Al=Ay[1]|0,this.Bh=Ay[2]|0,this.Bl=Ay[3]|0,this.Ch=Ay[4]|0,this.Cl=Ay[5]|0,this.Dh=Ay[6]|0,this.Dl=Ay[7]|0,this.Eh=Ay[8]|0,this.El=Ay[9]|0,this.Fh=Ay[10]|0,this.Fl=Ay[11]|0,this.Gh=Ay[12]|0,this.Gl=Ay[13]|0,this.Hh=Ay[14]|0,this.Hl=Ay[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)eb[n]=e.getUint32(t),tb[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=eb[e-15]|0,n=tb[e-15]|0,r=Ly(t,n,1)^Ly(t,n,8)^Fy(t,n,7),i=Ry(t,n,1)^Ry(t,n,8)^Iy(t,n,7),a=eb[e-2]|0,o=tb[e-2]|0,s=Ly(a,o,19)^zy(a,o,61)^Fy(a,o,6),c=Wy(i,Ry(a,o,19)^By(a,o,61)^Iy(a,o,6),tb[e-7],tb[e-16]),l=Gy(c,r,s,eb[e-7],eb[e-16]);eb[e]=l|0,tb[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=Ly(u,d,14)^Ly(u,d,18)^zy(u,d,41),v=Ry(u,d,14)^Ry(u,d,18)^By(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=Ky(_,v,b,$y[e],tb[e]),S=qy(x,g,t,y,Qy[e],eb[e]),C=x|0,w=Ly(n,r,28)^zy(n,r,34)^zy(n,r,39),T=Ry(n,r,28)^By(n,r,34)^By(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}=Vy(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=Hy(C,T,D);n=Uy(O,S,w,E),r=O|0}({h:n,l:r}=Vy(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=Vy(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=Vy(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=Vy(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Vy(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=Vy(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=Vy(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=Vy(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(){gv(eb,tb)}destroy(){gv(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},rb=class extends nb{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}},ib=kv(()=>new Xy),ab=kv(()=>new nb),ob=kv(()=>new rb),sb=class extends Ov{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,pv(e);let n=Ev(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),gv(i)}update(e){return mv(this),this.iHash.update(e),this}digestInto(e){mv(this),fv(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()}},cb=(e,t,n)=>new sb(e,t).update(n).digest();cb.create=(e,t)=>new sb(e,t);var lb=BigInt(0),ub=BigInt(1);function db(e,t){let n=t.negate();return e?n:t}function fb(e,t){let n=_y(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function pb(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function mb(e,t){pb(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:Kv(e),maxNumber:i,shiftBy:BigInt(e)}}function hb(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+=ub);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 gb(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 _b(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 vb=new WeakMap,yb=new WeakMap;function bb(e){return yb.get(e)||1}function xb(e){if(e!==lb)throw Error(`invalid wNAF`)}var Sb=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>lb;)t&ub&&(n=n.add(r)),r=r.double(),t>>=ub;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=mb(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=mb(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=hb(n,e,a);n=o,c?i=i.add(db(u,t[d])):r=r.add(db(l,t[s]))}return xb(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=mb(e,this.bits);for(let e=0;e<i.windows&&n!==lb;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=hb(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return xb(n),r}getPrecomputes(e,t,n){let r=vb.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),vb.set(t,r))),r}cached(e,t,n){let r=bb(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=bb(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){pb(t,this.bits),yb.set(e,t),vb.delete(e)}hasCache(e){return bb(e)!==1}};function Cb(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>lb||r>lb;)n&ub&&(a=a.add(i)),r&ub&&(o=o.add(i)),i=i.double(),n>>=ub,r>>=ub;return{p1:a,p2:o}}function wb(e,t,n,r){gb(n,e),_b(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=Gv(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=Kv(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 Tb(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return hy(t),t}return by(e,{isLE:n})}function Eb(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>lb))throw Error(`CURVE.${e} must be positive bigint`)}let i=Tb(t.p,n.Fp,r),a=Tb(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 Db=(e,t)=>(e+(e>=0?t:-t)/Pb)/t;function Ob(e,t,n){let[[r,i],[a,o]]=t,s=Db(o*e,n),c=Db(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<Mb,f=u<Mb;d&&(l=-l),f&&(u=-u);let p=Kv(Math.ceil(Gv(n)/2))+Nb;if(l<Mb||l>=p||u<Mb||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 Ab(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return Nv(n.lowS,`lowS`),Nv(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=Fv(r);if(i.length/2&128)throw new n(`tlv.encode: long form length too big`);let a=r>127?Fv(i.length/2|128):``;return Fv(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<Mb)throw new t(`integer: negative integers are not allowed`);let n=Fv(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 Lv(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=jb,i=Vv(`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)}},Mb=BigInt(0),Nb=BigInt(1),Pb=BigInt(2),Fb=BigInt(3),Ib=BigInt(4);function Lb(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=Vv(`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 Rb(e,t={}){let n=Eb(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;Jv(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=Bb(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 Nv(n,`isCompressed`),n?(u(),Dv(zb(!r.isOdd(a)),o)):Dv(Uint8Array.of(4),o,r.toBytes(a))}function f(e){Pv(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,Fb),Ib),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 Ob(e,c.basises,i.ORDER)}let S=Yv((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=Yv(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=db(i,t),n=db(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(Pv(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return T.fromBytes(Vv(`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(Fb),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,Fb),{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,Fb),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=>fb(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 fb(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===Mb||r.is0())return T.ZERO;if(e===Nb)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}=Cb(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===Nb?!0:e?e(T,this):D.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===Nb?this:e?e(T,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Nv(e,`isCompressed`),this.assertValidity(),p(T,this,e)}toHex(e=!0){return xv(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 fb(T,e)}static msm(e,t){return wb(T,i,e,t)}static fromPrivateKey(e){return T.BASE.multiply(Lb(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 Sb(T,t.endo?Math.ceil(E/2):E);return T.BASE.precompute(8),T}function zb(e){return Uint8Array.of(e?2:3)}function Bb(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Vb(e,t={}){let{Fn:n}=e,r=t.randomBytes||Av,i=Object.assign(Bb(e.Fp,n),{seed:Sy(n.ORDER)});function a(e){try{return!!Lb(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 Cy(Pv(e,i.seed,`seed`),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(Lb(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=Vv(`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=Lb(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=>Lb(n,e),precompute(t=8,n=e.BASE){return n.precompute(t,!1)}},lengths:i})}function Hb(e,t,n={}){pv(t),Jv(n,{},{hmac:`function`,lowS:`boolean`,randomBytes:`function`,bits2int:`function`,bits2int_modN:`function`});let r=n.randomBytes||Av,i=n.hmac||((e,...n)=>cb(t,e,Dv(...n))),{Fp:a,Fn:o}=e,{ORDER:s,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p}=Vb(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>>Nb}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 Pv(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(Pv(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(wv(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*Pb<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(Dv(zb(!(c&1)),u)),f=o.inv(l),p=x(Vv(`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 wv(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 Dv(Uint8Array.of(this.recovery),t,n)}return Dv(t,n)}toHex(e){return xv(this.toBytes(e))}assertValidity(){}static fromCompact(e){return y.fromBytes(Vv(`sig`,e),`compact`)}static fromDER(e){return y.fromBytes(Vv(`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 xv(this.toBytes(`der`))}toCompactRawBytes(){return this.toBytes(`compact`)}toCompactHex(){return xv(this.toBytes(`compact`))}}let b=n.bits2int||function(e){if(e.length>8192)throw Error(`input is too large`);let t=Lv(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=Kv(c);function C(e){return Wv(`num < 2^`+c,e,Mb,S),o.toBytes(e)}function w(e,n){return Pv(e,void 0,`message`),n?Pv(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}=Ab(i,m);t=w(t,s);let l=x(t),u=Lb(o,n),d=[C(u),C(l)];if(c!=null&&c!==!1){let e=c===!0?r(p.secretKey):c;d.push(Vv(`extraEntropy`,e))}let f=Dv(...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===Mb)return;let c=o.create(r*o.create(h+s*u));if(c===Mb)return;let l=(i.x===s?0:2)|Number(i.y&Nb),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=Vv(`message`,e);let{seed:a,k2sig:s}=T(e,n,r);return qv(t.outputLen,o.BYTES,i)(a,s)}function D(e){let t,n=typeof e==`string`||uv(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(Vv(`sig`,e),`der`)}catch(e){if(!(e instanceof jb.Err))throw e}if(!t)try{t=y.fromBytes(Vv(`sig`,e),`compact`)}catch{return!1}}return t||!1}function O(t,n,r,i={}){let{lowS:a,prehash:s,format:c}=Ab(i,m);if(r=Vv(`publicKey`,r),n=w(Vv(`message`,n),s),`strict`in i)throw Error(`options.strict was renamed to lowS`);let l=c===void 0?D(t):y.fromBytes(Vv(`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}=Ab(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 Ub(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:by(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 Wb(e){let{CURVE:t,curveOpts:n}=Ub(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 Gb(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,yy(n.Fn.ORDER,n.Fn.BITS))})}function Kb(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=Wb(e);return Gb(e,Hb(Rb(t,n),r,i))}function qb(e,t){let n=t=>Kb({...e,hash:t});return{...n(t),create:n}}var Jb={p:BigInt(`0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff`),n:BigInt(`0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551`),h:BigInt(1),a:BigInt(`0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc`),b:BigInt(`0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b`),Gx:BigInt(`0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296`),Gy:BigInt(`0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5`)},Yb={p:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff`),n:BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973`),h:BigInt(1),a:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc`),b:BigInt(`0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef`),Gx:BigInt(`0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7`),Gy:BigInt(`0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f`)},Xb={p:BigInt(`0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),n:BigInt(`0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409`),h:BigInt(1),a:BigInt(`0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc`),b:BigInt(`0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00`),Gx:BigInt(`0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66`),Gy:BigInt(`0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650`)},Zb=by(Jb.p),Qb=by(Yb.p),$b=by(Xb.p),ex=qb({...Jb,Fp:Zb,lowS:!1},ib);qb({...Yb,Fp:Qb,lowS:!1},ob),qb({...Xb,Fp:$b,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},ab);var tx=ex,nx=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}})),rx=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}})),ix=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}})),ax=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}})),ox=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}})),sx=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)})),cx=R((e=>{var t=te(`buffer`).Buffer,n=nx(),r=rx(),i=ix(),a=ax(),o=ox(),s=sx(),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}})),lx=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)})}})),ux=V(R(((e,t)=>{var n=cx(),r=te(`dgram`),i=lx(),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 dx(){return c(2).readUInt16BE(0)}function fx(){return c(4).readUInt32BE(0)}var px=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}},mx=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 hx(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 gx(e,t){return _x(e)(t)}function _x(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 vx(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 yx=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++)}},bx=3988292384,xx=2197175160;function Sx(e){return typeof e!=`string`}function Cx(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 wx(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 Tx(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 Ex(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 Dx=Cx(bx),Ox=wx(Dx),kx=Cx(xx),Ax=wx(kx);function jx(e,t=0){return Sx(e)?Ex(e,t,Dx,Ox):Tx(e,t,Dx)}function Mx(e,t=0){return Sx(e)?Ex(e,t,kx,Ax):Tx(e,t,kx)}function Nx(e,t){return e+t&255}function Px(e,t){return e+t&65535}function Fx(e,t){return Number(BigInt(e)+BigInt(t)&4294967295n)}function Ix(e){return e&16777215}function Lx(e,t){let n=32768;return e<t&&t-e>n||e>t&&e-t<n}function Rx(e,t){let n=2147483648;return e<t&&t-e>n||e>t&&e-t<n}function zx(e,t){return e===t||Rx(e,t)}var Bx=e=>Number.parseInt(e,10),Vx=(e,t)=>t?t[e]:void 0;async function Hx(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:Vx(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 Ux(e){return e===`IPv4`?4:e===`IPv6`?6:e}var Wx=qr.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}},Gx=class{_disposer=[];push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e()),this._disposer=[]}},Kx=Wx(`werift-ice:packages/ice/src/transport.ts`),qx=class e{constructor(e,t={}){this.socketType=e,this.options=t,this.socket=f(e),this.socket.on(`message`,(e,t)=>{Ux(t.family)===6&&([t.address]=t.address.split(`%`)),this.rinfo=t;try{this.onData(e,[t.address,t.port])}catch(e){Kx(`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=Vx(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 Hx(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?(Kx(`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()}})},Jx=class e{type=`tcp`;stream;constructor(e){this.stream=new Xx(`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()}},Yx=class e{type=`tls`;stream;constructor(e,t={}){this.stream=new Xx(`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()}},Xx=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=>{Kx(`${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()}},Zx={rsa_1:1,ecdsa_3:3},Qx={sha256_4:4},$x={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},eS=Object.values($x),tS={x25519_29:29,secp256r1_23:23},nS=Object.values(tS),rS={named_curve_3:3},iS={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},aS=[1,64],oS=[{hash:Qx.sha256_4,signature:Zx.rsa_1},{hash:Qx.sha256_4,signature:Zx.ecdsa_3}],sS=()=>{let e=tx.utils.randomPrivateKey(),t=tx.getPublicKey(e,!1);return{privateKey:Buffer.from(e),publicKey:Buffer.from(t)}},cS=({publicKey:e,privateKey:t})=>{let n=tx.getSharedSecret(t,e);return Buffer.from(n).subarray(1)};function lS(e,t,n){switch(n){case tS.secp256r1_23:return cS({publicKey:e,privateKey:t});case tS.x25519_29:return Buffer.from(cv.default.scalarMult(t,e));default:throw Error()}}function uS(e,t,n){let r=o(e,t);return r.update(n),r.digest()}function dS(e,t,n,r=`sha256`){let i=n,a=[],o=t;do{o=uS(r,e,o);let i=uS(r,e,Buffer.concat([o,t]));a.push(i),n-=i.length}while(n>0);return Buffer.concat(a,i)}function fS(e,t,n){return dS(e,Buffer.concat([Buffer.from(`master secret`),t,n]),48)}function pS(e,t){let n=hS(`sha256`,t);return dS(e,Buffer.concat([Buffer.from(`extended master secret`),n]),48)}function mS(e,t,n,r,i,a){let o=a?r:i,s=a?i:r;return dS(n,Buffer.concat([Buffer.from(e),o,s]),t)}function hS(e,t){return a(e).update(t).digest()}function gS(e,t,n,r=12){let i=hS(`sha256`,t);return dS(e,Buffer.concat([Buffer.from(n),i]),r)}function _S(e,t){return gS(e,t,`client finished`)}function vS(e,t){return gS(e,t,`server finished`)}function yS(e,t,n,r,i,a,o=`sha256`){let s=r*2+i*2,c=e,l=Buffer.concat([n,t]),u=dS(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 bS={CLIENT:1,SERVER:2},xS=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}},SS=d;lg.set(SS);var CS=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 Zx.rsa_1:return`RSASSA-PKCS1-v1_5`;case Zx.ecdsa_3:return`ECDSA`}})(),r=(()=>{switch(e.hash){case Qx.sha256_4:return`SHA-256`}})(),i=(()=>{switch(t){case tS.secp256r1_23:return`P-256`;case tS.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 SS.subtle.generateKey(a,!0,[`sign`,`verify`]);return{certPem:(await I_.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:Ng.encode(await SS.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===bS.CLIENT?_S(this.masterSecret,e):vS(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===bS.CLIENT?this.localRandom:this.remoteRandom,n=this.sessionType===bS.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=Jr.Certificate.fromPEM(Buffer.from(e)),i=Jr.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:rS.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])}},wS=class{srtpProfile;static findMatchingSRTPProfile(e,t){for(let n of t)if(e.includes(n))return n}},TS=e=>`0x`+e.toString(`hex`).replace(/(.)(.)/g,`$1$2 `).split(` `).filter(e=>e!=null&&e.length>0).join(`,0x`),ES=e=>Object.entries({...e}).reduce((e,[t,n])=>((typeof n==`number`||typeof n==`string`)&&(e[t]=n),Buffer.isBuffer(n)&&(e[t]=TS(n)),e),{}),DS=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 ES(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:OS,uint24be:kS,buffer:AS,array:jS,uint8:MS,string:NS}=Q.types,PS=jS({type:OS,data:AS(OS)},OS,`bytes`),FS=AS(kS),IS=MS,LS=NS(OS),RS={hash:MS,signature:MS},zS={major:MS,minor:MS},BS=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)}},VS=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:BS.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:PS};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 DS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},HS=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:zS,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)}},US=class e{constructor(e,t){this.recordLayerHeader=e,this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:TS(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 HS(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},WS=e=>t=>(e.lastFlight=t,t.flatMap(t=>(t.messageSeq=e.sequenceNumber++,t.toFragment().chunk()))),GS=e=>(t,n)=>t.map(t=>new US({contentType:t.type,protocolVersion:e.version,epoch:e.epoch,sequenceNumber:n,contentLen:t.fragment.length},t.fragment)),KS=(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))(KS||{}),qS=Wx(`werift-dtls : packages/dtls/src/flight/flight.ts : warn`),JS=Wx(`werift-dtls : packages/dtls/src/flight/flight.ts : err`),YS=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=WS(this.dtls)(e);return this.dtls.bufferHandshakeCache(t,!0,this.flight),GS(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=>{JS(`fail to send`,JS)}),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}qS(this.dtls.sessionId,`retransmit`,n,this.dtls.flight)}if(n>e.RetransmitCount)throw JS(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}},XS=class extends YS{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 VS({major:254,minor:253},new BS,Buffer.from([]),Buffer.from([]),eS,[0],e);this.dtls.version=t.clientVersion,this.cipher.localRandom=BS.from(t.random);let n=this.createPacket([t]),r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}},ZS=Wx(`werift-dtls : packages/dtls/src/flight/client/flight3.ts : log`),QS=class extends YS{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;ZS(`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])}},$S={NULL:0,ECDHE:1},eC={NULL:0,RSA:1,ECDSA:2,PSK:3},tC={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},nC=class{id=0;name;signType;keyType;toString(){return this.name}};function rC(){let e=new nC;return e.id=tC.RSA,e.name=`RSA`,e.keyType=eC.RSA,e}function iC(){let e=new nC;return e.id=tC.ECDHE_RSA,e.name=`ECDHE_RSA`,e.signType=$S.ECDHE,e.keyType=eC.RSA,e}function aC(){let e=new nC;return e.id=tC.ECDHE_ECDSA,e.name=`ECDHE_ECDSA`,e.signType=$S.ECDHE,e.keyType=eC.ECDSA,e}function oC(){let e=new nC;return e.id=tC.PSK,e.name=`PSK`,e.signType=$S.NULL,e.keyType=eC.PSK,e}function sC(){let e=new nC;return e.id=tC.ECDHE_PSK,e.name=`ECDHE_PSK`,e.signType=$S.ECDHE,e.keyType=eC.PSK,e}var cC=Wx(`werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err`),lC=class extends xS{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return ES(this)}init(e,t,n){let r=yS(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===bS.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===bS.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 cC(`decrypt failed`,r,e,TS(t),n,this.summary),r}}},uC={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},dC={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},fC={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},pC=rC(),mC=iC(),hC=aC(),gC=oC(),_C=sC();function vC(e){switch(e){case uC.TLS_RSA_WITH_AES_128_GCM_SHA256:return yC(uC.TLS_RSA_WITH_AES_128_GCM_SHA256,`TLS_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,pC,dC);case uC.TLS_RSA_WITH_AES_256_GCM_SHA384:return yC(uC.TLS_RSA_WITH_AES_256_GCM_SHA384,`TLS_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,pC,fC,`sha384`);case uC.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return yC(uC.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,mC,dC);case uC.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return yC(uC.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,mC,fC,`sha384`);case uC.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return yC(uC.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,hC,dC);case uC.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return yC(uC.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,hC,fC,`sha384`);case uC.TLS_PSK_WITH_AES_128_GCM_SHA256:return yC(uC.TLS_PSK_WITH_AES_128_GCM_SHA256,`TLS_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,gC,dC,`sha256`);case uC.TLS_PSK_WITH_AES_256_GCM_SHA384:return yC(uC.TLS_PSK_WITH_AES_256_GCM_SHA384,`TLS_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,gC,fC,`sha384`);case uC.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return yC(uC.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,_C,dC,`sha256`);case uC.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return yC(uC.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,_C,fC,`sha384`)}return null}function yC(e,t,n,r,i,a=`sha256`){let o=new lC;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 bC(e){switch(e){case tS.secp256r1_23:{let{privateKey:t,publicKey:n}=sS();return{curve:e,privateKey:t,publicKey:n}}case tS.x25519_29:{let t=cv.default.box.keyPair();return{curve:e,privateKey:Buffer.from(t.secretKey.buffer),publicKey:Buffer.from(t.publicKey.buffer)}}default:throw Error()}}var xC=class{static type=23},SC=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)}}},CC=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)}}},wC=class e{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:Q.types.array(FS,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 DS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},TC=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)}},EC=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 DS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},DC=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 DS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},OC=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 DS(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(IS,Q.types.uint8,`bytes`),signatures:Q.types.array(RS,Q.types.uint16be,`bytes`),authorities:Q.types.array(LS,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 DS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},AC=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:zS,random:BS.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:PS}))):r}serialize(){let t=this.extensions===void 0?(0,Q.encode)(this,e.spec).slice():(0,Q.encode)(this,{...e.spec,extensions:PS}).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new DS(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 DS(this.msgType,e.length,this.messageSeq,0,e.length,e)}};function MC(e,t){return Buffer.from((0,Q.encode)(e,t).slice())}var NC=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 MC(this,e.spec)}toFragment(){let e=this.serialize();return new DS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},PC=e=>{switch(e){case 1:case 7:return 16}},FC=e=>{switch(e){case 1:return 14;case 7:return 12}};Wx(`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 IC(e,t){let n=Buffer.alloc(t);return e.copy(n),n}function LC(e){return Number.parseInt(e.toString(),10)}function RC(e){let t=e[0];return t>127&&t<192}var zC=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 px(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),gx([1,1,2],[e.value,this.type,this.length])}static deSerialize(t){let[n,r,i]=vx(t,[1,1,2]),a=hx(n,0,2),o=hx(n,2,1)>0,s=hx(n,3,5);return new e({version:a,padding:o,count:s,type:r,length:i})}},BC=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]=vx(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=gx([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])}},VC=class e{static count=1;count=e.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(t){let[n,r]=vx(t,[4,4]);return new e({senderSsrc:n,mediaSsrc:r})}serialize(){return gx([4,4],[this.senderSsrc,this.mediaSsrc])}},HC=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]=vx(t,[4,4,4,1,1]),s=hx(o,0,6),c=(hx(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:gx([4],[i]).toString(),ssrcNum:a,brExp:s,brMantissa:c,ssrcFeedbacks:u,bitrate:l})}serialize(){let e=Buffer.concat([gx([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),gx([1],[this.ssrcNum])]),t=new px(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);let n=Buffer.concat(this.ssrcFeedbacks.map(e=>gx([4],[e]))),r=Buffer.concat([e,gx([3],[t.value]),n]);return this.length=r.length/4,r}},UC=Wx(`werift-rtp: /rtcp/psfb/index`),WC=class e{static type=206;type=e.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return zC.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(t,n){let r;switch(n.count){case BC.count:r=BC.deSerialize(t);break;case VC.count:r=VC.deSerialize(t);break;case HC.count:r=HC.deSerialize(t);break;default:UC(`unknown psfb packet`,n.count)}return new e({feedback:r})}},GC=class e{ssrc=0;reports=[];static type=201;type=e.type;constructor(e={}){Object.assign(this,e)}serialize(){let t=gx([4],[this.ssrc]);return t=Buffer.concat([t,...this.reports.map(e=>e.serialize())]),zC.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let[r]=vx(t,[4]),i=4,a=[];for(let e=0;e<n;e++)a.push(KC.deSerialize(t.slice(i,i+24))),i+=24;return new e({ssrc:r,reports:a})}},KC=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 gx([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]=vx(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})}},qC=205,JC=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 zC({type:qC,count:this.count,version:2})}static deSerialize(t,n){let[r,i]=vx(t,[4,4]),a=[];for(let e=8;e<t.length;e+=4){let[n,r]=vx(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=gx([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(gx([2,2],[e,n])),e=r,n=0)}),t.push(gx([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])}},YC=Wx(`werift/rtp/rtcp/rtpfb/twcc`),XC=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 zC({type:205,count:this.count,version:2})}static deSerialize(t,n){let[r,i,a,o,s,c]=vx(t,[4,4,2,2,3,1]),l=[],u=[],d=16;for(let e=0;e<o;){let n=hx(t.slice(d,d+1)[0],0,1),r;switch(n){case 0:{let n=ZC.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 $C({type:n.packetStatus}));e+=i}break;case 1:{let n=QC.deSerialize(t.slice(d,d+2));r=n,n.symbolSize===0&&n.symbolList.forEach(e=>{e===1&&u.push(new $C({type:1}))}),n.symbolSize===1&&n.symbolList.forEach(e=>{(e===1||e===2)&&u.push(new $C({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=gx([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){YC(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 ZC).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}},ZC=class e{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(t){let n=hx(t[0],1,2),r=(hx(t[0],3,5)<<8)+t[1];return new e({type:0,packetStatus:n,runLength:r})}serialize(){return new mx(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 ew({sequenceNumber:++e,received:t}));return n}},QC=class e{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=hx(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(hx(t[0],2+e,1))),i(8,e=>r.push(hx(t[1],e,1)));break;case 1:i(3,e=>r.push(hx(t[0],2+e*2,2))),i(4,e=>r.push(hx(t[1],e*2,2)));break;default:n=(hx(t[0],2,6)<<8)+t[1]}return new e({type:1,symbolSize:n,symbolList:r})}serialize(){let e=Buffer.alloc(2),t=new mx(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}},$C=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)}},ew=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(e){Object.assign(this,e)}},tw=Wx(`werift-rtp:packages/rtp/rtcp/rtpfb/index`),nw=class e{static type=qC;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 JC.count:r=JC.deSerialize(t,n);break;case XC.count:r=XC.deSerialize(t,n);break;default:tw(`unknown rtpfb packet`,n.count)}return new e({feedback:r,header:n})}},rw=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 zC.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=iw.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({chunks:r})}},iw=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+=ow(e),e}serialize(){let e=Buffer.concat([gx([4],[this.source]),Buffer.concat(this.items.map(e=>e.serialize()))]);return Buffer.concat([e,Buffer.alloc(ow(e.length))])}static deSerialize(t){let n=t.readUInt32BE(),r=[];for(let e=4;e<t.length&&t[e]!==0;){let n=aw.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({source:n,items:r})}},aw=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([gx([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 ow(e){return e%4==0?0:4-e%4}var sw=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())]),zC.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let r=t.readUInt32BE(),i=cw.deSerialize(t.subarray(4,24)),a=24,o=[];for(let e=0;e<n;e++)o.push(KC.deSerialize(t.subarray(a,a+24))),a+=24;return new e({ssrc:r,senderInfo:i,reports:o})}},cw=class e{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:lw(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return gx([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(t){let[n,r,i,a]=vx(t,[8,4,4,4]);return new e({ntpTimestamp:n,rtpTimestamp:r,packetCount:i,octetCount:a})}},lw=e=>{let[t,n]=vx(gx([8],[e]),[4,4]);return Number(`${t}.${n}`)},uw=Wx(`werift-rtp:packages/rtp/src/rtcp/rtcp.ts`),dw=class{static deSerialize(e){let t=0,n=[];for(;t<e.length;){let r=zC.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 sw.type:n.push(sw.deSerialize(i,r.count));break;case GC.type:n.push(GC.deSerialize(i,r.count));break;case rw.type:n.push(rw.deSerialize(i,r));break;case nw.type:n.push(nw.deSerialize(i,r));break;case WC.type:n.push(WC.deSerialize(i,r))}}catch(e){uw(`deSerialize RTCP`,e)}}return n}};function fw(e){return e.length>=2&&e[1]>=192&&e[1]<=208}var pw={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 mw(e,t){return e.map(e=>{let n=t[e.id];if(!n)return{uri:`unknown`,value:e.payload};switch(n){case pw.sdesMid:case pw.sdesRTPStreamID:case pw.repairedRtpStreamId:return{uri:n,value:bw(e.payload)};case pw.transportWideCC:return{uri:n,value:xw(e.payload)};case pw.absSendTime:return{uri:n,value:Sw(e.payload)};case pw.audioLevelIndication:return{uri:n,value:Cw(e.payload)};case pw.videoOrientation:return{uri:n,value:ww(e.payload)};default:return{uri:n,value:e.payload}}}).reduce((e,t)=>(t&&(e[t.uri]=t.value),e),{})}function hw(e){return Buffer.from(e)}function gw(e){return Buffer.from(e)}function _w(e){return Buffer.from(e)}function vw(e){return gx([2],[e])}function yw(e){let t=Buffer.alloc(3),n=e>>14n&16777215n;return t.writeUIntBE(Number(n),0,3),t}function bw(e){return e.toString()}function xw(e){return e.readUInt16BE()}function Sw(e){return vx(e,[3])[0]}function Cw(e){let t=new yx(e);return{v:t.readBits(1)===1,level:t.readBits(7)}}function ww(e){let t=new yx(e);return t.readBits(4),{c:t.readBits(1),f:t.readBits(1),r1:t.readBits(1),r0:t.readBits(1)}}var Tw=Wx(`packages/rtp/src/rtp/red/packet.ts`),Ew=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]=Dw.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 Dw;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}},Dw=class e{fields=[];static deSerialize(t){let n=0,r=new e;for(;;){let e={};r.fields.push(e);let i=new yx(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 yx(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 yx(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,n.uint8Array])}}catch(e){Tw(e?.message)}return e}},Ow=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 Ew,t=this.cache.slice(-(this.distance+1)),n=t.pop();return n?(t.forEach(t=>{let r=Fx(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,Aw=class{size=150;sequenceNumbers=[];push(e,t){let n=[];return e.blocks.forEach(({blockPT:r,timestampOffset:i,block:a},o)=>{let s=Px(t.header.sequenceNumber,-(e.blocks.length-(o+1)));i?n.push(new Rw(new Lw({timestamp:Fx(t.header.timestamp,-i),payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:!0}),a)):n.push(new Rw(new Lw({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},Mw=2,Nw=4,Pw=8,Fw=12,Iw=4,Lw=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=hx(i,0,2),n.padding=hx(i,2)>0,n.extension=hx(i,3)>0,n.csrcLength=hx(i,4,4),n.csrc=[...Array(n.csrcLength)].map(()=>{let e=t.readUInt32BE(r);return r+=4,e}),r+=Fw-1;let a=t[1];n.marker=hx(a,0)>0,n.payloadType=hx(a,1,7),n.sequenceNumber=t.readUInt16BE(Mw),n.timestamp=t.readUInt32BE(Nw),n.ssrc=t.readUInt32BE(Pw);for(let e=0;e<n.csrc.length;e++){let r=Fw+e*Iw;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*Iw;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 px(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 px(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),t.writeUInt8(i.value,n++),t.writeUInt16BE(this.sequenceNumber,Mw),n+=2,t.writeUInt32BE(this.timestamp,Nw),n+=4,t.writeUInt32BE(this.ssrc,Pw),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}},Rw=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 Lw({...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=Lw.deSerialize(t);return new e(n,t.subarray(n.payloadOffset,t.length-n.paddingSize))}clear(){this.payload=null}};function zw(e,t,n){return new Rw(new Lw({payloadType:t,marker:e.header.marker,sequenceNumber:e.payload.readUInt16BE(0),timestamp:e.header.timestamp,ssrc:n}),e.payload.subarray(2))}function Bw(e,t,n,r){let i=Buffer.allocUnsafe(2);return i.writeUInt16BE(e.header.sequenceNumber,0),new Rw(new Lw({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 Vw=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[]}},Hw=class extends Error{constructor(e){super(e),this.name=`SrtpAuthenticationError`}},Uw=12,Ww=8;function Gw(e,t,n=`Failed to authenticate SRTP packet`){let r=e.length-t;qw(e.length>=Uw+t,n);let i=Jw(()=>Lw.deSerialize(e.subarray(0,r)),n);return i.paddingSize=0,qw(i.payloadOffset>=Uw&&i.payloadOffset<=r,n),i}function Kw(e,t,n,r=`Failed to authenticate SRTCP packet`){return qw(e.length>=Ww+t+n,r),Jw(()=>zC.deSerialize(e.subarray(0,4)),r)}function qw(e,t){if(!e)throw new Hw(t)}function Jw(e,t){try{return e()}catch{throw new Hw(t)}}function Yw(e,t,n=`Failed to authenticate SRTP packet`){if(!e.padding)return e.paddingSize=0,e;qw(t.length>e.payloadOffset,n);let r=t[t.length-1];return qw(r>0&&r<=t.length-e.payloadOffset,n),e.paddingSize=r,e}var Xw=class extends Vw{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=Gw(e,this.authTagLength)){let r=e.length-this.authTagLength,a=e.subarray(0,r);Qw(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,Yw(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=Kw(e,this.authTagLength,Zw),n=e.length-(this.authTagLength+Zw),r=e.subarray(0,e.length-this.authTagLength);Qw(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)}},Zw=4;function Qw(e,t,n){if(e.length!==t.length||!u(e,t))throw new Hw(n)}var $w=class extends Vw{aeadAuthTagLen=16;rtpIvWriter=_x([2,4,4,2],!0);rtcpIvWriter=_x([2,4,2,4],!0);aadWriter=_x([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=Gw(e,this.aeadAuthTagLen)){let r=e.subarray(0,n.payloadOffset),a=e.length-this.aeadAuthTagLen,o=e.subarray(a),s=Buffer.from([]);s=IC(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 nT(u,`SRTP`),d.copy(s,n.payloadOffset),[s,Yw(n,s,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){let n=e.readUInt32BE(4),i=e.length+this.aeadAuthTagLen,a=Buffer.from([]);a=IC(a,i+eT),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=Kw(e,this.aeadAuthTagLen,eT),n=e.length-eT,r=n-this.aeadAuthTagLen,a=e.readUInt32BE(4),o=e.readUInt32BE(n),s=o>>>31==1,c=o&~(tT<<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 nT(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]|=tT,n}},eT=4,tT=128;function nT(e,t){try{e.final()}catch{throw new Hw(`Failed to authenticate ${t} packet`)}}function rT(e,t){let n=r(`aes-128-ecb`,e,null);return n.setAutoPadding(!1),Buffer.concat([n.update(t),n.final()])}var iT=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 Xw(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case 7:this.cipher=new $w(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])]),rT(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=rT(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=rT(this.masterKey,r),i=rT(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>aT&&t.rolloverCounter++:t.lastSequenceNumber<aT&&e>oT-aT?t.rolloverCounter>0&&t.rolloverCounter--:e<aT&&t.lastSequenceNumber>oT-aT&&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}},aT=100,oT=65535,sT=class extends iT{constructor(e,t,n){super(e,t,n)}encryptRTCP(e){let t=e.readUInt32BE(4),n=this.getSrtcpSsrcState(t);return n.srtcpIndex++,n.srtcpIndex>>cT&&(n.srtcpIndex=0),this.cipher.encryptRTCP(e,n.srtcpIndex)}decryptRTCP(e){return this.cipher.decryptRTCP(e)}},cT=2147483647,lT=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)}},uT=class extends lT{constructor(e){super(sT),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)}},dT=class extends iT{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=Gw(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}},fT=class extends lT{constructor(e){super(dT),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)}},pT=Wx(`werift-dtls : packages/dtls/src/flight/client/flight5.ts : log`),mT=class extends YS{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 AC.deSerialize(e.fragment);case 11:return wC.deSerialize(e.fragment);case 12:return NC.deSerialize(e.fragment);case 13:return kC.deSerialize(e.fragment);case 14:return jC.deSerialize(e.fragment)}})();t&&hT[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}async exec(){if(this.dtls.flight===5){pT(this.dtls.sessionId,`flight5 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let e=this.dtls.requestedCertificateTypes.length>0;pT(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 wC([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 DC(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=lS(i.publicKey,r.privateKey,r.curve);pT(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?pS(a,o):fS(a,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=vC(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),pT(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 Zx.ecdsa_3:return iS.ecdsa_secp256r1_sha256;case Zx.rsa_1:return iS.rsa_pkcs1_sha256}})();if(!n)throw Error();pT(this.dtls.sessionId,`signatureScheme`,this.cipher.signatureHashAlgorithm?.signature,n);let r=new EC(n,t),i=this.createPacket([r]);return Buffer.concat(i.map(e=>e.serialize()))}sendChangeCipherSpec(){let e=TC.createEmpty().serialize(),t=GS(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 OC(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 pT(this.dtls.sessionId,`finished`,this.cipher.cipher.summary),r}},hT={};hT[2]=({cipher:e,srtp:t,dtls:n})=>r=>{pT(n.sessionId,`serverHello`,r.cipherSuite),e.remoteRandom=BS.from(r.random),e.cipherSuite=r.cipherSuite,pT(n.sessionId,`selected cipherSuite`,e.cipherSuite),r.extensions&&r.extensions.forEach(e=>{switch(e.type){case CC.type:{let r=CC.fromData(e.data),i=wS.findMatchingSRTPProfile(r.profiles,n.options.srtpProfiles||[]);if(pT(n.sessionId,`selected srtp profile`,i),i==null)return;t.srtpProfile=i}break;case xC.type:n.remoteExtendedMasterSecret=!0;break;case SC.type:pT(n.sessionId,`RenegotiationIndication`)}})},hT[11]=({cipher:e,dtls:t})=>n=>{pT(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},hT[12]=({cipher:e,dtls:t})=>n=>{if(!e.localRandom||!e.remoteRandom)throw Error();pT(t.sessionId,`ServerKeyExchange`,n),pT(t.sessionId,`selected curve`,n.namedCurve),e.remoteKeyPair={curve:n.namedCurve,publicKey:n.publicKey},e.localKeyPair=bC(n.namedCurve)},hT[13]=({dtls:e})=>t=>{pT(e.sessionId,`certificate_request`,t),e.requestedCertificateTypes=t.certificateTypes,e.requestedSignatureAlgorithms=t.signatures},hT[14]=({dtls:e})=>t=>{pT(e.sessionId,`server_hello_done`,t)};var gT=class e{constructor(e,t){this.serverVersion=e,this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:zS,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 DS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},_T=Wx(`werift-dtls : packages/dtls/src/context/dtls.ts : log`),vT=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||(_T(this.sessionId,`exist`,r.summary,t,n),!1)});this.handshakeCache[n].data=[...this.handshakeCache[n].data,...r]}},yT=class{constructor(e){this.socket=e}send=(e,t)=>this.socket.send(e,t)},bT=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)}}},xT=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)}}},ST=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)}},CT=Wx(`werift-dtls : packages/dtls/record/receive.ts : log`),wT=Wx(`werift-dtls : packages/dtls/record/receive.ts : err`),TT=e=>{let t=0,n=[];for(;e.length>t;){let r=e.readUInt16BE(t+11);if(e.length<t+(12+r))break;let i=US.deSerialize(e.subarray(t));n.push(i),t+=13+r}return n},ET=(e,t)=>n=>{switch(n.recordLayerHeader.contentType){case 20:return CT(e.sessionId,`change cipher spec`),[{type:20,data:void 0}];case 22:{let r=n.fragment;try{n.recordLayerHeader.epoch>0&&(CT(e.sessionId,`decrypt handshake`),r=t.decryptPacket(n))}catch(t){throw wT(e.sessionId,`decrypt failed`,t),t}try{let e=0,t=[];for(;r.length>e;){let n=DS.deSerialize(r.subarray(e));t.push({type:22,data:n}),e+=n.fragment_length+12}return t}catch(t){throw wT(e.sessionId,`decSerialize failed`,t,r),t}}case 23:return[{type:23,data:t.decryptPacket(n)}];case 21:{let r=ST.deSerialize(n.fragment);if(KS[r.description]==null){let e=t.decryptPacket(n);r=ST.deSerialize(e)}if(wT(e.sessionId,`ContentType.alert`,r,KS[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}]}},DT=Wx(`werift-dtls : packages/dtls/src/socket.ts : log`),OT=Wx(`werift-dtls : packages/dtls/src/socket.ts : err`),kT=class{constructor(e,t){this.options=e,this.sessionType=t,this.dtls=new vT(this.options,this.sessionType),this.cipher=new CS(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new yT(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new $;onData=new $;onError=new $;onClose=new $;transport;cipher;dtls;srtp=new wS;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){DT(`renegotiation`,this.sessionType),this.connected=!1,this.cipher=new CS(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new vT(this.options,this.sessionType),this.srtp=new wS,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=e=>{let t=TT(e);for(let e of t)try{let t=ET(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=>DS.assemble(e)).sort((e,t)=>e.msg_type-t.msg_type);this.onHandleHandshakes(r).catch(e=>{OT(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){OT(this.dtls.sessionId,`catch udpOnMessage error`,e)}};setupExtensions(){if(DT(this.dtls.sessionId,`support srtpProfiles`,this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let e=CC.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{let e=bT.createEmpty();e.data=nS,this.extensions.push(e.extension)}{let e=xT.createEmpty();e.data=oS,this.extensions.push(e.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:xC.type,data:Buffer.alloc(0)});{let e=SC.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=GS(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===bS.CLIENT?{localKey:r,localSalt:a,remoteKey:i,remoteSalt:o}:{localKey:i,localSalt:o,remoteKey:r,remoteSalt:a}}exportKeyingMaterial(e,t){return mS(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===bS.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},AT=Wx(`werift-dtls : packages/dtls/src/client.ts : log`),jT=class extends kT{constructor(e){super(e,bS.CLIENT),this.onHandleHandshakes=this.handleHandshakes,AT(this.dtls.sessionId,`start client`)}async connect(){await new XS(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async e=>{AT(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(let t of e)switch(t.msg_type){case 3:{let e=gT.deSerialize(t.fragment);await new QS(this.transport,this.dtls).exec(e)}break;case 2:if(this.connected)return;this.flight5=new mT(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(),AT(this.dtls.sessionId,`dtls connected`)}}},MT=Wx(`werift-dtls : packages/dtls/flight/server/flight2.ts : log`),NT=(e,t,n,r)=>i=>{MT(`dtls version`,i.clientVersion),t.flight=2,t.recordSequenceNumber=0,t.sequenceNumber=0,i.extensions.forEach(e=>{switch(e.type){case bT.type:{let r=bT.fromData(e.data).data;MT(t.sessionId,`curves`,r),n.namedCurve=r.filter(e=>nS.includes(e))[0],MT(t.sessionId,`curve selected`,n.namedCurve)}break;case xT.type:{if(!n.signatureHashAlgorithm)throw Error(`need to set certificate`);let r=xT.fromData(e.data).data;MT(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 CC.type:{if(!t.options?.srtpProfiles||t.options.srtpProfiles.length===0)return;let n=CC.fromData(e.data);MT(t.sessionId,`srtp profiles`,n.profiles);let i=wS.findMatchingSRTPProfile(n.profiles,t.options?.srtpProfiles);if(!i)throw Error();r.srtpProfile=i,MT(t.sessionId,`srtp profile selected`,r.srtpProfile)}break;case xC.type:t.remoteExtendedMasterSecret=!0;break;case SC.type:MT(t.sessionId,`RenegotiationIndication`,e.data);break;case 43:MT(`dtls supported version`,[...e.data.subarray(1)].map(e=>e.toString(10)))}}),n.localRandom=new BS,n.remoteRandom=BS.from(i.random);let a=i.cipherSuites;MT(t.sessionId,`cipher suites`,a);let o=(()=>{switch(n.signatureHashAlgorithm?.signature){case Zx.ecdsa_3:return $x.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case Zx.rsa_1:return $x.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,MT(t.sessionId,`selected cipherSuite`,n.cipherSuite),n.localKeyPair=bC(n.namedCurve),t.cookie||=c(20);let s=new gT({major:254,minor:253},t.cookie),l=WS(t)([s]),u=GS(t)(l.map(e=>({type:22,fragment:e.serialize()})),++t.recordSequenceNumber).map(e=>e.serialize());for(let t of u)e.send(t)},PT=Wx(`werift-dtls : packages/dtls/flight/server/flight4.ts : log`),FT=class extends YS{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){PT(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(CC.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&e.push({type:xC.type,data:Buffer.alloc(0)});let t=SC.createEmpty();e.push(t.extension);let n=new AC(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 wC([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 NC(rS.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(aS,oS,[]);PT(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()))}},IT=Wx(`werift-dtls : packages/dtls/flight/server/flight6.ts`),LT=class extends YS{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 wC.deSerialize(e.fragment);case 15:return EC.deSerialize(e.fragment);case 16:return DC.deSerialize(e.fragment);case 20:return OC.deSerialize(e.fragment)}})();if(t){let e=RT[t.msgType];if(!e)return;e({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){IT(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=TC.createEmpty().serialize(),t=GS(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 OC(this.cipher.verifyData(e));this.dtls.epoch=1;let[n]=this.createPacket([t]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(n).serialize()}},RT={};RT[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=lS(e.remoteKeyPair.publicKey,e.localKeyPair.privateKey,e.localKeyPair.curve);IT(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?pS(r,i):fS(r,e.remoteRandom.serialize(),e.localRandom.serialize()),e.cipher=vC(e.cipherSuite),e.cipher.init(e.masterSecret,e.localRandom.serialize(),e.remoteRandom.serialize()),IT(t.sessionId,`setup cipher`,e.cipher.summary)},RT[11]=({cipher:e,dtls:t})=>n=>{IT(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},RT[15]=({cipher:e,dtls:t})=>n=>{if(!e.remoteCertificate)throw Error(`client certificate missing before certificate verify`);IT(t.sessionId,`certificate_verify`,n.algorithm)},RT[20]=({dtls:e})=>t=>{IT(e.sessionId,`finished`,t)};var zT=Wx(`werift-dtls : packages/dtls/src/server.ts : log`),BT=class extends kT{constructor(e){super(e,bS.SERVER),this.onHandleHandshakes=this.handleHandshakes,zT(this.dtls.sessionId,`start server`)}flight6;handleHandshakes=async e=>{zT(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=VS.deSerialize(t.fragment);e.cookie.length===0?(zT(this.dtls.sessionId,`send flight2`),NT(this.transport,this.dtls,this.cipher,this.srtp)(e)):this.dtls.cookie&&e.cookie.equals(this.dtls.cookie)?(zT(this.dtls.sessionId,`send flight4`),await new FT(this.transport,this.dtls,this.cipher,this.srtp).exec(t,this.options.certificateRequest)):zT(`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 LT(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(),zT(this.dtls.sessionId,`dtls connected`)}}}},VT=554869826,HT=1398035790;function UT(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 WT(e){let t=Buffer.alloc(2);return t.writeUInt16BE(e.length,0),Buffer.concat([t,e])}function GT(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 KT(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=KT(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 qT(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 JT(e){return x(e)}function YT(e){let[t]=e,n=JT(t)?1:2,r=Buffer.alloc(4);return r.writeUInt8(0,0),r.writeUInt8(n,1),r.writeUInt16BE(e[1],2),Buffer.concat([r,KT(t)])}function XT(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 ZT(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[qT(r),n];case 2:if(r.length!==16)throw Error(`STUN address has invalid length for IPv6`);return[qT(r),n];default:throw Error(`STUN address has unknown protocol`)}}var QT=Buffer.alloc(6);QT.writeUInt16BE(VT>>16,0),QT.writeUInt32BE(VT,2);function $T(e,t){let n=[...QT,...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 eE(e,t){return ZT($T(e,t))}function tE(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 nE(e){let t=Buffer.alloc(e.length*2);return e.forEach((e,n)=>{t.writeUInt16BE(e,n*2)}),t}function rE(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 iE(e,t){return $T(YT(e),t)}var aE=e=>{let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t},oE=e=>e.readUInt32BE(0),sE=e=>{let t=Buffer.alloc(4);return t.writeUInt16BE(e,0),t},cE=e=>e.readUInt16BE(0),lE=e=>{let t=Buffer.allocUnsafe(8);return t.writeBigUInt64BE(e,0),t},uE=e=>e.readBigUInt64BE(0),dE=e=>Buffer.from(e,`utf8`),fE=e=>e.toString(`utf8`),pE=e=>{if([...e].length>=128)throw Error(`SOFTWARE must be shorter than 128 characters`);return dE(e)},mE=e=>e,hE=e=>e,gE=[[1,`MAPPED-ADDRESS`,YT,ZT],[3,`CHANGE-REQUEST`,aE,oE],[4,`SOURCE-ADDRESS`,YT,ZT],[5,`CHANGED-ADDRESS`,YT,ZT],[6,`USERNAME`,dE,fE],[8,`MESSAGE-INTEGRITY`,mE,hE],[9,`ERROR-CODE`,tE,XT],[10,`UNKNOWN-ATTRIBUTES`,nE,rE],[12,`CHANNEL-NUMBER`,sE,cE],[13,`LIFETIME`,aE,oE],[18,`XOR-PEER-ADDRESS`,iE,eE],[19,`DATA`,mE,hE],[20,`REALM`,dE,fE],[21,`NONCE`,mE,hE],[22,`XOR-RELAYED-ADDRESS`,iE,eE],[23,`REQUESTED-ADDRESS-FAMILY`,aE,oE],[24,`EVEN-PORT`,mE,hE],[25,`REQUESTED-TRANSPORT`,aE,oE],[28,`MESSAGE-INTEGRITY-SHA256`,mE,hE],[29,`PASSWORD-ALGORITHM`,mE,hE],[30,`USERHASH`,mE,hE],[32,`XOR-MAPPED-ADDRESS`,iE,eE],[34,`RESERVATION-TOKEN`,mE,hE],[36,`PRIORITY`,aE,oE],[37,`USE-CANDIDATE`,()=>Buffer.alloc(0),()=>null],[32770,`PASSWORD-ALGORITHMS`,mE,hE],[32771,`ALTERNATE-DOMAIN`,dE,fE],[32802,`SOFTWARE`,pE,fE],[32803,`ALTERNATE-SERVER`,YT,ZT],[32808,`FINGERPRINT`,aE,oE],[32809,`ICE-CONTROLLED`,lE,uE],[32810,`ICE-CONTROLLING`,lE,uE],[32811,`RESPONSE-ORIGIN`,YT,ZT],[32812,`OTHER-ADDRESS`,YT,ZT]],_E=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=[]}},vE=gE.reduce((e,t)=>(e[t[0]]=t,e),{}),yE=gE.reduce((e,t)=>(e[t[1]]=t,e),{});function bE(e,t){if(!UT(e))return;let n=e.readUInt16BE(0),r=Buffer.from(e.slice(8,20)),i=new _E,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=EE(c);if(u+f>e.length)return;let p=vE[s];if(p){let[,a,,s]=p,c;try{c=s.name===eE.name?s(d,r):s(d)}catch{return}if(i.setAttribute(a,c),a===`FINGERPRINT`){let t=wE(e.slice(0,n));if(i.getAttributeValue(`FINGERPRINT`)!==t)return}else if(a===`MESSAGE-INTEGRITY`&&t){let r=TE(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 xE(n&16111,n&272,r,i.getAttributes(),a)}var xE=class extends _E{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=>SE(e.type,e.value))),t=Buffer.alloc(8);return t.writeUInt16BE(this.messageMethod|this.messageClass,0),t.writeUInt16BE(e.length,2),t.writeUInt32BE(VT,4),Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){return this.setAttribute(`MESSAGE-INTEGRITY`,this.messageIntegrity(e)),this}messageIntegrity(e){let t=CE(this.bytes,this.bytes.length-20+24);return Buffer.from(o(`sha1`,e).update(t).digest(`hex`),`hex`)}addFingerprint(){return this.setAttribute(`FINGERPRINT`,wE(this.bytes)),this}get serializedAttributes(){let e=[];for(let t of this.attributesKeys){let n=this.getAttributeValue(t),[r,,i]=yE[t],a=i.name===iE.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 SE(e,t){let n=t.length,r=EE(n),i=Buffer.alloc(4);return i.writeUInt16BE(e,0),i.writeUInt16BE(n,2),Buffer.concat([i,t,Buffer.alloc(r)])}var CE=(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 wE(e){return(jx(CE(e,e.length-20+8))^HT)>>>0}function TE(e,t){let n=CE(e,e.length-20+24);return Buffer.from(o(`sha1`,t).update(n).digest(`hex`),`hex`)}function EE(e){let t=e%4;return t===0?0:4-t}var DE=class extends Error{response;addr},OE=class extends DE{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 DE{get str(){return`STUN transaction timed out`}},AE=Wx(`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 ME(e,t){return typeof e==`object`&&e?e:{retransmissions:typeof e==`number`?e:void 0,onRequestSent:t}}function NE(e,t){return e[0]===t[0]&&e[1]===t[1]}var PE=class{constructor(e,t,n,r,i){this.request=e,this.addr=t,this.protocol=n;let a=ME(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(!NE(this.expectedAddr,t)){AE(`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`))){AE(`ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)`);return}e.messageClass===256?(this.onResponse.execute(e,t),this.onResponse.complete()):this.onResponse.error(new OE(e,t))}};run=async()=>{try{if(this.signal?.aborted)throw new kE;return this.attachAbortListener(),this.retry().catch(e=>{AE(`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=>{AE(`send stun failed`,e)}),await this.wait(this.timeoutDelay),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&!this.ended&&(AE(`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 FE(e,t,n){let r=ME(t,n);return e&&!r.integrityKey&&(r.integrityKey=e),r}var IE=Wx(`werift-ice:packages/ice/src/stun/tcpProtocol.ts`);function LE(e){return`${e[0]}:${e[1]}`}function RE(e){if(e.remoteAddress&&e.remotePort)return[e.remoteAddress,e.remotePort]}async function zE(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 BE=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(LE(t),e)}forgetSocket(e){e&&this.sockets.delete(LE(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}=GT(n.buffer);n.buffer=i;let a=n.remoteAddr??RE(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=>{IE(`tcp socket error`,e)}),n}handleFrame(e,t){try{let n=bE(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?bE(e,r.integrityKey):n;if(!i){IE(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){IE(`tcp frame parse error`,e)}}async sendFrame(e,t){let n=await this.getSocket(t);await new Promise((t,r)=>{n.socket.write(WT(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=FE(n,r,i),s=new PE(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===LE(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()}},VE=class extends BE{pendingSockets=new Map;async connectionMade(e){this.localIp=e}async getSocket(e){let t=LE(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)}}},HE=class extends BE{server=y(e=>{this.registerSocket(e,RE(e))});async connectionMade(e,t){if(this.localIp=e,t){let n;for(let r=t[0];r<=t[1];r++)try{await zE(this.server,e,r);return}catch(e){n=e}throw n??Error(`tcp port not found`)}await zE(this.server,e)}async getSocket(e){let t=this.sockets.get(LE(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())})}},UE=Wx(`werift-ice : packages/ice/src/stun/protocol.ts`),WE=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 qx.init(`udp4`,{portRange:t,interfaceAddresses:n}):await qx.init(`udp6`,{portRange:t,interfaceAddresses:n}),this.transport.onData=(e,t)=>{this.datagramReceived(e,t)}};datagramReceived(e,t){try{let n=bE(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?bE(e,r.integrityKey):n;if(!i){UE(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){UE(`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(()=>{UE(`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=FE(n,r,i),s=new PE(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 GE(e,t,n){return a(`md5`).update(Buffer.from([e,t,n].join(`:`))).digest()}function KE(e){return c(e).toString(`hex`).substring(0,e)}function qE(){return c(12)}var JE=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)})})}},YE=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 XE(e){return e.length>=4&&(e[0]&192)==64}function ZE(e,t){let n=Buffer.alloc(4);return n.writeUInt16BE(e,0),n.writeUInt16BE(t.length,2),Buffer.concat([n,t])}function QE(e){if(!XE(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 $E(e){let t=EE(e.length);return t>0?Buffer.concat([e,Buffer.alloc(t)]):e}function eD(e){let t=[],n=0,r=!1;for(;e.length-n>=4;){let i;if(XE(e.subarray(n))){let t=e.readUInt16BE(n+2);i=4+t+EE(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+EE(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 tD=Wx(`werift-ice:packages/ice/src/turn/protocol.ts`),nD=500,rD=600,iD=285212672;function aD(e){return e.type===`tcp`||e.type===`tls`}function oD(e){return e[0]}function sD(e){return JSON.stringify(e)}var cD=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 Gx;onRequestReceived=new $;onDataReceived=new $;handleStunMessage=(e,t)=>{try{let n=bE(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?bE(e,r.integrityKey):n;if(!i){tD(`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){tD(`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=FE(n,r,i),s=new PE(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()}},lD=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??nD}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 xE(3,0);e.setAttribute(`LIFETIME`,this.lifetime).setAttribute(`REQUESTED-TRANSPORT`,iD);let[t]=await this.requestWithRetry(e,this.server).catch(e=>{throw tD(`connect error`,e),e});this.relayedAddress=t.getAttributeValue(`XOR-RELAYED-ADDRESS`),this.mappedAddress=t.getAttributeValue(`XOR-MAPPED-ADDRESS`);let n=t.getAttributeValue(`LIFETIME`);tD(`connect`,this.relayedAddress,this.mappedAddress,{exp:n}),this.refresh(n)}handleChannelData(e){let t=QE(e),n=t&&this.addrByChannel[t.channelNumber];n&&t&&this.onData.execute(t.data,n)}handleSTUNMessage(e,t){try{let n=bE(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?bE(e,r.integrityKey):n;if(!i){tD(`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{tD(`parse error`,e.toString())}}dataReceived(e,t){let n=(e,t)=>{e.length>=4&&XE(e)?this.handleChannelData(e):this.handleSTUNMessage(e,t)};if(aD(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);let{frames:r,rest:i}=eD(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(aD(this.transport)?$E(e):e,t)}async createPermission(e){let t=new xE(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=YE(async(t,n,r)=>{let i=!0;for(r.once(()=>{i=!1});i;){let t=5/6*e*1e3;tD(`refresh delay`,t,{exp:e}),await E(t);let n=new xE(4,0);n.setAttribute(`LIFETIME`,e);try{let[t]=await this.requestWithRetry(n,this.server);e=t.getAttributeValue(`LIFETIME`),tD(`refresh`,{exp:e})}catch(e){tD(`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=FE(this.integrityKey,r,i),s=new PE(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 OE==0)throw tD(`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)tD(`retry with nonce`,i),this.nonce=a,i===401&&(this.realm=o),this.integrityKey=fD(this.username,this.realm,this.password),e.transactionId=qE(),[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){tD(`channelBind error; falling back to Send Indication`,e)}if(!n){await this.getPermission(t);let n=new xE(6,16).setAttribute(`DATA`,e).setAttribute(`XOR-PEER-ADDRESS`,t);await this.sendStun(n,this.server);return}await this.send(ZE(n.number,e),this.server)}async getPermission(e){let t=oD(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 tD(`createPermission error`,e),e}finally{this.creatingPermissionByAddr.get(t)===r&&this.creatingPermissionByAddr.delete(t)}}async getChannel(e){let t=sD(e),n=this.channelBindingByAddr.get(t);if(n)return n;let r=this.channelByAddr[t],i=Bx(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 tD(`channelBind error`,e),e}finally{this.channelBindingByAddr.get(t)===a&&this.channelBindingByAddr.delete(t)}}async ensureChannel(e){let t=sD(e),n=Bx(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=Bx(Date.now()/1e3)+this.channelRefreshTime,tD(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 xE(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 uD({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){r??=rD,c??=o?`tls`:`udp`;let l=c===`udp`?await qx.init(`udp4`,{portRange:i,interfaceAddresses:a}):c===`tcp`?await Jx.init(e):await Yx.init(e,s),u=new lD(e,t,n,r,l);return await u.connectionMade(),u}async function dD({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){return new cD(await uD({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}))}function fD(e,t,n){return GE(e,t,n)}var pD=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()&&bD(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}},mD={host:126,prflx:110,srflx:100,relay:0},hD={host:105,prflx:90,srflx:80,relay:0},gD={active:6,passive:4,so:2},_D={active:4,passive:2,so:6};function vD(e){return e?.toLowerCase()??`udp`}function yD(e){switch(e){case`active`:case`passive`:case`so`:return e;default:return}}function bD(e,t){if(vD(e.transport)!==`tcp`)return!0;let n=yD(e.tcptype),r=yD(t.tcptype);return!n||!r?!1:n===`active`&&r===`passive`||n===`passive`&&r===`active`||n===`so`&&r===`so`}function xD({candidateType:e,transport:t=`udp`,tcptype:n,otherPreference:r=8191}){if(vD(t)!==`tcp`)return r;let i=yD(n)??`active`;return 8192*(e===`srflx`||e===`prflx`?_D[i]:gD[i])+r}function SD(e,t=`udp`){return(vD(t)===`tcp`?hD:mD)[e]??0}function CD(e,t,n){let r=`${e}|${t}|${n}`;return a(`md5`).update(r,`ascii`).digest(`hex`).slice(7)}function wD(e,t=65535){let n=typeof t==`number`?`udp`:vD(t.transport),r=typeof t==`number`?t:t.localPreference??xD({candidateType:e,transport:n,tcptype:t.tcptype,otherPreference:t.otherPreference});return(1<<24)*SD(e,n)+256*r+255}function TD(e){switch(e){case`passive`:return`active`;case`active`:return`passive`;default:return`so`}}var ED=class{cache=new Map;mdnsInstance=(0,ux.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()}},DD=Wx(`werift-ice : packages/ice/src/ice.ts : log`),OD=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 PD(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 AD(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 MD(e){if(![`host`,`relay`,`srflx`].includes(e.type))throw Error(`Unexpected candidate type "${e.type}"`);return e}function ND(e,t){return e.sort((e,n)=>PD(e.localCandidate,e.remoteCandidate,t)-PD(n.localCandidate,n.remoteCandidate,t)).reverse()}function PD(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 FD(e,t){let n=new xE(1,0);try{let[r]=await e.request(n,t),i=e.localCandidate;if(!i)throw Error(`not exist`);return new pD(CD(`srflx`,i.transport,i.host),i.component,i.transport,wD(`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){DD(`error serverReflexiveCandidate`,e)}}function ID(e){return e&&Number.isNaN(e[1])?[e[0],443]:e}function LD(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=>Ux(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 RD=Wx(`werift-ice : packages/ice/src/utils.ts`);function zD(e){return Ux(e.family)===4&&e.address?.startsWith(`169.254.`)||Ux(e.family)===6&&e.address?.startsWith(`fe80::`)}function BD(e,{useLinkLocalAddress:t}={}){let n=m.networkInterfaces();return RD(n),LD(n,e,{useLinkLocalAddress:t},zD)}function VD(e,t,n={}){let r=[];return e&&r.push(...BD(4,n)),t&&r.push(...BD(6,n)),r}var HD=Wx(`werift-ice : packages/ice/src/ice.ts : log`),UD=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=ID(n)??[`stun.l.google.com`,19302],this.turnServer=ID(r),this.restart(),HD(`new Connection`,this.options)}localUsername=KE(4);localPassword=KE(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 JE;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=KE(4),this.localPassword=KE(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 JE,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(){HD(`resetNominatedPair`),this.nominated=void 0,this.nominating=!1,this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:n}){HD(`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=VD(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}=GD(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 xE(1,256,t.transactionId);s.setAttribute(`XOR-MAPPED-ADDRESS`,n).addMessageIntegrity(Buffer.from(a,`utf8`)).addFingerprint(),e.sendStun(s,n).catch(e=>{HD(`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){HD(`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 WE;this.ensureProtocol(t);try{await t.connectionMade(w(e),this.options.portRange,this.options.interfaceAddresses),t.localIp=e,this.protocols.push(t),HD(`protocol`,t.localIp);let n=[e,t.getExtraInfo()[1]];return t.localCandidate=new pD(CD(`host`,`udp`,n[0]),1,`udp`,wD(`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){HD(`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 HE;if(this.ensureProtocol(t),await t.connectionMade(e,this.options.portRange),t.localIp=e,t.localCandidate=new pD(CD(`host`,`tcp`,e),1,`tcp`,wD(`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 VE;this.ensureProtocol(t),await t.connectionMade(e),t.localIp=e,t.localCandidate=new pD(CD(`host`,`tcp`,e),1,`tcp`,wD(`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 FD(n,r).catch(e=>{HD(`error`,e)});t&&this.appendLocalCandidate(t),clearTimeout(a),e(t)}else clearTimeout(a),e()}).catch(e=>{HD(`query STUN server`,e)})});n.push(...e)}if(!s&&i&&a&&o){let e=(async()=>{let e=this.options.turnTransport??`udp`,t=await dD({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 dD({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 HD(`turn candidateAddress`,n),t.localCandidate=new pD(CD(`relay`,`udp`,n[0]),1,`udp`,wD(`relay`),n[0],n[1],`relay`,r[0],r[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(t.localCandidate),t.localCandidate})().catch(e=>{HD(`query TURN server`,e)});n.push(e)}return n}async connect(){if(HD(`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(),HD(`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(),HD(`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(),HD(`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===WE.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=YE(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`&&(HD(`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=AD(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&&HD(`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 ED,e.host=await this.lookup.lookup(e.host)}catch{return}try{MD(e)}catch{return}HD(`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{MD(t)}catch{continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){ND(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){HD(`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){HD(`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||=(HD(`ICE completed`),this.checkListState.put(new Promise(e=>e(1))),!0);return}HD(`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||(HD(`ICE failed`),this.checkListState.put(new Promise(e=>{e(2)}))))}checkStart=e=>YE(async t=>{HD(`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++,HD(`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(HD(`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){HD(`retry 401`,e.toJSON()),await this.checkStart(e).awaitable,t();return}HD(`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}=GD(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 pD(KE(10),1,n.localCandidate?.transport??`udp`,e.getAttributeValue(`PRIORITY`),a,o,`prflx`,void 0,void 0,n.localCandidate?.transport===`tcp`?TD(n.localCandidate.tcptype):void 0,void 0,void 0),this._remoteCandidates.push(i));let s=this.findPair(n,i);if(s||(s=new OD(n,i,this.iceControlling),s.updateState(1),this.addPair(s)),s.noteIncomingRequest(e.transactionIdHex),s.requestsReceived++,s.responsesSent++,s.localCandidate.ufrag=r,HD(`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 OD(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=WD({remoteUsername:t,localUsername:n}),o=new xE(1,0);return o.setAttribute(`USERNAME`,a).setAttribute(`PRIORITY`,wD(`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 xE(e.messageMethod,272,e.transactionId);i.setAttribute(`ERROR-CODE`,r).addMessageIntegrity(Buffer.from(this.localPassword,`utf8`)).addFingerprint(),n.sendStun(i,t).catch(e=>{HD(`sendStun error`,e)})}},WD=({remoteUsername:e,localUsername:t})=>`${e}:${t}`,GD=e=>{let[t,n]=e.split(`:`);return{remoteUsername:t,localUsername:n}};function KD(e){return e.map((e,t)=>[t,e])}function qD(e,t){let n=e.split(t);return[n[0],n.slice(1).join(t)]}var JD=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)},YD=Wx(`werift:packages/webrtc/src/dataChannel.ts`);function XD(e){return Buffer.isBuffer(e)?e.length:Buffer.byteLength(e)}var ZD=class extends JD{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()}YD(`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)}},QD=class{label=``;maxPacketLifeTime;maxRetransmits;ordered=!0;protocol=``;negotiated=!1;id;constructor(e={}){Object.assign(this,e)}},$D=()=>({type:`nack`}),eO=()=>({type:`nack`,parameter:`pli`}),tO=()=>({type:`goog-remb`}),nO=()=>({type:`transport-cc`}),rO=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}},iO=class{id;uri;constructor(e){Object.assign(this,e)}},aO=class{type;parameter;constructor(e={}){Object.assign(this,e)}},oO=class{ssrc;constructor(e={}){Object.assign(this,e)}},sO=class{ssrc;payloadType;rtx;constructor(e){Object.assign(this,e)}},cO=class{rid;direction;constructor(e){Object.assign(this,e)}},lO=(e={})=>new rO({mimeType:`video/h264`,clockRate:9e4,rtcpFeedback:[$D(),eO(),tO()],parameters:`profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1`,...e}),uO=(e={})=>new rO({mimeType:`video/VP8`,clockRate:9e4,rtcpFeedback:[$D(),eO(),tO()],...e}),dO=(e={})=>new rO({mimeType:`video/VP9`,clockRate:9e4,rtcpFeedback:[$D(),eO(),tO()],...e}),fO=(e={})=>new rO({mimeType:`video/AV1X`,clockRate:9e4,rtcpFeedback:[$D(),eO(),tO()],...e}),pO=(e={})=>new rO({mimeType:`audio/OPUS`,clockRate:48e3,channels:2,...e}),mO=(e={})=>new rO({mimeType:`audio/PCMU`,clockRate:8e3,channels:1,payloadType:0,...e}),hO=[fO(),dO(),uO(),lO(),pO(),mO()].map(e=>e.mimeType);hO.filter(e=>e.toLowerCase().startsWith(`video/`)),hO.filter(e=>e.toLowerCase().startsWith(`audio/`));var gO=2,_O=3,vO=0,yO=50,bO=51,xO=53,SO=56,CO=57,wO=`0.0.0.0`,TO=9,EO={auto:`actpass`,client:`active`,server:`passive`},DO=Object.keys(EO).reduce((e,t)=>{let n=EO[t];return e[n]=t,e},{}),OO=[`apt`,`max-fr`,`max-fs`,`maxplaybackrate`,`minptime`,`stereo`,`useinbandfec`],kO=[`cname`,`msid`,`mslabel`,`label`],AO={SRTP_AES128_CM_HMAC_SHA1_80:1,SRTP_AEAD_AES_128_GCM:7},jO=[`sendonly`,`sendrecv`],MO=[`sendrecv`,`recvonly`],NO=class extends Map{constructor(e){if(super(),e)for(let t of e)this.set(t.id,t)}};function PO(e,...t){return`${e}_${t.filter(e=>e!==void 0).join(`_`)}`}function FO(e,t,n){return PO(`codec`,e,t,n)}function IO(){return performance.timeOrigin+performance.now()}function LO(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 RO(e,t){let n=new Map;for(let t of e)n.set(t.id,t);if(!t)return new NO([...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(...LO(t)))}return new NO([...r].map(e=>n.get(e)).filter(e=>!!e))}var zO=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=IO();return this.collectCodecStats(e)}collectCodecStats(e){let t=[];if(!this.dtlsTransport)return t;let n=PO(`transport`,this.dtlsTransport.id);for(let r of this.codecs){let i={type:`codec`,id:FO(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}},BO=[`inactive`,`sendonly`,`recvonly`,`sendrecv`],VO=class extends JD{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)?Rw.deSerialize(e):e;t.header.payloadType=this.codec?.payloadType??t.header.payloadType,this.onReceiveRtp.execute(t)}},HO=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`)}},UO=Wx(`werift:packages/webrtc/src/utils.ts`);function WO(e,t){return(e=>e.match(/(.{2})/g).join(`:`))((e=>e.toUpperCase())(a(t).update(e).digest(`hex`)))}var GO={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 KO(e){return GO[e.trim().toLowerCase()]}function qO(e){return e.replace(/[^0-9a-f]/gi,``).toLowerCase()}function JO(e){let t=e[0];return t>19&&t<64}var YO=(e,t)=>BO[BO.indexOf(e)&BO.indexOf(t)];function XO(e){return e===`sendonly`?`recvonly`:e===`recvonly`?`sendonly`:e}var ZO=Date.now,QO=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,$O=()=>QO+process.hrtime.bigint()/1000n,ek=()=>Date.now()/1e3,tk=()=>{let[e,t]=((A.timeOrigin+A.now()-Date.UTC(1900,0,1))/1e3).toString().split(`.`).map(Number);return gx([4,4],[e,t]).readBigUInt64BE()},nk=e=>{let[t,n]=vx(gx([8],[e]),[4,4]);return t*1e3+n+Date.UTC(1900,0,1)},rk=e=>{let[,t,n]=vx(gx([8],[e]),[2,2,2,2]);return gx([2,2],[t,n]).readUInt32BE()};function ik(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=ok(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 UO(`iceOptions`,t),t}function ak({configuredTurnTransport:e,forceTurnTCP:t,parsedTurnTransport:n}){if(n)return n;if(e)return e;if(t)return`tcp`}function ok(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=lk(a,ck(i));if(!s)return;if(i===`stun`||i===`stuns`)return{kind:`stun`,address:s};let c=sk({scheme:i,transportParam:new URLSearchParams(o).get(`transport`)});if(c!==`invalid`)return{kind:`turn`,address:s,transport:c}}function sk({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 ck(e){return e===`stuns`||e===`turns`?5349:3478}function lk(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),uk(n.slice(e+1),t)]}let r=n.indexOf(`:`),i=n.lastIndexOf(`:`);return r!==-1&&r===i?[n.slice(0,r),uk(n.slice(r+1),t)]:[n,t]}function uk(e,t){let n=e.startsWith(`:`)?e.slice(1):e,r=Number.parseInt(n,10);return Number.isFinite(r)?r:t}CS.createSelfSignedCertificateWithKey;var dk=(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},fk=Wx(`werift:packages/webrtc/src/media/receiver/nack.ts`),pk=150,mk=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){fk(`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===Px(this.newEstSeqNum,1))this.newEstSeqNum=t;else if(t>Px(this.newEstSeqNum,1)){for(let e=Px(this.newEstSeqNum,1);e<t;e=Px(e,1))this.setLost(e,1);this.newEstSeqNum=t,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>pk&&(this._lost=Object.entries(this._lost).slice(-pk).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 JC({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),r=new nw({feedback:n});this.receiver.dtlsTransport.sendRtcp([r]).then(e).catch(t),this.updateRetryCount(),this.onPacketLost.execute(n)}})},hk=Wx(`werift:packages/webrtc/media/receiver/receiverTwcc`),gk=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:$O()},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=Px(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 $C({delta:Number(i)});a.parseDelta(),c.push(a),s!=null&&s.status!==a.type&&(r.push(new ZC({packetStatus:s.status,runLength:e-s.minTSN})),s={minTSN:e,status:a.type}),e===n&&(s==null?r.push(new ZC({packetStatus:a.type,runLength:1})):r.push(new ZC({packetStatus:s.status,runLength:e-s.minTSN+1}))),s??={minTSN:e,status:a.type}}}if(!o)return;let l=new nw({feedback:new XC({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:i,packetStatusCount:a,referenceTime:Ix(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:r})});this.dtlsTransport.sendRtcp([l]).catch(e=>{hk(e)}),this.extensionInfo={},this.fbPktCount=Nx(this.fbPktCount,1)}},_k=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||Lx(e.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.bytesReceived+=e.payload.length,this.headerBytesReceived+=e.header.serializeSize,this.lastPacketReceivedTimestamp=IO(),this.base_seq??=e.header.sequenceNumber,n){let n=Bx(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}},vk=Wx(`werift:packages/webrtc/src/transport/dtls.ts`);function yk(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 bk(e){switch(e){case 1:return`AES_CM_128_HMAC_SHA1_80`;case 7:return`AEAD_AES_128_GCM`;default:return}}var xk=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 JD;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 wk(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 CS.createSelfSignedCertificateWithKey({signature:Zx.ecdsa_3,hash:Qx.sha256_4},tS.secp256r1_23);return this.localCertificate=new Sk(t,e,n),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let t=Tk([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),n=e.role===`auto`&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new wk(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 BT({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`),vk(`dtls failed`,e),t(e)}),this.dtls instanceof jT&&(await E(100),this.dtls.connect().catch(e=>{this.setState(`failed`),vk(`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`),vk(`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=KO(e);if(!n)return[];let r=qO(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=Dk(t),r=t.filter(({normalizedAlgorithm:e})=>e===n),i=r.reduce((t,{normalizedAlgorithm:n})=>(t.has(n)||t.set(n,qO(WO(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`);vk(`selected SRTP Profile`,e);let{localKey:t,localSalt:n,remoteKey:r,remoteSalt:i}=this.dtls.extractSessionKeys(PC(e),FC(e)),a={keys:{localMasterKey:t,localMasterSalt:n,remoteMasterKey:r,remoteMasterSalt:i},profile:e};this.srtp=new fT(a),this.srtcp=new uT(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())&&RC(e)){if(this.bytesReceived+=e.length,this.packetsReceived++,fw(e)){let t;try{t=this.srtcp.decrypt(e)}catch(e){if(e instanceof Hw){vk(`dropping invalid SRTCP packet`,e);return}throw e}let n;try{n=dw.deSerialize(t)}catch(e){vk(`dropping malformed SRTCP packet`,e);return}for(let e of n)try{this.onRtcp.execute(e)}catch(e){vk(`RTCP error`,e)}}else{let t;try{t=this.srtp.decrypt(e)}catch(e){if(e instanceof Hw){vk(`dropping invalid SRTP packet`,e);return}throw e}let n;try{n=Rw.deSerialize(t)}catch(e){vk(`dropping malformed SRTP packet`,e);return}try{this.onRtp.execute(n)}catch(e){vk(`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 vk(`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=IO()){let t=[],n=PO(`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?PO(`candidate-pair`,this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?PO(`certificate`,this.id,`local`):void 0,remoteCertificateId:this.dtls?.remoteCertificate?PO(`certificate`,this.id,`remote`):void 0,dtlsRole:this.role===`auto`?void 0:this.role,tlsVersion:yk(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:bk(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:PO(`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:PO(`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}},Sk=class{constructor(e,t,n){this.certPem=t,this.signatureHash=n;let r=Jr.Certificate.fromPEM(Buffer.from(t));this.publicKey=r.publicKey.toPEM(),this.privateKey=Jr.PrivateKey.fromPEM(Buffer.from(e)).toPEM()}publicKey;privateKey;getFingerprints(){return[new Ck(`sha-256`,WO(Jr.Certificate.fromPEM(Buffer.from(this.certPem)).raw,`sha256`))]}},Ck=class{constructor(e,t){this.algorithm=e,this.value=t}},wk=class{constructor(e=[],t){this.fingerprints=e,this.role=t}},Tk=e=>{let t=new Set;return e.filter(({algorithm:e,value:n})=>{let r=`${KO(e)??e.trim().toLowerCase()}:${qO(n)}`;return!t.has(r)&&(t.add(r),!0)})},Ek=[`sha512`,`sha384`,`sha256`,`sha224`,`sha1`],Dk=e=>Ek.find(t=>e.some(({normalizedAlgorithm:e})=>e===t))??e[0].normalizedAlgorithm,Ok=class{constructor(e){this.ice=e,e.onData.subscribe(e=>{JO(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 Ok(e),Ak=Wx(`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 Mk=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 JD;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=>Pk(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>Pk(e).toJSON())}getSelectedCandidatePair(){let e=this.connection.candidatePairs.find(e=>e.nominated)??this.connection.candidatePairs.find(e=>e.state===3);return e?{local:Pk(e.localCandidate).toJSON(),remote:Pk(e.remoteCandidate).toJSON()}:null}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){return!this.connection.remoteUsername||!this.connection.remotePassword?null:new Rk({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(Fk(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?(Ak(`renomination`,e),this.connection.resetNominatedPair(),this.renominating=!1):(Ak(`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=IO(),t=PO(`transport`,this.id)){let n=[];for(let r of this.connection.localCandidates){let i={type:`local-candidate`,id:PO(`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:PO(`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:PO(`candidate-pair`,i.id),timestamp:e,transportId:t,localCandidateId:PO(`local-candidate`,i.localCandidate.id),remoteCandidateId:PO(`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}},Nk=class{constructor(e={}){this.options=e,this.connection=new UD(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(Pk(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(Pk)}get localParameters(){return new Rk({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 Pk(e){let t=new Lk(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 Fk(e){return new pD(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 Ik=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(e){Object.assign(this,e)}static fromSdp(e){return Pk(pD.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}}},Lk=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 Ik({candidate:tj(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate)throw Error(`candidate is required`);let t=aj(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{}}},Rk=class{iceLite=!1;usernameFragment;password;constructor(e={}){Object.assign(this,e)}},zk=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(aA(this.body.length))].map(()=>Buffer.from(`\0`))])}},Bk=class extends zk{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=sA(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,oA(this.params)])}},Vk=class e extends Bk{static type=1;get type(){return e.type}},Hk=class e extends Bk{static type=2;get type(){return e.type}},Uk=class e extends Bk{static type=130;get type(){return e.type}},Wk=class e extends zk{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})])}},Gk=class e extends zk{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(aA(e))].map(()=>Buffer.from(`\0`))])),n}},Kk=class e extends zk{static type=10;get type(){return e.type}},qk=class e extends zk{static type=11;get type(){return e.type}},Jk=class extends zk{constructor(e=0,t=void 0){super(e,t),this.flags=e,t&&(this.params=sA(t))}params=[];get body(){return oA(this.params)}},Yk=class e extends Jk{static type=6;get type(){return e.type}},Xk=class e extends Jk{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}))}},Zk=class e extends Jk{static type=4;get type(){return e.type}},Qk=class e extends Jk{static type=5;get type(){return e.type}},$k=class e extends Jk{static type=130;get type(){return e.type}},eA=class e extends zk{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}},tA=class e extends zk{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}},nA=class e extends zk{static type=8;get type(){return e.type}},rA=class e extends zk{static type=14;get type(){return e.type}},iA=[Gk,Vk,Hk,eA,Zk,Qk,Yk,tA,nA,Xk,Kk,qk,rA,$k,Wk].reduce((e,t)=>(e[t.type]=t,e),{});function aA(e){let t=e%4;return t?4-t:0}function oA(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(aA(i))].map(()=>Buffer.from(`\0`)))}),t}function sA(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+aA(i)}return t}function cA(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)!==Mx(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=iA[t.toString()];if(s)i.push(new s(n,o));else throw Error(`unknown`);a+=r+aA(r)}return[t,n,r,i]}function lA(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=Mx(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 uA(e){return e.map((e,t)=>[t,e])}function dA(e){return e.reduce((e,t)=>(e[t]=new $,e),{})}var fA=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)}},pA=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)}},mA={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},hA=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)}},gA={13:fA,16:hA,17:pA},_A=Wx(`werift/sctp/sctp`),vA=24,yA=60,bA=65535,xA=1200,SA=1,CA=2,wA=4,TA=10,EA=8,DA=1/8,OA=1/4,kA=3,AA=1,jA=60,MA=2**32,NA=200,PA=30,FA=135,IA=7,LA=32776,RA=49152,zA=[`new`,`closed`,`connected`,`connecting`],BA=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=dA(zA);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=fx();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=bA;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*xA;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=bA;localTsn=Number(fx());lastSackedTsn=UA(this.localTsn);advancedPeerAckTsn=UA(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=PA;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]=cA(e);if(r.filter(e=>e.type===Vk.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=>{_A(`send delayed sack failed`,e.message)})},NA)}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],t;[...this.sackMisOrdered].sort().forEach(n=>{let r=(n-this.lastReceivedTsn)%MA;n===t?e[e.length-1][1]=r:e.push([r,r]),t=WA(n)});let n=new eA(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=>{_A(`send sack failed`,e.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case Gk.type:this.receiveDataChunk(e);break;case Vk.type:{if(!this.isServer)return;let t=e;_A(`receive init`,t),this.lastReceivedTsn=UA(t.initialTsn),this.reconfigResponseSeq=UA(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 Hk;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([IA,a]),_A(`send initAck`,n),await this.sendChunk(n).catch(e=>{_A(`send initAck failed`,e.message)})}break;case Hk.type:{if(this.associationState!=2)return;let t=e;this.timer1Cancel(),this.lastReceivedTsn=UA(t.initialTsn),this.reconfigResponseSeq=UA(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 Kk;for(let[e,r]of t.params)if(e===IA){n.body=r;break}await this.sendChunk(n).catch(e=>{_A(`send echo failed`,e.message)}),this.timer1Start(n),this.setState(3)}break;case eA.type:await this.receiveSackChunk(e);break;case Zk.type:{let t=new Qk;t.params=e.params,await this.sendChunk(t).catch(e=>{_A(`send heartbeat ack failed`,e.message)})}break;case Yk.type:this.setState(1);break;case tA.type:{this.timer2Cancel(),this.setState(7);let e=new nA;await this.sendChunk(e).catch(e=>{_A(`send shutdown ack failed`,e.message)}),this.t2Start(e),this.setState(6)}break;case Xk.type:_A(`ErrorChunk`,e.descriptions);break;case Kk.type:{if(!this.isServer)return;let t=e.body,n=o(`sha1`,this.hmacKey).update(t.slice(0,4)).digest();if(t?.length!=vA||!t.slice(4).equals(n)){_A(`x State cookie is invalid`);return}let r=Math.floor(Date.now()/1e3),i=t.readUInt32BE(0);if(i<r-yA||i>r){let e=new Xk(0,void 0);e.params.push([Xk.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(`\0`)))]),await this.sendChunk(e).catch(e=>{_A(`send errorChunk failed`,e.message)});return}let a=new qk;await this.sendChunk(a).catch(e=>{_A(`send cookieAck failed`,e.message)}),this.setState(4)}break;case qk.type:if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4);break;case rA.type:if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1);break;case $k.type:{if(this.associationState!=4)return;let t=e;for(let[e,n]of t.params){let t=gA[e];t&&await this.receiveReconfigParam(t.parse(n))}}break;case Wk.type:this.receiveForwardTsnChunk(e)}}getExtensions(e){for(let[t,n]of e)t===RA?this.remotePartialReliability=!0:t===LA&&(this.remoteExtensions=[...n])}async receiveReconfigParam(e){switch(_A(`receiveReconfigParam`,gA[e.type]),e.type){case fA.type:{let t=e,n=new hA(t.requestSequence,mA.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 hA.type:{let t=e;if(t.result!==mA.ReconfigResultSuccessPerformed)_A(`OutgoingSSNResetRequestParam failed`,Object.keys(mA).find(e=>mA[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 pA.type:{let t=e;this._inboundStreamsCount+=t.newStreams;let n=new hA(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&SA)===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(Rx(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&&zx(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)%MA,t.add(n)});let r=e.cumulativeTsn;for(let e of this.sentQueue){if(Rx(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(Rx(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,xA):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=xA))),a&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*xA),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):zx(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,zx(this.lastReceivedTsn,e.cumulativeTsn))return;let t=e=>Rx(e,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let e of[...this.sackMisOrdered].sort())if(e===WA(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=Px(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-OA)*this.rttvar+OA*Math.abs(this.srtt-e),this.srtt=(1-DA)*this.srtt+DA*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(AA,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 VA),this.inboundStreams[e]}markReceived(e){if(zx(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===WA(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;let t=e=>Rx(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/xA),c=0,l=[];for(let u=0;u<s;u++){let d=new Gk(0,void 0);d.flags=0,a||(d.flags=wA),u===0&&(d.flags|=CA),u===s-1&&(d.flags|=SA),d.tsn=this.localTsn,d.streamId=e,d.streamSeqNum=o,d.protocol=t,d.userData=n.slice(c,c+xA),d.bookSize=d.userData.length,d.expiry=r,d.maxRetransmits=i,c+=xA,this.localTsn=WA(this.localTsn),l.push(d)}for(l.forEach(e=>{this.outboundQueue.push(e)}),a&&(this.outboundStreamSeq[e]=Px(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=>{_A(`send forwardTsn failed`,e.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit==null?4*xA:2*xA,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=>{_A(`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=>{_A(`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,FA);this.reconfigQueue=e.slice(FA);let n=new fA(this.reconfigRequestSeq,this.reconfigResponseSeq,UA(this.localTsn),t);this.reconfigRequestSeq=WA(this.reconfigRequestSeq),this.reconfigRequest=n,await this.sendReconfigParam(n),this.timerReconfigHandleStart()}}async sendReconfigParam(e){_A(`sendReconfigParam`,e);let t=new $k;t.params.push([e.type,e.bytes]),await this.sendChunk(t).catch(e=>{_A(`send reconfig failed`,e.message)})}async sendResetRequest(e){_A(`sendResetRequest`,e);let t=new Gk(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>EA)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{_A(`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>TA)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{_A(`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*xA),this.cwnd=xA,this.transmit())};timer3Cancel(){this.timer3Handle&&=(clearTimeout(this.timer3Handle),void 0)}timerReconfigHandleStart(){this.isStopped||(this.timerReconfigHandle||=(_A(`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>TA)_A(`timerReconfigFailures`,this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(_A(`timerReconfigHandleExpired`,this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(_A(`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 Zk,t=Buffer.allocUnsafe(4);t.writeUInt32BE(Math.floor(Date.now()/1e3),0),e.params.push([1,t]),await this.sendChunk(e).catch(e=>{_A(`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(){Rx(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&wA||(t[n.streamId]=n.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new Wk(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&SA)break}for(let e=t;e<this.sentQueue.length;e++){let t=this.sentQueue[e];if(t.abandoned=!0,t.retransmit=!1,t.flags&SA)break}return!0}static getCapabilities(){return new HA(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 Vk;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),_A(`send init`,e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(e){_A(`send init failed`,e.message)}}setExtensions(e){let t=[];this.localPartialReliability&&(e.push([RA,Buffer.from(``)]),t.push(Wk.type)),t.push(Uk.type),e.push([LA,Buffer.from(t)])}async sendChunk(e){if(this.state===`closed`)return;if(this.remotePort===void 0)throw Error(`invalid remote port`);let t=lA(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,_A(`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 Yk;await this.sendChunk(e).catch(e=>{_A(`send abort failed`,e.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},VA=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(e){if(this.reassembly.length===0||Rx(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(let[t,n]of uA(this.reassembly)){if(n.tsn===e.tsn)throw Error(`duplicate chunk in reassembly`);if(Rx(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&wA),!(i.flags&CA)){if(r)break;e++;continue}if(r&&Lx(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&SA){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=Px(this.streamSequenceNumber,1)),e=t,yield[i.streamId,i.protocol,a]}else e++;n=WA(n)}}pruneChunks(e){let t=-1,n=0;for(let[r,i]of this.reassembly.entries())if(zx(e,i.tsn))t=r,n+=i.userData.length;else break;return this.reassembly=this.reassembly.slice(t+1),n}},HA=class{constructor(e){this.maxMessageSize=e}};function UA(e){return(e-1)%MA}function WA(e){return(e+1)%MA}var GA=Wx(`werift:packages/webrtc/src/transport/sctp.ts`),KA=65536,qA=class e{constructor(e=5e3,t=KA){this.port=e,this.maxMessageSize=t}dtlsTransport;sctp;onDataChannel=new $;id=l().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=KA;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 BA(new YA(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===yO&&n.length>0)switch(GA(`DCEP`,e,t,n),n[0]){case _O:{if(n.length<12){GA(`DATA_CHANNEL_OPEN data.length not enough`);return}if(Object.keys(this.dataChannels).includes(e.toString()))GA(`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`);GA(`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 QD({label:s,ordered:!(t&128),maxPacketLifeTime:u,maxRetransmits:l,protocol:c,id:e}),f=new ZD(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(gO,0),this.dataChannelQueue.push([t,yO,r]),await this.dataChannelFlush()}break;case gO:{GA(`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 bO:return n.toString(`utf8`);case SO:return``;case xO:return n;case CO: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=vO,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(_O,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,yO,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===yO)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=XD(t);return this.assertSendableMessageSize(r),e.addBufferedAmount(r),this.dataChannelQueue.push(typeof t==`string`?[e,bO,n]:[e,xO,n]),this.sctp.associationState!==4&&GA(`sctp not established`,this.sctp.associationState),this.dataChannelFlush(),r};getCapabilities(){return e.getCapabilities(this.maxMessageSize)}static getCapabilities(e=KA){return new JA(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`)))}},JA=class{constructor(e){this.maxMessageSize=e}},YA=class{constructor(e){this.dtls=e}set onData(e){this.dtls.dataReceiver=e}send=e=>this.dtls.sendData(e);close(){}},XA=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]=nj(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=$A(e.slice(2));else if(e.startsWith(`t=`))i.time=e.slice(2);else if(e.startsWith(`a=`)){let[t,n]=rj(e);switch(t){case`fingerprint`:{let[e,t]=n?.split(` `)||[];i.dtlsFingerprints.push(new Ck(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`:ij(i.group,n);break;case`msid-semantic`:ij(i.msidSemantic,n);break;case`setup`:i.dtlsRole=DO[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 ZA(n,Number.parseInt(t[2]),t[3],o||r);if(s.dtlsParams=new wk([...i.dtlsFingerprints],i.dtlsRole),s.iceParams=new Rk({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=$A(e.slice(2));else if(e.startsWith(`a=`)){let[t,n]=rj(e);switch(t){case`candidate`:if(!n)throw Error();s.iceCandidates.push(aj(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 iO({id:Number.parseInt(e),uri:t}))}break;case`fingerprint`:{if(!n)throw Error();let[e,t]=n.split(` `);s.dtlsParams?.fingerprints.push(new Ck(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 JA(Number.parseInt(n,10));break;case`mid`:s.rtp.muxId=n;break;case`msid`:s.msids.push(n);break;case`rtcp`:{let[e,t]=qD(n,` `);s.rtcpPort=Number.parseInt(e),s.rtcpHost=$A(t)}break;case`rtcp-mux`:s.rtcpMux=!0;break;case`setup`:s.dtlsParams.role=DO[n];break;case`recvonly`:case`sendonly`:case`sendrecv`:case`inactive`:s.direction=t;break;case`rtpmap`:{let[e,t]=qD(n,` `),[r,i,a]=t.split(`/`),o;s.kind===`audio`&&(o=a?Number.parseInt(a):1);let c=new rO({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]=qD(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]=qD(n,` `),r=Number.parseInt(e),[i,a]=qD(t,`:`),o=s.ssrc.find(e=>e.ssrc===r);o||(o=new lj({ssrc:r}),s.ssrc.push(o)),kO.includes(i)&&(o[i]=a)}break;case`ssrc-group`:ij(s.ssrcGroup,n);break;case`rid`:{let[e,t]=qD(n,` `);s.simulcastParameters.push(new cO({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]=rj(e);if(t===`fmtp`){let[e,t]=qD(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 aO({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=${ej(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)}})),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
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 oj(e,this.type)),this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}},ZA=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=${ej(this.host)}`),this.iceCandidates.forEach(t=>{e.push(`a=candidate:${tj(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:${EO[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} ${ej(this.rtcpHost)}`),this.rtcpMux&&e.push(`a=rtcp-mux`)),this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)}),this.ssrc.forEach(t=>{kO.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
141
+ `+t}toJSON(){let e=this.string;return(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type)&&(this.cachedJson=new Cj(e,this.type)),this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}},mj=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=${_j(this.host)}`),this.iceCandidates.forEach(t=>{e.push(`a=candidate:${vj(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:${UO[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} ${_j(this.rtcpHost)}`),this.rtcpMux&&e.push(`a=rtcp-mux`)),this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)}),this.ssrc.forEach(t=>{KO.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
- `}},QA=class{constructor(e,t){this.semantic=e,this.items=t}get str(){return`${this.semantic} ${this.items.join(` `)}`}};function $A(e){let t=e.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!t)throw Error(`exception`);return t[2]}function ej(e){return`IN IP${w(e)?4:6} ${e}`}function tj(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 nj(e){let t=[],n=[],r=e.split(`\r
143
+ `}},hj=class{constructor(e,t){this.semantic=e,this.items=t}get str(){return`${this.semantic} ${this.items.join(` `)}`}};function gj(e){let t=e.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!t)throw Error(`exception`);return t[2]}function _j(e){return`IN IP${w(e)?4:6} ${e}`}function vj(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 yj(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 rj(e){if(e.includes(`:`)){let t=qD(e.slice(2),`:`);return[t[0],t[1]]}return[e.slice(2),void 0]}function ij(e,t,n=e=>e.toString()){let r=t.split(` `);r.length>0&&e.push(new QA(r[0],r.slice(1).map(n)))}function aj(e){return Pk(pD.fromSdp(e))}var oj=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 sj(e,t){t.origin=`- ${c(8).readBigUInt64BE(0).toString().slice(0,8)} 0 IN IP4 0.0.0.0`,t.msidSemantic.push(new QA(`WMS`,[`*`])),t.type=e}function cj(e){let t={};return e.split(`;`).forEach(e=>{if(e.includes(`=`)){let[n,r]=qD(e,`=`);OO.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 lj=class{ssrc;cname;msid;msLabel;label;constructor(e){Object.assign(this,e)}},uj=Wx(`werift:packages/webrtc/src/media/rtpReceiver.ts`),dj=class{constructor(e,t,n){this.config=e,this.kind=t,this.rtcpSsrc=n,this.defaultTrack=new VO({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 mk(this);audioRedHandler=new Aw;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===nO().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===eO().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 gk(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=ek()-this.receiveLastSRTimestamp[e];t>0&&t<65536&&(r=Bx(t*65536))}return new KC({ssrc:Number(e),fractionLost:t.fraction_lost,packetsLost:t.packets_lost,highestSequence:t.max_seq,jitter:t.jitter,lsr:n,dlsr:r})}),t=new GC({ssrc:this.rtcpSsrc,reports:e});try{this.config.debug.receiverReportDelay&&await E(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([t])}catch(e){uj(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}getInboundRtpStatsId(e){return PO(`inbound-rtp`,e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return PO(`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?PO(`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?FO(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=IO(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),RO(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){uj(`pli not supported`,{mediaSsrc:e});return}if(this.stopped)return;uj(`sendRtcpPLI`,{mediaSsrc:e});let t=new WC({feedback:new VC({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1,await this.dtlsTransport.sendRtcp([t])}catch(e){uj(e)}}handleRtcpPacket(e){switch(e.type){case sw.type:{let t=e;this.lastSRtimestamp[t.ssrc]=rk(t.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[t.ssrc]=ek(),this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1,this.remoteTimestampsBySsrc[t.ssrc]=nk(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 _k(r.clockRate),this.remoteStreams[e.header.ssrc].add(e),this.receiverTWCC){let e=t[pw.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=cj(r.parameters??``),a=this.codecs[i.apt];if(e.payload.length<2)return;e=zw(e,a.payloadType,t),n=this.trackBySSRC[t]}let i;if(!(r.name.toLowerCase()===`red`&&(i=Ew.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()}}},fj=Wx(`werift:packages/webrtc/src/media/router.ts`),pj=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){fj(`registerRtpReceiver`,t),this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){fj(`registerRtpReceiverBySsrc`,t),t.encodings.filter(e=>e.ssrc!=null).forEach((n,r)=>{this.registerRtpReceiver(e.receiver,n.ssrc),e.addTrack(new VO({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;fj(`registerRtpReceiverByRid`,t),e.addTrack(new VO({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:!0,codec:r})),this.ridTable[t.rid]=e.receiver}routeRtp=e=>{let t=mw(e.header.extensions,this.extIdUriMap),n=this.ssrcTable[e.header.ssrc],r=t[pw.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 dj).find(t=>t.trackBySSRC[e.header.ssrc]),n&&(fj(`simulcast register receiver by ssrc`,e.header.ssrc),this.registerRtpReceiver(n,e.header.ssrc),n.handleRtpBySsrc(e,t))),!n){fj(`ssrcReceiver not found`);return}let i=t[pw.sdesMid];typeof i==`string`&&(n.sdesMid=i);let a=t[pw.repairedRtpStreamId];typeof a==`string`&&(n.latestRepairedRid=a)};routeRtcp=e=>{let t=[];switch(e.type){case sw.type:e=e,t.push(this.ssrcTable[e.ssrc]);break;case GC.type:e=e,e.reports.forEach(e=>{t.push(this.ssrcTable[e.ssrc])});break;case rw.type:break;case nw.type:{let n=e;n.feedback&&t.push(this.ssrcTable[n.feedback.mediaSourceSsrc])}break;case WC.type:{let n=e;switch(n.feedback.count){case HC.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))}},mj=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 LC(this.totalSize/e*8*1e3)}get sendBitrate(){let e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;return LC(this.totalSize/e*8*1e3)}},hj=20,gj=10,_j=class{congestion=!1;onAvailableBitrate=new $;onCongestion=new $;onCongestionScore=new $;congestionCounter=0;cumulativeResult=new mj;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=ZO()-this.cumulativeResult.firstPacketSentAtMs;t>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<hj?this.congestionCounter++:this.congestionScore<gj&&this.congestionScore++,this.congestionCounter>=hj&&!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>-hj){let e=LC(hj/2)+1,t=e-(e-(LC(hj/4)+1))/10*this.congestionScore;this.congestionCounter-=t}this.congestionCounter<=-hj&&(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}},vj=Wx(`werift:packages/webrtc/src/media/rtpSender.ts`),yj=128,bj=.85,xj=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 _j;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=dx();redRedundantPayloadType;_redDistance=2;redEncoder=new Ow(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=cj(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),vj(`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 sw({ssrc:this.ssrc,senderInfo:new cw({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=rk(this.ntpTimestamp),this.lastSentSRTimestamp=ek(),this.cname&&e.push(new rw({chunks:[new iw({source:this.ssrc,items:[new aw({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(e)}catch(e){vj(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:e,timestamp:t},n=!1){this.sequenceNumber!=null&&(this.seqOffset=Px(this.sequenceNumber,-e),n&&(this.seqOffset=Px(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=Fx(this.timestamp,-t),n&&(this.timestampOffset=Px(this.timestampOffset,1))),this.rtpCache=[],vj(`replaceRTP`,this.sequenceNumber,e,this.seqOffset)}async sendRtp(e){if(this.dtlsTransport.state!==`connected`||!this.codec)return;e=Buffer.isBuffer(e)?Rw.deSerialize(e):e;let{header:t,payload:n}=e;t.ssrc=this.ssrc,t.payloadType=this.codec.payloadType,t.timestamp=Fx(t.timestamp,this.timestampOffset),t.sequenceNumber=Px(t.sequenceNumber,this.seqOffset),this.timestamp=t.timestamp,this.sequenceNumber=t.sequenceNumber;let r=tk(),i=[...t.extensions];t.extensions=this.headerExtensions.map(e=>{let t=(()=>{switch(e.uri){case pw.sdesMid:return this.mid?hw(this.mid):void 0;case pw.sdesRTPStreamID:return this.rtpStreamId?gw(this.rtpStreamId):void 0;case pw.repairedRtpStreamId:return this.repairedRtpStreamId?_w(this.repairedRtpStreamId):void 0;case pw.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Px(this.dtlsTransport.transportSequenceNumber,1),vw(this.dtlsTransport.transportSequenceNumber);case pw.absSendTime:return yw(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=Fx(this.packetCount,1),this.rtpCache[t.sequenceNumber%yj]=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=ZO(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:s,sentAtMs:s};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(e){switch(e.type){case sw.type:case GC.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=ek()-this.lastSentSRTimestamp-e.dlsr/65536;this.totalRoundTripTime+=t,this.roundTripTimeMeasurements++,this.rtt=this.rtt===void 0?t:bj*this.rtt+(1-bj)*t}});break;case nw.type:{let t=e;switch(t.feedback.count){case XC.count:{let e=t.feedback;this.senderBWE.receiveTWCC(e)}break;case JC.count:{let e=t.feedback;this.nackCount++,e.lost.forEach(async e=>{let t=this.rtpCache[e%yj];t&&t.header.sequenceNumber!==e&&(t=void 0),t&&(this.rtxPayloadType!=null&&(t=Bw(t,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Px(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 WC.type:{let t=e;switch(t.feedback.count){case HC.count:{let e=t.feedback;this.receiverEstimatedMaxBitrate=e.bitrate}break;case VC.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 PO(`outbound-rtp`,this.trackId)}get mediaSourceStatsId(){return PO(`media-source`,this.trackId)}get remoteInboundRtpStatsId(){return PO(`remote-inbound-rtp`,this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){let t=[],n=this.dtlsTransport?PO(`transport`,this.dtlsTransport.id):void 0,r=this.codec&&n?FO(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=IO(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),RO(t,this.getStatsRootIds())}};function Sj(e,t=e){return new DOMException(t,e)}function Cj(e){return TypeError(e)}var wj=Wx(`werift:packages/webrtc/src/transport/sctpManager.ts`),Tj=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new $;constructor(){}createSctpTransport(e){let t=new qA(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=Ej(t.maxPacketLifeTime,`maxPacketLifeTime`),r=Ej(t.maxRetransmits,`maxRetransmits`),i={protocol:``,ordered:!0,negotiated:!1,...t,maxPacketLifeTime:n,maxRetransmits:r};if(i.maxPacketLifeTime!=null&&i.maxRetransmits!=null)throw Cj(`maxPacketLifeTime and maxRetransmits cannot both be set`);this.sctpTransport||=this.createSctpTransport();let a=new QD({id:i.id,label:e,maxPacketLifeTime:i.maxPacketLifeTime,maxRetransmits:i.maxRetransmits,negotiated:i.negotiated,ordered:i.ordered,protocol:i.protocol}),o=new ZD(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(),wj(`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=IO()){let t=[];for(let n of this.dataChannels){let r={type:`data-channel`,id:PO(`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 Ej(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw Cj(`${t} must be an unsigned short`);return n}var Dj=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 ZA(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 lj({ssrc:e.sender.ssrc,cname:this.cname})],e.options.simulcast&&(n.simulcastParameters=e.options.simulcast.map(e=>new cO(e))),n.rtp.codecs.find(e=>e.name.toLowerCase()===`rtx`)&&(n.ssrc.push(new lj({ssrc:e.sender.rtxSsrc,cname:this.cname})),n.ssrcGroup=[new QA(`FID`,[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]),this.addTransportDescription(n,e.dtlsTransport),n}createMediaDescriptionForSctp(e){let t=new ZA(`application`,TO,`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=wO,e.port=TO,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=XA.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 Sj(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-remote-offer`,`have-local-pranswer`].includes(n))throw Sj(`InvalidStateError`,`Cannot handle answer in signaling state`)}else if(r===`offer`){if(![`stable`,`have-remote-offer`,`have-local-offer`].includes(n))throw Sj(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-local-offer`,`have-remote-pranswer`].includes(n))throw Sj(`InvalidStateError`,`Cannot handle answer in signaling state`)}buildOfferSdp(e,t){let n=new XA;sj(`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 QA(`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 XA;sj(`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,YO(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 QA(`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 Sj(`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 Sj(`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)}},Oj=Wx(`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 Sk(e.keyPem,e.certPem,e.signatureHash)}createTransport(){let e=this.iceTransports.find(e=>e.state!==`closed`),t=ik(this.config.iceServers),n=ak({parsedTurnTransport:t.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP}),r=new Nk({...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 Mk(r);return i.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new xk(this.config,i,this.certificate,Aj)}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=Lk.fromJSON(t);if(!c)throw Sj(`OperationError`,`Failed to parse ICE candidate`);let l=s[0],u=e.media[l];if(!u)throw Sj(`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 Sj(`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 Sj(`OperationError`,`Media section for sdpMid was not found`);a=[t]}else if(typeof r==`number`){if(r<0||r>=e.media.length)throw Sj(`OperationError`,`Media section for sdpMLineIndex was not found`);a=[r]}else if(t)a=e.media.map((e,t)=>t);else throw Cj(`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 Sj(`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&&(Oj(`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?Oj(`skipping ICE gathering for bundled connection`):await Promise.allSettled(this.iceTransports.map(e=>e.gather())).catch(e=>{Oj(`gatherCandidates failed`,e)})}setConnectionState(e){this.connectionState!==e&&(Oj(`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 xk.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()}},Aj=[AO.SRTP_AEAD_AES_128_GCM,AO.SRTP_AES128_CM_HMAC_SHA1_80],jj=Wx(`werift:packages/webrtc/src/peerConnection.ts`),Mj=class extends JD{id=l().toString();cname=l().toString();config=Pj();signalingState=`stable`;negotiationneeded=!1;needRestart=!1;router=new pj;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 Dj({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new Vj(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 zj({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 Tj,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=Fj(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&&!Lj(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(dk(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 KD([...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 Rj(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 Sj(`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 Sj(`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 KD(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=YO(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 Sj(`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 XA&&(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 Sj(`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 Sj(`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:PO(`peer-connection`,this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){let t=IO(),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?RO(n,this.transceiverManager.getStatsRootIds(e)):RO(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()}},Nj=(e,t)=>e.find(e=>e.mimeType.toLowerCase()===t.mimeType.toLowerCase())?t:void 0;function Pj(){return{codecs:{audio:[pO(),mO()],video:[uO()]},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:KA}}Pj();function Fj(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 Cj(`certificates must be an array of RTCCertificate`);else n.certificates=[...t.certificates]}return`iceCandidatePoolSize`in t&&(n.iceCandidatePoolSize=Ij(t.iceCandidatePoolSize,`iceCandidatePoolSize`)),n}function Ij(e,t){let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw Cj(`${t} must be an unsigned short`);return n}function Lj(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Rj(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 zj=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}},Bj=Wx(`werift:packages/webrtc/src/media/rtpTransceiverManager.ts`),Vj=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 xj(e),o=new zO(r,t,new dj(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 Sj(`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 Sj(`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!!MO.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[cj(n.parameters??``).apt];return r&&e.ssrc.length===2&&(r.rtx=new oO({ssrc:e.ssrc[1].ssrc})),t}return t[n.payloadType]=new sO({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=Nj(n,e);if(!r)return!1;if(r?.name.toLowerCase()===`rtx`){let e=cj(r.parameters??``).apt,i=t.rtp.codecs.find(t=>t.payloadType===e);return i?!!Nj(n,i):!1}return!0}),Bj(`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=XO(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 HO({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 Hj(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 Uj(){let e=new Set,t=new WeakMap,n=!1,r;function i(n){let i=t.get(n);if(i)return i;let a=n.close();return t.set(n,a),a.then(()=>e.delete(n),t=>{r??=t,e.delete(n)}),a}return{createPeerConnection(t){if(n)throw Error(`Native room transport is closed`);let r=new Mj({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()=>i(e);if(t===`createDataChannel`)return(...t)=>Hj(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:Hj(e.channel)}),!0):Reflect.set(e,t,n,e)}})},async close(){if(n=!0,await Promise.all([...e].map(i)),r)throw r}}}function Wj(e){return zn(e)}function Gj(e){if(typeof e!=`string`)throw TypeError(`Stadium source must be a string`);let t=pn(e);return Object.freeze({name:t.name,canBeStored:t.canBeStored,warnings:Object.freeze([...t.warnings])})}async function Kj(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=vn(r??`https://ball2d.com`),s=vr(a),c=Uj(),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 _r.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===`/api/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(`/api/sdk/rooms`,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 re(o,i,e.id,e.lease,n,p)}return r}return fetch(e,t)},loadEngine:async e=>gn.create(await t(new URL(`./core.wasm`,import.meta.url),{signal:e})),loadStadium:xn(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(),xr(e,g)}catch(e){throw f?.close(),await d?.stop(),await c.close(),e}}export{Kj as createRoom,Wj as readReplay,Gj 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 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};