ball2d 0.2.1 → 0.2.2

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)}},oe=n(`/`),se;try{se=oe(`worker_threads`),se.Worker,se.isMarkedAsUntransferable}catch{}var ce=Uint8Array,le=Uint16Array,ue=Int32Array,de=new ce([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]),fe=new ce([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]),pe=new ce([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),me=function(e,t){for(var n=new le(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new ue(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}},se=me(de,2),he=se.b,ge=se.r;he[28]=258,ge[258]=28;for(var _e=me(fe,0),ve=_e.b,ye=_e.r,be=new le(32768),xe=0;xe<32768;++xe){var Se=(xe&43690)>>1|(xe&21845)<<1;Se=(Se&52428)>>2|(Se&13107)<<2,Se=(Se&61680)>>4|(Se&3855)<<4,be[xe]=((Se&65280)>>8|(Se&255)<<8)>>1}for(var Ce=(function(e,t,n){for(var r=e.length,i=0,a=new le(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new le(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new le(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[be[d]>>c]=l}else for(s=new le(r),i=0;i<r;++i)e[i]&&(s[i]=be[o[e[i]-1]++]>>15-e[i]);return s}),we=new ce(288),xe=0;xe<144;++xe)we[xe]=8;for(var xe=144;xe<256;++xe)we[xe]=9;for(var xe=256;xe<280;++xe)we[xe]=7;for(var xe=280;xe<288;++xe)we[xe]=8;for(var Te=new ce(32),xe=0;xe<32;++xe)Te[xe]=5;var Ee=Ce(we,9,0),De=Ce(we,9,1),Oe=Ce(Te,5,0),ke=Ce(Te,5,1),Ae=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},je=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Me=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Ne=function(e){return(e+7)/8|0},Pe=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new ce(e.subarray(t,n))},Fe=[`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`],Ie=function(e,t,n){var r=Error(t||Fe[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Ie),!n)throw r;return r},Le=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new ce(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new ce(i*3));var l=function(e){var t=n.length;if(e>t){var r=new ce(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=je(e,d,1);var v=je(e,d+1,3);if(d+=3,!v){var y=Ne(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&Ie(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=De,m=ke,h=9,g=5;else if(v==2){var S=je(e,d,31)+257,C=je(e,d+10,15)+4,w=S+je(e,d+5,31)+1;d+=14;for(var T=new ce(w),E=new ce(19),D=0;D<C;++D)E[pe[D]]=je(e,d+D*3,7);d+=C*3;for(var O=Ae(E),k=(1<<O)-1,A=Ce(E,O,1),D=0;D<w;){var j=A[je(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+je(e,d,3),d+=2,M=T[D-1]):y==17?(N=3+je(e,d,7),d+=3):y==18&&(N=11+je(e,d,127),d+=7);N--;)T[D++]=M}}var P=T.subarray(0,S),F=T.subarray(S);h=Ae(P),g=Ae(F),p=Ce(P,h,1),m=Ce(F,g,1)}else Ie(1);if(d>_){c&&Ie(0);break}}s&&l(f+131072);for(var I=(1<<h)-1,L=(1<<g)-1,R=d;;R=d){var M=p[Me(e,d)&I],z=M>>4;if(d+=M&15,d>_){c&&Ie(0);break}if(M||Ie(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=de[D];B=je(e,d,(1<<V)-1)+he[D],d+=V}var ee=m[Me(e,d)&L],te=ee>>4;ee||Ie(3),d+=ee&15;var F=ve[te];if(te>3){var V=fe[te];F+=Me(e,d)&(1<<V)-1,d+=V}if(d>_){c&&Ie(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&&Ie(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?Pe(n,0,f):n.subarray(0,f)},Re=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},ze=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},Be=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 ce(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 le(f+1),m=Ve(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 ce(p),l:m}},Ve=function(e,t,n){return e.s==-1?Math.max(Ve(e.l,t,n+1),Ve(e.r,t,n+1)):t[e.s]=n},He=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new le(++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}},Ue=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},We=function(e,t,n){var r=n.length,i=Ne(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},Ge=function(e,t,n,r,i,a,o,s,c,l,u){Re(t,u++,n),++i[256];for(var d=Be(i,15),f=d.t,p=d.l,m=Be(a,15),h=m.t,g=m.l,_=He(f),v=_.c,y=_.n,b=He(h),x=b.c,S=b.n,C=new le(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=Be(C,7),E=T.t,D=T.l,O=19;O>4&&!E[pe[O-1]];--O);var k=l+5<<3,A=Ue(i,we)+Ue(a,Te)+o,j=Ue(i,f)+Ue(a,h)+o+14+3*O+Ue(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&k<=A&&k<=j)return We(t,u,e.subarray(c,c+l));var M,N,P,F;if(Re(t,u,1+(j<A)),u+=2,j<A){M=Ce(f,p,0),N=f,P=Ce(h,g,0),F=h;var I=Ce(E,D,0);Re(t,u,y-257),Re(t,u+5,S-1),Re(t,u+10,O-4),u+=14;for(var w=0;w<O;++w)Re(t,u+3*w,E[pe[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;Re(t,u,I[B]),u+=E[B],B>15&&(Re(t,u,z[w]>>5&127),u+=z[w]>>12)}}else M=Ee,N=we,P=Oe,F=Te;for(var w=0;w<s;++w){var V=r[w];if(V>255){var B=V>>18&31;ze(t,u,M[B+257]),u+=N[B+257],B>7&&(Re(t,u,V>>23&31),u+=de[B]);var ee=V&31;ze(t,u,P[ee]),u+=F[ee],ee>3&&(ze(t,u,V>>5&8191),u+=fe[ee])}else ze(t,u,M[V]),u+=N[V]}return ze(t,u,M[256]),u+N[256]},Ke=new ue([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),qe=new ce(0),Je=function(e,t,n,r,i,a){var o=a.z||e.length,s=new ce(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=Ke[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new le(32768),g=a.h||new le(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new ue(25e3),x=new le(288),S=new le(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=Ge(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|ge[P]<<18|ye[F];var ie=ge[P]&31,ae=ye[F]&31;w+=de[ie]+fe[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=Ge(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=We(c,u+1,e.subarray(T,oe))}a.i=o}return Pe(s,0,r+Ne(u)+i)},Ye=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new ce(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return Je(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 Xe(e,t){return Ye(e,t||{},0,0)}var Ze=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 ce(32768),this.p=new ce(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||Ie(5),this.d&&Ie(4),!this.p.length)this.p=e;else if(e.length){var t=new ce(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=Le(this.p,this.s,this.o);this.ondata(Pe(n,t,this.s.b),this.d),this.o=Pe(n,this.s.b-32768),this.s.b=this.o.length,this.p=Pe(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),Qe=typeof TextDecoder<`u`&&new TextDecoder;try{Qe.decode(qe,{stream:!0})}catch{}var $e=5389,et=(e,t,n)=>Number.isInteger(e)&&e>=t&&e<=n,tt=e=>Number.isFinite(e)&&e>=1&&e<=1e5,nt=class{core;enabled=!1;constructor(e){if(this.core=e,e.surface_state_capacity()!==5389)throw Error(`Unsupported surface state version`)}configure(e){if(!et(e.seed,0,4294967295)||!tt(e.halfWidth)||!tt(e.halfHeight)||!et(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(!et(e.rainMilliMmH,0,2e5)||!et(e.temperatureMilliC,-3e4,6e4)||!et(e.humidityPermille,0,1e3)||!et(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=>et(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,$e)}},rt=131072,it=49152,at=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});var ot=(e,t)=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=t;function st(e,t){if(!ot(t,65535)||!ot(e.tick,4294967295)||!Array.isArray(e.surface)||e.surface.length!==5389)throw Error(`Invalid terrain snapshot`);let n=at.encode(JSON.stringify(e));if(n.length>rt)throw Error(`Terrain snapshot exceeds size limit`);let r=Xe(n,{level:1});if(r.length>it)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 ct(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 lt=new Set([`noPlayer`,`playerName`,`roomName`,`maxPlayers`,`password`,`public`,`stadium`]);function ut(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(!lt.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 dt(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 ft(e){let t=dt(e);if(!t)throw Error(`Invalid room code`);return`/r/${t}`}function pt(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 mt(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:pt(e.angle,e.textColor,e.colors))}var ht=[`normal`,`bold`,`italic`,`small`,`small-bold`,`small-italic`];function gt(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&&!ht.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 _t(e){return e===null||typeof e==`string`&&Array.from(e).length<=2&&!/[\p{Cc}\p{Cf}]/u.test(e)}var vt=[[`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 yt(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid disc property update`);let t=e,n={};for(let e=0;e<vt.length;e++){let[r,,i,a]=vt[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 bt=`5a27b77ea69c9f5e179f`,xt={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]/},St={isSpaceSeparator(e){return typeof e==`string`&&xt.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||xt.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===`‍`||xt.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)}},Ct,wt,Tt,Et,Dt,Ot,kt,At,jt,Mt=function(e,t){Ct=String(e),wt=`start`,Tt=[],Et=0,Dt=1,Ot=0,kt=void 0,At=void 0,jt=void 0;do kt=zt(),qt[wt]();while(kt.type!==`eof`);return typeof t==`function`?Nt({"":jt},``,t):jt};function Nt(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=Nt(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=Nt(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 Pt,Ft,It,Lt,Rt;function zt(){for(Pt=`default`,Ft=``,It=!1,Lt=1;;){Rt=Bt();let e=Vt[Pt]();if(e)return e}}function Bt(){if(Ct[Et])return String.fromCodePoint(Ct.codePointAt(Et))}function H(){let e=Bt();return e===`
2
+ `?(Dt++,Ot=0):e?Ot+=e.length:Ot++,e&&(Et+=e.length),e}var Vt={default(){switch(Rt){case` `:case`\v`:case`\f`:case` `:case`\xA0`:case``:case`
3
+ `:case`\r`:case`\u2028`:case`\u2029`:H();return;case`/`:H(),Pt=`comment`;return;case void 0:return H(),Ht(`eof`)}if(St.isSpaceSeparator(Rt)){H();return}return Vt[wt]()},comment(){switch(Rt){case`*`:H(),Pt=`multiLineComment`;return;case`/`:H(),Pt=`singleLineComment`;return}throw Xt(H())},multiLineComment(){switch(Rt){case`*`:H(),Pt=`multiLineCommentAsterisk`;return;case void 0:throw Xt(H())}H()},multiLineCommentAsterisk(){switch(Rt){case`*`:H();return;case`/`:H(),Pt=`default`;return;case void 0:throw Xt(H())}H(),Pt=`multiLineComment`},singleLineComment(){switch(Rt){case`
4
+ `:case`\r`:case`\u2028`:case`\u2029`:H(),Pt=`default`;return;case void 0:return H(),Ht(`eof`)}H()},value(){switch(Rt){case`{`:case`[`:return Ht(`punctuator`,H());case`n`:return H(),Ut(`ull`),Ht(`null`,null);case`t`:return H(),Ut(`rue`),Ht(`boolean`,!0);case`f`:return H(),Ut(`alse`),Ht(`boolean`,!1);case`-`:case`+`:H()===`-`&&(Lt=-1),Pt=`sign`;return;case`.`:Ft=H(),Pt=`decimalPointLeading`;return;case`0`:Ft=H(),Pt=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Ft=H(),Pt=`decimalInteger`;return;case`I`:return H(),Ut(`nfinity`),Ht(`numeric`,1/0);case`N`:return H(),Ut(`aN`),Ht(`numeric`,NaN);case`"`:case`'`:It=H()===`"`,Ft=``,Pt=`string`;return}throw Xt(H())},identifierNameStartEscape(){if(Rt!==`u`)throw Xt(H());H();let e=Kt();switch(e){case`$`:case`_`:break;default:if(!St.isIdStartChar(e))throw Qt()}Ft+=e,Pt=`identifierName`},identifierName(){switch(Rt){case`$`:case`_`:case`‌`:case`‍`:Ft+=H();return;case`\\`:H(),Pt=`identifierNameEscape`;return}if(St.isIdContinueChar(Rt)){Ft+=H();return}return Ht(`identifier`,Ft)},identifierNameEscape(){if(Rt!==`u`)throw Xt(H());H();let e=Kt();switch(e){case`$`:case`_`:case`‌`:case`‍`:break;default:if(!St.isIdContinueChar(e))throw Qt()}Ft+=e,Pt=`identifierName`},sign(){switch(Rt){case`.`:Ft=H(),Pt=`decimalPointLeading`;return;case`0`:Ft=H(),Pt=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:Ft=H(),Pt=`decimalInteger`;return;case`I`:return H(),Ut(`nfinity`),Ht(`numeric`,Lt*(1/0));case`N`:return H(),Ut(`aN`),Ht(`numeric`,NaN)}throw Xt(H())},zero(){switch(Rt){case`.`:Ft+=H(),Pt=`decimalPoint`;return;case`e`:case`E`:Ft+=H(),Pt=`decimalExponent`;return;case`x`:case`X`:Ft+=H(),Pt=`hexadecimal`;return}return Ht(`numeric`,Lt*0)},decimalInteger(){switch(Rt){case`.`:Ft+=H(),Pt=`decimalPoint`;return;case`e`:case`E`:Ft+=H(),Pt=`decimalExponent`;return}if(St.isDigit(Rt)){Ft+=H();return}return Ht(`numeric`,Lt*Number(Ft))},decimalPointLeading(){if(St.isDigit(Rt)){Ft+=H(),Pt=`decimalFraction`;return}throw Xt(H())},decimalPoint(){switch(Rt){case`e`:case`E`:Ft+=H(),Pt=`decimalExponent`;return}if(St.isDigit(Rt)){Ft+=H(),Pt=`decimalFraction`;return}return Ht(`numeric`,Lt*Number(Ft))},decimalFraction(){switch(Rt){case`e`:case`E`:Ft+=H(),Pt=`decimalExponent`;return}if(St.isDigit(Rt)){Ft+=H();return}return Ht(`numeric`,Lt*Number(Ft))},decimalExponent(){switch(Rt){case`+`:case`-`:Ft+=H(),Pt=`decimalExponentSign`;return}if(St.isDigit(Rt)){Ft+=H(),Pt=`decimalExponentInteger`;return}throw Xt(H())},decimalExponentSign(){if(St.isDigit(Rt)){Ft+=H(),Pt=`decimalExponentInteger`;return}throw Xt(H())},decimalExponentInteger(){if(St.isDigit(Rt)){Ft+=H();return}return Ht(`numeric`,Lt*Number(Ft))},hexadecimal(){if(St.isHexDigit(Rt)){Ft+=H(),Pt=`hexadecimalInteger`;return}throw Xt(H())},hexadecimalInteger(){if(St.isHexDigit(Rt)){Ft+=H();return}return Ht(`numeric`,Lt*Number(Ft))},string(){switch(Rt){case`\\`:H(),Ft+=Wt();return;case`"`:if(It)return H(),Ht(`string`,Ft);Ft+=H();return;case`'`:if(!It)return H(),Ht(`string`,Ft);Ft+=H();return;case`
5
+ `:case`\r`:throw Xt(H());case`\u2028`:case`\u2029`:$t(Rt);break;case void 0:throw Xt(H())}Ft+=H()},start(){switch(Rt){case`{`:case`[`:return Ht(`punctuator`,H())}Pt=`value`},beforePropertyName(){switch(Rt){case`$`:case`_`:Ft=H(),Pt=`identifierName`;return;case`\\`:H(),Pt=`identifierNameStartEscape`;return;case`}`:return Ht(`punctuator`,H());case`"`:case`'`:It=H()===`"`,Pt=`string`;return}if(St.isIdStartChar(Rt)){Ft+=H(),Pt=`identifierName`;return}throw Xt(H())},afterPropertyName(){if(Rt===`:`)return Ht(`punctuator`,H());throw Xt(H())},beforePropertyValue(){Pt=`value`},afterPropertyValue(){switch(Rt){case`,`:case`}`:return Ht(`punctuator`,H())}throw Xt(H())},beforeArrayValue(){if(Rt===`]`)return Ht(`punctuator`,H());Pt=`value`},afterArrayValue(){switch(Rt){case`,`:case`]`:return Ht(`punctuator`,H())}throw Xt(H())},end(){throw Xt(H())}};function Ht(e,t){return{type:e,value:t,line:Dt,column:Ot}}function Ut(e){for(let t of e){if(Bt()!==t)throw Xt(H());H()}}function Wt(){switch(Bt()){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(),St.isDigit(Bt()))throw Xt(H());return`\0`;case`x`:return H(),Gt();case`u`:return H(),Kt();case`
7
+ `:case`\u2028`:case`\u2029`:return H(),``;case`\r`:return H(),Bt()===`
8
+ `&&H(),``;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:throw Xt(H());case void 0:throw Xt(H())}return H()}function Gt(){let e=``,t=Bt();if(!St.isHexDigit(t)||(e+=H(),t=Bt(),!St.isHexDigit(t)))throw Xt(H());return e+=H(),String.fromCodePoint(parseInt(e,16))}function Kt(){let e=``,t=4;for(;t-->0;){let t=Bt();if(!St.isHexDigit(t))throw Xt(H());e+=H()}return String.fromCodePoint(parseInt(e,16))}var qt={start(){if(kt.type===`eof`)throw Zt();Jt()},beforePropertyName(){switch(kt.type){case`identifier`:case`string`:At=kt.value,wt=`afterPropertyName`;return;case`punctuator`:Yt();return;case`eof`:throw Zt()}},afterPropertyName(){if(kt.type===`eof`)throw Zt();wt=`beforePropertyValue`},beforePropertyValue(){if(kt.type===`eof`)throw Zt();Jt()},beforeArrayValue(){if(kt.type===`eof`)throw Zt();if(kt.type===`punctuator`&&kt.value===`]`){Yt();return}Jt()},afterPropertyValue(){if(kt.type===`eof`)throw Zt();switch(kt.value){case`,`:wt=`beforePropertyName`;return;case`}`:Yt()}},afterArrayValue(){if(kt.type===`eof`)throw Zt();switch(kt.value){case`,`:wt=`beforeArrayValue`;return;case`]`:Yt()}},end(){}};function Jt(){let e;switch(kt.type){case`punctuator`:switch(kt.value){case`{`:e={};break;case`[`:e=[]}break;case`null`:case`boolean`:case`numeric`:case`string`:e=kt.value}if(jt===void 0)jt=e;else{let t=Tt[Tt.length-1];Array.isArray(t)?t.push(e):Object.defineProperty(t,At,{value:e,writable:!0,enumerable:!0,configurable:!0})}if(typeof e==`object`&&e)Tt.push(e),wt=Array.isArray(e)?`beforeArrayValue`:`beforePropertyName`;else{let e=Tt[Tt.length-1];wt=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}}function Yt(){Tt.pop();let e=Tt[Tt.length-1];wt=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}function Xt(e){return tn(e===void 0?`JSON5: invalid end of input at ${Dt}:${Ot}`:`JSON5: invalid character '${en(e)}' at ${Dt}:${Ot}`)}function Zt(){return tn(`JSON5: invalid end of input at ${Dt}:${Ot}`)}function Qt(){return Ot-=5,tn(`JSON5: invalid identifier character at ${Dt}:${Ot}`)}function $t(e){console.warn(`JSON5: '${en(e)}' in strings is not valid ECMAScript; consider escaping`)}function en(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 tn(e){let t=SyntaxError(e);return t.lineNumber=Dt,t.columnNumber=Ot,t}var nn={parse:Mt,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(St.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(!St.isIdStartChar(t))return u(e,!0);for(let n=t.length;n<e.length;n++)if(!St.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}}},rn={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},an=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Expected an object`);return e},on=(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},sn=(e,t=[0,0])=>{if(e===void 0)return[...t];if(!Array.isArray(e)||e.length!==2)throw Error(`Expected [x, y]`);return[on(e[0],0),on(e[1],0)]},cn=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e)||e.length>t)throw Error(`Array limit: ${t}`);return e};function ln(e,t){return e===void 0?t:typeof e==`number`?on(e,t,-2147483648,4294967295)|0:cn(e,16).reduce((e,t)=>{if(typeof t!=`string`||!Object.hasOwn(rn,t))throw Error(`Unknown collision flag`);return e|rn[t]},0)}function un(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(on(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 dn=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(` `))])),fn=new Set([`vertexes`,`segments`,`discs`,`planes`,`goals`,`joints`,`playerPhysics`].flatMap(e=>[...dn[e]]));function pn(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,dn.root,`$`),r(e.bg,dn.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,dn[t],`$.${t}[${n}]`)})}if(r(e.ballPhysics,dn.discs,`$.ballPhysics`),r(e.playerPhysics,dn.playerPhysics,`$.playerPhysics`),e.traits&&typeof e.traits==`object`&&!Array.isArray(e.traits))for(let[t,i]of Object.entries(e.traits))r(i,fn,n(`$.traits`,t));return t}function mn(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 hn(e){if(new TextEncoder().encode(e).length>262144)throw Error(`Stadium exceeds 256 KB`);let t=an(nn.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?{}:an(t.traits),i=e=>{let t=an(e);if(t.trait===void 0)return t;if(typeof t.trait!=`string`||!Object.hasOwn(r,t.trait))throw Error(`Unknown trait`);return{...an(r[t.trait]),...t}},a=(e,t=!1)=>({pos:sn(e.pos),speed:sn(e.speed),gravity:sn(e.gravity),radius:on(e.radius,10,.5,100),invMass:on(e.invMass,1,0,8192),damping:on(e.damping,.99,0,8192),bCoef:on(e.bCoef,.5,-1,8192),cGroup:ln(e.cGroup,t?193:63),cMask:ln(e.cMask,63),color:un(e.color)}),o=cn(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=cn(t.vertexes,1024).map(e=>i(e)),c=[],l=[],u=pn(t);for(let e of s)c.push({a:[on(e.x,0),on(e.y,0)],b:[on(e.x,0),on(e.y,0)],bCoef:on(e.bCoef,1,-1,8192),cGroup:ln(e.cGroup,32),cMask:ln(e.cMask,63),bias:0,color:`transparent`,vis:!1});let d=[...c];for(let e of cn(t.segments,1024)){let t=i(e),n=on(t.v0,-1,0,s.length-1),r=on(t.v1,-1,0,s.length-1);if(!Number.isInteger(n)||!Number.isInteger(r))throw Error(`Vertex indices must be integers`);let a=[on(s[n].x,0),on(s[n].y,0)],o=[on(s[r].x,0),on(s[r].y,0)],u={bCoef:on(t.bCoef,1,-1,8192),cGroup:ln(t.cGroup,32),cMask:ln(t.cMask,63),bias:on(t.bias,0,-100,100),color:un(t.color,`000000`),vis:t.vis!==!1},f=t.curveF===void 0?on(t.curve,0,-359,359):2*Math.atan2(1,on(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:on(f.acceleration,.1,-8192,8192),kickingAcceleration:on(f.kickingAcceleration,.07,-8192,8192),kickingDamping:on(f.kickingDamping,.96,0,8192),kickStrength:on(f.kickStrength,5,-8192,8192),kickback:on(f.kickback,0,-8192,8192)};mn(n,o.length,c.length,cn(t.planes,64).length+cn(t.joints,128).length,Math.min(p.radius,...o.map(e=>e.radius)));let m=t.bg===void 0?{}:an(t.bg);return{version:1,physicsMode:n,name:typeof t.name==`string`?t.name.slice(0,64):`Untitled stadium`,canBeStored:t.canBeStored!==!1,width:on(t.width,520,100,2048),height:on(t.height,300,80,2048),maxViewWidth:on(t.maxViewWidth,0,0,4096),cameraFollow:t.cameraFollow===`player`?`player`:`ball`,bg:{type:m.type===`grass`?`grass`:m.type===`hockey`?`hockey`:`none`,cornerRadius:on(m.cornerRadius,0,0,500),goalLine:on(m.goalLine,0,0,2048),width:on(m.width,0,0,2048),height:on(m.height,0,0,2048),color:un(m.color,`718C5A`),kickOffRadius:on(m.kickOffRadius,0,0,500)},discs:o,segments:c,arcs:l,colliders:d,player:p,spawnDistance:on(t.spawnDistance,200,0,1500),kickOffReset:t.kickOffReset===`full`?`full`:`partial`,redSpawnPoints:cn(t.redSpawnPoints,32).map(e=>sn(e)),blueSpawnPoints:cn(t.blueSpawnPoints,32).map(e=>sn(e)),warnings:u,planes:cn(t.planes,64).map(e=>{let t=i(e),n=sn(t.normal);if(Math.hypot(...n)<1e-6)throw Error(`Plane normal is zero`);return{normal:n,dist:on(t.dist,0),bCoef:on(t.bCoef,1,-1,8192),cGroup:ln(t.cGroup,32),cMask:ln(t.cMask,63)}}),goals:cn(t.goals,16).map(e=>{let t=i(e);if(t.team!==`red`&&t.team!==`blue`)throw Error(`Invalid goal team`);let n=sn(t.p0),r=sn(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:cn(t.joints,128).map(e=>{let t=i(e),n=on(t.d0,-1,0,o.length-1),r=on(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]:sn(t.length);return{d0:n,d1:r,min:on(s[0],0,0),max:on(s[1],0,0),strength:t.strength===void 0||t.strength===`rigid`?`rigid`:on(t.strength,0,-8192,8192),color:un(t.color,`000000`)}})}}function gn(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 _n=`ball2d-core/1/${bt}`,vn=32,yn=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=bn(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 nt(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=hn(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<vn;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>=vn)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=yt(t),i=!1;for(let[t,a]of vt){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]));mn(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 vt){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<vn;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<vn;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]);mn(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 bn(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 xn(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 Sn(){return{serviceOrigin:location.origin,signalingResume:!0,createWebSocket:e=>new WebSocket(e),createPeerConnection:e=>new RTCPeerConnection(e)}}var Cn=[[`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 wn(e){let t=new Map;return async n=>{let r=Cn.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 hn(n),n})(),t.set(r[0],i),i.catch(()=>t.delete(r[0]))),i}}function Tn(){let e=Sn(),t=(e,t)=>fetch(e,t);return{network:e,request:t,loadEngine:e=>yn.create(void 0,e),loadStadium:wn(n=>t(new URL(n,e.serviceOrigin)))}}var En={message:{burst:240,perSecond:160},action:{burst:12,perSecond:6},chat:{burst:4,perSecond:1}},Dn=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}=En[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()}},On=33554432,kn=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});function An(e){let t=2166136261;for(let n of e)t=Math.imul(t^n,16777619);return t>>>0}function jn(e){if(e.length>33554432)throw Error(`Replay exceeds 32 MB`);let t=Xe(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,An(e),!0),n.set(t,16),n}function Mn(e){if(typeof e==`string`){if(kn.encode(e).length>33554432)throw Error(`Replay exceeds 32 MB`);return kn.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 Ze((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||An(i)!==n.getUint32(12,!0))throw Error(`Compressed replay integrity failure`);return i}var Nn=[`input`,`team`,`start`,`stop`,`pause`,`scoreLimit`,`timeLimit`,`kickRate`,`join`,`disc`,`surface`],Pn=new TextEncoder,Fn=new TextDecoder(`utf-8`,{fatal:!0});function In(e){return jn(Ln(e))}function Ln(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=Pn.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(On,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=Nn.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=yt(e.properties),n=0;vt.forEach(([e],r)=>{t[e]!==void 0&&(n|=1<<r)}),p(n);for(let[e]of vt){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 Rn(e){let t=Mn(e);if(t[0]!==66||t[1]!==50||t[2]!==68||t[3]!==80)return JSON.parse(Fn.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(Fn.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=Nn[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={};vt.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:yt(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 zn(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 Bn(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 Vn=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:_n,stadium:e.source,initial:r,commands:[],checkpoints:[],roster:t.map(e=>({...e,tick:r.tick})),styles:[{tick:r.tick,teams:mt(n)}],orders:[{tick:r.tick,slots:[...this.playerOrder]}],end:r.tick,finalHash:zn(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:mt(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:yt(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:zn(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=zn(e.snapshot()),Ln(this.replay)}finish(e){return this.replay.end=e.tick,this.replay.finalHash=zn(e.snapshot()),new Blob([In(this.replay)],{type:`application/x-ball2d-replay`})}};async function Hn(e){if(e.size>33554432)throw Error(`Replay exceeds 32 MB`);return Un(await e.arrayBuffer())}function Un(e){let t=Rn(e);if(t.magic!==`B2DR`||t.version!==1||t.engine!==_n)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=yt(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&&!_t(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=mt(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 Wn=e=>Number.isSafeInteger(e)&&e>0&&e<=9e4,Gn=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,!Wn(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&&!Wn(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`||!Wn(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{}}},Kn=2,qn=9e4,Jn=33;function Yn(e,t){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}var Xn=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),Zn=e=>typeof e==`string`&&/^[0-9a-f]{64}$/.test(e),Qn=(e,t)=>Number.isSafeInteger(e)&&e>=t,$n=e=>Qn(e,1)&&e<=qn,er=e=>e===`host`||e===`guest`;function tr(e){return!Yn(e,[`version`,`roomGeneration`,`secret`,`connectionEpoch`,`membershipValidForMs`])||e.version!==Kn||!Xn(e.roomGeneration)||!Zn(e.secret)||!Qn(e.connectionEpoch,1)||!$n(e.membershipValidForMs)?null:{version:2,roomGeneration:e.roomGeneration,secret:e.secret,connectionEpoch:e.connectionEpoch,membershipValidForMs:e.membershipValidForMs}}function nr(e){if(!Yn(e,[`type`,`version`,`roomGeneration`,`attemptId`,`id`,`hostId`,`role`,`connectionEpoch`,`membershipValidForMs`,`rosterRevision`,`members`,`requireVerification`,`locked`])||e.type!==`resumed`||e.version!==Kn||!Xn(e.roomGeneration)||!Xn(e.attemptId)||!Xn(e.id)||!Xn(e.hostId)||!er(e.role)||!Qn(e.connectionEpoch,1)||!$n(e.membershipValidForMs)||!Qn(e.rosterRevision,0)||typeof e.requireVerification!=`boolean`||typeof e.locked!=`boolean`||!Array.isArray(e.members)||e.members.length<1||e.members.length>Jn)return null;let t=ir(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 rr(e){if(!Yn(e,[`type`,`id`,`hostId`,`role`,`resumeGrant`,`rosterRevision`,`members`,`requireVerification`,`locked`])||e.type!==`ready`)return null;let t=tr(e.resumeGrant);if(!t)return null;let n=nr({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 ir(e,t){if(!Array.isArray(e)||e.length<1||e.length>Jn)return null;let n=[],r=new Set;for(let t of e){if(!Yn(t,[`id`,`role`,`attached`,`connectionEpoch`])||!Xn(t.id)||!er(t.role)||typeof t.attached!=`boolean`||!Qn(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 ar(e){if(!Yn(e,[`type`,`roomGeneration`,`hostId`,`rosterRevision`,`members`])||e.type!==`roster`||!Xn(e.roomGeneration)||!Xn(e.hostId)||!Qn(e.rosterRevision,0))return null;let t=ir(e.members,e.hostId);return t?{type:`roster`,roomGeneration:e.roomGeneration,hostId:e.hostId,rosterRevision:e.rosterRevision,members:t}:null}function or(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 sr=524288,cr=16384,lr=12;function ur(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>sr)throw Error(`Control message exceeds 512 KB`);if(r.length<=cr)return[n];let i=Math.ceil(r.length/cr),a=[];for(let e=0;e<i;e++){let n=r.subarray(e*cr,(e+1)*cr),o=new ArrayBuffer(lr+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,lr).set(n),a.push(o)}return a}var dr=class{partial;push(e,t=performance.now()){if(typeof e==`string`){if(this.partial||new TextEncoder().encode(e).length>cr)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-lr,o.bytes>sr)throw Error(`Control size limit`);if(o.parts.push(new Uint8Array(e.slice(lr))),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))}},fr=class extends Error{},pr=1,mr=e=>typeof e==`string`&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(e),hr=e=>Number.isSafeInteger(e)&&e>0,gr=e=>e?.match(/(?:^|\r?\n)a=ice-ufrag:([^\s]+)/)?.[1],_r=e=>e.usernameFragment??e.candidate?.match(/(?:^| )ufrag ([^ ]+)/)?.[1],vr=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===pr&&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!==pr?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!==pr?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 fr(e):Error(e)))}updateBan(e,t){return this.closed||!this.host||!this.signalingAdmitted||this.ws.readyState!==pr?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=Sn()){this.room=e,this.credentials=t,this.hooks=n,this.runtime=r;let i=new URL(re.signal(e),xn(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===pr&&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 Gn({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),xn(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===pr&&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=nr(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||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=ar(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!==pr)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=rr(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(!mr(e.id)||!hr(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&&(!mr(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(!mr(e.negotiationId))return;if(e.signal.type===`offer`){if(this.host||!gr(e.signal.sdp))return;n.negotiationId!==e.negotiationId&&(n.candidates=[]),this.beginNegotiation(n,e.negotiationId),n.remoteIceUfrag=gr(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(!gr(e.signal.sdp))return;n.remoteIceUfrag=gr(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=gr(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&&(!_r(e.signal.candidate)||n.remoteIceUfrag&&_r(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.`)})}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=gr(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.`)}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&&_r(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!==pr)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=gr(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.`),!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&&_r(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 dr,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=ur(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=or(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===pr&&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()}}},yr=5;function br(e,t){return e!==t&&e-t>>>0<2147483648}function xr(e){if(e.byteLength!==14)throw Error(`Input length`);let t=new DataView(e);if(t.getUint8(0)!==1||t.getUint8(1)!==yr||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 Sr(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,yr),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 Cr=Object.freeze({...rn}),wr=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 Dn;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=Tn(),r){let i=xn(n.network.serviceOrigin);if(t=ut(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=ct(r),c;try{s.signal.throwIfAborted();let r=await s.run(n.loadEngine(s.signal));r.load(t.stadium??gn()),c=new e(r,n);let l=c,u=await s.run(n.request(new URL(re.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}${ft(d.id)}`;let f;try{await s.run(new Promise((e,t)=>{f=setTimeout(()=>t(Error(`Signaling timed out`)),12e3),l.network=new vr(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=st(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 Sr(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!==_n||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:_n,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`&&_t(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}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:pt(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=xr(t);if(r.epoch!==this.epoch)return;let i=this.inputs.get(e.id);(!i||br(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`);Bn(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,pt(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(!_t(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 fr&&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=gt(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=bn(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;hn(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 Cr}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=yt(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`);Bn(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 Vn(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 Tr(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 ut({...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 Er=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)}},Dr=`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 Or(e,t){let n=Object.create(null);t&&Object.defineProperty(n,"closed",{enumerable:!0,value:t});let r=new Er(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 Dr)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 kr=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`:``)}})),Ar=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=kr(),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})),jr=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=Ar()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Mr=z({createSupportsColor:()=>Lr,default:()=>Br});function Nr(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 Pr(){if(!(`FORCE_COLOR`in Rr))return;if(Rr.FORCE_COLOR===`true`)return 1;if(Rr.FORCE_COLOR===`false`)return 0;if(Rr.FORCE_COLOR.length===0)return 1;let e=Math.min(Number.parseInt(Rr.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}function Fr(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Ir(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Pr();r!==void 0&&(zr=r);let i=n?zr:r;if(i===0)return 0;if(n){if(Nr(`color=16m`)||Nr(`color=full`)||Nr(`color=truecolor`))return 3;if(Nr(`color=256`))return 2}if(`TF_BUILD`in Rr&&`AGENT_NAME`in Rr)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(Rr.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 Rr)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in Rr)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in Rr)||Rr.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in Rr)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Rr.TEAMCITY_VERSION);if(Rr.COLORTERM===`truecolor`||Rr.TERM===`xterm-kitty`||Rr.TERM===`xterm-ghostty`||Rr.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in Rr){let e=Number.parseInt((Rr.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(Rr.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(Rr.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Rr.TERM)||`COLORTERM`in Rr?1:a}function Lr(e,t={}){return Fr(Ir(e,{streamIsTTY:e&&e.isTTY,...t}))}var Rr,zr,Br,Vr=L((()=>{({env:Rr}=p),Nr(`no-color`)||Nr(`no-colors`)||Nr(`color=false`)||Nr(`color=never`)?zr=0:(Nr(`color`)||Nr(`colors`)||Nr(`color=true`)||Nr(`color=always`))&&(zr=1),Br={stdout:Lr({isTTY:g.isatty(1)}),stderr:Lr({isTTY:g.isatty(2)})}})),Hr=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=(Vr(),ee(Mr));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=Ar()(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)}})),Ur=R(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?jr():Hr()})),Wr=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`)})),Gr=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||{})})),Kr=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}}})),qr=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}})),Jr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=Kr(),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}})),Yr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferVisitor=Kr().BufferVisitor,e.PEM=qr().PEM;var t=Jr();e.ASN1=t.ASN1,e.Class=t.Class,e.Tag=t.Tag,e.BitString=t.BitString})),Xr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=te(`crypto`),r=Gr(),i=Yr(),a=Wr();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))})})),Zr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=te(`util`),n=te(`crypto`),r=Yr(),i=Wr(),a=Xr(),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}})),Qr=R((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Wr();e.bytesFromIP=t.bytesFromIP,e.bytesToIP=t.bytesToIP,e.getOID=t.getOID,e.getOIDName=t.getOIDName;var n=Xr();e.PublicKey=n.PublicKey,e.PrivateKey=n.PrivateKey,e.RSAPublicKey=n.RSAPublicKey,e.RSAPrivateKey=n.RSAPrivateKey;var r=Zr();e.Certificate=r.Certificate,e.DistinguishedName=r.DistinguishedName})),$r=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||={})})),ei=V(Ur(),1),ti=Qr();$r();var ni=`[object ArrayBuffer]`,U=class e{static isArrayBuffer(e){return Object.prototype.toString.call(e)===ni}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}},ri=`string`,ii=/^[0-9a-f\s]+$/i,ai=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,oi=/^[a-zA-Z0-9-_]+$/,si=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))}},ci=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}},li=class e{static isHex(e){return typeof e===ri&&ii.test(e)}static isBase64(e){return typeof e===ri&&ai.test(e)}static isBase64Url(e){return typeof e===ri&&oi.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 ci.toString(n,!0);case`utf16`:case`utf16be`:return ci.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 ci.fromString(e,!0);case`utf16`:case`utf16be`:return ci.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 si.fromString(t);case`utf16`:case`utf16be`:return ci.fromString(t);case`utf16le`:case`usc2`:return ci.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 si.toString(t);case`utf16`:case`utf16be`:return ci.toString(t);case`utf16le`:case`usc2`:return ci.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 ci.toString(e,t)}static FromUtf16String(e,t=!1){return ci.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,``)||``}};li.DEFAULT_UTF8_ENCODING=`utf8`;function ui(...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 di(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 fi(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 pi(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 mi(...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 hi(){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=fi(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,fi(a,8)-r}function gi(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=pi(n-t,8,r),i=new Uint8Array(e);return i[0]|=128,e}let i=pi(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 _i(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 vi(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 yi=z({Any:()=>Ho,BaseBlock:()=>qi,BaseStringBlock:()=>Yi,BitString:()=>ka,BmpString:()=>ao,Boolean:()=>Ca,CharacterString:()=>Do,Choice:()=>Uo,Constructed:()=>ha,DATE:()=>No,DEFAULT_MAX_CONTENT_LENGTH:()=>ea,DEFAULT_MAX_DEPTH:()=>100,DEFAULT_MAX_NODES:()=>$i,DateTime:()=>Lo,Duration:()=>zo,EndOfContent:()=>va,Enumerated:()=>Ra,GeneralString:()=>To,GeneralizedTime:()=>jo,GraphicString:()=>xo,HexBlock:()=>Hi,IA5String:()=>yo,Integer:()=>Ia,Null:()=>ba,NumericString:()=>uo,ObjectIdentifier:()=>Ha,OctetString:()=>Ea,Primitive:()=>Qi,PrintableString:()=>po,RawData:()=>Go,RelativeObjectIdentifier:()=>Ka,Repeated:()=>Wo,Sequence:()=>Ja,Set:()=>Xa,TIME:()=>Vo,TeletexString:()=>ho,TimeOfDay:()=>Fo,UTCTime:()=>ko,UniversalString:()=>co,Utf8String:()=>no,ValueBlock:()=>Wi,VideotexString:()=>_o,ViewWriter:()=>Ci,VisibleString:()=>Co,compareSchema:()=>Ko,fromBER:()=>da,verifySchema:()=>qo});function bi(){if(typeof BigInt>`u`)throw Error(`BigInt is not defined. Your environment doesn't implement BigInt.`)}function xi(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 Si(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 Ci=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return xi(this.items)}},wi=[new Uint8Array([1])],Ti=`0123456789`,Ei=`name`,Di=`valueHexView`,Oi=`isHexOnly`,ki=`idBlock`,Ai=`tagClass`,ji=`tagNumber`,Mi=`isConstructed`,Ni=`fromBER`,Pi=`toBER`,Fi=`local`,Ii=``,Li=new ArrayBuffer(0),Ri=new Uint8Array,zi=`EndOfContent`,Bi=`OCTET STRING`,Vi=`BIT STRING`;function Hi(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):Ri}fromBER(e,t,n,r){let i=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Si(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`,Li)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:li.ToHex(this.valueHexView)}}};return t.NAME=`hexBlock`,t}var Ui=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=Ii,warnings:n=[],valueBeforeDecode:r=Ri}={}){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:li.ToHex(this.valueBeforeDecodeView)}}};Ui.NAME=`baseBlock`;var Wi=class extends Ui{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'`)}};Wi.NAME=`valueBlock`;var Gi=class extends Hi(Ui){constructor({idBlock:e={}}={}){super(),e?(this.isHexOnly=e.isHexOnly??!1,this.valueHexView=e.valueHex?U.toUint8Array(e.valueHex):Ri,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`,Li}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=pi(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(!Si(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=fi(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}}};Gi.NAME=`identificationBlock`;var Ki=class extends Ui{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(!Si(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=fi(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=pi(this.length,8);if(r.byteLength>127)return this.error=`Too big length`,Li;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}}};Ki.NAME=`lengthBlock`;var W={},qi=class extends Ui{constructor({name:e=Ii,optional:t=!1,primitiveSchema:n,...r}={},i){super(r),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Gi(r),this.lenBlock=new Ki(r),this.valueBlock=i?new i(r):new Wi(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 Ci;t||Ji(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?Li: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():li.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${li.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&_i(this.toBER(),e.toBER())}};qi.NAME=`BaseBlock`;function Ji(e){if(e instanceof W.Constructed)for(let t of e.valueBlock.value)Ji(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock?.isIndefiniteForm}var Yi=class extends qi{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Ii,...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}'`}};Yi.NAME=`BaseStringBlock`;var Xi=class extends Hi(Wi){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Xi.NAME=`PrimitiveValueBlock`;var Zi,Qi=class extends qi{constructor(e={}){super(e,Xi),this.idBlock.isConstructed=!1}};Zi=Qi,W.Primitive=Zi,Qi.NAME=`PRIMITIVE`;var $i=1e4,ea=16777216,ta=`Maximum ASN.1 nesting depth exceeded`,na=`Maximum ASN.1 node count exceeded`,ra=`Maximum ASN.1 content length exceeded`;function ia(e={}){return{depth:0,maxDepth:e.maxDepth??100,nodesCount:0,maxNodes:e.maxNodes??$i,maxContentLength:e.maxContentLength??ea}}function aa(e){let t=new qi({},Wi);return t.error=e,{offset:-1,result:t}}function oa(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return na}function sa(e,t){if(e>t.maxContentLength)return ra}function ca(e,t,n,r){let i=r.depth+1;if(i>r.maxDepth)return aa(ta);r.depth=i;try{return ua(e,t,n,r)}finally{--r.depth}}function la(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 ua(e,t=0,n=e.length,r=ia()){let i=t,a=new qi({},Wi),o=new Ui;if(!Si(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=oa(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=sa(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=qi;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=la(a,d),c=a.fromBER(e,t,l,r),a.valueBeforeDecodeView=e.subarray(i,i+a.blockLength),{offset:c,result:a}}function da(e,t={}){if(!e.byteLength){let e=new qi({},Wi);return e.error=`Input buffer has zero length`,{offset:-1,result:e}}return ua(U.toUint8Array(e).slice(),0,e.byteLength,ia(t))}function fa(e,t){return e?1:t}var pa=class extends Wi{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??ia();if(!Si(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(;fa(this.isIndefiniteForm,n)>0;){let e=ca(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===zi)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===zi?this.value.pop():this.warnings.push(`No EndOfContent block encoded`)),o}toBER(e,t){let n=t||new Ci;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,n);return t?Li:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};pa.NAME=`ConstructedValueBlock`;var ma,ha=class extends qi{constructor(e={}){super(e,pa),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} :`}};ma=ha,W.Constructed=ma,ha.NAME=`CONSTRUCTED`;var ga=class extends Wi{fromBER(e,t,n){return t}toBER(e){return Li}};ga.override=`EndOfContentValueBlock`;var _a,va=class extends qi{constructor(e={}){super(e,ga),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};_a=va,W.EndOfContent=_a,va.NAME=zi;var ya,ba=class extends qi{constructor(e={}){super(e,Wi),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}`}};ya=ba,W.Null=ya,ba.NAME=`NULL`;var xa=class extends Hi(Wi){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 Si(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,hi.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};xa.NAME=`BooleanValueBlock`;var Sa,Ca=class extends qi{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,xa),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Sa=Ca,W.Boolean=Sa,Ca.NAME=`BOOLEAN`;var wa=class extends Hi(pa){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=pa.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===zi){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only`,-1}if(t!==Bi)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?pa.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};wa.NAME=`OctetStringValueBlock`;var Ta,Ea=class extends qi{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},wa),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??ia(),t=ca(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?ha.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${li.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 Ta&&e.push(t.valueBlock.valueHexView);return U.concat(e)}};Ta=Ea,W.OctetString=Ta,Ea.NAME=Bi;var Da=class extends Hi(pa){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=pa.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===zi){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only`,-1}if(t!==Vi)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(!Si(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??ia(),i=ca(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 pa.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}}};Da.NAME=`BitStringValueBlock`;var Oa,ka=class extends qi{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Da),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 ha.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)}`}}};Oa=ka,W.BitString=Oa,ka.NAME=Vi;var Aa;function ja(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=mi(new Uint8Array([l%10]),a);break;default:a[o-d]=l%10}}return n[0]>0&&(a=mi(n,a)),a}function Ma(e){if(e>=wi.length)for(let t=wi.length;t<=e;t++){let e=new Uint8Array([0]),n=wi[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=mi(e,n)),wi.push(n)}return wi[e]}function Na(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 Pa=class extends Hi(Wi){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=hi.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(gi(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=Na(Ma(n),t),a=`-`;break;default:t=ja(t,Ma(n))}n++,r>>=1}}for(let e=0;e<t.length;e++)t[e]&&(o=!0),o&&(a+=Ti.charAt(t[e]));return o===!1&&(a+=Ti.charAt(0)),a}};Aa=Pa,Pa.NAME=`IntegerValueBlock`,Object.defineProperty(Aa.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Fa,Ia=class extends qi{constructor(e={}){super(e,Pa),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return bi(),BigInt(this.valueBlock.toString())}static fromBigInt(e){bi();let t=BigInt(e),n=new Ci,r=t.toString(16).replace(/^-/,``),i=new Uint8Array(li.FromHex(r));if(t<0){let e=new Uint8Array(i.length+(i[0]&128?1:0));e[0]|=128;let r=BigInt(`0x${li.ToHex(e)}`)+t,a=U.toUint8Array(li.FromHex(r.toString(16)));a[0]|=128,n.write(a)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new Fa({valueHex:n.final()})}convertToDER(){let e=new Fa({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Fa({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Fa=Ia,W.Integer=Fa,Ia.NAME=`INTEGER`;var La,Ra=class extends Ia{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};La=Ra,W.Enumerated=La,Ra.NAME=`ENUMERATED`;var za=class extends Hi(Wi){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(!Si(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=fi(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}set valueBigInt(e){bi();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=pi(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,Li;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=li.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}}};za.NAME=`sidBlock`;var Ba=class extends Wi{constructor({value:e=Ii,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new za;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,Li;t.push(r)}return xi(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 za;if(r>2**53-1)bi(),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}};Ba.NAME=`ObjectIdentifierValueBlock`;var Va,Ha=class extends qi{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Ba),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Va=Ha,W.ObjectIdentifier=Va,Ha.NAME=`OBJECT IDENTIFIER`;var Ua=class extends Hi(Ui){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(!Si(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=fi(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=pi(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,Li;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?li.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ua.NAME=`relativeSidBlock`;var Wa=class extends Wi{constructor({value:e=Ii,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new Ua;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,Li;n.push(r)}return xi(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 Ua;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}};Wa.NAME=`RelativeObjectIdentifierValueBlock`;var Ga,Ka=class extends qi{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Wa),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Ga=Ka,W.RelativeObjectIdentifier=Ga,Ka.NAME=`RelativeObjectIdentifier`;var qa,Ja=class extends ha{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};qa=Ja,W.Sequence=qa,Ja.NAME=`SEQUENCE`;var Ya,Xa=class extends ha{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Ya=Xa,W.Set=Ya,Xa.NAME=`SET`;var Za=class extends Hi(Wi){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ii}toJSON(){return{...super.toJSON(),value:this.value}}};Za.NAME=`StringValueBlock`;var Qa=class extends Za{};Qa.NAME=`SimpleStringValueBlock`;var $a=class extends Yi{constructor({...e}={}){super(e,Qa)}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}};$a.NAME=`SIMPLE STRING`;var eo=class extends $a{fromBuffer(e){this.valueBlock.valueHexView=U.toUint8Array(e);try{this.valueBlock.value=li.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=li.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(li.FromUtf8String(e)),this.valueBlock.value=e}};eo.NAME=`Utf8StringValueBlock`;var to,no=class extends eo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};to=no,W.Utf8String=to,no.NAME=`UTF8String`;var ro=class extends $a{fromBuffer(e){this.valueBlock.value=li.ToUtf16String(e),this.valueBlock.valueHexView=U.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(li.FromUtf16String(e))}};ro.NAME=`BmpStringValueBlock`;var io,ao=class extends ro{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};io=ao,W.BmpString=io,ao.NAME=`BMPString`;var oo=class extends $a{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=pi(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}};oo.NAME=`UniversalStringValueBlock`;var so,co=class extends oo{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};so=co,W.UniversalString=so,co.NAME=`UniversalString`;var lo,uo=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};lo=uo,W.NumericString=lo,uo.NAME=`NumericString`;var fo,po=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};fo=po,W.PrintableString=fo,po.NAME=`PrintableString`;var mo,ho=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};mo=ho,W.TeletexString=mo,ho.NAME=`TeletexString`;var go,_o=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};go=_o,W.VideotexString=go,_o.NAME=`VideotexString`;var vo,yo=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};vo=yo,W.IA5String=vo,yo.NAME=`IA5String`;var bo,xo=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};bo=xo,W.GraphicString=bo,xo.NAME=`GraphicString`;var So,Co=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};So=Co,W.VisibleString=So,Co.NAME=`VisibleString`;var wo,To=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};wo=To,W.GeneralString=wo,To.NAME=`GeneralString`;var Eo,Do=class extends $a{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Eo=Do,W.CharacterString=Eo,Do.NAME=`CharacterString`;var Oo,ko=class extends Co{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]=vi(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=vi(this.month,2),e[2]=vi(this.day,2),e[3]=vi(this.hour,2),e[4]=vi(this.minute,2),e[5]=vi(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}}};Oo=ko,W.UTCTime=Oo,ko.NAME=`UTCTime`;var Ao,jo=class extends ko{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(vi(this.year,4)),e.push(vi(this.month,2)),e.push(vi(this.day,2)),e.push(vi(this.hour,2)),e.push(vi(this.minute,2)),e.push(vi(this.second,2)),this.millisecond!==0&&(e.push(`.`),e.push(vi(this.millisecond,3))),e.push(`Z`),e.join(``)}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Ao=jo,W.GeneralizedTime=Ao,jo.NAME=`GeneralizedTime`;var Mo,No=class extends no{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Mo=No,W.DATE=Mo,No.NAME=`DATE`;var Po,Fo=class extends no{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Po=Fo,W.TimeOfDay=Po,Fo.NAME=`TimeOfDay`;var Io,Lo=class extends no{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Io=Lo,W.DateTime=Io,Lo.NAME=`DateTime`;var Ro,zo=class extends no{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Ro=zo,W.Duration=Ro,zo.NAME=`Duration`;var Bo,Vo=class extends no{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Bo=Vo,W.TIME=Bo,Vo.NAME=`TIME`;var Ho=class{constructor({name:e=Ii,optional:t=!1}={}){this.name=e,this.optional=t}},Uo=class extends Ho{constructor({value:e=[],...t}={}){super(t),this.value=e}},Wo=class extends Ho{constructor({value:e=new Ho,local:t=!1,...n}={}){super(n),this.value=e,this.local=t}},Go=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=U.toUint8Array(e)}constructor({data:e=Ri}={}){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 Ko(e,t,n){if(n instanceof Uo){for(let r of n.value)if(Ko(e,t,r).verified)return{verified:!0,result:e};{let e={verified:!1,result:{error:`Wrong values for Choice type`}};return n.hasOwnProperty(Ei)&&(e.name=n.name),e}}if(n instanceof Ho)return n.hasOwnProperty(Ei)&&(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)||!(ki in n)||!(Ni in n.idBlock)||!(Pi 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(Ai)===!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(ji)===!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(Mi)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(Oi 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(!(Di 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,Ii),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 Wo&&(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,Ii),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,Ii),n.name&&(delete e[n.name],t.name=n.name)),t}}else if(n.valueBlock.value[0]instanceof Wo){if(i=Ko(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,Ii),n.name&&delete e[n.name]),i}if(Ei in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let r={};r=Fi 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=Ko(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,Ii),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,Ii),n.name&&(delete e[n.name],t.name=n.name)),t}return{verified:!0,result:e}}if(n.primitiveSchema&&Di in t.valueBlock){let r=ua(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,Ii),n.name&&(delete e[n.name],t.name=n.name)),t}return Ko(e,r.result,n.primitiveSchema)}return{verified:!0,result:e}}function qo(e,t){if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 schema type`}};let n=ua(U.toUint8Array(e));return n.offset===-1?{verified:!1,result:n.result}:Ko(n.result,n.result,t)}var Jo=`[object ArrayBuffer]`,Yo=`[object SharedArrayBuffer]`;function Xo(e){return Object.prototype.toString.call(e)}function Zo(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`&&es(t.buffer)}function Qo(e){return Xo(e)===Jo}function $o(e){return typeof SharedArrayBuffer<`u`&&Xo(e)===Yo}function es(e){return Qo(e)||$o(e)}function ts(e){return Zo(e)}function ns(e){return es(e)||ts(e)}function rs(e){if(!ns(e))throw TypeError(`Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView`)}function is(e){return rs(e),es(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function as(e){if(rs(e),Qo(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(is(e)),t}function os(e,t,n={}){let r=is(e),i=is(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 ss(e){let t=is(e),n=``;for(let e of t)n+=String.fromCharCode(e);return n}function cs(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function ls(e){return typeof e==`string`}var us=/^[0-9a-f]$/i,ds=[` `,` `,`
27
+ `,`\r`,`:`,`-`,`.`];function fs(e){return e.separators===`none`?[]:!e.separators||e.separators===`common`?ds:e.separators}function ps(e){if(!e)throw TypeError(`Hex separators must be non-empty strings`)}function ms(e,t,n){for(let r of n)if(e.startsWith(r,t))return r}function hs(e){let t=/[A-F]/.test(e),n=/[a-f]/.test(e);return t&&!n?`upper`:`lower`}function gs(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 _s(e){return e.replace(/[^0-9a-f]/gi,``)}function vs(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 ys(e){let t=e.trim(),n=/^0x/i.test(t)?`0x`:``,r=n?t.slice(2):t,i=gs(r),a=r.split(/\r\n|\n/).filter(e=>e.length>0),o=vs(a[0]?.trim()??``),s={case:hs(t),prefix:n};if(o&&(s.group=o),i&&a.length>1){let e=_s(a[0]??``).length/2;e>0&&a.slice(0,-1).every(t=>_s(t).length/2===e)&&(s.line={bytesPerLine:e,separator:i})}return s}function bs(e,t){let n=t.allowPrefix??!0,r=[...fs(t)].sort((e,t)=>t.length-e.length);for(let e of r)ps(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(us.test(n)){a+=n,o=!1,e+=1;continue}let s=ms(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 xs(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 Ss(e,t={}){return bs(e,t)}function Cs(e,t={}){if(typeof e!=`string`)return!1;try{return Ss(e,t),!0}catch{return!1}}function ws(e,t={}){let n=is(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(xs(i.slice(n,n+e),t.group));a=r.join(n)}else a=xs(i,t.group);return`${t.prefix??``}${a}`}function Ts(e,t={}){let n=Ss(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 Es(e,t={}){let n=Ss(e,t);return{bytes:Ts(n),format:ys(e),normalized:n}}function Ds(e,t){return ws(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 Os(e){return new TextEncoder().encode(e)}function ks(e){return new TextDecoder(`utf-8`,{fatal:!1}).decode(is(e))}function As(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 js(e,t={}){let n=as(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 Ms=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Ns(){return globalThis.Buffer}function Ps(e){return e.replace(/[\n\r\t ]/g,``)}function Fs(e){let t=e.length%4;return t?e+`=`.repeat(4-t):e}function Is(e){if(typeof e!=`string`)return!1;let t=Ps(e);return t===``||Ms.test(t)}function Ls(e,t){let n=is(e),r=Ns();return r?r.from(n).toString(`base64`):btoa(ss(n))}function Rs(e,t){let n=Ps(e);if(!Is(n))throw TypeError(`Input is not valid Base64 text`);let r=Ns();return r?new Uint8Array(r.from(n,`base64`)):cs(atob(n))}var zs={encode:Ls,decode:Rs,is:Is,normalize:Ps,pad:Fs},Bs=/^[A-Za-z0-9_-]*$/;function Vs(e){return e.replace(/[\n\r\t ]/g,``)}function Hs(e){return typeof e==`string`&&Bs.test(Vs(e))}function Us(e,t){return zs.encode(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}function Ws(e,t){let n=Vs(e);if(!Hs(n))throw TypeError(`Input is not valid Base64Url text`);return zs.decode(zs.pad(n.replace(/-/g,`+`).replace(/_/g,`/`)))}var Gs=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,Ks=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function qs(e){if(!Gs.test(e))throw TypeError(`Invalid PEM label '${e}'`)}function Js(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Ys(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 Xs(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 Zs(e,t={}){let n=[],r=t.label,i;for(Ks.lastIndex=0;i=Ks.exec(e);){let e=i[1].trim();if(r&&e!==r)continue;qs(e);let t=Ys(i[2]);n.push({label:e,data:zs.decode(t.base64Text),headers:t.headers,lineLength:t.base64Lines[0]?.length??64,newline:Xs(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 Qs(e,t,n={}){qs(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(...Js(zs.encode(t),r)),a.push(`-----END ${e}-----`),`${a.join(i)}${i}`}function $s(e,t={}){return Zs(e,t).map(({lineLength:e,newline:t,...n})=>n)}function ec(e,t){let[n]=$s(e,{label:t,strict:!0});return n.data}function tc(e,t={}){let[n]=Zs(e,{...t,strict:!0}),r={label:n.label,headers:n.headers,lineLength:n.lineLength,newline:n.newline};return{bytes:n.data,format:r,normalized:Qs(n.label,n.data,r)}}function nc(e,t){return Qs(t.label,e,t)}var rc={name:`pem`,encode:(e,t)=>{if(!t?.label)throw TypeError(`PEM label is required`);return Qs(t.label,e,t)},decode:(e,t)=>ec(e,t?.label),format:nc,is:e=>typeof e==`string`&&/-----BEGIN [^-]+-----/.test(e),parse:tc};function ic(e){return e.trim().toLowerCase()}function ac(e){return e instanceof Error?e:Error(String(e))}function oc(e,t,n){for(let t of[n.name,...n.aliases??[]])e.delete(ic(t));t.delete(ic(n.name))}function sc(e,t,n){let r=e[n];if(typeof r!=`function`)throw Error(`Converter '${t}' does not support ${n}()`);return r}function cc(e,t,n){let r=ic(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 lc(e=[]){let t=new Map,n=new Set,r={register(e,r={}){if(!e.name||!ic(e.name))throw TypeError(`Converter name is required`);let i=[...new Set([e.name,...e.aliases??[]].map(ic))],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)oc(t,n,e);for(let n of i)t.set(n,e);return n.add(ic(e.name)),this},unregister(e){let r=t.get(ic(e));return r?(oc(t,n,r),!0):!1},has(e){return t.has(ic(e))},get(e){let n=t.get(ic(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:ac(e)}}},normalize(e,t,n){let r=this.get(e);return sc(r,e,`normalize`).call(r,t,n)},parse(e,t,n){let r=this.get(e);return sc(r,e,`parse`).call(r,t,n)},format(e,t,n){let r=this.get(e);return sc(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(ic(e))),r=new Map;for(let t of n){let n=this.get(t),i=cc(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}lc([{name:`binary`,aliases:[`latin1`],encode:ss,decode:cs,is:ls},{name:`hex`,encode:ws,decode:Ts,format:Ds,is:Cs,normalize:Ss,parse:Es},{name:`base64`,aliases:[`b64`],encode:Ls,decode:Rs,is:Is,normalize:Ps},{name:`base64url`,aliases:[`base64-url`,`b64url`],encode:Us,decode:Ws,is:Hs,normalize:Vs},{name:`utf8`,aliases:[`utf-8`],encode:e=>ks(e),decode:e=>Os(e),is:e=>typeof e==`string`},{name:`utf16be`,aliases:[`utf16`,`utf-16`,`utf-16be`],encode:e=>js(e),decode:e=>As(e),is:e=>typeof e==`string`},{name:`utf16le`,aliases:[`utf-16le`,`ucs2`,`usc2`],encode:e=>js(e,{littleEndian:!0}),decode:e=>As(e,{littleEndian:!0}),is:e=>typeof e==`string`},rc]);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 uc=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e){if(typeof e==`number`)this.fromNumber(e);else if(ns(e))this.unusedBits=t,this.value=as(e);else throw TypeError(`Unsupported type of 'params' argument for BitString`)}}fromASN(e){if(!(e instanceof ka))throw TypeError(`Argument 'asn' is not instance of ASN.1 BitString`);return this.unusedBits=e.valueBlock.unusedBits,this.value=as(e.valueBlock.valueHex),this}toASN(){return new ka({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new ka({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}},dc=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){this.buffer=typeof e==`number`?new ArrayBuffer(e):ns(e)?as(e):Array.isArray(e)?new Uint8Array(e).buffer:new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Ea))throw TypeError(`Argument 'asn' is not instance of ASN.1 OctetString`);return this.buffer=as(e.valueBlock.valueHex),this}toASN(){return new Ea({valueHex:this.buffer})}toSchema(e){return new Ea({name:e})}},fc={fromASN:e=>e instanceof ba?null:as(e.valueBeforeDecodeView),toASN:e=>{if(e===null)return new ba;let t=da(e);if(t.result.error)throw Error(t.result.error);return t.result}},pc={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Ia({value:+e})},mc={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new Ra({value:e})},hc={fromASN:e=>as(e.valueBlock.valueHexView),toASN:e=>new Ia({valueHex:e})},gc={fromASN:e=>as(e.valueBlock.valueHexView),toASN:e=>new ka({valueHex:e})},_c={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Ha({value:e})},vc={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Ka({value:e})},yc={fromASN:e=>e.valueBlock.value,toASN:e=>new Ca({value:e})},bc={fromASN:e=>as(e.valueBlock.valueHexView),toASN:e=>new Ea({valueHex:e})},xc={fromASN:e=>new dc(e.getValue()),toASN:e=>e.toASN()};function Sc(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var Cc=Sc(no),wc=Sc(ao),Tc=Sc(co),Ec=Sc(uo),Dc=Sc(po),Oc=Sc(ho),kc=Sc(_o),Ac=Sc(yo),jc=Sc(xo),Mc=Sc(Co),Nc=Sc(To),Pc=Sc(Do),Fc={fromASN:e=>e.toDate(),toASN:e=>new ko({valueDate:e})},Ic={fromASN:e=>e.toDate(),toASN:e=>new jo({valueDate:e})},Lc={fromASN:()=>null,toASN:()=>new ba};function Rc(e){switch(e){case K.Any:return fc;case K.BitString:return gc;case K.BmpString:return wc;case K.Boolean:return yc;case K.CharacterString:return Pc;case K.Enumerated:return mc;case K.GeneralString:return Nc;case K.GeneralizedTime:return Ic;case K.GraphicString:return jc;case K.IA5String:return Ac;case K.Integer:return pc;case K.Null:return Lc;case K.NumericString:return Ec;case K.ObjectIdentifier:return _c;case K.RelativeObjectIdentifier:return vc;case K.OctetString:return bc;case K.PrintableString:return Dc;case K.TeletexString:return Oc;case K.UTCTime:return Fc;case K.UniversalString:return Tc;case K.Utf8String:return Cc;case K.VideotexString:return kc;case K.VisibleString:return Mc;default:return null}}function zc(e){return typeof e==`function`&&e.prototype?e.prototype.toASN&&e.prototype.fromASN?!0:zc(e.prototype):!!(e&&typeof e==`object`&&`toASN`in e&&`fromASN`in e)}function Bc(e){if(e){let t=Object.getPrototypeOf(e);return t?.prototype?.constructor===Array||Bc(t)}return!1}function Vc(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 Hc=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=yi[e];if(!t)throw Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:a})}else zc(i.type)?o=new i.type().toSchema(a):i.optional?this.get(i.type).type===G.Choice?o=new Ho({name:a}):(o=this.create(i.type,!1),o.name=a):o=new Ho({name:a});let s=!!i.optional||i.defaultValue!==void 0;if(i.repeated&&(o.name=``,o=new(i.repeated===`set`?Xa:Ja)({name:``,value:[new Wo({name:a,value:o})]})),i.context!==null&&i.context!==void 0){if(i.implicit){if(typeof i.type==`number`||zc(i.type)){let e=i.repeated?ha:Qi;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 ha({name:e?``:a,optional:s,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}}else r.push(new ha({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 Ja({value:r,name:``});case G.Set:return new Xa({value:r,name:``});case G.Choice:return new Uo({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;Hc.has(t)?n=Hc.get(t):(n=Hc.createDefault(t),Hc.set(t,n)),Object.assign(n,e)},J=e=>(t,n)=>{let r;Hc.has(t.constructor)?r=Hc.get(t.constructor):(r=Hc.createDefault(t.constructor),Hc.set(t.constructor,r));let i=Object.assign({},e);if(typeof i.type==`number`&&!i.converter){let r=Rc(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},Uc=class extends Error{schemas=[]},Wc=class{static parse(e,t,n){let r=da(as(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(zc(t))return new t().fromASN(e);let r=Hc.get(t);Hc.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 Bc(t)?this.handleArrayTypes(e,r,t,n):(this.processSchemaItems(r,o,s,n),s)}catch(e){throw e instanceof Uc&&e.schemas.push(t.name),e}}static handleChoiceTypes(e,t,n,r,i){if(e.constructor===ha&&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`&&Hc.has(a.type)){let t=Hc.get(a.type);if(t&&t.type===G.Sequence){let t=new Ja;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===ha&&t.type!==G.Choice){let n=new ha({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=Ko({},e,r);if(!t.verified)throw new Uc(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}{let t=Ko({},e,r);if(!t.verified)throw new Uc(`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=Rc(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=Rc(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`&&Hc.has(e.type)&&Hc.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 Uc&&/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=Rc(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`||zc(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??(zc(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`?Ja:Xa);i.valueBlock=e.valueBlock;let a=da(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(zc(n))e=new n().toSchema(``);else{let t=K[n],r=yi[t];if(!r)throw Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=a.valueBlock,a=da(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 Uc&&/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=Hc.get(n);if(t.type===G.Sequence){let t=new Ja;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 Xa;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}}return e}},Gc=class e{static serialize(e){return e instanceof qi?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&typeof t==`object`&&zc(t))return t.toASN();if(!(t&&typeof t==`object`))throw TypeError(`Parameter 1 should be type of Object.`);let n=t.constructor,r=Hc.get(n);Hc.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=Rc(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`&&Vc(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`||zc(o.type))){let e={};e.valueHex=c instanceof ba?as(c.valueBeforeDecodeView):c.valueBlock.toBER(),i.push(new Qi({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},...e}))}else i.push(new ha({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:c.valueBlock.value}))}else i.push(new ha({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 Ja({value:i});break;case G.Set:a=new Xa({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`?Ja:Xa)({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`?Ja:Xa)({value:t})}else i=this.toASN(r);return i}},Kc=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 Gc.serialize(e)}static parse(e,t,n){return Wc.parse(e,t,n)}static toString(t,n){let r=da(ns(t)?as(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 qc(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 Jc(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 Yc=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(ws(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}},Xc,Zc,Qc,$c=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})],$c.prototype,`teletexString`,void 0),X([J({type:K.PrintableString})],$c.prototype,`printableString`,void 0),X([J({type:K.UniversalString})],$c.prototype,`universalString`,void 0),X([J({type:K.Utf8String})],$c.prototype,`utf8String`,void 0),X([J({type:K.BmpString})],$c.prototype,`bmpString`,void 0),$c=X([q({type:G.Choice})],$c);var el=class extends $c{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?ws(this.anyValue):super.toString())}};X([J({type:K.IA5String})],el.prototype,`ia5String`,void 0),X([J({type:K.Any})],el.prototype,`anyValue`,void 0),el=X([q({type:G.Choice})],el);var tl=class{type=``;value=new el;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],tl.prototype,`type`,void 0),X([J({type:el})],tl.prototype,`value`,void 0);var nl=Xc=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Xc.prototype)}};nl=Xc=X([q({type:G.Set,itemType:tl})],nl);var rl=Zc=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Zc.prototype)}};rl=Zc=X([q({type:G.Sequence,itemType:nl})],rl);var il=Qc=class extends rl{constructor(e){super(e),Object.setPrototypeOf(this,Qc.prototype)}};il=Qc=X([q({type:G.Sequence})],il);var al={fromASN:e=>Yc.toString(bc.fromASN(e)),toASN:e=>bc.toASN(Yc.fromString(e))},ol=class{typeId=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ol.prototype,`typeId`,void 0),X([J({type:K.Any,context:0})],ol.prototype,`value`,void 0);var sl=class{nameAssigner;partyName=new $c;constructor(e={}){Object.assign(this,e)}};X([J({type:$c,optional:!0,context:0,implicit:!0})],sl.prototype,`nameAssigner`,void 0),X([J({type:$c,context:1,implicit:!0})],sl.prototype,`partyName`,void 0);var cl=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};X([J({type:ol,context:0,implicit:!0})],cl.prototype,`otherName`,void 0),X([J({type:K.IA5String,context:1,implicit:!0})],cl.prototype,`rfc822Name`,void 0),X([J({type:K.IA5String,context:2,implicit:!0})],cl.prototype,`dNSName`,void 0),X([J({type:K.Any,context:3,implicit:!0})],cl.prototype,`x400Address`,void 0),X([J({type:il,context:4,implicit:!1})],cl.prototype,`directoryName`,void 0),X([J({type:sl,context:5})],cl.prototype,`ediPartyName`,void 0),X([J({type:K.IA5String,context:6,implicit:!0})],cl.prototype,`uniformResourceIdentifier`,void 0),X([J({type:K.OctetString,context:7,implicit:!0,converter:al})],cl.prototype,`iPAddress`,void 0),X([J({type:K.ObjectIdentifier,context:8,implicit:!0})],cl.prototype,`registeredID`,void 0),cl=X([q({type:G.Choice})],cl);var ll=`1.3.6.1.5.5.7`,ul=`${ll}.1`,dl=`${ll}.2`,fl=`${ll}.3`,pl=`${ll}.48`;`${dl}`,`${dl}`;var ml=`${pl}.1`,hl=`${pl}.2`,gl=`${pl}.3`,_l=`${pl}.5`,vl=`2.5.29`,yl,bl=`${ul}.1`,xl=class{accessMethod=``;accessLocation=new cl;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],xl.prototype,`accessMethod`,void 0),X([J({type:cl})],xl.prototype,`accessLocation`,void 0);var Sl=yl=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,yl.prototype)}};Sl=yl=X([q({type:G.Sequence,itemType:xl})],Sl);var Cl=`${vl}.35`,wl=class extends dc{},Tl=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};X([J({type:wl,context:0,optional:!0,implicit:!0})],Tl.prototype,`keyIdentifier`,void 0),X([J({type:cl,context:1,optional:!0,implicit:!0,repeated:`sequence`})],Tl.prototype,`authorityCertIssuer`,void 0),X([J({type:K.Integer,context:2,optional:!0,implicit:!0,converter:hc})],Tl.prototype,`authorityCertSerialNumber`,void 0);var El=`${vl}.19`,Dl=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Boolean,defaultValue:!1})],Dl.prototype,`cA`,void 0),X([J({type:K.Integer,optional:!0})],Dl.prototype,`pathLenConstraint`,void 0);var Ol,kl=Ol=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Ol.prototype)}};kl=Ol=X([q({type:G.Sequence,itemType:cl})],kl);var Al;`${vl}`;var jl=Al=class extends kl{constructor(e){super(e),Object.setPrototypeOf(this,Al.prototype)}};jl=Al=X([q({type:G.Sequence})],jl);var Ml,Nl=`${vl}.32`;`${Nl}`;var Pl=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})],Pl.prototype,`ia5String`,void 0),X([J({type:K.VisibleString})],Pl.prototype,`visibleString`,void 0),X([J({type:K.BmpString})],Pl.prototype,`bmpString`,void 0),X([J({type:K.Utf8String})],Pl.prototype,`utf8String`,void 0),Pl=X([q({type:G.Choice})],Pl);var Fl=class{organization=new Pl;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};X([J({type:Pl})],Fl.prototype,`organization`,void 0),X([J({type:K.Integer,repeated:`sequence`})],Fl.prototype,`noticeNumbers`,void 0);var Il=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};X([J({type:Fl,optional:!0})],Il.prototype,`noticeRef`,void 0),X([J({type:Pl,optional:!0})],Il.prototype,`explicitText`,void 0);var Ll=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};X([J({type:K.IA5String})],Ll.prototype,`cPSuri`,void 0),X([J({type:Il})],Ll.prototype,`userNotice`,void 0),Ll=X([q({type:G.Choice})],Ll);var Rl=class{policyQualifierId=``;qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Rl.prototype,`policyQualifierId`,void 0),X([J({type:K.Any})],Rl.prototype,`qualifier`,void 0);var zl=class{policyIdentifier=``;policyQualifiers;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],zl.prototype,`policyIdentifier`,void 0),X([J({type:Rl,repeated:`sequence`,optional:!0})],zl.prototype,`policyQualifiers`,void 0);var Bl=Ml=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Ml.prototype)}};Bl=Ml=X([q({type:G.Sequence,itemType:zl})],Bl),`${vl}`;var Vl=class{value;constructor(e=0){this.value=e}};X([J({type:K.Integer})],Vl.prototype,`value`,void 0),Vl=X([q({type:G.Choice})],Vl),`${vl}`;var Hl=class extends Vl{};Hl=X([q({type:G.Choice})],Hl);var Ul,Wl=`${vl}.31`,Gl;(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`})(Gl||={});var Kl=class extends uc{toJSON(){let e=[],t=this.toNumber();return t&Gl.aACompromise&&e.push(`aACompromise`),t&Gl.affiliationChanged&&e.push(`affiliationChanged`),t&Gl.cACompromise&&e.push(`cACompromise`),t&Gl.certificateHold&&e.push(`certificateHold`),t&Gl.cessationOfOperation&&e.push(`cessationOfOperation`),t&Gl.keyCompromise&&e.push(`keyCompromise`),t&Gl.privilegeWithdrawn&&e.push(`privilegeWithdrawn`),t&Gl.superseded&&e.push(`superseded`),t&Gl.unused&&e.push(`unused`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},ql=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:cl,context:0,repeated:`sequence`,implicit:!0})],ql.prototype,`fullName`,void 0),X([J({type:nl,context:1,implicit:!0})],ql.prototype,`nameRelativeToCRLIssuer`,void 0),ql=X([q({type:G.Choice})],ql);var Jl=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};X([J({type:ql,context:0,optional:!0})],Jl.prototype,`distributionPoint`,void 0),X([J({type:Kl,context:1,optional:!0,implicit:!0})],Jl.prototype,`reasons`,void 0),X([J({type:cl,context:2,optional:!0,repeated:`sequence`,implicit:!0})],Jl.prototype,`cRLIssuer`,void 0);var Yl=Ul=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Ul.prototype)}};Yl=Ul=X([q({type:G.Sequence,itemType:Jl})],Yl);var Xl;`${vl}`;var Zl=Xl=class extends Yl{constructor(e){super(e),Object.setPrototypeOf(this,Xl.prototype)}};Zl=Xl=X([q({type:G.Sequence,itemType:Jl})],Zl),`${vl}`;var Ql=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:ql,context:0,optional:!0})],Ql.prototype,`distributionPoint`,void 0),X([J({type:K.Boolean,context:1,defaultValue:Ql.ONLY,implicit:!0})],Ql.prototype,`onlyContainsUserCerts`,void 0),X([J({type:K.Boolean,context:2,defaultValue:Ql.ONLY,implicit:!0})],Ql.prototype,`onlyContainsCACerts`,void 0),X([J({type:Kl,context:3,optional:!0,implicit:!0})],Ql.prototype,`onlySomeReasons`,void 0),X([J({type:K.Boolean,context:4,defaultValue:Ql.ONLY,implicit:!0})],Ql.prototype,`indirectCRL`,void 0),X([J({type:K.Boolean,context:5,defaultValue:Ql.ONLY,implicit:!0})],Ql.prototype,`onlyContainsAttributeCerts`,void 0),`${vl}`;var $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||={});var eu=class{reason=$l.unspecified;constructor(e=$l.unspecified){this.reason=e}toJSON(){return $l[this.reason]}toString(){return this.toJSON()}};X([J({type:K.Enumerated})],eu.prototype,`reason`,void 0),eu=X([q({type:G.Choice})],eu);var tu,nu=`${vl}.37`,ru=tu=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,tu.prototype)}};ru=tu=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],ru),`${nu}`;var iu=`${fl}.1`,au=`${fl}.2`,ou=`${fl}.3`,su=`${fl}.4`,cu=`${fl}.8`,lu=`${fl}.9`;`${vl}`;var uu=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};X([J({type:K.Integer,converter:hc})],uu.prototype,`value`,void 0),uu=X([q({type:G.Choice})],uu),`${vl}`;var du=class{value=new Date;constructor(e){e&&(this.value=e)}};X([J({type:K.GeneralizedTime})],du.prototype,`value`,void 0),du=X([q({type:G.Choice})],du);var fu,pu=`${vl}.18`,mu=fu=class extends kl{constructor(e){super(e),Object.setPrototypeOf(this,fu.prototype)}};mu=fu=X([q({type:G.Sequence})],mu);var hu=`${vl}.15`,gu;(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`})(gu||={});var _u=class extends uc{toJSON(){let e=this.toNumber(),t=[];return e&gu.cRLSign&&t.push(`crlSign`),e&gu.dataEncipherment&&t.push(`dataEncipherment`),e&gu.decipherOnly&&t.push(`decipherOnly`),e&gu.digitalSignature&&t.push(`digitalSignature`),e&gu.encipherOnly&&t.push(`encipherOnly`),e&gu.keyAgreement&&t.push(`keyAgreement`),e&gu.keyCertSign&&t.push(`keyCertSign`),e&gu.keyEncipherment&&t.push(`keyEncipherment`),e&gu.nonRepudiation&&t.push(`nonRepudiation`),t}toString(){return`[${this.toJSON().join(`, `)}]`}},vu;`${vl}`;var yu=class{base=new cl;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};X([J({type:cl})],yu.prototype,`base`,void 0),X([J({type:K.Integer,context:0,defaultValue:0,implicit:!0})],yu.prototype,`minimum`,void 0),X([J({type:K.Integer,context:1,optional:!0,implicit:!0})],yu.prototype,`maximum`,void 0);var bu=vu=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,vu.prototype)}};bu=vu=X([q({type:G.Sequence,itemType:yu})],bu);var xu=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};X([J({type:bu,context:0,optional:!0,implicit:!0})],xu.prototype,`permittedSubtrees`,void 0),X([J({type:bu,context:1,optional:!0,implicit:!0})],xu.prototype,`excludedSubtrees`,void 0),`${vl}`;var Su=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,implicit:!0,optional:!0,converter:hc})],Su.prototype,`requireExplicitPolicy`,void 0),X([J({type:K.Integer,context:1,implicit:!0,optional:!0,converter:hc})],Su.prototype,`inhibitPolicyMapping`,void 0);var Cu;`${vl}`;var wu=class{issuerDomainPolicy=``;subjectDomainPolicy=``;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],wu.prototype,`issuerDomainPolicy`,void 0),X([J({type:K.ObjectIdentifier})],wu.prototype,`subjectDomainPolicy`,void 0);var Tu=Cu=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Cu.prototype)}};Tu=Cu=X([q({type:G.Sequence,itemType:wu})],Tu);var Eu,Du=`${vl}.17`,Ou=Eu=class extends kl{constructor(e){super(e),Object.setPrototypeOf(this,Eu.prototype)}};Ou=Eu=X([q({type:G.Sequence})],Ou);var ku=class{type=``;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],ku.prototype,`type`,void 0),X([J({type:K.Any,repeated:`set`})],ku.prototype,`values`,void 0);var Au;`${vl}`;var ju=Au=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Au.prototype)}};ju=Au=X([q({type:G.Sequence,itemType:ku})],ju);var Mu=`${vl}.14`,Nu=class extends wl{};`${vl}`;var Pu=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime,context:0,implicit:!0,optional:!0})],Pu.prototype,`notBefore`,void 0),X([J({type:K.GeneralizedTime,context:1,implicit:!0,optional:!0})],Pu.prototype,`notAfter`,void 0);var Fu;(function(e){e[e.keyUpdateAllowed=1]=`keyUpdateAllowed`,e[e.newExtensions=2]=`newExtensions`,e[e.pKIXCertificate=4]=`pKIXCertificate`})(Fu||={});var Iu=class extends uc{toJSON(){let e=[],t=this.toNumber();return t&Fu.pKIXCertificate&&e.push(`pKIXCertificate`),t&Fu.newExtensions&&e.push(`newExtensions`),t&Fu.keyUpdateAllowed&&e.push(`keyUpdateAllowed`),e}toString(){return`[${this.toJSON().join(`, `)}]`}},Lu=class{entrustVers=``;entrustInfoFlags=new Iu;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralString})],Lu.prototype,`entrustVers`,void 0),X([J({type:Iu})],Lu.prototype,`entrustInfoFlags`,void 0);var Ru;`${ul}`;var zu=Ru=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Ru.prototype)}};zu=Ru=X([q({type:G.Sequence,itemType:xl})],zu);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&&os(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 Bu=class{algorithm=new Z;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Bu.prototype,`algorithm`,void 0),X([J({type:K.BitString})],Bu.prototype,`subjectPublicKey`,void 0);var Vu=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})],Vu.prototype,`utcTime`,void 0),X([J({type:K.GeneralizedTime})],Vu.prototype,`generalTime`,void 0),Vu=X([q({type:G.Choice})],Vu);var Hu=class{notBefore=new Vu(new Date);notAfter=new Vu(new Date);constructor(e){e&&(this.notBefore=new Vu(e.notBefore),this.notAfter=new Vu(e.notAfter))}};X([J({type:Vu})],Hu.prototype,`notBefore`,void 0),X([J({type:Vu})],Hu.prototype,`notAfter`,void 0);var Uu,Wu=class e{static CRITICAL=!1;extnID=``;critical=e.CRITICAL;extnValue=new dc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Wu.prototype,`extnID`,void 0),X([J({type:K.Boolean,defaultValue:Wu.CRITICAL})],Wu.prototype,`critical`,void 0),X([J({type:dc})],Wu.prototype,`extnValue`,void 0);var Gu=Uu=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Uu.prototype)}};Gu=Uu=X([q({type:G.Sequence,itemType:Wu})],Gu);var Ku;(function(e){e[e.v1=0]=`v1`,e[e.v2=1]=`v2`,e[e.v3=2]=`v3`})(Ku||={});var qu=class{version=Ku.v1;serialNumber=new ArrayBuffer(0);signature=new Z;issuer=new il;validity=new Hu;subject=new il;subjectPublicKeyInfo=new Bu;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,context:0,defaultValue:Ku.v1})],qu.prototype,`version`,void 0),X([J({type:K.Integer,converter:hc})],qu.prototype,`serialNumber`,void 0),X([J({type:Z})],qu.prototype,`signature`,void 0),X([J({type:il})],qu.prototype,`issuer`,void 0),X([J({type:Hu})],qu.prototype,`validity`,void 0),X([J({type:il})],qu.prototype,`subject`,void 0),X([J({type:Bu})],qu.prototype,`subjectPublicKeyInfo`,void 0),X([J({type:K.BitString,context:1,implicit:!0,optional:!0})],qu.prototype,`issuerUniqueID`,void 0),X([J({type:K.BitString,context:2,implicit:!0,optional:!0})],qu.prototype,`subjectUniqueID`,void 0),X([J({type:Gu,context:3,optional:!0})],qu.prototype,`extensions`,void 0);var Ju=class{tbsCertificate=new qu;tbsCertificateRaw;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:qu,raw:!0})],Ju.prototype,`tbsCertificate`,void 0),X([J({type:Z})],Ju.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Ju.prototype,`signatureValue`,void 0);var Yu=class{userCertificate=new ArrayBuffer(0);revocationDate=new Vu;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:hc})],Yu.prototype,`userCertificate`,void 0),X([J({type:Vu})],Yu.prototype,`revocationDate`,void 0),X([J({type:Wu,optional:!0,repeated:`sequence`})],Yu.prototype,`crlEntryExtensions`,void 0);var Xu=class{version;signature=new Z;issuer=new il;thisUpdate=new Vu;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],Xu.prototype,`version`,void 0),X([J({type:Z})],Xu.prototype,`signature`,void 0),X([J({type:il})],Xu.prototype,`issuer`,void 0),X([J({type:Vu})],Xu.prototype,`thisUpdate`,void 0),X([J({type:Vu,optional:!0})],Xu.prototype,`nextUpdate`,void 0),X([J({type:Yu,repeated:`sequence`,optional:!0})],Xu.prototype,`revokedCertificates`,void 0),X([J({type:Wu,optional:!0,context:0,repeated:`sequence`})],Xu.prototype,`crlExtensions`,void 0);var Zu=class{tbsCertList=new Xu;tbsCertListRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Xu,raw:!0})],Zu.prototype,`tbsCertList`,void 0),X([J({type:Z})],Zu.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Zu.prototype,`signature`,void 0);var Qu=class{issuer=new il;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:il})],Qu.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:hc})],Qu.prototype,`serialNumber`,void 0);var $u=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Nu,context:0,implicit:!0})],$u.prototype,`subjectKeyIdentifier`,void 0),X([J({type:Qu})],$u.prototype,`issuerAndSerialNumber`,void 0),$u=X([q({type:G.Choice})],$u);var ed;(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`})(ed||={});var td=class extends Z{};td=X([q({type:G.Sequence})],td);var nd=class extends Z{};nd=X([q({type:G.Sequence})],nd);var rd=class extends Z{};rd=X([q({type:G.Sequence})],rd);var id=class extends Z{};id=X([q({type:G.Sequence})],id);var ad=class extends Z{};ad=X([q({type:G.Sequence})],ad);var od=class extends Z{};od=X([q({type:G.Sequence})],od);var sd=class{attrType=``;attrValues=[];constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],sd.prototype,`attrType`,void 0),X([J({type:K.Any,repeated:`set`})],sd.prototype,`attrValues`,void 0);var cd,ld=class{version=ed.v0;sid=new $u;digestAlgorithm=new td;signedAttrs;signedAttrsRaw;signatureAlgorithm=new nd;signature=new dc;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],ld.prototype,`version`,void 0),X([J({type:$u})],ld.prototype,`sid`,void 0),X([J({type:td})],ld.prototype,`digestAlgorithm`,void 0),X([J({type:sd,repeated:`set`,context:0,implicit:!0,optional:!0,raw:!0})],ld.prototype,`signedAttrs`,void 0),X([J({type:nd})],ld.prototype,`signatureAlgorithm`,void 0),X([J({type:dc})],ld.prototype,`signature`,void 0),X([J({type:sd,repeated:`set`,context:1,implicit:!0,optional:!0})],ld.prototype,`unsignedAttrs`,void 0);var ud=cd=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,cd.prototype)}};ud=cd=X([q({type:G.Set,itemType:ld})],ud);var dd=class extends ld{};dd=X([q({type:G.Sequence})],dd);var fd=class extends Vu{};fd=X([q({type:G.Choice})],fd);var pd=class{acIssuer=new cl;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};X([J({type:cl})],pd.prototype,`acIssuer`,void 0),X([J({type:K.Integer})],pd.prototype,`acSerial`,void 0),X([J({type:ku,repeated:`sequence`})],pd.prototype,`attrs`,void 0);var md,hd=md=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,md.prototype)}};hd=md=X([q({type:G.Sequence,itemType:K.ObjectIdentifier})],hd);var gd=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,optional:!0})],gd.prototype,`pathLenConstraint`,void 0),X([J({type:hd,implicit:!0,context:0,optional:!0})],gd.prototype,`permittedAttrs`,void 0),X([J({type:hd,implicit:!0,context:1,optional:!0})],gd.prototype,`excludedAttrs`,void 0),X([J({type:K.Boolean,defaultValue:!0})],gd.prototype,`permitUnSpecified`,void 0);var _d=class{issuer=new kl;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:kl})],_d.prototype,`issuer`,void 0),X([J({type:K.Integer,converter:hc})],_d.prototype,`serial`,void 0),X([J({type:K.BitString,optional:!0})],_d.prototype,`issuerUID`,void 0);var vd;(function(e){e[e.publicKey=0]=`publicKey`,e[e.publicKeyCert=1]=`publicKeyCert`,e[e.otherObjectTypes=2]=`otherObjectTypes`})(vd||={});var yd=class{digestedObjectType=vd.publicKey;otherObjectTypeID;digestAlgorithm=new Z;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Enumerated})],yd.prototype,`digestedObjectType`,void 0),X([J({type:K.ObjectIdentifier,optional:!0})],yd.prototype,`otherObjectTypeID`,void 0),X([J({type:Z})],yd.prototype,`digestAlgorithm`,void 0),X([J({type:K.BitString})],yd.prototype,`objectDigest`,void 0);var bd=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:kl,optional:!0})],bd.prototype,`issuerName`,void 0),X([J({type:_d,context:0,implicit:!0,optional:!0})],bd.prototype,`baseCertificateID`,void 0),X([J({type:yd,context:1,implicit:!0,optional:!0})],bd.prototype,`objectDigestInfo`,void 0);var xd=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};X([J({type:cl,repeated:`sequence`})],xd.prototype,`v1Form`,void 0),X([J({type:bd,context:0,implicit:!0})],xd.prototype,`v2Form`,void 0),xd=X([q({type:G.Choice})],xd);var Sd=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};X([J({type:K.GeneralizedTime})],Sd.prototype,`notBeforeTime`,void 0),X([J({type:K.GeneralizedTime})],Sd.prototype,`notAfterTime`,void 0);var Cd=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:_d,implicit:!0,context:0,optional:!0})],Cd.prototype,`baseCertificateID`,void 0),X([J({type:kl,implicit:!0,context:1,optional:!0})],Cd.prototype,`entityName`,void 0),X([J({type:yd,implicit:!0,context:2,optional:!0})],Cd.prototype,`objectDigestInfo`,void 0);var wd;(function(e){e[e.v2=1]=`v2`})(wd||={});var Td=class{version=wd.v2;holder=new Cd;issuer=new xd;signature=new Z;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Sd;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Td.prototype,`version`,void 0),X([J({type:Cd})],Td.prototype,`holder`,void 0),X([J({type:xd})],Td.prototype,`issuer`,void 0),X([J({type:Z})],Td.prototype,`signature`,void 0),X([J({type:K.Integer,converter:hc})],Td.prototype,`serialNumber`,void 0),X([J({type:Sd})],Td.prototype,`attrCertValidityPeriod`,void 0),X([J({type:ku,repeated:`sequence`})],Td.prototype,`attributes`,void 0),X([J({type:K.BitString,optional:!0})],Td.prototype,`issuerUniqueID`,void 0),X([J({type:Gu,optional:!0})],Td.prototype,`extensions`,void 0);var Ed=class{acinfo=new Td;signatureAlgorithm=new Z;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Td})],Ed.prototype,`acinfo`,void 0),X([J({type:Z})],Ed.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Ed.prototype,`signatureValue`,void 0);var Dd;(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`})(Dd||={});var Od=class extends uc{},kd=class{type=``;value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier,implicit:!0,context:0})],kd.prototype,`type`,void 0),X([J({type:K.Any,implicit:!0,context:1})],kd.prototype,`value`,void 0);var Ad=class{policyId=``;classList=new Od(Dd.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Ad.prototype,`policyId`,void 0),X([J({type:Od,defaultValue:new Od(Dd.unclassified)})],Ad.prototype,`classList`,void 0),X([J({type:kd,repeated:`set`})],Ad.prototype,`securityCategories`,void 0);var jd=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};X([J({type:dc})],jd.prototype,`cotets`,void 0),X([J({type:K.ObjectIdentifier})],jd.prototype,`oid`,void 0),X([J({type:K.Utf8String})],jd.prototype,`string`,void 0);var Md=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};X([J({type:kl,implicit:!0,context:0,optional:!0})],Md.prototype,`policyAuthority`,void 0),X([J({type:jd,repeated:`sequence`})],Md.prototype,`values`,void 0),`${ul}`,`${ul}`,`${ul}`,`${vl}`;var Nd=`${ll}.10`;`${Nd}`,`${Nd}`,`${Nd}`,`${Nd}`,`${Nd}`;var Pd=`2.5.4`;`${Pd}`;var Fd,Id=class{targetCertificate=new _d;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:_d})],Id.prototype,`targetCertificate`,void 0),X([J({type:cl,optional:!0})],Id.prototype,`targetName`,void 0),X([J({type:yd,optional:!0})],Id.prototype,`certDigestInfo`,void 0);var Ld=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};X([J({type:cl,context:0,implicit:!0})],Ld.prototype,`targetName`,void 0),X([J({type:cl,context:1,implicit:!0})],Ld.prototype,`targetGroup`,void 0),X([J({type:Id,context:2,implicit:!0})],Ld.prototype,`targetCert`,void 0),Ld=X([q({type:G.Choice})],Ld);var Rd=Fd=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Fd.prototype)}};Rd=Fd=X([q({type:G.Sequence,itemType:Ld})],Rd);var zd,Bd=zd=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,zd.prototype)}};Bd=zd=X([q({type:G.Sequence,itemType:Rd})],Bd);var Vd=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};X([J({type:kl,implicit:!0,context:0,optional:!0})],Vd.prototype,`roleAuthority`,void 0),X([J({type:cl,implicit:!0,context:1})],Vd.prototype,`roleName`,void 0);var Hd=class{service=new cl;ident=new cl;authInfo;constructor(e={}){Object.assign(this,e)}};X([J({type:cl})],Hd.prototype,`service`,void 0),X([J({type:cl})],Hd.prototype,`ident`,void 0),X([J({type:dc,optional:!0})],Hd.prototype,`authInfo`,void 0);var Ud,Wd=class{otherCertFormat=``;otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Wd.prototype,`otherCertFormat`,void 0),X([J({type:K.Any})],Wd.prototype,`otherCert`,void 0);var Gd=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};X([J({type:Ju})],Gd.prototype,`certificate`,void 0),X([J({type:Ed,context:2,implicit:!0})],Gd.prototype,`v2AttrCert`,void 0),X([J({type:Wd,context:3,implicit:!0})],Gd.prototype,`other`,void 0),Gd=X([q({type:G.Choice})],Gd);var Kd=Ud=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Ud.prototype)}};Kd=Ud=X([q({type:G.Set,itemType:Gd})],Kd);var qd=class{contentType=``;content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],qd.prototype,`contentType`,void 0),X([J({type:K.Any,context:0})],qd.prototype,`content`,void 0);var Jd=class{single;any;constructor(e={}){Object.assign(this,e)}};X([J({type:dc})],Jd.prototype,`single`,void 0),X([J({type:K.Any})],Jd.prototype,`any`,void 0),Jd=X([q({type:G.Choice})],Jd);var Yd=class{eContentType=``;eContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Yd.prototype,`eContentType`,void 0),X([J({type:Jd,context:0,optional:!0})],Yd.prototype,`eContent`,void 0);var Xd=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};X([J({type:dc,context:0,implicit:!0,optional:!0})],Xd.prototype,`value`,void 0),X([J({type:dc,converter:xc,context:0,implicit:!0,optional:!0,repeated:`sequence`})],Xd.prototype,`constructedValue`,void 0),Xd=X([q({type:G.Choice})],Xd);var Zd=class{contentType=``;contentEncryptionAlgorithm=new id;encryptedContent;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Zd.prototype,`contentType`,void 0),X([J({type:id})],Zd.prototype,`contentEncryptionAlgorithm`,void 0),X([J({type:Xd,optional:!0})],Zd.prototype,`encryptedContent`,void 0);var Qd=class{keyAttrId=``;keyAttr;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Qd.prototype,`keyAttrId`,void 0),X([J({type:K.Any,optional:!0})],Qd.prototype,`keyAttr`,void 0);var $d,ef=class{subjectKeyIdentifier=new Nu;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:Nu})],ef.prototype,`subjectKeyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],ef.prototype,`date`,void 0),X([J({type:Qd,optional:!0})],ef.prototype,`other`,void 0);var tf=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:ef,context:0,implicit:!0,optional:!0})],tf.prototype,`rKeyId`,void 0),X([J({type:Qu,optional:!0})],tf.prototype,`issuerAndSerialNumber`,void 0),tf=X([q({type:G.Choice})],tf);var nf=class{rid=new tf;encryptedKey=new dc;constructor(e={}){Object.assign(this,e)}};X([J({type:tf})],nf.prototype,`rid`,void 0),X([J({type:dc})],nf.prototype,`encryptedKey`,void 0);var rf=$d=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,$d.prototype)}};rf=$d=X([q({type:G.Sequence,itemType:nf})],rf);var af=class{algorithm=new Z;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],af.prototype,`algorithm`,void 0),X([J({type:K.BitString})],af.prototype,`publicKey`,void 0);var of=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Nu,context:0,implicit:!0,optional:!0})],of.prototype,`subjectKeyIdentifier`,void 0),X([J({type:af,context:1,implicit:!0,optional:!0})],of.prototype,`originatorKey`,void 0),X([J({type:Qu,optional:!0})],of.prototype,`issuerAndSerialNumber`,void 0),of=X([q({type:G.Choice})],of);var sf=class{version=ed.v3;originator=new of;ukm;keyEncryptionAlgorithm=new rd;recipientEncryptedKeys=new rf;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],sf.prototype,`version`,void 0),X([J({type:of,context:0})],sf.prototype,`originator`,void 0),X([J({type:dc,context:1,optional:!0})],sf.prototype,`ukm`,void 0),X([J({type:rd})],sf.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:rf})],sf.prototype,`recipientEncryptedKeys`,void 0);var cf=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};X([J({type:Nu,context:0,implicit:!0})],cf.prototype,`subjectKeyIdentifier`,void 0),X([J({type:Qu})],cf.prototype,`issuerAndSerialNumber`,void 0),cf=X([q({type:G.Choice})],cf);var lf=class{version=ed.v0;rid=new cf;keyEncryptionAlgorithm=new rd;encryptedKey=new dc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],lf.prototype,`version`,void 0),X([J({type:cf})],lf.prototype,`rid`,void 0),X([J({type:rd})],lf.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:dc})],lf.prototype,`encryptedKey`,void 0);var uf=class{keyIdentifier=new dc;date;other;constructor(e={}){Object.assign(this,e)}};X([J({type:dc})],uf.prototype,`keyIdentifier`,void 0),X([J({type:K.GeneralizedTime,optional:!0})],uf.prototype,`date`,void 0),X([J({type:Qd,optional:!0})],uf.prototype,`other`,void 0);var df=class{version=ed.v4;kekid=new uf;keyEncryptionAlgorithm=new rd;encryptedKey=new dc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],df.prototype,`version`,void 0),X([J({type:uf})],df.prototype,`kekid`,void 0),X([J({type:rd})],df.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:dc})],df.prototype,`encryptedKey`,void 0);var ff=class{version=ed.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new rd;encryptedKey=new dc;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],ff.prototype,`version`,void 0),X([J({type:od,context:0,optional:!0})],ff.prototype,`keyDerivationAlgorithm`,void 0),X([J({type:rd})],ff.prototype,`keyEncryptionAlgorithm`,void 0),X([J({type:dc})],ff.prototype,`encryptedKey`,void 0);var pf=class{oriType=``;oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],pf.prototype,`oriType`,void 0),X([J({type:K.Any})],pf.prototype,`oriValue`,void 0);var mf=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};X([J({type:lf,optional:!0})],mf.prototype,`ktri`,void 0),X([J({type:sf,context:1,implicit:!0,optional:!0})],mf.prototype,`kari`,void 0),X([J({type:df,context:2,implicit:!0,optional:!0})],mf.prototype,`kekri`,void 0),X([J({type:ff,context:3,implicit:!0,optional:!0})],mf.prototype,`pwri`,void 0),X([J({type:pf,context:4,implicit:!0,optional:!0})],mf.prototype,`ori`,void 0),mf=X([q({type:G.Choice})],mf);var hf,gf=hf=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,hf.prototype)}};gf=hf=X([q({type:G.Set,itemType:mf})],gf);var _f,vf=`${ll}.16`;`${vf}`,`${vf}`;var yf=class{otherRevInfoFormat=``;otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],yf.prototype,`otherRevInfoFormat`,void 0),X([J({type:K.Any})],yf.prototype,`otherRevInfo`,void 0);var bf=class{other=new yf;constructor(e={}){Object.assign(this,e)}};X([J({type:yf,context:1,implicit:!0})],bf.prototype,`other`,void 0),bf=X([q({type:G.Choice})],bf);var xf=_f=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,_f.prototype)}};xf=_f=X([q({type:G.Set,itemType:bf})],xf);var Sf=class{certs;crls;constructor(e={}){Object.assign(this,e)}};X([J({type:Kd,context:0,implicit:!0,optional:!0})],Sf.prototype,`certs`,void 0),X([J({type:xf,context:1,implicit:!0,optional:!0})],Sf.prototype,`crls`,void 0);var Cf,wf=Cf=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Cf.prototype)}};wf=Cf=X([q({type:G.Set,itemType:sd})],wf);var Tf=class{version=ed.v0;originatorInfo;recipientInfos=new gf;encryptedContentInfo=new Zd;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Tf.prototype,`version`,void 0),X([J({type:Sf,context:0,implicit:!0,optional:!0})],Tf.prototype,`originatorInfo`,void 0),X([J({type:gf})],Tf.prototype,`recipientInfos`,void 0),X([J({type:Zd})],Tf.prototype,`encryptedContentInfo`,void 0),X([J({type:wf,context:1,implicit:!0,optional:!0})],Tf.prototype,`unprotectedAttrs`,void 0);var Ef=`1.2.840.113549.1.7.2`,Df,Of=Df=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Df.prototype)}};Of=Df=X([q({type:G.Set,itemType:td})],Of);var kf=class{version=ed.v0;digestAlgorithms=new Of;encapContentInfo=new Yd;certificates;crls;signerInfos=new ud;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],kf.prototype,`version`,void 0),X([J({type:Of})],kf.prototype,`digestAlgorithms`,void 0),X([J({type:Yd})],kf.prototype,`encapContentInfo`,void 0),X([J({type:Kd,context:0,implicit:!0,optional:!0})],kf.prototype,`certificates`,void 0),X([J({type:xf,context:1,implicit:!0,optional:!0})],kf.prototype,`crls`,void 0),X([J({type:ud})],kf.prototype,`signerInfos`,void 0);var Af=`1.2.840.10045.2.1`,jf=`1.2.840.10045.4.1`,Mf=`1.2.840.10045.4.3.1`,Nf=`1.2.840.10045.4.3.2`,Pf=`1.2.840.10045.4.3.3`,Ff=`1.2.840.10045.4.3.4`,If=`1.2.840.10045.3.1.7`,Lf=`1.3.132.0.34`,Rf=`1.3.132.0.35`;function zf(e){return new Z({algorithm:e})}var Bf=zf(jf);zf(Mf);var Vf=zf(Nf),Hf=zf(Pf),Uf=zf(Ff),Wf=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Wf.prototype,`fieldType`,void 0),X([J({type:K.Any})],Wf.prototype,`parameters`,void 0),Wf=X([q({type:G.Sequence})],Wf);var Gf=class extends dc{},Kf=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};X([J({type:K.OctetString})],Kf.prototype,`a`,void 0),X([J({type:K.OctetString})],Kf.prototype,`b`,void 0),X([J({type:K.BitString,optional:!0})],Kf.prototype,`seed`,void 0),Kf=X([q({type:G.Sequence})],Kf);var qf;(function(e){e[e.ecpVer1=1]=`ecpVer1`})(qf||={});var Jf=class{version=qf.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Jf.prototype,`version`,void 0),X([J({type:Wf})],Jf.prototype,`fieldID`,void 0),X([J({type:Kf})],Jf.prototype,`curve`,void 0),X([J({type:Gf})],Jf.prototype,`base`,void 0),X([J({type:K.Integer,converter:hc})],Jf.prototype,`order`,void 0),X([J({type:K.Integer,optional:!0})],Jf.prototype,`cofactor`,void 0),Jf=X([q({type:G.Sequence})],Jf);var Yf=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Yf.prototype,`namedCurve`,void 0),X([J({type:K.Null})],Yf.prototype,`implicitCurve`,void 0),X([J({type:Jf})],Yf.prototype,`specifiedCurve`,void 0),Yf=X([q({type:G.Choice})],Yf);var Xf=class{version=1;privateKey=new dc;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Xf.prototype,`version`,void 0),X([J({type:dc})],Xf.prototype,`privateKey`,void 0),X([J({type:Yf,context:0,optional:!0})],Xf.prototype,`parameters`,void 0),X([J({type:K.BitString,context:1,optional:!0})],Xf.prototype,`publicKey`,void 0);var Zf=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:hc})],Zf.prototype,`r`,void 0),X([J({type:K.Integer,converter:hc})],Zf.prototype,`s`,void 0);var Qf=`1.2.840.113549.1.1`,$f=`${Qf}.1`,ep=`${Qf}.7`,tp=`${Qf}.9`,np=`${Qf}.10`,rp=`${Qf}.2`,ip=`${Qf}.4`,ap=`${Qf}.5`,op=`${Qf}.14`,sp=`${Qf}.11`,cp=`${Qf}.12`,lp=`${Qf}.13`,up=`${Qf}.15`,dp=`${Qf}.16`,fp=`1.3.14.3.2.26`,pp=`2.16.840.1.101.3.4.2.4`,mp=`2.16.840.1.101.3.4.2.1`,hp=`2.16.840.1.101.3.4.2.2`,gp=`2.16.840.1.101.3.4.2.3`,_p=`2.16.840.1.101.3.4.2.5`,vp=`2.16.840.1.101.3.4.2.6`,yp=`1.2.840.113549.2.2`,bp=`1.2.840.113549.2.5`,xp=`${Qf}.8`;function Sp(e){return new Z({algorithm:e,parameters:null})}Sp(yp),Sp(bp);var Cp=Sp(fp);Sp(pp),Sp(mp),Sp(hp),Sp(gp),Sp(_p),Sp(vp);var wp=new Z({algorithm:xp,parameters:Y.serialize(Cp)}),Tp=new Z({algorithm:tp,parameters:Y.serialize(bc.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});Sp($f),Sp(rp),Sp(ip),Sp(ap),Sp(up),Sp(dp),Sp(cp),Sp(lp),Sp(up),Sp(dp);var Ep=class{hashAlgorithm=new Z(Cp);maskGenAlgorithm=new Z({algorithm:xp,parameters:Y.serialize(Cp)});pSourceAlgorithm=new Z(Tp);constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:Cp})],Ep.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:wp})],Ep.prototype,`maskGenAlgorithm`,void 0),X([J({type:Z,context:2,defaultValue:Tp})],Ep.prototype,`pSourceAlgorithm`,void 0),new Z({algorithm:ep,parameters:Y.serialize(new Ep)});var Dp=class{hashAlgorithm=new Z(Cp);maskGenAlgorithm=new Z({algorithm:xp,parameters:Y.serialize(Cp)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};X([J({type:Z,context:0,defaultValue:Cp})],Dp.prototype,`hashAlgorithm`,void 0),X([J({type:Z,context:1,defaultValue:wp})],Dp.prototype,`maskGenAlgorithm`,void 0),X([J({type:K.Integer,context:2,defaultValue:20})],Dp.prototype,`saltLength`,void 0),X([J({type:K.Integer,context:3,defaultValue:1})],Dp.prototype,`trailerField`,void 0),new Z({algorithm:np,parameters:Y.serialize(new Dp)});var Op=class{digestAlgorithm=new Z;digest=new dc;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Op.prototype,`digestAlgorithm`,void 0),X([J({type:dc})],Op.prototype,`digest`,void 0);var kp,Ap=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:hc})],Ap.prototype,`prime`,void 0),X([J({type:K.Integer,converter:hc})],Ap.prototype,`exponent`,void 0),X([J({type:K.Integer,converter:hc})],Ap.prototype,`coefficient`,void 0);var jp=kp=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,kp.prototype)}};jp=kp=X([q({type:G.Sequence,itemType:Ap})],jp);var Mp=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})],Mp.prototype,`version`,void 0),X([J({type:K.Integer,converter:hc})],Mp.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:hc})],Mp.prototype,`publicExponent`,void 0),X([J({type:K.Integer,converter:hc})],Mp.prototype,`privateExponent`,void 0),X([J({type:K.Integer,converter:hc})],Mp.prototype,`prime1`,void 0),X([J({type:K.Integer,converter:hc})],Mp.prototype,`prime2`,void 0),X([J({type:K.Integer,converter:hc})],Mp.prototype,`exponent1`,void 0),X([J({type:K.Integer,converter:hc})],Mp.prototype,`exponent2`,void 0),X([J({type:K.Integer,converter:hc})],Mp.prototype,`coefficient`,void 0),X([J({type:jp,optional:!0})],Mp.prototype,`otherPrimeInfos`,void 0);var Np=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer,converter:hc})],Np.prototype,`modulus`,void 0),X([J({type:K.Integer,converter:hc})],Np.prototype,`publicExponent`,void 0);var Pp;(function(e){e[e.Transient=0]=`Transient`,e[e.Singleton=1]=`Singleton`,e[e.ResolutionScoped=2]=`ResolutionScoped`,e[e.ContainerScoped=3]=`ContainerScoped`})(Pp||={});var Fp=Pp,Ip=function(e,t){return Ip=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])},Ip(e,t)};function Lp(e,t){Ip(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function Rp(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 zp(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 Bp(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 Vp(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 Hp(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Vp(arguments[t]));return e}function Up(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 Wp(e){return!!e.useClass}function Gp(e){return!!e.useFactory}var Kp=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,Hp(t))}}),t},e}();function qp(e){return typeof e==`string`||typeof e==`symbol`}function Jp(e){return typeof e==`object`&&`token`in e&&`multiple`in e}function Yp(e){return typeof e==`object`&&`token`in e&&`transform`in e}function Xp(e){return typeof e==`function`||e instanceof Kp}function Zp(e){return!!e.useToken}function Qp(e){return e.useValue!=null}function $p(e){return Wp(e)||Qp(e)||Zp(e)||Gp(e)}var em=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}(),tm=function(e){Lp(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(em),nm=function(){function e(){this.scopedResolutions=new Map}return e}();function rm(e,t){return e===null?`at position #`+t:`"`+e.split(`,`)[t].trim()+`" at position #`+t}function im(e,t,n){return n===void 0&&(n=` `),Hp([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 am(e,t,n){var r=Vp(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return im(`Cannot inject the dependency `+rm(r===void 0?null:r,t)+` of "`+e.name+`" constructor. Reason:`,n)}function om(e){return!(typeof e.dispose!=`function`||e.dispose.length>0)}var sm=function(e){Lp(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(em),cm=function(e){Lp(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(em),lm=function(){function e(){this.preResolution=new sm,this.postResolution=new cm}return e}(),um=new Map,dm=new(function(){function e(e){this.parent=e,this._registry=new tm,this.interceptors=new lm,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,n){n===void 0&&(n={lifecycle:Fp.Transient}),this.ensureNotDisposed();var r=$p(t)?t:{useClass:t};if(Zp(r))for(var i=[e],a=r;a!=null;){var o=a.useToken;if(i.includes(o))throw Error(`Token registration cycle detected! `+Hp(i,[o]).join(` -> `));i.push(o);var s=this._registry.get(o);a=s&&Zp(s.provider)?s.provider:null}if((n.lifecycle===Fp.Singleton||n.lifecycle==Fp.ContainerScoped||n.lifecycle==Fp.ResolutionScoped)&&(Qp(r)||Gp(r)))throw Error(`Cannot use lifecycle "`+Fp[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(),qp(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(),qp(e)){if(qp(t))return this.register(e,{useToken:t},{lifecycle:Fp.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:Fp.Singleton});throw Error(`Cannot register a type name as a singleton without a "to" token`)}var n=e;return t&&!qp(t)&&(n=t),this.register(e,{useClass:n},{lifecycle:Fp.Singleton})},e.prototype.resolve=function(e,t,n){t===void 0&&(t=new nm),n===void 0&&(n=!1),this.ensureNotDisposed();var r=this.getRegistration(e);if(!r&&qp(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(Xp(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=Bp(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=Bp(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===Fp.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var n=e.options.lifecycle===Fp.Singleton,r=e.options.lifecycle===Fp.ContainerScoped,i=n||r,a=Qp(e.provider)?e.provider.useValue:Zp(e.provider)?i?e.instance||=this.resolve(e.provider.useToken,t):this.resolve(e.provider.useToken,t):Wp(e.provider)?i?e.instance||=this.construct(e.provider.useClass,t):this.construct(e.provider.useClass,t):Gp(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t);return e.options.lifecycle===Fp.ResolutionScoped&&t.scopedResolutions.set(e,a),a},e.prototype.resolveAll=function(e,t,n){var r=this;t===void 0&&(t=new nm),n===void 0&&(n=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&qp(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=Bp(this._registry.entries()),r=n.next();!r.done;r=n.next()){var i=Vp(r.value,2),a=i[0],o=i[1];this._registry.setAll(a,o.filter(function(e){return!Qp(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=Bp(this._registry.entries()),a=i.next();!a.done;a=i.next()){var o=Vp(a.value,2),s=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===Fp.ContainerScoped})&&r._registry.setAll(s,c.map(function(e){return e.options.lifecycle===Fp.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 Rp(this,void 0,void 0,function(){var e;return zp(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 Kp)return e.createProxy(function(e){return n.resolve(e,t)});var r=(function(){var r=um.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,Hp([void 0],i)))})();return om(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 Jp(r)?Yp(r)?r.multiple?(a=n.resolve(r.transform)).transform.apply(a,Hp([n.resolveAll(r.token,new nm,r.isOptional)],r.transformArgs)):(o=n.resolve(r.transform)).transform.apply(o,Hp([n.resolve(r.token,e,r.isOptional)],r.transformArgs)):r.multiple?n.resolveAll(r.token,new nm,r.isOptional):n.resolve(r.token,e,r.isOptional):Yp(r)?(s=n.resolve(r.transform,e)).transform.apply(s,Hp([n.resolve(r.token,e)],r.transformArgs)):n.resolve(r,e)}catch(e){throw Error(am(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 fm(e){return function(t){um.set(t,Up(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){dm.register(e,t)}):dm.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 pm,mm=class{attrId=``;attrValues=[];constructor(e={}){Object.assign(e)}};X([J({type:K.ObjectIdentifier})],mm.prototype,`attrId`,void 0),X([J({type:K.Any,repeated:`set`})],mm.prototype,`attrValues`,void 0);var hm=pm=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,pm.prototype)}};hm=pm=X([q({type:G.Sequence,itemType:mm})],hm);var gm,_m=gm=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,gm.prototype)}};_m=gm=X([q({type:G.Sequence,itemType:qd})],_m);var vm=`1.2.840.113549.1.12`,ym=`${vm}.1`;`${ym}`,`${ym}`,`${ym}`,`${ym}`,`${ym}`,`${ym}`;var bm=`${vm}.10.1`;`${bm}`,`${bm}`,`${bm}`,`${bm}`,`${bm}`,`${bm}`;var xm=`1.2.840.113549.1.9`,Sm=class{certId=``;certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Sm.prototype,`certId`,void 0),X([J({type:K.Any,context:0})],Sm.prototype,`certValue`,void 0);var Cm=`${xm}.22`;`${Cm}`,`${Cm}`;var wm=class{crlId=``;crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],wm.prototype,`crlId`,void 0),X([J({type:K.Any,context:0})],wm.prototype,`crltValue`,void 0),`${xm}`;var Tm=class extends dc{},Em=class{encryptionAlgorithm=new Z;encryptedData=new Tm;constructor(e={}){Object.assign(this,e)}};X([J({type:Z})],Em.prototype,`encryptionAlgorithm`,void 0),X([J({type:Tm})],Em.prototype,`encryptedData`,void 0);var Dm,Om;(function(e){e[e.v1=0]=`v1`})(Om||={});var km=class extends dc{},Am=Dm=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Dm.prototype)}};Am=Dm=X([q({type:G.Sequence,itemType:ku})],Am);var jm=class{version=Om.v1;privateKeyAlgorithm=new Z;privateKey=new km;attributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],jm.prototype,`version`,void 0),X([J({type:Z})],jm.prototype,`privateKeyAlgorithm`,void 0),X([J({type:km})],jm.prototype,`privateKey`,void 0),X([J({type:Am,implicit:!0,context:0,optional:!0})],jm.prototype,`attributes`,void 0);var Mm=class extends jm{};Mm=X([q({type:G.Sequence})],Mm);var Nm=class extends Em{};Nm=X([q({type:G.Sequence})],Nm);var Pm=class{secretTypeId=``;secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Pm.prototype,`secretTypeId`,void 0),X([J({type:K.Any,context:0})],Pm.prototype,`secretValue`,void 0);var Fm=class{mac=new Op;macSalt=new dc;iterations=1;constructor(e={}){Object.assign(this,e)}};X([J({type:Op})],Fm.prototype,`mac`,void 0),X([J({type:dc})],Fm.prototype,`macSalt`,void 0),X([J({type:K.Integer,defaultValue:1})],Fm.prototype,`iterations`,void 0);var Im=class{version=3;authSafe=new qd;macData=new Fm;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Im.prototype,`version`,void 0),X([J({type:qd})],Im.prototype,`authSafe`,void 0),X([J({type:Fm,optional:!0})],Im.prototype,`macData`,void 0);var Lm,Rm=class{bagId=``;bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};X([J({type:K.ObjectIdentifier})],Rm.prototype,`bagId`,void 0),X([J({type:K.Any,context:0})],Rm.prototype,`bagValue`,void 0),X([J({type:mm,repeated:`set`,optional:!0})],Rm.prototype,`bagAttributes`,void 0);var zm=Lm=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Lm.prototype)}};zm=Lm=X([q({type:G.Sequence,itemType:Rm})],zm);var Bm,Vm,Hm,Um=`1.2.840.113549.1.9`;`${Um}`;var Wm=`${Um}.24`,Gm=`${Um}.25`,Km=`${Um}.26`,qm=`${Um}.27`;`${Wm}`,`${Wm}`,`${Um}`,`${Um}`,`${Um}`,`${Um}`,`${Um}`,`${Um}`;var Jm=`${Um}.7`;`${Um}`,`${Um}`,`${Um}`;var Ym=`${Um}.14`;`${Um}`,`${Um}`,`${Um}`,`${Gm}`,`${Gm}`,`${Gm}`,`${Gm}`,`${Gm}`;var Xm=`1.3.6.1.5.5.7.9`;`${Xm}`,`${Xm}`,`${Xm}`,`${Xm}`,`${Xm}`,`${Km}`,`${Km}`,`${qm}`,`${qm}`,`${Um}`,`${Um}`,`${Um}`,`${Pd}`;var Zm=class extends $c{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};X([J({type:K.IA5String})],Zm.prototype,`ia5String`,void 0),Zm=X([q({type:G.Choice})],Zm);var Qm=class extends qd{};Qm=X([q({type:G.Sequence})],Qm);var $m=class extends Im{};$m=X([q({type:G.Sequence})],$m);var eh=class extends Em{};eh=X([q({type:G.Sequence})],eh);var th=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.IA5String})],th.prototype,`value`,void 0),th=X([q({type:G.Choice})],th);var nh=class extends Zm{};nh=X([q({type:G.Choice})],nh);var rh=class extends $c{};rh=X([q({type:G.Choice})],rh);var ih=class{value;constructor(e=new Date){this.value=e}};X([J({type:K.GeneralizedTime})],ih.prototype,`value`,void 0),ih=X([q({type:G.Choice})],ih);var ah=class extends $c{};ah=X([q({type:G.Choice})],ah);var oh=class{value;constructor(e=`M`){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],oh.prototype,`value`,void 0),oh=X([q({type:G.Choice})],oh);var sh=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.PrintableString})],sh.prototype,`value`,void 0),sh=X([q({type:G.Choice})],sh);var ch=class extends sh{};ch=X([q({type:G.Choice})],ch);var lh=class extends $c{};lh=X([q({type:G.Choice})],lh);var uh=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.ObjectIdentifier})],uh.prototype,`value`,void 0),uh=X([q({type:G.Choice})],uh);var dh=class extends Vu{};dh=X([q({type:G.Choice})],dh);var fh=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};X([J({type:K.Integer})],fh.prototype,`value`,void 0),fh=X([q({type:G.Choice})],fh);var ph=class extends ld{};ph=X([q({type:G.Sequence})],ph);var mh=class extends $c{};mh=X([q({type:G.Choice})],mh);var hh=Bm=class extends Gu{constructor(e){super(e),Object.setPrototypeOf(this,Bm.prototype)}};hh=Bm=X([q({type:G.Sequence})],hh);var gh=Vm=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Vm.prototype)}};gh=Vm=X([q({type:G.Set,itemType:sd})],gh);var _h=class{value;constructor(e=``){this.value=e}toString(){return this.value}};X([J({type:K.BmpString})],_h.prototype,`value`,void 0),_h=X([q({type:G.Choice})],_h);var vh=class extends Z{};vh=X([q({type:G.Sequence})],vh);var yh=Hm=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,Hm.prototype)}};yh=Hm=X([q({type:G.Sequence,itemType:vh})],yh);var bh,xh=bh=class extends Kc{constructor(e){super(e),Object.setPrototypeOf(this,bh.prototype)}};xh=bh=X([q({type:G.Sequence,itemType:ku})],xh);var Sh=class{version=0;subject=new il;subjectPKInfo=new Bu;attributes=new xh;constructor(e={}){Object.assign(this,e)}};X([J({type:K.Integer})],Sh.prototype,`version`,void 0),X([J({type:il})],Sh.prototype,`subject`,void 0),X([J({type:Bu})],Sh.prototype,`subjectPKInfo`,void 0),X([J({type:xh,implicit:!0,context:0,optional:!0})],Sh.prototype,`attributes`,void 0);var Ch=class{certificationRequestInfo=new Sh;certificationRequestInfoRaw;signatureAlgorithm=new Z;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};X([J({type:Sh,raw:!0})],Ch.prototype,`certificationRequestInfo`,void 0),X([J({type:Z})],Ch.prototype,`signatureAlgorithm`,void 0),X([J({type:K.BitString})],Ch.prototype,`signature`,void 0);var wh=`crypto.algorithm`,Th=class{getAlgorithms(){return dm.resolveAll(wh)}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}}},Eh=`crypto.algorithmProvider`;dm.registerSingleton(Eh,Th);var Dh,Oh=`1.3.36.3.3.2.8.1.1`,kh=`${Oh}.1`,Ah=`${Oh}.2`,jh=`${Oh}.3`,Mh=`${Oh}.4`,Nh=`${Oh}.5`,Ph=`${Oh}.6`,Fh=`${Oh}.7`,Ih=`${Oh}.8`,Lh=`${Oh}.9`,Rh=`${Oh}.10`,zh=`${Oh}.11`,Bh=`${Oh}.12`,Vh=`${Oh}.13`,Hh=`${Oh}.14`,Uh=`brainpoolP160r1`,Wh=`brainpoolP160t1`,Gh=`brainpoolP192r1`,Kh=`brainpoolP192t1`,qh=`brainpoolP224r1`,Jh=`brainpoolP224t1`,Yh=`brainpoolP256r1`,Xh=`brainpoolP256t1`,Zh=`brainpoolP320r1`,Qh=`brainpoolP320t1`,$h=`brainpoolP384r1`,eg=`brainpoolP384t1`,tg=`brainpoolP512r1`,ng=`brainpoolP512t1`,rg=`ECDSA`,ig=Dh=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case rg.toLowerCase():if(`hash`in e)switch((typeof e.hash==`string`?e.hash:e.hash.name).toLowerCase()){case`sha-1`:return Bf;case`sha-256`:return Vf;case`sha-384`:return Hf;case`sha-512`:return Uf}else if(`namedCurve`in e){let t=``;switch(e.namedCurve){case`P-256`:t=If;break;case`K-256`:t=Dh.SECP256K1;break;case`P-384`:t=Lf;break;case`P-521`:t=Rf;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;break;case Xh:t=Ih;break;case Zh:t=Lh;break;case Qh:t=Rh;break;case $h:t=zh;break;case eg:t=Bh;break;case tg:t=Vh;break;case ng:t=Hh}if(t)return new Z({algorithm:Af,parameters:Y.serialize(new Yf({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case jf:return{name:rg,hash:{name:`SHA-1`}};case Nf:return{name:rg,hash:{name:`SHA-256`}};case Pf:return{name:rg,hash:{name:`SHA-384`}};case Ff:return{name:rg,hash:{name:`SHA-512`}};case Af:if(!e.parameters)throw TypeError(`Cannot get required parameters from EC algorithm`);switch(Y.parse(e.parameters,Yf).namedCurve){case If:return{name:rg,namedCurve:`P-256`};case Dh.SECP256K1:return{name:rg,namedCurve:`K-256`};case Lf:return{name:rg,namedCurve:`P-384`};case Rf:return{name:rg,namedCurve:`P-521`};case kh:return{name:rg,namedCurve:Uh};case Ah:return{name:rg,namedCurve:Wh};case jh:return{name:rg,namedCurve:Gh};case Mh:return{name:rg,namedCurve:Kh};case Nh:return{name:rg,namedCurve:qh};case Ph:return{name:rg,namedCurve:Jh};case Fh:return{name:rg,namedCurve:Yh};case Ih:return{name:rg,namedCurve:Xh};case Lh:return{name:rg,namedCurve:Zh};case Rh:return{name:rg,namedCurve:Qh};case zh:return{name:rg,namedCurve:$h};case Bh:return{name:rg,namedCurve:eg};case Vh:return{name:rg,namedCurve:tg};case Hh:return{name:rg,namedCurve:ng}}}return null}};ig.SECP256K1=`1.3.132.0.10`,ig=Dh=X([fm()],ig),dm.registerSingleton(wh,ig);var ag=Symbol(`name`),og=Symbol(`value`),sg=class{constructor(e,t={},n=``){this[ag]=e,this[og]=n;for(let e in t)this[e]=t[e]}};sg.NAME=ag,sg.VALUE=og;var cg=class{static toTextObject(e){let t=new sg(`Algorithm Identifier`,{},lg.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Af:{let n=new ig().toWebAlgorithm(e);n&&`namedCurve`in n?t[`Named Curve`]=n.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}},lg=class{static toString(e){return this.items[e]||e}};lg.items={[fp]:`sha1`,[pp]:`sha224`,[mp]:`sha256`,[hp]:`sha384`,[gp]:`sha512`,[$f]:`rsaEncryption`,[ap]:`sha1WithRSAEncryption`,[op]:`sha224WithRSAEncryption`,[sp]:`sha256WithRSAEncryption`,[cp]:`sha384WithRSAEncryption`,[lp]:`sha512WithRSAEncryption`,[Af]:`ecPublicKey`,[jf]:`ecdsaWithSHA1`,[Mf]:`ecdsaWithSHA224`,[Nf]:`ecdsaWithSHA256`,[Pf]:`ecdsaWithSHA384`,[Ff]:`ecdsaWithSHA512`,[iu]:`TLS WWW server authentication`,[au]:`TLS WWW client authentication`,[ou]:`Code Signing`,[su]:`E-mail Protection`,[cu]:`Time Stamping`,[lu]:`OCSP Signing`,[Ef]:`Signed Data`};var ug=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[sg.VALUE];a&&(i=` ${a}`),n.push(`${r}${e[sg.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[sg.NAME]=i,n.push(...this.serializeObj(e,t));else if(a instanceof sg)a[sg.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[sg.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)}};ug.oidSerializer=lg,ug.algorithmSerializer=cg;var dg,fg=class e{get rawData(){return qc(this,dg,`f`)||Jc(this,dg,Y.serialize(this.asn),`f`),qc(this,dg,`f`)}constructor(...e){dg.set(this,void 0),U.isBufferSource(e[0])?(this.asn=Y.parse(e[0],e[1]),Jc(this,dg,U.toArrayBuffer(e[0]),`f`),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(t){return t instanceof e&&di(t.rawData,this.rawData)}toString(e=`text`){switch(e){case`asn`:return Y.toString(this.rawData);case`text`:return ug.serialize(this.toTextObject());case`hex`:return li.ToHex(this.rawData);case`base64`:return li.ToBase64(this.rawData);case`base64url`:return li.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 sg(this.getTextName(),{},e)}};dg=new WeakMap,fg.NAME=`ASN`;var pg=class e extends fg{constructor(...e){let t;t=U.isBufferSource(e[0])?U.toArrayBuffer(e[0]):Y.serialize(new Wu({extnID:e[0],critical:e[1],extnValue:new dc(U.toArrayBuffer(e[2]))})),super(t,Wu)}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[sg.NAME]===e.NAME&&(t[sg.NAME]=lg.toString(this.type)),t}},mg,hg=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[mg]=`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}};mg=Symbol.toStringTag,hg.DEFAULT=`default`;var gg=new hg,_g=/^[0-2](?:\.[1-9][0-9]*)+$/;function vg(e){return new RegExp(_g).test(e)}var yg=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 vg(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},bg=new yg;bg.register(`CN`,`2.5.4.3`),bg.register(`L`,`2.5.4.7`),bg.register(`ST`,`2.5.4.8`),bg.register(`O`,`2.5.4.10`),bg.register(`OU`,`2.5.4.11`),bg.register(`C`,`2.5.4.6`),bg.register(`DC`,`0.9.2342.19200300.100.1.25`),bg.register(`E`,`1.2.840.113549.1.9.1`),bg.register(`G`,`2.5.4.42`),bg.register(`I`,`2.5.4.43`),bg.register(`SN`,`2.5.4.4`),bg.register(`T`,`2.5.4.12`);function xg(e,t){return`\\${li.ToHex(li.FromUtf8String(t)).toUpperCase()}`}function Sg(e){return e.replace(/([,+"\\<>;])/g,`\\$1`).replace(/^([ #])/,`\\$1`).replace(/([ ]$)/,`\\$1`).replace(/([\r\n\t])/,xg)}var Cg=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 yg,this.asn=new il;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 il?e:U.isBufferSource(e)?Y.parse(e,il):this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||bg.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)||bg.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${li.ToHex(e.value.anyValue)}`:Sg(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?`#${li.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(n)}return e}fromString(e){let t=new il,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 nl([s])),i=o}return t}fromJSON(e){let t=new il;for(let n of e){let e=new nl;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 tl({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=li.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]||gg.get()):t=e[0]||gg.get(),await t.subtle.digest(n,this.toArrayBuffer())}},wg=`Cannot initialize GeneralName from ASN.1 data.`,Tg=`${wg} Unsupported string format in use.`,Eg=`${wg} Value doesn't match to GUID regular expression.`,Dg=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Og=`1.3.6.1.4.1.311.25.1`,kg=`1.3.6.1.4.1.311.20.2.3`,Ag=`email`,jg=`guid`,Mg=class extends fg{constructor(...e){let t;if(e.length===2)switch(e[0]){case`dn`:{let n=new Cg(e[1]).toArrayBuffer(),r=Y.parse(n,il);t=new cl({directoryName:r});break}case`dns`:t=new cl({dNSName:e[1]});break;case Ag:t=new cl({rfc822Name:e[1]});break;case jg:{let n=new RegExp(Dg,`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?li.ToHex(new Uint8Array(li.FromHex(e)).reverse()):e).join(``);t=new cl({otherName:new ol({typeId:Og,value:Y.serialize(new dc(li.FromHex(r)))})});break}case`ip`:t=new cl({iPAddress:e[1]});break;case`id`:t=new cl({registeredID:e[1]});break;case`upn`:t=new cl({otherName:new ol({typeId:kg,value:Y.serialize(Cc.toASN(e[1]))})});break;case`url`:t=new cl({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],cl):e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=`dns`,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Ag,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 Cg(e.directoryName).toString();else if(e.otherName!=null){if(e.otherName.typeId===Og){this.type=jg;let t=Y.parse(e.otherName.value,dc),n=new RegExp(Dg,`i`).exec(li.ToHex(t));if(!n)throw Error(Eg);this.value=n.slice(1).map((e,t)=>t<3?li.ToHex(new Uint8Array(li.FromHex(e)).reverse()):e).join(`-`)}else if(e.otherName.typeId===kg)this.type=`upn`,this.value=Y.parse(e.otherName.value,$c).toString();else throw Error(Tg)}else throw Error(Tg)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case`dn`:case`dns`:case jg:case`ip`:case`id`:case`upn`:case`url`:e=this.type.toUpperCase();break;case Ag:e=`Email`;break;default:throw Error(`Unsupported GeneralName type`)}let t=this.value;return this.type===`id`&&(t=lg.toString(t)),new sg(e,void 0,t)}},Ng=class extends fg{constructor(e){let t;if(e instanceof kl)t=e;else if(Array.isArray(e)){let n=[];for(let t of e)if(t instanceof cl)n.push(t);else{let e=Y.parse(new Mg(t.type,t.value).rawData,cl);n.push(e)}t=new kl(n)}else if(U.isBufferSource(e))t=Y.parse(e,kl);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 Mg(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[sg.NAME]];Array.isArray(r)||(r=[],e[n[sg.NAME]]=r),r.push(n)}return e}};Ng.NAME=`GeneralNames`;var Pg=`-{5}`,Fg=`\\n`,Ig=`${Pg}BEGIN (${`[^${Fg}]+`}(?=${Pg}))${Pg}`,Lg=`${Pg}END \\1${Pg}`,Rg=`\\n`,zg=`${Ig}${Rg}(?:((?:${`[^:${Fg}]+`}: ${`(?:[^${Fg}]+${Rg}(?: +[^${Fg}]+${Rg})*)`})+))?${Rg}?(${`(?:[a-zA-Z0-9=+/]+${Rg})+`})${Lg}`,Bg=class{static isPem(e){return typeof e==`string`&&new RegExp(zg,`g`).test(e.replace(/\r/g,``))}static decodeWithHeaders(e){e=e.replace(/\r/g,``);let t=new RegExp(zg,`g`),n=[],r=null;for(;r=t.exec(e);){let e=r[3].replace(RegExp(`[${Fg}]+`,`g`),``),t={type:r[1],headers:[],rawData:li.FromBase64(e)},i=r[2];if(i){let e=i.split(new RegExp(Rg,`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=li.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
+ `)}};Bg.CertificateTag=`CERTIFICATE`,Bg.CrlTag=`CRL`,Bg.CertificateRequestTag=`CERTIFICATE REQUEST`,Bg.PublicKeyTag=`PUBLIC KEY`,Bg.PrivateKeyTag=`PRIVATE KEY`;var Vg=class e extends fg{static isAsnEncoded(e){return U.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(Bg.isPem(e))return Bg.decode(e)[0];if(li.isHex(e))return li.FromHex(e);if(li.isBase64(e))return li.FromBase64(e);if(li.isBase64Url(e))return li.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=li.ToBinary(e);if(Bg.isPem(n))return Bg.decode(n)[0];if(li.isHex(n))return li.FromHex(n);if(li.isBase64(n))return li.FromBase64(n);if(li.isBase64Url(n))return li.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 Bg.encode(this.rawData,this.tag);default:return super.toString(e)}}},Hg=class e extends Vg{static async create(t,n=gg.get()){if(t instanceof e)return t;if(hg.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){Vg.isAsnEncoded(e)?super(e,Bu):super(e),this.tag=Bg.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]||gg.get()):t=e[0]||gg.get();let i=this.rawData,a=Y.parse(this.rawData,Bu);return a.algorithm.algorithm===np&&(i=Ug(a,i)),t.subtle.importKey(`spki`,i,r,!0,n)}onInit(e){let t=dm.resolve(Eh),n=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case $f:{let t=Y.parse(e.subjectPublicKey,Np),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]||gg.get()):t=e[0]||gg.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=gg.get()):t=e[0]:e.length===2?(n=e[0],t=e[1]):t=gg.get();let r=Y.parse(this.rawData,Bu);return await t.subtle.digest(n,r.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,Bu);switch(e.Algorithm=ug.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Af:e[`EC Point`]=t.subjectPublicKey;break;case $f:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function Ug(e,t){return e.algorithm=new Z({algorithm:$f,parameters:null}),t=Y.serialize(e),t}var Wg=class e extends pg{static async create(t,n=!1,r=gg.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let i=await(await Hg.create(t,r)).getKeyIdentifier(r);return new e(li.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new Tl({keyIdentifier:new wl(li.FromHex(e[0]))});super(Cl,e[1],Y.serialize(t))}else{let t=e[0],n=new Tl({authorityCertIssuer:t.name instanceof Ng?Y.parse(t.name.rawData,kl):t.name,authorityCertSerialNumber:li.FromHex(t.serialNumber)});super(Cl,e[1],Y.serialize(n))}}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Tl);t.keyIdentifier&&(this.keyId=li.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?li.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=Y.parse(this.value,Tl);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new Ng(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};Wg.NAME=`Authority Key Identifier`;var Gg=class extends pg{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Dl);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new Dl({cA:e[0],pathLenConstraint:e[1]});super(El,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}};Gg.NAME=`Basic Constraints`;var Kg;(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`})(Kg||={});var qg=class extends pg{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,ru);this.usages=t.map(e=>e)}else{let t=new ru(e[0]);super(nu,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.usages.map(e=>lg.toString(e)).join(`, `),e}};qg.NAME=`Extended Key Usages`;var Jg;(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`})(Jg||={});var Yg=class extends pg{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,_u);this.usages=t.toNumber()}else{let t=new _u(e[0]);super(hu,e[1],Y.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,_u).toJSON().join(`, `),e}};Yg.NAME=`Key Usages`;var Xg=class e extends pg{static async create(t,n=!1,r=gg.get()){let i=await(await Hg.create(t,r)).getKeyIdentifier(r);return new e(li.ToHex(i),n)}constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Nu);this.keyId=li.ToHex(t)}else{let t=typeof e[0]==`string`?li.FromHex(e[0]):e[0],n=new Nu(t);super(Mu,e[1],Y.serialize(n)),this.keyId=li.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=Y.parse(this.value,Nu),e}};Xg.NAME=`Subject Key Identifier`;var Zg=class extends pg{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(Du,e[1],new Ng(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Ou);this.names=new Ng(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};Zg.NAME=`Subject Alternative Name`;var Qg=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new pg(e),n=this.items.get(t.type);return n?new n(e):t}};Qg.items=new Map;var $g=class extends pg{constructor(...e){if(U.isBufferSource(e[0])){super(e[0]);let t=Y.parse(this.value,Bl);this.policies=t.map(e=>e.policyIdentifier)}else{let t=e[0],n=e[1]??!1,r=new Bl(t.map(e=>new zl({policyIdentifier:e})));super(Nl,n,Y.serialize(r)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new sg(``,{},lg.toString(e))),e}};$g.NAME=`Certificate Policies`,Qg.register(Nl,$g);var e_=class extends pg{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 Jl({distributionPoint:new ql({fullName:[new cl({uniformResourceIdentifier:e})]})})),n=new Yl(t);super(Wl,e[1],Y.serialize(n))}else{let t=new Yl(e[0]);super(Wl,e[1],Y.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,Yl);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 Mg(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};e_.NAME=`CRL Distribution Points`;var t_=class extends pg{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Sl){let t=new Sl(e[0]);super(bl,e[1],Y.serialize(t))}else{let t=e[0],n=new Sl;r_(n,t,ml,`ocsp`),r_(n,t,hl,`caIssuers`),r_(n,t,gl,`timeStamping`),r_(n,t,_l,`caRepository`),super(bl,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,Sl).forEach(e=>{switch(e.accessMethod){case ml:this.ocsp.push(new Mg(e.accessLocation));break;case hl:this.caIssuers.push(new Mg(e.accessLocation));break;case gl:this.timeStamping.push(new Mg(e.accessLocation));break;case _l:this.caRepository.push(new Mg(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&n_(e,`OCSP`,this.ocsp),this.caIssuers.length&&n_(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&n_(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&n_(e,`CA Repository`,this.caRepository),e}};t_.NAME=`Authority Info Access`;function n_(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new sg(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[sg.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function r_(e,t,n,r){let i=t[r];i&&(Array.isArray(i)?i:[i]).forEach(t=>{typeof t==`string`&&(t=new Mg(`url`,t)),e.push(new xl({accessMethod:n,accessLocation:Y.parse(t.rawData,cl)}))})}var i_=class extends pg{constructor(...e){U.isBufferSource(e[0])?super(e[0]):super(pu,e[1],new Ng(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=Y.parse(e.extnValue,kl);this.names=new Ng(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};i_.NAME=`Issuer Alternative Name`;var a_=class e extends fg{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 ku({type:n,values:r}))}super(t,ku)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new sg(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[sg.NAME]===e.NAME&&(t[sg.NAME]=lg.toString(this.type)),t}};a_.NAME=`Attribute`;var o_=class extends a_{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=new mh({printableString:e[0]});super(Jm,[Y.serialize(t)])}this.password??=``}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],mh);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[sg.VALUE]=this.password,e}};o_.NAME=`Challenge Password`;var s_=class extends a_{constructor(...e){if(U.isBufferSource(e[0]))super(e[0]);else{let t=e[0],n=new Gu;for(let e of t)n.push(Y.parse(e.rawData,Wu));super(Ym,[Y.serialize(n)])}this.items??=[]}onInit(e){if(super.onInit(e),this.values[0]){let e=Y.parse(this.values[0],Gu);this.items=e.map(e=>Qg.create(Y.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[sg.NAME]]=n;return e}};s_.NAME=`Extensions`;var c_=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new a_(e),n=this.items.get(t.type);return n?new n(e):t}};c_.items=new Map;var l_=`crypto.signatureFormatter`,u_=class{toAsnSignature(e,t){return U.toArrayBuffer(t)}toWebSignature(e,t){return U.toArrayBuffer(t)}},d_,f_=d_=class{static createPssParams(e,t){let n=d_.getHashAlgorithm(e);return n?new Dp({hashAlgorithm:n,maskGenAlgorithm:new Z({algorithm:xp,parameters:Y.serialize(n)}),saltLength:t}):null}static getHashAlgorithm(e){let t=dm.resolve(Eh);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:ap,parameters:null});case`sha-256`:return new Z({algorithm:sp,parameters:null});case`sha-384`:return new Z({algorithm:cp,parameters:null});case`sha-512`:return new Z({algorithm:lp,parameters:null})}}else return new Z({algorithm:$f,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=d_.createPssParams(e.hash,e.saltLength);if(!t)throw Error(`Cannot create PSS parameters`);return new Z({algorithm:np,parameters:Y.serialize(t)})}return new Z({algorithm:np,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case $f:return{name:`RSASSA-PKCS1-v1_5`};case ap:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case sp:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case cp:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case lp:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case np:if(e.parameters){let t=Y.parse(e.parameters,Dp);return{name:`RSA-PSS`,hash:dm.resolve(Eh).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:`RSA-PSS`}}return null}};f_=d_=X([fm()],f_),dm.registerSingleton(wh,f_);var p_=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new Z({algorithm:fp});case`sha-256`:return new Z({algorithm:mp});case`sha-384`:return new Z({algorithm:hp});case`sha-512`:return new Z({algorithm:gp})}return null}toWebAlgorithm(e){switch(e.algorithm){case fp:return{name:`SHA-1`};case mp:return{name:`SHA-256`};case hp:return{name:`SHA-384`};case gp:return{name:`SHA-512`}}return null}};p_=X([fm()],p_),dm.registerSingleton(wh,p_);var m_=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 Zf,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,Zf),i=t.namedCurve,a=e.namedCurveSize.get(i)||e.defaultNamedCurveSize;return ui(this.addPadding(a,this.removePadding(r.r)),this.addPadding(a,this.removePadding(r.s)))}return null}};m_.namedCurveSize=new Map,m_.defaultNamedCurveSize=32;var h_=`1.3.101.110`,g_=`1.3.101.111`,__=`1.3.101.112`,v_=`1.3.101.113`,y_=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=__;break;case`x25519`:t=h_;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=__;break;case`ed448`:t=v_}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=h_;break;case`x448`:t=g_}}return t?new Z({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case __:return{name:`Ed25519`};case v_:return{name:`EdDSA`,namedCurve:`Ed448`};case h_:return{name:`X25519`};case g_:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}};y_=X([fm()],y_),dm.registerSingleton(wh,y_);var b_,x_,S_,C_,w_,T_,E_,D_,O_=class extends Vg{get subjectName(){return qc(this,x_,`f`)||Jc(this,x_,new Cg(this.asn.certificationRequestInfo.subject),`f`),qc(this,x_,`f`)}get subject(){return qc(this,S_,`f`)||Jc(this,S_,this.subjectName.toString(),`f`),qc(this,S_,`f`)}get signatureAlgorithm(){if(!qc(this,C_,`f`)){let e=dm.resolve(Eh);Jc(this,C_,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return qc(this,C_,`f`)}get signature(){return qc(this,w_,`f`)||Jc(this,w_,this.asn.signature,`f`),qc(this,w_,`f`)}get publicKey(){return qc(this,T_,`f`)||Jc(this,T_,new Hg(this.asn.certificationRequestInfo.subjectPKInfo),`f`),qc(this,T_,`f`)}get attributes(){return qc(this,E_,`f`)||Jc(this,E_,this.asn.certificationRequestInfo.attributes.map(e=>c_.create(Y.serialize(e))),`f`),qc(this,E_,`f`)}get extensions(){if(!qc(this,D_,`f`)){Jc(this,D_,[],`f`);let e=this.getAttribute(Ym);e instanceof s_&&Jc(this,D_,e.items,`f`)}return qc(this,D_,`f`)}get tbs(){return qc(this,b_,`f`)||Jc(this,b_,this.asn.certificationRequestInfoRaw||Y.serialize(this.asn.certificationRequestInfo),`f`),qc(this,b_,`f`)}constructor(e){let t=Vg.isAsnEncoded(e)?[e,Ch]:[e];super(t[0],t[1]),b_.set(this,void 0),x_.set(this,void 0),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),this.tag=Bg.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=gg.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=dm.resolveAll(l_).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,Ch),n=t.certificationRequestInfo,r=new sg(``,{Version:`${Ku[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new sg(``);for(let t of this.attributes){let n=t.toTextObject();e[n[sg.NAME]]=n}r.Attributes=e}return e.Data=r,e.Signature=new sg(``,{Algorithm:ug.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};b_=new WeakMap,x_=new WeakMap,S_=new WeakMap,C_=new WeakMap,w_=new WeakMap,T_=new WeakMap,E_=new WeakMap,D_=new WeakMap,O_.NAME=`PKCS#10 Certificate Request`;var k_,A_,j_,M_,N_,P_,F_,I_,L_,R_,z_,B_,V_=class extends Vg{get publicKey(){return qc(this,B_,`f`)||Jc(this,B_,new Hg(this.asn.tbsCertificate.subjectPublicKeyInfo),`f`),qc(this,B_,`f`)}get serialNumber(){if(!qc(this,A_,`f`)){let e=this.asn.tbsCertificate,t=new Uint8Array(e.serialNumber);t.length>1&&t[0]===0&&t[1]>127&&(t=t.slice(1)),Jc(this,A_,li.ToHex(t),`f`)}return qc(this,A_,`f`)}get subjectName(){return qc(this,j_,`f`)||Jc(this,j_,new Cg(this.asn.tbsCertificate.subject),`f`),qc(this,j_,`f`)}get subject(){return qc(this,M_,`f`)||Jc(this,M_,this.subjectName.toString(),`f`),qc(this,M_,`f`)}get issuerName(){return qc(this,N_,`f`)||Jc(this,N_,new Cg(this.asn.tbsCertificate.issuer),`f`),qc(this,N_,`f`)}get issuer(){return qc(this,P_,`f`)||Jc(this,P_,this.issuerName.toString(),`f`),qc(this,P_,`f`)}get notBefore(){if(!qc(this,F_,`f`)){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw Error(`Cannot get 'notBefore' value`);Jc(this,F_,e,`f`)}return qc(this,F_,`f`)}get notAfter(){if(!qc(this,I_,`f`)){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw Error(`Cannot get 'notAfter' value`);Jc(this,I_,e,`f`)}return qc(this,I_,`f`)}get signatureAlgorithm(){if(!qc(this,L_,`f`)){let e=dm.resolve(Eh);Jc(this,L_,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return qc(this,L_,`f`)}get signature(){return qc(this,R_,`f`)||Jc(this,R_,this.asn.signatureValue,`f`),qc(this,R_,`f`)}get extensions(){return qc(this,z_,`f`)||(Jc(this,z_,[],`f`),this.asn.tbsCertificate.extensions&&Jc(this,z_,this.asn.tbsCertificate.extensions.map(e=>Qg.create(Y.serialize(e))),`f`)),qc(this,z_,`f`)}get tbs(){return qc(this,k_,`f`)||Jc(this,k_,this.asn.tbsCertificateRaw||Y.serialize(this.asn.tbsCertificate),`f`),qc(this,k_,`f`)}constructor(e){let t=Vg.isAsnEncoded(e)?[e,Ju]:[e];super(t[0],t[1]),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),P_.set(this,void 0),F_.set(this,void 0),I_.set(this,void 0),L_.set(this,void 0),R_.set(this,void 0),z_.set(this,void 0),B_.set(this,void 0),this.tag=Bg.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=gg.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 Hg)n={...i.algorithm,...this.signatureAlgorithm},r=await i.export(n,[`verify`],t);else if(U.isBufferSource(i)){let e=new Hg(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=dm.resolveAll(l_).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??=gg.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=gg.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=Y.parse(this.rawData,Ju),n=t.tbsCertificate,r=new sg(``,{Version:`${Ku[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":ug.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new sg(``,{"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 sg(``);for(let t of this.extensions){let n=t.toTextObject();e[n[sg.NAME]]=n}r.Extensions=e}return e.Data=r,e.Signature=new sg(``,{Algorithm:ug.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};k_=new WeakMap,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_=new WeakMap,z_=new WeakMap,B_=new WeakMap,V_.NAME=`Certificate`;function H_(e,t=gg.get()){let n=U.toUint8Array(li.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 U_=class{static async createSelfSigned(e,t=gg.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=gg.get()){let n;n=e.publicKey instanceof Hg?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=H_(e.serialNumber,t),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),o=new Ju({tbsCertificate:new qu({version:Ku.v3,serialNumber:r,validity:new Hu({notBefore:i,notAfter:a}),extensions:new Gu(e.extensions?.map(e=>Y.parse(e.rawData,Wu))||[]),subjectPublicKeyInfo:Y.parse(n,Bu)})});if(e.subject){let t=e.subject instanceof Cg?e.subject:new Cg(e.subject);o.tbsCertificate.subject=Y.parse(t.toArrayBuffer(),il)}if(e.issuer){let t=e.issuer instanceof Cg?e.issuer:new Cg(e.issuer);o.tbsCertificate.issuer=Y.parse(t.toArrayBuffer(),il)}let s={hash:`SHA-256`},c=`signingKey`in e?{...s,...e.signingAlgorithm,...e.signingKey.algorithm}:{...s,...e.signingAlgorithm},l=dm.resolve(Eh);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=dm.resolveAll(l_).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 V_(Y.serialize(o))}},W_;(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`})(W_||={}),Qg.register(El,Gg),Qg.register(nu,qg),Qg.register(hu,Yg),Qg.register(Mu,Xg),Qg.register(Cl,Wg),Qg.register(Du,Zg),Qg.register(Wl,e_),Qg.register(bl,t_),Qg.register(pu,i_),c_.register(Jm,o_),c_.register(Ym,s_),dm.registerSingleton(l_,u_),dm.registerSingleton(l_,m_),m_.namedCurveSize.set(`P-256`,32),m_.namedCurveSize.set(`K-256`,32),m_.namedCurveSize.set(`P-384`,48),m_.namedCurveSize.set(`P-521`,66);var G_=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})),K_=R(((e,t)=>{for(var n=te(`util`),r=G_(),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})),q_=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}}})),J_=R(((e,t)=>{var n=K_(),r=q_(),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})),Y_=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`}}})),X_=R(((e,t)=>{var{Transform:n}=te(`stream`),r=K_(),i=J_(),a=Y_(),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})),Z_=R(((e,t)=>{t.exports=function(e){return typeof e==`object`&&!!e&&Array.isArray(e)===!1}})),Q_=R(((e,t)=>{var n=Z_();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)}})),$_=R(((e,t)=>{t.exports={isType:n,isUserType:Q_(),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)}})),ev=R(((e,t)=>{t.exports={skip:Symbol(`skip`),bytes:Symbol(`bytes`)}})),tv=R(((e,t)=>{var n=ev();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)}}})),nv=R(((e,t)=>{var{isType:n,isUserType:r,isDecodeType:i}=$_(),a=X_(),o=ev(),s=tv();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.`)}})),rv=R(((e,t)=>{var{isUserType:n,isEncodeType:r,isType:i}=$_(),a=ev(),o=tv(),s=X_();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.")}})),iv=R(((e,t)=>{var{isUserType:n,isType:r}=$_(),i=tv(),a=ev();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)}}})),av=R(((e,t)=>{var{decodeCommon:n}=nv(),{encodeCommon:r}=rv(),{encodingLengthCommon:i}=iv(),{isType:a,isUserType:o,isFunction:s}=$_(),c=tv();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}})),ov=R(((e,t)=>{var{isType:n,isFunction:r}=$_(),i=Y_(),a=X_();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.`)}})),sv=R(((e,t)=>{var{isType:n}=$_();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}}})),cv=R(((e,t)=>{var{decodeCommon:n}=nv(),{encodeCommon:r}=rv(),{encodingLengthCommon:i}=iv(),{isType:a,isFunction:o}=$_(),s=ev(),c=tv();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)}}})),lv=R(((e,t)=>{var{isType:n}=$_(),r=Y_();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}`)}})),uv=R(((e,t)=>{var n=K_();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()}}})),dv=R(((e,t)=>{var{isType:n,isFunction:r,isUserType:i}=$_(),a=ev(),{decodeCommon:o}=nv(),{encodeCommon:s}=rv(),{encodingLengthCommon:c}=iv(),l=tv();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}}})),fv=R(((e,t)=>{var n=ev(),{decodeCommon:r}=nv(),i=tv();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}}})),pv=R(((e,t)=>{var n=K_(),r=Y_(),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)}})),mv=R(((e,t)=>{var n=X_(),r=av(),i=ov(),a=sv(),o=cv(),s=lv(),c=uv(),l=dv(),u=fv(),{encode:d}=rv(),{decode:f}=nv(),{encodingLength:p}=iv(),m=pv(),h=Y_(),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}})),hv=V(Gr(),1),Q=mv(),gv=T&&typeof T==`object`&&`webcrypto`in T?T.webcrypto:T&&typeof T==`object`&&`randomBytes`in T?T:void 0;function _v(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function vv(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function yv(e,...t){if(!_v(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 bv(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.createHasher`);vv(e.outputLen),vv(e.blockLen)}function xv(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 Sv(e,t){yv(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function Cv(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function wv(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Tv(e,t){return e<<32-t|e>>>t}var Ev=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Dv=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Ov(e){if(yv(e),Ev)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Dv[e[n]];return t}var kv={_0:48,_9:57,A:65,F:70,a:97,f:102};function Av(e){if(e>=kv._0&&e<=kv._9)return e-kv._0;if(e>=kv.A&&e<=kv.F)return e-(kv.A-10);if(e>=kv.a&&e<=kv.f)return e-(kv.a-10)}function jv(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(Ev)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=Av(e.charCodeAt(i)),a=Av(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 Mv(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function Nv(e){return typeof e==`string`&&(e=Mv(e)),yv(e),e}function Pv(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];yv(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 Fv=class{};function Iv(e){let t=t=>e().update(Nv(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Lv(e=32){if(gv&&typeof gv.getRandomValues==`function`)return gv.getRandomValues(new Uint8Array(e));if(gv&&typeof gv.randomBytes==`function`)return Uint8Array.from(gv.randomBytes(e));throw Error(`crypto.getRandomValues must be defined`)}var Rv=BigInt(0),zv=BigInt(1);function Bv(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function Vv(e,t,n=``){let r=_v(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 Hv(e){let t=e.toString(16);return t.length&1?`0`+t:t}function Uv(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?Rv:BigInt(`0x`+e)}function Wv(e){return Uv(Ov(e))}function Gv(e){return yv(e),Uv(Ov(Uint8Array.from(e).reverse()))}function Kv(e,t){return jv(e.toString(16).padStart(t*2,`0`))}function qv(e,t){return Kv(e,t).reverse()}function Jv(e,t,n){let r;if(typeof t==`string`)try{r=jv(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(_v(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 Yv=e=>typeof e==`bigint`&&Rv<=e;function Xv(e,t,n){return Yv(e)&&Yv(t)&&Yv(n)&&t<=e&&e<n}function Zv(e,t,n,r){if(!Xv(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function Qv(e){let t=0;for(;e>Rv;e>>=zv,t+=1);return t}var $v=e=>(zv<<BigInt(e))-zv;function ey(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 Pv(...n)};return(e,t)=>{c(),u(e);let n;for(;!(n=t(d()));)u();return c(),n}}function ty(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 ny(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 ry=BigInt(0),iy=BigInt(1),ay=BigInt(2),oy=BigInt(3),sy=BigInt(4),cy=BigInt(5),ly=BigInt(7),uy=BigInt(8),dy=BigInt(9),fy=BigInt(16);function py(e,t){let n=e%t;return n>=ry?n:t+n}function my(e,t){if(e===ry)throw Error(`invert: expected non-zero number`);if(t<=ry)throw Error(`invert: expected positive modulus, got `+t);let n=py(e,t),r=t,i=ry,a=iy,o=iy,s=ry;for(;n!==ry;){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!==iy)throw Error(`invert: does not exist`);return py(i,t)}function hy(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function gy(e,t){let n=(e.ORDER+iy)/sy,r=e.pow(t,n);return hy(e,r,t),r}function _y(e,t){let n=(e.ORDER-cy)/uy,r=e.mul(t,ay),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,ay),i),s=e.mul(a,e.sub(o,e.ONE));return hy(e,s,t),s}function vy(e){let t=Dy(e),n=yy(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+ly)/fy;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 hy(e,p,t),p}}function yy(e){if(e<oy)throw Error(`sqrt is not defined for small field`);let t=e-iy,n=0;for(;t%ay===ry;)t/=ay,n++;let r=ay,i=Dy(e);for(;Ty(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return gy;let a=i.pow(r,t),o=(t+iy)/ay;return function(e,r){if(e.is0(r))return r;if(Ty(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=iy<<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 by(e){return e%sy===oy?gy:e%uy===cy?_y:e%fy===dy?vy(e):yy(e)}var xy=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function Sy(e){return ty(e,xy.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function Cy(e,t,n){if(n<ry)throw Error(`invalid exponent, negatives unsupported`);if(n===ry)return e.ONE;if(n===iy)return t;let r=e.ONE,i=t;for(;n>ry;)n&iy&&(r=e.mul(r,i)),i=e.sqr(i),n>>=iy;return r}function wy(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 Ty(e,t){let n=(e.ORDER-iy)/ay,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 Ey(e,t){t!==void 0&&vv(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Dy(e,t,n=!1,r={}){if(e<=ry)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}=Ey(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:$v(c),ZERO:ry,ONE:iy,allowedLengths:s,create:t=>py(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return ry<=t&&t<e},is0:e=>e===ry,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&iy)===iy,neg:t=>py(-t,e),eql:(e,t)=>e===t,sqr:t=>py(t*t,e),add:(t,n)=>py(t+n,e),sub:(t,n)=>py(t-n,e),mul:(t,n)=>py(t*n,e),pow:(e,t)=>Cy(d,e,t),div:(t,n)=>py(t*my(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>my(t,e),sqrt:a||(t=>(u||=by(e),u(d,t))),toBytes:e=>n?qv(e,l):Kv(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?Gv(t):Wv(t);if(o&&(i=py(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>wy(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function Oy(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function ky(e){let t=Oy(e);return t+Math.ceil(t/2)}function Ay(e,t,n=!1){let r=e.length,i=Oy(t),a=ky(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=py(n?Gv(e):Wv(e),t-iy)+iy;return n?qv(o,i):Kv(o,i)}function jy(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 My(e,t,n){return e&t^~e&n}function Ny(e,t,n){return e&t^e&n^t&n}var Py=class extends Fv{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=wv(this.buffer)}update(e){xv(this),e=Nv(e),yv(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=wv(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){xv(this),Sv(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,Cv(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;jy(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=wv(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()}},Fy=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Iy=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Ly=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ry=BigInt(2**32-1),zy=BigInt(32);function By(e,t=!1){return t?{h:Number(e&Ry),l:Number(e>>zy&Ry)}:{h:Number(e>>zy&Ry)|0,l:Number(e&Ry)|0}}function Vy(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}=By(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var Hy=(e,t,n)=>e>>>n,Uy=(e,t,n)=>e<<32-n|t>>>n,Wy=(e,t,n)=>e>>>n|t<<32-n,Gy=(e,t,n)=>e<<32-n|t>>>n,Ky=(e,t,n)=>e<<64-n|t>>>n-32,qy=(e,t,n)=>e>>>n-32|t<<64-n;function Jy(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var Yy=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Xy=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Zy=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Qy=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,$y=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),eb=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,tb=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]),nb=new Uint32Array(64),rb=class extends Py{constructor(e=32){super(64,e,8,!1),this.A=Fy[0]|0,this.B=Fy[1]|0,this.C=Fy[2]|0,this.D=Fy[3]|0,this.E=Fy[4]|0,this.F=Fy[5]|0,this.G=Fy[6]|0,this.H=Fy[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)nb[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=nb[e-15],n=nb[e-2],r=Tv(t,7)^Tv(t,18)^t>>>3,i=Tv(n,17)^Tv(n,19)^n>>>10;nb[e]=i+nb[e-7]+r+nb[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=Tv(o,6)^Tv(o,11)^Tv(o,25),u=l+t+My(o,s,c)+tb[e]+nb[e]|0,d=(Tv(n,2)^Tv(n,13)^Tv(n,22))+Ny(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(){Cv(nb)}destroy(){this.set(0,0,0,0,0,0,0,0),Cv(this.buffer)}},ib=Vy(`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))),ab=ib[0],ob=ib[1],sb=new Uint32Array(80),cb=new Uint32Array(80),lb=class extends Py{constructor(e=64){super(128,e,16,!1),this.Ah=Ly[0]|0,this.Al=Ly[1]|0,this.Bh=Ly[2]|0,this.Bl=Ly[3]|0,this.Ch=Ly[4]|0,this.Cl=Ly[5]|0,this.Dh=Ly[6]|0,this.Dl=Ly[7]|0,this.Eh=Ly[8]|0,this.El=Ly[9]|0,this.Fh=Ly[10]|0,this.Fl=Ly[11]|0,this.Gh=Ly[12]|0,this.Gl=Ly[13]|0,this.Hh=Ly[14]|0,this.Hl=Ly[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)sb[n]=e.getUint32(t),cb[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=sb[e-15]|0,n=cb[e-15]|0,r=Wy(t,n,1)^Wy(t,n,8)^Hy(t,n,7),i=Gy(t,n,1)^Gy(t,n,8)^Uy(t,n,7),a=sb[e-2]|0,o=cb[e-2]|0,s=Wy(a,o,19)^Ky(a,o,61)^Hy(a,o,6),c=Zy(i,Gy(a,o,19)^qy(a,o,61)^Uy(a,o,6),cb[e-7],cb[e-16]),l=Qy(c,r,s,sb[e-7],sb[e-16]);sb[e]=l|0,cb[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=Wy(u,d,14)^Wy(u,d,18)^Ky(u,d,41),v=Gy(u,d,14)^Gy(u,d,18)^qy(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=$y(_,v,b,ob[e],cb[e]),S=eb(x,g,t,y,ab[e],sb[e]),C=x|0,w=Wy(n,r,28)^Ky(n,r,34)^Ky(n,r,39),T=Gy(n,r,28)^qy(n,r,34)^qy(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}=Jy(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=Yy(C,T,D);n=Xy(O,S,w,E),r=O|0}({h:n,l:r}=Jy(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=Jy(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=Jy(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=Jy(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Jy(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=Jy(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=Jy(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=Jy(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(){Cv(sb,cb)}destroy(){Cv(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ub=class extends lb{constructor(){super(48),this.Ah=Iy[0]|0,this.Al=Iy[1]|0,this.Bh=Iy[2]|0,this.Bl=Iy[3]|0,this.Ch=Iy[4]|0,this.Cl=Iy[5]|0,this.Dh=Iy[6]|0,this.Dl=Iy[7]|0,this.Eh=Iy[8]|0,this.El=Iy[9]|0,this.Fh=Iy[10]|0,this.Fl=Iy[11]|0,this.Gh=Iy[12]|0,this.Gl=Iy[13]|0,this.Hh=Iy[14]|0,this.Hl=Iy[15]|0}},db=Iv(()=>new rb),fb=Iv(()=>new lb),pb=Iv(()=>new ub),mb=class extends Fv{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,bv(e);let n=Nv(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),Cv(i)}update(e){return xv(this),this.iHash.update(e),this}digestInto(e){xv(this),yv(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()}},hb=(e,t,n)=>new mb(e,t).update(n).digest();hb.create=(e,t)=>new mb(e,t);var gb=BigInt(0),_b=BigInt(1);function vb(e,t){let n=t.negate();return e?n:t}function yb(e,t){let n=wy(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function bb(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function xb(e,t){bb(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:$v(e),maxNumber:i,shiftBy:BigInt(e)}}function Sb(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+=_b);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 Cb(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 wb(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 Tb=new WeakMap,Eb=new WeakMap;function Db(e){return Eb.get(e)||1}function Ob(e){if(e!==gb)throw Error(`invalid wNAF`)}var kb=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>gb;)t&_b&&(n=n.add(r)),r=r.double(),t>>=_b;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=xb(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=xb(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Sb(n,e,a);n=o,c?i=i.add(vb(u,t[d])):r=r.add(vb(l,t[s]))}return Ob(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=xb(e,this.bits);for(let e=0;e<i.windows&&n!==gb;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=Sb(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return Ob(n),r}getPrecomputes(e,t,n){let r=Tb.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),Tb.set(t,r))),r}cached(e,t,n){let r=Db(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=Db(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){bb(t,this.bits),Eb.set(e,t),Tb.delete(e)}hasCache(e){return Db(e)!==1}};function Ab(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>gb||r>gb;)n&_b&&(a=a.add(i)),r&_b&&(o=o.add(i)),i=i.double(),n>>=_b,r>>=_b;return{p1:a,p2:o}}function jb(e,t,n,r){Cb(n,e),wb(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=Qv(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=$v(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 Mb(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return Sy(t),t}return Dy(e,{isLE:n})}function Nb(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>gb))throw Error(`CURVE.${e} must be positive bigint`)}let i=Mb(t.p,n.Fp,r),a=Mb(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 Pb=(e,t)=>(e+(e>=0?t:-t)/Vb)/t;function Fb(e,t,n){let[[r,i],[a,o]]=t,s=Pb(o*e,n),c=Pb(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<zb,f=u<zb;d&&(l=-l),f&&(u=-u);let p=$v(Math.ceil(Qv(n)/2))+Bb;if(l<zb||l>=p||u<zb||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}function Ib(e){if(![`compact`,`recovered`,`der`].includes(e))throw Error(`Signature format must be "compact", "recovered", or "der"`);return e}function Lb(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return Bv(n.lowS,`lowS`),Bv(n.prehash,`prehash`),n.format!==void 0&&Ib(n.format),n}var Rb={Err:class extends Error{constructor(e=``){super(e)}},_tlv:{encode:(e,t)=>{let{Err:n}=Rb;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=Hv(r);if(i.length/2&128)throw new n(`tlv.encode: long form length too big`);let a=r>127?Hv(i.length/2|128):``;return Hv(e)+a+i+t},decode(e,t){let{Err:n}=Rb,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}=Rb;if(e<zb)throw new t(`integer: negative integers are not allowed`);let n=Hv(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}=Rb;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 Wv(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=Rb,i=Jv(`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}=Rb,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},zb=BigInt(0),Bb=BigInt(1),Vb=BigInt(2),Hb=BigInt(3),Ub=BigInt(4);function Wb(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=Jv(`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 Gb(e,t={}){let n=Nb(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;ty(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=qb(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 Bv(n,`isCompressed`),n?(u(),Pv(Kb(!r.isOdd(a)),o)):Pv(Uint8Array.of(4),o,r.toBytes(a))}function f(e){Vv(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,Hb),Ub),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 Fb(e,c.basises,i.ORDER)}let S=ny((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=ny(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=vb(i,t),n=vb(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(Vv(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return T.fromBytes(Jv(`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(Hb),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,Hb),{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,Hb),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=>yb(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 yb(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===zb||r.is0())return T.ZERO;if(e===Bb)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}=Ab(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===Bb?!0:e?e(T,this):D.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===Bb?this:e?e(T,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Bv(e,`isCompressed`),this.assertValidity(),p(T,this,e)}toHex(e=!0){return Ov(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 yb(T,e)}static msm(e,t){return jb(T,i,e,t)}static fromPrivateKey(e){return T.BASE.multiply(Wb(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 kb(T,t.endo?Math.ceil(E/2):E);return T.BASE.precompute(8),T}function Kb(e){return Uint8Array.of(e?2:3)}function qb(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Jb(e,t={}){let{Fn:n}=e,r=t.randomBytes||Lv,i=Object.assign(qb(e.Fp,n),{seed:ky(n.ORDER)});function a(e){try{return!!Wb(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 Ay(Vv(e,i.seed,`seed`),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(Wb(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=Jv(`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=Wb(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=>Wb(n,e),precompute(t=8,n=e.BASE){return n.precompute(t,!1)}},lengths:i})}function Yb(e,t,n={}){bv(t),ty(n,{},{hmac:`function`,lowS:`boolean`,randomBytes:`function`,bits2int:`function`,bits2int_modN:`function`});let r=n.randomBytes||Lv,i=n.hmac||((e,...n)=>hb(t,e,Pv(...n))),{Fp:a,Fn:o}=e,{ORDER:s,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p}=Jb(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>>Bb}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){Ib(t);let n=p.signature;return Vv(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}=Rb.toSig(Vv(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(jv(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*Vb<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(Pv(Kb(!(c&1)),u)),f=o.inv(l),p=x(Jv(`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(Ib(e),e===`der`)return jv(Rb.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 Pv(Uint8Array.of(this.recovery),t,n)}return Pv(t,n)}toHex(e){return Ov(this.toBytes(e))}assertValidity(){}static fromCompact(e){return y.fromBytes(Jv(`sig`,e),`compact`)}static fromDER(e){return y.fromBytes(Jv(`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 Ov(this.toBytes(`der`))}toCompactRawBytes(){return this.toBytes(`compact`)}toCompactHex(){return Ov(this.toBytes(`compact`))}}let b=n.bits2int||function(e){if(e.length>8192)throw Error(`input is too large`);let t=Wv(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=$v(c);function C(e){return Zv(`num < 2^`+c,e,zb,S),o.toBytes(e)}function w(e,n){return Vv(e,void 0,`message`),n?Vv(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}=Lb(i,m);t=w(t,s);let l=x(t),u=Wb(o,n),d=[C(u),C(l)];if(c!=null&&c!==!1){let e=c===!0?r(p.secretKey):c;d.push(Jv(`extraEntropy`,e))}let f=Pv(...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===zb)return;let c=o.create(r*o.create(h+s*u));if(c===zb)return;let l=(i.x===s?0:2)|Number(i.y&Bb),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=Jv(`message`,e);let{seed:a,k2sig:s}=T(e,n,r);return ey(t.outputLen,o.BYTES,i)(a,s)}function D(e){let t,n=typeof e==`string`||_v(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(Jv(`sig`,e),`der`)}catch(e){if(!(e instanceof Rb.Err))throw e}if(!t)try{t=y.fromBytes(Jv(`sig`,e),`compact`)}catch{return!1}}return t||!1}function O(t,n,r,i={}){let{lowS:a,prehash:s,format:c}=Lb(i,m);if(r=Jv(`publicKey`,r),n=w(Jv(`message`,n),s),`strict`in i)throw Error(`options.strict was renamed to lowS`);let l=c===void 0?D(t):y.fromBytes(Jv(`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}=Lb(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 Xb(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:Dy(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 Zb(e){let{CURVE:t,curveOpts:n}=Xb(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 Qb(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Ey(n.Fn.ORDER,n.Fn.BITS))})}function $b(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=Zb(e);return Qb(e,Yb(Gb(t,n),r,i))}function ex(e,t){let n=t=>$b({...e,hash:t});return{...n(t),create:n}}var tx={p:BigInt(`0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff`),n:BigInt(`0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551`),h:BigInt(1),a:BigInt(`0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc`),b:BigInt(`0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b`),Gx:BigInt(`0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296`),Gy:BigInt(`0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5`)},nx={p:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff`),n:BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973`),h:BigInt(1),a:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc`),b:BigInt(`0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef`),Gx:BigInt(`0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7`),Gy:BigInt(`0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f`)},rx={p:BigInt(`0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),n:BigInt(`0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409`),h:BigInt(1),a:BigInt(`0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc`),b:BigInt(`0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00`),Gx:BigInt(`0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66`),Gy:BigInt(`0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650`)},ix=Dy(tx.p),ax=Dy(nx.p),ox=Dy(rx.p),sx=ex({...tx,Fp:ix,lowS:!1},db);ex({...nx,Fp:ax,lowS:!1},pb),ex({...rx,Fp:ox,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},fb);var cx=sx,lx=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}})),ux=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}})),dx=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}})),fx=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}})),px=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}})),mx=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)})),hx=R((e=>{var t=te(`buffer`).Buffer,n=lx(),r=ux(),i=dx(),a=fx(),o=px(),s=mx(),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}})),gx=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)})}})),_x=V(R(((e,t)=>{var n=hx(),r=te(`dgram`),i=gx(),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 vx(){return c(2).readUInt16BE(0)}function yx(){return c(4).readUInt32BE(0)}var bx=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}},xx=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 Sx(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 Cx(e,t){return wx(e)(t)}function wx(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 Tx(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 Ex=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++)}},Dx=3988292384,Ox=2197175160;function kx(e){return typeof e!=`string`}function Ax(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 jx(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 Mx(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 Nx(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 Px=Ax(Dx),Fx=jx(Px),Ix=Ax(Ox),Lx=jx(Ix);function Rx(e,t=0){return kx(e)?Nx(e,t,Px,Fx):Mx(e,t,Px)}function zx(e,t=0){return kx(e)?Nx(e,t,Ix,Lx):Mx(e,t,Ix)}function Bx(e,t){return e+t&255}function Vx(e,t){return e+t&65535}function Hx(e,t){return Number(BigInt(e)+BigInt(t)&4294967295n)}function Ux(e){return e&16777215}function Wx(e,t){let n=32768;return e<t&&t-e>n||e>t&&e-t<n}function Gx(e,t){let n=2147483648;return e<t&&t-e>n||e>t&&e-t<n}function Kx(e,t){return e===t||Gx(e,t)}var qx=e=>Number.parseInt(e,10),Jx=(e,t)=>t?t[e]:void 0;async function Yx(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:Jx(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 Xx(e){return e===`IPv4`?4:e===`IPv6`?6:e}var Zx=ei.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}},Qx=class{_disposer=[];push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e()),this._disposer=[]}},$x=Zx(`werift-ice:packages/ice/src/transport.ts`),eS=class e{constructor(e,t={}){this.socketType=e,this.options=t,this.socket=f(e),this.socket.on(`message`,(e,t)=>{Xx(t.family)===6&&([t.address]=t.address.split(`%`)),this.rinfo=t;try{this.onData(e,[t.address,t.port])}catch(e){$x(`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=Jx(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 Yx(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?($x(`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()}})},tS=class e{type=`tcp`;stream;constructor(e){this.stream=new rS(`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()}},nS=class e{type=`tls`;stream;constructor(e,t={}){this.stream=new rS(`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()}},rS=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=>{$x(`${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()}},iS={rsa_1:1,ecdsa_3:3},aS={sha256_4:4},oS={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},sS=Object.values(oS),cS={x25519_29:29,secp256r1_23:23},lS=Object.values(cS),uS={named_curve_3:3},dS={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},fS=[1,64],pS=[{hash:aS.sha256_4,signature:iS.rsa_1},{hash:aS.sha256_4,signature:iS.ecdsa_3}],mS=()=>{let e=cx.utils.randomPrivateKey(),t=cx.getPublicKey(e,!1);return{privateKey:Buffer.from(e),publicKey:Buffer.from(t)}},hS=({publicKey:e,privateKey:t})=>{let n=cx.getSharedSecret(t,e);return Buffer.from(n).subarray(1)};function gS(e,t,n){switch(n){case cS.secp256r1_23:return hS({publicKey:e,privateKey:t});case cS.x25519_29:return Buffer.from(hv.default.scalarMult(t,e));default:throw Error()}}function _S(e,t,n){let r=o(e,t);return r.update(n),r.digest()}function vS(e,t,n,r=`sha256`){let i=n,a=[],o=t;do{o=_S(r,e,o);let i=_S(r,e,Buffer.concat([o,t]));a.push(i),n-=i.length}while(n>0);return Buffer.concat(a,i)}function yS(e,t,n){return vS(e,Buffer.concat([Buffer.from(`master secret`),t,n]),48)}function bS(e,t){let n=SS(`sha256`,t);return vS(e,Buffer.concat([Buffer.from(`extended master secret`),n]),48)}function xS(e,t,n,r,i,a){let o=a?r:i,s=a?i:r;return vS(n,Buffer.concat([Buffer.from(e),o,s]),t)}function SS(e,t){return a(e).update(t).digest()}function CS(e,t,n,r=12){let i=SS(`sha256`,t);return vS(e,Buffer.concat([Buffer.from(n),i]),r)}function wS(e,t){return CS(e,t,`client finished`)}function TS(e,t){return CS(e,t,`server finished`)}function ES(e,t,n,r,i,a,o=`sha256`){let s=r*2+i*2,c=e,l=Buffer.concat([n,t]),u=vS(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 DS={CLIENT:1,SERVER:2},OS=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}},kS=d;gg.set(kS);var AS=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 iS.rsa_1:return`RSASSA-PKCS1-v1_5`;case iS.ecdsa_3:return`ECDSA`}})(),r=(()=>{switch(e.hash){case aS.sha256_4:return`SHA-256`}})(),i=(()=>{switch(t){case cS.secp256r1_23:return`P-256`;case cS.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 kS.subtle.generateKey(a,!0,[`sign`,`verify`]);return{certPem:(await U_.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:Bg.encode(await kS.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===DS.CLIENT?wS(this.masterSecret,e):TS(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===DS.CLIENT?this.localRandom:this.remoteRandom,n=this.sessionType===DS.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=ti.Certificate.fromPEM(Buffer.from(e)),i=ti.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:uS.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])}},jS=class{srtpProfile;static findMatchingSRTPProfile(e,t){for(let n of t)if(e.includes(n))return n}},MS=e=>`0x`+e.toString(`hex`).replace(/(.)(.)/g,`$1$2 `).split(` `).filter(e=>e!=null&&e.length>0).join(`,0x`),NS=e=>Object.entries({...e}).reduce((e,[t,n])=>((typeof n==`number`||typeof n==`string`)&&(e[t]=n),Buffer.isBuffer(n)&&(e[t]=MS(n)),e),{}),PS=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 NS(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:FS,uint24be:IS,buffer:LS,array:RS,uint8:zS,string:BS}=Q.types,VS=RS({type:FS,data:LS(FS)},FS,`bytes`),HS=LS(IS),US=zS,WS=BS(FS),GS={hash:zS,signature:zS},KS={major:zS,minor:zS},qS=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)}},JS=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:qS.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:VS};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 PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},YS=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:KS,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)}},XS=class e{constructor(e,t){this.recordLayerHeader=e,this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:MS(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 YS(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},ZS=e=>t=>(e.lastFlight=t,t.flatMap(t=>(t.messageSeq=e.sequenceNumber++,t.toFragment().chunk()))),QS=e=>(t,n)=>t.map(t=>new XS({contentType:t.type,protocolVersion:e.version,epoch:e.epoch,sequenceNumber:n,contentLen:t.fragment.length},t.fragment)),$S=(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))($S||{}),eC=Zx(`werift-dtls : packages/dtls/src/flight/flight.ts : warn`),tC=Zx(`werift-dtls : packages/dtls/src/flight/flight.ts : err`),nC=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=ZS(this.dtls)(e);return this.dtls.bufferHandshakeCache(t,!0,this.flight),QS(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=>{tC(`fail to send`,tC)}),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}eC(this.dtls.sessionId,`retransmit`,n,this.dtls.flight)}if(n>e.RetransmitCount)throw tC(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}},rC=class extends nC{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 JS({major:254,minor:253},new qS,Buffer.from([]),Buffer.from([]),sS,[0],e);this.dtls.version=t.clientVersion,this.cipher.localRandom=qS.from(t.random);let n=this.createPacket([t]),r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}},iC=Zx(`werift-dtls : packages/dtls/src/flight/client/flight3.ts : log`),aC=class extends nC{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;iC(`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])}},oC={NULL:0,ECDHE:1},sC={NULL:0,RSA:1,ECDSA:2,PSK:3},cC={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},lC=class{id=0;name;signType;keyType;toString(){return this.name}};function uC(){let e=new lC;return e.id=cC.RSA,e.name=`RSA`,e.keyType=sC.RSA,e}function dC(){let e=new lC;return e.id=cC.ECDHE_RSA,e.name=`ECDHE_RSA`,e.signType=oC.ECDHE,e.keyType=sC.RSA,e}function fC(){let e=new lC;return e.id=cC.ECDHE_ECDSA,e.name=`ECDHE_ECDSA`,e.signType=oC.ECDHE,e.keyType=sC.ECDSA,e}function pC(){let e=new lC;return e.id=cC.PSK,e.name=`PSK`,e.signType=oC.NULL,e.keyType=sC.PSK,e}function mC(){let e=new lC;return e.id=cC.ECDHE_PSK,e.name=`ECDHE_PSK`,e.signType=oC.ECDHE,e.keyType=sC.PSK,e}var hC=Zx(`werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err`),gC=class extends OS{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return NS(this)}init(e,t,n){let r=ES(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===DS.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===DS.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 hC(`decrypt failed`,r,e,MS(t),n,this.summary),r}}},_C={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},vC={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},yC={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},bC=uC(),xC=dC(),SC=fC(),CC=pC(),wC=mC();function TC(e){switch(e){case _C.TLS_RSA_WITH_AES_128_GCM_SHA256:return EC(_C.TLS_RSA_WITH_AES_128_GCM_SHA256,`TLS_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,bC,vC);case _C.TLS_RSA_WITH_AES_256_GCM_SHA384:return EC(_C.TLS_RSA_WITH_AES_256_GCM_SHA384,`TLS_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,bC,yC,`sha384`);case _C.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return EC(_C.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,xC,vC);case _C.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return EC(_C.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,xC,yC,`sha384`);case _C.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return EC(_C.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,SC,vC);case _C.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return EC(_C.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,SC,yC,`sha384`);case _C.TLS_PSK_WITH_AES_128_GCM_SHA256:return EC(_C.TLS_PSK_WITH_AES_128_GCM_SHA256,`TLS_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,CC,vC,`sha256`);case _C.TLS_PSK_WITH_AES_256_GCM_SHA384:return EC(_C.TLS_PSK_WITH_AES_256_GCM_SHA384,`TLS_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,CC,yC,`sha384`);case _C.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return EC(_C.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,wC,vC,`sha256`);case _C.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return EC(_C.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,wC,yC,`sha384`)}return null}function EC(e,t,n,r,i,a=`sha256`){let o=new gC;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 DC(e){switch(e){case cS.secp256r1_23:{let{privateKey:t,publicKey:n}=mS();return{curve:e,privateKey:t,publicKey:n}}case cS.x25519_29:{let t=hv.default.box.keyPair();return{curve:e,privateKey:Buffer.from(t.secretKey.buffer),publicKey:Buffer.from(t.publicKey.buffer)}}default:throw Error()}}var OC=class{static type=23},kC=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)}}},AC=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)}}},jC=class e{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:Q.types.array(HS,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 PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},MC=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)}},NC=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 PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},PC=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 PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},FC=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 PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},IC=class e{constructor(e,t,n){this.certificateTypes=e,this.signatures=t,this.authorities=n}msgType=13;messageSeq;static spec={certificateTypes:Q.types.array(US,Q.types.uint8,`bytes`),signatures:Q.types.array(GS,Q.types.uint16be,`bytes`),authorities:Q.types.array(WS,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 PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},LC=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:KS,random:qS.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:VS}))):r}serialize(){let t=this.extensions===void 0?(0,Q.encode)(this,e.spec).slice():(0,Q.encode)(this,{...e.spec,extensions:VS}).slice();return Buffer.from(t)}toFragment(){let e=this.serialize();return new PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},RC=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 PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}};function zC(e,t){return Buffer.from((0,Q.encode)(e,t).slice())}var BC=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 zC(this,e.spec)}toFragment(){let e=this.serialize();return new PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},VC=e=>{switch(e){case 1:case 7:return 16}},HC=e=>{switch(e){case 1:return 14;case 7:return 12}};Zx(`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 UC(e,t){let n=Buffer.alloc(t);return e.copy(n),n}function WC(e){return Number.parseInt(e.toString(),10)}function GC(e){let t=e[0];return t>127&&t<192}var KC=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 bx(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),Cx([1,1,2],[e.value,this.type,this.length])}static deSerialize(t){let[n,r,i]=Tx(t,[1,1,2]),a=Sx(n,0,2),o=Sx(n,2,1)>0,s=Sx(n,3,5);return new e({version:a,padding:o,count:s,type:r,length:i})}},qC=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]=Tx(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=Cx([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])}},JC=class e{static count=1;count=e.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(t){let[n,r]=Tx(t,[4,4]);return new e({senderSsrc:n,mediaSsrc:r})}serialize(){return Cx([4,4],[this.senderSsrc,this.mediaSsrc])}},YC=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]=Tx(t,[4,4,4,1,1]),s=Sx(o,0,6),c=(Sx(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:Cx([4],[i]).toString(),ssrcNum:a,brExp:s,brMantissa:c,ssrcFeedbacks:u,bitrate:l})}serialize(){let e=Buffer.concat([Cx([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),Cx([1],[this.ssrcNum])]),t=new bx(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);let n=Buffer.concat(this.ssrcFeedbacks.map(e=>Cx([4],[e]))),r=Buffer.concat([e,Cx([3],[t.value]),n]);return this.length=r.length/4,r}},XC=Zx(`werift-rtp: /rtcp/psfb/index`),ZC=class e{static type=206;type=e.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return KC.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(t,n){let r;switch(n.count){case qC.count:r=qC.deSerialize(t);break;case JC.count:r=JC.deSerialize(t);break;case YC.count:r=YC.deSerialize(t);break;default:XC(`unknown psfb packet`,n.count)}return new e({feedback:r})}},QC=class e{ssrc=0;reports=[];static type=201;type=e.type;constructor(e={}){Object.assign(this,e)}serialize(){let t=Cx([4],[this.ssrc]);return t=Buffer.concat([t,...this.reports.map(e=>e.serialize())]),KC.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let[r]=Tx(t,[4]),i=4,a=[];for(let e=0;e<n;e++)a.push($C.deSerialize(t.slice(i,i+24))),i+=24;return new e({ssrc:r,reports:a})}},$C=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 Cx([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]=Tx(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})}},ew=205,tw=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 KC({type:ew,count:this.count,version:2})}static deSerialize(t,n){let[r,i]=Tx(t,[4,4]),a=[];for(let e=8;e<t.length;e+=4){let[n,r]=Tx(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=Cx([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(Cx([2,2],[e,n])),e=r,n=0)}),t.push(Cx([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])}},nw=Zx(`werift/rtp/rtcp/rtpfb/twcc`),rw=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 KC({type:205,count:this.count,version:2})}static deSerialize(t,n){let[r,i,a,o,s,c]=Tx(t,[4,4,2,2,3,1]),l=[],u=[],d=16;for(let e=0;e<o;){let n=Sx(t.slice(d,d+1)[0],0,1),r;switch(n){case 0:{let n=iw.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 ow({type:n.packetStatus}));e+=i}break;case 1:{let n=aw.deSerialize(t.slice(d,d+2));r=n,n.symbolSize===0&&n.symbolList.forEach(e=>{e===1&&u.push(new ow({type:1}))}),n.symbolSize===1&&n.symbolList.forEach(e=>{(e===1||e===2)&&u.push(new ow({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=Cx([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){nw(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 iw).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}},iw=class e{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(t){let n=Sx(t[0],1,2),r=(Sx(t[0],3,5)<<8)+t[1];return new e({type:0,packetStatus:n,runLength:r})}serialize(){return new xx(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 sw({sequenceNumber:++e,received:t}));return n}},aw=class e{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=Sx(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(Sx(t[0],2+e,1))),i(8,e=>r.push(Sx(t[1],e,1)));break;case 1:i(3,e=>r.push(Sx(t[0],2+e*2,2))),i(4,e=>r.push(Sx(t[1],e*2,2)));break;default:n=(Sx(t[0],2,6)<<8)+t[1]}return new e({type:1,symbolSize:n,symbolList:r})}serialize(){let e=Buffer.alloc(2),t=new xx(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}},ow=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)}},sw=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(e){Object.assign(this,e)}},cw=Zx(`werift-rtp:packages/rtp/rtcp/rtpfb/index`),lw=class e{static type=ew;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 tw.count:r=tw.deSerialize(t,n);break;case rw.count:r=rw.deSerialize(t,n);break;default:cw(`unknown rtpfb packet`,n.count)}return new e({feedback:r,header:n})}},uw=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 KC.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=dw.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({chunks:r})}},dw=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+=pw(e),e}serialize(){let e=Buffer.concat([Cx([4],[this.source]),Buffer.concat(this.items.map(e=>e.serialize()))]);return Buffer.concat([e,Buffer.alloc(pw(e.length))])}static deSerialize(t){let n=t.readUInt32BE(),r=[];for(let e=4;e<t.length&&t[e]!==0;){let n=fw.deSerialize(t.slice(e));r.push(n),e+=n.length}return new e({source:n,items:r})}},fw=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([Cx([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 pw(e){return e%4==0?0:4-e%4}var mw=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())]),KC.serialize(e.type,this.reports.length,t,Math.floor(t.length/4))}static deSerialize(t,n){let r=t.readUInt32BE(),i=hw.deSerialize(t.subarray(4,24)),a=24,o=[];for(let e=0;e<n;e++)o.push($C.deSerialize(t.subarray(a,a+24))),a+=24;return new e({ssrc:r,senderInfo:i,reports:o})}},hw=class e{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:gw(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return Cx([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(t){let[n,r,i,a]=Tx(t,[8,4,4,4]);return new e({ntpTimestamp:n,rtpTimestamp:r,packetCount:i,octetCount:a})}},gw=e=>{let[t,n]=Tx(Cx([8],[e]),[4,4]);return Number(`${t}.${n}`)},_w=Zx(`werift-rtp:packages/rtp/src/rtcp/rtcp.ts`),vw=class{static deSerialize(e){let t=0,n=[];for(;t<e.length;){let r=KC.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 mw.type:n.push(mw.deSerialize(i,r.count));break;case QC.type:n.push(QC.deSerialize(i,r.count));break;case uw.type:n.push(uw.deSerialize(i,r));break;case lw.type:n.push(lw.deSerialize(i,r));break;case ZC.type:n.push(ZC.deSerialize(i,r))}}catch(e){_w(`deSerialize RTCP`,e)}}return n}};function yw(e){return e.length>=2&&e[1]>=192&&e[1]<=208}var bw={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 xw(e,t){return e.map(e=>{let n=t[e.id];if(!n)return{uri:`unknown`,value:e.payload};switch(n){case bw.sdesMid:case bw.sdesRTPStreamID:case bw.repairedRtpStreamId:return{uri:n,value:Dw(e.payload)};case bw.transportWideCC:return{uri:n,value:Ow(e.payload)};case bw.absSendTime:return{uri:n,value:kw(e.payload)};case bw.audioLevelIndication:return{uri:n,value:Aw(e.payload)};case bw.videoOrientation:return{uri:n,value:jw(e.payload)};default:return{uri:n,value:e.payload}}}).reduce((e,t)=>(t&&(e[t.uri]=t.value),e),{})}function Sw(e){return Buffer.from(e)}function Cw(e){return Buffer.from(e)}function ww(e){return Buffer.from(e)}function Tw(e){return Cx([2],[e])}function Ew(e){let t=Buffer.alloc(3),n=e>>14n&16777215n;return t.writeUIntBE(Number(n),0,3),t}function Dw(e){return e.toString()}function Ow(e){return e.readUInt16BE()}function kw(e){return Tx(e,[3])[0]}function Aw(e){let t=new Ex(e);return{v:t.readBits(1)===1,level:t.readBits(7)}}function jw(e){let t=new Ex(e);return t.readBits(4),{c:t.readBits(1),f:t.readBits(1),r1:t.readBits(1),r0:t.readBits(1)}}var Mw=Zx(`packages/rtp/src/rtp/red/packet.ts`),Nw=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]=Pw.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 Pw;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}},Pw=class e{fields=[];static deSerialize(t){let n=0,r=new e;for(;;){let e={};r.fields.push(e);let i=new Ex(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 Ex(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 Ex(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,n.uint8Array])}}catch(e){Mw(e?.message)}return e}},Fw=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 Nw,t=this.cache.slice(-(this.distance+1)),n=t.pop();return n?(t.forEach(t=>{let r=Hx(n.timestamp,-t.timestamp);r>Iw||e.blocks.push({block:t.block,blockPT:t.blockPT,timestampOffset:r})}),e.blocks.push({block:n.block,blockPT:n.blockPT}),e):e}},Iw=16383,Lw=class{size=150;sequenceNumbers=[];push(e,t){let n=[];return e.blocks.forEach(({blockPT:r,timestampOffset:i,block:a},o)=>{let s=Vx(t.header.sequenceNumber,-(e.blocks.length-(o+1)));i?n.push(new Gw(new Ww({timestamp:Hx(t.header.timestamp,-i),payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:!0}),a)):n.push(new Gw(new Ww({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))}},Rw={OneByte:48862,TwoByte:4096},zw=2,Bw=4,Vw=8,Hw=12,Uw=4,Ww=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=Rw.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(t){let n=new e,r=0,i=t[r++];n.version=Sx(i,0,2),n.padding=Sx(i,2)>0,n.extension=Sx(i,3)>0,n.csrcLength=Sx(i,4,4),n.csrc=[...Array(n.csrcLength)].map(()=>{let e=t.readUInt32BE(r);return r+=4,e}),r+=Hw-1;let a=t[1];n.marker=Sx(a,0)>0,n.payloadType=Sx(a,1,7),n.sequenceNumber=t.readUInt16BE(zw),n.timestamp=t.readUInt32BE(Bw),n.ssrc=t.readUInt32BE(Vw);for(let e=0;e<n.csrc.length;e++){let r=Hw+e*Uw;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 Rw.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 Rw.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*Uw;if(n.length>0||this.extension===!0){let e=4;switch(t){case Rw.OneByte:for(let t of n)e+=1+t.payload.length;break;case Rw.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 bx(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 bx(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),t.writeUInt8(i.value,n++),t.writeUInt16BE(this.sequenceNumber,zw),n+=2,t.writeUInt32BE(this.timestamp,Bw),n+=4,t.writeUInt32BE(this.ssrc,Vw),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 Rw.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 Rw.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}},Gw=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 Ww({...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=Ww.deSerialize(t);return new e(n,t.subarray(n.payloadOffset,t.length-n.paddingSize))}clear(){this.payload=null}};function Kw(e,t,n){return new Gw(new Ww({payloadType:t,marker:e.header.marker,sequenceNumber:e.payload.readUInt16BE(0),timestamp:e.header.timestamp,ssrc:n}),e.payload.subarray(2))}function qw(e,t,n,r){let i=Buffer.allocUnsafe(2);return i.writeUInt16BE(e.header.sequenceNumber,0),new Gw(new Ww({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 Jw=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[]}},Yw=class extends Error{constructor(e){super(e),this.name=`SrtpAuthenticationError`}},Xw=12,Zw=8;function Qw(e,t,n=`Failed to authenticate SRTP packet`){let r=e.length-t;eT(e.length>=Xw+t,n);let i=tT(()=>Ww.deSerialize(e.subarray(0,r)),n);return i.paddingSize=0,eT(i.payloadOffset>=Xw&&i.payloadOffset<=r,n),i}function $w(e,t,n,r=`Failed to authenticate SRTCP packet`){return eT(e.length>=Zw+t+n,r),tT(()=>KC.deSerialize(e.subarray(0,4)),r)}function eT(e,t){if(!e)throw new Yw(t)}function tT(e,t){try{return e()}catch{throw new Yw(t)}}function nT(e,t,n=`Failed to authenticate SRTP packet`){if(!e.padding)return e.paddingSize=0,e;eT(t.length>e.payloadOffset,n);let r=t[t.length-1];return eT(r>0&&r<=t.length-e.payloadOffset,n),e.paddingSize=r,e}var rT=class extends Jw{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=Qw(e,this.authTagLength)){let r=e.length-this.authTagLength,a=e.subarray(0,r);aT(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,nT(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=$w(e,this.authTagLength,iT),n=e.length-(this.authTagLength+iT),r=e.subarray(0,e.length-this.authTagLength);aT(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)}},iT=4;function aT(e,t,n){if(e.length!==t.length||!u(e,t))throw new Yw(n)}var oT=class extends Jw{aeadAuthTagLen=16;rtpIvWriter=wx([2,4,4,2],!0);rtcpIvWriter=wx([2,4,2,4],!0);aadWriter=wx([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=Qw(e,this.aeadAuthTagLen)){let r=e.subarray(0,n.payloadOffset),a=e.length-this.aeadAuthTagLen,o=e.subarray(a),s=Buffer.from([]);s=UC(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 lT(u,`SRTP`),d.copy(s,n.payloadOffset),[s,nT(n,s,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){let n=e.readUInt32BE(4),i=e.length+this.aeadAuthTagLen,a=Buffer.from([]);a=UC(a,i+sT),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=$w(e,this.aeadAuthTagLen,sT),n=e.length-sT,r=n-this.aeadAuthTagLen,a=e.readUInt32BE(4),o=e.readUInt32BE(n),s=o>>>31==1,c=o&~(cT<<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 lT(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]|=cT,n}},sT=4,cT=128;function lT(e,t){try{e.final()}catch{throw new Yw(`Failed to authenticate ${t} packet`)}}function uT(e,t){let n=r(`aes-128-ecb`,e,null);return n.setAutoPadding(!1),Buffer.concat([n.update(t),n.final()])}var dT=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 rT(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case 7:this.cipher=new oT(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])]),uT(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=uT(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=uT(this.masterKey,r),i=uT(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>fT&&t.rolloverCounter++:t.lastSequenceNumber<fT&&e>pT-fT?t.rolloverCounter>0&&t.rolloverCounter--:e<fT&&t.lastSequenceNumber>pT-fT&&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}},fT=100,pT=65535,mT=class extends dT{constructor(e,t,n){super(e,t,n)}encryptRTCP(e){let t=e.readUInt32BE(4),n=this.getSrtcpSsrcState(t);return n.srtcpIndex++,n.srtcpIndex>>hT&&(n.srtcpIndex=0),this.cipher.encryptRTCP(e,n.srtcpIndex)}decryptRTCP(e){return this.cipher.decryptRTCP(e)}},hT=2147483647,gT=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)}},_T=class extends gT{constructor(e){super(mT),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)}},vT=class extends dT{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=Qw(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}},yT=class extends gT{constructor(e){super(vT),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)}},bT=Zx(`werift-dtls : packages/dtls/src/flight/client/flight5.ts : log`),xT=class extends nC{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 LC.deSerialize(e.fragment);case 11:return jC.deSerialize(e.fragment);case 12:return BC.deSerialize(e.fragment);case 13:return IC.deSerialize(e.fragment);case 14:return RC.deSerialize(e.fragment)}})();t&&ST[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}async exec(){if(this.dtls.flight===5){bT(this.dtls.sessionId,`flight5 twice`),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let e=this.dtls.requestedCertificateTypes.length>0;bT(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 jC([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 PC(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=gS(i.publicKey,r.privateKey,r.curve);bT(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?bS(a,o):yS(a,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=TC(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),bT(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 iS.ecdsa_3:return dS.ecdsa_secp256r1_sha256;case iS.rsa_1:return dS.rsa_pkcs1_sha256}})();if(!n)throw Error();bT(this.dtls.sessionId,`signatureScheme`,this.cipher.signatureHashAlgorithm?.signature,n);let r=new NC(n,t),i=this.createPacket([r]);return Buffer.concat(i.map(e=>e.serialize()))}sendChangeCipherSpec(){let e=MC.createEmpty().serialize(),t=QS(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 FC(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 bT(this.dtls.sessionId,`finished`,this.cipher.cipher.summary),r}},ST={};ST[2]=({cipher:e,srtp:t,dtls:n})=>r=>{bT(n.sessionId,`serverHello`,r.cipherSuite),e.remoteRandom=qS.from(r.random),e.cipherSuite=r.cipherSuite,bT(n.sessionId,`selected cipherSuite`,e.cipherSuite),r.extensions&&r.extensions.forEach(e=>{switch(e.type){case AC.type:{let r=AC.fromData(e.data),i=jS.findMatchingSRTPProfile(r.profiles,n.options.srtpProfiles||[]);if(bT(n.sessionId,`selected srtp profile`,i),i==null)return;t.srtpProfile=i}break;case OC.type:n.remoteExtendedMasterSecret=!0;break;case kC.type:bT(n.sessionId,`RenegotiationIndication`)}})},ST[11]=({cipher:e,dtls:t})=>n=>{bT(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},ST[12]=({cipher:e,dtls:t})=>n=>{if(!e.localRandom||!e.remoteRandom)throw Error();bT(t.sessionId,`ServerKeyExchange`,n),bT(t.sessionId,`selected curve`,n.namedCurve),e.remoteKeyPair={curve:n.namedCurve,publicKey:n.publicKey},e.localKeyPair=DC(n.namedCurve)},ST[13]=({dtls:e})=>t=>{bT(e.sessionId,`certificate_request`,t),e.requestedCertificateTypes=t.certificateTypes,e.requestedSignatureAlgorithms=t.signatures},ST[14]=({dtls:e})=>t=>{bT(e.sessionId,`server_hello_done`,t)};var CT=class e{constructor(e,t){this.serverVersion=e,this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:KS,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 PS(this.msgType,e.length,this.messageSeq,0,e.length,e)}},wT=Zx(`werift-dtls : packages/dtls/src/context/dtls.ts : log`),TT=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||(wT(this.sessionId,`exist`,r.summary,t,n),!1)});this.handshakeCache[n].data=[...this.handshakeCache[n].data,...r]}},ET=class{constructor(e){this.socket=e}send=(e,t)=>this.socket.send(e,t)},DT=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)}}},OT=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)}}},kT=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)}},AT=Zx(`werift-dtls : packages/dtls/record/receive.ts : log`),jT=Zx(`werift-dtls : packages/dtls/record/receive.ts : err`),MT=e=>{let t=0,n=[];for(;e.length>t;){let r=e.readUInt16BE(t+11);if(e.length<t+(12+r))break;let i=XS.deSerialize(e.subarray(t));n.push(i),t+=13+r}return n},NT=(e,t)=>n=>{switch(n.recordLayerHeader.contentType){case 20:return AT(e.sessionId,`change cipher spec`),[{type:20,data:void 0}];case 22:{let r=n.fragment;try{n.recordLayerHeader.epoch>0&&(AT(e.sessionId,`decrypt handshake`),r=t.decryptPacket(n))}catch(t){throw jT(e.sessionId,`decrypt failed`,t),t}try{let e=0,t=[];for(;r.length>e;){let n=PS.deSerialize(r.subarray(e));t.push({type:22,data:n}),e+=n.fragment_length+12}return t}catch(t){throw jT(e.sessionId,`decSerialize failed`,t,r),t}}case 23:return[{type:23,data:t.decryptPacket(n)}];case 21:{let r=kT.deSerialize(n.fragment);if($S[r.description]==null){let e=t.decryptPacket(n);r=kT.deSerialize(e)}if(jT(e.sessionId,`ContentType.alert`,r,$S[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}]}},PT=Zx(`werift-dtls : packages/dtls/src/socket.ts : log`),FT=Zx(`werift-dtls : packages/dtls/src/socket.ts : err`),IT=class{constructor(e,t){this.options=e,this.sessionType=t,this.dtls=new TT(this.options,this.sessionType),this.cipher=new AS(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new ET(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new $;onData=new $;onError=new $;onClose=new $;transport;cipher;dtls;srtp=new jS;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){PT(`renegotiation`,this.sessionType),this.connected=!1,this.cipher=new AS(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new TT(this.options,this.sessionType),this.srtp=new jS,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=e=>{let t=MT(e);for(let e of t)try{let t=NT(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=>PS.assemble(e)).sort((e,t)=>e.msg_type-t.msg_type);this.onHandleHandshakes(r).catch(e=>{FT(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){FT(this.dtls.sessionId,`catch udpOnMessage error`,e)}};setupExtensions(){if(PT(this.dtls.sessionId,`support srtpProfiles`,this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let e=AC.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{let e=DT.createEmpty();e.data=lS,this.extensions.push(e.extension)}{let e=OT.createEmpty();e.data=pS,this.extensions.push(e.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:OC.type,data:Buffer.alloc(0)});{let e=kC.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=QS(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===DS.CLIENT?{localKey:r,localSalt:a,remoteKey:i,remoteSalt:o}:{localKey:i,localSalt:o,remoteKey:r,remoteSalt:a}}exportKeyingMaterial(e,t){return xS(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===DS.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},LT=Zx(`werift-dtls : packages/dtls/src/client.ts : log`),RT=class extends IT{constructor(e){super(e,DS.CLIENT),this.onHandleHandshakes=this.handleHandshakes,LT(this.dtls.sessionId,`start client`)}async connect(){await new rC(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async e=>{LT(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(let t of e)switch(t.msg_type){case 3:{let e=CT.deSerialize(t.fragment);await new aC(this.transport,this.dtls).exec(e)}break;case 2:if(this.connected)return;this.flight5=new xT(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(),LT(this.dtls.sessionId,`dtls connected`)}}},zT=Zx(`werift-dtls : packages/dtls/flight/server/flight2.ts : log`),BT=(e,t,n,r)=>i=>{zT(`dtls version`,i.clientVersion),t.flight=2,t.recordSequenceNumber=0,t.sequenceNumber=0,i.extensions.forEach(e=>{switch(e.type){case DT.type:{let r=DT.fromData(e.data).data;zT(t.sessionId,`curves`,r),n.namedCurve=r.filter(e=>lS.includes(e))[0],zT(t.sessionId,`curve selected`,n.namedCurve)}break;case OT.type:{if(!n.signatureHashAlgorithm)throw Error(`need to set certificate`);let r=OT.fromData(e.data).data;zT(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 AC.type:{if(!t.options?.srtpProfiles||t.options.srtpProfiles.length===0)return;let n=AC.fromData(e.data);zT(t.sessionId,`srtp profiles`,n.profiles);let i=jS.findMatchingSRTPProfile(n.profiles,t.options?.srtpProfiles);if(!i)throw Error();r.srtpProfile=i,zT(t.sessionId,`srtp profile selected`,r.srtpProfile)}break;case OC.type:t.remoteExtendedMasterSecret=!0;break;case kC.type:zT(t.sessionId,`RenegotiationIndication`,e.data);break;case 43:zT(`dtls supported version`,[...e.data.subarray(1)].map(e=>e.toString(10)))}}),n.localRandom=new qS,n.remoteRandom=qS.from(i.random);let a=i.cipherSuites;zT(t.sessionId,`cipher suites`,a);let o=(()=>{switch(n.signatureHashAlgorithm?.signature){case iS.ecdsa_3:return oS.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case iS.rsa_1:return oS.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,zT(t.sessionId,`selected cipherSuite`,n.cipherSuite),n.localKeyPair=DC(n.namedCurve),t.cookie||=c(20);let s=new CT({major:254,minor:253},t.cookie),l=ZS(t)([s]),u=QS(t)(l.map(e=>({type:22,fragment:e.serialize()})),++t.recordSequenceNumber).map(e=>e.serialize());for(let t of u)e.send(t)},VT=Zx(`werift-dtls : packages/dtls/flight/server/flight4.ts : log`),HT=class extends nC{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){VT(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(AC.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&e.push({type:OC.type,data:Buffer.alloc(0)});let t=kC.createEmpty();e.push(t.extension);let n=new LC(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 jC([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 BC(uS.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 IC(fS,pS,[]);VT(this.dtls.sessionId,`sendCertificateRequest`,e);let t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendServerHelloDone(){let e=new RC,t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}},UT=Zx(`werift-dtls : packages/dtls/flight/server/flight6.ts`),WT=class extends nC{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 jC.deSerialize(e.fragment);case 15:return NC.deSerialize(e.fragment);case 16:return PC.deSerialize(e.fragment);case 20:return FC.deSerialize(e.fragment)}})();if(t){let e=GT[t.msgType];if(!e)return;e({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){UT(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=MC.createEmpty().serialize(),t=QS(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 FC(this.cipher.verifyData(e));this.dtls.epoch=1;let[n]=this.createPacket([t]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(n).serialize()}},GT={};GT[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=gS(e.remoteKeyPair.publicKey,e.localKeyPair.privateKey,e.localKeyPair.curve);UT(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?bS(r,i):yS(r,e.remoteRandom.serialize(),e.localRandom.serialize()),e.cipher=TC(e.cipherSuite),e.cipher.init(e.masterSecret,e.localRandom.serialize(),e.remoteRandom.serialize()),UT(t.sessionId,`setup cipher`,e.cipher.summary)},GT[11]=({cipher:e,dtls:t})=>n=>{UT(t.sessionId,`handshake certificate`,n),e.remoteCertificate=n.certificateList[0]},GT[15]=({cipher:e,dtls:t})=>n=>{if(!e.remoteCertificate)throw Error(`client certificate missing before certificate verify`);UT(t.sessionId,`certificate_verify`,n.algorithm)},GT[20]=({dtls:e})=>t=>{UT(e.sessionId,`finished`,t)};var KT=Zx(`werift-dtls : packages/dtls/src/server.ts : log`),qT=class extends IT{constructor(e){super(e,DS.SERVER),this.onHandleHandshakes=this.handleHandshakes,KT(this.dtls.sessionId,`start server`)}flight6;handleHandshakes=async e=>{KT(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=JS.deSerialize(t.fragment);e.cookie.length===0?(KT(this.dtls.sessionId,`send flight2`),BT(this.transport,this.dtls,this.cipher,this.srtp)(e)):this.dtls.cookie&&e.cookie.equals(this.dtls.cookie)?(KT(this.dtls.sessionId,`send flight4`),await new HT(this.transport,this.dtls,this.cipher,this.srtp).exec(t,this.options.certificateRequest)):KT(`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 WT(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(),KT(this.dtls.sessionId,`dtls connected`)}}}},JT=554869826,YT=1398035790;function XT(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 ZT(e){let t=Buffer.alloc(2);return t.writeUInt16BE(e.length,0),Buffer.concat([t,e])}function QT(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 $T(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=$T(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 eE(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 tE(e){return x(e)}function nE(e){let[t]=e,n=tE(t)?1:2,r=Buffer.alloc(4);return r.writeUInt8(0,0),r.writeUInt8(n,1),r.writeUInt16BE(e[1],2),Buffer.concat([r,$T(t)])}function rE(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 iE(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[eE(r),n];case 2:if(r.length!==16)throw Error(`STUN address has invalid length for IPv6`);return[eE(r),n];default:throw Error(`STUN address has unknown protocol`)}}var aE=Buffer.alloc(6);aE.writeUInt16BE(JT>>16,0),aE.writeUInt32BE(JT,2);function oE(e,t){let n=[...aE,...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 sE(e,t){return iE(oE(e,t))}function cE(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 lE(e){let t=Buffer.alloc(e.length*2);return e.forEach((e,n)=>{t.writeUInt16BE(e,n*2)}),t}function uE(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 dE(e,t){return oE(nE(e),t)}var fE=e=>{let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t},pE=e=>e.readUInt32BE(0),mE=e=>{let t=Buffer.alloc(4);return t.writeUInt16BE(e,0),t},hE=e=>e.readUInt16BE(0),gE=e=>{let t=Buffer.allocUnsafe(8);return t.writeBigUInt64BE(e,0),t},_E=e=>e.readBigUInt64BE(0),vE=e=>Buffer.from(e,`utf8`),yE=e=>e.toString(`utf8`),bE=e=>{if([...e].length>=128)throw Error(`SOFTWARE must be shorter than 128 characters`);return vE(e)},xE=e=>e,SE=e=>e,CE=[[1,`MAPPED-ADDRESS`,nE,iE],[3,`CHANGE-REQUEST`,fE,pE],[4,`SOURCE-ADDRESS`,nE,iE],[5,`CHANGED-ADDRESS`,nE,iE],[6,`USERNAME`,vE,yE],[8,`MESSAGE-INTEGRITY`,xE,SE],[9,`ERROR-CODE`,cE,rE],[10,`UNKNOWN-ATTRIBUTES`,lE,uE],[12,`CHANNEL-NUMBER`,mE,hE],[13,`LIFETIME`,fE,pE],[18,`XOR-PEER-ADDRESS`,dE,sE],[19,`DATA`,xE,SE],[20,`REALM`,vE,yE],[21,`NONCE`,xE,SE],[22,`XOR-RELAYED-ADDRESS`,dE,sE],[23,`REQUESTED-ADDRESS-FAMILY`,fE,pE],[24,`EVEN-PORT`,xE,SE],[25,`REQUESTED-TRANSPORT`,fE,pE],[28,`MESSAGE-INTEGRITY-SHA256`,xE,SE],[29,`PASSWORD-ALGORITHM`,xE,SE],[30,`USERHASH`,xE,SE],[32,`XOR-MAPPED-ADDRESS`,dE,sE],[34,`RESERVATION-TOKEN`,xE,SE],[36,`PRIORITY`,fE,pE],[37,`USE-CANDIDATE`,()=>Buffer.alloc(0),()=>null],[32770,`PASSWORD-ALGORITHMS`,xE,SE],[32771,`ALTERNATE-DOMAIN`,vE,yE],[32802,`SOFTWARE`,bE,yE],[32803,`ALTERNATE-SERVER`,nE,iE],[32808,`FINGERPRINT`,fE,pE],[32809,`ICE-CONTROLLED`,gE,_E],[32810,`ICE-CONTROLLING`,gE,_E],[32811,`RESPONSE-ORIGIN`,nE,iE],[32812,`OTHER-ADDRESS`,nE,iE]],wE=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=[]}},TE=CE.reduce((e,t)=>(e[t[0]]=t,e),{}),EE=CE.reduce((e,t)=>(e[t[1]]=t,e),{});function DE(e,t){if(!XT(e))return;let n=e.readUInt16BE(0),r=Buffer.from(e.slice(8,20)),i=new wE,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=NE(c);if(u+f>e.length)return;let p=TE[s];if(p){let[,a,,s]=p,c;try{c=s.name===sE.name?s(d,r):s(d)}catch{return}if(i.setAttribute(a,c),a===`FINGERPRINT`){let t=jE(e.slice(0,n));if(i.getAttributeValue(`FINGERPRINT`)!==t)return}else if(a===`MESSAGE-INTEGRITY`&&t){let r=ME(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 OE(n&16111,n&272,r,i.getAttributes(),a)}var OE=class extends wE{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=>kE(e.type,e.value))),t=Buffer.alloc(8);return t.writeUInt16BE(this.messageMethod|this.messageClass,0),t.writeUInt16BE(e.length,2),t.writeUInt32BE(JT,4),Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){return this.setAttribute(`MESSAGE-INTEGRITY`,this.messageIntegrity(e)),this}messageIntegrity(e){let t=AE(this.bytes,this.bytes.length-20+24);return Buffer.from(o(`sha1`,e).update(t).digest(`hex`),`hex`)}addFingerprint(){return this.setAttribute(`FINGERPRINT`,jE(this.bytes)),this}get serializedAttributes(){let e=[];for(let t of this.attributesKeys){let n=this.getAttributeValue(t),[r,,i]=EE[t],a=i.name===dE.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 kE(e,t){let n=t.length,r=NE(n),i=Buffer.alloc(4);return i.writeUInt16BE(e,0),i.writeUInt16BE(n,2),Buffer.concat([i,t,Buffer.alloc(r)])}var AE=(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 jE(e){return(Rx(AE(e,e.length-20+8))^YT)>>>0}function ME(e,t){let n=AE(e,e.length-20+24);return Buffer.from(o(`sha1`,t).update(n).digest(`hex`),`hex`)}function NE(e){let t=e%4;return t===0?0:4-t}var PE=class extends Error{response;addr},FE=class extends PE{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}},IE=class extends PE{get str(){return`STUN transaction timed out`}},LE=Zx(`werift-ice:packages/ice/src/stun/transaction.ts`);async function RE(e,t=0){return b(e[0])?e:[(await D.lookup(e[0],{family:t})).address,e[1]]}function zE(e,t){return typeof e==`object`&&e?e:{retransmissions:typeof e==`number`?e:void 0,onRequestSent:t}}function BE(e,t){return e[0]===t[0]&&e[1]===t[1]}var VE=class{constructor(e,t,n,r,i){this.request=e,this.addr=t,this.protocol=n;let a=zE(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(!BE(this.expectedAddr,t)){LE(`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`))){LE(`ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)`);return}e.messageClass===256?(this.onResponse.execute(e,t),this.onResponse.complete()):this.onResponse.error(new FE(e,t))}};run=async()=>{try{if(this.signal?.aborted)throw new IE;return this.attachAbortListener(),this.retry().catch(e=>{LE(`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 IE))}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=>{LE(`send stun failed`,e)}),await this.wait(this.timeoutDelay),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&!this.ended&&(LE(`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 HE(e,t,n){let r=zE(t,n);return e&&!r.integrityKey&&(r.integrityKey=e),r}var UE=Zx(`werift-ice:packages/ice/src/stun/tcpProtocol.ts`);function WE(e){return`${e[0]}:${e[1]}`}function GE(e){if(e.remoteAddress&&e.remotePort)return[e.remoteAddress,e.remotePort]}async function KE(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 qE=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(WE(t),e)}forgetSocket(e){e&&this.sockets.delete(WE(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}=QT(n.buffer);n.buffer=i;let a=n.remoteAddr??GE(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=>{UE(`tcp socket error`,e)}),n}handleFrame(e,t){try{let n=DE(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?DE(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(`tcp frame parse error`,e)}}async sendFrame(e,t){let n=await this.getSocket(t);await new Promise((t,r)=>{n.socket.write(ZT(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 RE(t),o=HE(n,r,i),s=new VE(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===WE(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()}},JE=class extends qE{pendingSockets=new Map;async connectionMade(e){this.localIp=e}async getSocket(e){let t=WE(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)}}},YE=class extends qE{server=y(e=>{this.registerSocket(e,GE(e))});async connectionMade(e,t){if(this.localIp=e,t){let n;for(let r=t[0];r<=t[1];r++)try{await KE(this.server,e,r);return}catch(e){n=e}throw n??Error(`tcp port not found`)}await KE(this.server,e)}async getSocket(e){let t=this.sockets.get(WE(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())})}},XE=Zx(`werift-ice : packages/ice/src/stun/protocol.ts`),ZE=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 eS.init(`udp4`,{portRange:t,interfaceAddresses:n}):await eS.init(`udp6`,{portRange:t,interfaceAddresses:n}),this.transport.onData=(e,t)=>{this.datagramReceived(e,t)}};datagramReceived(e,t){try{let n=DE(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?DE(e,r.integrityKey):n;if(!i){XE(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else n.messageClass===0&&this.onRequestReceived.execute(n,t,e)}catch(e){XE(`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(()=>{XE(`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 RE(t,this.transport.socketType===`udp6`?6:4),o=HE(n,r,i),s=new VE(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 QE(e,t,n){return a(`md5`).update(Buffer.from([e,t,n].join(`:`))).digest()}function $E(e){return c(e).toString(`hex`).substring(0,e)}function eD(){return c(12)}var tD=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)})})}},nD=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 rD(e){return e.length>=4&&(e[0]&192)==64}function iD(e,t){let n=Buffer.alloc(4);return n.writeUInt16BE(e,0),n.writeUInt16BE(t.length,2),Buffer.concat([n,t])}function aD(e){if(!rD(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 oD(e){let t=NE(e.length);return t>0?Buffer.concat([e,Buffer.alloc(t)]):e}function sD(e){let t=[],n=0,r=!1;for(;e.length-n>=4;){let i;if(rD(e.subarray(n))){let t=e.readUInt16BE(n+2);i=4+t+NE(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+NE(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 cD=Zx(`werift-ice:packages/ice/src/turn/protocol.ts`),lD=500,uD=600,dD=285212672;function fD(e){return e.type===`tcp`||e.type===`tls`}function pD(e){return e[0]}function mD(e){return JSON.stringify(e)}var hD=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 Qx;onRequestReceived=new $;onDataReceived=new $;handleStunMessage=(e,t)=>{try{let n=DE(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?DE(e,r.integrityKey):n;if(!i){cD(`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){cD(`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 RE(t),o=HE(n,r,i),s=new VE(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()}},gD=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??lD}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 OE(3,0);e.setAttribute(`LIFETIME`,this.lifetime).setAttribute(`REQUESTED-TRANSPORT`,dD);let[t]=await this.requestWithRetry(e,this.server).catch(e=>{throw cD(`connect error`,e),e});this.relayedAddress=t.getAttributeValue(`XOR-RELAYED-ADDRESS`),this.mappedAddress=t.getAttributeValue(`XOR-MAPPED-ADDRESS`);let n=t.getAttributeValue(`LIFETIME`);cD(`connect`,this.relayedAddress,this.mappedAddress,{exp:n}),this.refresh(n)}handleChannelData(e){let t=aD(e),n=t&&this.addrByChannel[t.channelNumber];n&&t&&this.onData.execute(t.data,n)}handleSTUNMessage(e,t){try{let n=DE(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?DE(e,r.integrityKey):n;if(!i){cD(`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{cD(`parse error`,e.toString())}}dataReceived(e,t){let n=(e,t)=>{e.length>=4&&rD(e)?this.handleChannelData(e):this.handleSTUNMessage(e,t)};if(fD(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);let{frames:r,rest:i}=sD(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(fD(this.transport)?oD(e):e,t)}async createPermission(e){let t=new OE(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=nD(async(t,n,r)=>{let i=!0;for(r.once(()=>{i=!1});i;){let t=5/6*e*1e3;cD(`refresh delay`,t,{exp:e}),await E(t);let n=new OE(4,0);n.setAttribute(`LIFETIME`,e);try{let[t]=await this.requestWithRetry(n,this.server);e=t.getAttributeValue(`LIFETIME`),cD(`refresh`,{exp:e})}catch(e){cD(`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 RE(t),o=HE(this.integrityKey,r,i),s=new VE(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 FE==0)throw cD(`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)cD(`retry with nonce`,i),this.nonce=a,i===401&&(this.realm=o),this.integrityKey=yD(this.username,this.realm,this.password),e.transactionId=eD(),[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){cD(`channelBind error; falling back to Send Indication`,e)}if(!n){await this.getPermission(t);let n=new OE(6,16).setAttribute(`DATA`,e).setAttribute(`XOR-PEER-ADDRESS`,t);await this.sendStun(n,this.server);return}await this.send(iD(n.number,e),this.server)}async getPermission(e){let t=pD(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 cD(`createPermission error`,e),e}finally{this.creatingPermissionByAddr.get(t)===r&&this.creatingPermissionByAddr.delete(t)}}async getChannel(e){let t=mD(e),n=this.channelBindingByAddr.get(t);if(n)return n;let r=this.channelByAddr[t],i=qx(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 cD(`channelBind error`,e),e}finally{this.channelBindingByAddr.get(t)===a&&this.channelBindingByAddr.delete(t)}}async ensureChannel(e){let t=mD(e),n=qx(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=qx(Date.now()/1e3)+this.channelRefreshTime,cD(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 OE(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 _D({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){r??=uD,c??=o?`tls`:`udp`;let l=c===`udp`?await eS.init(`udp4`,{portRange:i,interfaceAddresses:a}):c===`tcp`?await tS.init(e):await nS.init(e,s),u=new gD(e,t,n,r,l);return await u.connectionMade(),u}async function vD({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}={}){return new hD(await _D({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c}))}function yD(e,t,n){return QE(e,t,n)}var bD=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()&&DD(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}},xD={host:126,prflx:110,srflx:100,relay:0},SD={host:105,prflx:90,srflx:80,relay:0},CD={active:6,passive:4,so:2},wD={active:4,passive:2,so:6};function TD(e){return e?.toLowerCase()??`udp`}function ED(e){switch(e){case`active`:case`passive`:case`so`:return e;default:return}}function DD(e,t){if(TD(e.transport)!==`tcp`)return!0;let n=ED(e.tcptype),r=ED(t.tcptype);return!n||!r?!1:n===`active`&&r===`passive`||n===`passive`&&r===`active`||n===`so`&&r===`so`}function OD({candidateType:e,transport:t=`udp`,tcptype:n,otherPreference:r=8191}){if(TD(t)!==`tcp`)return r;let i=ED(n)??`active`;return 8192*(e===`srflx`||e===`prflx`?wD[i]:CD[i])+r}function kD(e,t=`udp`){return(TD(t)===`tcp`?SD:xD)[e]??0}function AD(e,t,n){let r=`${e}|${t}|${n}`;return a(`md5`).update(r,`ascii`).digest(`hex`).slice(7)}function jD(e,t=65535){let n=typeof t==`number`?`udp`:TD(t.transport),r=typeof t==`number`?t:t.localPreference??OD({candidateType:e,transport:n,tcptype:t.tcptype,otherPreference:t.otherPreference});return(1<<24)*kD(e,n)+256*r+255}function MD(e){switch(e){case`passive`:return`active`;case`active`:return`passive`;default:return`so`}}var ND=class{cache=new Map;mdnsInstance=(0,_x.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()}},PD=Zx(`werift-ice : packages/ice/src/ice.ts : log`),FD=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 VD(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)}},ID=1e3;function LD(e){return e===void 0||!Number.isFinite(e)||e<=0?ID:Math.max(500,Math.round(e*1e3*2+200))}var RD={iceLite:!1,useTcp:!1,useIpv4:!0,useIpv6:!0};function zD(e){if(![`host`,`relay`,`srflx`].includes(e.type))throw Error(`Unexpected candidate type "${e.type}"`);return e}function BD(e,t){return e.sort((e,n)=>VD(e.localCandidate,e.remoteCandidate,t)-VD(n.localCandidate,n.remoteCandidate,t)).reverse()}function VD(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 HD(e,t){let n=new OE(1,0);try{let[r]=await e.request(n,t),i=e.localCandidate;if(!i)throw Error(`not exist`);return new bD(AD(`srflx`,i.transport,i.host),i.component,i.transport,jD(`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){PD(`error serverReflexiveCandidate`,e)}}function UD(e){return e&&Number.isNaN(e[1])?[e[0],443]:e}function WD(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=>Xx(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 GD=Zx(`werift-ice : packages/ice/src/utils.ts`);function KD(e){return Xx(e.family)===4&&e.address?.startsWith(`169.254.`)||Xx(e.family)===6&&e.address?.startsWith(`fe80::`)}function qD(e,{useLinkLocalAddress:t}={}){let n=m.networkInterfaces();return GD(n),WD(n,e,{useLinkLocalAddress:t},KD)}function JD(e,t,n={}){let r=[];return e&&r.push(...qD(4,n)),t&&r.push(...qD(6,n)),r}var YD=Zx(`werift-ice : packages/ice/src/ice.ts : log`),XD=class{constructor(e,t){this._iceControlling=e,this.options={...RD,...t},this.iceLite&&(this._iceControlling=!1);let{stunServer:n,turnServer:r}=this.options;this.stunServer=UD(n)??[`stun.l.google.com`,19302],this.turnServer=UD(r),this.restart(),YD(`new Connection`,this.options)}localUsername=$E(4);localPassword=$E(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 tD;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=$E(4),this.localPassword=$E(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 tD,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(){YD(`resetNominatedPair`),this.nominated=void 0,this.nominating=!1,this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:n}){YD(`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=JD(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}=QD(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 OE(1,256,t.transactionId);s.setAttribute(`XOR-MAPPED-ADDRESS`,n).addMessageIntegrity(Buffer.from(a,`utf8`)).addFingerprint(),e.sendStun(s,n).catch(e=>{YD(`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){YD(`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 ZE;this.ensureProtocol(t);try{await t.connectionMade(w(e),this.options.portRange,this.options.interfaceAddresses),t.localIp=e,this.protocols.push(t),YD(`protocol`,t.localIp);let n=[e,t.getExtraInfo()[1]];return t.localCandidate=new bD(AD(`host`,`udp`,n[0]),1,`udp`,jD(`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){YD(`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 YE;if(this.ensureProtocol(t),await t.connectionMade(e,this.options.portRange),t.localIp=e,t.localCandidate=new bD(AD(`host`,`tcp`,e),1,`tcp`,jD(`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 JE;this.ensureProtocol(t),await t.connectionMade(e),t.localIp=e,t.localCandidate=new bD(AD(`host`,`tcp`,e),1,`tcp`,jD(`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 HD(n,r).catch(e=>{YD(`error`,e)});t&&this.appendLocalCandidate(t),clearTimeout(a),e(t)}else clearTimeout(a),e()}).catch(e=>{YD(`query STUN server`,e)})});n.push(...e)}if(!s&&i&&a&&o){let e=(async()=>{let e=this.options.turnTransport??`udp`,t=await vD({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 vD({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 YD(`turn candidateAddress`,n),t.localCandidate=new bD(AD(`relay`,`udp`,n[0]),1,`udp`,jD(`relay`),n[0],n[1],`relay`,r[0],r[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(t.localCandidate),t.localCandidate})().catch(e=>{YD(`query TURN server`,e)});n.push(e)}return n}async connect(){if(YD(`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(),YD(`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(),YD(`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(),YD(`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===ZE.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=nD(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`&&(YD(`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=LD(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&&YD(`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 ND,e.host=await this.lookup.lookup(e.host)}catch{return}try{zD(e)}catch{return}YD(`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{zD(t)}catch{continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){BD(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){YD(`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){YD(`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||=(YD(`ICE completed`),this.checkListState.put(new Promise(e=>e(1))),!0);return}YD(`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||(YD(`ICE failed`),this.checkListState.put(new Promise(e=>{e(2)}))))}checkStart=e=>nD(async t=>{YD(`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++,YD(`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(YD(`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){YD(`retry 401`,e.toJSON()),await this.checkStart(e).awaitable,t();return}YD(`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}=QD(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 bD($E(10),1,n.localCandidate?.transport??`udp`,e.getAttributeValue(`PRIORITY`),a,o,`prflx`,void 0,void 0,n.localCandidate?.transport===`tcp`?MD(n.localCandidate.tcptype):void 0,void 0,void 0),this._remoteCandidates.push(i));let s=this.findPair(n,i);if(s||(s=new FD(n,i,this.iceControlling),s.updateState(1),this.addPair(s)),s.noteIncomingRequest(e.transactionIdHex),s.requestsReceived++,s.responsesSent++,s.localCandidate.ufrag=r,YD(`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 FD(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=ZD({remoteUsername:t,localUsername:n}),o=new OE(1,0);return o.setAttribute(`USERNAME`,a).setAttribute(`PRIORITY`,jD(`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 OE(e.messageMethod,272,e.transactionId);i.setAttribute(`ERROR-CODE`,r).addMessageIntegrity(Buffer.from(this.localPassword,`utf8`)).addFingerprint(),n.sendStun(i,t).catch(e=>{YD(`sendStun error`,e)})}},ZD=({remoteUsername:e,localUsername:t})=>`${e}:${t}`,QD=e=>{let[t,n]=e.split(`:`);return{remoteUsername:t,localUsername:n}};function $D(e){return e.map((e,t)=>[t,e])}function eO(e,t){let n=e.split(t);return[n[0],n.slice(1).join(t)]}var tO=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)},nO=Zx(`werift:packages/webrtc/src/dataChannel.ts`);function rO(e){return Buffer.isBuffer(e)?e.length:Buffer.byteLength(e)}var iO=class extends tO{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()}nO(`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)}},aO=class{label=``;maxPacketLifeTime;maxRetransmits;ordered=!0;protocol=``;negotiated=!1;id;constructor(e={}){Object.assign(this,e)}},oO=()=>({type:`nack`}),sO=()=>({type:`nack`,parameter:`pli`}),cO=()=>({type:`goog-remb`}),lO=()=>({type:`transport-cc`}),uO=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}},dO=class{id;uri;constructor(e){Object.assign(this,e)}},fO=class{type;parameter;constructor(e={}){Object.assign(this,e)}},pO=class{ssrc;constructor(e={}){Object.assign(this,e)}},mO=class{ssrc;payloadType;rtx;constructor(e){Object.assign(this,e)}},hO=class{rid;direction;constructor(e){Object.assign(this,e)}},gO=(e={})=>new uO({mimeType:`video/h264`,clockRate:9e4,rtcpFeedback:[oO(),sO(),cO()],parameters:`profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1`,...e}),_O=(e={})=>new uO({mimeType:`video/VP8`,clockRate:9e4,rtcpFeedback:[oO(),sO(),cO()],...e}),vO=(e={})=>new uO({mimeType:`video/VP9`,clockRate:9e4,rtcpFeedback:[oO(),sO(),cO()],...e}),yO=(e={})=>new uO({mimeType:`video/AV1X`,clockRate:9e4,rtcpFeedback:[oO(),sO(),cO()],...e}),bO=(e={})=>new uO({mimeType:`audio/OPUS`,clockRate:48e3,channels:2,...e}),xO=(e={})=>new uO({mimeType:`audio/PCMU`,clockRate:8e3,channels:1,payloadType:0,...e}),SO=[yO(),vO(),_O(),gO(),bO(),xO()].map(e=>e.mimeType);SO.filter(e=>e.toLowerCase().startsWith(`video/`)),SO.filter(e=>e.toLowerCase().startsWith(`audio/`));var CO=2,wO=3,TO=0,EO=50,DO=51,OO=53,kO=56,AO=57,jO=`0.0.0.0`,MO=9,NO={auto:`actpass`,client:`active`,server:`passive`},PO=Object.keys(NO).reduce((e,t)=>{let n=NO[t];return e[n]=t,e},{}),FO=[`apt`,`max-fr`,`max-fs`,`maxplaybackrate`,`minptime`,`stereo`,`useinbandfec`],IO=[`cname`,`msid`,`mslabel`,`label`],LO={SRTP_AES128_CM_HMAC_SHA1_80:1,SRTP_AEAD_AES_128_GCM:7},RO=[`sendonly`,`sendrecv`],zO=[`sendrecv`,`recvonly`],BO=class extends Map{constructor(e){if(super(),e)for(let t of e)this.set(t.id,t)}};function VO(e,...t){return`${e}_${t.filter(e=>e!==void 0).join(`_`)}`}function HO(e,t,n){return VO(`codec`,e,t,n)}function UO(){return performance.timeOrigin+performance.now()}function WO(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 GO(e,t){let n=new Map;for(let t of e)n.set(t.id,t);if(!t)return new BO([...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(...WO(t)))}return new BO([...r].map(e=>n.get(e)).filter(e=>!!e))}var KO=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`&&RO.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=UO();return this.collectCodecStats(e)}collectCodecStats(e){let t=[];if(!this.dtlsTransport)return t;let n=VO(`transport`,this.dtlsTransport.id);for(let r of this.codecs){let i={type:`codec`,id:HO(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}},qO=[`inactive`,`sendonly`,`recvonly`,`sendrecv`],JO=class extends tO{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)?Gw.deSerialize(e):e;t.header.payloadType=this.codec?.payloadType??t.header.payloadType,this.onReceiveRtp.execute(t)}},YO=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`)}},XO=Zx(`werift:packages/webrtc/src/utils.ts`);function ZO(e,t){return(e=>e.match(/(.{2})/g).join(`:`))((e=>e.toUpperCase())(a(t).update(e).digest(`hex`)))}var QO={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 $O(e){return QO[e.trim().toLowerCase()]}function ek(e){return e.replace(/[^0-9a-f]/gi,``).toLowerCase()}function tk(e){let t=e[0];return t>19&&t<64}var nk=(e,t)=>qO[qO.indexOf(e)&qO.indexOf(t)];function rk(e){return e===`sendonly`?`recvonly`:e===`recvonly`?`sendonly`:e}var ik=Date.now,ak=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,ok=()=>ak+process.hrtime.bigint()/1000n,sk=()=>Date.now()/1e3,ck=()=>{let[e,t]=((A.timeOrigin+A.now()-Date.UTC(1900,0,1))/1e3).toString().split(`.`).map(Number);return Cx([4,4],[e,t]).readBigUInt64BE()},lk=e=>{let[t,n]=Tx(Cx([8],[e]),[4,4]);return t*1e3+n+Date.UTC(1900,0,1)},uk=e=>{let[,t,n]=Tx(Cx([8],[e]),[2,2,2,2]);return Cx([2,2],[t,n]).readUInt32BE()};function dk(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=pk(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 XO(`iceOptions`,t),t}function fk({configuredTurnTransport:e,forceTurnTCP:t,parsedTurnTransport:n}){if(n)return n;if(e)return e;if(t)return`tcp`}function pk(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=gk(a,hk(i));if(!s)return;if(i===`stun`||i===`stuns`)return{kind:`stun`,address:s};let c=mk({scheme:i,transportParam:new URLSearchParams(o).get(`transport`)});if(c!==`invalid`)return{kind:`turn`,address:s,transport:c}}function mk({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 hk(e){return e===`stuns`||e===`turns`?5349:3478}function gk(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),_k(n.slice(e+1),t)]}let r=n.indexOf(`:`),i=n.lastIndexOf(`:`);return r!==-1&&r===i?[n.slice(0,r),_k(n.slice(r+1),t)]:[n,t]}function _k(e,t){let n=e.startsWith(`:`)?e.slice(1):e,r=Number.parseInt(n,10);return Number.isFinite(r)?r:t}AS.createSelfSignedCertificateWithKey;var vk=(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},yk=Zx(`werift:packages/webrtc/src/media/receiver/nack.ts`),bk=150,xk=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){yk(`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===Vx(this.newEstSeqNum,1))this.newEstSeqNum=t;else if(t>Vx(this.newEstSeqNum,1)){for(let e=Vx(this.newEstSeqNum,1);e<t;e=Vx(e,1))this.setLost(e,1);this.newEstSeqNum=t,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>bk&&(this._lost=Object.entries(this._lost).slice(-bk).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 tw({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),r=new lw({feedback:n});this.receiver.dtlsTransport.sendRtcp([r]).then(e).catch(t),this.updateRetryCount(),this.onPacketLost.execute(n)}})},Sk=Zx(`werift:packages/webrtc/media/receiver/receiverTwcc`),Ck=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:ok()},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=Vx(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 ow({delta:Number(i)});a.parseDelta(),c.push(a),s!=null&&s.status!==a.type&&(r.push(new iw({packetStatus:s.status,runLength:e-s.minTSN})),s={minTSN:e,status:a.type}),e===n&&(s==null?r.push(new iw({packetStatus:a.type,runLength:1})):r.push(new iw({packetStatus:s.status,runLength:e-s.minTSN+1}))),s??={minTSN:e,status:a.type}}}if(!o)return;let l=new lw({feedback:new rw({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:i,packetStatusCount:a,referenceTime:Ux(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:r})});this.dtlsTransport.sendRtcp([l]).catch(e=>{Sk(e)}),this.extensionInfo={},this.fbPktCount=Bx(this.fbPktCount,1)}},wk=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||Wx(e.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.bytesReceived+=e.payload.length,this.headerBytesReceived+=e.header.serializeSize,this.lastPacketReceivedTimestamp=UO(),this.base_seq??=e.header.sequenceNumber,n){let n=qx(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}},Tk=Zx(`werift:packages/webrtc/src/transport/dtls.ts`);function Ek(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 Dk(e){switch(e){case 1:return`AES_CM_128_HMAC_SHA1_80`;case 7:return`AEAD_AES_128_GCM`;default:return}}var Ok=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 tO;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 jk(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 AS.createSelfSignedCertificateWithKey({signature:iS.ecdsa_3,hash:aS.sha256_4},cS.secp256r1_23);return this.localCertificate=new kk(t,e,n),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let t=Mk([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),n=e.role===`auto`&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new jk(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 qT({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Ik(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):new RT({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Ik(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`),Tk(`dtls failed`,e),t(e)}),this.dtls instanceof RT&&(await E(100),this.dtls.connect().catch(e=>{this.setState(`failed`),Tk(`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`),Tk(`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=$O(e);if(!n)return[];let r=ek(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=Pk(t),r=t.filter(({normalizedAlgorithm:e})=>e===n),i=r.reduce((t,{normalizedAlgorithm:n})=>(t.has(n)||t.set(n,ek(ZO(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`);Tk(`selected SRTP Profile`,e);let{localKey:t,localSalt:n,remoteKey:r,remoteSalt:i}=this.dtls.extractSessionKeys(VC(e),HC(e)),a={keys:{localMasterKey:t,localMasterSalt:n,remoteMasterKey:r,remoteMasterSalt:i},profile:e};this.srtp=new yT(a),this.srtcp=new _T(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())&&GC(e)){if(this.bytesReceived+=e.length,this.packetsReceived++,yw(e)){let t;try{t=this.srtcp.decrypt(e)}catch(e){if(e instanceof Yw){Tk(`dropping invalid SRTCP packet`,e);return}throw e}let n;try{n=vw.deSerialize(t)}catch(e){Tk(`dropping malformed SRTCP packet`,e);return}for(let e of n)try{this.onRtcp.execute(e)}catch(e){Tk(`RTCP error`,e)}}else{let t;try{t=this.srtp.decrypt(e)}catch(e){if(e instanceof Yw){Tk(`dropping invalid SRTP packet`,e);return}throw e}let n;try{n=Gw.deSerialize(t)}catch(e){Tk(`dropping malformed SRTP packet`,e);return}try{this.onRtp.execute(n)}catch(e){Tk(`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 Tk(`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=UO()){let t=[],n=VO(`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?VO(`candidate-pair`,this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?VO(`certificate`,this.id,`local`):void 0,remoteCertificateId:this.dtls?.remoteCertificate?VO(`certificate`,this.id,`remote`):void 0,dtlsRole:this.role===`auto`?void 0:this.role,tlsVersion:Ek(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:Dk(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:VO(`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:VO(`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}},kk=class{constructor(e,t,n){this.certPem=t,this.signatureHash=n;let r=ti.Certificate.fromPEM(Buffer.from(t));this.publicKey=r.publicKey.toPEM(),this.privateKey=ti.PrivateKey.fromPEM(Buffer.from(e)).toPEM()}publicKey;privateKey;getFingerprints(){return[new Ak(`sha-256`,ZO(ti.Certificate.fromPEM(Buffer.from(this.certPem)).raw,`sha256`))]}},Ak=class{constructor(e,t){this.algorithm=e,this.value=t}},jk=class{constructor(e=[],t){this.fingerprints=e,this.role=t}},Mk=e=>{let t=new Set;return e.filter(({algorithm:e,value:n})=>{let r=`${$O(e)??e.trim().toLowerCase()}:${ek(n)}`;return!t.has(r)&&(t.add(r),!0)})},Nk=[`sha512`,`sha384`,`sha256`,`sha224`,`sha1`],Pk=e=>Nk.find(t=>e.some(({normalizedAlgorithm:e})=>e===t))??e[0].normalizedAlgorithm,Fk=class{constructor(e){this.ice=e,e.onData.subscribe(e=>{tk(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()}},Ik=e=>new Fk(e),Lk=Zx(`werift:packages/webrtc/src/transport/ice.ts`);function Rk(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 zk=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 tO;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=>Vk(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>Vk(e).toJSON())}getSelectedCandidatePair(){let e=this.connection.candidatePairs.find(e=>e.nominated)??this.connection.candidatePairs.find(e=>e.state===3);return e?{local:Vk(e.localCandidate).toJSON(),remote:Vk(e.remoteCandidate).toJSON()}:null}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){return!this.connection.remoteUsername||!this.connection.remotePassword?null:new Gk({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(Hk(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?(Lk(`renomination`,e),this.connection.resetNominatedPair(),this.renominating=!1):(Lk(`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=UO(),t=VO(`transport`,this.id)){let n=[];for(let r of this.connection.localCandidates){let i={type:`local-candidate`,id:VO(`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:VO(`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:VO(`candidate-pair`,i.id),timestamp:e,transportId:t,localCandidateId:VO(`local-candidate`,i.localCandidate.id),remoteCandidateId:VO(`remote-candidate`,i.remoteCandidate.id),state:Rk(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}},Bk=class{constructor(e={}){this.options=e,this.connection=new XD(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(Vk(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(Vk)}get localParameters(){return new Gk({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 Vk(e){let t=new Wk(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 Hk(e){return new bD(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 Uk=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(e){Object.assign(this,e)}static fromSdp(e){return Vk(bD.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}}},Wk=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 Uk({candidate:cj(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate)throw Error(`candidate is required`);let t=fj(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{}}},Gk=class{iceLite=!1;usernameFragment;password;constructor(e={}){Object.assign(this,e)}},Kk=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(fA(this.body.length))].map(()=>Buffer.from(`\0`))])}},qk=class extends Kk{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=mA(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,pA(this.params)])}},Jk=class e extends qk{static type=1;get type(){return e.type}},Yk=class e extends qk{static type=2;get type(){return e.type}},Xk=class e extends qk{static type=130;get type(){return e.type}},Zk=class e extends Kk{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})])}},Qk=class e extends Kk{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(fA(e))].map(()=>Buffer.from(`\0`))])),n}},$k=class e extends Kk{static type=10;get type(){return e.type}},eA=class e extends Kk{static type=11;get type(){return e.type}},tA=class extends Kk{constructor(e=0,t=void 0){super(e,t),this.flags=e,t&&(this.params=mA(t))}params=[];get body(){return pA(this.params)}},nA=class e extends tA{static type=6;get type(){return e.type}},rA=class e extends tA{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}))}},iA=class e extends tA{static type=4;get type(){return e.type}},aA=class e extends tA{static type=5;get type(){return e.type}},oA=class e extends tA{static type=130;get type(){return e.type}},sA=class e extends Kk{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}},cA=class e extends Kk{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}},lA=class e extends Kk{static type=8;get type(){return e.type}},uA=class e extends Kk{static type=14;get type(){return e.type}},dA=[Qk,Jk,Yk,sA,iA,aA,nA,cA,lA,rA,$k,eA,uA,oA,Zk].reduce((e,t)=>(e[t.type]=t,e),{});function fA(e){let t=e%4;return t?4-t:0}function pA(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(fA(i))].map(()=>Buffer.from(`\0`)))}),t}function mA(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+fA(i)}return t}function hA(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)!==zx(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=dA[t.toString()];if(s)i.push(new s(n,o));else throw Error(`unknown`);a+=r+fA(r)}return[t,n,r,i]}function gA(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=zx(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 _A(e){return e.map((e,t)=>[t,e])}function vA(e){return e.reduce((e,t)=>(e[t]=new $,e),{})}var yA=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)}},bA=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)}},xA={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},SA=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)}},CA={13:yA,16:SA,17:bA},wA=Zx(`werift/sctp/sctp`),TA=24,EA=60,DA=65535,OA=1200,kA=1,AA=2,jA=4,MA=10,NA=8,PA=1/8,FA=1/4,IA=3,LA=1,RA=60,zA=2**32,BA=200,VA=30,HA=135,UA=7,WA=32776,GA=49152,KA=[`new`,`closed`,`connected`,`connecting`],qA=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=vA(KA);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=yx();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=DA;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*OA;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=DA;localTsn=Number(yx());lastSackedTsn=XA(this.localTsn);advancedPeerAckTsn=XA(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=IA;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=VA;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]=hA(e);if(r.filter(e=>e.type===Jk.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=>{wA(`send delayed sack failed`,e.message)})},BA)}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],t;[...this.sackMisOrdered].sort().forEach(n=>{let r=(n-this.lastReceivedTsn)%zA;n===t?e[e.length-1][1]=r:e.push([r,r]),t=ZA(n)});let n=new sA(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=>{wA(`send sack failed`,e.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case Qk.type:this.receiveDataChunk(e);break;case Jk.type:{if(!this.isServer)return;let t=e;wA(`receive init`,t),this.lastReceivedTsn=XA(t.initialTsn),this.reconfigResponseSeq=XA(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 Yk;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([UA,a]),wA(`send initAck`,n),await this.sendChunk(n).catch(e=>{wA(`send initAck failed`,e.message)})}break;case Yk.type:{if(this.associationState!=2)return;let t=e;this.timer1Cancel(),this.lastReceivedTsn=XA(t.initialTsn),this.reconfigResponseSeq=XA(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 $k;for(let[e,r]of t.params)if(e===UA){n.body=r;break}await this.sendChunk(n).catch(e=>{wA(`send echo failed`,e.message)}),this.timer1Start(n),this.setState(3)}break;case sA.type:await this.receiveSackChunk(e);break;case iA.type:{let t=new aA;t.params=e.params,await this.sendChunk(t).catch(e=>{wA(`send heartbeat ack failed`,e.message)})}break;case nA.type:this.setState(1);break;case cA.type:{this.timer2Cancel(),this.setState(7);let e=new lA;await this.sendChunk(e).catch(e=>{wA(`send shutdown ack failed`,e.message)}),this.t2Start(e),this.setState(6)}break;case rA.type:wA(`ErrorChunk`,e.descriptions);break;case $k.type:{if(!this.isServer)return;let t=e.body,n=o(`sha1`,this.hmacKey).update(t.slice(0,4)).digest();if(t?.length!=TA||!t.slice(4).equals(n)){wA(`x State cookie is invalid`);return}let r=Math.floor(Date.now()/1e3),i=t.readUInt32BE(0);if(i<r-EA||i>r){let e=new rA(0,void 0);e.params.push([rA.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(`\0`)))]),await this.sendChunk(e).catch(e=>{wA(`send errorChunk failed`,e.message)});return}let a=new eA;await this.sendChunk(a).catch(e=>{wA(`send cookieAck failed`,e.message)}),this.setState(4)}break;case eA.type:if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4);break;case uA.type:if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1);break;case oA.type:{if(this.associationState!=4)return;let t=e;for(let[e,n]of t.params){let t=CA[e];t&&await this.receiveReconfigParam(t.parse(n))}}break;case Zk.type:this.receiveForwardTsnChunk(e)}}getExtensions(e){for(let[t,n]of e)t===GA?this.remotePartialReliability=!0:t===WA&&(this.remoteExtensions=[...n])}async receiveReconfigParam(e){switch(wA(`receiveReconfigParam`,CA[e.type]),e.type){case yA.type:{let t=e,n=new SA(t.requestSequence,xA.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 SA.type:{let t=e;if(t.result!==xA.ReconfigResultSuccessPerformed)wA(`OutgoingSSNResetRequestParam failed`,Object.keys(xA).find(e=>xA[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=IA,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case bA.type:{let t=e;this._inboundStreamsCount+=t.newStreams;let n=new SA(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&kA)===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(Gx(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&&Kx(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)%zA,t.add(n)});let r=e.cumulativeTsn;for(let e of this.sentQueue){if(Gx(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(Gx(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,OA):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=OA))),a&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*OA),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):Kx(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,Kx(this.lastReceivedTsn,e.cumulativeTsn))return;let t=e=>Gx(e,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let e of[...this.sackMisOrdered].sort())if(e===ZA(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=Vx(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-FA)*this.rttvar+FA*Math.abs(this.srtt-e),this.srtt=(1-PA)*this.srtt+PA*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(LA,Math.min(this.srtt+4*this.rttvar,RA))}receive(e,t,n){this.onReceive.execute(e,t,n)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new JA),this.inboundStreams[e]}markReceived(e){if(Kx(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===ZA(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;let t=e=>Gx(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/OA),c=0,l=[];for(let u=0;u<s;u++){let d=new Qk(0,void 0);d.flags=0,a||(d.flags=jA),u===0&&(d.flags|=AA),u===s-1&&(d.flags|=kA),d.tsn=this.localTsn,d.streamId=e,d.streamSeqNum=o,d.protocol=t,d.userData=n.slice(c,c+OA),d.bookSize=d.userData.length,d.expiry=r,d.maxRetransmits=i,c+=OA,this.localTsn=ZA(this.localTsn),l.push(d)}for(l.forEach(e=>{this.outboundQueue.push(e)}),a&&(this.outboundStreamSeq[e]=Vx(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=>{wA(`send forwardTsn failed`,e.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit==null?4*OA:2*OA,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=>{wA(`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=>{wA(`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,HA);this.reconfigQueue=e.slice(HA);let n=new yA(this.reconfigRequestSeq,this.reconfigResponseSeq,XA(this.localTsn),t);this.reconfigRequestSeq=ZA(this.reconfigRequestSeq),this.reconfigRequest=n,await this.sendReconfigParam(n),this.timerReconfigHandleStart()}}async sendReconfigParam(e){wA(`sendReconfigParam`,e);let t=new oA;t.params.push([e.type,e.bytes]),await this.sendChunk(t).catch(e=>{wA(`send reconfig failed`,e.message)})}async sendResetRequest(e){wA(`sendResetRequest`,e);let t=new Qk(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>NA)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{wA(`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>MA)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{wA(`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*OA),this.cwnd=OA,this.transmit())};timer3Cancel(){this.timer3Handle&&=(clearTimeout(this.timer3Handle),void 0)}timerReconfigHandleStart(){this.isStopped||(this.timerReconfigHandle||=(wA(`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>MA)wA(`timerReconfigFailures`,this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(wA(`timerReconfigHandleExpired`,this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(wA(`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 iA,t=Buffer.allocUnsafe(4);t.writeUInt32BE(Math.floor(Date.now()/1e3),0),e.params.push([1,t]),await this.sendChunk(e).catch(e=>{wA(`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(){Gx(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&jA||(t[n.streamId]=n.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new Zk(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&kA)break}for(let e=t;e<this.sentQueue.length;e++){let t=this.sentQueue[e];if(t.abandoned=!0,t.retransmit=!1,t.flags&kA)break}return!0}static getCapabilities(){return new YA(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 Jk;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),wA(`send init`,e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(e){wA(`send init failed`,e.message)}}setExtensions(e){let t=[];this.localPartialReliability&&(e.push([GA,Buffer.from(``)]),t.push(Zk.type)),t.push(Xk.type),e.push([WA,Buffer.from(t)])}async sendChunk(e){if(this.state===`closed`)return;if(this.remotePort===void 0)throw Error(`invalid remote port`);let t=gA(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,wA(`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 nA;await this.sendChunk(e).catch(e=>{wA(`send abort failed`,e.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},JA=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(e){if(this.reassembly.length===0||Gx(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(let[t,n]of _A(this.reassembly)){if(n.tsn===e.tsn)throw Error(`duplicate chunk in reassembly`);if(Gx(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&jA),!(i.flags&AA)){if(r)break;e++;continue}if(r&&Wx(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&kA){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=Vx(this.streamSequenceNumber,1)),e=t,yield[i.streamId,i.protocol,a]}else e++;n=ZA(n)}}pruneChunks(e){let t=-1,n=0;for(let[r,i]of this.reassembly.entries())if(Kx(e,i.tsn))t=r,n+=i.userData.length;else break;return this.reassembly=this.reassembly.slice(t+1),n}},YA=class{constructor(e){this.maxMessageSize=e}};function XA(e){return(e-1)%zA}function ZA(e){return(e+1)%zA}var QA=Zx(`werift:packages/webrtc/src/transport/sctp.ts`),$A=65536,ej=class e{constructor(e=5e3,t=$A){this.port=e,this.maxMessageSize=t}dtlsTransport;sctp;onDataChannel=new $;id=l().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=$A;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 qA(new nj(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===EO&&n.length>0)switch(QA(`DCEP`,e,t,n),n[0]){case wO:{if(n.length<12){QA(`DATA_CHANNEL_OPEN data.length not enough`);return}if(Object.keys(this.dataChannels).includes(e.toString()))QA(`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`);QA(`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 aO({label:s,ordered:!(t&128),maxPacketLifeTime:u,maxRetransmits:l,protocol:c,id:e}),f=new iO(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(CO,0),this.dataChannelQueue.push([t,EO,r]),await this.dataChannelFlush()}break;case CO:{QA(`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 DO:return n.toString(`utf8`);case kO:return``;case OO:return n;case AO: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=TO,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(wO,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,EO,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===EO)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=rO(t);return this.assertSendableMessageSize(r),e.addBufferedAmount(r),this.dataChannelQueue.push(typeof t==`string`?[e,DO,n]:[e,OO,n]),this.sctp.associationState!==4&&QA(`sctp not established`,this.sctp.associationState),this.dataChannelFlush(),r};getCapabilities(){return e.getCapabilities(this.maxMessageSize)}static getCapabilities(e=$A){return new tj(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`)))}},tj=class{constructor(e){this.maxMessageSize=e}},nj=class{constructor(e){this.dtls=e}set onData(e){this.dtls.dataReceiver=e}send=e=>this.dtls.sendData(e);close(){}},rj=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]=lj(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=oj(e.slice(2));else if(e.startsWith(`t=`))i.time=e.slice(2);else if(e.startsWith(`a=`)){let[t,n]=uj(e);switch(t){case`fingerprint`:{let[e,t]=n?.split(` `)||[];i.dtlsFingerprints.push(new Ak(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`:dj(i.group,n);break;case`msid-semantic`:dj(i.msidSemantic,n);break;case`setup`:i.dtlsRole=PO[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 ij(n,Number.parseInt(t[2]),t[3],o||r);if(s.dtlsParams=new jk([...i.dtlsFingerprints],i.dtlsRole),s.iceParams=new Gk({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=oj(e.slice(2));else if(e.startsWith(`a=`)){let[t,n]=uj(e);switch(t){case`candidate`:if(!n)throw Error();s.iceCandidates.push(fj(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 dO({id:Number.parseInt(e),uri:t}))}break;case`fingerprint`:{if(!n)throw Error();let[e,t]=n.split(` `);s.dtlsParams?.fingerprints.push(new Ak(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 tj(Number.parseInt(n,10));break;case`mid`:s.rtp.muxId=n;break;case`msid`:s.msids.push(n);break;case`rtcp`:{let[e,t]=eO(n,` `);s.rtcpPort=Number.parseInt(e),s.rtcpHost=oj(t)}break;case`rtcp-mux`:s.rtcpMux=!0;break;case`setup`:s.dtlsParams.role=PO[n];break;case`recvonly`:case`sendonly`:case`sendrecv`:case`inactive`:s.direction=t;break;case`rtpmap`:{let[e,t]=eO(n,` `),[r,i,a]=t.split(`/`),o;s.kind===`audio`&&(o=a?Number.parseInt(a):1);let c=new uO({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]=eO(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]=eO(n,` `),r=Number.parseInt(e),[i,a]=eO(t,`:`),o=s.ssrc.find(e=>e.ssrc===r);o||(o=new gj({ssrc:r}),s.ssrc.push(o)),IO.includes(i)&&(o[i]=a)}break;case`ssrc-group`:dj(s.ssrcGroup,n);break;case`rid`:{let[e,t]=eO(n,` `);s.simulcastParameters.push(new hO({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]=uj(e);if(t===`fmtp`){let[e,t]=eO(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 fO({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=${sj(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 pj(e,this.type)),this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}},ij=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=${sj(this.host)}`),this.iceCandidates.forEach(t=>{e.push(`a=candidate:${cj(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:${NO[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} ${sj(this.rtcpHost)}`),this.rtcpMux&&e.push(`a=rtcp-mux`)),this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)}),this.ssrc.forEach(t=>{IO.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
+ `}},aj=class{constructor(e,t){this.semantic=e,this.items=t}get str(){return`${this.semantic} ${this.items.join(` `)}`}};function oj(e){let t=e.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!t)throw Error(`exception`);return t[2]}function sj(e){return`IN IP${w(e)?4:6} ${e}`}function cj(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 lj(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 uj(e){if(e.includes(`:`)){let t=eO(e.slice(2),`:`);return[t[0],t[1]]}return[e.slice(2),void 0]}function dj(e,t,n=e=>e.toString()){let r=t.split(` `);r.length>0&&e.push(new aj(r[0],r.slice(1).map(n)))}function fj(e){return Vk(bD.fromSdp(e))}var pj=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 mj(e,t){t.origin=`- ${c(8).readBigUInt64BE(0).toString().slice(0,8)} 0 IN IP4 0.0.0.0`,t.msidSemantic.push(new aj(`WMS`,[`*`])),t.type=e}function hj(e){let t={};return e.split(`;`).forEach(e=>{if(e.includes(`=`)){let[n,r]=eO(e,`=`);FO.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 gj=class{ssrc;cname;msid;msLabel;label;constructor(e){Object.assign(this,e)}},_j=Zx(`werift:packages/webrtc/src/media/rtpReceiver.ts`),vj=class{constructor(e,t,n){this.config=e,this.kind=t,this.rtcpSsrc=n,this.defaultTrack=new JO({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 xk(this);audioRedHandler=new Lw;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===lO().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===sO().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 Ck(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=sk()-this.receiveLastSRTimestamp[e];t>0&&t<65536&&(r=qx(t*65536))}return new $C({ssrc:Number(e),fractionLost:t.fraction_lost,packetsLost:t.packets_lost,highestSequence:t.max_seq,jitter:t.jitter,lsr:n,dlsr:r})}),t=new QC({ssrc:this.rtcpSsrc,reports:e});try{this.config.debug.receiverReportDelay&&await E(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([t])}catch(e){_j(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}getInboundRtpStatsId(e){return VO(`inbound-rtp`,e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return VO(`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?VO(`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?HO(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=UO(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),GO(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){_j(`pli not supported`,{mediaSsrc:e});return}if(this.stopped)return;_j(`sendRtcpPLI`,{mediaSsrc:e});let t=new ZC({feedback:new JC({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1,await this.dtlsTransport.sendRtcp([t])}catch(e){_j(e)}}handleRtcpPacket(e){switch(e.type){case mw.type:{let t=e;this.lastSRtimestamp[t.ssrc]=uk(t.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[t.ssrc]=sk(),this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1,this.remoteTimestampsBySsrc[t.ssrc]=lk(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 wk(r.clockRate),this.remoteStreams[e.header.ssrc].add(e),this.receiverTWCC){let e=t[bw.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=hj(r.parameters??``),a=this.codecs[i.apt];if(e.payload.length<2)return;e=Kw(e,a.payloadType,t),n=this.trackBySSRC[t]}let i;if(!(r.name.toLowerCase()===`red`&&(i=Nw.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()}}},yj=Zx(`werift:packages/webrtc/src/media/router.ts`),bj=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){yj(`registerRtpReceiver`,t),this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){yj(`registerRtpReceiverBySsrc`,t),t.encodings.filter(e=>e.ssrc!=null).forEach((n,r)=>{this.registerRtpReceiver(e.receiver,n.ssrc),e.addTrack(new JO({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;yj(`registerRtpReceiverByRid`,t),e.addTrack(new JO({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:!0,codec:r})),this.ridTable[t.rid]=e.receiver}routeRtp=e=>{let t=xw(e.header.extensions,this.extIdUriMap),n=this.ssrcTable[e.header.ssrc],r=t[bw.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 vj).find(t=>t.trackBySSRC[e.header.ssrc]),n&&(yj(`simulcast register receiver by ssrc`,e.header.ssrc),this.registerRtpReceiver(n,e.header.ssrc),n.handleRtpBySsrc(e,t))),!n){yj(`ssrcReceiver not found`);return}let i=t[bw.sdesMid];typeof i==`string`&&(n.sdesMid=i);let a=t[bw.repairedRtpStreamId];typeof a==`string`&&(n.latestRepairedRid=a)};routeRtcp=e=>{let t=[];switch(e.type){case mw.type:e=e,t.push(this.ssrcTable[e.ssrc]);break;case QC.type:e=e,e.reports.forEach(e=>{t.push(this.ssrcTable[e.ssrc])});break;case uw.type:break;case lw.type:{let n=e;n.feedback&&t.push(this.ssrcTable[n.feedback.mediaSourceSsrc])}break;case ZC.type:{let n=e;switch(n.feedback.count){case YC.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))}},xj=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 WC(this.totalSize/e*8*1e3)}get sendBitrate(){let e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;return WC(this.totalSize/e*8*1e3)}},Sj=20,Cj=10,wj=class{congestion=!1;onAvailableBitrate=new $;onCongestion=new $;onCongestionScore=new $;congestionCounter=0;cumulativeResult=new xj;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=ik()-this.cumulativeResult.firstPacketSentAtMs;t>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<Sj?this.congestionCounter++:this.congestionScore<Cj&&this.congestionScore++,this.congestionCounter>=Sj&&!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>-Sj){let e=WC(Sj/2)+1,t=e-(e-(WC(Sj/4)+1))/10*this.congestionScore;this.congestionCounter-=t}this.congestionCounter<=-Sj&&(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}},Tj=Zx(`werift:packages/webrtc/src/media/rtpSender.ts`),Ej=128,Dj=.85,Oj=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 wj;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=vx();redRedundantPayloadType;_redDistance=2;redEncoder=new Fw(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=hj(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),Tj(`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 mw({ssrc:this.ssrc,senderInfo:new hw({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=uk(this.ntpTimestamp),this.lastSentSRTimestamp=sk(),this.cname&&e.push(new uw({chunks:[new dw({source:this.ssrc,items:[new fw({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(e)}catch(e){Tj(`sendRtcp failed`,e),await E(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:e,timestamp:t},n=!1){this.sequenceNumber!=null&&(this.seqOffset=Vx(this.sequenceNumber,-e),n&&(this.seqOffset=Vx(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=Hx(this.timestamp,-t),n&&(this.timestampOffset=Vx(this.timestampOffset,1))),this.rtpCache=[],Tj(`replaceRTP`,this.sequenceNumber,e,this.seqOffset)}async sendRtp(e){if(this.dtlsTransport.state!==`connected`||!this.codec)return;e=Buffer.isBuffer(e)?Gw.deSerialize(e):e;let{header:t,payload:n}=e;t.ssrc=this.ssrc,t.payloadType=this.codec.payloadType,t.timestamp=Hx(t.timestamp,this.timestampOffset),t.sequenceNumber=Vx(t.sequenceNumber,this.seqOffset),this.timestamp=t.timestamp,this.sequenceNumber=t.sequenceNumber;let r=ck(),i=[...t.extensions];t.extensions=this.headerExtensions.map(e=>{let t=(()=>{switch(e.uri){case bw.sdesMid:return this.mid?Sw(this.mid):void 0;case bw.sdesRTPStreamID:return this.rtpStreamId?Cw(this.rtpStreamId):void 0;case bw.repairedRtpStreamId:return this.repairedRtpStreamId?ww(this.repairedRtpStreamId):void 0;case bw.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Vx(this.dtlsTransport.transportSequenceNumber,1),Tw(this.dtlsTransport.transportSequenceNumber);case bw.absSendTime:return Ew(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=Hx(this.packetCount,1),this.rtpCache[t.sequenceNumber%Ej]=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=ik(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:s,sentAtMs:s};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(e){switch(e.type){case mw.type:case QC.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=sk()-this.lastSentSRTimestamp-e.dlsr/65536;this.totalRoundTripTime+=t,this.roundTripTimeMeasurements++,this.rtt=this.rtt===void 0?t:Dj*this.rtt+(1-Dj)*t}});break;case lw.type:{let t=e;switch(t.feedback.count){case rw.count:{let e=t.feedback;this.senderBWE.receiveTWCC(e)}break;case tw.count:{let e=t.feedback;this.nackCount++,e.lost.forEach(async e=>{let t=this.rtpCache[e%Ej];t&&t.header.sequenceNumber!==e&&(t=void 0),t&&(this.rtxPayloadType!=null&&(t=qw(t,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Vx(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 ZC.type:{let t=e;switch(t.feedback.count){case YC.count:{let e=t.feedback;this.receiverEstimatedMaxBitrate=e.bitrate}break;case JC.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 VO(`outbound-rtp`,this.trackId)}get mediaSourceStatsId(){return VO(`media-source`,this.trackId)}get remoteInboundRtpStatsId(){return VO(`remote-inbound-rtp`,this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){let t=[],n=this.dtlsTransport?VO(`transport`,this.dtlsTransport.id):void 0,r=this.codec&&n?HO(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=UO(),t=this.collectStats(e);return this.dtlsTransport&&t.push(...await this.dtlsTransport.getStats(e)),GO(t,this.getStatsRootIds())}};function kj(e,t=e){return new DOMException(t,e)}function Aj(e){return TypeError(e)}var jj=Zx(`werift:packages/webrtc/src/transport/sctpManager.ts`),Mj=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new $;constructor(){}createSctpTransport(e){let t=new ej(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=Nj(t.maxPacketLifeTime,`maxPacketLifeTime`),r=Nj(t.maxRetransmits,`maxRetransmits`),i={protocol:``,ordered:!0,negotiated:!1,...t,maxPacketLifeTime:n,maxRetransmits:r};if(i.maxPacketLifeTime!=null&&i.maxRetransmits!=null)throw Aj(`maxPacketLifeTime and maxRetransmits cannot both be set`);this.sctpTransport||=this.createSctpTransport();let a=new aO({id:i.id,label:e,maxPacketLifeTime:i.maxPacketLifeTime,maxRetransmits:i.maxRetransmits,negotiated:i.negotiated,ordered:i.ordered,protocol:i.protocol}),o=new iO(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(),jj(`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=UO()){let t=[];for(let n of this.dataChannels){let r={type:`data-channel`,id:VO(`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 Nj(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw Aj(`${t} must be an unsigned short`);return n}var Pj=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 ij(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 gj({ssrc:e.sender.ssrc,cname:this.cname})],e.options.simulcast&&(n.simulcastParameters=e.options.simulcast.map(e=>new hO(e))),n.rtp.codecs.find(e=>e.name.toLowerCase()===`rtx`)&&(n.ssrc.push(new gj({ssrc:e.sender.rtxSsrc,cname:this.cname})),n.ssrcGroup=[new aj(`FID`,[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]),this.addTransportDescription(n,e.dtlsTransport),n}createMediaDescriptionForSctp(e){let t=new ij(`application`,MO,`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=jO,e.port=MO,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=rj.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 kj(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-remote-offer`,`have-local-pranswer`].includes(n))throw kj(`InvalidStateError`,`Cannot handle answer in signaling state`)}else if(r===`offer`){if(![`stable`,`have-remote-offer`,`have-local-offer`].includes(n))throw kj(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)&&![`have-local-offer`,`have-remote-pranswer`].includes(n))throw kj(`InvalidStateError`,`Cannot handle answer in signaling state`)}buildOfferSdp(e,t){let n=new rj;mj(`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 aj(`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 rj;mj(`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,nk(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 aj(`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 kj(`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 kj(`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)}},Fj=Zx(`werift:packages/webrtc/src/transport/secureTransportManager.ts`),Ij=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 kk(e.keyPem,e.certPem,e.signatureHash)}createTransport(){let e=this.iceTransports.find(e=>e.state!==`closed`),t=dk(this.config.iceServers),n=fk({parsedTurnTransport:t.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP}),r=new Bk({...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 zk(r);return i.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new Ok(this.config,i,this.certificate,Lj)}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=Wk.fromJSON(t);if(!c)throw kj(`OperationError`,`Failed to parse ICE candidate`);let l=s[0],u=e.media[l];if(!u)throw kj(`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 kj(`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 kj(`OperationError`,`Media section for sdpMid was not found`);a=[t]}else if(typeof r==`number`){if(r<0||r>=e.media.length)throw kj(`OperationError`,`Media section for sdpMLineIndex was not found`);a=[r]}else if(t)a=e.media.map((e,t)=>t);else throw Aj(`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 kj(`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&&(Fj(`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?Fj(`skipping ICE gathering for bundled connection`):await Promise.allSettled(this.iceTransports.map(e=>e.gather())).catch(e=>{Fj(`gatherCandidates failed`,e)})}setConnectionState(e){this.connectionState!==e&&(Fj(`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 Ok.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()}},Lj=[LO.SRTP_AEAD_AES_128_GCM,LO.SRTP_AES128_CM_HMAC_SHA1_80],Rj=Zx(`werift:packages/webrtc/src/peerConnection.ts`),zj=class extends tO{id=l().toString();cname=l().toString();config=Vj();signalingState=`stable`;negotiationneeded=!1;needRestart=!1;router=new bj;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 Pj({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new Jj(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 Kj({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 Mj,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 Ij({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=Hj(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&&!Wj(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(vk(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 $D([...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 Gj(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 kj(`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){Rj(`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){Rj(`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 kj(`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 $D(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=nk(e.direction,e.offerDirection);e.setCurrentDirection(t)}return this.sdpManager.setLocal(a,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(e=>{Rj(`gatherCandidates failed`,e)}),a.type===`answer`&&this.connect().catch(e=>{Rj(`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 kj(`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(){Rj(`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 Rj(`iceTransport.start failed`,e),e}),e.state!==`connected`&&(await e.start().catch(e=>{throw Rj(`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 rj&&(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`&&(Rj(`caller start connect`),this.connect().catch(e=>{Rj(`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 kj(`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 kj(`InvalidStateError`,`RTCPeerConnection is closed`)}setSignalingState(e){this.signalingState!==e&&(Rj(`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:VO(`peer-connection`,this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){let t=UO(),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?GO(n,this.transceiverManager.getStatsRootIds(e)):GO(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(),Rj(`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()}},Bj=(e,t)=>e.find(e=>e.mimeType.toLowerCase()===t.mimeType.toLowerCase())?t:void 0;function Vj(){return{codecs:{audio:[bO(),xO()],video:[_O()]},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:$A}}Vj();function Hj(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 Aj(`certificates must be an array of RTCCertificate`);else n.certificates=[...t.certificates]}return`iceCandidatePoolSize`in t&&(n.iceCandidatePoolSize=Uj(t.iceCandidatePoolSize,`iceCandidatePoolSize`)),n}function Uj(e,t){let n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw Aj(`${t} must be an unsigned short`);return n}function Wj(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Gj(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 Kj=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}},qj=Zx(`werift:packages/webrtc/src/media/rtpTransceiverManager.ts`),Jj=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 Oj(e),o=new KO(r,t,new vj(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 kj(`InvalidAccessError`,`Track already added`);let n=this.transceivers.find(t=>t.sender.track==null&&t.kind===e.kind&&RO.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&&RO.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 kj(`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!!zO.includes(e.direction);case`sendonly`:return!!RO.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[hj(n.parameters??``).apt];return r&&e.ssrc.length===2&&(r.rtx=new pO({ssrc:e.ssrc[1].ssrc})),t}return t[n.payloadType]=new mO({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=Bj(n,e);if(!r)return!1;if(r?.name.toLowerCase()===`rtx`){let e=hj(r.parameters??``).apt,i=t.rtp.codecs.find(t=>t.payloadType===e);return i?!!Bj(n,i):!1}return!0}),qj(`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=rk(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 YO({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 Yj(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 Xj(){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 zj({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)=>Yj(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:Yj(e.channel)}),!0):Reflect.set(e,t,n,e)}})},async close(){if(n=!0,await Promise.all([...e].map(i)),r)throw r}}}function Zj(e){return Hn(e)}function Qj(e){if(typeof e!=`string`)throw TypeError(`Stadium source must be a string`);let t=hn(e);return Object.freeze({name:t.name,canBeStored:t.canBeStored,warnings:Object.freeze([...t.warnings])})}async function $j(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=xn(r??`https://ball2d.com`),s=Tr(a),c=Xj(),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 wr.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=>yn.create(await t(new URL(`./core.wasm`,import.meta.url),{signal:e})),loadStadium:wn(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(),Or(e,g)}catch(e){throw f?.close(),await d?.stop(),await c.close(),e}}export{$j as createRoom,Zj as readReplay,Qj as validateStadium};